blob: 954ecac56b01f22ec03e6c47a9c1361c8e21a30e [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
Jakub Josef502bac22017-09-04 15:57:25 +020077 sh "packer build -only=${BUILD_ONLY} ${PACKER_ARGS} -parallel=false template.json"
Filip Pytloun35640b62017-02-23 09:45:34 +010078
Jakub Josef6ee6f992017-01-27 16:16:04 +010079 def packerStatus = sh(script: "grep \"Some builds didn't complete successfully and had errors\" ${PACKER_LOG_PATH}", returnStatus: true)
80 // grep returns 0 if find something
81 if (packerStatus != 0) {
82 if (buildTypes.contains("qemu")) {
83 def imageQemu = sh(script: "find images/ | grep -- '-qemu-' | tail -1", returnStdout: true).trim()
84 if (imageQemu != null && imageQemu != "") {
85 def qemuConvertStatus = sh(script: "qemu-img convert -c -O qcow2 ${imageQemu} ${imageQemu}.qcow2", returnStatus:true)
86 if(qemuConvertStatus == 0){
Jakub Joseffc2f2412017-02-27 15:14:07 +010087 def imageDir = imageQemu.substring(0, imageQemu.lastIndexOf("/") + 1)
88 def imageQemuName = imageQemu.substring(imageQemu.lastIndexOf("/") + 1)
Jakub Josefc6bcfd72017-02-14 18:14:28 +010089 def moveResult = sh(script: "mv ${imageQemu}.qcow2 ${imageDir}..", returnStatus: true)
90 if(moveResult == 0){
91 sh "rm -rf ${imageDir}"
92 sh "rm -f ${imageQemu}"
Jakub Joseffc2f2412017-02-27 15:14:07 +010093 createdImages.add(imageQemuName+".qcow2")
Jakub Josefc6bcfd72017-02-14 18:14:28 +010094 }
Jakub Josef6ee6f992017-01-27 16:16:04 +010095 }else{
96 throw new Exception("Qemu image convert failed")
97 }
98 }
99 }
100 if (buildTypes.contains("docker")) {
101 def imageDocker = sh(script: "find images/ | grep -- '-docker-' | grep '.tar\$' | tail -1", returnStdout: true).trim()
102 if (imageDocker != null && imageDocker != "") {
103 def pbZip2Status = sh(script: "pbzip2 ${imageDocker}", returnStatus: true)
104 if(pbZip2Status == 0){
105 sh "rm -f ${imageDocker}"
Jakub Joseffc2f2412017-02-27 15:14:07 +0100106 createdImages.add(imageDocker+".bz2")
Jakub Josef6ee6f992017-01-27 16:16:04 +0100107 }else{
108 throw new Exception("pbzip2 image convert failed")
109 }
110 }
111 }
112 } else {
113 throw new Exception("Packer build failed")
114 }
115 }
116 }
117 }
118 stage("upload"){
119 dir(BUILD_OS + "/images") {
120 def images = findFiles(glob: "*.*")
Jakub Josef6ee6f992017-01-27 16:16:04 +0100121 def imageBuilds = [:]
Jakub Joseffc2f2412017-02-27 15:14:07 +0100122 def openstack = new com.mirantis.mk.Openstack()
123 def openstackEnv = String.format("%s/venv", workspace);
124 def openstackVersion = OPENSTACK_API_CLIENT ? OPENSTACK_API_CLIENT : 'liberty'
125 def rcFile = openstack.createOpenstackEnv(GLANCE_URL, GLANCE_CREDENTIALS_ID, GLANCE_PROJECT)
126 def glanceImgTypes = GLANCE_IMG_TYPES.tokenize(" ")
127 openstack.setupOpenstackVirtualenv(openstackEnv, openstackVersion)
128 openstack.runOpenstackCommand("pip install python-glanceclient==1.0.0", rcFile, openstackEnv)
Jakub Josef6ee6f992017-01-27 16:16:04 +0100129 for (int i = 0; i < images.size(); i++) {
130 def imageName = images[i].name
131 def imageNameList = imageName.tokenize(".")
132 def imageType = "." + imageNameList[imageNameList.size() - 1]
133 if(imageType.equals(".md5")){
134 continue;
135 }
Jakub Joseffc2f2412017-02-27 15:14:07 +0100136
Jakub Josef6ee6f992017-01-27 16:16:04 +0100137 imageBuilds["build${i}"]={
138 if (SKIP_UPLOAD != 'true') {
139 sh "md5sum ${imageName} > ${imageName}.md5"
Jakub Josefeb98c8e2017-03-13 18:13:58 +0100140 common.infoMsg("Uploading image " + imageName)
Jakub Josef6ee6f992017-01-27 16:16:04 +0100141 def uploadImageStatus = sh(script: "curl -f -T ${imageName} ${UPLOAD_URL}", returnStatus: true)
142 def uploadMd5Status = sh(script: "curl -f -T ${imageName}.md5 ${UPLOAD_URL}", returnStatus: true)
Jakub Josef469d26a2017-03-28 17:55:02 +0200143 // upload latest
144 def latestImageName = imageName.substring(0, imageName.lastIndexOf("-")) + "-latest" + imageType
145 common.infoMsg("Uploading image ${imageName} as latest")
146 def uploadLatestStatus = sh(script: "curl -f -T ${imageName} ${UPLOAD_URL}${latestImageName}", returnStatus: true)
147 def uploadLatestMd5Status = sh(script: "curl -f -T ${imageName}.md5 ${UPLOAD_URL}${latestImageName}.md5", returnStatus: true)
148 if(uploadLatestStatus != 0 || uploadLatestMd5Status != 0){
149 common.errorMsg("Latest image upload failed")
150 }
Jakub Joseffc2f2412017-02-27 15:14:07 +0100151 if (GLANCE_UPLOAD == 'true' && glanceImgTypes.contains(imageType.substring(1))) {
152 def glanceRunArgs = String.format("%s --disk-format %s --container-format bare", GLANCE_ARGS, imageType.substring(1))
153 if (GLANCE_PUBLIC == 'true') {
154 glanceRunArgs += " --visibility public"
155 }
156
157 def imageShortName = imageNameList.get(0)
158 openstack.runOpenstackCommand(String.format("glance image-create --name '%s' %s --file %s", imageShortName, glanceRunArgs, imageName), rcFile, openstackEnv)
159 }
Jakub Josef6ee6f992017-01-27 16:16:04 +0100160 if(uploadImageStatus==0 && uploadMd5Status == 0){
161 uploadedImages.add(imageName)
Jakub Josefc6bcfd72017-02-14 18:14:28 +0100162 sh(String.format("rm -r %s %s.md5",imageName, imageName))
Jakub Joseffc2f2412017-02-27 15:14:07 +0100163 createdImages.remove(imageName)
Jakub Josef6ee6f992017-01-27 16:16:04 +0100164 }else{
165 throw new Exception("Image upload failed")
166 }
167 }
168 if (CLEANUP_OLD == 'true') {
169 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)
170 if (remoteImages != "") {
171 def cleanupImages = getCleanupImageList(remoteImages, imageType, BUILD_OS)
172 def deleteCount = cleanupImages.size() - Integer.parseInt(CLEANUP_KEEP)
173 if (deleteCount > 0) {
174 for (int j = 0; j < deleteCount; j++) {
Jakub Josefeb98c8e2017-03-13 18:13:58 +0100175 common.infoMsg(String.format("Deleting image %s from aptly", cleanupImages[j]))
Jakub Josefc6bcfd72017-02-14 18:14:28 +0100176 sh "curl -f -X DELETE ${UPLOAD_URL}" + cleanupImages[j]
177 sh "curl -f -X DELETE ${UPLOAD_URL}" + cleanupImages[j] + ".md5"
Jakub Josef6ee6f992017-01-27 16:16:04 +0100178 cleanedImages.add(cleanupImages[j])
179 }
180 }
181 }
182 }
183 }
184 }
185 parallel imageBuilds
Jakub Josefeb98c8e2017-03-13 18:13:58 +0100186 common.infoMsg(String.format("Uploaded %s images with names %s", uploadedImages.size(), uploadedImages.toString()))
187 common.infoMsg(String.format("Cleaned %s images with names %s", cleanedImages.size(), cleanedImages.toString()))
Jakub Josef6ee6f992017-01-27 16:16:04 +0100188 }
189 }
190 } catch (Throwable e) {
191 // If there was an error or exception thrown, the build failed
192 currentBuild.result = "FAILURE"
193 throw e
194 } finally {
195 common.sendNotification(currentBuild.result, "", ["slack"])
196 if (buildTypes.contains("docker")) {
197 withEnv(["PACKER_LOG_PATH=${workspace}/packer.log"]) {
198 sh "docker rmi --force \$(grep \"docker: Image ID:\" ${PACKER_LOG_PATH} | cut -d : -f 6 | head -1 | sed s,\\ ,,g) || true"
199 }
200 }
Jakub Joseffc2f2412017-02-27 15:14:07 +0100201 // clean created images if error occured
202 if(!createdImages.isEmpty()){
203 dir(BUILD_OS + "/images"){
204 for(int i=0;i<createdImages.size();i++){
205 sh String.format("rm -f %s",createdImages.get(i))
206 }
207 }
208 }
Jakub Josef6ee6f992017-01-27 16:16:04 +0100209 }
210}
211
212@NonCPS
213def getCleanupImageList(remoteImagesString, imageType, osImage) {
214 def remoteImages = remoteImagesString.tokenize("\n")
215 def imageTypeForRegex = Pattern.quote(imageType)
Jakub Josefc6bcfd72017-02-14 18:14:28 +0100216 def osImageForRegex = Pattern.quote(osImage.replaceAll(/\./,"-"))
217 def remoteImagesSameType = remoteImages.findAll { it ->
218 it =~ /${imageTypeForRegex}$/
Jakub Josef6ee6f992017-01-27 16:16:04 +0100219 }
Jakub Josef338a1cb2018-01-10 18:50:51 +0100220 def imagesToClean = remoteImagesSameType.toSorted().findAll { it ->
Jakub Josefc6bcfd72017-02-14 18:14:28 +0100221 it =~ /^${osImageForRegex}-/
Jakub Josef6ee6f992017-01-27 16:16:04 +0100222 }
Jakub Josef338a1cb2018-01-10 18:50:51 +0100223 // dont cleanup non timestamp images
224 return imageToClean.findAll { it ->
225 it =~ /${osImageForRegex}-x(64|32)-\d+${imageTypeForRegex}/
226 }
Filip Pytloun35640b62017-02-23 09:45:34 +0100227}