blob: 56387c9b694cbcc7408b3ba9bb5d5962ef51ce2a [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}")
274 common.infoMsg("For debug pin use:\n'${fullTaskName}' : ${jobOverrideID}")
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200275 return Jenkins.instance.getItemByFullName(job_name, hudson.model.Job).getBuildByNumber(jobOverrideID.toInteger())
azvyagintsev061179d2021-05-05 16:52:18 +0300276 } else {
277 return runJob(job_name, job_parameters, global_variables, propagate)
278 }
279}
280
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300281/**
282 * Store URLs of the specified artifacts to the global_variables
283 *
Andrii Baraniukcf4c2fa2023-04-18 13:53:32 +0300284 * @param build_url URL of the completed job
285 * @param step_artifacts Map that contains artifact names in the job, and variable names
286 * where the URLs to that atrifacts should be stored, for example:
287 * {'ARTIFACT1': 'logs.tar.gz', 'ARTIFACT2': 'test_report.xml', ...}
288 * @param global_variables Map that will keep the artifact URLs. Variable 'ARTIFACT1', for example,
289 * be used in next job parameters: {'ARTIFACT1_URL':{ 'use_variable': 'ARTIFACT1', ...}}
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300290 *
Andrii Baraniukcf4c2fa2023-04-18 13:53:32 +0300291 * If the artifact with the specified name not found, the parameter ARTIFACT1_URL
292 * will be empty.
293 * @param artifactory_server Artifactory server ID defined in Jenkins config
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300294 *
295 */
Dennis Dmitrievaa0fa742024-03-27 22:38:25 +0200296def 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 +0300297 def common = new com.mirantis.mk.Common()
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300298 def http = new com.mirantis.mk.Http()
Andrii Baraniukcf4c2fa2023-04-18 13:53:32 +0300299 def artifactory = new com.mirantis.mcp.MCPArtifactory()
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200300 if (!artifactory_url && !artifactory_server) {
Andrii Baraniukcf4c2fa2023-04-18 13:53:32 +0300301 artifactory_url = 'https://artifactory.mcp.mirantis.net/artifactory/api/storage/si-local/jenkins-job-artifacts'
302 } else if (!artifactory_url && artifactory_server) {
303 artifactory_url = artifactory.getArtifactoryServer(artifactory_server).getUrl() + '/artifactory/api/storage/si-local/jenkins-job-artifacts'
Aleksey Zvyagintsev25ed4a52021-05-12 14:35:03 +0000304 }
Andrii Baraniukcf4c2fa2023-04-18 13:53:32 +0300305
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300306 def baseJenkins = [:]
307 def baseArtifactory = [:]
308 build_url = build_url.replaceAll(~/\/+$/, "")
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300309 baseArtifactory["url"] = artifactory_url + "/${job_name}/${build_num}"
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300310 baseJenkins["url"] = build_url
311 def job_config = http.restGet(baseJenkins, "/api/json/")
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300312 def job_artifacts = job_config['artifacts']
Dennis Dmitrievaa0fa742024-03-27 22:38:25 +0200313 common.infoMsg("Attempt to store ${artifacts_msg} for: ${job_name}/${build_num}")
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300314 for (artifact in step_artifacts) {
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300315 try {
azvyagintsev0d978152022-01-27 14:01:33 +0200316 def artifactoryResp = http.restGet(baseArtifactory, "/${artifact.value}")
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300317 global_variables[artifact.key] = artifactoryResp.downloadUri
azvyagintsev0d978152022-01-27 14:01:33 +0200318 common.infoMsg("Artifact URL ${artifactoryResp.downloadUri} stored to ${artifact.key}")
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300319 continue
320 } catch (Exception e) {
azvyagintsev0d978152022-01-27 14:01:33 +0200321 common.warningMsg("Can't find an artifact in ${artifactory_url}/${job_name}/${build_num}/${artifact.value} to store in ${artifact.key}\n" +
322 "error code ${e.message}")
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300323 }
324
azvyagintsev0d978152022-01-27 14:01:33 +0200325 def job_artifact = job_artifacts.findAll { item -> artifact.value == item['fileName'] || artifact.value == item['relativePath'] }
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300326 if (job_artifact.size() == 1) {
327 // Store artifact URL
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300328 def artifact_url = "${build_url}/artifact/${job_artifact[0]['relativePath']}"
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300329 global_variables[artifact.key] = artifact_url
azvyagintsev0d978152022-01-27 14:01:33 +0200330 common.infoMsg("Artifact URL ${artifact_url} stored to ${artifact.key}")
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300331 } else if (job_artifact.size() > 1) {
332 // Error: too many artifacts with the same name, fail the job
333 error "Multiple artifacts ${artifact.value} for ${artifact.key} found in the build results ${build_url}, expected one:\n${job_artifact}"
334 } else {
335 // Warning: no artifact with expected name
azvyagintsev0d978152022-01-27 14:01:33 +0200336 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 +0300337 global_variables[artifact.key] = ''
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300338 }
339 }
340}
341
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200342
343def getStatusStyle(status) {
344 // Styling the status of job result
345 def status_style = ''
346 switch (status) {
347 case "SUCCESS":
348 status_style = "<td style='color: green;'><img src='/images/16x16/blue.png' alt='SUCCESS'>"
349 break
350 case "UNSTABLE":
351 status_style = "<td style='color: #FF5733;'><img src='/images/16x16/yellow.png' alt='UNSTABLE'>"
352 break
353 case "ABORTED":
354 status_style = "<td style='color: red;'><img src='/images/16x16/aborted.png' alt='ABORTED'>"
355 break
356 case "NOT_BUILT":
357 status_style = "<td style='color: red;'><img src='/images/16x16/aborted.png' alt='NOT_BUILT'>"
358 break
359 case "FAILURE":
360 status_style = "<td style='color: red;'><img src='/images/16x16/red.png' alt='FAILURE'>"
361 break
362 default:
363 status_style = "<td>-"
364 }
365 return status_style
366}
367
368
369def getTrStyle(jobdata) {
370 def trstyle = "<tr>"
371 // Grey background for 'finally' jobs in list
372 if (jobdata.getOrDefault('type', '') == 'finally') {
373 trstyle = "<tr style='background: #DDDDDD;'>"
374 }
375 return trstyle
376}
377
378
AndrewB8505a7f2020-06-05 13:42:08 +0300379/**
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200380 * Update a 'job' step description
AndrewB8505a7f2020-06-05 13:42:08 +0300381 *
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200382 * @param jobsdata Map with a 'job' step details and status
AndrewB8505a7f2020-06-05 13:42:08 +0300383 */
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200384def getJobDescription(jobdata) {
385 def trstyle = getTrStyle(jobdata)
386 def display_name = jobdata['desc'] ? "${jobdata['desc']}: ${jobdata['build_id']}" : "${jobdata['name']}: ${jobdata['build_id']}"
387 if ((env.WF_SHOW_FULL_WORKFLOW_DESCRIPTION ?: false).toBoolean()) {
388 display_name = "[${jobdata['name']}/${jobdata['build_id']}]: ${jobdata['desc']}"
389 }
AndrewB8505a7f2020-06-05 13:42:08 +0300390
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200391 // Attach url for already built jobs
392 def build_url = display_name
393 if (jobdata['build_url'] != "0") {
394 build_url = "<a href=${jobdata['build_url']}>$display_name</a>"
395 }
396
397 def status_style = getStatusStyle(jobdata['status'].toString())
398
399 return [[trstyle, build_url, jobdata['duration'], status_style,],]
400}
401
402
403/**
404 * Update a 'script' step description
405 *
406 * @param jobsdata Map with a 'script' step details and status
407 */
408def getScriptDescription(jobdata) {
409 def trstyle = getTrStyle(jobdata)
410
411 def display_name = "${jobdata['desc']}" ?: "${jobdata['name']}"
412 if ((env.WF_SHOW_FULL_WORKFLOW_DESCRIPTION ?: false).toBoolean()) {
413 display_name = "[${jobdata['name']}]: ${jobdata['desc']}"
414 }
415
416 // Attach url for already built jobs
417 def build_url = display_name
418 if (jobdata['build_url'] != "0") {
419 build_url = "<a href=${jobdata['build_url']}>$display_name</a>"
420 }
421
422 def status_style = getStatusStyle(jobdata['status'].toString())
423
424 return [[trstyle, build_url, jobdata['duration'], status_style,],]
425}
426
427
428/**
429 * Update a 'parallel' or a 'sequence' step description
430 *
431 * @param jobsdata Map with a 'together' step details and statuses
432 */
433def getNestedDescription(jobdata) {
434 def tableEntries = []
435 def trstyle = getTrStyle(jobdata)
Tetiana Leontovych20fc4b22025-06-24 20:26:51 +0200436 def nestedTableEntries = []
437 def nested_trstyle = ''
438 def nested_display_name = ''
439 def nested_duration = ''
440 def nested_status_style = ''
441 def _other_data = ''
442
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200443
444 def display_name = "${jobdata['desc']}" ?: "${jobdata['name']}"
445 if ((env.WF_SHOW_FULL_WORKFLOW_DESCRIPTION ?: false).toBoolean()) {
446 display_name = "[${jobdata['name']}]: ${jobdata['desc']}"
447 }
448
449 // Attach url for already built jobs
450 def build_url = display_name
451 if (jobdata['build_url'] != "0") {
452 build_url = "<a href=${jobdata['build_url']}>$display_name</a>"
453 }
454
455 def status_style = getStatusStyle(jobdata['status'].toString())
456
457 tableEntries += [[trstyle, build_url, jobdata['duration'], status_style,],]
458
459 // Collect nested job descriptions
460 for (nested_jobdata in jobdata['nested_steps_data']) {
Tetiana Leontovych20fc4b22025-06-24 20:26:51 +0200461 (nestedTableEntries, _other_data) = getStepDescription(nested_jobdata.value)
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200462 for (nestedTableEntry in nestedTableEntries) {
463 (nested_trstyle, nested_display_name, nested_duration, nested_status_style) = nestedTableEntry
464 tableEntries += [[nested_trstyle, "&emsp;| ${nested_jobdata.key}: ${nested_display_name}", nested_duration, nested_status_style,],]
465 }
466 }
467 return tableEntries
468}
469
470
471def getStepDescription(jobs_data) {
472 def tableEntries = []
473 def child_jobs_description = ''
AndrewB8505a7f2020-06-05 13:42:08 +0300474 for (jobdata in jobs_data) {
AndrewB8505a7f2020-06-05 13:42:08 +0300475
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200476 if (jobdata['step_key'] == 'job') {
477 tableEntries += getJobDescription(jobdata)
AndrewB8505a7f2020-06-05 13:42:08 +0300478 }
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200479 else if (jobdata['step_key'] == 'script') {
480 tableEntries += getScriptDescription(jobdata)
AndrewB8505a7f2020-06-05 13:42:08 +0300481 }
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200482 else if (jobdata['step_key'] == 'parallel' || jobdata['step_key'] == 'sequence') {
483 tableEntries += getNestedDescription(jobdata)
484 }
AndrewB8505a7f2020-06-05 13:42:08 +0300485
486 // Collecting descriptions of builded child jobs
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200487 if (jobdata['child_desc'] != '') {
AndrewB8505a7f2020-06-05 13:42:08 +0300488 child_jobs_description += "<b><small><a href=${jobdata['build_url']}>- ${jobdata['name']} (${jobdata['status']}):</a></small></b><br>"
azvyagintsev0d978152022-01-27 14:01:33 +0200489 // remove "null" message-result from description, but leave XXX:JOBRESULT in description
azvyagintsev8b8224d2023-10-06 20:52:26 +0300490 if (jobdata['child_desc'] != 'null') {
azvyagintsev0d978152022-01-27 14:01:33 +0200491 child_jobs_description += "<small>${jobdata['child_desc']}</small><br>"
492 }
AndrewB8505a7f2020-06-05 13:42:08 +0300493 }
494 }
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200495 return [tableEntries, child_jobs_description]
496}
497
498/**
499 * Update description for workflow steps
500 *
501 * @param jobs_data Map with all step names and result statuses, to showing it in description
502 */
503def updateDescription(jobs_data) {
504 def child_jobs_description = '<strong>Descriptions from jobs:</strong><br>'
505 def table_template_start = "<div><table style='border: solid 1px;'><tr><th>Job:</th><th>Duration:</th><th>Status:</th></tr>"
506 def table_template_end = "</table></div>"
Tetiana Leontovych8913fa12025-06-24 01:06:47 +0200507 def tableEntries = ''
508 def _child_jobs_description = ''
509 def trstyle = ''
510 def display_name = ''
511 def duration = ''
512 def status_style = ''
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200513
514 (tableEntries, _child_jobs_description) = getStepDescription(jobs_data)
515
516 def table = ''
517 for (tableEntry in tableEntries) {
518 // Collect table
519 (trstyle, display_name, duration, status_style) = tableEntry
520 table += "${trstyle}<td>${display_name}</td><td>${duration}</td>${status_style}</td></tr>"
521 }
522
523 child_jobs_description += _child_jobs_description
524
AndrewB8505a7f2020-06-05 13:42:08 +0300525 currentBuild.description = table_template_start + table + table_template_end + child_jobs_description
526}
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300527
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200528
Dennis Dmitrievaa0fa742024-03-27 22:38:25 +0200529def runStep(global_variables, step, Boolean propagate = false, artifactoryBaseUrl = '', artifactoryServer = '', parent_global_variables=null) {
azvyagintsev0d978152022-01-27 14:01:33 +0200530 return {
531 def common = new com.mirantis.mk.Common()
532 def engine = new groovy.text.GStringTemplateEngine()
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200533 def env_variables = common.getEnvAsMap()
Tetiana Leontovych8913fa12025-06-24 01:06:47 +0200534 def artifacts_msg = ''
azvyagintsev0d978152022-01-27 14:01:33 +0200535
536 String jobDescription = step['description'] ?: ''
537 def jobName = step['job']
538 def jobParameters = [:]
539 def stepParameters = step['parameters'] ?: [:]
540 if (step['inherit_parent_params'] ?: false) {
541 // add parameters from the current job for the child job
542 jobParameters << getJobDefaultParameters(env.JOB_NAME)
543 }
544 // add parameters from the workflow for the child job
545 jobParameters << stepParameters
546 def wfPauseStepBeforeRun = (step['wf_pause_step_before_run'] ?: false).toBoolean()
547 def wfPauseStepTimeout = (step['wf_pause_step_timeout'] ?: 10).toInteger()
548 def wfPauseStepSlackReportChannel = step['wf_pause_step_slack_report_channel'] ?: ''
549
550 if (wfPauseStepBeforeRun) {
551 // Try-catch construction will allow to continue Steps, if timeout reached
552 try {
553 if (wfPauseStepSlackReportChannel) {
554 def slack = new com.mirantis.mcp.SlackNotification()
azvyagintsevda22aa82022-06-10 15:46:55 +0300555 wfPauseStepSlackReportChannel.split(',').each {
556 slack.jobResultNotification('wf_pause_step_before_run',
557 it.toString(),
558 env.JOB_NAME, null,
559 env.BUILD_URL, 'slack_webhook_url')
560 }
azvyagintsev0d978152022-01-27 14:01:33 +0200561 }
562 timeout(time: wfPauseStepTimeout, unit: 'MINUTES') {
563 input("Workflow pause requested before run: ${jobName}/${jobDescription}\n" +
564 "Timeout set to ${wfPauseStepTimeout}.\n" +
565 "Do you want to proceed workflow?")
566 }
567 } catch (err) { // timeout reached or input false
Sergey Lalova89e16a2024-10-17 20:26:44 +0400568 def cause = err.getCauses().get(0)
569 if (cause instanceof org.jenkinsci.plugins.workflow.steps.TimeoutStepExecution.ExceededTimeout) {
azvyagintsev0d978152022-01-27 14:01:33 +0200570 common.infoMsg("Timeout finished, continue..")
Sergey Lalova89e16a2024-10-17 20:26:44 +0400571 } else {
572 def user = causes[0].getUser()
573 error("Aborted after workflow pause by: [${user}]")
azvyagintsev0d978152022-01-27 14:01:33 +0200574 }
575 }
576 }
577 common.infoMsg("Attempt to run: ${jobName}/${jobDescription}")
578 // Collect job parameters and run the job
579 // WARN(alexz): desc must not contain invalid chars for yaml
580 def jobResult = runOrGetJob(jobName, jobParameters,
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200581 global_variables, propagate, jobDescription)
azvyagintsev0d978152022-01-27 14:01:33 +0200582 def buildDuration = jobResult.durationString ?: '-'
583 if (buildDuration.toString() == null) {
584 buildDuration = '-'
585 }
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200586 def desc = engine.createTemplate(jobDescription.toString()).make(env_variables + global_variables)
587 if ((desc.toString() == '') || (desc.toString() == 'null')) {
588 desc = ''
589 }
azvyagintsev0d978152022-01-27 14:01:33 +0200590 def jobSummary = [
591 job_result : jobResult.getResult().toString(),
592 build_url : jobResult.getAbsoluteUrl().toString(),
593 build_id : jobResult.getId().toString(),
594 buildDuration : buildDuration,
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200595 desc : desc,
azvyagintsev0d978152022-01-27 14:01:33 +0200596 ]
597 def _buildDescription = jobResult.getDescription().toString()
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200598 if (_buildDescription) {
azvyagintsev0d978152022-01-27 14:01:33 +0200599 jobSummary['build_description'] = _buildDescription
600 }
601 // Store links to the resulting artifacts into 'global_variables'
602 storeArtifacts(jobSummary['build_url'], step['artifacts'],
Dennis Dmitrievaa0fa742024-03-27 22:38:25 +0200603 global_variables, jobName, jobSummary['build_id'], artifactoryBaseUrl, artifactoryServer, artifacts_msg='artifacts to local variables')
604 // Store links to the resulting 'global_artifacts' into 'global_variables'
605 storeArtifacts(jobSummary['build_url'], step['global_artifacts'],
606 global_variables, jobName, jobSummary['build_id'], artifactoryBaseUrl, artifactoryServer, artifacts_msg='global_artifacts to local variables')
607 // Store links to the resulting 'global_artifacts' into 'parent_global_variables'
608 storeArtifacts(jobSummary['build_url'], step['global_artifacts'],
609 parent_global_variables, jobName, jobSummary['build_id'], artifactoryBaseUrl, artifactoryServer, artifacts_msg='global_artifacts to global_variables')
azvyagintsev0d978152022-01-27 14:01:33 +0200610 return jobSummary
611 }
612}
AndrewB8505a7f2020-06-05 13:42:08 +0300613
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200614
Dennis Dmitrievaa0fa742024-03-27 22:38:25 +0200615def runScript(global_variables, step, artifactoryBaseUrl = '', artifactoryServer = '', scriptsLibrary = null, parent_global_variables=null) {
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200616 def common = new com.mirantis.mk.Common()
617 def env_variables = common.getEnvAsMap()
618
619 if (!scriptsLibrary) {
620 error "'scriptsLibrary' argument is not provided to load a script object '${step['script']}' from that library"
621 }
622 // Evaluate the object from it's name, for example: scriptsLibrary.com.mirantis.si.runtime_steps.ParallelMkeMoskUpgradeSequences
623 def scriptObj = scriptsLibrary
624 for (sObj in step['script'].split("\\.")) {
625 scriptObj = scriptObj."$sObj"
626 }
627
628 def script = scriptObj.new()
629
630 def scriptSummary = [
631 job_result : '',
632 desc : step['description'] ?: '',
633 ]
634
635 // prepare 'script_env' from merged 'env' and script step parameters
636 def script_env = env_variables.clone()
Tetiana Leontovych8913fa12025-06-24 01:06:47 +0200637 def artifacts_msg = ''
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200638 def stepParameters = step['parameters'] ?: [:]
639 def script_parameters = generateParameters(stepParameters, global_variables)
640 println "${script_parameters}"
641 for (script_parameter in script_parameters) {
642 common.infoMsg("Updating script env['${script_parameter.name}'] with value: ${script_parameter.value}")
643 script_env[script_parameter.name] = script_parameter.value
644 }
645
646 try {
647 script.main(this, script_env)
648 scriptSummary['script_result'] = 'SUCCESS'
649 } catch (InterruptedException e) {
650 scriptSummary['script_result'] = 'ABORTED'
651 printStackTrace(e)
652 } catch (e) {
653 scriptSummary['script_result'] = 'FAILURE'
654 printStackTrace(e)
655 }
656
Dennis Dmitrievaa0fa742024-03-27 22:38:25 +0200657 // Store links to the resulting 'artifacts' into 'global_variables'
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200658 storeArtifacts(env.BUILD_URL, step['artifacts'],
Dennis Dmitrievaa0fa742024-03-27 22:38:25 +0200659 global_variables, env.JOB_NAME, env.BUILD_NUMBER, artifactoryBaseUrl, artifactoryServer, artifacts_msg='artifacts to local variables')
660 // Store links to the resulting 'global_artifacts' into 'global_variables'
661 storeArtifacts(env.BUILD_URL, step['global_artifacts'],
662 global_variables, env.JOB_NAME, env.BUILD_NUMBER, artifactoryBaseUrl, artifactoryServer, artifacts_msg='global_artifacts to local variables')
663 // Store links to the resulting 'global_artifacts' into 'parent_global_variables'
664 storeArtifacts(env.BUILD_URL, step['global_artifacts'],
665 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 +0200666
667 return scriptSummary
668}
669
670
Dennis Dmitrievaa0fa742024-03-27 22:38:25 +0200671def 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 +0200672 // Run the specified steps in parallel
673 // Repeat the steps for each parameters set from 'repeat_with_parameters_from_yaml'
674 // If 'repeat_with_parameters_from_yaml' is not provided, then 'parallel' step will perform just one iteration for a default "- _FOO: _BAR" parameter
675 // If 'repeat_with_parameters_from_yaml' is present, but the specified artifact contains empty list '[]', then 'parallel' step will be skipped
676 // Example:
677 // - parallel:
678 // - job:
679 // - job:
680 // - sequence:
681 // repeat_with_parameters_from_yaml:
682 // type: TextParameterValue
683 // get_variable_from_url: SI_PARALLEL_PARAMETERS
684 // max_concurrent: 2 # how many parallel jobs shold be run at the same time
685 // max_concurrent_interval: 300 # how many seconds should be passed between checking for an available concurrency
686 // check_failed_concurrent: false # stop waiting for available concurrent executors if count of failed jobs >= max_concurrent,
687 // # which means that all available shared resources are occupied by the failed jobs
azvyagintsev8bf15d72024-09-19 14:43:33 +0300688 // 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 +0200689 def common = new com.mirantis.mk.Common()
690
691 def sourceText = ""
692 def defaultSourceText = "- _FOO: _BAR"
693 if (step['repeat_with_parameters_from_yaml']) {
694 def sourceParameter = ["repeat_with_parameters_from_yaml": step['repeat_with_parameters_from_yaml']]
695 for (parameter in generateParameters(sourceParameter, global_variables)) {
696 if (parameter.name == "repeat_with_parameters_from_yaml") {
697 sourceText = parameter.value
698 common.infoMsg("'repeat_with_parameters_from_yaml' is defined, using it as a yaml text:\n${sourceText}")
699 }
700 }
701 }
702 if (!sourceText) {
703 sourceText = defaultSourceText
704 common.warningMsg("'repeat_with_parameters_from_yaml' is not defined. To get one iteration, use default single entry:\n${sourceText}")
705 }
706 def iterateParametersList = readYaml text: sourceText
707 if (!(iterateParametersList instanceof List)) {
708 // Stop the pipeline if there is wrong parameters data type, to not generate parallel jobs for wrong data
709 error "Expected a List in 'repeat_with_parameters_from_yaml' for 'parallel' step, but got:\n${sourceText}"
710 }
711
712 // Limit the maximum steps in parallel at the same time
713 def max_concurrent = (step['max_concurrent'] ?: 100).toInteger()
714 // Sleep for the specified amount of time until a free thread will be available
715 def max_concurrent_interval = (step['max_concurrent_interval'] ?: 600).toInteger()
716 // Check that failed jobs is not >= free executors. if 'true', then don't wait for free executors, fail the parallel step
717 def check_failed_concurrent = (step['check_failed_concurrent'] ?: false).toBoolean()
718
719 def jobs = [:]
azvyagintsev8bf15d72024-09-19 14:43:33 +0300720 jobs.failFast = (step['abort_on_parallel_fail'] ?: false).toBoolean()
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200721 def nested_step_id = 0
722 def free_concurrent = max_concurrent
723 def failed_concurrent = []
724
725 common.printMsg("${prefixMsg} Running parallel steps with the following parameters:\n${iterateParametersList}", "purple")
726
727 for (parameters in iterateParametersList) {
728 for (parallel_step in step['parallel']) {
729 def step_name = "parallel#${nested_step_id}"
730 def nested_step = parallel_step
731 def nested_step_name = step_name
732 def nested_prefix_name = "${prefixMsg}${nested_step_name} | "
733
734 nested_steps_data[step_name] = []
735 prepareJobsData([nested_step,], 'parallel', nested_steps_data[step_name])
736
737 //Copy global variables and merge "parameters" dict into it for the current particular step
738 def nested_global_variables = global_variables.clone()
739 nested_global_variables << parameters
740
741 jobs[step_name] = {
742 // initialRecurrencePeriod in milliseconds
743 waitUntil(initialRecurrencePeriod: 1500, quiet: true) {
744 if (check_failed_concurrent) {
745 if (failed_concurrent.size() >= max_concurrent){
746 common.errorMsg("Failed jobs count is equal max_concurrent value ${max_concurrent}. Will not continue because resources are consumed")
747 error("max_concurrent == failed_concurrent")
748 }
749 }
750 if (free_concurrent > 0) {
751 free_concurrent--
752 true
753 } else {
754 sleep(max_concurrent_interval)
755 false
756 }
757 }
758
759 try {
Dennis Dmitrievaa0fa742024-03-27 22:38:25 +0200760 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 +0200761 }
762 catch (e) {
763 failed_concurrent.add(step_name)
764 throw(e)
765 }
766
767 free_concurrent++
768 } // 'jobs' closure
769
770 nested_step_id++
771 }
772 }
773
774 def parallelSummary = [
775 nested_result : '',
776 desc : step['description'] ?: '',
777 nested_steps_data : [:],
778 ]
779
780 if (iterateParametersList) {
781 // Run parallel iterations
782 try {
783 common.infoMsg("${prefixMsg} Run steps in parallel")
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200784 parallel jobs
785
786 parallelSummary['nested_result'] = 'SUCCESS'
787 } catch (InterruptedException e) {
788 parallelSummary['nested_result'] = 'ABORTED'
789 printStackTrace(e)
790 } catch (e) {
791 parallelSummary['nested_result'] = 'FAILURE'
792 printStackTrace(e)
793 }
794 parallelSummary['nested_steps_data'] = nested_steps_data
795 }
796 else
797 {
798 // No parameters were provided to iterate
799 common.errorMsg("${prefixMsg} No parameters were provided to iterate, skipping 'parallel' step")
800 parallelSummary['nested_result'] = 'SUCCESS'
801 }
802 return parallelSummary
803}
804
805
Dennis Dmitrievaa0fa742024-03-27 22:38:25 +0200806def 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 +0200807 // 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'
808 // If 'repeat_with_parameters_from_yaml' is not provided, then 'sequence' step will perform just one iteration for a default "- _FOO: _BAR" parameter
809 // If 'repeat_with_parameters_from_yaml' is present, but the specified artifact contains empty list '[]', then 'sequence' step will be skipped
810 // - sequence:
811 // - job:
812 // - job:
813 // - script:
814 // repeat_with_parameters_from_yaml:
815 // type: TextParameterValue
816 // get_variable_from_url: SI_PARALLEL_PARAMETERS
817 def common = new com.mirantis.mk.Common()
818
819 def sourceText = ""
820 def defaultSourceText = "- _FOO: _BAR"
821 if (step['repeat_with_parameters_from_yaml']) {
822 def sourceParameter = ["repeat_with_parameters_from_yaml": step['repeat_with_parameters_from_yaml']]
823 for (parameter in generateParameters(sourceParameter, global_variables)) {
824 if (parameter.name == "repeat_with_parameters_from_yaml") {
825 sourceText = parameter.value
826 common.infoMsg("'repeat_with_parameters_from_yaml' is defined, using it as a yaml text:\n${sourceText}")
827 }
828 }
829 }
830 if (!sourceText) {
831 sourceText = defaultSourceText
832 common.warningMsg("'repeat_with_parameters_from_yaml' is not defined. To get one iteration, use default single entry:\n${sourceText}")
833 }
834 def iterateParametersList = readYaml text: sourceText
835 if (!(iterateParametersList instanceof List)) {
836 // Stop the pipeline if there is wrong parameters data type, to not generate parallel jobs for wrong data
837 error "Expected a List in 'repeat_with_parameters_from_yaml' for 'sequence' step, but got:\n${sourceText}"
838 }
839
840 def jobs = [:]
841 def nested_step_id = 0
842
843 common.printMsg("${prefixMsg} Running parallel steps with the following parameters:\n${iterateParametersList}", "purple")
844
845 for (parameters in iterateParametersList) {
846 def step_name = "sequence#${nested_step_id}"
847 def nested_steps = step['sequence']
848 def nested_step_name = step_name
849 def nested_prefix_name = "${prefixMsg}${nested_step_name} | "
850
851 nested_steps_data[step_name] = []
852 prepareJobsData(nested_steps, 'sequence', nested_steps_data[step_name])
853
854 //Copy global variables and merge "parameters" dict into it for the current particular step
855 def nested_global_variables = global_variables.clone()
856 nested_global_variables << parameters
857
858 jobs[step_name] = {
859
Dennis Dmitrievaa0fa742024-03-27 22:38:25 +0200860 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 +0200861
862 } // 'jobs' closure
863
864 nested_step_id++
865 }
866
867 def sequenceSummary = [
868 nested_result : '',
869 desc : step['description'] ?: '',
870 nested_steps_data : [:],
871 ]
872
873 if (iterateParametersList) {
874 // Run sequence iterations
875 try {
876 jobs.each { stepName, job ->
877 common.infoMsg("${prefixMsg} Running sequence ${stepName}")
878 job()
azvyagintsevd5f05122024-09-21 13:00:16 +0300879 // just in case sleep.
880 sleep(5)
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200881 }
882 sequenceSummary['nested_result'] = 'SUCCESS'
883 } catch (InterruptedException e) {
884 sequenceSummary['nested_result'] = 'ABORTED'
885 printStackTrace(e)
886 } catch (e) {
887 sequenceSummary['nested_result'] = 'FAILURE'
888 printStackTrace(e)
889 }
890 sequenceSummary['nested_steps_data'] = nested_steps_data
891 }
892 else
893 {
894 // No parameters were provided to iterate
895 common.errorMsg("${prefixMsg} No parameters were provided to iterate, skipping 'sequence' step")
896 sequenceSummary['nested_result'] = 'SUCCESS'
897 }
898
899 return sequenceSummary
900}
901
902
903def checkResult(job_result, build_url, step, failed_jobs) {
904 // Check job result, in case of SUCCESS, move to next step.
905 // In case job has status NOT_BUILT, fail the build or keep going depending on 'ignore_not_built' flag
906 // In other cases check flag ignore_failed, if true ignore any statuses and keep going additionally
907 // if skip_results is not set or set to false fail entrie workflow, otherwise succed.
908 if (job_result != 'SUCCESS') {
909 def ignoreStepResult = false
910 switch (job_result) {
911 // In cases when job was waiting too long in queue or internal job logic allows to skip building,
912 // job may have NOT_BUILT status. In that case ignore_not_built flag can be used not to fail scenario.
913 case "NOT_BUILT":
914 ignoreStepResult = step['ignore_not_built'] ?: false
915 break
916 case "UNSTABLE":
917 ignoreStepResult = step['ignore_unstable'] ?: (step['ignore_failed'] ?: false)
918 if (ignoreStepResult && !step['skip_results'] ?: false) {
919 failed_jobs[build_url] = job_result
920 }
921 break
azvyagintseve012e412024-05-22 16:09:23 +0300922 case "ABORTED":
923 ignoreStepResult = step['ignore_aborted'] ?: (step['ignore_failed'] ?: false)
924 if (ignoreStepResult && !step['skip_results'] ?: false) {
925 failed_jobs[build_url] = job_result
926 }
927 break
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200928 default:
929 ignoreStepResult = step['ignore_failed'] ?: false
930 if (ignoreStepResult && !step['skip_results'] ?: false) {
931 failed_jobs[build_url] = job_result
932 }
933 }
934 if (!ignoreStepResult) {
935 currentBuild.result = job_result
936 error "Job ${build_url} finished with result: ${job_result}"
937 }
938 }
939}
940
Dennis Dmitrievaa0fa742024-03-27 22:38:25 +0200941def 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 +0200942 def common = new com.mirantis.mk.Common()
Tetiana Leontovych8913fa12025-06-24 01:06:47 +0200943 def job_result = ''
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200944
945 def _sep = "\n======================\n"
946 if (step.containsKey('job')) {
947
948 common.printMsg("${_sep}${prefixMsg}Run job ${step['job']} [at ${java.time.LocalDateTime.now()}]${_sep}", "blue")
949 stage("Run job ${step['job']}") {
950
Dennis Dmitrievaa0fa742024-03-27 22:38:25 +0200951 def job_summary = runStep(global_variables, step, propagate, artifactoryBaseUrl, artifactoryServer, parent_global_variables).call()
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300952
AndrewB8505a7f2020-06-05 13:42:08 +0300953 // Update jobs_data for updating description
azvyagintsev0d978152022-01-27 14:01:33 +0200954 jobs_data[step_id]['build_url'] = job_summary['build_url']
955 jobs_data[step_id]['build_id'] = job_summary['build_id']
956 jobs_data[step_id]['status'] = job_summary['job_result']
957 jobs_data[step_id]['duration'] = job_summary['buildDuration']
958 jobs_data[step_id]['desc'] = job_summary['desc']
959 if (job_summary['build_description']) {
960 jobs_data[step_id]['child_desc'] = job_summary['build_description']
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300961 }
Tetiana Leontovych8913fa12025-06-24 01:06:47 +0200962 job_result = job_summary['job_result']
azvyagintsev0d978152022-01-27 14:01:33 +0200963 def build_url = job_summary['build_url']
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200964 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 +0200965 }
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200966 }
967 else if (step.containsKey('script')) {
968 common.printMsg("${_sep}${prefixMsg}Run script ${step['script']} [at ${java.time.LocalDateTime.now()}]${_sep}", "blue")
969 stage("Run script ${step['script']}") {
970
Dennis Dmitrievaa0fa742024-03-27 22:38:25 +0200971 def scriptResult = runScript(global_variables, step, artifactoryBaseUrl, artifactoryServer, scriptsLibrary, parent_global_variables)
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200972
973 // Use build_url just as an unique key for failed_jobs.
974 // All characters after '#' are 'comment'
975 def build_url = "${env.BUILD_URL}#${step_id}:${step['script']}"
Tetiana Leontovych8913fa12025-06-24 01:06:47 +0200976 job_result = scriptResult['script_result']
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200977 common.printMsg("${_sep}${prefixMsg}Script ${build_url} finished with result: ${job_result} [at ${java.time.LocalDateTime.now()}]${_sep}", "blue")
978
979 jobs_data[step_id]['build_url'] = build_url
980 jobs_data[step_id]['status'] = scriptResult['script_result']
981 jobs_data[step_id]['desc'] = scriptResult['desc']
982 if (scriptResult['build_description']) {
983 jobs_data[step_id]['child_desc'] = scriptResult['build_description']
984 }
985 }
986 }
987 else if (step.containsKey('parallel')) {
988 common.printMsg("${_sep}${prefixMsg}Run steps in parallel [at ${java.time.LocalDateTime.now()}]:${_sep}", "blue")
989 stage("Run steps in parallel:") {
990
991 // Allocate a map to collect nested steps data for updateDescription()
992 def nested_steps_data = [:]
993 jobs_data[step_id]['nested_steps_data'] = nested_steps_data
994
Dennis Dmitrievaa0fa742024-03-27 22:38:25 +0200995 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 +0200996
997 // Use build_url just as an unique key for failed_jobs.
998 // All characters after '#' are 'comment'
999 def build_url = "${env.BUILD_URL}#${step_id}"
Tetiana Leontovych8913fa12025-06-24 01:06:47 +02001000 job_result = parallelResult['nested_result']
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +02001001 common.printMsg("${_sep}${prefixMsg}Parallel steps ${build_url} finished with result: ${job_result} [at ${java.time.LocalDateTime.now()}]${_sep}", "blue")
1002
1003 jobs_data[step_id]['build_url'] = build_url
1004 jobs_data[step_id]['status'] = parallelResult['nested_result']
1005 jobs_data[step_id]['desc'] = parallelResult['desc']
1006 if (parallelResult['build_description']) {
1007 jobs_data[step_id]['child_desc'] = parallelResult['build_description']
1008 }
1009 }
1010 }
1011 else if (step.containsKey('sequence')) {
1012 common.printMsg("${_sep}${prefixMsg}Run steps in sequence [at ${java.time.LocalDateTime.now()}]:${_sep}", "blue")
1013 stage("Run steps in sequence:") {
1014
1015 // Allocate a map to collect nested steps data for updateDescription()
1016 def nested_steps_data = [:]
1017 jobs_data[step_id]['nested_steps_data'] = nested_steps_data
1018
Dennis Dmitrievaa0fa742024-03-27 22:38:25 +02001019 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 +02001020
1021 // Use build_url just as an unique key for failed_jobs.
1022 // All characters after '#' are 'comment'
1023 def build_url = "${env.BUILD_URL}#${step_id}"
Tetiana Leontovych8913fa12025-06-24 01:06:47 +02001024 job_result = sequenceResult['nested_result']
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +02001025 common.printMsg("${_sep}${prefixMsg}Sequence steps ${build_url} finished with result: ${job_result} [at ${java.time.LocalDateTime.now()}]${_sep}", "blue")
1026
1027 jobs_data[step_id]['build_url'] = build_url
1028 jobs_data[step_id]['status'] = sequenceResult['nested_result']
1029 jobs_data[step_id]['desc'] = sequenceResult['desc']
1030 if (sequenceResult['build_description']) {
1031 jobs_data[step_id]['child_desc'] = sequenceResult['build_description']
1032 }
1033 }
1034 }
1035
1036 updateDescription(global_jobs_data)
1037
1038 job_result = jobs_data[step_id]['status']
1039 checkResult(job_result, build_url, step, failed_jobs)
1040
1041// return build_url
1042
1043}
1044
1045/**
1046 * Run the workflow or final steps one by one
1047 *
1048 * @param steps List of steps (Jenkins jobs) to execute
1049 * @param global_variables Map where the collected artifact URLs and 'env' objects are stored
1050 * @param failed_jobs Map with failed job names and result statuses, to report it later
1051 * @param jobs_data Map with all job names and result statuses, to showing it in description
1052 * @param step_id Counter for matching step ID with cell ID in description table
1053 * @param propagate Boolean. If false: allows to collect artifacts after job is finished, even with FAILURE status
1054 * If true: immediatelly fails the pipeline. DO NOT USE 'true' with runScenario().
1055 */
Dennis Dmitrievaa0fa742024-03-27 22:38:25 +02001056def 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 +02001057 // Show expected jobs list in description
1058 updateDescription(global_jobs_data)
1059
1060 for (step in steps) {
1061
Dennis Dmitrievaa0fa742024-03-27 22:38:25 +02001062 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 +02001063
azvyagintsev75390d92021-04-12 14:20:11 +03001064 // Jump to next ID for updating next job data in description table
1065 step_id++
azvyagintsev0d978152022-01-27 14:01:33 +02001066 }
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +03001067}
1068
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +02001069
1070/**
1071 * Prepare jobs_data for generating the scenario description
1072 */
1073def prepareJobsData(scenario_steps, step_type, jobs_data) {
1074 def list_id = jobs_data.size()
1075
1076 for (step in scenario_steps) {
1077 def display_name = ''
1078 def step_key = ''
1079 def desc = ''
1080
1081 if (step.containsKey('job')) {
1082 display_name = step['job']
1083 step_key = 'job'
1084 }
1085 else if (step.containsKey('script')) {
1086 display_name = step['script']
1087 step_key = 'script'
1088 }
1089 else if (step.containsKey('parallel')) {
1090 display_name = 'Parallel steps'
1091 step_key = 'parallel'
1092 }
1093 else if (step.containsKey('sequence')) {
1094 display_name = 'Sequence steps'
1095 step_key = 'sequence'
1096 }
1097
1098 if (step['description'] != null && step['description'] != 'null' && step['description'].toString() != '') {
1099 desc = (step['description'] ?: '').toString()
1100 }
1101
1102 jobs_data.add([list_id : "$list_id",
1103 type : step_type,
1104 name : "$display_name",
1105 build_url : "0",
1106 build_id : "-",
1107 status : "-",
1108 desc : desc,
1109 child_desc : "",
1110 duration : '-',
1111 step_key : step_key,
1112 together_steps: [],
1113 ])
1114 list_id += 1
1115 }
1116}
1117
1118
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +03001119/**
1120 * Run the workflow scenario
1121 *
1122 * @param scenario: Map with scenario steps.
1123
1124 * There are two keys in the scenario:
1125 * workflow: contains steps to run deploy and test jobs
1126 * finally: contains steps to run report and cleanup jobs
1127 *
1128 * Scenario execution example:
1129 *
1130 * scenario_yaml = """\
1131 * workflow:
1132 * - job: deploy-kaas
1133 * ignore_failed: false
AndrewB8505a7f2020-06-05 13:42:08 +03001134 * description: "Management cluster ${KAAS_VERSION}"
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +03001135 * parameters:
1136 * KAAS_VERSION:
1137 * type: StringParameterValue
1138 * use_variable: KAAS_VERSION
1139 * artifacts:
1140 * KUBECONFIG_ARTIFACT: artifacts/management_kubeconfig
Dennis Dmitrievcae9bca2019-09-19 16:10:03 +03001141 * DEPLOYED_KAAS_VERSION: artifacts/management_version
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +03001142 *
Dennis Dmitriev5f014d82020-04-29 00:00:34 +03001143 * - job: create-child
1144 * inherit_parent_params: true
1145 * ignore_failed: false
1146 * parameters:
1147 * KUBECONFIG_ARTIFACT_URL:
1148 * type: StringParameterValue
1149 * use_variable: KUBECONFIG_ARTIFACT
1150 * KAAS_VERSION:
1151 * type: StringParameterValue
1152 * get_variable_from_url: DEPLOYED_KAAS_VERSION
Dennis Dmitriev6c355be2021-11-09 14:06:56 +02001153 * RELEASE_NAME:
1154 * type: StringParameterValue
1155 * get_variable_from_yaml:
1156 * yaml_url: SI_CONFIG_ARTIFACT
1157 * yaml_key: .clusters[0].release_name
Dennis Dmitrievaa0fa742024-03-27 22:38:25 +02001158 * global_artifacts:
1159 * CHILD_CONFIG_1: artifacts/child_kubeconfig
Dennis Dmitriev5f014d82020-04-29 00:00:34 +03001160 *
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +03001161 * - job: test-kaas-ui
Mykyta Karpina3d775e2020-04-24 14:45:17 +03001162 * ignore_not_built: false
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +03001163 * parameters:
1164 * KUBECONFIG_ARTIFACT_URL:
1165 * type: StringParameterValue
1166 * use_variable: KUBECONFIG_ARTIFACT
Dennis Dmitrievcae9bca2019-09-19 16:10:03 +03001167 * KAAS_VERSION:
1168 * type: StringParameterValue
1169 * get_variable_from_url: DEPLOYED_KAAS_VERSION
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +03001170 * artifacts:
1171 * REPORT_SI_KAAS_UI: artifacts/test_kaas_ui_result.xml
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +03001172 * finally:
1173 * - job: testrail-report
1174 * ignore_failed: true
1175 * parameters:
Dennis Dmitrievce470932019-09-18 18:31:11 +03001176 * KAAS_VERSION:
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +03001177 * type: StringParameterValue
Dennis Dmitrievcae9bca2019-09-19 16:10:03 +03001178 * get_variable_from_url: DEPLOYED_KAAS_VERSION
Dennis Dmitrievce470932019-09-18 18:31:11 +03001179 * REPORTS_LIST:
1180 * type: TextParameterValue
1181 * use_template: |
1182 * REPORT_SI_KAAS_UI: \$REPORT_SI_KAAS_UI
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +03001183 * """
1184 *
1185 * runScenario(scenario)
1186 *
Dennis Dmitriev5f014d82020-04-29 00:00:34 +03001187 * Scenario workflow keys:
1188 *
1189 * job: string. Jenkins job name
1190 * 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 +04001191 * 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 +03001192 * 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 +02001193 * 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 +03001194 * 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
1195 * inherit_parent_params: bool. if true, provide all parameters from the parent job to the child job as defaults
1196 * 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 +02001197 * wf_pause_step_before_run: bool. Interactive pause exact step before run.
1198 * wf_pause_step_slack_report_channel: If step paused, send message about it in slack.
1199 * wf_pause_step_timeout: timeout im minutes to wait for manual unpause.
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +03001200 */
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +02001201def runScenario(scenario, slackReportChannel = '', artifactoryBaseUrl = '', Boolean logGlobalVariables = false, artifactoryServer = '', scriptsLibrary = null,
1202 global_variables = null, failed_jobs = null, jobs_data = null) {
1203 def common = new com.mirantis.mk.Common()
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +03001204
Dennis Dmitriev79f3a2d2019-08-09 16:06:00 +03001205 // Clear description before adding new messages
1206 currentBuild.description = ''
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +03001207 // Collect the parameters for the jobs here
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +02001208 if (global_variables == null) {
1209 global_variables = [:]
1210 }
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +03001211 // List of failed jobs to show at the end
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +02001212 if (failed_jobs == null) {
1213 failed_jobs = [:]
1214 }
AndrewB8505a7f2020-06-05 13:42:08 +03001215 // Jobs data to use for wf job build description
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +02001216 if (jobs_data == null) {
1217 jobs_data = []
1218 }
1219 def global_jobs_data = jobs_data
1220
AndrewB8505a7f2020-06-05 13:42:08 +03001221 // Counter for matching step ID with cell ID in description table
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +02001222 def step_id = jobs_data.size()
AndrewB8505a7f2020-06-05 13:42:08 +03001223 // Generate expected list jobs for description
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +02001224 prepareJobsData(scenario['workflow'], 'workflow', jobs_data)
azvyagintsev0d978152022-01-27 14:01:33 +02001225
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +02001226 def pause_step_id = jobs_data.size()
1227 // Generate expected list jobs for description
1228 prepareJobsData(scenario['pause'], 'pause', jobs_data)
Sergey Lalov702384d2022-11-10 12:10:23 +04001229
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +02001230 def finally_step_id = jobs_data.size()
1231 // Generate expected list jobs for description
1232 prepareJobsData(scenario['finally'], 'finally', jobs_data)
1233
1234
Sergey Lalov702384d2022-11-10 12:10:23 +04001235 def job_failed_flag = false
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +03001236 try {
1237 // Run the 'workflow' jobs
Dennis Dmitrievaa0fa742024-03-27 22:38:25 +02001238 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 +02001239 } catch (InterruptedException e) {
Sergey Lalov702384d2022-11-10 12:10:23 +04001240 job_failed_flag = true
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +03001241 error "The job was aborted"
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +03001242 } catch (e) {
Sergey Lalov702384d2022-11-10 12:10:23 +04001243 job_failed_flag = true
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +02001244 printStackTrace(e)
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +03001245 error("Build failed: " + e.toString())
Sergey Lalov702384d2022-11-10 12:10:23 +04001246
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +03001247 } finally {
Dennis Dmitriev38a45cd2023-02-27 14:22:13 +02001248 // Log global_variables
1249 if (logGlobalVariables) {
1250 printVariables(global_variables)
1251 }
1252
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +02001253 def flag_pause_variable = (env.PAUSE_FOR_DEBUG) != null
Sergey Lalov702384d2022-11-10 12:10:23 +04001254 // Run the 'finally' or 'pause' jobs
Sergey Lalov6e9400c2022-11-17 12:59:31 +04001255 common.infoMsg(failed_jobs)
Sergey Lalov2d1cd9c2023-08-03 17:08:09 +04001256 // Run only if there are failed jobs in the scenario
1257 if (flag_pause_variable && (PAUSE_FOR_DEBUG && job_failed_flag)) {
Sergey Lalov702384d2022-11-10 12:10:23 +04001258 // Switching to 'pause' step index
1259 common.infoMsg("FINALLY BLOCK - PAUSE")
1260 step_id = pause_step_id
Dennis Dmitrievaa0fa742024-03-27 22:38:25 +02001261 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 +04001262
1263 }
1264 // Switching to 'finally' step index
1265 common.infoMsg("FINALLY BLOCK - CLEAR")
AndrewB8505a7f2020-06-05 13:42:08 +03001266 step_id = finally_step_id
Dennis Dmitrievaa0fa742024-03-27 22:38:25 +02001267 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 +03001268
1269 if (failed_jobs) {
azvyagintsev0d978152022-01-27 14:01:33 +02001270 def statuses = []
sgudz9ac09d22020-01-22 14:31:30 +02001271 failed_jobs.each {
sgudz74c8cdd2020-01-23 14:26:32 +02001272 statuses += it.value
azvyagintsev75390d92021-04-12 14:20:11 +03001273 }
sgudz9ac09d22020-01-22 14:31:30 +02001274 if (statuses.contains('FAILURE')) {
1275 currentBuild.result = 'FAILURE'
Sergey Lalove5e0a842023-10-02 15:55:59 +04001276 } else if (statuses.contains('ABORTED')) {
1277 currentBuild.result = 'ABORTED'
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +02001278 } else if (statuses.contains('UNSTABLE')) {
sgudz9ac09d22020-01-22 14:31:30 +02001279 currentBuild.result = 'UNSTABLE'
azvyagintsev75390d92021-04-12 14:20:11 +03001280 } else {
sgudz9ac09d22020-01-22 14:31:30 +02001281 currentBuild.result = 'FAILURE'
1282 }
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +03001283 println "Failed jobs: ${failed_jobs}"
vnaumov68cba272020-05-20 11:24:02 +02001284 } else {
1285 currentBuild.result = 'SUCCESS'
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +03001286 }
vnaumov5a6eb8a2020-03-31 11:16:54 +02001287
Sergey Lalov3a2e7902023-07-27 01:19:02 +04001288 common.infoMsg("Workflow finished with result: ${currentBuild.result}")
1289
vnaumov5a6eb8a2020-03-31 11:16:54 +02001290 if (slackReportChannel) {
1291 def slack = new com.mirantis.mcp.SlackNotification()
1292 slack.jobResultNotification(currentBuild.result, slackReportChannel, '', null, '', 'slack_webhook_url')
1293 }
sgudz9ac09d22020-01-22 14:31:30 +02001294 } // finally
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +03001295}
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +02001296
1297
1298def manageArtifacts(entrypointDirectory, storeArtsInJenkins = false, artifactoryServerName = 'mcp-ci') {
1299 def mcpArtifactory = new com.mirantis.mcp.MCPArtifactory()
1300 def artifactoryRepoPath = "si-local/jenkins-job-artifacts/${JOB_NAME}/${BUILD_NUMBER}"
1301 def tests_log = "${entrypointDirectory}/tests.log"
Tetiana Leontovych8913fa12025-06-24 01:06:47 +02001302 def artConfig = []
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +02001303
1304 if (fileExists(tests_log)) {
1305 try {
1306 def size = sh([returnStdout: true, script: "stat --printf='%s' ${tests_log}"]).trim().toInteger()
1307 // do not archive unless it is more than 50 MB
1308 def allowed_size = 1048576 * 50
1309 if (size >= allowed_size) {
1310 sh("gzip ${tests_log} || true")
1311 }
1312 } catch (e) {
1313 print("Cannot determine tests.log filesize: ${e}")
1314 }
1315 }
1316
1317 if (storeArtsInJenkins) {
1318 archiveArtifacts(
1319 artifacts: "${entrypointDirectory}/**",
1320 allowEmptyArchive: true
1321 )
1322 }
1323 artConfig = [
1324 deleteArtifacts: false,
1325 artifactory : artifactoryServerName,
1326 artifactPattern: "${entrypointDirectory}/**",
1327 artifactoryRepo: "artifactory/${artifactoryRepoPath}",
1328 ]
1329 def artDescription = mcpArtifactory.uploadArtifactsToArtifactory(artConfig)
Vasyl Saienkoc0c029e2024-10-03 09:24:23 +03001330 if (currentBuild.description) {
1331 currentBuild.description += "${artDescription}<br>"
1332 } else {
1333 currentBuild.description = "${artDescription}<br>"
1334 }
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +02001335
1336 junit(testResults: "${entrypointDirectory}/**/*.xml", allowEmptyResults: true)
1337
1338 def artifactoryServer = Artifactory.server(artifactoryServerName)
1339 def artifactsUrl = "${artifactoryServer.getUrl()}/artifactory/${artifactoryRepoPath}"
1340 return artifactsUrl
1341}
1342
1343
1344return this