blob: be3bd4de9ba93be9e9b391cc68c7088b7a130f99 [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 *
6 * Expected parameters:
7 * BUILD_OS
8 * BUILD_ONLY
9 * PACKER_DEBUG
10 * PACKER_URL
11 * PACKER_ZIP
12 * PACKER_ZIP_MD5
13 * PACKER_ARGS
14 * UPLOAD_URL
15 * SKIP_UPLOAD
16 * CLEANUP_OLD
17 * CLEANUP_KEEP
18 * PIPELINE_LIBS_URL
19 * PIPELINE_LIBS_BRANCH
20 * PIPELINE_LIBS_CREDENTIALS_ID
Jakub Joseffc2f2412017-02-27 15:14:07 +010021 * GLANCE_UPLOAD
22 * GLANCE_IMG_TYPES
23 * GLANCE_URL
24 * GLANCE_CREDENTIALS_ID
25 * GLANCE_PROJECT
26 * GLANCE_ARGS
27 * OPENSTACK_API_CLIENT
Jakub Josef6ee6f992017-01-27 16:16:04 +010028 */
29
Jakub Josef6ee6f992017-01-27 16:16:04 +010030// Load shared libs
Jakub Joseffc2f2412017-02-27 15:14:07 +010031common = new com.mirantis.mk.Common()
Jakub Josef6ee6f992017-01-27 16:16:04 +010032
33node('qemu') {
34 // Define global variables
35 def workspace = common.getWorkspace()
36 def buildTypes = BUILD_ONLY.tokenize(" ")
Jakub Joseffc2f2412017-02-27 15:14:07 +010037 def createdImages=[]
38 def uploadedImages=[]
39 def cleanedImages=[]
40
Jakub Josef6ee6f992017-01-27 16:16:04 +010041 checkout scm
42 try {
43 stage("prepare") {
44 if (!fileExists("${workspace}/tmp")) {
45 sh "mkdir -p ${workspace}/tmp"
46 }
47 if (!fileExists("${workspace}/images")) {
48 sh "mkdir ${workspace}/images"
49 }
50 }
51 if (!fileExists("bin")) {
Jakub Josefeb98c8e2017-03-13 18:13:58 +010052 common.infoMsg("Downloading packer")
Jakub Josef6ee6f992017-01-27 16:16:04 +010053 sh "mkdir bin"
54 dir("bin") {
55 sh "wget -O ${PACKER_ZIP} ${PACKER_URL}"
56 sh "echo \"${PACKER_ZIP_MD5} ${PACKER_ZIP}\" >> md5sum"
57 sh "md5sum -c --status md5sum"
58 sh "unzip ${PACKER_ZIP}"
59 }
60 }
Jakub Joseffc2f2412017-02-27 15:14:07 +010061 // clean images dir before building
62 sh(script: String.format("rm -rf %s/images/*", BUILD_OS), returnStatus: true)
63 // clean virtualenv is exists
64 sh(script: String.format("rm -rf %s/venv", workspace), returnStatus: true)
65
Jakub Josef6ee6f992017-01-27 16:16:04 +010066 stage("build") {
67 dir(BUILD_OS) {
68 withEnv([String.format("PATH=%s:%s/bin", env.PATH, workspace),
69 "PACKER_LOG_PATH=${workspace}/packer.log",
70 "PACKER_LOG=1",
71 "TMPDIR=${workspace}/tmp"
72 ]) {
73 if (PACKER_DEBUG == 'true') {
74 PACKER_ARGS = "${PACKER_ARGS} -debug"
75 }
Filip Pytloun35640b62017-02-23 09:45:34 +010076
alexz5b795142018-02-13 15:59:28 +010077 if (fileExists("config-drive/user-data.yaml")) {
78 common.infoMsg("Creating cloud-config drive")
79 if (fileExists("config-drive/cloudata.iso")) {
80 sh "rm -v config-drive/cloudata.iso"
81 }
82 sh "cloud-localds config-drive/cloudata.iso config-drive/user-data.yaml"
83 }
Jakub Josef502bac22017-09-04 15:57:25 +020084 sh "packer build -only=${BUILD_ONLY} ${PACKER_ARGS} -parallel=false template.json"
Filip Pytloun35640b62017-02-23 09:45:34 +010085
Jakub Josef6ee6f992017-01-27 16:16:04 +010086 def packerStatus = sh(script: "grep \"Some builds didn't complete successfully and had errors\" ${PACKER_LOG_PATH}", returnStatus: true)
87 // grep returns 0 if find something
88 if (packerStatus != 0) {
89 if (buildTypes.contains("qemu")) {
90 def imageQemu = sh(script: "find images/ | grep -- '-qemu-' | tail -1", returnStdout: true).trim()
91 if (imageQemu != null && imageQemu != "") {
92 def qemuConvertStatus = sh(script: "qemu-img convert -c -O qcow2 ${imageQemu} ${imageQemu}.qcow2", returnStatus:true)
93 if(qemuConvertStatus == 0){
Jakub Joseffc2f2412017-02-27 15:14:07 +010094 def imageDir = imageQemu.substring(0, imageQemu.lastIndexOf("/") + 1)
95 def imageQemuName = imageQemu.substring(imageQemu.lastIndexOf("/") + 1)
Jakub Josefc6bcfd72017-02-14 18:14:28 +010096 def moveResult = sh(script: "mv ${imageQemu}.qcow2 ${imageDir}..", returnStatus: true)
97 if(moveResult == 0){
98 sh "rm -rf ${imageDir}"
99 sh "rm -f ${imageQemu}"
Jakub Joseffc2f2412017-02-27 15:14:07 +0100100 createdImages.add(imageQemuName+".qcow2")
Jakub Josefc6bcfd72017-02-14 18:14:28 +0100101 }
Jakub Josef6ee6f992017-01-27 16:16:04 +0100102 }else{
103 throw new Exception("Qemu image convert failed")
104 }
105 }
106 }
107 if (buildTypes.contains("docker")) {
108 def imageDocker = sh(script: "find images/ | grep -- '-docker-' | grep '.tar\$' | tail -1", returnStdout: true).trim()
109 if (imageDocker != null && imageDocker != "") {
110 def pbZip2Status = sh(script: "pbzip2 ${imageDocker}", returnStatus: true)
111 if(pbZip2Status == 0){
112 sh "rm -f ${imageDocker}"
Jakub Joseffc2f2412017-02-27 15:14:07 +0100113 createdImages.add(imageDocker+".bz2")
Jakub Josef6ee6f992017-01-27 16:16:04 +0100114 }else{
115 throw new Exception("pbzip2 image convert failed")
116 }
117 }
118 }
119 } else {
120 throw new Exception("Packer build failed")
121 }
122 }
123 }
124 }
125 stage("upload"){
126 dir(BUILD_OS + "/images") {
127 def images = findFiles(glob: "*.*")
Jakub Josef6ee6f992017-01-27 16:16:04 +0100128 def imageBuilds = [:]
Jakub Joseffc2f2412017-02-27 15:14:07 +0100129 def openstack = new com.mirantis.mk.Openstack()
130 def openstackEnv = String.format("%s/venv", workspace);
131 def openstackVersion = OPENSTACK_API_CLIENT ? OPENSTACK_API_CLIENT : 'liberty'
132 def rcFile = openstack.createOpenstackEnv(GLANCE_URL, GLANCE_CREDENTIALS_ID, GLANCE_PROJECT)
133 def glanceImgTypes = GLANCE_IMG_TYPES.tokenize(" ")
134 openstack.setupOpenstackVirtualenv(openstackEnv, openstackVersion)
135 openstack.runOpenstackCommand("pip install python-glanceclient==1.0.0", rcFile, openstackEnv)
Jakub Josef6ee6f992017-01-27 16:16:04 +0100136 for (int i = 0; i < images.size(); i++) {
137 def imageName = images[i].name
138 def imageNameList = imageName.tokenize(".")
139 def imageType = "." + imageNameList[imageNameList.size() - 1]
140 if(imageType.equals(".md5")){
141 continue;
142 }
Jakub Joseffc2f2412017-02-27 15:14:07 +0100143
Jakub Josef6ee6f992017-01-27 16:16:04 +0100144 imageBuilds["build${i}"]={
145 if (SKIP_UPLOAD != 'true') {
146 sh "md5sum ${imageName} > ${imageName}.md5"
Jakub Josefeb98c8e2017-03-13 18:13:58 +0100147 common.infoMsg("Uploading image " + imageName)
Jakub Josef6ee6f992017-01-27 16:16:04 +0100148 def uploadImageStatus = sh(script: "curl -f -T ${imageName} ${UPLOAD_URL}", returnStatus: true)
149 def uploadMd5Status = sh(script: "curl -f -T ${imageName}.md5 ${UPLOAD_URL}", returnStatus: true)
Jakub Josef469d26a2017-03-28 17:55:02 +0200150 // upload latest
151 def latestImageName = imageName.substring(0, imageName.lastIndexOf("-")) + "-latest" + imageType
152 common.infoMsg("Uploading image ${imageName} as latest")
153 def uploadLatestStatus = sh(script: "curl -f -T ${imageName} ${UPLOAD_URL}${latestImageName}", returnStatus: true)
154 def uploadLatestMd5Status = sh(script: "curl -f -T ${imageName}.md5 ${UPLOAD_URL}${latestImageName}.md5", returnStatus: true)
155 if(uploadLatestStatus != 0 || uploadLatestMd5Status != 0){
156 common.errorMsg("Latest image upload failed")
157 }
Jakub Joseffc2f2412017-02-27 15:14:07 +0100158 if (GLANCE_UPLOAD == 'true' && glanceImgTypes.contains(imageType.substring(1))) {
159 def glanceRunArgs = String.format("%s --disk-format %s --container-format bare", GLANCE_ARGS, imageType.substring(1))
160 if (GLANCE_PUBLIC == 'true') {
161 glanceRunArgs += " --visibility public"
162 }
163
164 def imageShortName = imageNameList.get(0)
165 openstack.runOpenstackCommand(String.format("glance image-create --name '%s' %s --file %s", imageShortName, glanceRunArgs, imageName), rcFile, openstackEnv)
166 }
Jakub Josef6ee6f992017-01-27 16:16:04 +0100167 if(uploadImageStatus==0 && uploadMd5Status == 0){
168 uploadedImages.add(imageName)
Jakub Josefc6bcfd72017-02-14 18:14:28 +0100169 sh(String.format("rm -r %s %s.md5",imageName, imageName))
Jakub Joseffc2f2412017-02-27 15:14:07 +0100170 createdImages.remove(imageName)
Jakub Josef6ee6f992017-01-27 16:16:04 +0100171 }else{
172 throw new Exception("Image upload failed")
173 }
174 }
175 if (CLEANUP_OLD == 'true') {
176 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)
177 if (remoteImages != "") {
178 def cleanupImages = getCleanupImageList(remoteImages, imageType, BUILD_OS)
179 def deleteCount = cleanupImages.size() - Integer.parseInt(CLEANUP_KEEP)
180 if (deleteCount > 0) {
181 for (int j = 0; j < deleteCount; j++) {
Jakub Josefeb98c8e2017-03-13 18:13:58 +0100182 common.infoMsg(String.format("Deleting image %s from aptly", cleanupImages[j]))
Jakub Josefc6bcfd72017-02-14 18:14:28 +0100183 sh "curl -f -X DELETE ${UPLOAD_URL}" + cleanupImages[j]
184 sh "curl -f -X DELETE ${UPLOAD_URL}" + cleanupImages[j] + ".md5"
Jakub Josef6ee6f992017-01-27 16:16:04 +0100185 cleanedImages.add(cleanupImages[j])
186 }
187 }
188 }
189 }
190 }
191 }
192 parallel imageBuilds
Jakub Josefeb98c8e2017-03-13 18:13:58 +0100193 common.infoMsg(String.format("Uploaded %s images with names %s", uploadedImages.size(), uploadedImages.toString()))
194 common.infoMsg(String.format("Cleaned %s images with names %s", cleanedImages.size(), cleanedImages.toString()))
Jakub Josef6ee6f992017-01-27 16:16:04 +0100195 }
196 }
197 } catch (Throwable e) {
198 // If there was an error or exception thrown, the build failed
199 currentBuild.result = "FAILURE"
200 throw e
201 } finally {
202 common.sendNotification(currentBuild.result, "", ["slack"])
203 if (buildTypes.contains("docker")) {
204 withEnv(["PACKER_LOG_PATH=${workspace}/packer.log"]) {
205 sh "docker rmi --force \$(grep \"docker: Image ID:\" ${PACKER_LOG_PATH} | cut -d : -f 6 | head -1 | sed s,\\ ,,g) || true"
206 }
207 }
Jakub Joseffc2f2412017-02-27 15:14:07 +0100208 // clean created images if error occured
209 if(!createdImages.isEmpty()){
210 dir(BUILD_OS + "/images"){
211 for(int i=0;i<createdImages.size();i++){
212 sh String.format("rm -f %s",createdImages.get(i))
213 }
214 }
215 }
Jakub Josef6ee6f992017-01-27 16:16:04 +0100216 }
217}
218
219@NonCPS
220def getCleanupImageList(remoteImagesString, imageType, osImage) {
221 def remoteImages = remoteImagesString.tokenize("\n")
222 def imageTypeForRegex = Pattern.quote(imageType)
Jakub Josefc6bcfd72017-02-14 18:14:28 +0100223 def osImageForRegex = Pattern.quote(osImage.replaceAll(/\./,"-"))
224 def remoteImagesSameType = remoteImages.findAll { it ->
225 it =~ /${imageTypeForRegex}$/
Jakub Josef6ee6f992017-01-27 16:16:04 +0100226 }
Jakub Josef338a1cb2018-01-10 18:50:51 +0100227 def imagesToClean = remoteImagesSameType.toSorted().findAll { it ->
Jakub Josefc6bcfd72017-02-14 18:14:28 +0100228 it =~ /^${osImageForRegex}-/
Jakub Josef6ee6f992017-01-27 16:16:04 +0100229 }
Jakub Josef338a1cb2018-01-10 18:50:51 +0100230 // dont cleanup non timestamp images
231 return imageToClean.findAll { it ->
232 it =~ /${osImageForRegex}-x(64|32)-\d+${imageTypeForRegex}/
233 }
Filip Pytloun35640b62017-02-23 09:45:34 +0100234}