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