blob: 3a58bd32cc149edb5ae53f47d199d10b87c3fc95 [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
19
20/**
21 * Run a Jenkins job using the collected parameters
22 *
23 * @param job_name Name of the running job
24 * @param job_parameters Map that declares which values from global_variables should be used, in the following format:
25 * {'PARAM_NAME': {'type': <job parameter $class name>, 'use_variable': <a key from global_variables>}, ...}
Dennis Dmitrievce470932019-09-18 18:31:11 +030026 * or
Dennis Dmitrievcae9bca2019-09-19 16:10:03 +030027 * {'PARAM_NAME': {'type': <job parameter $class name>, 'get_variable_from_url': <a key from global_variables which contains URL with required content>}, ...}
28 * or
Dennis Dmitrievce470932019-09-18 18:31:11 +030029 * {'PARAM_NAME': {'type': <job parameter $class name>, 'use_template': <a GString multiline template with variables from global_variables>}, ...}
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +030030 * @param global_variables Map that keeps the artifact URLs and used 'env' objects:
31 * {'PARAM1_NAME': <param1 value>, 'PARAM2_NAME': 'http://.../artifacts/param2_value', ...}
Dennis Dmitrieve09e0292019-07-30 16:39:27 +030032 * @param propagate Boolean. If false: allows to collect artifacts after job is finished, even with FAILURE status
33 * If true: immediatelly fails the pipeline. DO NOT USE 'true' if you want to collect artifacts
34 * for 'finally' steps
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +030035 */
Dennis Dmitrieve09e0292019-07-30 16:39:27 +030036def runJob(job_name, job_parameters, global_variables, Boolean propagate = false) {
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +030037 def parameters = []
Dennis Dmitrievcae9bca2019-09-19 16:10:03 +030038 def http = new com.mirantis.mk.Http()
Dennis Dmitrievce470932019-09-18 18:31:11 +030039 def engine = new groovy.text.GStringTemplateEngine()
40 def template
Dennis Dmitrievcae9bca2019-09-19 16:10:03 +030041 def base = [:]
42 base["url"] = ''
43 def variable_content
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +030044
45 // Collect required parameters from 'global_variables' or 'env'
46 for (param in job_parameters) {
Dennis Dmitrievce470932019-09-18 18:31:11 +030047 if (param.value.containsKey('use_variable')) {
48 if (!global_variables[param.value.use_variable]) {
49 global_variables[param.value.use_variable] = env[param.value.use_variable] ?: ''
50 }
51 parameters.add([$class: "${param.value.type}", name: "${param.key}", value: global_variables[param.value.use_variable]])
52 println "${param.key}: <${param.value.type}> ${global_variables[param.value.use_variable]}"
Dennis Dmitrievcae9bca2019-09-19 16:10:03 +030053 } else if (param.value.containsKey('get_variable_from_url')) {
54 if (!global_variables[param.value.get_variable_from_url]) {
55 global_variables[param.value.get_variable_from_url] = env[param.value.get_variable_from_url] ?: ''
56 }
57 variable_content = http.restGet(base, global_variables[param.value.get_variable_from_url])
58 parameters.add([$class: "${param.value.type}", name: "${param.key}", value: variable_content])
59 println "${param.key}: <${param.value.type}> ${variable_content}"
Dennis Dmitrievce470932019-09-18 18:31:11 +030060 } else if (param.value.containsKey('use_template')) {
61 template = engine.createTemplate(param.value.use_template).make(global_variables)
62 parameters.add([$class: "${param.value.type}", name: "${param.key}", value: template.toString()])
63 println "${param.key}: <${param.value.type}>\n${template.toString()}"
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +030064 }
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +030065 }
66
67 // Build the job
Dennis Dmitrieve09e0292019-07-30 16:39:27 +030068 def job_info = build job: "${job_name}", parameters: parameters, propagate: propagate
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +030069 return job_info
70}
71
72/**
73 * Store URLs of the specified artifacts to the global_variables
74 *
75 * @param build_url URL of the completed job
76 * @param step_artifacts Map that contains artifact names in the job, and variable names
77 * where the URLs to that atrifacts should be stored, for example:
78 * {'ARTIFACT1': 'logs.tar.gz', 'ARTIFACT2': 'test_report.xml', ...}
79 * @param global_variables Map that will keep the artifact URLs. Variable 'ARTIFACT1', for example,
80 * be used in next job parameters: {'ARTIFACT1_URL':{ 'use_variable': 'ARTIFACT1', ...}}
81 *
82 * If the artifact with the specified name not found, the parameter ARTIFACT1_URL
83 * will be empty.
84 *
85 */
86def storeArtifacts(build_url, step_artifacts, global_variables) {
87 def http = new com.mirantis.mk.Http()
88 def base = [:]
89 base["url"] = build_url
90 def job_config = http.restGet(base, "/api/json/")
91 def job_artifacts = job_config['artifacts']
92 for (artifact in step_artifacts) {
93 def job_artifact = job_artifacts.findAll { item -> artifact.value == item['fileName'] || artifact.value == item['relativePath'] }
94 if (job_artifact.size() == 1) {
95 // Store artifact URL
96 def artifact_url = "${build_url}artifact/${job_artifact[0]['relativePath']}"
97 global_variables[artifact.key] = artifact_url
98 println "Artifact URL ${artifact_url} stored to ${artifact.key}"
99 } else if (job_artifact.size() > 1) {
100 // Error: too many artifacts with the same name, fail the job
101 error "Multiple artifacts ${artifact.value} for ${artifact.key} found in the build results ${build_url}, expected one:\n${job_artifact}"
102 } else {
103 // Warning: no artifact with expected name
104 println "Artifact ${artifact.value} for ${artifact.key} not found in the build results ${build_url}, found the following artifacts:\n${job_artifacts}"
105 }
106 }
107}
108
109
110/**
111 * Run the workflow or final steps one by one
112 *
113 * @param steps List of steps (Jenkins jobs) to execute
114 * @param global_variables Map where the collected artifact URLs and 'env' objects are stored
115 * @param failed_jobs Map with failed job names and result statuses, to report it later
Dennis Dmitrieve09e0292019-07-30 16:39:27 +0300116 * @param propagate Boolean. If false: allows to collect artifacts after job is finished, even with FAILURE status
117 * If true: immediatelly fails the pipeline. DO NOT USE 'true' with runScenario().
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300118 */
Dennis Dmitrieve09e0292019-07-30 16:39:27 +0300119def runSteps(steps, global_variables, failed_jobs, Boolean propagate = false) {
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300120 for (step in steps) {
121 stage("Running job ${step['job']}") {
122
123 def job_name = step['job']
124 def job_parameters = step['parameters']
125 // Collect job parameters and run the job
Dennis Dmitrieve09e0292019-07-30 16:39:27 +0300126 def job_info = runJob(job_name, job_parameters, global_variables, propagate)
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300127 def job_result = job_info.getResult()
128 def build_url = job_info.getAbsoluteUrl()
129 def build_description = job_info.getDescription()
130
131 currentBuild.description += "<a href=${build_url}>${job_name}</a>: ${job_result}<br>"
132 // Import the remote build description into the current build
133 if (build_description) { // TODO - add also the job status
134 currentBuild.description += build_description
135 }
136
137 // Store links to the resulting artifacts into 'global_variables'
138 storeArtifacts(build_url, step['artifacts'], global_variables)
139
140 // Job failed, fail the build or keep going depending on 'ignore_failed' flag
141 if (job_result != "SUCCESS") {
142 def job_ignore_failed = step['ignore_failed'] ?: false
143 failed_jobs[build_url] = job_result
144 if (job_ignore_failed) {
145 println "Job ${build_url} finished with result: ${job_result}"
146 } else {
147 currentBuild.result = job_result
148 error "Job ${build_url} finished with result: ${job_result}"
149 }
150 } // if (job_result == "SUCCESS")
151 } // stage ("Running job ${step['job']}")
152 } // for (step in scenario['workflow'])
153}
154
155/**
156 * Run the workflow scenario
157 *
158 * @param scenario: Map with scenario steps.
159
160 * There are two keys in the scenario:
161 * workflow: contains steps to run deploy and test jobs
162 * finally: contains steps to run report and cleanup jobs
163 *
164 * Scenario execution example:
165 *
166 * scenario_yaml = """\
167 * workflow:
168 * - job: deploy-kaas
169 * ignore_failed: false
170 * parameters:
171 * KAAS_VERSION:
172 * type: StringParameterValue
173 * use_variable: KAAS_VERSION
174 * artifacts:
175 * KUBECONFIG_ARTIFACT: artifacts/management_kubeconfig
Dennis Dmitrievcae9bca2019-09-19 16:10:03 +0300176 * DEPLOYED_KAAS_VERSION: artifacts/management_version
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300177 *
178 * - job: test-kaas-ui
179 * ignore_failed: false
180 * parameters:
181 * KUBECONFIG_ARTIFACT_URL:
182 * type: StringParameterValue
183 * use_variable: KUBECONFIG_ARTIFACT
Dennis Dmitrievcae9bca2019-09-19 16:10:03 +0300184 * KAAS_VERSION:
185 * type: StringParameterValue
186 * get_variable_from_url: DEPLOYED_KAAS_VERSION
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300187 * artifacts:
188 * REPORT_SI_KAAS_UI: artifacts/test_kaas_ui_result.xml
189 *
190 * finally:
191 * - job: testrail-report
192 * ignore_failed: true
193 * parameters:
Dennis Dmitrievce470932019-09-18 18:31:11 +0300194 * KAAS_VERSION:
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300195 * type: StringParameterValue
Dennis Dmitrievcae9bca2019-09-19 16:10:03 +0300196 * get_variable_from_url: DEPLOYED_KAAS_VERSION
Dennis Dmitrievce470932019-09-18 18:31:11 +0300197 * REPORTS_LIST:
198 * type: TextParameterValue
199 * use_template: |
200 * REPORT_SI_KAAS_UI: \$REPORT_SI_KAAS_UI
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300201 * """
202 *
203 * runScenario(scenario)
204 *
205 */
206
207def runScenario(scenario) {
208
Dennis Dmitriev79f3a2d2019-08-09 16:06:00 +0300209 // Clear description before adding new messages
210 currentBuild.description = ''
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300211 // Collect the parameters for the jobs here
212 global_variables = [:]
213 // List of failed jobs to show at the end
214 failed_jobs = [:]
215
216 try {
217 // Run the 'workflow' jobs
218 runSteps(scenario['workflow'], global_variables, failed_jobs)
219
220 } catch (InterruptedException x) {
221 error "The job was aborted"
222
223 } catch (e) {
224 error("Build failed: " + e.toString())
225
226 } finally {
227 // Run the 'finally' jobs
228 runSteps(scenario['finally'], global_variables, failed_jobs)
229
230 if (failed_jobs) {
231 println "Failed jobs: ${failed_jobs}"
232 currentBuild.result = "FAILED"
233 }
234 } // try
235}