blob: fd01573b2d0d4d55beada6b179bcdc450fb72f67 [file] [log] [blame]
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +03001package com.mirantis.mcp
2
Sergey Kolekonov74a6b6e2019-06-28 11:45:47 +04003import org.jfrog.hudson.pipeline.common.types.ArtifactoryServer
4import org.jfrog.hudson.pipeline.common.types.buildInfo.BuildInfo
Sergey Kulanov91d8def2016-11-15 13:53:17 +02005
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/**
Sergey Kolekonov76c17f52019-09-09 16:55:01 +0400113 * Create an empty directory in Artifactory repo
114 *
115 * @param artifactoryURL String, an URL to Artifactory
116 * @param path String, a path to the desired directory including repository name
117 * @param dir String, desired directory name
118 */
119def createDir (String artifactoryURL, String path, String dir) {
120 def url = "${artifactoryURL}/${path}/${dir}/"
121 withCredentials([
122 [$class : 'UsernamePasswordMultiBinding',
123 credentialsId : 'artifactory',
124 passwordVariable: 'ARTIFACTORY_PASSWORD',
125 usernameVariable: 'ARTIFACTORY_LOGIN']
126 ]) {
127 sh "bash -c \"curl -X PUT -u ${ARTIFACTORY_LOGIN}:${ARTIFACTORY_PASSWORD} \'${url}\'\""
128 }
129}
130
131/**
Sergey Kolekonovce616712019-09-10 16:09:23 +0400132 * Move/copy an artifact or a folder to the specified destination
133 *
134 * @param artifactoryURL String, an URL to Artifactory
135 * @param sourcePath String, a source path to the artifact including repository name
136 * @param dstPath String, a destination path to the artifact including repository name
137 * @param copy boolean, whether to copy or move the item, default is move
138 * @param dryRun boolean, whether to perform dry run on not, default is false
139 */
140def moveItem (String artifactoryURL, String sourcePath, String dstPath, boolean copy = false, boolean dryRun = false) {
141 def url = "${artifactoryURL}/api/${copy ? 'copy' : 'move'}/${sourcePath}?to=/${dstPath}&dry=${dryRun ? '1' : '0'}"
Alexandr Lovtsov066f4882021-01-18 17:29:26 +0300142 def http = new com.mirantis.mk.Http()
143 return http.doPost(url, 'artifactory')
Sergey Kolekonovce616712019-09-10 16:09:23 +0400144}
145
146/**
147 * Recursively delete the specified artifact or a folder
148 *
149 * @param artifactoryURL String, an URL to Artifactory
150 * @param itemPath String, a source path to the item including repository name
151 */
152def deleteItem (String artifactoryURL, String itemPath) {
153 def url = "${artifactoryURL}/${itemPath}"
154 withCredentials([
155 [$class : 'UsernamePasswordMultiBinding',
156 credentialsId : 'artifactory',
157 passwordVariable: 'ARTIFACTORY_PASSWORD',
158 usernameVariable: 'ARTIFACTORY_LOGIN']
159 ]) {
160 sh "bash -c \"curl -X DELETE -u ${ARTIFACTORY_LOGIN}:${ARTIFACTORY_PASSWORD} \'${url}\'\""
161 }
162}
163
164/**
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +0300165 * Get properties for specified artifact in Artifactory
166 * Returns LinkedHashMap of properties
167 *
168 * @param artifactUrl String, an URL to artifact in Artifactory repo
169 */
170def getPropertiesForArtifact(String artifactUrl) {
171 def url = "${artifactUrl}?properties"
172 def result
173 withCredentials([
174 [$class : 'UsernamePasswordMultiBinding',
175 credentialsId : 'artifactory',
176 passwordVariable: 'ARTIFACTORY_PASSWORD',
177 usernameVariable: 'ARTIFACTORY_LOGIN']
178 ]) {
179 result = sh(script: "bash -c \"curl -X GET -u ${ARTIFACTORY_LOGIN}:${ARTIFACTORY_PASSWORD} \'${url}\'\"",
180 returnStdout: true).trim()
181 }
182 def properties = new groovy.json.JsonSlurperClassic().parseText(result)
183 return properties.get("properties")
184}
185
186/**
vnaumov5b2dccf2019-10-10 22:12:15 +0200187 * Get checksums of artifact
188 *
189 * @param artifactoryUrl String, an URL ofArtifactory repo
190 * @param repoName Artifact repository name
191 * @param artifactName Artifactory object name
192 * @param checksumType Type of checksum (default md5)
193 */
194
195def getArtifactChecksum(artifactoryUrl, repoName, artifactName, checksumType = 'md5'){
196 def url = "${artifactoryUrl}/api/storage/${repoName}/${artifactName}"
197 withCredentials([
198 [$class : 'UsernamePasswordMultiBinding',
199 credentialsId : 'artifactory',
200 passwordVariable: 'ARTIFACTORY_PASSWORD',
201 usernameVariable: 'ARTIFACTORY_LOGIN']
202 ]) {
203 def result = sh(script: "bash -c \"curl -X GET -u ${ARTIFACTORY_LOGIN}:${ARTIFACTORY_PASSWORD} \'${url}\'\"",
204 returnStdout: true).trim()
205 }
206
207 def properties = new groovy.json.JsonSlurperClassic().parseText(result)
208 return properties['checksums'][checksumType]
209}
210
211/**
Denis Egorenkoedd21dc2018-11-23 17:38:17 +0400212 * Check if image with tag exist by provided path
213 * Returns true or false
214 *
215 * @param artifactoryURL String, an URL to Artifactory
216 * @param imageRepo String, path to image to check, includes repo path and image name
217 * @param tag String, tag to check
218 * @param artifactoryCreds String, artifactory creds to use. Optional, default is 'artifactory'
219 */
220def imageExists(String artifactoryURL, String imageRepo, String tag, String artifactoryCreds = 'artifactory') {
Sergey Otpuschennikov406778f2019-10-10 14:49:40 +0400221 def url = artifactoryURL + '/v2/' + imageRepo + '/manifests/' + tag
Denis Egorenkoedd21dc2018-11-23 17:38:17 +0400222 def result
223 withCredentials([
224 [$class : 'UsernamePasswordMultiBinding',
225 credentialsId : artifactoryCreds,
226 passwordVariable: 'ARTIFACTORY_PASSWORD',
227 usernameVariable: 'ARTIFACTORY_LOGIN']
228 ]) {
229 result = sh(script: "bash -c \"curl -X GET -u ${ARTIFACTORY_LOGIN}:${ARTIFACTORY_PASSWORD} \'${url}\'\"",
230 returnStdout: true).trim()
231 }
232 def properties = new groovy.json.JsonSlurperClassic().parseText(result)
233 return properties.get("errors") ? false : true
234}
235
236/**
Denis Egorenko7c0abfe2017-02-14 15:42:02 +0400237 * Find docker images by tag
238 * Returns Array of image' hashes with names as full path in @repo
239 *
240 * Example:
241 *
242 * [ {
243 * "path" : "mirantis/ccp/ci-cd/gerrit-manage/test"
244 * },
245 * {
246 * "path" : "mirantis/ccp/ci-cd/gerrit/test"
247 * }
248 * ]
249 *
250 * @param artifactoryURL String, an URL to Artifactory
251 * @param repo String, a name of repo where should be executed search
252 * @param tag String, tag of searched image
253 */
254def getImagesByTag(String artifactoryURL, String repo, String tag) {
255 def url = "${artifactoryURL}/api/search/aql"
256 def result
257 writeFile file: "query",
258 text: """\
259 items.find(
260 {
261 \"repo\": \"${repo}\",
262 \"@docker.manifest\": { \"\$match\" : \"${tag}*\" }
263 }
264 ).
265 include(\"path\")
266 """.stripIndent()
267 withCredentials([
268 [$class: 'UsernamePasswordMultiBinding',
269 credentialsId: 'artifactory',
270 passwordVariable: 'ARTIFACTORY_PASSWORD',
271 usernameVariable: 'ARTIFACTORY_LOGIN']
272 ]) {
273 result = sh(script: "bash -c \"curl -X POST -u ${ARTIFACTORY_LOGIN}:${ARTIFACTORY_PASSWORD} -d @query \'${url}\'\"",
274 returnStdout: true).trim()
275 }
276 def images = new groovy.json.JsonSlurperClassic().parseText(result)
277 return images.get("results")
278}
279
280/**
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +0300281 * Upload docker image to Artifactory
282 *
Sergey Kulanov8cd6d222016-11-17 13:42:47 +0200283 * @param server ArtifactoryServer, the instance of Artifactory server
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +0300284 * @param registry String, the name of Docker registry
285 * @param image String, Docker image name
286 * @param version String, Docker image version
287 * @param repository String, The name of Artifactory Docker repository
Sergey Kulanov8cd6d222016-11-17 13:42:47 +0200288 * @param buildInfo BuildInfo, the instance of a build-info object which can be published,
289 * if defined, then we publish BuildInfo
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +0300290 */
Sergey Kulanov8cd6d222016-11-17 13:42:47 +0200291def uploadImageToArtifactory (ArtifactoryServer server, String registry, String image,
292 String version, String repository,
Dmitry Burmistrov6ee39522017-05-22 12:46:25 +0400293 BuildInfo buildInfo = null,
294 LinkedHashMap properties = null) {
Denis Egorenkoedba5a52016-11-15 19:55:56 +0300295 // TODO Switch to Artifactoy image' pushing mechanism once we will
296 // prepare automatical way for enabling artifactory build-proxy
297 //def artDocker
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +0300298 withCredentials([
299 [$class: 'UsernamePasswordMultiBinding',
300 credentialsId: 'artifactory',
301 passwordVariable: 'ARTIFACTORY_PASSWORD',
302 usernameVariable: 'ARTIFACTORY_LOGIN']
303 ]) {
304 sh ("docker login -u ${ARTIFACTORY_LOGIN} -p ${ARTIFACTORY_PASSWORD} ${registry}")
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +0300305 //artDocker = Artifactory.docker("${env.ARTIFACTORY_LOGIN}", "${env.ARTIFACTORY_PASSWORD}")
306 }
307
Denis Egorenkoedba5a52016-11-15 19:55:56 +0300308 sh ("docker push ${registry}/${image}:${version}")
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +0300309 //artDocker.push("${registry}/${image}:${version}", "${repository}")
Sergey Kulanov8cd6d222016-11-17 13:42:47 +0200310 def image_url = server.getUrl() + "/api/storage/${repository}/${image}/${version}"
Dmitry Burmistrov6ee39522017-05-22 12:46:25 +0400311 if ( ! properties ) {
312 properties = [
Sergey Kulanovc70f1c22016-11-16 13:05:20 +0200313 'com.mirantis.buildName':"${env.JOB_NAME}",
314 'com.mirantis.buildNumber': "${env.BUILD_NUMBER}",
315 'com.mirantis.gerritProject': "${env.GERRIT_PROJECT}",
316 'com.mirantis.gerritChangeNumber': "${env.GERRIT_CHANGE_NUMBER}",
317 'com.mirantis.gerritPatchsetNumber': "${env.GERRIT_PATCHSET_NUMBER}",
318 'com.mirantis.gerritChangeId': "${env.GERRIT_CHANGE_ID}",
319 'com.mirantis.gerritPatchsetRevision': "${env.GERRIT_PATCHSET_REVISION}",
Sergey Kulanov4d3951c2016-11-24 13:58:15 +0200320 'com.mirantis.targetImg': "${image}",
Sergey Kulanovc70f1c22016-11-16 13:05:20 +0200321 'com.mirantis.targetTag': "${version}"
Dmitry Burmistrov6ee39522017-05-22 12:46:25 +0400322 ]
323 }
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +0300324
325 setProperties(image_url, properties)
Sergey Kulanov8cd6d222016-11-17 13:42:47 +0200326
327 if ( buildInfo != null ) {
328 buildInfo.env.capture = true
329 buildInfo.env.filter.addInclude("*")
330 buildInfo.env.filter.addExclude("*PASSWORD*")
331 buildInfo.env.filter.addExclude("*password*")
332 buildInfo.env.collect()
333 server.publishBuildInfo(buildInfo)
334 }
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +0300335}
336
337/**
338 * Upload binaries to Artifactory
339 *
340 * @param server ArtifactoryServer, the instance of Artifactory server
341 * @param buildInfo BuildInfo, the instance of a build-info object which can be published
342 * @param uploadSpec String, a spec which is a JSON file that specifies which files should be
343 * uploaded or downloaded and the target path
344 * @param publishInfo Boolean, whether publish a build-info object to Artifactory
345 */
Sergey Kulanov91d8def2016-11-15 13:53:17 +0200346def uploadBinariesToArtifactory (ArtifactoryServer server, BuildInfo buildInfo, String uploadSpec,
347 Boolean publishInfo = false) {
Jakub Josefbefcf6c2017-11-14 18:03:10 +0100348 server.upload(uploadSpec, buildInfo)
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +0300349
350 if ( publishInfo ) {
351 buildInfo.env.capture = true
352 buildInfo.env.filter.addInclude("*")
353 buildInfo.env.filter.addExclude("*PASSWORD*")
354 buildInfo.env.filter.addExclude("*password*")
355 buildInfo.env.collect()
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +0300356 server.publishBuildInfo(buildInfo)
357 }
358}
359
360/**
361 * Promote Docker image artifact to release repo
362 *
363 * @param artifactoryURL String, an URL to Artifactory
364 * @param artifactoryDevRepo String, the source dev repository name
365 * @param artifactoryProdRepo String, the target repository for the move or copy
366 * @param dockerRepo String, the docker repository name to promote
367 * @param artifactTag String, an image tag name to promote
368 * @param targetTag String, target tag to assign the image after promotion
369 * @param copy Boolean, an optional value to set whether to copy instead of move
370 * Default: false
371 */
372def promoteDockerArtifact(String artifactoryURL, String artifactoryDevRepo,
373 String artifactoryProdRepo, String dockerRepo,
374 String artifactTag, String targetTag, Boolean copy = false) {
375 def url = "${artifactoryURL}/api/docker/${artifactoryDevRepo}/v2/promote"
Dmitry Burmistrov5deaa7d2017-05-30 17:12:54 +0400376 String queryFile = UUID.randomUUID().toString()
Dmitry Burmistrov97beb9b2017-05-29 17:21:34 +0400377 writeFile file: queryFile,
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +0300378 text: """{
379 \"targetRepo\": \"${artifactoryProdRepo}\",
380 \"dockerRepository\": \"${dockerRepo}\",
381 \"tag\": \"${artifactTag}\",
382 \"targetTag\" : \"${targetTag}\",
383 \"copy\": \"${copy}\"
384 }""".stripIndent()
Dmitry Burmistrov97beb9b2017-05-29 17:21:34 +0400385 sh "cat ${queryFile}"
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +0300386 withCredentials([
387 [$class : 'UsernamePasswordMultiBinding',
388 credentialsId : 'artifactory',
389 passwordVariable: 'ARTIFACTORY_PASSWORD',
390 usernameVariable: 'ARTIFACTORY_LOGIN']
391 ]) {
Sergey Reshetnyakf0775fb2018-06-28 14:54:01 +0400392 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 +0300393 }
Dmitry Burmistrov97beb9b2017-05-29 17:21:34 +0400394 sh "rm -v ${queryFile}"
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +0300395}
Denis Egorenko60f47c12019-03-11 20:54:13 +0400396
397/**
398 * Save job artifacts to Artifactory server if available.
399 * Returns link to Artifactory repo, where saved job artifacts.
400 *
401 * @param config LinkedHashMap which contains next parameters:
402 * @param artifactory String, Artifactory server id
403 * @param artifactoryRepo String, repo to save job artifacts
404 * @param buildProps ArrayList, additional props for saved artifacts. Optional, default: []
405 * @param artifactory_not_found_fail Boolean, whether to fail if provided artifactory
406 * id is not found or just print warning message. Optional, default: false
407 */
408def uploadJobArtifactsToArtifactory(LinkedHashMap config) {
409 def common = new com.mirantis.mk.Common()
410 def artifactsDescription = ''
411 def artifactoryServer
Dmitry Tyzhnenko9ade0722020-03-31 13:17:54 +0300412
413 if (!config.containsKey('deleteArtifacts')) {
414 config.deleteArtifacts = true // default behavior before add the flag
415 }
416
Denis Egorenko60f47c12019-03-11 20:54:13 +0400417 try {
418 artifactoryServer = Artifactory.server(config.get('artifactory'))
419 } catch (Exception e) {
420 if (config.get('artifactory_not_found_fail', false)) {
421 throw e
422 } else {
423 common.warningMsg(e)
424 return "Artifactory server is not found. Can't save artifacts in Artifactory."
425 }
426 }
Dmitry Tyzhnenko812673a2020-03-26 21:59:14 +0200427 def artifactDir = config.get('artifactDir') ?: 'cur_build_artifacts'
Denis Egorenko60f47c12019-03-11 20:54:13 +0400428 def user = ''
429 wrap([$class: 'BuildUser']) {
430 user = env.BUILD_USER_ID
431 }
432 dir(artifactDir) {
433 try {
Denis Egorenko5fc40f82019-03-13 18:35:51 +0400434 unarchive(mapping: ['**/*' : '.'])
Denis Egorenko60f47c12019-03-11 20:54:13 +0400435 // Mandatory and additional properties
436 def properties = getBinaryBuildProperties(config.get('buildProps', []) << "buildUser=${user}")
Dmitry Tyzhnenko812673a2020-03-26 21:59:14 +0200437 def pattern = config.get('artifactPattern') ?: '*'
Denis Egorenko60f47c12019-03-11 20:54:13 +0400438
439 // Build Artifactory spec object
440 def uploadSpec = """{
441 "files":
442 [
443 {
Dmitry Tyzhnenko812673a2020-03-26 21:59:14 +0200444 "pattern": "${pattern}",
Denis Egorenko60f47c12019-03-11 20:54:13 +0400445 "target": "${config.get('artifactoryRepo')}/",
Denis Egorenko850f56a2019-03-13 20:44:43 +0400446 "flat": false,
Denis Egorenko60f47c12019-03-11 20:54:13 +0400447 "props": "${properties}"
448 }
449 ]
450 }"""
451
452 artifactoryServer.upload(uploadSpec, newBuildInfo())
453 def linkUrl = "${artifactoryServer.getUrl()}/artifactory/${config.get('artifactoryRepo')}"
454 artifactsDescription = "Job artifacts uploaded to Artifactory: <a href=\"${linkUrl}\">${linkUrl}</a>"
455 } catch (Exception e) {
456 if (e =~ /no artifacts/) {
457 artifactsDescription = 'Build has no artifacts saved.'
458 } else {
459 throw e
460 }
461 } finally {
Dmitry Tyzhnenko9ade0722020-03-31 13:17:54 +0300462 if (config.deleteArtifacts) {
463 deleteDir()
464 }
Denis Egorenko60f47c12019-03-11 20:54:13 +0400465 }
466 }
467 return artifactsDescription
468}
Dmitry Tyzhnenko39cf09c2020-05-05 20:08:52 +0300469
470/**
471 * Save custom artifacts to Artifactory server if available.
472 * Returns link to Artifactory repo, where saved artifacts.
473 *
474 * @param config LinkedHashMap which contains next parameters:
475 * @param artifactory String, Artifactory server id
476 * @param artifactoryRepo String, repo to save job artifacts
477 * @param buildProps ArrayList, additional props for saved artifacts. Optional, default: []
478 * @param artifactory_not_found_fail Boolean, whether to fail if provided artifactory
479 * id is not found or just print warning message. Optional, default: false
480 */
481def uploadArtifactsToArtifactory(LinkedHashMap config) {
482 def common = new com.mirantis.mk.Common()
483 def artifactsDescription = ''
484 def artifactoryServer
485
486 try {
487 artifactoryServer = Artifactory.server(config.get('artifactory'))
488 } catch (Exception e) {
489 if (config.get('artifactory_not_found_fail', false)) {
490 throw e
491 } else {
492 common.warningMsg(e)
493 return "Artifactory server is not found. Can't save artifacts in Artifactory."
494 }
495 }
496 def user = ''
497 wrap([$class: 'BuildUser']) {
498 user = env.BUILD_USER_ID
499 }
500 try {
501 // Mandatory and additional properties
502 def properties = getBinaryBuildProperties(config.get('buildProps', []) << "buildUser=${user}")
503 def pattern = config.get('artifactPattern') ?: '*'
504
505 // Build Artifactory spec object
506 def uploadSpec = """{
507 "files":
508 [
509 {
510 "pattern": "${pattern}",
511 "target": "${config.get('artifactoryRepo')}/",
512 "flat": false,
513 "props": "${properties}"
514 }
515 ]
516 }"""
517
518 artifactoryServer.upload(uploadSpec, newBuildInfo())
Alexandr Lovtsov9293d992021-01-19 19:55:41 +0300519 def linkUrl = "${artifactoryServer.getUrl()}/${config.get('artifactoryRepo')}"
Dmitry Tyzhnenko39cf09c2020-05-05 20:08:52 +0300520 artifactsDescription = "Job artifacts uploaded to Artifactory: <a href=\"${linkUrl}\">${linkUrl}</a>"
521 } catch (Exception e) {
522 if (e =~ /no artifacts/) {
523 artifactsDescription = 'Build has no artifacts saved.'
524 } else {
525 throw e
526 }
527 }
528 return artifactsDescription
529}