blob: 439f40a86f994dbf7bf9cc515dd756c8dd899e02 [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)
66
67// Self-check
68for (String req_v : ['BUILD_OS', 'BUILD_ONLY','IMAGE_NAME'] ) {
69 if (!job_env.get(req_v, false)) {
70 throw new Exception("${req_v} not set!")
71 }
72}
73
74def MapToList(input_map) {
75/**
76 * Convert dict in bash-like list
77 */
azvyagintsev68786a12018-07-10 14:42:29 +030078 def data_list = []
azvyagintsev68786a12018-07-10 14:42:29 +030079 for (i = 0; i < input_map.size(); i++) {
80 data = ''
81 data = input_map.keySet()[i] + "=" + input_map.values()[i]
82 data_list.add(data)
83 }
azvyagintsev68786a12018-07-10 14:42:29 +030084 return data_list
azvyagintsev68786a12018-07-10 14:42:29 +030085}
86
87timeout(time: 6, unit: 'HOURS') {
88 node("jsl15.mcp.mirantis.net") {
89 def checkouted = false
azvyagintsevf2c70cc2018-07-12 12:19:11 +030090 def workspace = common.getWorkspace()
91 creds = common.getPasswordCredentials(job_env.CREDENTIALS_ID)
92 if (job_env.BUILD_ONLY == 'openstack' || job_env.PUBLISH_BACKEND == 'glance') {
93 rcFile = openstack.createOpenstackEnv(workspace, os_openrc.OS_AUTH_URL, job_env.OS_TENANT_ID, job_env.OS_TENANT_NAME, "default", "", "default", "2", "")
94 def openstackEnv = "${workspace}/venv"
95 }
azvyagintsev68786a12018-07-10 14:42:29 +030096
97 try {
azvyagintsev68786a12018-07-10 14:42:29 +030098 def _artifact_dir = "${workspace}/artifacts"
azvyagintsevf2c70cc2018-07-12 12:19:11 +030099 def _artifact_list = []
azvyagintsev68786a12018-07-10 14:42:29 +0300100 def ImagesCacheFolder = "${workspace}/../${env.JOB_NAME}_cache/"
101 stage("checkout") {
102 if (defaultGitRef && defaultGitUrl) {
103 checkouted = gerrit.gerritPatchsetCheckout(defaultGitUrl, defaultGitRef, "HEAD", job_env.CREDENTIALS_ID)
104 } else {
105 throw new Exception("Cannot checkout gerrit patchset: DEFAULT_GIT_URL is null")
106 }
107 }
108 stage("Prepare env") {
109 if (!fileExists("${workspace}/tmp")) {
110 sh "mkdir -p ${workspace}/tmp"
111 }
112 if (!fileExists(ImagesCacheFolder)) {
113 sh "mkdir -p ${ImagesCacheFolder}"
114 }
115 if (!fileExists(_artifact_dir)) {
116 sh "mkdir -p ${_artifact_dir}"
117 }
118 if (!fileExists("bin")) {
119 common.infoMsg("Downloading packer")
120 sh "mkdir -p bin"
121 dir("bin") {
122 def zipname = sh(script: "basename ${job_env.PACKER_URL}", returnStdout: true).trim()
123 sh(script: "wget --quiet ${job_env.PACKER_URL}", returnStdout: true)
124 sh "echo \"${job_env.PACKER_ZIP_MD5} ${zipname}\" >> md5sum"
125 sh(script: "md5sum -c --status md5sum", returnStdout: true)
126 sh "unzip ${zipname}"
127 }
128 }
129 if (!fileExists("${job_env.BUILD_OS}/images")) {
130 // clean images dir before building
131 sh(script: "rm -rf ${job_env.BUILD_OS}/images/*", returnStatus: true)
132 }
133 }
134
135 stage("Build Instance") {
136 def _packer_args = "${job_env.get(PACKER_ARGS, '')}"
137 def _packer_log = "${workspace}/packer.log"
azvyagintsev68786a12018-07-10 14:42:29 +0300138 // clean old log, for correct status grepping
139 if (fileExists(_packer_log)) {
140 sh "rm -v ${_packer_log}"
141 }
142
143 dir("${workspace}/${job_env.BUILD_OS}/") {
144 if (fileExists("config-drive/user-data.yaml")) {
145 common.infoMsg("Creating cloud-config drive")
146 if (fileExists("config-drive/cloudata.iso")) {
147 sh "rm -v config-drive/cloudata.iso"
148 }
149 sh "cloud-localds config-drive/cloudata.iso config-drive/user-data.yaml"
150 }
151 }
152
azvyagintsevf2c70cc2018-07-12 12:19:11 +0300153 if (job_env.BUILD_ONLY == "openstack") {
azvyagintsev68786a12018-07-10 14:42:29 +0300154 dir("${workspace}/${job_env.BUILD_OS}/") {
155 extra_vars_list = MapToList(extra_vars)
156 withEnv(["PATH=${env.PATH}:${workspace}/bin",
157 "PACKER_LOG_PATH=${_packer_log}",
158 "PACKER_LOG=1",
159 "TMPDIR=${workspace}/tmp",
160 "OS_USERNAME=${creds.username.toString()}",
161 "OS_PASSWORD=${creds.password.toString()}"] + extra_vars_list) {
162
163 common.infoMsg("Run build with:")
164 sh(script: 'printenv|sort')
165 sh(script: "set -xe; packer build -only='openstack' ${_packer_args} -parallel=false template.json" )
166 _os_private = "${workspace}/${job_env.BUILD_OS}/os_${job_env.BUILD_OS}.pem"
167 if (fileExists(_os_private)) {
168 common.infoMsg("Packer private key:")
169 sh "cat ${_os_private}"
170 }
171 def packerStatus = sh(script: "grep \"Some builds didn't complete successfully and had errors\" ${_packer_log}", returnStatus: true)
172 // grep returns 0 if find something
173 if (packerStatus != 0) {
174 common.infoMsg("Openstack instance build complete")
175 } else {
176 throw new Exception("Openstack Packer build failed")
177 }
178
179 common.retry(3, 5) {
180 common.infoMsg("Attempt download openstack image..")
azvyagintsevf2c70cc2018-07-12 12:19:11 +0300181 openstack.runOpenstackCommand("openstack image save --file ${_artifact_dir}/${imageName}.qcow2 ${imageName}", rcFile, openstackEnv)
azvyagintsev68786a12018-07-10 14:42:29 +0300182 }
183 }
184 }
185
azvyagintsevf2c70cc2018-07-12 12:19:11 +0300186 } else if (job_env.BUILD_ONLY == 'qemu') {
azvyagintsev68786a12018-07-10 14:42:29 +0300187
188 dir("${workspace}/${job_env.BUILD_OS}/") {
189 extra_vars_list = MapToList(extra_vars)
190 withEnv(["PATH=${env.PATH}:${workspace}/bin",
191 "PACKER_LOG_PATH=${_packer_log}",
192 "PACKER_LOG=1",
193 "TMPDIR=${workspace}/tmp",
194 "PACKER_IMAGES_CACHE=${ImagesCacheFolder}"] + extra_vars_list) {
195 common.infoMsg("Run build with:")
196 sh(script: 'printenv|sort')
197 sh(script: "set -xe ; packer build -on-error=ask -only='qemu' ${_packer_args} -parallel=false template.json".toString())
198
199 def packerStatus = sh(script: "grep \"Some builds didn't complete successfully and had errors\" ${PACKER_LOG_PATH}", returnStatus: true)
200 // grep returns 0 if find something
201 if (packerStatus != 0) {
202 common.infoMsg("qemu instance build completed successfully")
203 } else {
204 throw new Exception("qemu instance build failed")
205 }
206 // collect artifacts
207 // TODO make it possible, process multiply artifacts by one run.
208 dir('images/') {
azvyagintsevf2c70cc2018-07-12 12:19:11 +0300209 def _files = findFiles(glob: "*qemu*/${imageName}*")
azvyagintsev68786a12018-07-10 14:42:29 +0300210 if (_files.size() > 1) {
211 common.warningMsg("Multiply artifacts detected!Only first one will be processed!")
212 } else if (_files.size() == 0) {
azvyagintsevf2c70cc2018-07-12 12:19:11 +0300213 throw new Exception("No artifacts detected!BUILD_ONLY=${env.BUILD_ONLY} failed!")
azvyagintsev68786a12018-07-10 14:42:29 +0300214 }
215 for (String x : _files) {
216 _file = sh(script: "set -x ; readlink -f ${x}", returnStdout: true)
azvyagintsevf2c70cc2018-07-12 12:19:11 +0300217 sh(script: "mv -v ${x} ${_artifact_dir}/${imageName}.qcow2")
218 // Save filename to list
219 _artifact_list.add("${imageName}.qcow2")
azvyagintsev68786a12018-07-10 14:42:29 +0300220 }
221 }
222 }
223 }
224
225 } else {
226 throw new Exception("Unexpected BUILD_ONLY=${env.BUILD_ONLY} target!")
227 }
azvyagintsev68786a12018-07-10 14:42:29 +0300228 }
229
230 stage("Publish artifacts") {
231 dir(_artifact_dir) {
232 common.infoMsg("Processing md5 for artifacts")
233 for (String x : _artifact_list) {
azvyagintsevf2c70cc2018-07-12 12:19:11 +0300234 _md5 = sh(script: "md5sum ${x} > ${x}.md5; cat ${x}.md5", returnStdout: true).trim()
azvyagintsev68786a12018-07-10 14:42:29 +0300235 _size = sh(script: "ls -alh ${x}", returnStdout: true).trim()
236 common.infoMsg("Artifact file: ${_size}\n${_md5}")
237 }
azvyagintsevf2c70cc2018-07-12 12:19:11 +0300238 if (job_env.PUBLISH_BACKEND == 'local') {
azvyagintsev68786a12018-07-10 14:42:29 +0300239 common.infoMsg("Uploading to: local")
240 common.infoMsg("For local publish target - nothing to do, all files in: ${_artifact_dir}")
241 if (job_env.get('CLEANUP_AFTER', false)) {
242 common.warningMsg("You are trying to use 'local' publish method, along with enabled CLEANUP_AFTER! ")
243 common.warningMsg("Disabling CLEANUP_AFTER option, to save you'r data ;) ")
244 job_env.CLEANUP_AFTER = false
245 }
azvyagintsevf2c70cc2018-07-12 12:19:11 +0300246 } else if (job_env.PUBLISH_BACKEND == 'glance') {
247 common.infoMsg("Uploading to: glance-openstack")
azvyagintsev68786a12018-07-10 14:42:29 +0300248 if (fileExists("${workspace}/venv")) {
249 common.infoMsg("cleaning virtualenv at:${workspace}/venv")
250 sh(script: "rm -rf ${workspace}/venv", returnStatus: true)
251 }
252 openstack.setupOpenstackVirtualenv(openstackEnv, job_env.OS_VERSION)
azvyagintsevf2c70cc2018-07-12 12:19:11 +0300253 for (String x : findFiles(glob: "*.*")) {
254 if (x.endsWith('.md5')) {
255 common.warningMsg("Skipping:${x} from openstack upload!")
256 _md5sum = sh(script: "cat ${x}", returnStdout: true).trim().split()[0]
257 continue
258 }
259 _property = "--property data=${dateTime} --property md5sum=${_md5sum}"
260 _cmdline = String.format("glance image-create --visibility " +
261 "public %s --name '%s' %s --file %s", _property, imageShortName, glanceRunArgs, imageName)
262 openstack.runOpenstackCommand(_cmdline, rcFile, openstackEnv)
azvyagintsev68786a12018-07-10 14:42:29 +0300263 }
azvyagintsevf2c70cc2018-07-12 12:19:11 +0300264 // TODO
265 currentBuild.description = "${imageName}.qcow2 uploaded tenant: "
azvyagintsev68786a12018-07-10 14:42:29 +0300266
azvyagintsevf2c70cc2018-07-12 12:19:11 +0300267 } else if (job_env.PUBLISH_BACKEND == 'http') {
268 for (String u_file : findFiles(glob: '*.*')) {
269 common.infoMsg("Uploading image ${imageName}")
azvyagintsev68786a12018-07-10 14:42:29 +0300270 def uploadImageStatus = ''
271 common.retry(3, 5) {
azvyagintsevf2c70cc2018-07-12 12:19:11 +0300272 uploadImageStatus = sh(script: "curl -f -T ${u_file} ${job_env.UPLOAD_URL}", returnStatus: true)
azvyagintsev68786a12018-07-10 14:42:29 +0300273 if (uploadImageStatus != 0) {
274 throw new Exception("Uploading file: ${u_file} failed!")
275 }
276 }
azvyagintsevf2c70cc2018-07-12 12:19:11 +0300277 // Fixme for correct path ?
278 currentBuild.description = "<a href='http://ci.mcp.mirantis.net:8085/images/${imageName}.qcow2'>${imageName}.qcow2</a>"
azvyagintsev68786a12018-07-10 14:42:29 +0300279 }
azvyagintsevf2c70cc2018-07-12 12:19:11 +0300280
azvyagintsev68786a12018-07-10 14:42:29 +0300281 } else {
282 throw new Exception("Unsupported publish backend:${job_env.PUBLISH_BACKEND}")
283 }
284
285 }
286 }
287 } catch (Throwable e) {
288 // If there was an error or exception thrown, the build failed
289 currentBuild.result = "FAILURE"
290 throw e
291 } finally {
292 if (job_env.get('CLEANUP_AFTER', false)) {
293 dir(workspace) {
azvyagintsevf2c70cc2018-07-12 12:19:11 +0300294 sh "find . -mindepth 1 -delete || true"
295 }
296 if (job_env.BUILD_ONLY == 'openstack') {
297 common.warningMsg("openstack Env cleanup not implemented yet!")
azvyagintsev68786a12018-07-10 14:42:29 +0300298 }
299 } else {
azvyagintsevf2c70cc2018-07-12 12:19:11 +0300300 common.warningMsg("Env has not been cleaned!Please cleanup it manualy!")
azvyagintsev68786a12018-07-10 14:42:29 +0300301 }
302 }
303 }
304}