blob: 6a35dd698351551608e01cde7111139dc3b85939 [file] [log] [blame]
Jakub Josef6ee6f992017-01-27 16:16:04 +01001import java.util.regex.Pattern
2/**
3 *
Jakub Joseffc2f2412017-02-27 15:14:07 +01004 * OS images build pipeline
Jakub Josef6ee6f992017-01-27 16:16:04 +01005 *
azvyagintsev01785672018-02-27 17:33:14 +02006 * Target build slave node:
7 * target-build-slave: [ qemu ]
8 *
9 * This pipeline require to have slave with such dep's:
10 * ubuntu-pkgs: [ qemu-kvm, libvirt-bin, cloud-image-utils ]
11 *
Jakub Josef6ee6f992017-01-27 16:16:04 +010012 * Expected parameters:
13 * BUILD_OS
14 * BUILD_ONLY
15 * PACKER_DEBUG
16 * PACKER_URL
17 * PACKER_ZIP
18 * PACKER_ZIP_MD5
19 * PACKER_ARGS
20 * UPLOAD_URL
21 * SKIP_UPLOAD
22 * CLEANUP_OLD
23 * CLEANUP_KEEP
24 * PIPELINE_LIBS_URL
25 * PIPELINE_LIBS_BRANCH
26 * PIPELINE_LIBS_CREDENTIALS_ID
Jakub Joseffc2f2412017-02-27 15:14:07 +010027 * GLANCE_UPLOAD
28 * GLANCE_IMG_TYPES
29 * GLANCE_URL
30 * GLANCE_CREDENTIALS_ID
31 * GLANCE_PROJECT
32 * GLANCE_ARGS
33 * OPENSTACK_API_CLIENT
Jakub Josef6ee6f992017-01-27 16:16:04 +010034 */
35
Jakub Josef6ee6f992017-01-27 16:16:04 +010036// Load shared libs
Jakub Joseffc2f2412017-02-27 15:14:07 +010037common = new com.mirantis.mk.Common()
Jakub Josef6ee6f992017-01-27 16:16:04 +010038
azvyagintsev6d453852018-02-26 16:56:37 +020039timeout(time: 12, unit: 'HOURS') {
Jakub Josef6ee6f992017-01-27 16:16:04 +010040node('qemu') {
41 // Define global variables
42 def workspace = common.getWorkspace()
43 def buildTypes = BUILD_ONLY.tokenize(" ")
Jakub Joseffc2f2412017-02-27 15:14:07 +010044 def createdImages=[]
45 def uploadedImages=[]
46 def cleanedImages=[]
47
Jakub Josef6ee6f992017-01-27 16:16:04 +010048 checkout scm
49 try {
50 stage("prepare") {
51 if (!fileExists("${workspace}/tmp")) {
52 sh "mkdir -p ${workspace}/tmp"
53 }
54 if (!fileExists("${workspace}/images")) {
55 sh "mkdir ${workspace}/images"
56 }
57 }
58 if (!fileExists("bin")) {
Jakub Josefeb98c8e2017-03-13 18:13:58 +010059 common.infoMsg("Downloading packer")
Jakub Josef6ee6f992017-01-27 16:16:04 +010060 sh "mkdir bin"
61 dir("bin") {
62 sh "wget -O ${PACKER_ZIP} ${PACKER_URL}"
63 sh "echo \"${PACKER_ZIP_MD5} ${PACKER_ZIP}\" >> md5sum"
64 sh "md5sum -c --status md5sum"
65 sh "unzip ${PACKER_ZIP}"
66 }
67 }
Jakub Joseffc2f2412017-02-27 15:14:07 +010068 // clean images dir before building
69 sh(script: String.format("rm -rf %s/images/*", BUILD_OS), returnStatus: true)
70 // clean virtualenv is exists
71 sh(script: String.format("rm -rf %s/venv", workspace), returnStatus: true)
72
Jakub Josef6ee6f992017-01-27 16:16:04 +010073 stage("build") {
74 dir(BUILD_OS) {
75 withEnv([String.format("PATH=%s:%s/bin", env.PATH, workspace),
76 "PACKER_LOG_PATH=${workspace}/packer.log",
77 "PACKER_LOG=1",
78 "TMPDIR=${workspace}/tmp"
79 ]) {
80 if (PACKER_DEBUG == 'true') {
81 PACKER_ARGS = "${PACKER_ARGS} -debug"
82 }
Filip Pytloun35640b62017-02-23 09:45:34 +010083
alexz5b795142018-02-13 15:59:28 +010084 if (fileExists("config-drive/user-data.yaml")) {
85 common.infoMsg("Creating cloud-config drive")
86 if (fileExists("config-drive/cloudata.iso")) {
87 sh "rm -v config-drive/cloudata.iso"
88 }
89 sh "cloud-localds config-drive/cloudata.iso config-drive/user-data.yaml"
90 }
Jakub Josef502bac22017-09-04 15:57:25 +020091 sh "packer build -only=${BUILD_ONLY} ${PACKER_ARGS} -parallel=false template.json"
Filip Pytloun35640b62017-02-23 09:45:34 +010092
Jakub Josef6ee6f992017-01-27 16:16:04 +010093 def packerStatus = sh(script: "grep \"Some builds didn't complete successfully and had errors\" ${PACKER_LOG_PATH}", returnStatus: true)
94 // grep returns 0 if find something
95 if (packerStatus != 0) {
96 if (buildTypes.contains("qemu")) {
97 def imageQemu = sh(script: "find images/ | grep -- '-qemu-' | tail -1", returnStdout: true).trim()
98 if (imageQemu != null && imageQemu != "") {
99 def qemuConvertStatus = sh(script: "qemu-img convert -c -O qcow2 ${imageQemu} ${imageQemu}.qcow2", returnStatus:true)
100 if(qemuConvertStatus == 0){
Jakub Joseffc2f2412017-02-27 15:14:07 +0100101 def imageDir = imageQemu.substring(0, imageQemu.lastIndexOf("/") + 1)
102 def imageQemuName = imageQemu.substring(imageQemu.lastIndexOf("/") + 1)
Jakub Josefc6bcfd72017-02-14 18:14:28 +0100103 def moveResult = sh(script: "mv ${imageQemu}.qcow2 ${imageDir}..", returnStatus: true)
104 if(moveResult == 0){
105 sh "rm -rf ${imageDir}"
106 sh "rm -f ${imageQemu}"
Jakub Joseffc2f2412017-02-27 15:14:07 +0100107 createdImages.add(imageQemuName+".qcow2")
Jakub Josefc6bcfd72017-02-14 18:14:28 +0100108 }
Jakub Josef6ee6f992017-01-27 16:16:04 +0100109 }else{
110 throw new Exception("Qemu image convert failed")
111 }
112 }
113 }
114 if (buildTypes.contains("docker")) {
115 def imageDocker = sh(script: "find images/ | grep -- '-docker-' | grep '.tar\$' | tail -1", returnStdout: true).trim()
116 if (imageDocker != null && imageDocker != "") {
117 def pbZip2Status = sh(script: "pbzip2 ${imageDocker}", returnStatus: true)
118 if(pbZip2Status == 0){
119 sh "rm -f ${imageDocker}"
Jakub Joseffc2f2412017-02-27 15:14:07 +0100120 createdImages.add(imageDocker+".bz2")
Jakub Josef6ee6f992017-01-27 16:16:04 +0100121 }else{
122 throw new Exception("pbzip2 image convert failed")
123 }
124 }
125 }
azvyagintsev6d453852018-02-26 16:56:37 +0200126
Jakub Josef6ee6f992017-01-27 16:16:04 +0100127 } else {
128 throw new Exception("Packer build failed")
129 }
130 }
131 }
132 }
133 stage("upload"){
134 dir(BUILD_OS + "/images") {
135 def images = findFiles(glob: "*.*")
Jakub Josef6ee6f992017-01-27 16:16:04 +0100136 def imageBuilds = [:]
Jakub Joseffc2f2412017-02-27 15:14:07 +0100137 def openstack = new com.mirantis.mk.Openstack()
138 def openstackEnv = String.format("%s/venv", workspace);
139 def openstackVersion = OPENSTACK_API_CLIENT ? OPENSTACK_API_CLIENT : 'liberty'
140 def rcFile = openstack.createOpenstackEnv(GLANCE_URL, GLANCE_CREDENTIALS_ID, GLANCE_PROJECT)
141 def glanceImgTypes = GLANCE_IMG_TYPES.tokenize(" ")
142 openstack.setupOpenstackVirtualenv(openstackEnv, openstackVersion)
143 openstack.runOpenstackCommand("pip install python-glanceclient==1.0.0", rcFile, openstackEnv)
Jakub Josef6ee6f992017-01-27 16:16:04 +0100144 for (int i = 0; i < images.size(); i++) {
145 def imageName = images[i].name
146 def imageNameList = imageName.tokenize(".")
147 def imageType = "." + imageNameList[imageNameList.size() - 1]
148 if(imageType.equals(".md5")){
149 continue;
150 }
Jakub Joseffc2f2412017-02-27 15:14:07 +0100151
Jakub Josef6ee6f992017-01-27 16:16:04 +0100152 imageBuilds["build${i}"]={
153 if (SKIP_UPLOAD != 'true') {
154 sh "md5sum ${imageName} > ${imageName}.md5"
Jakub Josefeb98c8e2017-03-13 18:13:58 +0100155 common.infoMsg("Uploading image " + imageName)
Jakub Josef6ee6f992017-01-27 16:16:04 +0100156 def uploadImageStatus = sh(script: "curl -f -T ${imageName} ${UPLOAD_URL}", returnStatus: true)
157 def uploadMd5Status = sh(script: "curl -f -T ${imageName}.md5 ${UPLOAD_URL}", returnStatus: true)
Jakub Josef469d26a2017-03-28 17:55:02 +0200158 // upload latest
159 def latestImageName = imageName.substring(0, imageName.lastIndexOf("-")) + "-latest" + imageType
160 common.infoMsg("Uploading image ${imageName} as latest")
161 def uploadLatestStatus = sh(script: "curl -f -T ${imageName} ${UPLOAD_URL}${latestImageName}", returnStatus: true)
162 def uploadLatestMd5Status = sh(script: "curl -f -T ${imageName}.md5 ${UPLOAD_URL}${latestImageName}.md5", returnStatus: true)
163 if(uploadLatestStatus != 0 || uploadLatestMd5Status != 0){
164 common.errorMsg("Latest image upload failed")
165 }
Jakub Joseffc2f2412017-02-27 15:14:07 +0100166 if (GLANCE_UPLOAD == 'true' && glanceImgTypes.contains(imageType.substring(1))) {
167 def glanceRunArgs = String.format("%s --disk-format %s --container-format bare", GLANCE_ARGS, imageType.substring(1))
168 if (GLANCE_PUBLIC == 'true') {
169 glanceRunArgs += " --visibility public"
170 }
171
172 def imageShortName = imageNameList.get(0)
173 openstack.runOpenstackCommand(String.format("glance image-create --name '%s' %s --file %s", imageShortName, glanceRunArgs, imageName), rcFile, openstackEnv)
174 }
Jakub Josef6ee6f992017-01-27 16:16:04 +0100175 if(uploadImageStatus==0 && uploadMd5Status == 0){
176 uploadedImages.add(imageName)
Jakub Josefc6bcfd72017-02-14 18:14:28 +0100177 sh(String.format("rm -r %s %s.md5",imageName, imageName))
Jakub Joseffc2f2412017-02-27 15:14:07 +0100178 createdImages.remove(imageName)
Jakub Josef6ee6f992017-01-27 16:16:04 +0100179 }else{
180 throw new Exception("Image upload failed")
181 }
182 }
183 if (CLEANUP_OLD == 'true') {
184 def remoteImages = sh(script: "curl -f -sss ${UPLOAD_URL} | grep -Eo '>.*\\.(qcow2|box|tar\\.bz2)</a>' | sed -e 's,>,,g' -e 's,</a,,g'", returnStdout: true)
185 if (remoteImages != "") {
186 def cleanupImages = getCleanupImageList(remoteImages, imageType, BUILD_OS)
187 def deleteCount = cleanupImages.size() - Integer.parseInt(CLEANUP_KEEP)
188 if (deleteCount > 0) {
189 for (int j = 0; j < deleteCount; j++) {
Jakub Josefeb98c8e2017-03-13 18:13:58 +0100190 common.infoMsg(String.format("Deleting image %s from aptly", cleanupImages[j]))
Jakub Josefc6bcfd72017-02-14 18:14:28 +0100191 sh "curl -f -X DELETE ${UPLOAD_URL}" + cleanupImages[j]
192 sh "curl -f -X DELETE ${UPLOAD_URL}" + cleanupImages[j] + ".md5"
Jakub Josef6ee6f992017-01-27 16:16:04 +0100193 cleanedImages.add(cleanupImages[j])
194 }
195 }
196 }
197 }
198 }
199 }
200 parallel imageBuilds
Jakub Josefeb98c8e2017-03-13 18:13:58 +0100201 common.infoMsg(String.format("Uploaded %s images with names %s", uploadedImages.size(), uploadedImages.toString()))
202 common.infoMsg(String.format("Cleaned %s images with names %s", cleanedImages.size(), cleanedImages.toString()))
Jakub Josef6ee6f992017-01-27 16:16:04 +0100203 }
204 }
205 } catch (Throwable e) {
206 // If there was an error or exception thrown, the build failed
207 currentBuild.result = "FAILURE"
208 throw e
209 } finally {
210 common.sendNotification(currentBuild.result, "", ["slack"])
211 if (buildTypes.contains("docker")) {
212 withEnv(["PACKER_LOG_PATH=${workspace}/packer.log"]) {
213 sh "docker rmi --force \$(grep \"docker: Image ID:\" ${PACKER_LOG_PATH} | cut -d : -f 6 | head -1 | sed s,\\ ,,g) || true"
214 }
215 }
Jakub Joseffc2f2412017-02-27 15:14:07 +0100216 // clean created images if error occured
217 if(!createdImages.isEmpty()){
218 dir(BUILD_OS + "/images"){
219 for(int i=0;i<createdImages.size();i++){
220 sh String.format("rm -f %s",createdImages.get(i))
221 }
222 }
223 }
Jakub Josef6ee6f992017-01-27 16:16:04 +0100224 }
225}
226
227@NonCPS
228def getCleanupImageList(remoteImagesString, imageType, osImage) {
229 def remoteImages = remoteImagesString.tokenize("\n")
230 def imageTypeForRegex = Pattern.quote(imageType)
Jakub Josefc6bcfd72017-02-14 18:14:28 +0100231 def osImageForRegex = Pattern.quote(osImage.replaceAll(/\./,"-"))
232 def remoteImagesSameType = remoteImages.findAll { it ->
233 it =~ /${imageTypeForRegex}$/
Jakub Josef6ee6f992017-01-27 16:16:04 +0100234 }
Jakub Josef338a1cb2018-01-10 18:50:51 +0100235 def imagesToClean = remoteImagesSameType.toSorted().findAll { it ->
Jakub Josefc6bcfd72017-02-14 18:14:28 +0100236 it =~ /^${osImageForRegex}-/
Jakub Josef6ee6f992017-01-27 16:16:04 +0100237 }
Jakub Josef338a1cb2018-01-10 18:50:51 +0100238 // dont cleanup non timestamp images
239 return imageToClean.findAll { it ->
240 it =~ /${osImageForRegex}-x(64|32)-\d+${imageTypeForRegex}/
241 }
Filip Pytloun35640b62017-02-23 09:45:34 +0100242}
azvyagintsev6d453852018-02-26 16:56:37 +0200243}