blob: 1c5e4afc623f5f0c85802fd8e463a9350cb8ee8b [file] [log] [blame]
Jakub Josef6ee6f992017-01-27 16:16:04 +01001import java.util.regex.Pattern
2/**
3 *
4 * Images build pipeline
5 *
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
21 */
22
Jakub Josef6ee6f992017-01-27 16:16:04 +010023// Load shared libs
24def common
25fileLoader.withGit(PIPELINE_LIBS_URL, PIPELINE_LIBS_BRANCH, PIPELINE_LIBS_CREDENTIALS_ID, '') {
26 common = fileLoader.load("common");
27}
28
29node('qemu') {
30 // Define global variables
31 def workspace = common.getWorkspace()
32 def buildTypes = BUILD_ONLY.tokenize(" ")
33 checkout scm
34 try {
35 stage("prepare") {
36 if (!fileExists("${workspace}/tmp")) {
37 sh "mkdir -p ${workspace}/tmp"
38 }
39 if (!fileExists("${workspace}/images")) {
40 sh "mkdir ${workspace}/images"
41 }
42 }
43 if (!fileExists("bin")) {
44 println("Downloading packer")
45 sh "mkdir bin"
46 dir("bin") {
47 sh "wget -O ${PACKER_ZIP} ${PACKER_URL}"
48 sh "echo \"${PACKER_ZIP_MD5} ${PACKER_ZIP}\" >> md5sum"
49 sh "md5sum -c --status md5sum"
50 sh "unzip ${PACKER_ZIP}"
51 }
52 }
53 stage("build") {
54 dir(BUILD_OS) {
55 withEnv([String.format("PATH=%s:%s/bin", env.PATH, workspace),
56 "PACKER_LOG_PATH=${workspace}/packer.log",
57 "PACKER_LOG=1",
58 "TMPDIR=${workspace}/tmp"
59 ]) {
60 if (PACKER_DEBUG == 'true') {
61 PACKER_ARGS = "${PACKER_ARGS} -debug"
62 }
63 sh "packer build -only=${BUILD_ONLY} ${PACKER_ARGS} -parallel=false template.json"
64 def packerStatus = sh(script: "grep \"Some builds didn't complete successfully and had errors\" ${PACKER_LOG_PATH}", returnStatus: true)
65 // grep returns 0 if find something
66 if (packerStatus != 0) {
67 if (buildTypes.contains("qemu")) {
68 def imageQemu = sh(script: "find images/ | grep -- '-qemu-' | tail -1", returnStdout: true).trim()
69 if (imageQemu != null && imageQemu != "") {
70 def qemuConvertStatus = sh(script: "qemu-img convert -c -O qcow2 ${imageQemu} ${imageQemu}.qcow2", returnStatus:true)
71 if(qemuConvertStatus == 0){
Jakub Josefc6bcfd72017-02-14 18:14:28 +010072 def imageDir = imageQemu.substring(0, imageQemu.lastIndexOf("/") + 1);
73 def moveResult = sh(script: "mv ${imageQemu}.qcow2 ${imageDir}..", returnStatus: true)
74 if(moveResult == 0){
75 sh "rm -rf ${imageDir}"
76 sh "rm -f ${imageQemu}"
77 }
Jakub Josef6ee6f992017-01-27 16:16:04 +010078 }else{
79 throw new Exception("Qemu image convert failed")
80 }
81 }
82 }
83 if (buildTypes.contains("docker")) {
84 def imageDocker = sh(script: "find images/ | grep -- '-docker-' | grep '.tar\$' | tail -1", returnStdout: true).trim()
85 if (imageDocker != null && imageDocker != "") {
86 def pbZip2Status = sh(script: "pbzip2 ${imageDocker}", returnStatus: true)
87 if(pbZip2Status == 0){
88 sh "rm -f ${imageDocker}"
89 }else{
90 throw new Exception("pbzip2 image convert failed")
91 }
92 }
93 }
94 } else {
95 throw new Exception("Packer build failed")
96 }
97 }
98 }
99 }
100 stage("upload"){
101 dir(BUILD_OS + "/images") {
102 def images = findFiles(glob: "*.*")
103 def uploadedImages=[]
104 def cleanedImages=[]
105 def imageBuilds = [:]
106 for (int i = 0; i < images.size(); i++) {
107 def imageName = images[i].name
108 def imageNameList = imageName.tokenize(".")
109 def imageType = "." + imageNameList[imageNameList.size() - 1]
110 if(imageType.equals(".md5")){
111 continue;
112 }
113 imageBuilds["build${i}"]={
114 if (SKIP_UPLOAD != 'true') {
115 sh "md5sum ${imageName} > ${imageName}.md5"
116 println("Uploading image " + imageName)
117 def uploadImageStatus = sh(script: "curl -f -T ${imageName} ${UPLOAD_URL}", returnStatus: true)
118 def uploadMd5Status = sh(script: "curl -f -T ${imageName}.md5 ${UPLOAD_URL}", returnStatus: true)
119 if(uploadImageStatus==0 && uploadMd5Status == 0){
120 uploadedImages.add(imageName)
Jakub Josefc6bcfd72017-02-14 18:14:28 +0100121 sh(String.format("rm -r %s %s.md5",imageName, imageName))
Jakub Josef6ee6f992017-01-27 16:16:04 +0100122 }else{
123 throw new Exception("Image upload failed")
124 }
125 }
126 if (CLEANUP_OLD == 'true') {
127 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)
128 if (remoteImages != "") {
129 def cleanupImages = getCleanupImageList(remoteImages, imageType, BUILD_OS)
130 def deleteCount = cleanupImages.size() - Integer.parseInt(CLEANUP_KEEP)
131 if (deleteCount > 0) {
132 for (int j = 0; j < deleteCount; j++) {
133 println(String.format("Deleting image %s from aptly", cleanupImages[j]))
Jakub Josefc6bcfd72017-02-14 18:14:28 +0100134 sh "curl -f -X DELETE ${UPLOAD_URL}" + cleanupImages[j]
135 sh "curl -f -X DELETE ${UPLOAD_URL}" + cleanupImages[j] + ".md5"
Jakub Josef6ee6f992017-01-27 16:16:04 +0100136 cleanedImages.add(cleanupImages[j])
137 }
138 }
139 }
140 }
141 }
142 }
143 parallel imageBuilds
144 println(String.format("Uploaded %s images with names %s", uploadedImages.size(), uploadedImages.toString()))
145 println(String.format("Cleaned %s images with names %s", cleanedImages.size(), cleanedImages.toString()))
146 }
147 }
148 } catch (Throwable e) {
149 // If there was an error or exception thrown, the build failed
150 currentBuild.result = "FAILURE"
151 throw e
152 } finally {
153 common.sendNotification(currentBuild.result, "", ["slack"])
154 if (buildTypes.contains("docker")) {
155 withEnv(["PACKER_LOG_PATH=${workspace}/packer.log"]) {
156 sh "docker rmi --force \$(grep \"docker: Image ID:\" ${PACKER_LOG_PATH} | cut -d : -f 6 | head -1 | sed s,\\ ,,g) || true"
157 }
158 }
159 }
160}
161
162@NonCPS
163def getCleanupImageList(remoteImagesString, imageType, osImage) {
164 def remoteImages = remoteImagesString.tokenize("\n")
165 def imageTypeForRegex = Pattern.quote(imageType)
Jakub Josefc6bcfd72017-02-14 18:14:28 +0100166 def osImageForRegex = Pattern.quote(osImage.replaceAll(/\./,"-"))
167 def remoteImagesSameType = remoteImages.findAll { it ->
168 it =~ /${imageTypeForRegex}$/
Jakub Josef6ee6f992017-01-27 16:16:04 +0100169 }
Jakub Josefc6bcfd72017-02-14 18:14:28 +0100170 return remoteImagesSameType.toSorted().findAll { it ->
171 it =~ /^${osImageForRegex}-/
Jakub Josef6ee6f992017-01-27 16:16:04 +0100172 }
173}