blob: 0e53b5da1dbe229f3c2f6d5caad210b89d894f57 [file] [log] [blame]
azvyagintsev68786a12018-07-10 14:42:29 +03001/**
2 *
3 * Build mirror/aptly/apt01 image pipeline
4 *
5 * PACKER_URL = 'https://releases.hashicorp.com/packer/1.2.4/packer_1.2.4_linux_amd64.zip'
6 * PACKER_ZIP_MD5 = '997274e80ae41102eecf9df2e5b67860'
7 * PACKER_ARGS = '-debug'
8 * BUILD_ONLY = 'openstack|qemu'
9 * CLEANUP_AFTER = wipe workspace AFTER build
10 * IMAGE_NAME = Name of the result image.
11 * TIMESTAMP_INAME = True|false. If true - image will be uploaded to backend with IMAGE_NAME + timestamp
12 *
13 * OPENSTACK_OPENRC_YAML: aml of key:value variables required for openstack venv
14 * example:
15 * ---
16 * OS_TENANT_ID: 'xxxx'
17 * OS_TENANT_NAME: "mcp-oscore-ci"
18 *
19 * EXTRA_VARIABLES_YAML - Yaml of key:value variables required for template.json
20 * example:
21 * ---
22 * IMAGE_NAME: 'ubuntu-16.04-proposed'
23 *
24 * CREDENTIALS_ID = Global jenkins cred. for clone DEFAULT_GIT_URL
25 * DEFAULT_GIT_URL
26 * DEFAULT_GIT_REF
27 *
28 * OS_VERSION = OpenStack version
29 * OS_CREDENTIALS_ID = ID of credentials for OpenStack API stored in Jenkins.
30 * OS_URL = Keystone auth endpoint of the OpenStack.
31 * OS_PROJECT =
32 *
33 * PUBLISH_BACKEND = local|glance|http
34 * UPLOAD_URL = URL of an WebDAV used to upload the image after creating.(Only in case PUBLISH_BACKEND == http)
35 */
36
37// Load shared libs
38def common = new com.mirantis.mk.Common()
azvyagintsev68786a12018-07-10 14:42:29 +030039def openstack = new com.mirantis.mk.Openstack()
azvyagintsevf2c70cc2018-07-12 12:19:11 +030040def gerrit = new com.mirantis.mk.Gerrit()
azvyagintsev68786a12018-07-10 14:42:29 +030041def date = new Date()
42def dateTime = date.format("ddMMyyyy-HHmmss")
43//
44def job_env = env.getEnvironment().findAll { k, v -> v }
45
azvyagintsev68786a12018-07-10 14:42:29 +030046/////
47extra_vars = readYaml text: job_env.get('EXTRA_VARIABLES_YAML','').trim()
azvyagintsevf2c70cc2018-07-12 12:19:11 +030048// FIXME: os_openrc should be refactored.
49os_openrc = readYaml text: job_env.get('OPENSTACK_OPENRC_YAML','').trim()
azvyagintsev4f9239d2018-07-18 16:47:15 +030050if (job_env.get('TIMESTAMP_INAME', false).toBoolean()) {
azvyagintsevf2c70cc2018-07-12 12:19:11 +030051 imageName = job_env.IMAGE_NAME + "-" + dateTime
52}else {
53 imageName = job_env.IMAGE_NAME
azvyagintsev68786a12018-07-10 14:42:29 +030054}
55// Overwrite IMAGE_NAME in template.json with expected
azvyagintsevf2c70cc2018-07-12 12:19:11 +030056extra_vars['IMAGE_NAME'] = imageName
azvyagintsev4f9239d2018-07-18 16:47:15 +030057// Fix some variables
58job_env['CLEANUP_AFTER'] = job_env.CLEANUP_AFTER.toBoolean()
59job_env['SKIP_UPLOAD'] = job_env.SKIP_UPLOAD.toBoolean()
60job_env['CLEANUP_AFTER'] = job_env.CLEANUP_AFTER.toBoolean()
azvyagintsevf2c70cc2018-07-12 12:19:11 +030061job_env['BUILD_ONLY'] = job_env.BUILD_ONLY.toLowerCase()
62job_env['PUBLISH_BACKEND'] = job_env.PUBLISH_BACKEND.toLowerCase()
63//
azvyagintsev68786a12018-07-10 14:42:29 +030064defaultGitRef = job_env.get('DEFAULT_GIT_REF', 'HEAD')
65defaultGitUrl = job_env.get('DEFAULT_GIT_URL', null)
azvyagintsev1f5028c2018-08-10 20:22:27 +030066slaveNode = (env.SLAVE_NODE ?: 'jsl23.mcp.mirantis.net')
azvyagintsev68786a12018-07-10 14:42:29 +030067
68// Self-check
69for (String req_v : ['BUILD_OS', 'BUILD_ONLY','IMAGE_NAME'] ) {
70 if (!job_env.get(req_v, false)) {
71 throw new Exception("${req_v} not set!")
72 }
73}
74
75def MapToList(input_map) {
76/**
77 * Convert dict in bash-like list
78 */
azvyagintsev68786a12018-07-10 14:42:29 +030079 def data_list = []
azvyagintsev68786a12018-07-10 14:42:29 +030080 for (i = 0; i < input_map.size(); i++) {
81 data = ''
82 data = input_map.keySet()[i] + "=" + input_map.values()[i]
83 data_list.add(data)
84 }
azvyagintsev68786a12018-07-10 14:42:29 +030085 return data_list
azvyagintsev68786a12018-07-10 14:42:29 +030086}
87
88timeout(time: 6, unit: 'HOURS') {
azvyagintsev1f5028c2018-08-10 20:22:27 +030089 node(slaveNode) {
azvyagintsev68786a12018-07-10 14:42:29 +030090 def checkouted = false
azvyagintsevf2c70cc2018-07-12 12:19:11 +030091 def workspace = common.getWorkspace()
92 creds = common.getPasswordCredentials(job_env.CREDENTIALS_ID)
93 if (job_env.BUILD_ONLY == 'openstack' || job_env.PUBLISH_BACKEND == 'glance') {
94 rcFile = openstack.createOpenstackEnv(workspace, os_openrc.OS_AUTH_URL, job_env.OS_TENANT_ID, job_env.OS_TENANT_NAME, "default", "", "default", "2", "")
95 def openstackEnv = "${workspace}/venv"
96 }
azvyagintsev68786a12018-07-10 14:42:29 +030097
98 try {
azvyagintsev68786a12018-07-10 14:42:29 +030099 def _artifact_dir = "${workspace}/artifacts"
azvyagintsevf2c70cc2018-07-12 12:19:11 +0300100 def _artifact_list = []
azvyagintsev68786a12018-07-10 14:42:29 +0300101 def ImagesCacheFolder = "${workspace}/../${env.JOB_NAME}_cache/"
102 stage("checkout") {
103 if (defaultGitRef && defaultGitUrl) {
104 checkouted = gerrit.gerritPatchsetCheckout(defaultGitUrl, defaultGitRef, "HEAD", job_env.CREDENTIALS_ID)
105 } else {
106 throw new Exception("Cannot checkout gerrit patchset: DEFAULT_GIT_URL is null")
107 }
108 }
109 stage("Prepare env") {
110 if (!fileExists("${workspace}/tmp")) {
111 sh "mkdir -p ${workspace}/tmp"
112 }
113 if (!fileExists(ImagesCacheFolder)) {
114 sh "mkdir -p ${ImagesCacheFolder}"
115 }
116 if (!fileExists(_artifact_dir)) {
117 sh "mkdir -p ${_artifact_dir}"
118 }
119 if (!fileExists("bin")) {
120 common.infoMsg("Downloading packer")
121 sh "mkdir -p bin"
122 dir("bin") {
123 def zipname = sh(script: "basename ${job_env.PACKER_URL}", returnStdout: true).trim()
124 sh(script: "wget --quiet ${job_env.PACKER_URL}", returnStdout: true)
125 sh "echo \"${job_env.PACKER_ZIP_MD5} ${zipname}\" >> md5sum"
126 sh(script: "md5sum -c --status md5sum", returnStdout: true)
127 sh "unzip ${zipname}"
128 }
129 }
130 if (!fileExists("${job_env.BUILD_OS}/images")) {
131 // clean images dir before building
132 sh(script: "rm -rf ${job_env.BUILD_OS}/images/*", returnStatus: true)
133 }
134 }
135
136 stage("Build Instance") {
137 def _packer_args = "${job_env.get(PACKER_ARGS, '')}"
138 def _packer_log = "${workspace}/packer.log"
azvyagintsev68786a12018-07-10 14:42:29 +0300139 // clean old log, for correct status grepping
140 if (fileExists(_packer_log)) {
141 sh "rm -v ${_packer_log}"
142 }
143
144 dir("${workspace}/${job_env.BUILD_OS}/") {
145 if (fileExists("config-drive/user-data.yaml")) {
146 common.infoMsg("Creating cloud-config drive")
147 if (fileExists("config-drive/cloudata.iso")) {
148 sh "rm -v config-drive/cloudata.iso"
149 }
150 sh "cloud-localds config-drive/cloudata.iso config-drive/user-data.yaml"
151 }
152 }
153
azvyagintsevf2c70cc2018-07-12 12:19:11 +0300154 if (job_env.BUILD_ONLY == "openstack") {
azvyagintsev68786a12018-07-10 14:42:29 +0300155 dir("${workspace}/${job_env.BUILD_OS}/") {
156 extra_vars_list = MapToList(extra_vars)
157 withEnv(["PATH=${env.PATH}:${workspace}/bin",
158 "PACKER_LOG_PATH=${_packer_log}",
159 "PACKER_LOG=1",
160 "TMPDIR=${workspace}/tmp",
161 "OS_USERNAME=${creds.username.toString()}",
162 "OS_PASSWORD=${creds.password.toString()}"] + extra_vars_list) {
163
164 common.infoMsg("Run build with:")
165 sh(script: 'printenv|sort')
166 sh(script: "set -xe; packer build -only='openstack' ${_packer_args} -parallel=false template.json" )
167 _os_private = "${workspace}/${job_env.BUILD_OS}/os_${job_env.BUILD_OS}.pem"
168 if (fileExists(_os_private)) {
169 common.infoMsg("Packer private key:")
170 sh "cat ${_os_private}"
171 }
172 def packerStatus = sh(script: "grep \"Some builds didn't complete successfully and had errors\" ${_packer_log}", returnStatus: true)
173 // grep returns 0 if find something
174 if (packerStatus != 0) {
175 common.infoMsg("Openstack instance build complete")
176 } else {
177 throw new Exception("Openstack Packer build failed")
178 }
179
180 common.retry(3, 5) {
181 common.infoMsg("Attempt download openstack image..")
azvyagintsevf2c70cc2018-07-12 12:19:11 +0300182 openstack.runOpenstackCommand("openstack image save --file ${_artifact_dir}/${imageName}.qcow2 ${imageName}", rcFile, openstackEnv)
azvyagintsev68786a12018-07-10 14:42:29 +0300183 }
184 }
185 }
186
azvyagintsevf2c70cc2018-07-12 12:19:11 +0300187 } else if (job_env.BUILD_ONLY == 'qemu') {
azvyagintsev68786a12018-07-10 14:42:29 +0300188
189 dir("${workspace}/${job_env.BUILD_OS}/") {
190 extra_vars_list = MapToList(extra_vars)
191 withEnv(["PATH=${env.PATH}:${workspace}/bin",
192 "PACKER_LOG_PATH=${_packer_log}",
193 "PACKER_LOG=1",
194 "TMPDIR=${workspace}/tmp",
195 "PACKER_IMAGES_CACHE=${ImagesCacheFolder}"] + extra_vars_list) {
196 common.infoMsg("Run build with:")
197 sh(script: 'printenv|sort')
198 sh(script: "set -xe ; packer build -on-error=ask -only='qemu' ${_packer_args} -parallel=false template.json".toString())
199
200 def packerStatus = sh(script: "grep \"Some builds didn't complete successfully and had errors\" ${PACKER_LOG_PATH}", returnStatus: true)
201 // grep returns 0 if find something
202 if (packerStatus != 0) {
203 common.infoMsg("qemu instance build completed successfully")
204 } else {
205 throw new Exception("qemu instance build failed")
206 }
207 // collect artifacts
208 // TODO make it possible, process multiply artifacts by one run.
209 dir('images/') {
azvyagintsev1f5028c2018-08-10 20:22:27 +0300210 sh(script: 'find .', returnStdout: true)
azvyagintsevf2c70cc2018-07-12 12:19:11 +0300211 def _files = findFiles(glob: "*qemu*/${imageName}*")
azvyagintsev68786a12018-07-10 14:42:29 +0300212 if (_files.size() > 1) {
213 common.warningMsg("Multiply artifacts detected!Only first one will be processed!")
214 } else if (_files.size() == 0) {
azvyagintsevf2c70cc2018-07-12 12:19:11 +0300215 throw new Exception("No artifacts detected!BUILD_ONLY=${env.BUILD_ONLY} failed!")
azvyagintsev68786a12018-07-10 14:42:29 +0300216 }
217 for (String x : _files) {
218 _file = sh(script: "set -x ; readlink -f ${x}", returnStdout: true)
azvyagintsevf2c70cc2018-07-12 12:19:11 +0300219 sh(script: "mv -v ${x} ${_artifact_dir}/${imageName}.qcow2")
220 // Save filename to list
221 _artifact_list.add("${imageName}.qcow2")
azvyagintsev68786a12018-07-10 14:42:29 +0300222 }
223 }
224 }
225 }
226
227 } else {
228 throw new Exception("Unexpected BUILD_ONLY=${env.BUILD_ONLY} target!")
229 }
azvyagintsev68786a12018-07-10 14:42:29 +0300230 }
231
232 stage("Publish artifacts") {
233 dir(_artifact_dir) {
234 common.infoMsg("Processing md5 for artifacts")
235 for (String x : _artifact_list) {
azvyagintsevf2c70cc2018-07-12 12:19:11 +0300236 _md5 = sh(script: "md5sum ${x} > ${x}.md5; cat ${x}.md5", returnStdout: true).trim()
azvyagintsev68786a12018-07-10 14:42:29 +0300237 _size = sh(script: "ls -alh ${x}", returnStdout: true).trim()
238 common.infoMsg("Artifact file: ${_size}\n${_md5}")
239 }
azvyagintsevf2c70cc2018-07-12 12:19:11 +0300240 if (job_env.PUBLISH_BACKEND == 'local') {
azvyagintsev68786a12018-07-10 14:42:29 +0300241 common.infoMsg("Uploading to: local")
242 common.infoMsg("For local publish target - nothing to do, all files in: ${_artifact_dir}")
243 if (job_env.get('CLEANUP_AFTER', false)) {
244 common.warningMsg("You are trying to use 'local' publish method, along with enabled CLEANUP_AFTER! ")
245 common.warningMsg("Disabling CLEANUP_AFTER option, to save you'r data ;) ")
246 job_env.CLEANUP_AFTER = false
247 }
azvyagintsevf2c70cc2018-07-12 12:19:11 +0300248 } else if (job_env.PUBLISH_BACKEND == 'glance') {
249 common.infoMsg("Uploading to: glance-openstack")
azvyagintsev68786a12018-07-10 14:42:29 +0300250 if (fileExists("${workspace}/venv")) {
251 common.infoMsg("cleaning virtualenv at:${workspace}/venv")
252 sh(script: "rm -rf ${workspace}/venv", returnStatus: true)
253 }
254 openstack.setupOpenstackVirtualenv(openstackEnv, job_env.OS_VERSION)
azvyagintsevf2c70cc2018-07-12 12:19:11 +0300255 for (String x : findFiles(glob: "*.*")) {
256 if (x.endsWith('.md5')) {
257 common.warningMsg("Skipping:${x} from openstack upload!")
258 _md5sum = sh(script: "cat ${x}", returnStdout: true).trim().split()[0]
259 continue
260 }
261 _property = "--property data=${dateTime} --property md5sum=${_md5sum}"
262 _cmdline = String.format("glance image-create --visibility " +
263 "public %s --name '%s' %s --file %s", _property, imageShortName, glanceRunArgs, imageName)
264 openstack.runOpenstackCommand(_cmdline, rcFile, openstackEnv)
azvyagintsev68786a12018-07-10 14:42:29 +0300265 }
azvyagintsevf2c70cc2018-07-12 12:19:11 +0300266 // TODO
267 currentBuild.description = "${imageName}.qcow2 uploaded tenant: "
azvyagintsev68786a12018-07-10 14:42:29 +0300268
azvyagintsevf2c70cc2018-07-12 12:19:11 +0300269 } else if (job_env.PUBLISH_BACKEND == 'http') {
270 for (String u_file : findFiles(glob: '*.*')) {
271 common.infoMsg("Uploading image ${imageName}")
azvyagintsev68786a12018-07-10 14:42:29 +0300272 def uploadImageStatus = ''
273 common.retry(3, 5) {
azvyagintsevf2c70cc2018-07-12 12:19:11 +0300274 uploadImageStatus = sh(script: "curl -f -T ${u_file} ${job_env.UPLOAD_URL}", returnStatus: true)
azvyagintsev68786a12018-07-10 14:42:29 +0300275 if (uploadImageStatus != 0) {
276 throw new Exception("Uploading file: ${u_file} failed!")
277 }
278 }
azvyagintsevf2c70cc2018-07-12 12:19:11 +0300279 // Fixme for correct path ?
280 currentBuild.description = "<a href='http://ci.mcp.mirantis.net:8085/images/${imageName}.qcow2'>${imageName}.qcow2</a>"
azvyagintsev68786a12018-07-10 14:42:29 +0300281 }
azvyagintsevf2c70cc2018-07-12 12:19:11 +0300282
azvyagintsev68786a12018-07-10 14:42:29 +0300283 } else {
284 throw new Exception("Unsupported publish backend:${job_env.PUBLISH_BACKEND}")
285 }
286
287 }
288 }
289 } catch (Throwable e) {
290 // If there was an error or exception thrown, the build failed
291 currentBuild.result = "FAILURE"
292 throw e
293 } finally {
294 if (job_env.get('CLEANUP_AFTER', false)) {
295 dir(workspace) {
azvyagintsevf2c70cc2018-07-12 12:19:11 +0300296 sh "find . -mindepth 1 -delete || true"
297 }
298 if (job_env.BUILD_ONLY == 'openstack') {
299 common.warningMsg("openstack Env cleanup not implemented yet!")
azvyagintsev68786a12018-07-10 14:42:29 +0300300 }
301 } else {
azvyagintsevf2c70cc2018-07-12 12:19:11 +0300302 common.warningMsg("Env has not been cleaned!Please cleanup it manualy!")
azvyagintsev68786a12018-07-10 14:42:29 +0300303 }
304 }
305 }
306}