blob: e798a19e50f6473c969396183804fde59f9d16dc [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>}, ...}
26 * @param global_variables Map that keeps the artifact URLs and used 'env' objects:
27 * {'PARAM1_NAME': <param1 value>, 'PARAM2_NAME': 'http://.../artifacts/param2_value', ...}
Dennis Dmitrieve09e0292019-07-30 16:39:27 +030028 * @param propagate Boolean. If false: allows to collect artifacts after job is finished, even with FAILURE status
29 * If true: immediatelly fails the pipeline. DO NOT USE 'true' if you want to collect artifacts
30 * for 'finally' steps
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +030031 */
Dennis Dmitrieve09e0292019-07-30 16:39:27 +030032def runJob(job_name, job_parameters, global_variables, Boolean propagate = false) {
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +030033 def parameters = []
34
35 // Collect required parameters from 'global_variables' or 'env'
36 for (param in job_parameters) {
37 if (!global_variables[param.value.use_variable]) {
38 global_variables[param.value.use_variable] = env[param.value.use_variable] ?: ''
39 }
40 parameters.add([$class: "${param.value.type}", name: "${param.key}", value: global_variables[param.value.use_variable]])
41 println "${param.key}: <${param.value.type}> ${global_variables[param.value.use_variable]}"
42 }
43
44 // Build the job
Dennis Dmitrieve09e0292019-07-30 16:39:27 +030045 def job_info = build job: "${job_name}", parameters: parameters, propagate: propagate
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +030046 return job_info
47}
48
49/**
50 * Store URLs of the specified artifacts to the global_variables
51 *
52 * @param build_url URL of the completed job
53 * @param step_artifacts Map that contains artifact names in the job, and variable names
54 * where the URLs to that atrifacts should be stored, for example:
55 * {'ARTIFACT1': 'logs.tar.gz', 'ARTIFACT2': 'test_report.xml', ...}
56 * @param global_variables Map that will keep the artifact URLs. Variable 'ARTIFACT1', for example,
57 * be used in next job parameters: {'ARTIFACT1_URL':{ 'use_variable': 'ARTIFACT1', ...}}
58 *
59 * If the artifact with the specified name not found, the parameter ARTIFACT1_URL
60 * will be empty.
61 *
62 */
63def storeArtifacts(build_url, step_artifacts, global_variables) {
64 def http = new com.mirantis.mk.Http()
65 def base = [:]
66 base["url"] = build_url
67 def job_config = http.restGet(base, "/api/json/")
68 def job_artifacts = job_config['artifacts']
69 for (artifact in step_artifacts) {
70 def job_artifact = job_artifacts.findAll { item -> artifact.value == item['fileName'] || artifact.value == item['relativePath'] }
71 if (job_artifact.size() == 1) {
72 // Store artifact URL
73 def artifact_url = "${build_url}artifact/${job_artifact[0]['relativePath']}"
74 global_variables[artifact.key] = artifact_url
75 println "Artifact URL ${artifact_url} stored to ${artifact.key}"
76 } else if (job_artifact.size() > 1) {
77 // Error: too many artifacts with the same name, fail the job
78 error "Multiple artifacts ${artifact.value} for ${artifact.key} found in the build results ${build_url}, expected one:\n${job_artifact}"
79 } else {
80 // Warning: no artifact with expected name
81 println "Artifact ${artifact.value} for ${artifact.key} not found in the build results ${build_url}, found the following artifacts:\n${job_artifacts}"
82 }
83 }
84}
85
86
87/**
88 * Run the workflow or final steps one by one
89 *
90 * @param steps List of steps (Jenkins jobs) to execute
91 * @param global_variables Map where the collected artifact URLs and 'env' objects are stored
92 * @param failed_jobs Map with failed job names and result statuses, to report it later
Dennis Dmitrieve09e0292019-07-30 16:39:27 +030093 * @param propagate Boolean. If false: allows to collect artifacts after job is finished, even with FAILURE status
94 * If true: immediatelly fails the pipeline. DO NOT USE 'true' with runScenario().
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +030095 */
Dennis Dmitrieve09e0292019-07-30 16:39:27 +030096def runSteps(steps, global_variables, failed_jobs, Boolean propagate = false) {
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +030097 currentBuild.description = ''
98 for (step in steps) {
99 stage("Running job ${step['job']}") {
100
101 def job_name = step['job']
102 def job_parameters = step['parameters']
103 // Collect job parameters and run the job
Dennis Dmitrieve09e0292019-07-30 16:39:27 +0300104 def job_info = runJob(job_name, job_parameters, global_variables, propagate)
Dennis Dmitriev5d8a1532019-07-30 16:39:27 +0300105 def job_result = job_info.getResult()
106 def build_url = job_info.getAbsoluteUrl()
107 def build_description = job_info.getDescription()
108
109 currentBuild.description += "<a href=${build_url}>${job_name}</a>: ${job_result}<br>"
110 // Import the remote build description into the current build
111 if (build_description) { // TODO - add also the job status
112 currentBuild.description += build_description
113 }
114
115 // Store links to the resulting artifacts into 'global_variables'
116 storeArtifacts(build_url, step['artifacts'], global_variables)
117
118 // Job failed, fail the build or keep going depending on 'ignore_failed' flag
119 if (job_result != "SUCCESS") {
120 def job_ignore_failed = step['ignore_failed'] ?: false
121 failed_jobs[build_url] = job_result
122 if (job_ignore_failed) {
123 println "Job ${build_url} finished with result: ${job_result}"
124 } else {
125 currentBuild.result = job_result
126 error "Job ${build_url} finished with result: ${job_result}"
127 }
128 } // if (job_result == "SUCCESS")
129 } // stage ("Running job ${step['job']}")
130 } // for (step in scenario['workflow'])
131}
132
133/**
134 * Run the workflow scenario
135 *
136 * @param scenario: Map with scenario steps.
137
138 * There are two keys in the scenario:
139 * workflow: contains steps to run deploy and test jobs
140 * finally: contains steps to run report and cleanup jobs
141 *
142 * Scenario execution example:
143 *
144 * scenario_yaml = """\
145 * workflow:
146 * - job: deploy-kaas
147 * ignore_failed: false
148 * parameters:
149 * KAAS_VERSION:
150 * type: StringParameterValue
151 * use_variable: KAAS_VERSION
152 * artifacts:
153 * KUBECONFIG_ARTIFACT: artifacts/management_kubeconfig
154 *
155 * - job: test-kaas-ui
156 * ignore_failed: false
157 * parameters:
158 * KUBECONFIG_ARTIFACT_URL:
159 * type: StringParameterValue
160 * use_variable: KUBECONFIG_ARTIFACT
161 * artifacts:
162 * REPORT_SI_KAAS_UI: artifacts/test_kaas_ui_result.xml
163 *
164 * finally:
165 * - job: testrail-report
166 * ignore_failed: true
167 * parameters:
168 * REPORT_SI_KAAS_UI_URL:
169 * type: StringParameterValue
170 * use_variable: REPORT_SI_KAAS_UI
171 * """
172 *
173 * runScenario(scenario)
174 *
175 */
176
177def runScenario(scenario) {
178
179 // Collect the parameters for the jobs here
180 global_variables = [:]
181 // List of failed jobs to show at the end
182 failed_jobs = [:]
183
184 try {
185 // Run the 'workflow' jobs
186 runSteps(scenario['workflow'], global_variables, failed_jobs)
187
188 } catch (InterruptedException x) {
189 error "The job was aborted"
190
191 } catch (e) {
192 error("Build failed: " + e.toString())
193
194 } finally {
195 // Run the 'finally' jobs
196 runSteps(scenario['finally'], global_variables, failed_jobs)
197
198 if (failed_jobs) {
199 println "Failed jobs: ${failed_jobs}"
200 currentBuild.result = "FAILED"
201 }
202 } // try
203}