blob: ce609b7fc8b3b5f0e7cbb2ffc4c644f5326dbc23 [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
Jakub Josef6ee6f992017-01-27 16:16:04 +010039@NonCPS
40def getCleanupImageList(remoteImagesString, imageType, osImage) {
41 def remoteImages = remoteImagesString.tokenize("\n")
42 def imageTypeForRegex = Pattern.quote(imageType)
Jakub Josefc6bcfd72017-02-14 18:14:28 +010043 def osImageForRegex = Pattern.quote(osImage.replaceAll(/\./,"-"))
44 def remoteImagesSameType = remoteImages.findAll { it ->
45 it =~ /${imageTypeForRegex}$/
Jakub Josef6ee6f992017-01-27 16:16:04 +010046 }
Jakub Josef338a1cb2018-01-10 18:50:51 +010047 def imagesToClean = remoteImagesSameType.toSorted().findAll { it ->
Jakub Josefc6bcfd72017-02-14 18:14:28 +010048 it =~ /^${osImageForRegex}-/
Jakub Josef6ee6f992017-01-27 16:16:04 +010049 }
Jakub Josef338a1cb2018-01-10 18:50:51 +010050 // dont cleanup non timestamp images
Richard Felkl014083d2018-03-12 14:58:36 +010051 return imagesToClean.findAll { it ->
Jakub Josef338a1cb2018-01-10 18:50:51 +010052 it =~ /${osImageForRegex}-x(64|32)-\d+${imageTypeForRegex}/
53 }
Filip Pytloun35640b62017-02-23 09:45:34 +010054}
Richard Felklc3053fc2018-03-06 11:15:50 +010055
56timeout(time: 12, unit: 'HOURS') {
57 node('qemu') {
58 // Define global variables
59 def workspace = common.getWorkspace()
60 def buildTypes = BUILD_ONLY.tokenize(" ")
61 def createdImages=[]
62 def uploadedImages=[]
63 def cleanedImages=[]
64
65 checkout scm
66 try {
67 stage("prepare") {
68 if (!fileExists("${workspace}/tmp")) {
69 sh "mkdir -p ${workspace}/tmp"
70 }
71 if (!fileExists("${workspace}/images")) {
72 sh "mkdir ${workspace}/images"
73 }
74 }
75 if (!fileExists("bin")) {
76 common.infoMsg("Downloading packer")
77 sh "mkdir bin"
78 dir("bin") {
79 sh "wget -O ${PACKER_ZIP} ${PACKER_URL}"
80 sh "echo \"${PACKER_ZIP_MD5} ${PACKER_ZIP}\" >> md5sum"
81 sh "md5sum -c --status md5sum"
82 sh "unzip ${PACKER_ZIP}"
83 }
84 }
85 // clean images dir before building
86 sh(script: String.format("rm -rf %s/images/*", BUILD_OS), returnStatus: true)
87 // clean virtualenv is exists
88 sh(script: String.format("rm -rf %s/venv", workspace), returnStatus: true)
89
90 stage("build") {
91 dir(BUILD_OS) {
92 withEnv([String.format("PATH=%s:%s/bin", env.PATH, workspace),
93 "PACKER_LOG_PATH=${workspace}/packer.log",
94 "PACKER_LOG=1",
95 "TMPDIR=${workspace}/tmp"
96 ]) {
97 if (PACKER_DEBUG == 'true') {
98 PACKER_ARGS = "${PACKER_ARGS} -debug"
99 }
100
101 if (fileExists("config-drive/user-data.yaml")) {
102 common.infoMsg("Creating cloud-config drive")
103 if (fileExists("config-drive/cloudata.iso")) {
104 sh "rm -v config-drive/cloudata.iso"
105 }
106 sh "cloud-localds config-drive/cloudata.iso config-drive/user-data.yaml"
107 }
108 sh "packer build -only=${BUILD_ONLY} ${PACKER_ARGS} -parallel=false template.json"
109
110 def packerStatus = sh(script: "grep \"Some builds didn't complete successfully and had errors\" ${PACKER_LOG_PATH}", returnStatus: true)
111 // grep returns 0 if find something
112 if (packerStatus != 0) {
113 if (buildTypes.contains("qemu")) {
114 def imageQemu = sh(script: "find images/ | grep -- '-qemu-' | tail -1", returnStdout: true).trim()
115 if (imageQemu != null && imageQemu != "") {
116 def qemuConvertStatus = sh(script: "qemu-img convert -c -O qcow2 ${imageQemu} ${imageQemu}.qcow2", returnStatus:true)
117 if(qemuConvertStatus == 0){
118 def imageDir = imageQemu.substring(0, imageQemu.lastIndexOf("/") + 1)
119 def imageQemuName = imageQemu.substring(imageQemu.lastIndexOf("/") + 1)
120 def moveResult = sh(script: "mv ${imageQemu}.qcow2 ${imageDir}..", returnStatus: true)
121 if(moveResult == 0){
122 sh "rm -rf ${imageDir}"
123 sh "rm -f ${imageQemu}"
124 createdImages.add(imageQemuName+".qcow2")
125 }
126 }else{
127 throw new Exception("Qemu image convert failed")
128 }
129 }
130 }
131 if (buildTypes.contains("docker")) {
132 def imageDocker = sh(script: "find images/ | grep -- '-docker-' | grep '.tar\$' | tail -1", returnStdout: true).trim()
133 if (imageDocker != null && imageDocker != "") {
134 def pbZip2Status = sh(script: "pbzip2 ${imageDocker}", returnStatus: true)
135 if(pbZip2Status == 0){
136 sh "rm -f ${imageDocker}"
137 createdImages.add(imageDocker+".bz2")
138 }else{
139 throw new Exception("pbzip2 image convert failed")
140 }
141 }
142 }
143
144 } else {
145 throw new Exception("Packer build failed")
146 }
147 }
148 }
149 }
150 stage("upload"){
151 dir(BUILD_OS + "/images") {
152 def images = findFiles(glob: "*.*")
153 def imageBuilds = [:]
154 def openstack = new com.mirantis.mk.Openstack()
155 def openstackEnv = String.format("%s/venv", workspace);
156 def openstackVersion = OPENSTACK_API_CLIENT ? OPENSTACK_API_CLIENT : 'liberty'
Richard Felkl26d43ad2018-03-06 11:28:21 +0100157 def rcFile = openstack.createOpenstackEnv(workspace, GLANCE_URL, GLANCE_CREDENTIALS_ID, GLANCE_PROJECT)
Richard Felklc3053fc2018-03-06 11:15:50 +0100158 def glanceImgTypes = GLANCE_IMG_TYPES.tokenize(" ")
159 openstack.setupOpenstackVirtualenv(openstackEnv, openstackVersion)
160 openstack.runOpenstackCommand("pip install python-glanceclient==1.0.0", rcFile, openstackEnv)
161 for (int i = 0; i < images.size(); i++) {
162 def imageName = images[i].name
163 def imageNameList = imageName.tokenize(".")
164 def imageType = "." + imageNameList[imageNameList.size() - 1]
165 if(imageType.equals(".md5")){
166 continue;
167 }
168
169 imageBuilds["build${i}"]={
170 if (SKIP_UPLOAD != 'true') {
171 sh "md5sum ${imageName} > ${imageName}.md5"
172 common.infoMsg("Uploading image " + imageName)
173 def uploadImageStatus = sh(script: "curl -f -T ${imageName} ${UPLOAD_URL}", returnStatus: true)
174 def uploadMd5Status = sh(script: "curl -f -T ${imageName}.md5 ${UPLOAD_URL}", returnStatus: true)
175 // upload latest
176 def latestImageName = imageName.substring(0, imageName.lastIndexOf("-")) + "-latest" + imageType
177 common.infoMsg("Uploading image ${imageName} as latest")
178 def uploadLatestStatus = sh(script: "curl -f -T ${imageName} ${UPLOAD_URL}${latestImageName}", returnStatus: true)
179 def uploadLatestMd5Status = sh(script: "curl -f -T ${imageName}.md5 ${UPLOAD_URL}${latestImageName}.md5", returnStatus: true)
180 if(uploadLatestStatus != 0 || uploadLatestMd5Status != 0){
181 common.errorMsg("Latest image upload failed")
182 }
183 if (GLANCE_UPLOAD == 'true' && glanceImgTypes.contains(imageType.substring(1))) {
184 def glanceRunArgs = String.format("%s --disk-format %s --container-format bare", GLANCE_ARGS, imageType.substring(1))
185 if (GLANCE_PUBLIC == 'true') {
186 glanceRunArgs += " --visibility public"
187 }
188
189 def imageShortName = imageNameList.get(0)
190 openstack.runOpenstackCommand(String.format("glance image-create --name '%s' %s --file %s", imageShortName, glanceRunArgs, imageName), rcFile, openstackEnv)
191 }
192 if(uploadImageStatus==0 && uploadMd5Status == 0){
193 uploadedImages.add(imageName)
194 sh(String.format("rm -r %s %s.md5",imageName, imageName))
195 createdImages.remove(imageName)
196 }else{
197 throw new Exception("Image upload failed")
198 }
199 }
200 if (CLEANUP_OLD == 'true') {
201 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)
202 if (remoteImages != "") {
203 def cleanupImages = getCleanupImageList(remoteImages, imageType, BUILD_OS)
204 def deleteCount = cleanupImages.size() - Integer.parseInt(CLEANUP_KEEP)
205 if (deleteCount > 0) {
206 for (int j = 0; j < deleteCount; j++) {
207 common.infoMsg(String.format("Deleting image %s from aptly", cleanupImages[j]))
208 sh "curl -f -X DELETE ${UPLOAD_URL}" + cleanupImages[j]
209 sh "curl -f -X DELETE ${UPLOAD_URL}" + cleanupImages[j] + ".md5"
210 cleanedImages.add(cleanupImages[j])
211 }
212 }
213 }
214 }
215 }
216 }
217 parallel imageBuilds
218 common.infoMsg(String.format("Uploaded %s images with names %s", uploadedImages.size(), uploadedImages.toString()))
219 common.infoMsg(String.format("Cleaned %s images with names %s", cleanedImages.size(), cleanedImages.toString()))
220 }
221 }
222 } catch (Throwable e) {
223 // If there was an error or exception thrown, the build failed
224 currentBuild.result = "FAILURE"
225 throw e
226 } finally {
227 common.sendNotification(currentBuild.result, "", ["slack"])
228 if (buildTypes.contains("docker")) {
229 withEnv(["PACKER_LOG_PATH=${workspace}/packer.log"]) {
230 sh "docker rmi --force \$(grep \"docker: Image ID:\" ${PACKER_LOG_PATH} | cut -d : -f 6 | head -1 | sed s,\\ ,,g) || true"
231 }
232 }
233 // clean created images if error occured
234 if(!createdImages.isEmpty()){
235 dir(BUILD_OS + "/images"){
236 for(int i=0;i<createdImages.size();i++){
237 sh String.format("rm -f %s",createdImages.get(i))
238 }
239 }
240 }
241 }
242 }
azvyagintsev6d453852018-02-26 16:56:37 +0200243}