blob: 0a98ea3f384d0bcaa69c248efe02b37e0142f567 [file] [log] [blame]
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +03001package com.mirantis.mcp
2
Sergey Kulanov91d8def2016-11-15 13:53:17 +02003import org.jfrog.hudson.pipeline.types.ArtifactoryServer
4import org.jfrog.hudson.pipeline.types.buildInfo.BuildInfo
5
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +03006/**
7 * Return string of mandatory build properties for binaries
8 * User can also add some custom properties.
9 *
10 * @param customProperties a Array of Strings that should be added to mandatory props
11 * in format ["prop1=value1", "prop2=value2"]
12 * */
13def getBinaryBuildProperties(ArrayList customProperties) {
14 def namespace = "com.mirantis."
15 def properties = [
Sergey Kulanovc70f1c22016-11-16 13:05:20 +020016 "buildName=${env.JOB_NAME}",
17 "buildNumber=${env.BUILD_NUMBER}",
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +030018 "gerritProject=${env.GERRIT_PROJECT}",
19 "gerritChangeNumber=${env.GERRIT_CHANGE_NUMBER}",
20 "gerritPatchsetNumber=${env.GERRIT_PATCHSET_NUMBER}",
21 "gerritChangeId=${env.GERRIT_CHANGE_ID}",
22 "gerritPatchsetRevision=${env.GERRIT_PATCHSET_REVISION}"
23 ]
24
25 if (customProperties) {
26 properties.addAll(customProperties)
27 }
28
29 def common = new com.mirantis.mcp.Common()
30
31 return common.constructString(properties, namespace, ";")
32}
33
34/**
Kirill Mashchenko1d225c22018-06-19 13:52:17 +030035 * Get URL to artifact(s) by properties
36 * Returns String(s) with URL to found artifact or null if nothing
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +030037 *
38 * @param artifactoryURL String, an URL to Artifactory
39 * @param properties LinkedHashMap, a Hash of properties (key-value) which
40 * which should determine artifact in Artifactory
Kirill Mashchenko1d225c22018-06-19 13:52:17 +030041 * @param onlyLastItem Boolean, return only last URL if true(by default),
42 * else return list of all found artifact URLS
Sergey Kolekonov54c44842019-06-17 19:25:52 +040043 * @param repos ArrayList, a list of repositories to search in
Kirill Mashchenko1d225c22018-06-19 13:52:17 +030044 *
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +030045 */
Sergey Kolekonov54c44842019-06-17 19:25:52 +040046def uriByProperties(String artifactoryURL, LinkedHashMap properties, Boolean onlyLastItem=true, ArrayList repos=[]) {
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +030047 def key, value
48 def properties_str = ''
49 for (int i = 0; i < properties.size(); i++) {
50 // avoid serialization errors
Kirill Mashchenko56c8ff32018-06-28 03:01:34 +030051 key = properties.entrySet().toArray()[i].key.trim()
52 value = properties.entrySet().toArray()[i].value.trim()
53 properties_str += /${key}=${value}&/
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +030054 }
Sergey Kolekonov54c44842019-06-17 19:25:52 +040055 def repos_str = (repos) ? repos.join(',') : ''
56 def search_url
57 if (repos_str) {
58 search_url = "${artifactoryURL}/api/search/prop?${properties_str}&repos=${repos_str}"
59 } else {
60 search_url = "${artifactoryURL}/api/search/prop?${properties_str}"
61 }
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +030062
Kirill Mashchenko56c8ff32018-06-28 03:01:34 +030063 def result = sh(script: /curl -X GET '${search_url}'/,
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +030064 returnStdout: true).trim()
65 def content = new groovy.json.JsonSlurperClassic().parseText(result)
66 def uri = content.get("results")
67 if (uri) {
Kirill Mashchenko1d225c22018-06-19 13:52:17 +030068 if (onlyLastItem) {
69 return uri.last().get("uri")
70 } else {
71 res = []
72 uri.each {it ->
73 res.add(it.get("uri"))
74 }
75 return res
76 }
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +030077 } else {
78 return null
79 }
80}
81
Kirill Mashchenko1d225c22018-06-19 13:52:17 +030082
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +030083/**
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +030084 * Set properties for artifact in Artifactory repo
85 *
86 * @param artifactUrl String, an URL to artifact in Artifactory repo
87 * @param properties LinkedHashMap, a Hash of properties (key-value) which
88 * should be assigned for choosen artifact
89 * @param recursive Boolean, if artifact_url is a directory, whether to set
90 * properties recursively or not
91 */
92def setProperties(String artifactUrl, LinkedHashMap properties, Boolean recursive = false) {
93 def properties_str = 'properties='
94 def key, value
95 if (recursive) {
96 recursive = 'recursive=1'
97 } else {
98 recursive = 'recursive=0'
99 }
Alexander Evseevbd40ef92017-10-18 12:24:45 +0300100 properties_str += properties.collect({"${it.key}=${it.value}"}).join(';')
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +0300101 def url = "${artifactUrl}?${properties_str}&${recursive}"
102 withCredentials([
103 [$class : 'UsernamePasswordMultiBinding',
104 credentialsId : 'artifactory',
105 passwordVariable: 'ARTIFACTORY_PASSWORD',
106 usernameVariable: 'ARTIFACTORY_LOGIN']
107 ]) {
108 sh "bash -c \"curl -X PUT -u ${ARTIFACTORY_LOGIN}:${ARTIFACTORY_PASSWORD} \'${url}\'\""
109 }
110}
111
112/**
113 * Get properties for specified artifact in Artifactory
114 * Returns LinkedHashMap of properties
115 *
116 * @param artifactUrl String, an URL to artifact in Artifactory repo
117 */
118def getPropertiesForArtifact(String artifactUrl) {
119 def url = "${artifactUrl}?properties"
120 def result
121 withCredentials([
122 [$class : 'UsernamePasswordMultiBinding',
123 credentialsId : 'artifactory',
124 passwordVariable: 'ARTIFACTORY_PASSWORD',
125 usernameVariable: 'ARTIFACTORY_LOGIN']
126 ]) {
127 result = sh(script: "bash -c \"curl -X GET -u ${ARTIFACTORY_LOGIN}:${ARTIFACTORY_PASSWORD} \'${url}\'\"",
128 returnStdout: true).trim()
129 }
130 def properties = new groovy.json.JsonSlurperClassic().parseText(result)
131 return properties.get("properties")
132}
133
134/**
Denis Egorenkoedd21dc2018-11-23 17:38:17 +0400135 * Check if image with tag exist by provided path
136 * Returns true or false
137 *
138 * @param artifactoryURL String, an URL to Artifactory
139 * @param imageRepo String, path to image to check, includes repo path and image name
140 * @param tag String, tag to check
141 * @param artifactoryCreds String, artifactory creds to use. Optional, default is 'artifactory'
142 */
143def imageExists(String artifactoryURL, String imageRepo, String tag, String artifactoryCreds = 'artifactory') {
144 def url = artifactoryURL + '/v2/' + imageRepo + '/manifest/' + tag
145 def result
146 withCredentials([
147 [$class : 'UsernamePasswordMultiBinding',
148 credentialsId : artifactoryCreds,
149 passwordVariable: 'ARTIFACTORY_PASSWORD',
150 usernameVariable: 'ARTIFACTORY_LOGIN']
151 ]) {
152 result = sh(script: "bash -c \"curl -X GET -u ${ARTIFACTORY_LOGIN}:${ARTIFACTORY_PASSWORD} \'${url}\'\"",
153 returnStdout: true).trim()
154 }
155 def properties = new groovy.json.JsonSlurperClassic().parseText(result)
156 return properties.get("errors") ? false : true
157}
158
159/**
Denis Egorenko7c0abfe2017-02-14 15:42:02 +0400160 * Find docker images by tag
161 * Returns Array of image' hashes with names as full path in @repo
162 *
163 * Example:
164 *
165 * [ {
166 * "path" : "mirantis/ccp/ci-cd/gerrit-manage/test"
167 * },
168 * {
169 * "path" : "mirantis/ccp/ci-cd/gerrit/test"
170 * }
171 * ]
172 *
173 * @param artifactoryURL String, an URL to Artifactory
174 * @param repo String, a name of repo where should be executed search
175 * @param tag String, tag of searched image
176 */
177def getImagesByTag(String artifactoryURL, String repo, String tag) {
178 def url = "${artifactoryURL}/api/search/aql"
179 def result
180 writeFile file: "query",
181 text: """\
182 items.find(
183 {
184 \"repo\": \"${repo}\",
185 \"@docker.manifest\": { \"\$match\" : \"${tag}*\" }
186 }
187 ).
188 include(\"path\")
189 """.stripIndent()
190 withCredentials([
191 [$class: 'UsernamePasswordMultiBinding',
192 credentialsId: 'artifactory',
193 passwordVariable: 'ARTIFACTORY_PASSWORD',
194 usernameVariable: 'ARTIFACTORY_LOGIN']
195 ]) {
196 result = sh(script: "bash -c \"curl -X POST -u ${ARTIFACTORY_LOGIN}:${ARTIFACTORY_PASSWORD} -d @query \'${url}\'\"",
197 returnStdout: true).trim()
198 }
199 def images = new groovy.json.JsonSlurperClassic().parseText(result)
200 return images.get("results")
201}
202
203/**
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +0300204 * Upload docker image to Artifactory
205 *
Sergey Kulanov8cd6d222016-11-17 13:42:47 +0200206 * @param server ArtifactoryServer, the instance of Artifactory server
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +0300207 * @param registry String, the name of Docker registry
208 * @param image String, Docker image name
209 * @param version String, Docker image version
210 * @param repository String, The name of Artifactory Docker repository
Sergey Kulanov8cd6d222016-11-17 13:42:47 +0200211 * @param buildInfo BuildInfo, the instance of a build-info object which can be published,
212 * if defined, then we publish BuildInfo
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +0300213 */
Sergey Kulanov8cd6d222016-11-17 13:42:47 +0200214def uploadImageToArtifactory (ArtifactoryServer server, String registry, String image,
215 String version, String repository,
Dmitry Burmistrov6ee39522017-05-22 12:46:25 +0400216 BuildInfo buildInfo = null,
217 LinkedHashMap properties = null) {
Denis Egorenkoedba5a52016-11-15 19:55:56 +0300218 // TODO Switch to Artifactoy image' pushing mechanism once we will
219 // prepare automatical way for enabling artifactory build-proxy
220 //def artDocker
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +0300221 withCredentials([
222 [$class: 'UsernamePasswordMultiBinding',
223 credentialsId: 'artifactory',
224 passwordVariable: 'ARTIFACTORY_PASSWORD',
225 usernameVariable: 'ARTIFACTORY_LOGIN']
226 ]) {
227 sh ("docker login -u ${ARTIFACTORY_LOGIN} -p ${ARTIFACTORY_PASSWORD} ${registry}")
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +0300228 //artDocker = Artifactory.docker("${env.ARTIFACTORY_LOGIN}", "${env.ARTIFACTORY_PASSWORD}")
229 }
230
Denis Egorenkoedba5a52016-11-15 19:55:56 +0300231 sh ("docker push ${registry}/${image}:${version}")
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +0300232 //artDocker.push("${registry}/${image}:${version}", "${repository}")
Sergey Kulanov8cd6d222016-11-17 13:42:47 +0200233 def image_url = server.getUrl() + "/api/storage/${repository}/${image}/${version}"
Dmitry Burmistrov6ee39522017-05-22 12:46:25 +0400234 if ( ! properties ) {
235 properties = [
Sergey Kulanovc70f1c22016-11-16 13:05:20 +0200236 'com.mirantis.buildName':"${env.JOB_NAME}",
237 'com.mirantis.buildNumber': "${env.BUILD_NUMBER}",
238 'com.mirantis.gerritProject': "${env.GERRIT_PROJECT}",
239 'com.mirantis.gerritChangeNumber': "${env.GERRIT_CHANGE_NUMBER}",
240 'com.mirantis.gerritPatchsetNumber': "${env.GERRIT_PATCHSET_NUMBER}",
241 'com.mirantis.gerritChangeId': "${env.GERRIT_CHANGE_ID}",
242 'com.mirantis.gerritPatchsetRevision': "${env.GERRIT_PATCHSET_REVISION}",
Sergey Kulanov4d3951c2016-11-24 13:58:15 +0200243 'com.mirantis.targetImg': "${image}",
Sergey Kulanovc70f1c22016-11-16 13:05:20 +0200244 'com.mirantis.targetTag': "${version}"
Dmitry Burmistrov6ee39522017-05-22 12:46:25 +0400245 ]
246 }
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +0300247
248 setProperties(image_url, properties)
Sergey Kulanov8cd6d222016-11-17 13:42:47 +0200249
250 if ( buildInfo != null ) {
251 buildInfo.env.capture = true
252 buildInfo.env.filter.addInclude("*")
253 buildInfo.env.filter.addExclude("*PASSWORD*")
254 buildInfo.env.filter.addExclude("*password*")
255 buildInfo.env.collect()
256 server.publishBuildInfo(buildInfo)
257 }
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +0300258}
259
260/**
261 * Upload binaries to Artifactory
262 *
263 * @param server ArtifactoryServer, the instance of Artifactory server
264 * @param buildInfo BuildInfo, the instance of a build-info object which can be published
265 * @param uploadSpec String, a spec which is a JSON file that specifies which files should be
266 * uploaded or downloaded and the target path
267 * @param publishInfo Boolean, whether publish a build-info object to Artifactory
268 */
Sergey Kulanov91d8def2016-11-15 13:53:17 +0200269def uploadBinariesToArtifactory (ArtifactoryServer server, BuildInfo buildInfo, String uploadSpec,
270 Boolean publishInfo = false) {
Jakub Josefbefcf6c2017-11-14 18:03:10 +0100271 server.upload(uploadSpec, buildInfo)
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +0300272
273 if ( publishInfo ) {
274 buildInfo.env.capture = true
275 buildInfo.env.filter.addInclude("*")
276 buildInfo.env.filter.addExclude("*PASSWORD*")
277 buildInfo.env.filter.addExclude("*password*")
278 buildInfo.env.collect()
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +0300279 server.publishBuildInfo(buildInfo)
280 }
281}
282
283/**
284 * Promote Docker image artifact to release repo
285 *
286 * @param artifactoryURL String, an URL to Artifactory
287 * @param artifactoryDevRepo String, the source dev repository name
288 * @param artifactoryProdRepo String, the target repository for the move or copy
289 * @param dockerRepo String, the docker repository name to promote
290 * @param artifactTag String, an image tag name to promote
291 * @param targetTag String, target tag to assign the image after promotion
292 * @param copy Boolean, an optional value to set whether to copy instead of move
293 * Default: false
294 */
295def promoteDockerArtifact(String artifactoryURL, String artifactoryDevRepo,
296 String artifactoryProdRepo, String dockerRepo,
297 String artifactTag, String targetTag, Boolean copy = false) {
298 def url = "${artifactoryURL}/api/docker/${artifactoryDevRepo}/v2/promote"
Dmitry Burmistrov5deaa7d2017-05-30 17:12:54 +0400299 String queryFile = UUID.randomUUID().toString()
Dmitry Burmistrov97beb9b2017-05-29 17:21:34 +0400300 writeFile file: queryFile,
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +0300301 text: """{
302 \"targetRepo\": \"${artifactoryProdRepo}\",
303 \"dockerRepository\": \"${dockerRepo}\",
304 \"tag\": \"${artifactTag}\",
305 \"targetTag\" : \"${targetTag}\",
306 \"copy\": \"${copy}\"
307 }""".stripIndent()
Dmitry Burmistrov97beb9b2017-05-29 17:21:34 +0400308 sh "cat ${queryFile}"
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +0300309 withCredentials([
310 [$class : 'UsernamePasswordMultiBinding',
311 credentialsId : 'artifactory',
312 passwordVariable: 'ARTIFACTORY_PASSWORD',
313 usernameVariable: 'ARTIFACTORY_LOGIN']
314 ]) {
Sergey Reshetnyakf0775fb2018-06-28 14:54:01 +0400315 sh "bash -c \"curl --fail -u ${ARTIFACTORY_LOGIN}:${ARTIFACTORY_PASSWORD} -H \"Content-Type:application/json\" -X POST -d @${queryFile} ${url}\""
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +0300316 }
Dmitry Burmistrov97beb9b2017-05-29 17:21:34 +0400317 sh "rm -v ${queryFile}"
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +0300318}
Denis Egorenko60f47c12019-03-11 20:54:13 +0400319
320/**
321 * Save job artifacts to Artifactory server if available.
322 * Returns link to Artifactory repo, where saved job artifacts.
323 *
324 * @param config LinkedHashMap which contains next parameters:
325 * @param artifactory String, Artifactory server id
326 * @param artifactoryRepo String, repo to save job artifacts
327 * @param buildProps ArrayList, additional props for saved artifacts. Optional, default: []
328 * @param artifactory_not_found_fail Boolean, whether to fail if provided artifactory
329 * id is not found or just print warning message. Optional, default: false
330 */
331def uploadJobArtifactsToArtifactory(LinkedHashMap config) {
332 def common = new com.mirantis.mk.Common()
333 def artifactsDescription = ''
334 def artifactoryServer
335 try {
336 artifactoryServer = Artifactory.server(config.get('artifactory'))
337 } catch (Exception e) {
338 if (config.get('artifactory_not_found_fail', false)) {
339 throw e
340 } else {
341 common.warningMsg(e)
342 return "Artifactory server is not found. Can't save artifacts in Artifactory."
343 }
344 }
345 def artifactDir = 'cur_build_artifacts'
346 def user = ''
347 wrap([$class: 'BuildUser']) {
348 user = env.BUILD_USER_ID
349 }
350 dir(artifactDir) {
351 try {
Denis Egorenko5fc40f82019-03-13 18:35:51 +0400352 unarchive(mapping: ['**/*' : '.'])
Denis Egorenko60f47c12019-03-11 20:54:13 +0400353 // Mandatory and additional properties
354 def properties = getBinaryBuildProperties(config.get('buildProps', []) << "buildUser=${user}")
355
356 // Build Artifactory spec object
357 def uploadSpec = """{
358 "files":
359 [
360 {
361 "pattern": "*",
362 "target": "${config.get('artifactoryRepo')}/",
Denis Egorenko850f56a2019-03-13 20:44:43 +0400363 "flat": false,
Denis Egorenko60f47c12019-03-11 20:54:13 +0400364 "props": "${properties}"
365 }
366 ]
367 }"""
368
369 artifactoryServer.upload(uploadSpec, newBuildInfo())
370 def linkUrl = "${artifactoryServer.getUrl()}/artifactory/${config.get('artifactoryRepo')}"
371 artifactsDescription = "Job artifacts uploaded to Artifactory: <a href=\"${linkUrl}\">${linkUrl}</a>"
372 } catch (Exception e) {
373 if (e =~ /no artifacts/) {
374 artifactsDescription = 'Build has no artifacts saved.'
375 } else {
376 throw e
377 }
378 } finally {
379 deleteDir()
380 }
381 }
382 return artifactsDescription
383}