blob: 5e99c6776ff3d12036a3366ad258fcf69516c234 [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
27 * {'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 +030028 * @param global_variables Map that keeps the artifact URLs and used 'env' objects:
29 * {'PARAM1_NAME': <param1 value>, 'PARAM2_NAME': 'http://.../artifacts/param2_value', ...}
Dennis Dmitrieve09e0292019-07-30 16:39:27 +030030 * @param propagate Boolean. If false: allows to collect artifacts after job is finished, even with FAILURE status
31 * If true: immediatelly fails the pipeline. DO NOT USE 'true' if you want to collect artifacts
32 * for 'finally' steps
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +030033 */
Dennis Dmitrieve09e0292019-07-30 16:39:27 +030034def runJob(job_name, job_parameters, global_variables, Boolean propagate = false) {
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +030035 def parameters = []
Dennis Dmitrievce470932019-09-18 18:31:11 +030036 def engine = new groovy.text.GStringTemplateEngine()
37 def template
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +030038
39 // Collect required parameters from 'global_variables' or 'env'
40 for (param in job_parameters) {
Dennis Dmitrievce470932019-09-18 18:31:11 +030041 if (param.value.containsKey('use_variable')) {
42 if (!global_variables[param.value.use_variable]) {
43 global_variables[param.value.use_variable] = env[param.value.use_variable] ?: ''
44 }
45 parameters.add([$class: "${param.value.type}", name: "${param.key}", value: global_variables[param.value.use_variable]])
46 println "${param.key}: <${param.value.type}> ${global_variables[param.value.use_variable]}"
47 } else if (param.value.containsKey('use_template')) {
48 template = engine.createTemplate(param.value.use_template).make(global_variables)
49 parameters.add([$class: "${param.value.type}", name: "${param.key}", value: template.toString()])
50 println "${param.key}: <${param.value.type}>\n${template.toString()}"
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +030051 }
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +030052 }
53
54 // Build the job
Dennis Dmitrieve09e0292019-07-30 16:39:27 +030055 def job_info = build job: "${job_name}", parameters: parameters, propagate: propagate
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +030056 return job_info
57}
58
59/**
60 * Store URLs of the specified artifacts to the global_variables
61 *
62 * @param build_url URL of the completed job
63 * @param step_artifacts Map that contains artifact names in the job, and variable names
64 * where the URLs to that atrifacts should be stored, for example:
65 * {'ARTIFACT1': 'logs.tar.gz', 'ARTIFACT2': 'test_report.xml', ...}
66 * @param global_variables Map that will keep the artifact URLs. Variable 'ARTIFACT1', for example,
67 * be used in next job parameters: {'ARTIFACT1_URL':{ 'use_variable': 'ARTIFACT1', ...}}
68 *
69 * If the artifact with the specified name not found, the parameter ARTIFACT1_URL
70 * will be empty.
71 *
72 */
73def storeArtifacts(build_url, step_artifacts, global_variables) {
74 def http = new com.mirantis.mk.Http()
75 def base = [:]
76 base["url"] = build_url
77 def job_config = http.restGet(base, "/api/json/")
78 def job_artifacts = job_config['artifacts']
79 for (artifact in step_artifacts) {
80 def job_artifact = job_artifacts.findAll { item -> artifact.value == item['fileName'] || artifact.value == item['relativePath'] }
81 if (job_artifact.size() == 1) {
82 // Store artifact URL
83 def artifact_url = "${build_url}artifact/${job_artifact[0]['relativePath']}"
84 global_variables[artifact.key] = artifact_url
85 println "Artifact URL ${artifact_url} stored to ${artifact.key}"
86 } else if (job_artifact.size() > 1) {
87 // Error: too many artifacts with the same name, fail the job
88 error "Multiple artifacts ${artifact.value} for ${artifact.key} found in the build results ${build_url}, expected one:\n${job_artifact}"
89 } else {
90 // Warning: no artifact with expected name
91 println "Artifact ${artifact.value} for ${artifact.key} not found in the build results ${build_url}, found the following artifacts:\n${job_artifacts}"
92 }
93 }
94}
95
96
97/**
98 * Run the workflow or final steps one by one
99 *
100 * @param steps List of steps (Jenkins jobs) to execute
101 * @param global_variables Map where the collected artifact URLs and 'env' objects are stored
102 * @param failed_jobs Map with failed job names and result statuses, to report it later
Dennis Dmitrieve09e0292019-07-30 16:39:27 +0300103 * @param propagate Boolean. If false: allows to collect artifacts after job is finished, even with FAILURE status
104 * If true: immediatelly fails the pipeline. DO NOT USE 'true' with runScenario().
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300105 */
Dennis Dmitrieve09e0292019-07-30 16:39:27 +0300106def runSteps(steps, global_variables, failed_jobs, Boolean propagate = false) {
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300107 for (step in steps) {
108 stage("Running job ${step['job']}") {
109
110 def job_name = step['job']
111 def job_parameters = step['parameters']
112 // Collect job parameters and run the job
Dennis Dmitrieve09e0292019-07-30 16:39:27 +0300113 def job_info = runJob(job_name, job_parameters, global_variables, propagate)
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300114 def job_result = job_info.getResult()
115 def build_url = job_info.getAbsoluteUrl()
116 def build_description = job_info.getDescription()
117
118 currentBuild.description += "<a href=${build_url}>${job_name}</a>: ${job_result}<br>"
119 // Import the remote build description into the current build
120 if (build_description) { // TODO - add also the job status
121 currentBuild.description += build_description
122 }
123
124 // Store links to the resulting artifacts into 'global_variables'
125 storeArtifacts(build_url, step['artifacts'], global_variables)
126
127 // Job failed, fail the build or keep going depending on 'ignore_failed' flag
128 if (job_result != "SUCCESS") {
129 def job_ignore_failed = step['ignore_failed'] ?: false
130 failed_jobs[build_url] = job_result
131 if (job_ignore_failed) {
132 println "Job ${build_url} finished with result: ${job_result}"
133 } else {
134 currentBuild.result = job_result
135 error "Job ${build_url} finished with result: ${job_result}"
136 }
137 } // if (job_result == "SUCCESS")
138 } // stage ("Running job ${step['job']}")
139 } // for (step in scenario['workflow'])
140}
141
142/**
143 * Run the workflow scenario
144 *
145 * @param scenario: Map with scenario steps.
146
147 * There are two keys in the scenario:
148 * workflow: contains steps to run deploy and test jobs
149 * finally: contains steps to run report and cleanup jobs
150 *
151 * Scenario execution example:
152 *
153 * scenario_yaml = """\
154 * workflow:
155 * - job: deploy-kaas
156 * ignore_failed: false
157 * parameters:
158 * KAAS_VERSION:
159 * type: StringParameterValue
160 * use_variable: KAAS_VERSION
161 * artifacts:
162 * KUBECONFIG_ARTIFACT: artifacts/management_kubeconfig
163 *
164 * - job: test-kaas-ui
165 * ignore_failed: false
166 * parameters:
167 * KUBECONFIG_ARTIFACT_URL:
168 * type: StringParameterValue
169 * use_variable: KUBECONFIG_ARTIFACT
170 * artifacts:
171 * REPORT_SI_KAAS_UI: artifacts/test_kaas_ui_result.xml
172 *
173 * finally:
174 * - job: testrail-report
175 * ignore_failed: true
176 * parameters:
Dennis Dmitrievce470932019-09-18 18:31:11 +0300177 * KAAS_VERSION:
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300178 * type: StringParameterValue
Dennis Dmitrievce470932019-09-18 18:31:11 +0300179 * use_variable: KAAS_VERSION
180 * REPORTS_LIST:
181 * type: TextParameterValue
182 * use_template: |
183 * REPORT_SI_KAAS_UI: \$REPORT_SI_KAAS_UI
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300184 * """
185 *
186 * runScenario(scenario)
187 *
188 */
189
190def runScenario(scenario) {
191
Dennis Dmitriev79f3a2d2019-08-09 16:06:00 +0300192 // Clear description before adding new messages
193 currentBuild.description = ''
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300194 // Collect the parameters for the jobs here
195 global_variables = [:]
196 // List of failed jobs to show at the end
197 failed_jobs = [:]
198
199 try {
200 // Run the 'workflow' jobs
201 runSteps(scenario['workflow'], global_variables, failed_jobs)
202
203 } catch (InterruptedException x) {
204 error "The job was aborted"
205
206 } catch (e) {
207 error("Build failed: " + e.toString())
208
209 } finally {
210 // Run the 'finally' jobs
211 runSteps(scenario['finally'], global_variables, failed_jobs)
212
213 if (failed_jobs) {
214 println "Failed jobs: ${failed_jobs}"
215 currentBuild.result = "FAILED"
216 }
217 } // try
218}