blob: c8dd3d3fd865f16d60c041da6bb19c72c7960f8a [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 */
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +020028def printVariables(global_variables, Boolean yamlStyle = true) {
29 def common = new com.mirantis.mk.Common()
30 def mcpcommon = new com.mirantis.mcp.Common()
31 def global_variables_msg = ''
32 if (yamlStyle) {
33 global_variables_msg = mcpcommon.dumpYAML(global_variables)
34 } else {
35 for (variable in global_variables) {
36 global_variables_msg += "env.${variable.key}=\"\"\"${variable.value}\"\"\"\n"
37 }
Dennis Dmitriev38a45cd2023-02-27 14:22:13 +020038 }
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +020039 def message = "// Collected global_variables during the workflow:\n${global_variables_msg}"
Dennis Dmitriev38a45cd2023-02-27 14:22:13 +020040 common.warningMsg(message)
41}
42
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +020043
44/**
45 * Print stack trace to the console
46 */
47def printStackTrace(e, String prefix = 'at com.mirantis') {
48 def common = new com.mirantis.mk.Common()
49 StringWriter writer = new StringWriter()
50 e.printStackTrace(new PrintWriter(writer))
51 String stackTrace = writer
52
53 // Filter the stacktrace to show only the lines related to the specified library
54 String[] lines = stackTrace.split("\n")
55 String stackTraceFiltered = ''
56 Boolean filteredLine = false
57 for (String line in lines) {
58 if (line.contains('at ') && line.contains(prefix)) {
59 if (!filteredLine) {
60 stackTraceFiltered += "...\n"
61 filteredLine = true
62 }
63 stackTraceFiltered += "${line}\n"
64 }
65 else if (!line.contains('at ')) {
66 if (filteredLine) {
67 stackTraceFiltered += "...\n"
68 filteredLine = false
69 }
70 stackTraceFiltered += "${line}\n"
71 }
72 }
73 common.errorMsg("Stack trace:\n${stackTraceFiltered}")
74}
75
76
Dennis Dmitriev38a45cd2023-02-27 14:22:13 +020077/**
Dennis Dmitriev5f014d82020-04-29 00:00:34 +030078 * Get Jenkins parameter names, values and types from jobName
79 * @param jobName job name
80 * @return Map with parameter names as keys and the following map as values:
81 * [
82 * <str name1>: [type: <str cls1>, use_variable: <str name1>, defaultValue: <cls value1>],
83 * <str name2>: [type: <str cls2>, use_variable: <str name2>, defaultValue: <cls value2>],
84 * ]
85 */
86def getJobDefaultParameters(jobName) {
87 def jenkinsUtils = new com.mirantis.mk.JenkinsUtils()
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +020088 def item = jenkinsUtils.getJobByName(jobName)
Dennis Dmitriev5f014d82020-04-29 00:00:34 +030089 def parameters = [:]
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +020090 // def prop = item.getProperty(ParametersDefinitionProperty.class)
91 def prop = item.getProperty(ParametersDefinitionProperty)
azvyagintsev75390d92021-04-12 14:20:11 +030092 if (prop != null) {
93 for (param in prop.getParameterDefinitions()) {
Dennis Dmitriev5f014d82020-04-29 00:00:34 +030094 def defaultParam = param.getDefaultParameterValue()
95 def cls = defaultParam.getClass().getName()
96 def value = defaultParam.getValue()
97 def name = defaultParam.getName()
98 parameters[name] = [type: cls, use_variable: name, defaultValue: value]
99 }
100 }
101 return parameters
102}
103
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200104
Dennis Dmitriev5f014d82020-04-29 00:00:34 +0300105/**
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200106 * Generate parameters for a Jenkins job using different sources
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300107 *
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300108 * @param job_parameters Map that declares which values from global_variables should be used, in the following format:
109 * {'PARAM_NAME': {'type': <job parameter $class name>, 'use_variable': <a key from global_variables>}, ...}
Dennis Dmitrievce470932019-09-18 18:31:11 +0300110 * or
Dennis Dmitrievcae9bca2019-09-19 16:10:03 +0300111 * {'PARAM_NAME': {'type': <job parameter $class name>, 'get_variable_from_url': <a key from global_variables which contains URL with required content>}, ...}
112 * or
Dennis Dmitrievce470932019-09-18 18:31:11 +0300113 * {'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 +0200114 * or
115 * {'PARAM_NAME': {'type': <job parameter $class name>, 'get_variable_from_yaml': {'yaml_url': <URL with YAML content>,
116 * 'yaml_key': <a groovy-interpolating path to the key in the YAML, starting from dot '.'> } }, ...}
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200117 * or
118 * {'PARAM_NAME': {'type': <job parameter $class name>, 'use_variables_map': <a nested map of job_parameters>}, ...}
119 * , where job_parameters may contain a special 'type': '_defaultText' for a Yaml with some additional parameters for this map
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300120 * @param global_variables Map that keeps the artifact URLs and used 'env' objects:
121 * {'PARAM1_NAME': <param1 value>, 'PARAM2_NAME': 'http://.../artifacts/param2_value', ...}
122 */
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200123def generateParameters(job_parameters, global_variables) {
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300124 def parameters = []
azvyagintsev0d978152022-01-27 14:01:33 +0200125 def common = new com.mirantis.mk.Common()
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200126 def mcpcommon = new com.mirantis.mcp.Common()
Dennis Dmitrievcae9bca2019-09-19 16:10:03 +0300127 def http = new com.mirantis.mk.Http()
Dennis Dmitrievce470932019-09-18 18:31:11 +0300128 def engine = new groovy.text.GStringTemplateEngine()
129 def template
Dennis Dmitriev6c355be2021-11-09 14:06:56 +0200130 def yamls_from_urls = [:]
Dennis Dmitrievcae9bca2019-09-19 16:10:03 +0300131 def base = [:]
132 base["url"] = ''
133 def variable_content
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200134 def env_variables = common.getEnvAsMap()
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300135
136 // Collect required parameters from 'global_variables' or 'env'
azvyagintsev25015272023-11-28 17:31:18 +0200137 def _msg = ''
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300138 for (param in job_parameters) {
Dennis Dmitrievce470932019-09-18 18:31:11 +0300139 if (param.value.containsKey('use_variable')) {
140 if (!global_variables[param.value.use_variable]) {
141 global_variables[param.value.use_variable] = env[param.value.use_variable] ?: ''
142 }
143 parameters.add([$class: "${param.value.type}", name: "${param.key}", value: global_variables[param.value.use_variable]])
azvyagintsev25015272023-11-28 17:31:18 +0200144 _msg += "\n${param.key}: <${param.value.type}> From:${param.value.use_variable}, Value:${global_variables[param.value.use_variable]}"
Dennis Dmitrievcae9bca2019-09-19 16:10:03 +0300145 } else if (param.value.containsKey('get_variable_from_url')) {
146 if (!global_variables[param.value.get_variable_from_url]) {
147 global_variables[param.value.get_variable_from_url] = env[param.value.get_variable_from_url] ?: ''
148 }
Andrew Baraniuke0aef1e2019-10-16 14:50:10 +0300149 if (global_variables[param.value.get_variable_from_url]) {
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200150 variable_content = http.restGet(base, global_variables[param.value.get_variable_from_url])
151 // http.restGet() attempts to read the response as a JSON, and may return an object instead of a string
152 variable_content = "${variable_content}".trim()
Andrew Baraniuke0aef1e2019-10-16 14:50:10 +0300153 parameters.add([$class: "${param.value.type}", name: "${param.key}", value: variable_content])
azvyagintsev25015272023-11-28 17:31:18 +0200154 _msg += "\n${param.key}: <${param.value.type}> Content from url: ${variable_content}"
Andrew Baraniuke0aef1e2019-10-16 14:50:10 +0300155 } else {
azvyagintsev25015272023-11-28 17:31:18 +0200156 _msg += "\n${param.key} is empty, skipping get_variable_from_url"
Andrew Baraniuke0aef1e2019-10-16 14:50:10 +0300157 }
Dennis Dmitriev6c355be2021-11-09 14:06:56 +0200158 } else if (param.value.containsKey('get_variable_from_yaml')) {
159 if (param.value.get_variable_from_yaml.containsKey('yaml_url') && param.value.get_variable_from_yaml.containsKey('yaml_key')) {
160 // YAML url is stored in an environment or a global variable (like 'SI_CONFIG_ARTIFACT')
azvyagintsev0d978152022-01-27 14:01:33 +0200161 def yaml_url_var = param.value.get_variable_from_yaml.yaml_url
Dennis Dmitriev6c355be2021-11-09 14:06:56 +0200162 if (!global_variables[yaml_url_var]) {
163 global_variables[yaml_url_var] = env[yaml_url_var] ?: ''
164 }
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200165 def yaml_url = global_variables[yaml_url_var] // Real YAML URL
166 def yaml_key = param.value.get_variable_from_yaml.yaml_key
azvyagintsev353b8762022-01-14 12:30:43 +0200167 // Key to get the data from YAML, to interpolate in the groovy, for example:
168 // <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 +0200169 if (yaml_url) {
170 if (!yamls_from_urls[yaml_url]) {
azvyagintsev25015272023-11-28 17:31:18 +0200171 _msg += "\nReading YAML from ${yaml_url} for ${param.key}"
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200172 def yaml_content = http.restGet(base, yaml_url)
Dennis Dmitriev6c355be2021-11-09 14:06:56 +0200173 yamls_from_urls[yaml_url] = readYaml text: yaml_content
174 }
azvyagintsev25015272023-11-28 17:31:18 +0200175 _msg += "\nGetting key ${yaml_key} from YAML ${yaml_url} for ${param.key}"
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200176 def template_variables = [
azvyagintsev25015272023-11-28 17:31:18 +0200177 'yaml_data': yamls_from_urls[yaml_url],
Dennis Dmitriev6c355be2021-11-09 14:06:56 +0200178 ]
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200179 def request = "\${yaml_data${yaml_key}}"
Dennis Dmitriev5e076712022-02-08 15:05:21 +0200180 def result
Dennis Dmitriev450cf732021-11-11 14:59:17 +0200181 // Catch errors related to wrong key or index in the list or map objects
182 // For wrong key in map or wrong index in list, groovy returns <null> object,
183 // but it can be catched only after the string interpolation <template.toString()>,
184 // so we should catch the string 'null' instead of object <null>.
185 try {
186 template = engine.createTemplate(request).make(template_variables)
Dennis Dmitriev5e076712022-02-08 15:05:21 +0200187 result = template.toString()
Dennis Dmitriev450cf732021-11-11 14:59:17 +0200188 if (result == 'null') {
189 error "No such key or index, got 'null'"
190 }
191 } catch (e) {
192 error("Failed to get the key ${yaml_key} from YAML ${yaml_url}: " + e.toString())
193 }
194
195 parameters.add([$class: "${param.value.type}", name: "${param.key}", value: result])
azvyagintsev25015272023-11-28 17:31:18 +0200196 _msg += "\n${param.key}: <${param.value.type}>\n${result}"
Dennis Dmitriev6c355be2021-11-09 14:06:56 +0200197 } else {
azvyagintsev353b8762022-01-14 12:30:43 +0200198 common.warningMsg("'yaml_url' in ${param.key} is empty, skipping get_variable_from_yaml")
Dennis Dmitriev6c355be2021-11-09 14:06:56 +0200199 }
200 } else {
azvyagintsev353b8762022-01-14 12:30:43 +0200201 common.warningMsg("${param.key} missing 'yaml_url'/'yaml_key' parameters, skipping get_variable_from_yaml")
Dennis Dmitriev6c355be2021-11-09 14:06:56 +0200202 }
Dennis Dmitrievce470932019-09-18 18:31:11 +0300203 } else if (param.value.containsKey('use_template')) {
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200204 template = engine.createTemplate(param.value.use_template.toString()).make(env_variables + global_variables)
Dennis Dmitrievce470932019-09-18 18:31:11 +0300205 parameters.add([$class: "${param.value.type}", name: "${param.key}", value: template.toString()])
azvyagintsev25015272023-11-28 17:31:18 +0200206 _msg += "\n${param.key}: <${param.value.type}>\n${template.toString()}"
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200207 } else if (param.value.containsKey('use_variables_map')) {
azvyagintsev25015272023-11-28 17:31:18 +0200208 // Generate multistring YAML with key/value pairs (like job_parameters) from a nested parameters map
209 def nested_parameters = generateParameters(param.value.use_variables_map, global_variables)
210 def nested_values = [:]
211 for (_parameter in nested_parameters) {
212 if (_parameter.$class == '_defaultText') {
213 // This is a special type for multiline with default values
214 def _values = readYaml(text: _parameter.value ?: '---') ?: [:]
215 _values << nested_values
216 nested_values = _values
217 } else {
218 nested_values[_parameter.name] = _parameter.value
219 }
220 }
221 def multistring_value = mcpcommon.dumpYAML(nested_values)
222 parameters.add([$class: "${param.value.type}", name: "${param.key}", value: multistring_value])
223 _msg += "\n${param.key}: <${param.value.type}>\n${multistring_value}"
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300224 }
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300225 }
azvyagintsev25015272023-11-28 17:31:18 +0200226 common.infoMsg(_msg)
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200227 return parameters
228}
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300229
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200230
231/**
232 * Run a Jenkins job using the collected parameters
233 *
234 * @param job_name Name of the running job
235 * @param job_parameters Map that declares which values from global_variables should be used
236 * @param global_variables Map that keeps the artifact URLs and used 'env' objects
237 * @param propagate Boolean. If false: allows to collect artifacts after job is finished, even with FAILURE status
238 * If true: immediatelly fails the pipeline. DO NOT USE 'true' if you want to collect artifacts
239 * for 'finally' steps
240 */
241def runJob(job_name, job_parameters, global_variables, Boolean propagate = false) {
242
243 def parameters = generateParameters(job_parameters, global_variables)
azvyagintsevebe94b42025-01-11 18:07:41 +0200244 // Inject hidden random parameter (is not showed in jjb) to be sure we are triggering unique downstream job.
245 // Most actual case - parallel run for same jobs( but with different params)
246 // WARNING: dont move hack to generateParameters:
247 // PRODX-48965 - it will conflict with si_run_steps logic and will be copy-paste to sub.jobs
248 String rand_value = "${env.JOB_NAME.toLowerCase()}-${env.BUILD_NUMBER}-${UUID.randomUUID().toString().split('-')[0]}"
249 parameters.add([$class: "StringParameterValue",
250 name : "RANDOM_SEED_STRING",
251 value : rand_value])
azvyagintsevd3add022025-01-15 13:15:50 +0200252 // Build the job
253 def job_info = build job: "${job_name}", parameters: parameters, propagate: propagate
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300254 return job_info
255}
256
azvyagintsev061179d2021-05-05 16:52:18 +0300257def runOrGetJob(job_name, job_parameters, global_variables, propagate, String fullTaskName = '') {
258 /**
259 * Run job directly or try to find already executed build
260 * Flow, in case CI_JOBS_OVERRIDES passed:
261 *
262 *
263 * CI_JOBS_OVERRIDES = text in yaml|json format
264 * CI_JOBS_OVERRIDES = 'kaas-testing-core-release-artifact' : 3505
265 * 'reindex-testing-core-release-index-with-rc' : 2822
266 * 'si-test-release-sanity-check-prepare-configuration': 1877
267 */
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200268 def common = new com.mirantis.mk.Common()
azvyagintsev061179d2021-05-05 16:52:18 +0300269 def jobsOverrides = readYaml(text: env.CI_JOBS_OVERRIDES ?: '---') ?: [:]
270 // get id of overriding job
271 def jobOverrideID = jobsOverrides.getOrDefault(fullTaskName, '')
azvyagintsev061179d2021-05-05 16:52:18 +0300272 if (fullTaskName in jobsOverrides.keySet()) {
273 common.warningMsg("Overriding: ${fullTaskName}/${job_name} <<< ${jobOverrideID}")
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200274 return Jenkins.instance.getItemByFullName(job_name, hudson.model.Job).getBuildByNumber(jobOverrideID.toInteger())
azvyagintsev061179d2021-05-05 16:52:18 +0300275 } else {
276 return runJob(job_name, job_parameters, global_variables, propagate)
277 }
278}
279
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300280/**
281 * Store URLs of the specified artifacts to the global_variables
282 *
Andrii Baraniukcf4c2fa2023-04-18 13:53:32 +0300283 * @param build_url URL of the completed job
284 * @param step_artifacts Map that contains artifact names in the job, and variable names
285 * where the URLs to that atrifacts should be stored, for example:
286 * {'ARTIFACT1': 'logs.tar.gz', 'ARTIFACT2': 'test_report.xml', ...}
287 * @param global_variables Map that will keep the artifact URLs. Variable 'ARTIFACT1', for example,
288 * be used in next job parameters: {'ARTIFACT1_URL':{ 'use_variable': 'ARTIFACT1', ...}}
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300289 *
Andrii Baraniukcf4c2fa2023-04-18 13:53:32 +0300290 * If the artifact with the specified name not found, the parameter ARTIFACT1_URL
291 * will be empty.
292 * @param artifactory_server Artifactory server ID defined in Jenkins config
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300293 *
294 */
Dennis Dmitrievaa0fa742024-03-27 22:38:25 +0200295def storeArtifacts(build_url, step_artifacts, global_variables, job_name, build_num, artifactory_url = '', artifactory_server = '', artifacts_msg='local artifacts') {
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300296 def common = new com.mirantis.mk.Common()
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300297 def http = new com.mirantis.mk.Http()
Andrii Baraniukcf4c2fa2023-04-18 13:53:32 +0300298 def artifactory = new com.mirantis.mcp.MCPArtifactory()
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200299 if (!artifactory_url && !artifactory_server) {
Andrii Baraniukcf4c2fa2023-04-18 13:53:32 +0300300 artifactory_url = 'https://artifactory.mcp.mirantis.net/artifactory/api/storage/si-local/jenkins-job-artifacts'
301 } else if (!artifactory_url && artifactory_server) {
302 artifactory_url = artifactory.getArtifactoryServer(artifactory_server).getUrl() + '/artifactory/api/storage/si-local/jenkins-job-artifacts'
Aleksey Zvyagintsev25ed4a52021-05-12 14:35:03 +0000303 }
Andrii Baraniukcf4c2fa2023-04-18 13:53:32 +0300304
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300305 def baseJenkins = [:]
306 def baseArtifactory = [:]
307 build_url = build_url.replaceAll(~/\/+$/, "")
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300308 baseArtifactory["url"] = artifactory_url + "/${job_name}/${build_num}"
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300309 baseJenkins["url"] = build_url
310 def job_config = http.restGet(baseJenkins, "/api/json/")
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300311 def job_artifacts = job_config['artifacts']
Dennis Dmitrievaa0fa742024-03-27 22:38:25 +0200312 common.infoMsg("Attempt to store ${artifacts_msg} for: ${job_name}/${build_num}")
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300313 for (artifact in step_artifacts) {
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300314 try {
azvyagintsev0d978152022-01-27 14:01:33 +0200315 def artifactoryResp = http.restGet(baseArtifactory, "/${artifact.value}")
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300316 global_variables[artifact.key] = artifactoryResp.downloadUri
azvyagintsev0d978152022-01-27 14:01:33 +0200317 common.infoMsg("Artifact URL ${artifactoryResp.downloadUri} stored to ${artifact.key}")
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300318 continue
319 } catch (Exception e) {
azvyagintsev0d978152022-01-27 14:01:33 +0200320 common.warningMsg("Can't find an artifact in ${artifactory_url}/${job_name}/${build_num}/${artifact.value} to store in ${artifact.key}\n" +
321 "error code ${e.message}")
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300322 }
323
azvyagintsev0d978152022-01-27 14:01:33 +0200324 def job_artifact = job_artifacts.findAll { item -> artifact.value == item['fileName'] || artifact.value == item['relativePath'] }
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300325 if (job_artifact.size() == 1) {
326 // Store artifact URL
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300327 def artifact_url = "${build_url}/artifact/${job_artifact[0]['relativePath']}"
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300328 global_variables[artifact.key] = artifact_url
azvyagintsev0d978152022-01-27 14:01:33 +0200329 common.infoMsg("Artifact URL ${artifact_url} stored to ${artifact.key}")
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300330 } else if (job_artifact.size() > 1) {
331 // Error: too many artifacts with the same name, fail the job
332 error "Multiple artifacts ${artifact.value} for ${artifact.key} found in the build results ${build_url}, expected one:\n${job_artifact}"
333 } else {
334 // Warning: no artifact with expected name
azvyagintsev0d978152022-01-27 14:01:33 +0200335 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 +0300336 global_variables[artifact.key] = ''
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300337 }
338 }
339}
340
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200341
342def getStatusStyle(status) {
343 // Styling the status of job result
344 def status_style = ''
345 switch (status) {
346 case "SUCCESS":
347 status_style = "<td style='color: green;'><img src='/images/16x16/blue.png' alt='SUCCESS'>"
348 break
349 case "UNSTABLE":
350 status_style = "<td style='color: #FF5733;'><img src='/images/16x16/yellow.png' alt='UNSTABLE'>"
351 break
352 case "ABORTED":
353 status_style = "<td style='color: red;'><img src='/images/16x16/aborted.png' alt='ABORTED'>"
354 break
355 case "NOT_BUILT":
356 status_style = "<td style='color: red;'><img src='/images/16x16/aborted.png' alt='NOT_BUILT'>"
357 break
358 case "FAILURE":
359 status_style = "<td style='color: red;'><img src='/images/16x16/red.png' alt='FAILURE'>"
360 break
361 default:
362 status_style = "<td>-"
363 }
364 return status_style
365}
366
367
368def getTrStyle(jobdata) {
369 def trstyle = "<tr>"
370 // Grey background for 'finally' jobs in list
371 if (jobdata.getOrDefault('type', '') == 'finally') {
372 trstyle = "<tr style='background: #DDDDDD;'>"
373 }
374 return trstyle
375}
376
377
AndrewB8505a7f2020-06-05 13:42:08 +0300378/**
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200379 * Update a 'job' step description
AndrewB8505a7f2020-06-05 13:42:08 +0300380 *
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200381 * @param jobsdata Map with a 'job' step details and status
AndrewB8505a7f2020-06-05 13:42:08 +0300382 */
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200383def getJobDescription(jobdata) {
384 def trstyle = getTrStyle(jobdata)
385 def display_name = jobdata['desc'] ? "${jobdata['desc']}: ${jobdata['build_id']}" : "${jobdata['name']}: ${jobdata['build_id']}"
386 if ((env.WF_SHOW_FULL_WORKFLOW_DESCRIPTION ?: false).toBoolean()) {
387 display_name = "[${jobdata['name']}/${jobdata['build_id']}]: ${jobdata['desc']}"
388 }
AndrewB8505a7f2020-06-05 13:42:08 +0300389
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200390 // Attach url for already built jobs
391 def build_url = display_name
392 if (jobdata['build_url'] != "0") {
393 build_url = "<a href=${jobdata['build_url']}>$display_name</a>"
394 }
395
396 def status_style = getStatusStyle(jobdata['status'].toString())
397
398 return [[trstyle, build_url, jobdata['duration'], status_style,],]
399}
400
401
402/**
403 * Update a 'script' step description
404 *
405 * @param jobsdata Map with a 'script' step details and status
406 */
407def getScriptDescription(jobdata) {
408 def trstyle = getTrStyle(jobdata)
409
410 def display_name = "${jobdata['desc']}" ?: "${jobdata['name']}"
411 if ((env.WF_SHOW_FULL_WORKFLOW_DESCRIPTION ?: false).toBoolean()) {
412 display_name = "[${jobdata['name']}]: ${jobdata['desc']}"
413 }
414
415 // Attach url for already built jobs
416 def build_url = display_name
417 if (jobdata['build_url'] != "0") {
418 build_url = "<a href=${jobdata['build_url']}>$display_name</a>"
419 }
420
421 def status_style = getStatusStyle(jobdata['status'].toString())
422
423 return [[trstyle, build_url, jobdata['duration'], status_style,],]
424}
425
426
427/**
428 * Update a 'parallel' or a 'sequence' step description
429 *
430 * @param jobsdata Map with a 'together' step details and statuses
431 */
432def getNestedDescription(jobdata) {
433 def tableEntries = []
434 def trstyle = getTrStyle(jobdata)
Tetiana Leontovych20fc4b22025-06-24 20:26:51 +0200435 def nestedTableEntries = []
436 def nested_trstyle = ''
437 def nested_display_name = ''
438 def nested_duration = ''
439 def nested_status_style = ''
440 def _other_data = ''
441
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200442
443 def display_name = "${jobdata['desc']}" ?: "${jobdata['name']}"
444 if ((env.WF_SHOW_FULL_WORKFLOW_DESCRIPTION ?: false).toBoolean()) {
445 display_name = "[${jobdata['name']}]: ${jobdata['desc']}"
446 }
447
448 // Attach url for already built jobs
449 def build_url = display_name
450 if (jobdata['build_url'] != "0") {
451 build_url = "<a href=${jobdata['build_url']}>$display_name</a>"
452 }
453
454 def status_style = getStatusStyle(jobdata['status'].toString())
455
456 tableEntries += [[trstyle, build_url, jobdata['duration'], status_style,],]
457
458 // Collect nested job descriptions
459 for (nested_jobdata in jobdata['nested_steps_data']) {
Tetiana Leontovych20fc4b22025-06-24 20:26:51 +0200460 (nestedTableEntries, _other_data) = getStepDescription(nested_jobdata.value)
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200461 for (nestedTableEntry in nestedTableEntries) {
462 (nested_trstyle, nested_display_name, nested_duration, nested_status_style) = nestedTableEntry
463 tableEntries += [[nested_trstyle, "&emsp;| ${nested_jobdata.key}: ${nested_display_name}", nested_duration, nested_status_style,],]
464 }
465 }
466 return tableEntries
467}
468
469
470def getStepDescription(jobs_data) {
471 def tableEntries = []
472 def child_jobs_description = ''
AndrewB8505a7f2020-06-05 13:42:08 +0300473 for (jobdata in jobs_data) {
AndrewB8505a7f2020-06-05 13:42:08 +0300474
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200475 if (jobdata['step_key'] == 'job') {
476 tableEntries += getJobDescription(jobdata)
AndrewB8505a7f2020-06-05 13:42:08 +0300477 }
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200478 else if (jobdata['step_key'] == 'script') {
479 tableEntries += getScriptDescription(jobdata)
AndrewB8505a7f2020-06-05 13:42:08 +0300480 }
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200481 else if (jobdata['step_key'] == 'parallel' || jobdata['step_key'] == 'sequence') {
482 tableEntries += getNestedDescription(jobdata)
483 }
AndrewB8505a7f2020-06-05 13:42:08 +0300484
485 // Collecting descriptions of builded child jobs
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200486 if (jobdata['child_desc'] != '') {
AndrewB8505a7f2020-06-05 13:42:08 +0300487 child_jobs_description += "<b><small><a href=${jobdata['build_url']}>- ${jobdata['name']} (${jobdata['status']}):</a></small></b><br>"
azvyagintsev0d978152022-01-27 14:01:33 +0200488 // remove "null" message-result from description, but leave XXX:JOBRESULT in description
azvyagintsev8b8224d2023-10-06 20:52:26 +0300489 if (jobdata['child_desc'] != 'null') {
azvyagintsev0d978152022-01-27 14:01:33 +0200490 child_jobs_description += "<small>${jobdata['child_desc']}</small><br>"
491 }
AndrewB8505a7f2020-06-05 13:42:08 +0300492 }
493 }
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200494 return [tableEntries, child_jobs_description]
495}
496
497/**
498 * Update description for workflow steps
499 *
500 * @param jobs_data Map with all step names and result statuses, to showing it in description
501 */
502def updateDescription(jobs_data) {
503 def child_jobs_description = '<strong>Descriptions from jobs:</strong><br>'
504 def table_template_start = "<div><table style='border: solid 1px;'><tr><th>Job:</th><th>Duration:</th><th>Status:</th></tr>"
505 def table_template_end = "</table></div>"
Tetiana Leontovych8913fa12025-06-24 01:06:47 +0200506 def tableEntries = ''
507 def _child_jobs_description = ''
508 def trstyle = ''
509 def display_name = ''
510 def duration = ''
511 def status_style = ''
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200512
513 (tableEntries, _child_jobs_description) = getStepDescription(jobs_data)
514
515 def table = ''
516 for (tableEntry in tableEntries) {
517 // Collect table
518 (trstyle, display_name, duration, status_style) = tableEntry
519 table += "${trstyle}<td>${display_name}</td><td>${duration}</td>${status_style}</td></tr>"
520 }
521
522 child_jobs_description += _child_jobs_description
523
AndrewB8505a7f2020-06-05 13:42:08 +0300524 currentBuild.description = table_template_start + table + table_template_end + child_jobs_description
525}
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300526
Dennis Dmitrievaa0fa742024-03-27 22:38:25 +0200527def runStep(global_variables, step, Boolean propagate = false, artifactoryBaseUrl = '', artifactoryServer = '', parent_global_variables=null) {
azvyagintsev0d978152022-01-27 14:01:33 +0200528 return {
529 def common = new com.mirantis.mk.Common()
530 def engine = new groovy.text.GStringTemplateEngine()
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200531 def env_variables = common.getEnvAsMap()
Tetiana Leontovych8913fa12025-06-24 01:06:47 +0200532 def artifacts_msg = ''
azvyagintsev0d978152022-01-27 14:01:33 +0200533
534 String jobDescription = step['description'] ?: ''
535 def jobName = step['job']
536 def jobParameters = [:]
537 def stepParameters = step['parameters'] ?: [:]
538 if (step['inherit_parent_params'] ?: false) {
539 // add parameters from the current job for the child job
540 jobParameters << getJobDefaultParameters(env.JOB_NAME)
541 }
542 // add parameters from the workflow for the child job
543 jobParameters << stepParameters
544 def wfPauseStepBeforeRun = (step['wf_pause_step_before_run'] ?: false).toBoolean()
545 def wfPauseStepTimeout = (step['wf_pause_step_timeout'] ?: 10).toInteger()
546 def wfPauseStepSlackReportChannel = step['wf_pause_step_slack_report_channel'] ?: ''
547
548 if (wfPauseStepBeforeRun) {
549 // Try-catch construction will allow to continue Steps, if timeout reached
550 try {
551 if (wfPauseStepSlackReportChannel) {
552 def slack = new com.mirantis.mcp.SlackNotification()
azvyagintsevda22aa82022-06-10 15:46:55 +0300553 wfPauseStepSlackReportChannel.split(',').each {
554 slack.jobResultNotification('wf_pause_step_before_run',
555 it.toString(),
556 env.JOB_NAME, null,
557 env.BUILD_URL, 'slack_webhook_url')
558 }
azvyagintsev0d978152022-01-27 14:01:33 +0200559 }
560 timeout(time: wfPauseStepTimeout, unit: 'MINUTES') {
561 input("Workflow pause requested before run: ${jobName}/${jobDescription}\n" +
562 "Timeout set to ${wfPauseStepTimeout}.\n" +
563 "Do you want to proceed workflow?")
564 }
565 } catch (err) { // timeout reached or input false
Sergey Lalova89e16a2024-10-17 20:26:44 +0400566 def cause = err.getCauses().get(0)
567 if (cause instanceof org.jenkinsci.plugins.workflow.steps.TimeoutStepExecution.ExceededTimeout) {
azvyagintsev0d978152022-01-27 14:01:33 +0200568 common.infoMsg("Timeout finished, continue..")
Sergey Lalova89e16a2024-10-17 20:26:44 +0400569 } else {
570 def user = causes[0].getUser()
571 error("Aborted after workflow pause by: [${user}]")
azvyagintsev0d978152022-01-27 14:01:33 +0200572 }
573 }
574 }
575 common.infoMsg("Attempt to run: ${jobName}/${jobDescription}")
576 // Collect job parameters and run the job
577 // WARN(alexz): desc must not contain invalid chars for yaml
578 def jobResult = runOrGetJob(jobName, jobParameters,
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200579 global_variables, propagate, jobDescription)
azvyagintsev0d978152022-01-27 14:01:33 +0200580 def buildDuration = jobResult.durationString ?: '-'
581 if (buildDuration.toString() == null) {
582 buildDuration = '-'
583 }
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200584 def desc = engine.createTemplate(jobDescription.toString()).make(env_variables + global_variables)
585 if ((desc.toString() == '') || (desc.toString() == 'null')) {
586 desc = ''
587 }
azvyagintsev0d978152022-01-27 14:01:33 +0200588 def jobSummary = [
589 job_result : jobResult.getResult().toString(),
590 build_url : jobResult.getAbsoluteUrl().toString(),
591 build_id : jobResult.getId().toString(),
592 buildDuration : buildDuration,
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200593 desc : desc,
azvyagintsev0d978152022-01-27 14:01:33 +0200594 ]
azvyagintsev40540282025-07-04 11:33:17 +0300595 /// START: Print combined, already passed job/id -
596 // required ONLY for manual debugs with CI_JOBS_OVERRIDES logic
597 if (!global_variables['GLOBAL_PINS']) {
598 global_variables['GLOBAL_PINS'] = []
599 parent_global_variables['GLOBAL_PINS'] = []
600 }
601 def _label = desc ?: jobName
602 def _item_str = sprintf('"%s": %s', _label, jobSummary['build_id'])
603 global_variables['GLOBAL_PINS'].add(_item_str)
604 parent_global_variables['GLOBAL_PINS'].add(_item_str)
605 common.infoMsg("Current debug pins:")
606 common.infoMsg(global_variables['GLOBAL_PINS'].toSet().sort().collect { "${it}" }.join(",\n") + ',')
607 /// END
azvyagintsev0d978152022-01-27 14:01:33 +0200608 def _buildDescription = jobResult.getDescription().toString()
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200609 if (_buildDescription) {
azvyagintsev0d978152022-01-27 14:01:33 +0200610 jobSummary['build_description'] = _buildDescription
611 }
612 // Store links to the resulting artifacts into 'global_variables'
613 storeArtifacts(jobSummary['build_url'], step['artifacts'],
Dennis Dmitrievaa0fa742024-03-27 22:38:25 +0200614 global_variables, jobName, jobSummary['build_id'], artifactoryBaseUrl, artifactoryServer, artifacts_msg='artifacts to local variables')
615 // Store links to the resulting 'global_artifacts' into 'global_variables'
616 storeArtifacts(jobSummary['build_url'], step['global_artifacts'],
617 global_variables, jobName, jobSummary['build_id'], artifactoryBaseUrl, artifactoryServer, artifacts_msg='global_artifacts to local variables')
618 // Store links to the resulting 'global_artifacts' into 'parent_global_variables'
619 storeArtifacts(jobSummary['build_url'], step['global_artifacts'],
620 parent_global_variables, jobName, jobSummary['build_id'], artifactoryBaseUrl, artifactoryServer, artifacts_msg='global_artifacts to global_variables')
azvyagintsev0d978152022-01-27 14:01:33 +0200621 return jobSummary
622 }
623}
AndrewB8505a7f2020-06-05 13:42:08 +0300624
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200625
Dennis Dmitrievaa0fa742024-03-27 22:38:25 +0200626def runScript(global_variables, step, artifactoryBaseUrl = '', artifactoryServer = '', scriptsLibrary = null, parent_global_variables=null) {
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200627 def common = new com.mirantis.mk.Common()
628 def env_variables = common.getEnvAsMap()
629
630 if (!scriptsLibrary) {
631 error "'scriptsLibrary' argument is not provided to load a script object '${step['script']}' from that library"
632 }
633 // Evaluate the object from it's name, for example: scriptsLibrary.com.mirantis.si.runtime_steps.ParallelMkeMoskUpgradeSequences
634 def scriptObj = scriptsLibrary
635 for (sObj in step['script'].split("\\.")) {
636 scriptObj = scriptObj."$sObj"
637 }
638
639 def script = scriptObj.new()
640
641 def scriptSummary = [
642 job_result : '',
643 desc : step['description'] ?: '',
644 ]
645
646 // prepare 'script_env' from merged 'env' and script step parameters
647 def script_env = env_variables.clone()
Tetiana Leontovych8913fa12025-06-24 01:06:47 +0200648 def artifacts_msg = ''
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200649 def stepParameters = step['parameters'] ?: [:]
650 def script_parameters = generateParameters(stepParameters, global_variables)
651 println "${script_parameters}"
652 for (script_parameter in script_parameters) {
653 common.infoMsg("Updating script env['${script_parameter.name}'] with value: ${script_parameter.value}")
654 script_env[script_parameter.name] = script_parameter.value
655 }
656
657 try {
658 script.main(this, script_env)
659 scriptSummary['script_result'] = 'SUCCESS'
660 } catch (InterruptedException e) {
661 scriptSummary['script_result'] = 'ABORTED'
662 printStackTrace(e)
663 } catch (e) {
664 scriptSummary['script_result'] = 'FAILURE'
665 printStackTrace(e)
666 }
667
Dennis Dmitrievaa0fa742024-03-27 22:38:25 +0200668 // Store links to the resulting 'artifacts' into 'global_variables'
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200669 storeArtifacts(env.BUILD_URL, step['artifacts'],
Dennis Dmitrievaa0fa742024-03-27 22:38:25 +0200670 global_variables, env.JOB_NAME, env.BUILD_NUMBER, artifactoryBaseUrl, artifactoryServer, artifacts_msg='artifacts to local variables')
671 // Store links to the resulting 'global_artifacts' into 'global_variables'
672 storeArtifacts(env.BUILD_URL, step['global_artifacts'],
673 global_variables, env.JOB_NAME, env.BUILD_NUMBER, artifactoryBaseUrl, artifactoryServer, artifacts_msg='global_artifacts to local variables')
674 // Store links to the resulting 'global_artifacts' into 'parent_global_variables'
675 storeArtifacts(env.BUILD_URL, step['global_artifacts'],
676 parent_global_variables, env.JOB_NAME, env.BUILD_NUMBER, artifactoryBaseUrl, artifactoryServer, artifacts_msg='global_artifacts to global_variables')
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200677
678 return scriptSummary
679}
680
681
Dennis Dmitrievaa0fa742024-03-27 22:38:25 +0200682def runParallel(global_variables, step, failed_jobs, global_jobs_data, nested_steps_data, artifactoryBaseUrl = '', artifactoryServer = '', scriptsLibrary = null, prefixMsg = '', parent_global_variables=null) {
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200683 // Run the specified steps in parallel
684 // Repeat the steps for each parameters set from 'repeat_with_parameters_from_yaml'
685 // If 'repeat_with_parameters_from_yaml' is not provided, then 'parallel' step will perform just one iteration for a default "- _FOO: _BAR" parameter
686 // If 'repeat_with_parameters_from_yaml' is present, but the specified artifact contains empty list '[]', then 'parallel' step will be skipped
687 // Example:
688 // - parallel:
689 // - job:
690 // - job:
691 // - sequence:
692 // repeat_with_parameters_from_yaml:
693 // type: TextParameterValue
694 // get_variable_from_url: SI_PARALLEL_PARAMETERS
695 // max_concurrent: 2 # how many parallel jobs shold be run at the same time
696 // max_concurrent_interval: 300 # how many seconds should be passed between checking for an available concurrency
697 // check_failed_concurrent: false # stop waiting for available concurrent executors if count of failed jobs >= max_concurrent,
698 // # which means that all available shared resources are occupied by the failed jobs
azvyagintsev8bf15d72024-09-19 14:43:33 +0300699 // abort_on_parallel_fail: false # pass parallel.fail_fast option. force your parallel stages to all be aborted when any one of them fails
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200700 def common = new com.mirantis.mk.Common()
701
702 def sourceText = ""
703 def defaultSourceText = "- _FOO: _BAR"
704 if (step['repeat_with_parameters_from_yaml']) {
705 def sourceParameter = ["repeat_with_parameters_from_yaml": step['repeat_with_parameters_from_yaml']]
706 for (parameter in generateParameters(sourceParameter, global_variables)) {
707 if (parameter.name == "repeat_with_parameters_from_yaml") {
708 sourceText = parameter.value
709 common.infoMsg("'repeat_with_parameters_from_yaml' is defined, using it as a yaml text:\n${sourceText}")
710 }
711 }
712 }
713 if (!sourceText) {
714 sourceText = defaultSourceText
715 common.warningMsg("'repeat_with_parameters_from_yaml' is not defined. To get one iteration, use default single entry:\n${sourceText}")
716 }
717 def iterateParametersList = readYaml text: sourceText
718 if (!(iterateParametersList instanceof List)) {
719 // Stop the pipeline if there is wrong parameters data type, to not generate parallel jobs for wrong data
720 error "Expected a List in 'repeat_with_parameters_from_yaml' for 'parallel' step, but got:\n${sourceText}"
721 }
722
723 // Limit the maximum steps in parallel at the same time
724 def max_concurrent = (step['max_concurrent'] ?: 100).toInteger()
725 // Sleep for the specified amount of time until a free thread will be available
726 def max_concurrent_interval = (step['max_concurrent_interval'] ?: 600).toInteger()
727 // Check that failed jobs is not >= free executors. if 'true', then don't wait for free executors, fail the parallel step
728 def check_failed_concurrent = (step['check_failed_concurrent'] ?: false).toBoolean()
729
730 def jobs = [:]
azvyagintsev8bf15d72024-09-19 14:43:33 +0300731 jobs.failFast = (step['abort_on_parallel_fail'] ?: false).toBoolean()
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200732 def nested_step_id = 0
733 def free_concurrent = max_concurrent
734 def failed_concurrent = []
735
736 common.printMsg("${prefixMsg} Running parallel steps with the following parameters:\n${iterateParametersList}", "purple")
737
738 for (parameters in iterateParametersList) {
739 for (parallel_step in step['parallel']) {
740 def step_name = "parallel#${nested_step_id}"
741 def nested_step = parallel_step
742 def nested_step_name = step_name
743 def nested_prefix_name = "${prefixMsg}${nested_step_name} | "
744
745 nested_steps_data[step_name] = []
746 prepareJobsData([nested_step,], 'parallel', nested_steps_data[step_name])
747
748 //Copy global variables and merge "parameters" dict into it for the current particular step
749 def nested_global_variables = global_variables.clone()
750 nested_global_variables << parameters
751
752 jobs[step_name] = {
753 // initialRecurrencePeriod in milliseconds
754 waitUntil(initialRecurrencePeriod: 1500, quiet: true) {
755 if (check_failed_concurrent) {
756 if (failed_concurrent.size() >= max_concurrent){
757 common.errorMsg("Failed jobs count is equal max_concurrent value ${max_concurrent}. Will not continue because resources are consumed")
758 error("max_concurrent == failed_concurrent")
759 }
760 }
761 if (free_concurrent > 0) {
762 free_concurrent--
763 true
764 } else {
765 sleep(max_concurrent_interval)
766 false
767 }
768 }
769
770 try {
Dennis Dmitrievaa0fa742024-03-27 22:38:25 +0200771 runWorkflowStep(nested_global_variables, nested_step, 0, nested_steps_data[nested_step_name], global_jobs_data, failed_jobs, false, artifactoryBaseUrl, artifactoryServer, scriptsLibrary, nested_prefix_name, parent_global_variables)
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200772 }
773 catch (e) {
774 failed_concurrent.add(step_name)
775 throw(e)
776 }
777
778 free_concurrent++
779 } // 'jobs' closure
780
781 nested_step_id++
782 }
783 }
784
785 def parallelSummary = [
786 nested_result : '',
787 desc : step['description'] ?: '',
788 nested_steps_data : [:],
789 ]
790
791 if (iterateParametersList) {
792 // Run parallel iterations
793 try {
794 common.infoMsg("${prefixMsg} Run steps in parallel")
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200795 parallel jobs
796
797 parallelSummary['nested_result'] = 'SUCCESS'
798 } catch (InterruptedException e) {
799 parallelSummary['nested_result'] = 'ABORTED'
800 printStackTrace(e)
801 } catch (e) {
802 parallelSummary['nested_result'] = 'FAILURE'
803 printStackTrace(e)
804 }
805 parallelSummary['nested_steps_data'] = nested_steps_data
806 }
807 else
808 {
809 // No parameters were provided to iterate
810 common.errorMsg("${prefixMsg} No parameters were provided to iterate, skipping 'parallel' step")
811 parallelSummary['nested_result'] = 'SUCCESS'
812 }
813 return parallelSummary
814}
815
816
Dennis Dmitrievaa0fa742024-03-27 22:38:25 +0200817def runSequence(global_variables, step, failed_jobs, global_jobs_data, nested_steps_data, artifactoryBaseUrl = '', artifactoryServer = '', scriptsLibrary = null, prefixMsg = '', parent_global_variables=null) {
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200818 // Run the steps in the specified order, like in main workflow, but repeat the sequence for each parameters set from 'repeat_with_parameters_from_yaml'
819 // If 'repeat_with_parameters_from_yaml' is not provided, then 'sequence' step will perform just one iteration for a default "- _FOO: _BAR" parameter
820 // If 'repeat_with_parameters_from_yaml' is present, but the specified artifact contains empty list '[]', then 'sequence' step will be skipped
821 // - sequence:
822 // - job:
823 // - job:
824 // - script:
825 // repeat_with_parameters_from_yaml:
826 // type: TextParameterValue
827 // get_variable_from_url: SI_PARALLEL_PARAMETERS
828 def common = new com.mirantis.mk.Common()
829
830 def sourceText = ""
831 def defaultSourceText = "- _FOO: _BAR"
832 if (step['repeat_with_parameters_from_yaml']) {
833 def sourceParameter = ["repeat_with_parameters_from_yaml": step['repeat_with_parameters_from_yaml']]
834 for (parameter in generateParameters(sourceParameter, global_variables)) {
835 if (parameter.name == "repeat_with_parameters_from_yaml") {
836 sourceText = parameter.value
837 common.infoMsg("'repeat_with_parameters_from_yaml' is defined, using it as a yaml text:\n${sourceText}")
838 }
839 }
840 }
841 if (!sourceText) {
842 sourceText = defaultSourceText
843 common.warningMsg("'repeat_with_parameters_from_yaml' is not defined. To get one iteration, use default single entry:\n${sourceText}")
844 }
845 def iterateParametersList = readYaml text: sourceText
846 if (!(iterateParametersList instanceof List)) {
847 // Stop the pipeline if there is wrong parameters data type, to not generate parallel jobs for wrong data
848 error "Expected a List in 'repeat_with_parameters_from_yaml' for 'sequence' step, but got:\n${sourceText}"
849 }
850
851 def jobs = [:]
852 def nested_step_id = 0
853
854 common.printMsg("${prefixMsg} Running parallel steps with the following parameters:\n${iterateParametersList}", "purple")
855
856 for (parameters in iterateParametersList) {
857 def step_name = "sequence#${nested_step_id}"
858 def nested_steps = step['sequence']
859 def nested_step_name = step_name
860 def nested_prefix_name = "${prefixMsg}${nested_step_name} | "
861
862 nested_steps_data[step_name] = []
863 prepareJobsData(nested_steps, 'sequence', nested_steps_data[step_name])
864
865 //Copy global variables and merge "parameters" dict into it for the current particular step
866 def nested_global_variables = global_variables.clone()
867 nested_global_variables << parameters
868
869 jobs[step_name] = {
870
Dennis Dmitrievaa0fa742024-03-27 22:38:25 +0200871 runSteps(nested_steps, nested_global_variables, failed_jobs, nested_steps_data[nested_step_name], global_jobs_data, 0, false, artifactoryBaseUrl, artifactoryServer, scriptsLibrary, nested_prefix_name, parent_global_variables)
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200872
873 } // 'jobs' closure
874
875 nested_step_id++
876 }
877
878 def sequenceSummary = [
879 nested_result : '',
880 desc : step['description'] ?: '',
881 nested_steps_data : [:],
882 ]
883
884 if (iterateParametersList) {
885 // Run sequence iterations
886 try {
887 jobs.each { stepName, job ->
888 common.infoMsg("${prefixMsg} Running sequence ${stepName}")
889 job()
azvyagintsevd5f05122024-09-21 13:00:16 +0300890 // just in case sleep.
891 sleep(5)
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200892 }
893 sequenceSummary['nested_result'] = 'SUCCESS'
894 } catch (InterruptedException e) {
895 sequenceSummary['nested_result'] = 'ABORTED'
896 printStackTrace(e)
897 } catch (e) {
898 sequenceSummary['nested_result'] = 'FAILURE'
899 printStackTrace(e)
900 }
901 sequenceSummary['nested_steps_data'] = nested_steps_data
902 }
903 else
904 {
905 // No parameters were provided to iterate
906 common.errorMsg("${prefixMsg} No parameters were provided to iterate, skipping 'sequence' step")
907 sequenceSummary['nested_result'] = 'SUCCESS'
908 }
909
910 return sequenceSummary
911}
912
913
914def checkResult(job_result, build_url, step, failed_jobs) {
915 // Check job result, in case of SUCCESS, move to next step.
916 // In case job has status NOT_BUILT, fail the build or keep going depending on 'ignore_not_built' flag
917 // In other cases check flag ignore_failed, if true ignore any statuses and keep going additionally
918 // if skip_results is not set or set to false fail entrie workflow, otherwise succed.
919 if (job_result != 'SUCCESS') {
920 def ignoreStepResult = false
921 switch (job_result) {
922 // In cases when job was waiting too long in queue or internal job logic allows to skip building,
923 // job may have NOT_BUILT status. In that case ignore_not_built flag can be used not to fail scenario.
924 case "NOT_BUILT":
925 ignoreStepResult = step['ignore_not_built'] ?: false
926 break
927 case "UNSTABLE":
928 ignoreStepResult = step['ignore_unstable'] ?: (step['ignore_failed'] ?: false)
929 if (ignoreStepResult && !step['skip_results'] ?: false) {
930 failed_jobs[build_url] = job_result
931 }
932 break
azvyagintseve012e412024-05-22 16:09:23 +0300933 case "ABORTED":
934 ignoreStepResult = step['ignore_aborted'] ?: (step['ignore_failed'] ?: false)
935 if (ignoreStepResult && !step['skip_results'] ?: false) {
936 failed_jobs[build_url] = job_result
937 }
938 break
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200939 default:
940 ignoreStepResult = step['ignore_failed'] ?: false
941 if (ignoreStepResult && !step['skip_results'] ?: false) {
942 failed_jobs[build_url] = job_result
943 }
944 }
945 if (!ignoreStepResult) {
946 currentBuild.result = job_result
947 error "Job ${build_url} finished with result: ${job_result}"
948 }
949 }
950}
951
Dennis Dmitrievaa0fa742024-03-27 22:38:25 +0200952def runWorkflowStep(global_variables, step, step_id, jobs_data, global_jobs_data, failed_jobs, propagate, artifactoryBaseUrl, artifactoryServer, scriptsLibrary = null, prefixMsg = '', parent_global_variables=null) {
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200953 def common = new com.mirantis.mk.Common()
Tetiana Leontovych8913fa12025-06-24 01:06:47 +0200954 def job_result = ''
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200955
956 def _sep = "\n======================\n"
957 if (step.containsKey('job')) {
958
959 common.printMsg("${_sep}${prefixMsg}Run job ${step['job']} [at ${java.time.LocalDateTime.now()}]${_sep}", "blue")
960 stage("Run job ${step['job']}") {
961
Dennis Dmitrievaa0fa742024-03-27 22:38:25 +0200962 def job_summary = runStep(global_variables, step, propagate, artifactoryBaseUrl, artifactoryServer, parent_global_variables).call()
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300963
AndrewB8505a7f2020-06-05 13:42:08 +0300964 // Update jobs_data for updating description
azvyagintsev0d978152022-01-27 14:01:33 +0200965 jobs_data[step_id]['build_url'] = job_summary['build_url']
966 jobs_data[step_id]['build_id'] = job_summary['build_id']
967 jobs_data[step_id]['status'] = job_summary['job_result']
968 jobs_data[step_id]['duration'] = job_summary['buildDuration']
969 jobs_data[step_id]['desc'] = job_summary['desc']
970 if (job_summary['build_description']) {
971 jobs_data[step_id]['child_desc'] = job_summary['build_description']
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300972 }
Tetiana Leontovych8913fa12025-06-24 01:06:47 +0200973 job_result = job_summary['job_result']
azvyagintsev0d978152022-01-27 14:01:33 +0200974 def build_url = job_summary['build_url']
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200975 common.printMsg("${_sep}${prefixMsg}Job ${build_url} finished with result: ${job_result} [at ${java.time.LocalDateTime.now()}]${_sep}", "blue")
azvyagintsev0d978152022-01-27 14:01:33 +0200976 }
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200977 }
978 else if (step.containsKey('script')) {
979 common.printMsg("${_sep}${prefixMsg}Run script ${step['script']} [at ${java.time.LocalDateTime.now()}]${_sep}", "blue")
980 stage("Run script ${step['script']}") {
981
Dennis Dmitrievaa0fa742024-03-27 22:38:25 +0200982 def scriptResult = runScript(global_variables, step, artifactoryBaseUrl, artifactoryServer, scriptsLibrary, parent_global_variables)
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200983
984 // Use build_url just as an unique key for failed_jobs.
985 // All characters after '#' are 'comment'
986 def build_url = "${env.BUILD_URL}#${step_id}:${step['script']}"
Tetiana Leontovych8913fa12025-06-24 01:06:47 +0200987 job_result = scriptResult['script_result']
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200988 common.printMsg("${_sep}${prefixMsg}Script ${build_url} finished with result: ${job_result} [at ${java.time.LocalDateTime.now()}]${_sep}", "blue")
989
990 jobs_data[step_id]['build_url'] = build_url
991 jobs_data[step_id]['status'] = scriptResult['script_result']
992 jobs_data[step_id]['desc'] = scriptResult['desc']
993 if (scriptResult['build_description']) {
994 jobs_data[step_id]['child_desc'] = scriptResult['build_description']
995 }
996 }
997 }
998 else if (step.containsKey('parallel')) {
999 common.printMsg("${_sep}${prefixMsg}Run steps in parallel [at ${java.time.LocalDateTime.now()}]:${_sep}", "blue")
1000 stage("Run steps in parallel:") {
1001
1002 // Allocate a map to collect nested steps data for updateDescription()
1003 def nested_steps_data = [:]
1004 jobs_data[step_id]['nested_steps_data'] = nested_steps_data
1005
Dennis Dmitrievaa0fa742024-03-27 22:38:25 +02001006 def parallelResult = runParallel(global_variables, step, failed_jobs, global_jobs_data, nested_steps_data, artifactoryBaseUrl, artifactoryServer, scriptsLibrary, prefixMsg, parent_global_variables)
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +02001007
1008 // Use build_url just as an unique key for failed_jobs.
1009 // All characters after '#' are 'comment'
1010 def build_url = "${env.BUILD_URL}#${step_id}"
Tetiana Leontovych8913fa12025-06-24 01:06:47 +02001011 job_result = parallelResult['nested_result']
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +02001012 common.printMsg("${_sep}${prefixMsg}Parallel steps ${build_url} finished with result: ${job_result} [at ${java.time.LocalDateTime.now()}]${_sep}", "blue")
1013
1014 jobs_data[step_id]['build_url'] = build_url
1015 jobs_data[step_id]['status'] = parallelResult['nested_result']
1016 jobs_data[step_id]['desc'] = parallelResult['desc']
1017 if (parallelResult['build_description']) {
1018 jobs_data[step_id]['child_desc'] = parallelResult['build_description']
1019 }
1020 }
1021 }
1022 else if (step.containsKey('sequence')) {
1023 common.printMsg("${_sep}${prefixMsg}Run steps in sequence [at ${java.time.LocalDateTime.now()}]:${_sep}", "blue")
1024 stage("Run steps in sequence:") {
1025
1026 // Allocate a map to collect nested steps data for updateDescription()
1027 def nested_steps_data = [:]
1028 jobs_data[step_id]['nested_steps_data'] = nested_steps_data
1029
Dennis Dmitrievaa0fa742024-03-27 22:38:25 +02001030 def sequenceResult = runSequence(global_variables, step, failed_jobs, global_jobs_data, nested_steps_data, artifactoryBaseUrl, artifactoryServer, scriptsLibrary, prefixMsg, parent_global_variables)
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +02001031
1032 // Use build_url just as an unique key for failed_jobs.
1033 // All characters after '#' are 'comment'
1034 def build_url = "${env.BUILD_URL}#${step_id}"
Tetiana Leontovych8913fa12025-06-24 01:06:47 +02001035 job_result = sequenceResult['nested_result']
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +02001036 common.printMsg("${_sep}${prefixMsg}Sequence steps ${build_url} finished with result: ${job_result} [at ${java.time.LocalDateTime.now()}]${_sep}", "blue")
1037
1038 jobs_data[step_id]['build_url'] = build_url
1039 jobs_data[step_id]['status'] = sequenceResult['nested_result']
1040 jobs_data[step_id]['desc'] = sequenceResult['desc']
1041 if (sequenceResult['build_description']) {
1042 jobs_data[step_id]['child_desc'] = sequenceResult['build_description']
1043 }
1044 }
1045 }
1046
1047 updateDescription(global_jobs_data)
1048
1049 job_result = jobs_data[step_id]['status']
1050 checkResult(job_result, build_url, step, failed_jobs)
1051
1052// return build_url
1053
1054}
1055
1056/**
1057 * Run the workflow or final steps one by one
1058 *
1059 * @param steps List of steps (Jenkins jobs) to execute
1060 * @param global_variables Map where the collected artifact URLs and 'env' objects are stored
1061 * @param failed_jobs Map with failed job names and result statuses, to report it later
1062 * @param jobs_data Map with all job names and result statuses, to showing it in description
1063 * @param step_id Counter for matching step ID with cell ID in description table
1064 * @param propagate Boolean. If false: allows to collect artifacts after job is finished, even with FAILURE status
1065 * If true: immediatelly fails the pipeline. DO NOT USE 'true' with runScenario().
1066 */
Dennis Dmitrievaa0fa742024-03-27 22:38:25 +02001067def runSteps(steps, global_variables, failed_jobs, jobs_data, global_jobs_data, step_id, Boolean propagate = false, artifactoryBaseUrl = '', artifactoryServer = '', scriptsLibrary = null, prefixMsg = '', parent_global_variables=null) {
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +02001068 // Show expected jobs list in description
1069 updateDescription(global_jobs_data)
1070
1071 for (step in steps) {
1072
Dennis Dmitrievaa0fa742024-03-27 22:38:25 +02001073 runWorkflowStep(global_variables, step, step_id, jobs_data, global_jobs_data, failed_jobs, propagate, artifactoryBaseUrl, artifactoryServer, scriptsLibrary, prefixMsg, parent_global_variables)
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +02001074
azvyagintsev75390d92021-04-12 14:20:11 +03001075 // Jump to next ID for updating next job data in description table
1076 step_id++
azvyagintsev0d978152022-01-27 14:01:33 +02001077 }
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +03001078}
1079
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +02001080
1081/**
1082 * Prepare jobs_data for generating the scenario description
1083 */
1084def prepareJobsData(scenario_steps, step_type, jobs_data) {
1085 def list_id = jobs_data.size()
1086
1087 for (step in scenario_steps) {
1088 def display_name = ''
1089 def step_key = ''
1090 def desc = ''
1091
1092 if (step.containsKey('job')) {
1093 display_name = step['job']
1094 step_key = 'job'
1095 }
1096 else if (step.containsKey('script')) {
1097 display_name = step['script']
1098 step_key = 'script'
1099 }
1100 else if (step.containsKey('parallel')) {
1101 display_name = 'Parallel steps'
1102 step_key = 'parallel'
1103 }
1104 else if (step.containsKey('sequence')) {
1105 display_name = 'Sequence steps'
1106 step_key = 'sequence'
1107 }
1108
1109 if (step['description'] != null && step['description'] != 'null' && step['description'].toString() != '') {
1110 desc = (step['description'] ?: '').toString()
1111 }
1112
1113 jobs_data.add([list_id : "$list_id",
1114 type : step_type,
1115 name : "$display_name",
1116 build_url : "0",
1117 build_id : "-",
1118 status : "-",
1119 desc : desc,
1120 child_desc : "",
1121 duration : '-',
1122 step_key : step_key,
1123 together_steps: [],
1124 ])
1125 list_id += 1
1126 }
1127}
1128
1129
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +03001130/**
1131 * Run the workflow scenario
1132 *
1133 * @param scenario: Map with scenario steps.
1134
1135 * There are two keys in the scenario:
1136 * workflow: contains steps to run deploy and test jobs
1137 * finally: contains steps to run report and cleanup jobs
1138 *
1139 * Scenario execution example:
1140 *
1141 * scenario_yaml = """\
1142 * workflow:
1143 * - job: deploy-kaas
1144 * ignore_failed: false
AndrewB8505a7f2020-06-05 13:42:08 +03001145 * description: "Management cluster ${KAAS_VERSION}"
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +03001146 * parameters:
1147 * KAAS_VERSION:
1148 * type: StringParameterValue
1149 * use_variable: KAAS_VERSION
1150 * artifacts:
1151 * KUBECONFIG_ARTIFACT: artifacts/management_kubeconfig
Dennis Dmitrievcae9bca2019-09-19 16:10:03 +03001152 * DEPLOYED_KAAS_VERSION: artifacts/management_version
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +03001153 *
Dennis Dmitriev5f014d82020-04-29 00:00:34 +03001154 * - job: create-child
1155 * inherit_parent_params: true
1156 * ignore_failed: false
1157 * parameters:
1158 * KUBECONFIG_ARTIFACT_URL:
1159 * type: StringParameterValue
1160 * use_variable: KUBECONFIG_ARTIFACT
1161 * KAAS_VERSION:
1162 * type: StringParameterValue
1163 * get_variable_from_url: DEPLOYED_KAAS_VERSION
Dennis Dmitriev6c355be2021-11-09 14:06:56 +02001164 * RELEASE_NAME:
1165 * type: StringParameterValue
1166 * get_variable_from_yaml:
1167 * yaml_url: SI_CONFIG_ARTIFACT
1168 * yaml_key: .clusters[0].release_name
Dennis Dmitrievaa0fa742024-03-27 22:38:25 +02001169 * global_artifacts:
1170 * CHILD_CONFIG_1: artifacts/child_kubeconfig
Dennis Dmitriev5f014d82020-04-29 00:00:34 +03001171 *
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +03001172 * - job: test-kaas-ui
Mykyta Karpina3d775e2020-04-24 14:45:17 +03001173 * ignore_not_built: false
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +03001174 * parameters:
1175 * KUBECONFIG_ARTIFACT_URL:
1176 * type: StringParameterValue
1177 * use_variable: KUBECONFIG_ARTIFACT
Dennis Dmitrievcae9bca2019-09-19 16:10:03 +03001178 * KAAS_VERSION:
1179 * type: StringParameterValue
1180 * get_variable_from_url: DEPLOYED_KAAS_VERSION
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +03001181 * artifacts:
1182 * REPORT_SI_KAAS_UI: artifacts/test_kaas_ui_result.xml
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +03001183 * finally:
1184 * - job: testrail-report
1185 * ignore_failed: true
1186 * parameters:
Dennis Dmitrievce470932019-09-18 18:31:11 +03001187 * KAAS_VERSION:
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +03001188 * type: StringParameterValue
Dennis Dmitrievcae9bca2019-09-19 16:10:03 +03001189 * get_variable_from_url: DEPLOYED_KAAS_VERSION
Dennis Dmitrievce470932019-09-18 18:31:11 +03001190 * REPORTS_LIST:
1191 * type: TextParameterValue
1192 * use_template: |
1193 * REPORT_SI_KAAS_UI: \$REPORT_SI_KAAS_UI
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +03001194 * """
1195 *
1196 * runScenario(scenario)
1197 *
Dennis Dmitriev5f014d82020-04-29 00:00:34 +03001198 * Scenario workflow keys:
1199 *
1200 * job: string. Jenkins job name
1201 * 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 +04001202 * ignore_unstable: bool. if true, keep running the workflow jobs if the job is unstable, but mark the workflow is unstable at finish
azvyagintseve012e412024-05-22 16:09:23 +03001203 * ignore_aborted: bool. if true, keep running the workflow jobs if the job is aborted, but mark the workflow is unstable at finish
Vasyl Saienkoe72b9942021-03-04 10:54:49 +02001204 * 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 +03001205 * 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
1206 * inherit_parent_params: bool. if true, provide all parameters from the parent job to the child job as defaults
1207 * 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 +02001208 * wf_pause_step_before_run: bool. Interactive pause exact step before run.
1209 * wf_pause_step_slack_report_channel: If step paused, send message about it in slack.
1210 * wf_pause_step_timeout: timeout im minutes to wait for manual unpause.
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +03001211 */
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +02001212def runScenario(scenario, slackReportChannel = '', artifactoryBaseUrl = '', Boolean logGlobalVariables = false, artifactoryServer = '', scriptsLibrary = null,
1213 global_variables = null, failed_jobs = null, jobs_data = null) {
1214 def common = new com.mirantis.mk.Common()
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +03001215
Dennis Dmitriev79f3a2d2019-08-09 16:06:00 +03001216 // Clear description before adding new messages
1217 currentBuild.description = ''
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +03001218 // Collect the parameters for the jobs here
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +02001219 if (global_variables == null) {
1220 global_variables = [:]
1221 }
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +03001222 // List of failed jobs to show at the end
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +02001223 if (failed_jobs == null) {
1224 failed_jobs = [:]
1225 }
AndrewB8505a7f2020-06-05 13:42:08 +03001226 // Jobs data to use for wf job build description
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +02001227 if (jobs_data == null) {
1228 jobs_data = []
1229 }
1230 def global_jobs_data = jobs_data
1231
AndrewB8505a7f2020-06-05 13:42:08 +03001232 // Counter for matching step ID with cell ID in description table
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +02001233 def step_id = jobs_data.size()
AndrewB8505a7f2020-06-05 13:42:08 +03001234 // Generate expected list jobs for description
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +02001235 prepareJobsData(scenario['workflow'], 'workflow', jobs_data)
azvyagintsev0d978152022-01-27 14:01:33 +02001236
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +02001237 def pause_step_id = jobs_data.size()
1238 // Generate expected list jobs for description
1239 prepareJobsData(scenario['pause'], 'pause', jobs_data)
Sergey Lalov702384d2022-11-10 12:10:23 +04001240
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +02001241 def finally_step_id = jobs_data.size()
1242 // Generate expected list jobs for description
1243 prepareJobsData(scenario['finally'], 'finally', jobs_data)
1244
1245
Sergey Lalov702384d2022-11-10 12:10:23 +04001246 def job_failed_flag = false
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +03001247 try {
1248 // Run the 'workflow' jobs
Dennis Dmitrievaa0fa742024-03-27 22:38:25 +02001249 runSteps(scenario['workflow'], global_variables, failed_jobs, jobs_data, global_jobs_data, step_id, false, artifactoryBaseUrl, artifactoryServer, scriptsLibrary, '', global_variables)
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +02001250 } catch (InterruptedException e) {
Sergey Lalov702384d2022-11-10 12:10:23 +04001251 job_failed_flag = true
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +03001252 error "The job was aborted"
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +03001253 } catch (e) {
Sergey Lalov702384d2022-11-10 12:10:23 +04001254 job_failed_flag = true
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +02001255 printStackTrace(e)
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +03001256 error("Build failed: " + e.toString())
Sergey Lalov702384d2022-11-10 12:10:23 +04001257
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +03001258 } finally {
Dennis Dmitriev38a45cd2023-02-27 14:22:13 +02001259 // Log global_variables
1260 if (logGlobalVariables) {
1261 printVariables(global_variables)
1262 }
1263
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +02001264 def flag_pause_variable = (env.PAUSE_FOR_DEBUG) != null
Sergey Lalov702384d2022-11-10 12:10:23 +04001265 // Run the 'finally' or 'pause' jobs
Sergey Lalov6e9400c2022-11-17 12:59:31 +04001266 common.infoMsg(failed_jobs)
Sergey Lalov2d1cd9c2023-08-03 17:08:09 +04001267 // Run only if there are failed jobs in the scenario
1268 if (flag_pause_variable && (PAUSE_FOR_DEBUG && job_failed_flag)) {
Sergey Lalov702384d2022-11-10 12:10:23 +04001269 // Switching to 'pause' step index
1270 common.infoMsg("FINALLY BLOCK - PAUSE")
1271 step_id = pause_step_id
Dennis Dmitrievaa0fa742024-03-27 22:38:25 +02001272 runSteps(scenario['pause'], global_variables, failed_jobs, jobs_data, global_jobs_data, step_id, false, artifactoryBaseUrl, artifactoryServer, scriptsLibrary, '', global_variables)
Sergey Lalov702384d2022-11-10 12:10:23 +04001273
1274 }
1275 // Switching to 'finally' step index
1276 common.infoMsg("FINALLY BLOCK - CLEAR")
AndrewB8505a7f2020-06-05 13:42:08 +03001277 step_id = finally_step_id
Dennis Dmitrievaa0fa742024-03-27 22:38:25 +02001278 runSteps(scenario['finally'], global_variables, failed_jobs, jobs_data, global_jobs_data, step_id, false, artifactoryBaseUrl, artifactoryServer, scriptsLibrary, '', global_variables)
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +03001279
1280 if (failed_jobs) {
azvyagintsev0d978152022-01-27 14:01:33 +02001281 def statuses = []
sgudz9ac09d22020-01-22 14:31:30 +02001282 failed_jobs.each {
sgudz74c8cdd2020-01-23 14:26:32 +02001283 statuses += it.value
azvyagintsev75390d92021-04-12 14:20:11 +03001284 }
sgudz9ac09d22020-01-22 14:31:30 +02001285 if (statuses.contains('FAILURE')) {
1286 currentBuild.result = 'FAILURE'
Sergey Lalove5e0a842023-10-02 15:55:59 +04001287 } else if (statuses.contains('ABORTED')) {
1288 currentBuild.result = 'ABORTED'
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +02001289 } else if (statuses.contains('UNSTABLE')) {
sgudz9ac09d22020-01-22 14:31:30 +02001290 currentBuild.result = 'UNSTABLE'
azvyagintsev75390d92021-04-12 14:20:11 +03001291 } else {
sgudz9ac09d22020-01-22 14:31:30 +02001292 currentBuild.result = 'FAILURE'
1293 }
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +03001294 println "Failed jobs: ${failed_jobs}"
vnaumov68cba272020-05-20 11:24:02 +02001295 } else {
1296 currentBuild.result = 'SUCCESS'
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +03001297 }
vnaumov5a6eb8a2020-03-31 11:16:54 +02001298
Sergey Lalov3a2e7902023-07-27 01:19:02 +04001299 common.infoMsg("Workflow finished with result: ${currentBuild.result}")
1300
vnaumov5a6eb8a2020-03-31 11:16:54 +02001301 if (slackReportChannel) {
1302 def slack = new com.mirantis.mcp.SlackNotification()
1303 slack.jobResultNotification(currentBuild.result, slackReportChannel, '', null, '', 'slack_webhook_url')
1304 }
sgudz9ac09d22020-01-22 14:31:30 +02001305 } // finally
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +03001306}
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +02001307
1308
1309def manageArtifacts(entrypointDirectory, storeArtsInJenkins = false, artifactoryServerName = 'mcp-ci') {
1310 def mcpArtifactory = new com.mirantis.mcp.MCPArtifactory()
1311 def artifactoryRepoPath = "si-local/jenkins-job-artifacts/${JOB_NAME}/${BUILD_NUMBER}"
1312 def tests_log = "${entrypointDirectory}/tests.log"
Tetiana Leontovych8913fa12025-06-24 01:06:47 +02001313 def artConfig = []
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +02001314
1315 if (fileExists(tests_log)) {
1316 try {
1317 def size = sh([returnStdout: true, script: "stat --printf='%s' ${tests_log}"]).trim().toInteger()
1318 // do not archive unless it is more than 50 MB
1319 def allowed_size = 1048576 * 50
1320 if (size >= allowed_size) {
1321 sh("gzip ${tests_log} || true")
1322 }
1323 } catch (e) {
1324 print("Cannot determine tests.log filesize: ${e}")
1325 }
1326 }
1327
1328 if (storeArtsInJenkins) {
1329 archiveArtifacts(
1330 artifacts: "${entrypointDirectory}/**",
1331 allowEmptyArchive: true
1332 )
1333 }
1334 artConfig = [
1335 deleteArtifacts: false,
1336 artifactory : artifactoryServerName,
1337 artifactPattern: "${entrypointDirectory}/**",
1338 artifactoryRepo: "artifactory/${artifactoryRepoPath}",
1339 ]
1340 def artDescription = mcpArtifactory.uploadArtifactsToArtifactory(artConfig)
Vasyl Saienkoc0c029e2024-10-03 09:24:23 +03001341 if (currentBuild.description) {
1342 currentBuild.description += "${artDescription}<br>"
1343 } else {
1344 currentBuild.description = "${artDescription}<br>"
1345 }
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +02001346
1347 junit(testResults: "${entrypointDirectory}/**/*.xml", allowEmptyResults: true)
1348
1349 def artifactoryServer = Artifactory.server(artifactoryServerName)
1350 def artifactsUrl = "${artifactoryServer.getUrl()}/artifactory/${artifactoryRepoPath}"
1351 return artifactsUrl
1352}
1353
1354
1355return this