blob: e8f4ba2a3f5b60789081a4e0be286d06150424f9 [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 }
azvyagintseve2e26bb2024-09-24 18:03:59 +0300226 // Inject hidden random parameter (is not showed in jjb) to be sure we are triggering unique downstream job.
227 // Most actual case - parallel run for same jobs( but with different params)
azvyagintsev000556d2025-01-10 13:45:32 +0200228 parameters.add([$class: "StringParameterValue",
229 name : "RANDOM_SEED_STRING",
230 value : "${env.JOB_NAME.toLowerCase()}-${env.BUILD_NUMBER}-${UUID.randomUUID().toString().split('-')[0]}"])
azvyagintsev25015272023-11-28 17:31:18 +0200231 common.infoMsg(_msg)
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200232 return parameters
233}
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300234
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200235
236/**
237 * Run a Jenkins job using the collected parameters
238 *
239 * @param job_name Name of the running job
240 * @param job_parameters Map that declares which values from global_variables should be used
241 * @param global_variables Map that keeps the artifact URLs and used 'env' objects
242 * @param propagate Boolean. If false: allows to collect artifacts after job is finished, even with FAILURE status
243 * If true: immediatelly fails the pipeline. DO NOT USE 'true' if you want to collect artifacts
244 * for 'finally' steps
245 */
246def runJob(job_name, job_parameters, global_variables, Boolean propagate = false) {
247
248 def parameters = generateParameters(job_parameters, global_variables)
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300249 // Build the job
Dennis Dmitrieve09e0292019-07-30 16:39:27 +0300250 def job_info = build job: "${job_name}", parameters: parameters, propagate: propagate
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300251 return job_info
252}
253
azvyagintsev061179d2021-05-05 16:52:18 +0300254def runOrGetJob(job_name, job_parameters, global_variables, propagate, String fullTaskName = '') {
255 /**
256 * Run job directly or try to find already executed build
257 * Flow, in case CI_JOBS_OVERRIDES passed:
258 *
259 *
260 * CI_JOBS_OVERRIDES = text in yaml|json format
261 * CI_JOBS_OVERRIDES = 'kaas-testing-core-release-artifact' : 3505
262 * 'reindex-testing-core-release-index-with-rc' : 2822
263 * 'si-test-release-sanity-check-prepare-configuration': 1877
264 */
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200265 def common = new com.mirantis.mk.Common()
azvyagintsev061179d2021-05-05 16:52:18 +0300266 def jobsOverrides = readYaml(text: env.CI_JOBS_OVERRIDES ?: '---') ?: [:]
267 // get id of overriding job
268 def jobOverrideID = jobsOverrides.getOrDefault(fullTaskName, '')
azvyagintsev061179d2021-05-05 16:52:18 +0300269 if (fullTaskName in jobsOverrides.keySet()) {
270 common.warningMsg("Overriding: ${fullTaskName}/${job_name} <<< ${jobOverrideID}")
271 common.infoMsg("For debug pin use:\n'${fullTaskName}' : ${jobOverrideID}")
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200272 return Jenkins.instance.getItemByFullName(job_name, hudson.model.Job).getBuildByNumber(jobOverrideID.toInteger())
azvyagintsev061179d2021-05-05 16:52:18 +0300273 } else {
274 return runJob(job_name, job_parameters, global_variables, propagate)
275 }
276}
277
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300278/**
279 * Store URLs of the specified artifacts to the global_variables
280 *
Andrii Baraniukcf4c2fa2023-04-18 13:53:32 +0300281 * @param build_url URL of the completed job
282 * @param step_artifacts Map that contains artifact names in the job, and variable names
283 * where the URLs to that atrifacts should be stored, for example:
284 * {'ARTIFACT1': 'logs.tar.gz', 'ARTIFACT2': 'test_report.xml', ...}
285 * @param global_variables Map that will keep the artifact URLs. Variable 'ARTIFACT1', for example,
286 * be used in next job parameters: {'ARTIFACT1_URL':{ 'use_variable': 'ARTIFACT1', ...}}
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300287 *
Andrii Baraniukcf4c2fa2023-04-18 13:53:32 +0300288 * If the artifact with the specified name not found, the parameter ARTIFACT1_URL
289 * will be empty.
290 * @param artifactory_server Artifactory server ID defined in Jenkins config
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300291 *
292 */
Dennis Dmitrievaa0fa742024-03-27 22:38:25 +0200293def 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 +0300294 def common = new com.mirantis.mk.Common()
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300295 def http = new com.mirantis.mk.Http()
Andrii Baraniukcf4c2fa2023-04-18 13:53:32 +0300296 def artifactory = new com.mirantis.mcp.MCPArtifactory()
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200297 if (!artifactory_url && !artifactory_server) {
Andrii Baraniukcf4c2fa2023-04-18 13:53:32 +0300298 artifactory_url = 'https://artifactory.mcp.mirantis.net/artifactory/api/storage/si-local/jenkins-job-artifacts'
299 } else if (!artifactory_url && artifactory_server) {
300 artifactory_url = artifactory.getArtifactoryServer(artifactory_server).getUrl() + '/artifactory/api/storage/si-local/jenkins-job-artifacts'
Aleksey Zvyagintsev25ed4a52021-05-12 14:35:03 +0000301 }
Andrii Baraniukcf4c2fa2023-04-18 13:53:32 +0300302
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300303 def baseJenkins = [:]
304 def baseArtifactory = [:]
305 build_url = build_url.replaceAll(~/\/+$/, "")
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300306 baseArtifactory["url"] = artifactory_url + "/${job_name}/${build_num}"
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300307 baseJenkins["url"] = build_url
308 def job_config = http.restGet(baseJenkins, "/api/json/")
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300309 def job_artifacts = job_config['artifacts']
Dennis Dmitrievaa0fa742024-03-27 22:38:25 +0200310 common.infoMsg("Attempt to store ${artifacts_msg} for: ${job_name}/${build_num}")
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300311 for (artifact in step_artifacts) {
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300312 try {
azvyagintsev0d978152022-01-27 14:01:33 +0200313 def artifactoryResp = http.restGet(baseArtifactory, "/${artifact.value}")
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300314 global_variables[artifact.key] = artifactoryResp.downloadUri
azvyagintsev0d978152022-01-27 14:01:33 +0200315 common.infoMsg("Artifact URL ${artifactoryResp.downloadUri} stored to ${artifact.key}")
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300316 continue
317 } catch (Exception e) {
azvyagintsev0d978152022-01-27 14:01:33 +0200318 common.warningMsg("Can't find an artifact in ${artifactory_url}/${job_name}/${build_num}/${artifact.value} to store in ${artifact.key}\n" +
319 "error code ${e.message}")
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300320 }
321
azvyagintsev0d978152022-01-27 14:01:33 +0200322 def job_artifact = job_artifacts.findAll { item -> artifact.value == item['fileName'] || artifact.value == item['relativePath'] }
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300323 if (job_artifact.size() == 1) {
324 // Store artifact URL
Dmitry Tyzhnenkof446e412020-04-06 13:24:54 +0300325 def artifact_url = "${build_url}/artifact/${job_artifact[0]['relativePath']}"
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300326 global_variables[artifact.key] = artifact_url
azvyagintsev0d978152022-01-27 14:01:33 +0200327 common.infoMsg("Artifact URL ${artifact_url} stored to ${artifact.key}")
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300328 } else if (job_artifact.size() > 1) {
329 // Error: too many artifacts with the same name, fail the job
330 error "Multiple artifacts ${artifact.value} for ${artifact.key} found in the build results ${build_url}, expected one:\n${job_artifact}"
331 } else {
332 // Warning: no artifact with expected name
azvyagintsev0d978152022-01-27 14:01:33 +0200333 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 +0300334 global_variables[artifact.key] = ''
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300335 }
336 }
337}
338
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200339
340def getStatusStyle(status) {
341 // Styling the status of job result
342 def status_style = ''
343 switch (status) {
344 case "SUCCESS":
345 status_style = "<td style='color: green;'><img src='/images/16x16/blue.png' alt='SUCCESS'>"
346 break
347 case "UNSTABLE":
348 status_style = "<td style='color: #FF5733;'><img src='/images/16x16/yellow.png' alt='UNSTABLE'>"
349 break
350 case "ABORTED":
351 status_style = "<td style='color: red;'><img src='/images/16x16/aborted.png' alt='ABORTED'>"
352 break
353 case "NOT_BUILT":
354 status_style = "<td style='color: red;'><img src='/images/16x16/aborted.png' alt='NOT_BUILT'>"
355 break
356 case "FAILURE":
357 status_style = "<td style='color: red;'><img src='/images/16x16/red.png' alt='FAILURE'>"
358 break
359 default:
360 status_style = "<td>-"
361 }
362 return status_style
363}
364
365
366def getTrStyle(jobdata) {
367 def trstyle = "<tr>"
368 // Grey background for 'finally' jobs in list
369 if (jobdata.getOrDefault('type', '') == 'finally') {
370 trstyle = "<tr style='background: #DDDDDD;'>"
371 }
372 return trstyle
373}
374
375
AndrewB8505a7f2020-06-05 13:42:08 +0300376/**
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200377 * Update a 'job' step description
AndrewB8505a7f2020-06-05 13:42:08 +0300378 *
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200379 * @param jobsdata Map with a 'job' step details and status
AndrewB8505a7f2020-06-05 13:42:08 +0300380 */
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200381def getJobDescription(jobdata) {
382 def trstyle = getTrStyle(jobdata)
383 def display_name = jobdata['desc'] ? "${jobdata['desc']}: ${jobdata['build_id']}" : "${jobdata['name']}: ${jobdata['build_id']}"
384 if ((env.WF_SHOW_FULL_WORKFLOW_DESCRIPTION ?: false).toBoolean()) {
385 display_name = "[${jobdata['name']}/${jobdata['build_id']}]: ${jobdata['desc']}"
386 }
AndrewB8505a7f2020-06-05 13:42:08 +0300387
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200388 // Attach url for already built jobs
389 def build_url = display_name
390 if (jobdata['build_url'] != "0") {
391 build_url = "<a href=${jobdata['build_url']}>$display_name</a>"
392 }
393
394 def status_style = getStatusStyle(jobdata['status'].toString())
395
396 return [[trstyle, build_url, jobdata['duration'], status_style,],]
397}
398
399
400/**
401 * Update a 'script' step description
402 *
403 * @param jobsdata Map with a 'script' step details and status
404 */
405def getScriptDescription(jobdata) {
406 def trstyle = getTrStyle(jobdata)
407
408 def display_name = "${jobdata['desc']}" ?: "${jobdata['name']}"
409 if ((env.WF_SHOW_FULL_WORKFLOW_DESCRIPTION ?: false).toBoolean()) {
410 display_name = "[${jobdata['name']}]: ${jobdata['desc']}"
411 }
412
413 // Attach url for already built jobs
414 def build_url = display_name
415 if (jobdata['build_url'] != "0") {
416 build_url = "<a href=${jobdata['build_url']}>$display_name</a>"
417 }
418
419 def status_style = getStatusStyle(jobdata['status'].toString())
420
421 return [[trstyle, build_url, jobdata['duration'], status_style,],]
422}
423
424
425/**
426 * Update a 'parallel' or a 'sequence' step description
427 *
428 * @param jobsdata Map with a 'together' step details and statuses
429 */
430def getNestedDescription(jobdata) {
431 def tableEntries = []
432 def trstyle = getTrStyle(jobdata)
433
434 def display_name = "${jobdata['desc']}" ?: "${jobdata['name']}"
435 if ((env.WF_SHOW_FULL_WORKFLOW_DESCRIPTION ?: false).toBoolean()) {
436 display_name = "[${jobdata['name']}]: ${jobdata['desc']}"
437 }
438
439 // Attach url for already built jobs
440 def build_url = display_name
441 if (jobdata['build_url'] != "0") {
442 build_url = "<a href=${jobdata['build_url']}>$display_name</a>"
443 }
444
445 def status_style = getStatusStyle(jobdata['status'].toString())
446
447 tableEntries += [[trstyle, build_url, jobdata['duration'], status_style,],]
448
449 // Collect nested job descriptions
450 for (nested_jobdata in jobdata['nested_steps_data']) {
451 (nestedTableEntries, _) = getStepDescription(nested_jobdata.value)
452 for (nestedTableEntry in nestedTableEntries) {
453 (nested_trstyle, nested_display_name, nested_duration, nested_status_style) = nestedTableEntry
454 tableEntries += [[nested_trstyle, "&emsp;| ${nested_jobdata.key}: ${nested_display_name}", nested_duration, nested_status_style,],]
455 }
456 }
457 return tableEntries
458}
459
460
461def getStepDescription(jobs_data) {
462 def tableEntries = []
463 def child_jobs_description = ''
AndrewB8505a7f2020-06-05 13:42:08 +0300464 for (jobdata in jobs_data) {
AndrewB8505a7f2020-06-05 13:42:08 +0300465
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200466 if (jobdata['step_key'] == 'job') {
467 tableEntries += getJobDescription(jobdata)
AndrewB8505a7f2020-06-05 13:42:08 +0300468 }
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200469 else if (jobdata['step_key'] == 'script') {
470 tableEntries += getScriptDescription(jobdata)
AndrewB8505a7f2020-06-05 13:42:08 +0300471 }
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200472 else if (jobdata['step_key'] == 'parallel' || jobdata['step_key'] == 'sequence') {
473 tableEntries += getNestedDescription(jobdata)
474 }
AndrewB8505a7f2020-06-05 13:42:08 +0300475
476 // Collecting descriptions of builded child jobs
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200477 if (jobdata['child_desc'] != '') {
AndrewB8505a7f2020-06-05 13:42:08 +0300478 child_jobs_description += "<b><small><a href=${jobdata['build_url']}>- ${jobdata['name']} (${jobdata['status']}):</a></small></b><br>"
azvyagintsev0d978152022-01-27 14:01:33 +0200479 // remove "null" message-result from description, but leave XXX:JOBRESULT in description
azvyagintsev8b8224d2023-10-06 20:52:26 +0300480 if (jobdata['child_desc'] != 'null') {
azvyagintsev0d978152022-01-27 14:01:33 +0200481 child_jobs_description += "<small>${jobdata['child_desc']}</small><br>"
482 }
AndrewB8505a7f2020-06-05 13:42:08 +0300483 }
484 }
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200485 return [tableEntries, child_jobs_description]
486}
487
488/**
489 * Update description for workflow steps
490 *
491 * @param jobs_data Map with all step names and result statuses, to showing it in description
492 */
493def updateDescription(jobs_data) {
494 def child_jobs_description = '<strong>Descriptions from jobs:</strong><br>'
495 def table_template_start = "<div><table style='border: solid 1px;'><tr><th>Job:</th><th>Duration:</th><th>Status:</th></tr>"
496 def table_template_end = "</table></div>"
497
498 (tableEntries, _child_jobs_description) = getStepDescription(jobs_data)
499
500 def table = ''
501 for (tableEntry in tableEntries) {
502 // Collect table
503 (trstyle, display_name, duration, status_style) = tableEntry
504 table += "${trstyle}<td>${display_name}</td><td>${duration}</td>${status_style}</td></tr>"
505 }
506
507 child_jobs_description += _child_jobs_description
508
AndrewB8505a7f2020-06-05 13:42:08 +0300509 currentBuild.description = table_template_start + table + table_template_end + child_jobs_description
510}
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300511
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200512
Dennis Dmitrievaa0fa742024-03-27 22:38:25 +0200513def runStep(global_variables, step, Boolean propagate = false, artifactoryBaseUrl = '', artifactoryServer = '', parent_global_variables=null) {
azvyagintsev0d978152022-01-27 14:01:33 +0200514 return {
515 def common = new com.mirantis.mk.Common()
516 def engine = new groovy.text.GStringTemplateEngine()
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200517 def env_variables = common.getEnvAsMap()
azvyagintsev0d978152022-01-27 14:01:33 +0200518
519 String jobDescription = step['description'] ?: ''
520 def jobName = step['job']
521 def jobParameters = [:]
522 def stepParameters = step['parameters'] ?: [:]
523 if (step['inherit_parent_params'] ?: false) {
524 // add parameters from the current job for the child job
525 jobParameters << getJobDefaultParameters(env.JOB_NAME)
526 }
527 // add parameters from the workflow for the child job
528 jobParameters << stepParameters
529 def wfPauseStepBeforeRun = (step['wf_pause_step_before_run'] ?: false).toBoolean()
530 def wfPauseStepTimeout = (step['wf_pause_step_timeout'] ?: 10).toInteger()
531 def wfPauseStepSlackReportChannel = step['wf_pause_step_slack_report_channel'] ?: ''
532
533 if (wfPauseStepBeforeRun) {
534 // Try-catch construction will allow to continue Steps, if timeout reached
535 try {
536 if (wfPauseStepSlackReportChannel) {
537 def slack = new com.mirantis.mcp.SlackNotification()
azvyagintsevda22aa82022-06-10 15:46:55 +0300538 wfPauseStepSlackReportChannel.split(',').each {
539 slack.jobResultNotification('wf_pause_step_before_run',
540 it.toString(),
541 env.JOB_NAME, null,
542 env.BUILD_URL, 'slack_webhook_url')
543 }
azvyagintsev0d978152022-01-27 14:01:33 +0200544 }
545 timeout(time: wfPauseStepTimeout, unit: 'MINUTES') {
546 input("Workflow pause requested before run: ${jobName}/${jobDescription}\n" +
547 "Timeout set to ${wfPauseStepTimeout}.\n" +
548 "Do you want to proceed workflow?")
549 }
550 } catch (err) { // timeout reached or input false
Sergey Lalova89e16a2024-10-17 20:26:44 +0400551 def cause = err.getCauses().get(0)
552 if (cause instanceof org.jenkinsci.plugins.workflow.steps.TimeoutStepExecution.ExceededTimeout) {
azvyagintsev0d978152022-01-27 14:01:33 +0200553 common.infoMsg("Timeout finished, continue..")
Sergey Lalova89e16a2024-10-17 20:26:44 +0400554 } else {
555 def user = causes[0].getUser()
556 error("Aborted after workflow pause by: [${user}]")
azvyagintsev0d978152022-01-27 14:01:33 +0200557 }
558 }
559 }
560 common.infoMsg("Attempt to run: ${jobName}/${jobDescription}")
561 // Collect job parameters and run the job
562 // WARN(alexz): desc must not contain invalid chars for yaml
563 def jobResult = runOrGetJob(jobName, jobParameters,
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200564 global_variables, propagate, jobDescription)
azvyagintsev0d978152022-01-27 14:01:33 +0200565 def buildDuration = jobResult.durationString ?: '-'
566 if (buildDuration.toString() == null) {
567 buildDuration = '-'
568 }
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200569 def desc = engine.createTemplate(jobDescription.toString()).make(env_variables + global_variables)
570 if ((desc.toString() == '') || (desc.toString() == 'null')) {
571 desc = ''
572 }
azvyagintsev0d978152022-01-27 14:01:33 +0200573 def jobSummary = [
574 job_result : jobResult.getResult().toString(),
575 build_url : jobResult.getAbsoluteUrl().toString(),
576 build_id : jobResult.getId().toString(),
577 buildDuration : buildDuration,
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200578 desc : desc,
azvyagintsev0d978152022-01-27 14:01:33 +0200579 ]
580 def _buildDescription = jobResult.getDescription().toString()
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200581 if (_buildDescription) {
azvyagintsev0d978152022-01-27 14:01:33 +0200582 jobSummary['build_description'] = _buildDescription
583 }
584 // Store links to the resulting artifacts into 'global_variables'
585 storeArtifacts(jobSummary['build_url'], step['artifacts'],
Dennis Dmitrievaa0fa742024-03-27 22:38:25 +0200586 global_variables, jobName, jobSummary['build_id'], artifactoryBaseUrl, artifactoryServer, artifacts_msg='artifacts to local variables')
587 // Store links to the resulting 'global_artifacts' into 'global_variables'
588 storeArtifacts(jobSummary['build_url'], step['global_artifacts'],
589 global_variables, jobName, jobSummary['build_id'], artifactoryBaseUrl, artifactoryServer, artifacts_msg='global_artifacts to local variables')
590 // Store links to the resulting 'global_artifacts' into 'parent_global_variables'
591 storeArtifacts(jobSummary['build_url'], step['global_artifacts'],
592 parent_global_variables, jobName, jobSummary['build_id'], artifactoryBaseUrl, artifactoryServer, artifacts_msg='global_artifacts to global_variables')
azvyagintsev0d978152022-01-27 14:01:33 +0200593 return jobSummary
594 }
595}
AndrewB8505a7f2020-06-05 13:42:08 +0300596
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200597
Dennis Dmitrievaa0fa742024-03-27 22:38:25 +0200598def runScript(global_variables, step, artifactoryBaseUrl = '', artifactoryServer = '', scriptsLibrary = null, parent_global_variables=null) {
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200599 def common = new com.mirantis.mk.Common()
600 def env_variables = common.getEnvAsMap()
601
602 if (!scriptsLibrary) {
603 error "'scriptsLibrary' argument is not provided to load a script object '${step['script']}' from that library"
604 }
605 // Evaluate the object from it's name, for example: scriptsLibrary.com.mirantis.si.runtime_steps.ParallelMkeMoskUpgradeSequences
606 def scriptObj = scriptsLibrary
607 for (sObj in step['script'].split("\\.")) {
608 scriptObj = scriptObj."$sObj"
609 }
610
611 def script = scriptObj.new()
612
613 def scriptSummary = [
614 job_result : '',
615 desc : step['description'] ?: '',
616 ]
617
618 // prepare 'script_env' from merged 'env' and script step parameters
619 def script_env = env_variables.clone()
620 def stepParameters = step['parameters'] ?: [:]
621 def script_parameters = generateParameters(stepParameters, global_variables)
622 println "${script_parameters}"
623 for (script_parameter in script_parameters) {
624 common.infoMsg("Updating script env['${script_parameter.name}'] with value: ${script_parameter.value}")
625 script_env[script_parameter.name] = script_parameter.value
626 }
627
628 try {
629 script.main(this, script_env)
630 scriptSummary['script_result'] = 'SUCCESS'
631 } catch (InterruptedException e) {
632 scriptSummary['script_result'] = 'ABORTED'
633 printStackTrace(e)
634 } catch (e) {
635 scriptSummary['script_result'] = 'FAILURE'
636 printStackTrace(e)
637 }
638
Dennis Dmitrievaa0fa742024-03-27 22:38:25 +0200639 // Store links to the resulting 'artifacts' into 'global_variables'
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200640 storeArtifacts(env.BUILD_URL, step['artifacts'],
Dennis Dmitrievaa0fa742024-03-27 22:38:25 +0200641 global_variables, env.JOB_NAME, env.BUILD_NUMBER, artifactoryBaseUrl, artifactoryServer, artifacts_msg='artifacts to local variables')
642 // Store links to the resulting 'global_artifacts' into 'global_variables'
643 storeArtifacts(env.BUILD_URL, step['global_artifacts'],
644 global_variables, env.JOB_NAME, env.BUILD_NUMBER, artifactoryBaseUrl, artifactoryServer, artifacts_msg='global_artifacts to local variables')
645 // Store links to the resulting 'global_artifacts' into 'parent_global_variables'
646 storeArtifacts(env.BUILD_URL, step['global_artifacts'],
647 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 +0200648
649 return scriptSummary
650}
651
652
Dennis Dmitrievaa0fa742024-03-27 22:38:25 +0200653def 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 +0200654 // Run the specified steps in parallel
655 // Repeat the steps for each parameters set from 'repeat_with_parameters_from_yaml'
656 // If 'repeat_with_parameters_from_yaml' is not provided, then 'parallel' step will perform just one iteration for a default "- _FOO: _BAR" parameter
657 // If 'repeat_with_parameters_from_yaml' is present, but the specified artifact contains empty list '[]', then 'parallel' step will be skipped
658 // Example:
659 // - parallel:
660 // - job:
661 // - job:
662 // - sequence:
663 // repeat_with_parameters_from_yaml:
664 // type: TextParameterValue
665 // get_variable_from_url: SI_PARALLEL_PARAMETERS
666 // max_concurrent: 2 # how many parallel jobs shold be run at the same time
667 // max_concurrent_interval: 300 # how many seconds should be passed between checking for an available concurrency
668 // check_failed_concurrent: false # stop waiting for available concurrent executors if count of failed jobs >= max_concurrent,
669 // # which means that all available shared resources are occupied by the failed jobs
azvyagintsev8bf15d72024-09-19 14:43:33 +0300670 // 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 +0200671 def common = new com.mirantis.mk.Common()
672
673 def sourceText = ""
674 def defaultSourceText = "- _FOO: _BAR"
675 if (step['repeat_with_parameters_from_yaml']) {
676 def sourceParameter = ["repeat_with_parameters_from_yaml": step['repeat_with_parameters_from_yaml']]
677 for (parameter in generateParameters(sourceParameter, global_variables)) {
678 if (parameter.name == "repeat_with_parameters_from_yaml") {
679 sourceText = parameter.value
680 common.infoMsg("'repeat_with_parameters_from_yaml' is defined, using it as a yaml text:\n${sourceText}")
681 }
682 }
683 }
684 if (!sourceText) {
685 sourceText = defaultSourceText
686 common.warningMsg("'repeat_with_parameters_from_yaml' is not defined. To get one iteration, use default single entry:\n${sourceText}")
687 }
688 def iterateParametersList = readYaml text: sourceText
689 if (!(iterateParametersList instanceof List)) {
690 // Stop the pipeline if there is wrong parameters data type, to not generate parallel jobs for wrong data
691 error "Expected a List in 'repeat_with_parameters_from_yaml' for 'parallel' step, but got:\n${sourceText}"
692 }
693
694 // Limit the maximum steps in parallel at the same time
695 def max_concurrent = (step['max_concurrent'] ?: 100).toInteger()
696 // Sleep for the specified amount of time until a free thread will be available
697 def max_concurrent_interval = (step['max_concurrent_interval'] ?: 600).toInteger()
698 // Check that failed jobs is not >= free executors. if 'true', then don't wait for free executors, fail the parallel step
699 def check_failed_concurrent = (step['check_failed_concurrent'] ?: false).toBoolean()
700
701 def jobs = [:]
azvyagintsev8bf15d72024-09-19 14:43:33 +0300702 jobs.failFast = (step['abort_on_parallel_fail'] ?: false).toBoolean()
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200703 def nested_step_id = 0
704 def free_concurrent = max_concurrent
705 def failed_concurrent = []
706
707 common.printMsg("${prefixMsg} Running parallel steps with the following parameters:\n${iterateParametersList}", "purple")
708
709 for (parameters in iterateParametersList) {
710 for (parallel_step in step['parallel']) {
711 def step_name = "parallel#${nested_step_id}"
712 def nested_step = parallel_step
713 def nested_step_name = step_name
714 def nested_prefix_name = "${prefixMsg}${nested_step_name} | "
715
716 nested_steps_data[step_name] = []
717 prepareJobsData([nested_step,], 'parallel', nested_steps_data[step_name])
718
719 //Copy global variables and merge "parameters" dict into it for the current particular step
720 def nested_global_variables = global_variables.clone()
721 nested_global_variables << parameters
722
723 jobs[step_name] = {
724 // initialRecurrencePeriod in milliseconds
725 waitUntil(initialRecurrencePeriod: 1500, quiet: true) {
726 if (check_failed_concurrent) {
727 if (failed_concurrent.size() >= max_concurrent){
728 common.errorMsg("Failed jobs count is equal max_concurrent value ${max_concurrent}. Will not continue because resources are consumed")
729 error("max_concurrent == failed_concurrent")
730 }
731 }
732 if (free_concurrent > 0) {
733 free_concurrent--
734 true
735 } else {
736 sleep(max_concurrent_interval)
737 false
738 }
739 }
740
741 try {
Dennis Dmitrievaa0fa742024-03-27 22:38:25 +0200742 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 +0200743 }
744 catch (e) {
745 failed_concurrent.add(step_name)
746 throw(e)
747 }
748
749 free_concurrent++
750 } // 'jobs' closure
751
752 nested_step_id++
753 }
754 }
755
756 def parallelSummary = [
757 nested_result : '',
758 desc : step['description'] ?: '',
759 nested_steps_data : [:],
760 ]
761
762 if (iterateParametersList) {
763 // Run parallel iterations
764 try {
765 common.infoMsg("${prefixMsg} Run steps in parallel")
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200766 parallel jobs
767
768 parallelSummary['nested_result'] = 'SUCCESS'
769 } catch (InterruptedException e) {
770 parallelSummary['nested_result'] = 'ABORTED'
771 printStackTrace(e)
772 } catch (e) {
773 parallelSummary['nested_result'] = 'FAILURE'
774 printStackTrace(e)
775 }
776 parallelSummary['nested_steps_data'] = nested_steps_data
777 }
778 else
779 {
780 // No parameters were provided to iterate
781 common.errorMsg("${prefixMsg} No parameters were provided to iterate, skipping 'parallel' step")
782 parallelSummary['nested_result'] = 'SUCCESS'
783 }
784 return parallelSummary
785}
786
787
Dennis Dmitrievaa0fa742024-03-27 22:38:25 +0200788def 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 +0200789 // 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'
790 // If 'repeat_with_parameters_from_yaml' is not provided, then 'sequence' step will perform just one iteration for a default "- _FOO: _BAR" parameter
791 // If 'repeat_with_parameters_from_yaml' is present, but the specified artifact contains empty list '[]', then 'sequence' step will be skipped
792 // - sequence:
793 // - job:
794 // - job:
795 // - script:
796 // repeat_with_parameters_from_yaml:
797 // type: TextParameterValue
798 // get_variable_from_url: SI_PARALLEL_PARAMETERS
799 def common = new com.mirantis.mk.Common()
800
801 def sourceText = ""
802 def defaultSourceText = "- _FOO: _BAR"
803 if (step['repeat_with_parameters_from_yaml']) {
804 def sourceParameter = ["repeat_with_parameters_from_yaml": step['repeat_with_parameters_from_yaml']]
805 for (parameter in generateParameters(sourceParameter, global_variables)) {
806 if (parameter.name == "repeat_with_parameters_from_yaml") {
807 sourceText = parameter.value
808 common.infoMsg("'repeat_with_parameters_from_yaml' is defined, using it as a yaml text:\n${sourceText}")
809 }
810 }
811 }
812 if (!sourceText) {
813 sourceText = defaultSourceText
814 common.warningMsg("'repeat_with_parameters_from_yaml' is not defined. To get one iteration, use default single entry:\n${sourceText}")
815 }
816 def iterateParametersList = readYaml text: sourceText
817 if (!(iterateParametersList instanceof List)) {
818 // Stop the pipeline if there is wrong parameters data type, to not generate parallel jobs for wrong data
819 error "Expected a List in 'repeat_with_parameters_from_yaml' for 'sequence' step, but got:\n${sourceText}"
820 }
821
822 def jobs = [:]
823 def nested_step_id = 0
824
825 common.printMsg("${prefixMsg} Running parallel steps with the following parameters:\n${iterateParametersList}", "purple")
826
827 for (parameters in iterateParametersList) {
828 def step_name = "sequence#${nested_step_id}"
829 def nested_steps = step['sequence']
830 def nested_step_name = step_name
831 def nested_prefix_name = "${prefixMsg}${nested_step_name} | "
832
833 nested_steps_data[step_name] = []
834 prepareJobsData(nested_steps, 'sequence', nested_steps_data[step_name])
835
836 //Copy global variables and merge "parameters" dict into it for the current particular step
837 def nested_global_variables = global_variables.clone()
838 nested_global_variables << parameters
839
840 jobs[step_name] = {
841
Dennis Dmitrievaa0fa742024-03-27 22:38:25 +0200842 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 +0200843
844 } // 'jobs' closure
845
846 nested_step_id++
847 }
848
849 def sequenceSummary = [
850 nested_result : '',
851 desc : step['description'] ?: '',
852 nested_steps_data : [:],
853 ]
854
855 if (iterateParametersList) {
856 // Run sequence iterations
857 try {
858 jobs.each { stepName, job ->
859 common.infoMsg("${prefixMsg} Running sequence ${stepName}")
860 job()
azvyagintsevd5f05122024-09-21 13:00:16 +0300861 // just in case sleep.
862 sleep(5)
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200863 }
864 sequenceSummary['nested_result'] = 'SUCCESS'
865 } catch (InterruptedException e) {
866 sequenceSummary['nested_result'] = 'ABORTED'
867 printStackTrace(e)
868 } catch (e) {
869 sequenceSummary['nested_result'] = 'FAILURE'
870 printStackTrace(e)
871 }
872 sequenceSummary['nested_steps_data'] = nested_steps_data
873 }
874 else
875 {
876 // No parameters were provided to iterate
877 common.errorMsg("${prefixMsg} No parameters were provided to iterate, skipping 'sequence' step")
878 sequenceSummary['nested_result'] = 'SUCCESS'
879 }
880
881 return sequenceSummary
882}
883
884
885def checkResult(job_result, build_url, step, failed_jobs) {
886 // Check job result, in case of SUCCESS, move to next step.
887 // In case job has status NOT_BUILT, fail the build or keep going depending on 'ignore_not_built' flag
888 // In other cases check flag ignore_failed, if true ignore any statuses and keep going additionally
889 // if skip_results is not set or set to false fail entrie workflow, otherwise succed.
890 if (job_result != 'SUCCESS') {
891 def ignoreStepResult = false
892 switch (job_result) {
893 // In cases when job was waiting too long in queue or internal job logic allows to skip building,
894 // job may have NOT_BUILT status. In that case ignore_not_built flag can be used not to fail scenario.
895 case "NOT_BUILT":
896 ignoreStepResult = step['ignore_not_built'] ?: false
897 break
898 case "UNSTABLE":
899 ignoreStepResult = step['ignore_unstable'] ?: (step['ignore_failed'] ?: false)
900 if (ignoreStepResult && !step['skip_results'] ?: false) {
901 failed_jobs[build_url] = job_result
902 }
903 break
azvyagintseve012e412024-05-22 16:09:23 +0300904 case "ABORTED":
905 ignoreStepResult = step['ignore_aborted'] ?: (step['ignore_failed'] ?: false)
906 if (ignoreStepResult && !step['skip_results'] ?: false) {
907 failed_jobs[build_url] = job_result
908 }
909 break
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200910 default:
911 ignoreStepResult = step['ignore_failed'] ?: false
912 if (ignoreStepResult && !step['skip_results'] ?: false) {
913 failed_jobs[build_url] = job_result
914 }
915 }
916 if (!ignoreStepResult) {
917 currentBuild.result = job_result
918 error "Job ${build_url} finished with result: ${job_result}"
919 }
920 }
921}
922
Dennis Dmitrievaa0fa742024-03-27 22:38:25 +0200923def 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 +0200924 def common = new com.mirantis.mk.Common()
925
926 def _sep = "\n======================\n"
927 if (step.containsKey('job')) {
928
929 common.printMsg("${_sep}${prefixMsg}Run job ${step['job']} [at ${java.time.LocalDateTime.now()}]${_sep}", "blue")
930 stage("Run job ${step['job']}") {
931
Dennis Dmitrievaa0fa742024-03-27 22:38:25 +0200932 def job_summary = runStep(global_variables, step, propagate, artifactoryBaseUrl, artifactoryServer, parent_global_variables).call()
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300933
AndrewB8505a7f2020-06-05 13:42:08 +0300934 // Update jobs_data for updating description
azvyagintsev0d978152022-01-27 14:01:33 +0200935 jobs_data[step_id]['build_url'] = job_summary['build_url']
936 jobs_data[step_id]['build_id'] = job_summary['build_id']
937 jobs_data[step_id]['status'] = job_summary['job_result']
938 jobs_data[step_id]['duration'] = job_summary['buildDuration']
939 jobs_data[step_id]['desc'] = job_summary['desc']
940 if (job_summary['build_description']) {
941 jobs_data[step_id]['child_desc'] = job_summary['build_description']
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300942 }
azvyagintsev0d978152022-01-27 14:01:33 +0200943 def job_result = job_summary['job_result']
944 def build_url = job_summary['build_url']
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200945 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 +0200946 }
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200947 }
948 else if (step.containsKey('script')) {
949 common.printMsg("${_sep}${prefixMsg}Run script ${step['script']} [at ${java.time.LocalDateTime.now()}]${_sep}", "blue")
950 stage("Run script ${step['script']}") {
951
Dennis Dmitrievaa0fa742024-03-27 22:38:25 +0200952 def scriptResult = runScript(global_variables, step, artifactoryBaseUrl, artifactoryServer, scriptsLibrary, parent_global_variables)
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +0200953
954 // Use build_url just as an unique key for failed_jobs.
955 // All characters after '#' are 'comment'
956 def build_url = "${env.BUILD_URL}#${step_id}:${step['script']}"
957 def job_result = scriptResult['script_result']
958 common.printMsg("${_sep}${prefixMsg}Script ${build_url} finished with result: ${job_result} [at ${java.time.LocalDateTime.now()}]${_sep}", "blue")
959
960 jobs_data[step_id]['build_url'] = build_url
961 jobs_data[step_id]['status'] = scriptResult['script_result']
962 jobs_data[step_id]['desc'] = scriptResult['desc']
963 if (scriptResult['build_description']) {
964 jobs_data[step_id]['child_desc'] = scriptResult['build_description']
965 }
966 }
967 }
968 else if (step.containsKey('parallel')) {
969 common.printMsg("${_sep}${prefixMsg}Run steps in parallel [at ${java.time.LocalDateTime.now()}]:${_sep}", "blue")
970 stage("Run steps in parallel:") {
971
972 // Allocate a map to collect nested steps data for updateDescription()
973 def nested_steps_data = [:]
974 jobs_data[step_id]['nested_steps_data'] = nested_steps_data
975
Dennis Dmitrievaa0fa742024-03-27 22:38:25 +0200976 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 +0200977
978 // Use build_url just as an unique key for failed_jobs.
979 // All characters after '#' are 'comment'
980 def build_url = "${env.BUILD_URL}#${step_id}"
981 def job_result = parallelResult['nested_result']
982 common.printMsg("${_sep}${prefixMsg}Parallel steps ${build_url} finished with result: ${job_result} [at ${java.time.LocalDateTime.now()}]${_sep}", "blue")
983
984 jobs_data[step_id]['build_url'] = build_url
985 jobs_data[step_id]['status'] = parallelResult['nested_result']
986 jobs_data[step_id]['desc'] = parallelResult['desc']
987 if (parallelResult['build_description']) {
988 jobs_data[step_id]['child_desc'] = parallelResult['build_description']
989 }
990 }
991 }
992 else if (step.containsKey('sequence')) {
993 common.printMsg("${_sep}${prefixMsg}Run steps in sequence [at ${java.time.LocalDateTime.now()}]:${_sep}", "blue")
994 stage("Run steps in sequence:") {
995
996 // Allocate a map to collect nested steps data for updateDescription()
997 def nested_steps_data = [:]
998 jobs_data[step_id]['nested_steps_data'] = nested_steps_data
999
Dennis Dmitrievaa0fa742024-03-27 22:38:25 +02001000 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 +02001001
1002 // Use build_url just as an unique key for failed_jobs.
1003 // All characters after '#' are 'comment'
1004 def build_url = "${env.BUILD_URL}#${step_id}"
1005 def job_result = sequenceResult['nested_result']
1006 common.printMsg("${_sep}${prefixMsg}Sequence steps ${build_url} finished with result: ${job_result} [at ${java.time.LocalDateTime.now()}]${_sep}", "blue")
1007
1008 jobs_data[step_id]['build_url'] = build_url
1009 jobs_data[step_id]['status'] = sequenceResult['nested_result']
1010 jobs_data[step_id]['desc'] = sequenceResult['desc']
1011 if (sequenceResult['build_description']) {
1012 jobs_data[step_id]['child_desc'] = sequenceResult['build_description']
1013 }
1014 }
1015 }
1016
1017 updateDescription(global_jobs_data)
1018
1019 job_result = jobs_data[step_id]['status']
1020 checkResult(job_result, build_url, step, failed_jobs)
1021
1022// return build_url
1023
1024}
1025
1026/**
1027 * Run the workflow or final steps one by one
1028 *
1029 * @param steps List of steps (Jenkins jobs) to execute
1030 * @param global_variables Map where the collected artifact URLs and 'env' objects are stored
1031 * @param failed_jobs Map with failed job names and result statuses, to report it later
1032 * @param jobs_data Map with all job names and result statuses, to showing it in description
1033 * @param step_id Counter for matching step ID with cell ID in description table
1034 * @param propagate Boolean. If false: allows to collect artifacts after job is finished, even with FAILURE status
1035 * If true: immediatelly fails the pipeline. DO NOT USE 'true' with runScenario().
1036 */
Dennis Dmitrievaa0fa742024-03-27 22:38:25 +02001037def 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 +02001038 // Show expected jobs list in description
1039 updateDescription(global_jobs_data)
1040
1041 for (step in steps) {
1042
Dennis Dmitrievaa0fa742024-03-27 22:38:25 +02001043 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 +02001044
azvyagintsev75390d92021-04-12 14:20:11 +03001045 // Jump to next ID for updating next job data in description table
1046 step_id++
azvyagintsev0d978152022-01-27 14:01:33 +02001047 }
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +03001048}
1049
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +02001050
1051/**
1052 * Prepare jobs_data for generating the scenario description
1053 */
1054def prepareJobsData(scenario_steps, step_type, jobs_data) {
1055 def list_id = jobs_data.size()
1056
1057 for (step in scenario_steps) {
1058 def display_name = ''
1059 def step_key = ''
1060 def desc = ''
1061
1062 if (step.containsKey('job')) {
1063 display_name = step['job']
1064 step_key = 'job'
1065 }
1066 else if (step.containsKey('script')) {
1067 display_name = step['script']
1068 step_key = 'script'
1069 }
1070 else if (step.containsKey('parallel')) {
1071 display_name = 'Parallel steps'
1072 step_key = 'parallel'
1073 }
1074 else if (step.containsKey('sequence')) {
1075 display_name = 'Sequence steps'
1076 step_key = 'sequence'
1077 }
1078
1079 if (step['description'] != null && step['description'] != 'null' && step['description'].toString() != '') {
1080 desc = (step['description'] ?: '').toString()
1081 }
1082
1083 jobs_data.add([list_id : "$list_id",
1084 type : step_type,
1085 name : "$display_name",
1086 build_url : "0",
1087 build_id : "-",
1088 status : "-",
1089 desc : desc,
1090 child_desc : "",
1091 duration : '-',
1092 step_key : step_key,
1093 together_steps: [],
1094 ])
1095 list_id += 1
1096 }
1097}
1098
1099
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +03001100/**
1101 * Run the workflow scenario
1102 *
1103 * @param scenario: Map with scenario steps.
1104
1105 * There are two keys in the scenario:
1106 * workflow: contains steps to run deploy and test jobs
1107 * finally: contains steps to run report and cleanup jobs
1108 *
1109 * Scenario execution example:
1110 *
1111 * scenario_yaml = """\
1112 * workflow:
1113 * - job: deploy-kaas
1114 * ignore_failed: false
AndrewB8505a7f2020-06-05 13:42:08 +03001115 * description: "Management cluster ${KAAS_VERSION}"
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +03001116 * parameters:
1117 * KAAS_VERSION:
1118 * type: StringParameterValue
1119 * use_variable: KAAS_VERSION
1120 * artifacts:
1121 * KUBECONFIG_ARTIFACT: artifacts/management_kubeconfig
Dennis Dmitrievcae9bca2019-09-19 16:10:03 +03001122 * DEPLOYED_KAAS_VERSION: artifacts/management_version
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +03001123 *
Dennis Dmitriev5f014d82020-04-29 00:00:34 +03001124 * - job: create-child
1125 * inherit_parent_params: true
1126 * ignore_failed: false
1127 * parameters:
1128 * KUBECONFIG_ARTIFACT_URL:
1129 * type: StringParameterValue
1130 * use_variable: KUBECONFIG_ARTIFACT
1131 * KAAS_VERSION:
1132 * type: StringParameterValue
1133 * get_variable_from_url: DEPLOYED_KAAS_VERSION
Dennis Dmitriev6c355be2021-11-09 14:06:56 +02001134 * RELEASE_NAME:
1135 * type: StringParameterValue
1136 * get_variable_from_yaml:
1137 * yaml_url: SI_CONFIG_ARTIFACT
1138 * yaml_key: .clusters[0].release_name
Dennis Dmitrievaa0fa742024-03-27 22:38:25 +02001139 * global_artifacts:
1140 * CHILD_CONFIG_1: artifacts/child_kubeconfig
Dennis Dmitriev5f014d82020-04-29 00:00:34 +03001141 *
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +03001142 * - job: test-kaas-ui
Mykyta Karpina3d775e2020-04-24 14:45:17 +03001143 * ignore_not_built: false
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +03001144 * parameters:
1145 * KUBECONFIG_ARTIFACT_URL:
1146 * type: StringParameterValue
1147 * use_variable: KUBECONFIG_ARTIFACT
Dennis Dmitrievcae9bca2019-09-19 16:10:03 +03001148 * KAAS_VERSION:
1149 * type: StringParameterValue
1150 * get_variable_from_url: DEPLOYED_KAAS_VERSION
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +03001151 * artifacts:
1152 * REPORT_SI_KAAS_UI: artifacts/test_kaas_ui_result.xml
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +03001153 * finally:
1154 * - job: testrail-report
1155 * ignore_failed: true
1156 * parameters:
Dennis Dmitrievce470932019-09-18 18:31:11 +03001157 * KAAS_VERSION:
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +03001158 * type: StringParameterValue
Dennis Dmitrievcae9bca2019-09-19 16:10:03 +03001159 * get_variable_from_url: DEPLOYED_KAAS_VERSION
Dennis Dmitrievce470932019-09-18 18:31:11 +03001160 * REPORTS_LIST:
1161 * type: TextParameterValue
1162 * use_template: |
1163 * REPORT_SI_KAAS_UI: \$REPORT_SI_KAAS_UI
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +03001164 * """
1165 *
1166 * runScenario(scenario)
1167 *
Dennis Dmitriev5f014d82020-04-29 00:00:34 +03001168 * Scenario workflow keys:
1169 *
1170 * job: string. Jenkins job name
1171 * 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 +04001172 * 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 +03001173 * 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 +02001174 * 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 +03001175 * 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
1176 * inherit_parent_params: bool. if true, provide all parameters from the parent job to the child job as defaults
1177 * 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 +02001178 * wf_pause_step_before_run: bool. Interactive pause exact step before run.
1179 * wf_pause_step_slack_report_channel: If step paused, send message about it in slack.
1180 * wf_pause_step_timeout: timeout im minutes to wait for manual unpause.
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +03001181 */
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +02001182def runScenario(scenario, slackReportChannel = '', artifactoryBaseUrl = '', Boolean logGlobalVariables = false, artifactoryServer = '', scriptsLibrary = null,
1183 global_variables = null, failed_jobs = null, jobs_data = null) {
1184 def common = new com.mirantis.mk.Common()
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +03001185
Dennis Dmitriev79f3a2d2019-08-09 16:06:00 +03001186 // Clear description before adding new messages
1187 currentBuild.description = ''
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +03001188 // Collect the parameters for the jobs here
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +02001189 if (global_variables == null) {
1190 global_variables = [:]
1191 }
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +03001192 // List of failed jobs to show at the end
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +02001193 if (failed_jobs == null) {
1194 failed_jobs = [:]
1195 }
AndrewB8505a7f2020-06-05 13:42:08 +03001196 // Jobs data to use for wf job build description
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +02001197 if (jobs_data == null) {
1198 jobs_data = []
1199 }
1200 def global_jobs_data = jobs_data
1201
AndrewB8505a7f2020-06-05 13:42:08 +03001202 // Counter for matching step ID with cell ID in description table
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +02001203 def step_id = jobs_data.size()
AndrewB8505a7f2020-06-05 13:42:08 +03001204 // Generate expected list jobs for description
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +02001205 prepareJobsData(scenario['workflow'], 'workflow', jobs_data)
azvyagintsev0d978152022-01-27 14:01:33 +02001206
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +02001207 def pause_step_id = jobs_data.size()
1208 // Generate expected list jobs for description
1209 prepareJobsData(scenario['pause'], 'pause', jobs_data)
Sergey Lalov702384d2022-11-10 12:10:23 +04001210
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +02001211 def finally_step_id = jobs_data.size()
1212 // Generate expected list jobs for description
1213 prepareJobsData(scenario['finally'], 'finally', jobs_data)
1214
1215
Sergey Lalov702384d2022-11-10 12:10:23 +04001216 def job_failed_flag = false
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +03001217 try {
1218 // Run the 'workflow' jobs
Dennis Dmitrievaa0fa742024-03-27 22:38:25 +02001219 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 +02001220 } catch (InterruptedException e) {
Sergey Lalov702384d2022-11-10 12:10:23 +04001221 job_failed_flag = true
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +03001222 error "The job was aborted"
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +03001223 } catch (e) {
Sergey Lalov702384d2022-11-10 12:10:23 +04001224 job_failed_flag = true
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +02001225 printStackTrace(e)
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +03001226 error("Build failed: " + e.toString())
Sergey Lalov702384d2022-11-10 12:10:23 +04001227
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +03001228 } finally {
Dennis Dmitriev38a45cd2023-02-27 14:22:13 +02001229 // Log global_variables
1230 if (logGlobalVariables) {
1231 printVariables(global_variables)
1232 }
1233
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +02001234 def flag_pause_variable = (env.PAUSE_FOR_DEBUG) != null
Sergey Lalov702384d2022-11-10 12:10:23 +04001235 // Run the 'finally' or 'pause' jobs
Sergey Lalov6e9400c2022-11-17 12:59:31 +04001236 common.infoMsg(failed_jobs)
Sergey Lalov2d1cd9c2023-08-03 17:08:09 +04001237 // Run only if there are failed jobs in the scenario
1238 if (flag_pause_variable && (PAUSE_FOR_DEBUG && job_failed_flag)) {
Sergey Lalov702384d2022-11-10 12:10:23 +04001239 // Switching to 'pause' step index
1240 common.infoMsg("FINALLY BLOCK - PAUSE")
1241 step_id = pause_step_id
Dennis Dmitrievaa0fa742024-03-27 22:38:25 +02001242 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 +04001243
1244 }
1245 // Switching to 'finally' step index
1246 common.infoMsg("FINALLY BLOCK - CLEAR")
AndrewB8505a7f2020-06-05 13:42:08 +03001247 step_id = finally_step_id
Dennis Dmitrievaa0fa742024-03-27 22:38:25 +02001248 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 +03001249
1250 if (failed_jobs) {
azvyagintsev0d978152022-01-27 14:01:33 +02001251 def statuses = []
sgudz9ac09d22020-01-22 14:31:30 +02001252 failed_jobs.each {
sgudz74c8cdd2020-01-23 14:26:32 +02001253 statuses += it.value
azvyagintsev75390d92021-04-12 14:20:11 +03001254 }
sgudz9ac09d22020-01-22 14:31:30 +02001255 if (statuses.contains('FAILURE')) {
1256 currentBuild.result = 'FAILURE'
Sergey Lalove5e0a842023-10-02 15:55:59 +04001257 } else if (statuses.contains('ABORTED')) {
1258 currentBuild.result = 'ABORTED'
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +02001259 } else if (statuses.contains('UNSTABLE')) {
sgudz9ac09d22020-01-22 14:31:30 +02001260 currentBuild.result = 'UNSTABLE'
azvyagintsev75390d92021-04-12 14:20:11 +03001261 } else {
sgudz9ac09d22020-01-22 14:31:30 +02001262 currentBuild.result = 'FAILURE'
1263 }
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +03001264 println "Failed jobs: ${failed_jobs}"
vnaumov68cba272020-05-20 11:24:02 +02001265 } else {
1266 currentBuild.result = 'SUCCESS'
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +03001267 }
vnaumov5a6eb8a2020-03-31 11:16:54 +02001268
Sergey Lalov3a2e7902023-07-27 01:19:02 +04001269 common.infoMsg("Workflow finished with result: ${currentBuild.result}")
1270
vnaumov5a6eb8a2020-03-31 11:16:54 +02001271 if (slackReportChannel) {
1272 def slack = new com.mirantis.mcp.SlackNotification()
1273 slack.jobResultNotification(currentBuild.result, slackReportChannel, '', null, '', 'slack_webhook_url')
1274 }
sgudz9ac09d22020-01-22 14:31:30 +02001275 } // finally
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +03001276}
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +02001277
1278
1279def manageArtifacts(entrypointDirectory, storeArtsInJenkins = false, artifactoryServerName = 'mcp-ci') {
1280 def mcpArtifactory = new com.mirantis.mcp.MCPArtifactory()
1281 def artifactoryRepoPath = "si-local/jenkins-job-artifacts/${JOB_NAME}/${BUILD_NUMBER}"
1282 def tests_log = "${entrypointDirectory}/tests.log"
1283
1284 if (fileExists(tests_log)) {
1285 try {
1286 def size = sh([returnStdout: true, script: "stat --printf='%s' ${tests_log}"]).trim().toInteger()
1287 // do not archive unless it is more than 50 MB
1288 def allowed_size = 1048576 * 50
1289 if (size >= allowed_size) {
1290 sh("gzip ${tests_log} || true")
1291 }
1292 } catch (e) {
1293 print("Cannot determine tests.log filesize: ${e}")
1294 }
1295 }
1296
1297 if (storeArtsInJenkins) {
1298 archiveArtifacts(
1299 artifacts: "${entrypointDirectory}/**",
1300 allowEmptyArchive: true
1301 )
1302 }
1303 artConfig = [
1304 deleteArtifacts: false,
1305 artifactory : artifactoryServerName,
1306 artifactPattern: "${entrypointDirectory}/**",
1307 artifactoryRepo: "artifactory/${artifactoryRepoPath}",
1308 ]
1309 def artDescription = mcpArtifactory.uploadArtifactsToArtifactory(artConfig)
Vasyl Saienkoc0c029e2024-10-03 09:24:23 +03001310 if (currentBuild.description) {
1311 currentBuild.description += "${artDescription}<br>"
1312 } else {
1313 currentBuild.description = "${artDescription}<br>"
1314 }
Dennis Dmitriev44ad94c2023-11-29 12:38:12 +02001315
1316 junit(testResults: "${entrypointDirectory}/**/*.xml", allowEmptyResults: true)
1317
1318 def artifactoryServer = Artifactory.server(artifactoryServerName)
1319 def artifactsUrl = "${artifactoryServer.getUrl()}/artifactory/${artifactoryRepoPath}"
1320 return artifactsUrl
1321}
1322
1323
1324return this