blob: f4c1631b9e5c5e301b01d9d2ff0c69631eadbea2 [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
39node('qemu') {
40 // Define global variables
41 def workspace = common.getWorkspace()
42 def buildTypes = BUILD_ONLY.tokenize(" ")
Jakub Joseffc2f2412017-02-27 15:14:07 +010043 def createdImages=[]
44 def uploadedImages=[]
45 def cleanedImages=[]
46
Jakub Josef6ee6f992017-01-27 16:16:04 +010047 checkout scm
48 try {
49 stage("prepare") {
50 if (!fileExists("${workspace}/tmp")) {
51 sh "mkdir -p ${workspace}/tmp"
52 }
53 if (!fileExists("${workspace}/images")) {
54 sh "mkdir ${workspace}/images"
55 }
56 }
57 if (!fileExists("bin")) {
Jakub Josefeb98c8e2017-03-13 18:13:58 +010058 common.infoMsg("Downloading packer")
Jakub Josef6ee6f992017-01-27 16:16:04 +010059 sh "mkdir bin"
60 dir("bin") {
61 sh "wget -O ${PACKER_ZIP} ${PACKER_URL}"
62 sh "echo \"${PACKER_ZIP_MD5} ${PACKER_ZIP}\" >> md5sum"
63 sh "md5sum -c --status md5sum"
64 sh "unzip ${PACKER_ZIP}"
65 }
66 }
Jakub Joseffc2f2412017-02-27 15:14:07 +010067 // clean images dir before building
68 sh(script: String.format("rm -rf %s/images/*", BUILD_OS), returnStatus: true)
69 // clean virtualenv is exists
70 sh(script: String.format("rm -rf %s/venv", workspace), returnStatus: true)
71
Jakub Josef6ee6f992017-01-27 16:16:04 +010072 stage("build") {
73 dir(BUILD_OS) {
74 withEnv([String.format("PATH=%s:%s/bin", env.PATH, workspace),
75 "PACKER_LOG_PATH=${workspace}/packer.log",
76 "PACKER_LOG=1",
77 "TMPDIR=${workspace}/tmp"
78 ]) {
79 if (PACKER_DEBUG == 'true') {
80 PACKER_ARGS = "${PACKER_ARGS} -debug"
81 }
Filip Pytloun35640b62017-02-23 09:45:34 +010082
alexz5b795142018-02-13 15:59:28 +010083 if (fileExists("config-drive/user-data.yaml")) {
84 common.infoMsg("Creating cloud-config drive")
85 if (fileExists("config-drive/cloudata.iso")) {
86 sh "rm -v config-drive/cloudata.iso"
87 }
88 sh "cloud-localds config-drive/cloudata.iso config-drive/user-data.yaml"
89 }
Jakub Josef502bac22017-09-04 15:57:25 +020090 sh "packer build -only=${BUILD_ONLY} ${PACKER_ARGS} -parallel=false template.json"
Filip Pytloun35640b62017-02-23 09:45:34 +010091
Jakub Josef6ee6f992017-01-27 16:16:04 +010092 def packerStatus = sh(script: "grep \"Some builds didn't complete successfully and had errors\" ${PACKER_LOG_PATH}", returnStatus: true)
93 // grep returns 0 if find something
94 if (packerStatus != 0) {
95 if (buildTypes.contains("qemu")) {
96 def imageQemu = sh(script: "find images/ | grep -- '-qemu-' | tail -1", returnStdout: true).trim()
97 if (imageQemu != null && imageQemu != "") {
98 def qemuConvertStatus = sh(script: "qemu-img convert -c -O qcow2 ${imageQemu} ${imageQemu}.qcow2", returnStatus:true)
99 if(qemuConvertStatus == 0){
Jakub Joseffc2f2412017-02-27 15:14:07 +0100100 def imageDir = imageQemu.substring(0, imageQemu.lastIndexOf("/") + 1)
101 def imageQemuName = imageQemu.substring(imageQemu.lastIndexOf("/") + 1)
Jakub Josefc6bcfd72017-02-14 18:14:28 +0100102 def moveResult = sh(script: "mv ${imageQemu}.qcow2 ${imageDir}..", returnStatus: true)
103 if(moveResult == 0){
104 sh "rm -rf ${imageDir}"
105 sh "rm -f ${imageQemu}"
Jakub Joseffc2f2412017-02-27 15:14:07 +0100106 createdImages.add(imageQemuName+".qcow2")
Jakub Josefc6bcfd72017-02-14 18:14:28 +0100107 }
Jakub Josef6ee6f992017-01-27 16:16:04 +0100108 }else{
109 throw new Exception("Qemu image convert failed")
110 }
111 }
112 }
113 if (buildTypes.contains("docker")) {
114 def imageDocker = sh(script: "find images/ | grep -- '-docker-' | grep '.tar\$' | tail -1", returnStdout: true).trim()
115 if (imageDocker != null && imageDocker != "") {
116 def pbZip2Status = sh(script: "pbzip2 ${imageDocker}", returnStatus: true)
117 if(pbZip2Status == 0){
118 sh "rm -f ${imageDocker}"
Jakub Joseffc2f2412017-02-27 15:14:07 +0100119 createdImages.add(imageDocker+".bz2")
Jakub Josef6ee6f992017-01-27 16:16:04 +0100120 }else{
121 throw new Exception("pbzip2 image convert failed")
122 }
123 }
124 }
125 } else {
126 throw new Exception("Packer build failed")
127 }
128 }
129 }
130 }
131 stage("upload"){
132 dir(BUILD_OS + "/images") {
133 def images = findFiles(glob: "*.*")
Jakub Josef6ee6f992017-01-27 16:16:04 +0100134 def imageBuilds = [:]
Jakub Joseffc2f2412017-02-27 15:14:07 +0100135 def openstack = new com.mirantis.mk.Openstack()
136 def openstackEnv = String.format("%s/venv", workspace);
137 def openstackVersion = OPENSTACK_API_CLIENT ? OPENSTACK_API_CLIENT : 'liberty'
138 def rcFile = openstack.createOpenstackEnv(GLANCE_URL, GLANCE_CREDENTIALS_ID, GLANCE_PROJECT)
139 def glanceImgTypes = GLANCE_IMG_TYPES.tokenize(" ")
140 openstack.setupOpenstackVirtualenv(openstackEnv, openstackVersion)
141 openstack.runOpenstackCommand("pip install python-glanceclient==1.0.0", rcFile, openstackEnv)
Jakub Josef6ee6f992017-01-27 16:16:04 +0100142 for (int i = 0; i < images.size(); i++) {
143 def imageName = images[i].name
144 def imageNameList = imageName.tokenize(".")
145 def imageType = "." + imageNameList[imageNameList.size() - 1]
146 if(imageType.equals(".md5")){
147 continue;
148 }
Jakub Joseffc2f2412017-02-27 15:14:07 +0100149
Jakub Josef6ee6f992017-01-27 16:16:04 +0100150 imageBuilds["build${i}"]={
151 if (SKIP_UPLOAD != 'true') {
152 sh "md5sum ${imageName} > ${imageName}.md5"
Jakub Josefeb98c8e2017-03-13 18:13:58 +0100153 common.infoMsg("Uploading image " + imageName)
Jakub Josef6ee6f992017-01-27 16:16:04 +0100154 def uploadImageStatus = sh(script: "curl -f -T ${imageName} ${UPLOAD_URL}", returnStatus: true)
155 def uploadMd5Status = sh(script: "curl -f -T ${imageName}.md5 ${UPLOAD_URL}", returnStatus: true)
Jakub Josef469d26a2017-03-28 17:55:02 +0200156 // upload latest
157 def latestImageName = imageName.substring(0, imageName.lastIndexOf("-")) + "-latest" + imageType
158 common.infoMsg("Uploading image ${imageName} as latest")
159 def uploadLatestStatus = sh(script: "curl -f -T ${imageName} ${UPLOAD_URL}${latestImageName}", returnStatus: true)
160 def uploadLatestMd5Status = sh(script: "curl -f -T ${imageName}.md5 ${UPLOAD_URL}${latestImageName}.md5", returnStatus: true)
161 if(uploadLatestStatus != 0 || uploadLatestMd5Status != 0){
162 common.errorMsg("Latest image upload failed")
163 }
Jakub Joseffc2f2412017-02-27 15:14:07 +0100164 if (GLANCE_UPLOAD == 'true' && glanceImgTypes.contains(imageType.substring(1))) {
165 def glanceRunArgs = String.format("%s --disk-format %s --container-format bare", GLANCE_ARGS, imageType.substring(1))
166 if (GLANCE_PUBLIC == 'true') {
167 glanceRunArgs += " --visibility public"
168 }
169
170 def imageShortName = imageNameList.get(0)
171 openstack.runOpenstackCommand(String.format("glance image-create --name '%s' %s --file %s", imageShortName, glanceRunArgs, imageName), rcFile, openstackEnv)
172 }
Jakub Josef6ee6f992017-01-27 16:16:04 +0100173 if(uploadImageStatus==0 && uploadMd5Status == 0){
174 uploadedImages.add(imageName)
Jakub Josefc6bcfd72017-02-14 18:14:28 +0100175 sh(String.format("rm -r %s %s.md5",imageName, imageName))
Jakub Joseffc2f2412017-02-27 15:14:07 +0100176 createdImages.remove(imageName)
Jakub Josef6ee6f992017-01-27 16:16:04 +0100177 }else{
178 throw new Exception("Image upload failed")
179 }
180 }
181 if (CLEANUP_OLD == 'true') {
182 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)
183 if (remoteImages != "") {
184 def cleanupImages = getCleanupImageList(remoteImages, imageType, BUILD_OS)
185 def deleteCount = cleanupImages.size() - Integer.parseInt(CLEANUP_KEEP)
186 if (deleteCount > 0) {
187 for (int j = 0; j < deleteCount; j++) {
Jakub Josefeb98c8e2017-03-13 18:13:58 +0100188 common.infoMsg(String.format("Deleting image %s from aptly", cleanupImages[j]))
Jakub Josefc6bcfd72017-02-14 18:14:28 +0100189 sh "curl -f -X DELETE ${UPLOAD_URL}" + cleanupImages[j]
190 sh "curl -f -X DELETE ${UPLOAD_URL}" + cleanupImages[j] + ".md5"
Jakub Josef6ee6f992017-01-27 16:16:04 +0100191 cleanedImages.add(cleanupImages[j])
192 }
193 }
194 }
195 }
196 }
197 }
198 parallel imageBuilds
Jakub Josefeb98c8e2017-03-13 18:13:58 +0100199 common.infoMsg(String.format("Uploaded %s images with names %s", uploadedImages.size(), uploadedImages.toString()))
200 common.infoMsg(String.format("Cleaned %s images with names %s", cleanedImages.size(), cleanedImages.toString()))
Jakub Josef6ee6f992017-01-27 16:16:04 +0100201 }
202 }
203 } catch (Throwable e) {
204 // If there was an error or exception thrown, the build failed
205 currentBuild.result = "FAILURE"
206 throw e
207 } finally {
208 common.sendNotification(currentBuild.result, "", ["slack"])
209 if (buildTypes.contains("docker")) {
210 withEnv(["PACKER_LOG_PATH=${workspace}/packer.log"]) {
211 sh "docker rmi --force \$(grep \"docker: Image ID:\" ${PACKER_LOG_PATH} | cut -d : -f 6 | head -1 | sed s,\\ ,,g) || true"
212 }
213 }
Jakub Joseffc2f2412017-02-27 15:14:07 +0100214 // clean created images if error occured
215 if(!createdImages.isEmpty()){
216 dir(BUILD_OS + "/images"){
217 for(int i=0;i<createdImages.size();i++){
218 sh String.format("rm -f %s",createdImages.get(i))
219 }
220 }
221 }
Jakub Josef6ee6f992017-01-27 16:16:04 +0100222 }
223}
224
225@NonCPS
226def getCleanupImageList(remoteImagesString, imageType, osImage) {
227 def remoteImages = remoteImagesString.tokenize("\n")
228 def imageTypeForRegex = Pattern.quote(imageType)
Jakub Josefc6bcfd72017-02-14 18:14:28 +0100229 def osImageForRegex = Pattern.quote(osImage.replaceAll(/\./,"-"))
230 def remoteImagesSameType = remoteImages.findAll { it ->
231 it =~ /${imageTypeForRegex}$/
Jakub Josef6ee6f992017-01-27 16:16:04 +0100232 }
Jakub Josef338a1cb2018-01-10 18:50:51 +0100233 def imagesToClean = remoteImagesSameType.toSorted().findAll { it ->
Jakub Josefc6bcfd72017-02-14 18:14:28 +0100234 it =~ /^${osImageForRegex}-/
Jakub Josef6ee6f992017-01-27 16:16:04 +0100235 }
Jakub Josef338a1cb2018-01-10 18:50:51 +0100236 // dont cleanup non timestamp images
237 return imageToClean.findAll { it ->
238 it =~ /${osImageForRegex}-x(64|32)-\d+${imageTypeForRegex}/
239 }
Filip Pytloun35640b62017-02-23 09:45:34 +0100240}