blob: 83b1975861928e1f9ba5d045bb003df15ca3e1b4 [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}"
Alexandr Lovtsov89d24a52021-01-28 17:41:14 +0300154 def http = new com.mirantis.mk.Http()
155 return http.doDelete(url, 'artifactory')
Sergey Kolekonovce616712019-09-10 16:09:23 +0400156}
157
158/**
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +0300159 * Get properties for specified artifact in Artifactory
160 * Returns LinkedHashMap of properties
161 *
162 * @param artifactUrl String, an URL to artifact in Artifactory repo
163 */
164def getPropertiesForArtifact(String artifactUrl) {
165 def url = "${artifactUrl}?properties"
166 def result
167 withCredentials([
168 [$class : 'UsernamePasswordMultiBinding',
169 credentialsId : 'artifactory',
170 passwordVariable: 'ARTIFACTORY_PASSWORD',
171 usernameVariable: 'ARTIFACTORY_LOGIN']
172 ]) {
173 result = sh(script: "bash -c \"curl -X GET -u ${ARTIFACTORY_LOGIN}:${ARTIFACTORY_PASSWORD} \'${url}\'\"",
174 returnStdout: true).trim()
175 }
176 def properties = new groovy.json.JsonSlurperClassic().parseText(result)
177 return properties.get("properties")
178}
179
180/**
vnaumov5b2dccf2019-10-10 22:12:15 +0200181 * Get checksums of artifact
182 *
183 * @param artifactoryUrl String, an URL ofArtifactory repo
184 * @param repoName Artifact repository name
185 * @param artifactName Artifactory object name
186 * @param checksumType Type of checksum (default md5)
187 */
188
189def getArtifactChecksum(artifactoryUrl, repoName, artifactName, checksumType = 'md5'){
190 def url = "${artifactoryUrl}/api/storage/${repoName}/${artifactName}"
191 withCredentials([
192 [$class : 'UsernamePasswordMultiBinding',
193 credentialsId : 'artifactory',
194 passwordVariable: 'ARTIFACTORY_PASSWORD',
195 usernameVariable: 'ARTIFACTORY_LOGIN']
196 ]) {
197 def result = sh(script: "bash -c \"curl -X GET -u ${ARTIFACTORY_LOGIN}:${ARTIFACTORY_PASSWORD} \'${url}\'\"",
198 returnStdout: true).trim()
199 }
200
201 def properties = new groovy.json.JsonSlurperClassic().parseText(result)
202 return properties['checksums'][checksumType]
203}
204
205/**
Denis Egorenkoedd21dc2018-11-23 17:38:17 +0400206 * Check if image with tag exist by provided path
207 * Returns true or false
208 *
209 * @param artifactoryURL String, an URL to Artifactory
210 * @param imageRepo String, path to image to check, includes repo path and image name
211 * @param tag String, tag to check
212 * @param artifactoryCreds String, artifactory creds to use. Optional, default is 'artifactory'
213 */
214def imageExists(String artifactoryURL, String imageRepo, String tag, String artifactoryCreds = 'artifactory') {
Sergey Otpuschennikov406778f2019-10-10 14:49:40 +0400215 def url = artifactoryURL + '/v2/' + imageRepo + '/manifests/' + tag
Denis Egorenkoedd21dc2018-11-23 17:38:17 +0400216 def result
217 withCredentials([
218 [$class : 'UsernamePasswordMultiBinding',
219 credentialsId : artifactoryCreds,
220 passwordVariable: 'ARTIFACTORY_PASSWORD',
221 usernameVariable: 'ARTIFACTORY_LOGIN']
222 ]) {
223 result = sh(script: "bash -c \"curl -X GET -u ${ARTIFACTORY_LOGIN}:${ARTIFACTORY_PASSWORD} \'${url}\'\"",
224 returnStdout: true).trim()
225 }
226 def properties = new groovy.json.JsonSlurperClassic().parseText(result)
227 return properties.get("errors") ? false : true
228}
229
230/**
Denis Egorenko7c0abfe2017-02-14 15:42:02 +0400231 * Find docker images by tag
232 * Returns Array of image' hashes with names as full path in @repo
233 *
234 * Example:
235 *
236 * [ {
237 * "path" : "mirantis/ccp/ci-cd/gerrit-manage/test"
238 * },
239 * {
240 * "path" : "mirantis/ccp/ci-cd/gerrit/test"
241 * }
242 * ]
243 *
244 * @param artifactoryURL String, an URL to Artifactory
245 * @param repo String, a name of repo where should be executed search
246 * @param tag String, tag of searched image
247 */
248def getImagesByTag(String artifactoryURL, String repo, String tag) {
249 def url = "${artifactoryURL}/api/search/aql"
250 def result
251 writeFile file: "query",
252 text: """\
253 items.find(
254 {
255 \"repo\": \"${repo}\",
256 \"@docker.manifest\": { \"\$match\" : \"${tag}*\" }
257 }
258 ).
259 include(\"path\")
260 """.stripIndent()
261 withCredentials([
262 [$class: 'UsernamePasswordMultiBinding',
263 credentialsId: 'artifactory',
264 passwordVariable: 'ARTIFACTORY_PASSWORD',
265 usernameVariable: 'ARTIFACTORY_LOGIN']
266 ]) {
267 result = sh(script: "bash -c \"curl -X POST -u ${ARTIFACTORY_LOGIN}:${ARTIFACTORY_PASSWORD} -d @query \'${url}\'\"",
268 returnStdout: true).trim()
269 }
270 def images = new groovy.json.JsonSlurperClassic().parseText(result)
271 return images.get("results")
272}
273
274/**
Alexandr Lovtsova0295432021-01-28 17:20:32 +0300275 * Convert Mirantis docker image url/path to Mirantis artifactory path ready for use in API calls
276 *
277 * For example:
278 * 'docker-dev-kaas-local.docker.mirantis.net/mirantis/kaas/si-test:master' -> 'docker-dev-kaas-local/mirantis/kaas/si-test/master'
279 *
280 */
281def dockerImageToArtifactoryPath(String image) {
282 List imageParts = image.tokenize('/')
283 String repoName = imageParts[0].tokenize('.')[0]
284 String namespace = imageParts[1..-2].join('/')
285 String imageName = imageParts[-1].tokenize(':')[0]
286 String imageTag = imageParts[-1].tokenize(':')[1]
287
288 return [repoName, namespace, imageName, imageTag].join('/')
289}
290
291/**
Alexandr Lovtsov8fb5d7c2021-01-28 17:42:24 +0300292 * Copy docker image from one url to another
293 *
294 * @param srcImage String, Mirantis URL/path for docker image to copy from
295 * @param dstImage String, Mirantis URL/path for docker image to copy to
296 */
297def copyDockerImage(String srcImage, String dstImage) {
298 def artifactoryServer = Artifactory.server(env.ARTIFACTORY_SERVER ?: 'mcp-ci')
299 String srcPath = dockerImageToArtifactoryPath(srcImage)
300 String dstPath = dockerImageToArtifactoryPath(dstImage)
301
302 return moveItem(artifactoryServer.getUrl(), srcPath, dstPath, true)
303}
304
305/**
306 * Delete docker image on Mirantis's artifactory
307 *
308 * @param image String, Mirantis URL/path for docker image to delete
309 */
310def deleteDockerImage(String image) {
311 def artifactoryServer = Artifactory.server(env.ARTIFACTORY_SERVER ?: 'mcp-ci')
312
313 return deleteItem(artifactoryServer.getUrl() + '/artifactory', dockerImageToArtifactoryPath(image))
314}
315
316/**
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +0300317 * Upload docker image to Artifactory
318 *
Sergey Kulanov8cd6d222016-11-17 13:42:47 +0200319 * @param server ArtifactoryServer, the instance of Artifactory server
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +0300320 * @param registry String, the name of Docker registry
321 * @param image String, Docker image name
322 * @param version String, Docker image version
323 * @param repository String, The name of Artifactory Docker repository
Sergey Kulanov8cd6d222016-11-17 13:42:47 +0200324 * @param buildInfo BuildInfo, the instance of a build-info object which can be published,
325 * if defined, then we publish BuildInfo
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +0300326 */
Sergey Kulanov8cd6d222016-11-17 13:42:47 +0200327def uploadImageToArtifactory (ArtifactoryServer server, String registry, String image,
328 String version, String repository,
Dmitry Burmistrov6ee39522017-05-22 12:46:25 +0400329 BuildInfo buildInfo = null,
330 LinkedHashMap properties = null) {
Denis Egorenkoedba5a52016-11-15 19:55:56 +0300331 // TODO Switch to Artifactoy image' pushing mechanism once we will
332 // prepare automatical way for enabling artifactory build-proxy
333 //def artDocker
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +0300334 withCredentials([
335 [$class: 'UsernamePasswordMultiBinding',
336 credentialsId: 'artifactory',
337 passwordVariable: 'ARTIFACTORY_PASSWORD',
338 usernameVariable: 'ARTIFACTORY_LOGIN']
339 ]) {
340 sh ("docker login -u ${ARTIFACTORY_LOGIN} -p ${ARTIFACTORY_PASSWORD} ${registry}")
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +0300341 //artDocker = Artifactory.docker("${env.ARTIFACTORY_LOGIN}", "${env.ARTIFACTORY_PASSWORD}")
342 }
343
Denis Egorenkoedba5a52016-11-15 19:55:56 +0300344 sh ("docker push ${registry}/${image}:${version}")
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +0300345 //artDocker.push("${registry}/${image}:${version}", "${repository}")
Sergey Kulanov8cd6d222016-11-17 13:42:47 +0200346 def image_url = server.getUrl() + "/api/storage/${repository}/${image}/${version}"
Dmitry Burmistrov6ee39522017-05-22 12:46:25 +0400347 if ( ! properties ) {
348 properties = [
Sergey Kulanovc70f1c22016-11-16 13:05:20 +0200349 'com.mirantis.buildName':"${env.JOB_NAME}",
350 'com.mirantis.buildNumber': "${env.BUILD_NUMBER}",
351 'com.mirantis.gerritProject': "${env.GERRIT_PROJECT}",
352 'com.mirantis.gerritChangeNumber': "${env.GERRIT_CHANGE_NUMBER}",
353 'com.mirantis.gerritPatchsetNumber': "${env.GERRIT_PATCHSET_NUMBER}",
354 'com.mirantis.gerritChangeId': "${env.GERRIT_CHANGE_ID}",
355 'com.mirantis.gerritPatchsetRevision': "${env.GERRIT_PATCHSET_REVISION}",
Sergey Kulanov4d3951c2016-11-24 13:58:15 +0200356 'com.mirantis.targetImg': "${image}",
Sergey Kulanovc70f1c22016-11-16 13:05:20 +0200357 'com.mirantis.targetTag': "${version}"
Dmitry Burmistrov6ee39522017-05-22 12:46:25 +0400358 ]
359 }
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +0300360
361 setProperties(image_url, properties)
Sergey Kulanov8cd6d222016-11-17 13:42:47 +0200362
363 if ( buildInfo != null ) {
364 buildInfo.env.capture = true
365 buildInfo.env.filter.addInclude("*")
366 buildInfo.env.filter.addExclude("*PASSWORD*")
367 buildInfo.env.filter.addExclude("*password*")
368 buildInfo.env.collect()
369 server.publishBuildInfo(buildInfo)
370 }
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +0300371}
372
373/**
374 * Upload binaries to Artifactory
375 *
376 * @param server ArtifactoryServer, the instance of Artifactory server
377 * @param buildInfo BuildInfo, the instance of a build-info object which can be published
378 * @param uploadSpec String, a spec which is a JSON file that specifies which files should be
379 * uploaded or downloaded and the target path
380 * @param publishInfo Boolean, whether publish a build-info object to Artifactory
381 */
Sergey Kulanov91d8def2016-11-15 13:53:17 +0200382def uploadBinariesToArtifactory (ArtifactoryServer server, BuildInfo buildInfo, String uploadSpec,
383 Boolean publishInfo = false) {
Jakub Josefbefcf6c2017-11-14 18:03:10 +0100384 server.upload(uploadSpec, buildInfo)
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +0300385
386 if ( publishInfo ) {
387 buildInfo.env.capture = true
388 buildInfo.env.filter.addInclude("*")
389 buildInfo.env.filter.addExclude("*PASSWORD*")
390 buildInfo.env.filter.addExclude("*password*")
391 buildInfo.env.collect()
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +0300392 server.publishBuildInfo(buildInfo)
393 }
394}
395
396/**
397 * Promote Docker image artifact to release repo
398 *
399 * @param artifactoryURL String, an URL to Artifactory
400 * @param artifactoryDevRepo String, the source dev repository name
401 * @param artifactoryProdRepo String, the target repository for the move or copy
402 * @param dockerRepo String, the docker repository name to promote
403 * @param artifactTag String, an image tag name to promote
404 * @param targetTag String, target tag to assign the image after promotion
405 * @param copy Boolean, an optional value to set whether to copy instead of move
406 * Default: false
407 */
408def promoteDockerArtifact(String artifactoryURL, String artifactoryDevRepo,
409 String artifactoryProdRepo, String dockerRepo,
410 String artifactTag, String targetTag, Boolean copy = false) {
411 def url = "${artifactoryURL}/api/docker/${artifactoryDevRepo}/v2/promote"
Dmitry Burmistrov5deaa7d2017-05-30 17:12:54 +0400412 String queryFile = UUID.randomUUID().toString()
Dmitry Burmistrov97beb9b2017-05-29 17:21:34 +0400413 writeFile file: queryFile,
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +0300414 text: """{
415 \"targetRepo\": \"${artifactoryProdRepo}\",
416 \"dockerRepository\": \"${dockerRepo}\",
417 \"tag\": \"${artifactTag}\",
418 \"targetTag\" : \"${targetTag}\",
419 \"copy\": \"${copy}\"
420 }""".stripIndent()
Dmitry Burmistrov97beb9b2017-05-29 17:21:34 +0400421 sh "cat ${queryFile}"
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +0300422 withCredentials([
423 [$class : 'UsernamePasswordMultiBinding',
424 credentialsId : 'artifactory',
425 passwordVariable: 'ARTIFACTORY_PASSWORD',
426 usernameVariable: 'ARTIFACTORY_LOGIN']
427 ]) {
Sergey Reshetnyakf0775fb2018-06-28 14:54:01 +0400428 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 +0300429 }
Dmitry Burmistrov97beb9b2017-05-29 17:21:34 +0400430 sh "rm -v ${queryFile}"
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +0300431}
Denis Egorenko60f47c12019-03-11 20:54:13 +0400432
433/**
434 * Save job artifacts to Artifactory server if available.
435 * Returns link to Artifactory repo, where saved job artifacts.
436 *
437 * @param config LinkedHashMap which contains next parameters:
438 * @param artifactory String, Artifactory server id
439 * @param artifactoryRepo String, repo to save job artifacts
440 * @param buildProps ArrayList, additional props for saved artifacts. Optional, default: []
441 * @param artifactory_not_found_fail Boolean, whether to fail if provided artifactory
442 * id is not found or just print warning message. Optional, default: false
443 */
444def uploadJobArtifactsToArtifactory(LinkedHashMap config) {
445 def common = new com.mirantis.mk.Common()
446 def artifactsDescription = ''
447 def artifactoryServer
Dmitry Tyzhnenko9ade0722020-03-31 13:17:54 +0300448
449 if (!config.containsKey('deleteArtifacts')) {
450 config.deleteArtifacts = true // default behavior before add the flag
451 }
452
Denis Egorenko60f47c12019-03-11 20:54:13 +0400453 try {
454 artifactoryServer = Artifactory.server(config.get('artifactory'))
455 } catch (Exception e) {
456 if (config.get('artifactory_not_found_fail', false)) {
457 throw e
458 } else {
459 common.warningMsg(e)
460 return "Artifactory server is not found. Can't save artifacts in Artifactory."
461 }
462 }
Dmitry Tyzhnenko812673a2020-03-26 21:59:14 +0200463 def artifactDir = config.get('artifactDir') ?: 'cur_build_artifacts'
Denis Egorenko60f47c12019-03-11 20:54:13 +0400464 def user = ''
465 wrap([$class: 'BuildUser']) {
466 user = env.BUILD_USER_ID
467 }
468 dir(artifactDir) {
469 try {
Denis Egorenko5fc40f82019-03-13 18:35:51 +0400470 unarchive(mapping: ['**/*' : '.'])
Denis Egorenko60f47c12019-03-11 20:54:13 +0400471 // Mandatory and additional properties
472 def properties = getBinaryBuildProperties(config.get('buildProps', []) << "buildUser=${user}")
Dmitry Tyzhnenko812673a2020-03-26 21:59:14 +0200473 def pattern = config.get('artifactPattern') ?: '*'
Denis Egorenko60f47c12019-03-11 20:54:13 +0400474
475 // Build Artifactory spec object
476 def uploadSpec = """{
477 "files":
478 [
479 {
Dmitry Tyzhnenko812673a2020-03-26 21:59:14 +0200480 "pattern": "${pattern}",
Denis Egorenko60f47c12019-03-11 20:54:13 +0400481 "target": "${config.get('artifactoryRepo')}/",
Denis Egorenko850f56a2019-03-13 20:44:43 +0400482 "flat": false,
Denis Egorenko60f47c12019-03-11 20:54:13 +0400483 "props": "${properties}"
484 }
485 ]
486 }"""
487
488 artifactoryServer.upload(uploadSpec, newBuildInfo())
489 def linkUrl = "${artifactoryServer.getUrl()}/artifactory/${config.get('artifactoryRepo')}"
490 artifactsDescription = "Job artifacts uploaded to Artifactory: <a href=\"${linkUrl}\">${linkUrl}</a>"
491 } catch (Exception e) {
492 if (e =~ /no artifacts/) {
493 artifactsDescription = 'Build has no artifacts saved.'
494 } else {
495 throw e
496 }
497 } finally {
Dmitry Tyzhnenko9ade0722020-03-31 13:17:54 +0300498 if (config.deleteArtifacts) {
499 deleteDir()
500 }
Denis Egorenko60f47c12019-03-11 20:54:13 +0400501 }
502 }
503 return artifactsDescription
504}
Dmitry Tyzhnenko39cf09c2020-05-05 20:08:52 +0300505
506/**
507 * Save custom artifacts to Artifactory server if available.
508 * Returns link to Artifactory repo, where saved artifacts.
509 *
510 * @param config LinkedHashMap which contains next parameters:
511 * @param artifactory String, Artifactory server id
512 * @param artifactoryRepo String, repo to save job artifacts
513 * @param buildProps ArrayList, additional props for saved artifacts. Optional, default: []
514 * @param artifactory_not_found_fail Boolean, whether to fail if provided artifactory
515 * id is not found or just print warning message. Optional, default: false
516 */
517def uploadArtifactsToArtifactory(LinkedHashMap config) {
518 def common = new com.mirantis.mk.Common()
519 def artifactsDescription = ''
520 def artifactoryServer
521
522 try {
523 artifactoryServer = Artifactory.server(config.get('artifactory'))
524 } catch (Exception e) {
525 if (config.get('artifactory_not_found_fail', false)) {
526 throw e
527 } else {
528 common.warningMsg(e)
529 return "Artifactory server is not found. Can't save artifacts in Artifactory."
530 }
531 }
532 def user = ''
533 wrap([$class: 'BuildUser']) {
534 user = env.BUILD_USER_ID
535 }
536 try {
537 // Mandatory and additional properties
538 def properties = getBinaryBuildProperties(config.get('buildProps', []) << "buildUser=${user}")
539 def pattern = config.get('artifactPattern') ?: '*'
540
541 // Build Artifactory spec object
542 def uploadSpec = """{
543 "files":
544 [
545 {
546 "pattern": "${pattern}",
547 "target": "${config.get('artifactoryRepo')}/",
548 "flat": false,
549 "props": "${properties}"
550 }
551 ]
552 }"""
553
554 artifactoryServer.upload(uploadSpec, newBuildInfo())
Alexandr Lovtsov9293d992021-01-19 19:55:41 +0300555 def linkUrl = "${artifactoryServer.getUrl()}/${config.get('artifactoryRepo')}"
Dmitry Tyzhnenko39cf09c2020-05-05 20:08:52 +0300556 artifactsDescription = "Job artifacts uploaded to Artifactory: <a href=\"${linkUrl}\">${linkUrl}</a>"
557 } catch (Exception e) {
558 if (e =~ /no artifacts/) {
559 artifactsDescription = 'Build has no artifacts saved.'
560 } else {
561 throw e
562 }
563 }
564 return artifactsDescription
565}