blob: 33d6620b7d487e01be5f42e2f60b221657c78c2a [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/**
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +0300132 * Get properties for specified artifact in Artifactory
133 * Returns LinkedHashMap of properties
134 *
135 * @param artifactUrl String, an URL to artifact in Artifactory repo
136 */
137def getPropertiesForArtifact(String artifactUrl) {
138 def url = "${artifactUrl}?properties"
139 def result
140 withCredentials([
141 [$class : 'UsernamePasswordMultiBinding',
142 credentialsId : 'artifactory',
143 passwordVariable: 'ARTIFACTORY_PASSWORD',
144 usernameVariable: 'ARTIFACTORY_LOGIN']
145 ]) {
146 result = sh(script: "bash -c \"curl -X GET -u ${ARTIFACTORY_LOGIN}:${ARTIFACTORY_PASSWORD} \'${url}\'\"",
147 returnStdout: true).trim()
148 }
149 def properties = new groovy.json.JsonSlurperClassic().parseText(result)
150 return properties.get("properties")
151}
152
153/**
Denis Egorenkoedd21dc2018-11-23 17:38:17 +0400154 * Check if image with tag exist by provided path
155 * Returns true or false
156 *
157 * @param artifactoryURL String, an URL to Artifactory
158 * @param imageRepo String, path to image to check, includes repo path and image name
159 * @param tag String, tag to check
160 * @param artifactoryCreds String, artifactory creds to use. Optional, default is 'artifactory'
161 */
162def imageExists(String artifactoryURL, String imageRepo, String tag, String artifactoryCreds = 'artifactory') {
163 def url = artifactoryURL + '/v2/' + imageRepo + '/manifest/' + tag
164 def result
165 withCredentials([
166 [$class : 'UsernamePasswordMultiBinding',
167 credentialsId : artifactoryCreds,
168 passwordVariable: 'ARTIFACTORY_PASSWORD',
169 usernameVariable: 'ARTIFACTORY_LOGIN']
170 ]) {
171 result = sh(script: "bash -c \"curl -X GET -u ${ARTIFACTORY_LOGIN}:${ARTIFACTORY_PASSWORD} \'${url}\'\"",
172 returnStdout: true).trim()
173 }
174 def properties = new groovy.json.JsonSlurperClassic().parseText(result)
175 return properties.get("errors") ? false : true
176}
177
178/**
Denis Egorenko7c0abfe2017-02-14 15:42:02 +0400179 * Find docker images by tag
180 * Returns Array of image' hashes with names as full path in @repo
181 *
182 * Example:
183 *
184 * [ {
185 * "path" : "mirantis/ccp/ci-cd/gerrit-manage/test"
186 * },
187 * {
188 * "path" : "mirantis/ccp/ci-cd/gerrit/test"
189 * }
190 * ]
191 *
192 * @param artifactoryURL String, an URL to Artifactory
193 * @param repo String, a name of repo where should be executed search
194 * @param tag String, tag of searched image
195 */
196def getImagesByTag(String artifactoryURL, String repo, String tag) {
197 def url = "${artifactoryURL}/api/search/aql"
198 def result
199 writeFile file: "query",
200 text: """\
201 items.find(
202 {
203 \"repo\": \"${repo}\",
204 \"@docker.manifest\": { \"\$match\" : \"${tag}*\" }
205 }
206 ).
207 include(\"path\")
208 """.stripIndent()
209 withCredentials([
210 [$class: 'UsernamePasswordMultiBinding',
211 credentialsId: 'artifactory',
212 passwordVariable: 'ARTIFACTORY_PASSWORD',
213 usernameVariable: 'ARTIFACTORY_LOGIN']
214 ]) {
215 result = sh(script: "bash -c \"curl -X POST -u ${ARTIFACTORY_LOGIN}:${ARTIFACTORY_PASSWORD} -d @query \'${url}\'\"",
216 returnStdout: true).trim()
217 }
218 def images = new groovy.json.JsonSlurperClassic().parseText(result)
219 return images.get("results")
220}
221
222/**
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +0300223 * Upload docker image to Artifactory
224 *
Sergey Kulanov8cd6d222016-11-17 13:42:47 +0200225 * @param server ArtifactoryServer, the instance of Artifactory server
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +0300226 * @param registry String, the name of Docker registry
227 * @param image String, Docker image name
228 * @param version String, Docker image version
229 * @param repository String, The name of Artifactory Docker repository
Sergey Kulanov8cd6d222016-11-17 13:42:47 +0200230 * @param buildInfo BuildInfo, the instance of a build-info object which can be published,
231 * if defined, then we publish BuildInfo
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +0300232 */
Sergey Kulanov8cd6d222016-11-17 13:42:47 +0200233def uploadImageToArtifactory (ArtifactoryServer server, String registry, String image,
234 String version, String repository,
Dmitry Burmistrov6ee39522017-05-22 12:46:25 +0400235 BuildInfo buildInfo = null,
236 LinkedHashMap properties = null) {
Denis Egorenkoedba5a52016-11-15 19:55:56 +0300237 // TODO Switch to Artifactoy image' pushing mechanism once we will
238 // prepare automatical way for enabling artifactory build-proxy
239 //def artDocker
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +0300240 withCredentials([
241 [$class: 'UsernamePasswordMultiBinding',
242 credentialsId: 'artifactory',
243 passwordVariable: 'ARTIFACTORY_PASSWORD',
244 usernameVariable: 'ARTIFACTORY_LOGIN']
245 ]) {
246 sh ("docker login -u ${ARTIFACTORY_LOGIN} -p ${ARTIFACTORY_PASSWORD} ${registry}")
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +0300247 //artDocker = Artifactory.docker("${env.ARTIFACTORY_LOGIN}", "${env.ARTIFACTORY_PASSWORD}")
248 }
249
Denis Egorenkoedba5a52016-11-15 19:55:56 +0300250 sh ("docker push ${registry}/${image}:${version}")
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +0300251 //artDocker.push("${registry}/${image}:${version}", "${repository}")
Sergey Kulanov8cd6d222016-11-17 13:42:47 +0200252 def image_url = server.getUrl() + "/api/storage/${repository}/${image}/${version}"
Dmitry Burmistrov6ee39522017-05-22 12:46:25 +0400253 if ( ! properties ) {
254 properties = [
Sergey Kulanovc70f1c22016-11-16 13:05:20 +0200255 'com.mirantis.buildName':"${env.JOB_NAME}",
256 'com.mirantis.buildNumber': "${env.BUILD_NUMBER}",
257 'com.mirantis.gerritProject': "${env.GERRIT_PROJECT}",
258 'com.mirantis.gerritChangeNumber': "${env.GERRIT_CHANGE_NUMBER}",
259 'com.mirantis.gerritPatchsetNumber': "${env.GERRIT_PATCHSET_NUMBER}",
260 'com.mirantis.gerritChangeId': "${env.GERRIT_CHANGE_ID}",
261 'com.mirantis.gerritPatchsetRevision': "${env.GERRIT_PATCHSET_REVISION}",
Sergey Kulanov4d3951c2016-11-24 13:58:15 +0200262 'com.mirantis.targetImg': "${image}",
Sergey Kulanovc70f1c22016-11-16 13:05:20 +0200263 'com.mirantis.targetTag': "${version}"
Dmitry Burmistrov6ee39522017-05-22 12:46:25 +0400264 ]
265 }
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +0300266
267 setProperties(image_url, properties)
Sergey Kulanov8cd6d222016-11-17 13:42:47 +0200268
269 if ( buildInfo != null ) {
270 buildInfo.env.capture = true
271 buildInfo.env.filter.addInclude("*")
272 buildInfo.env.filter.addExclude("*PASSWORD*")
273 buildInfo.env.filter.addExclude("*password*")
274 buildInfo.env.collect()
275 server.publishBuildInfo(buildInfo)
276 }
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +0300277}
278
279/**
280 * Upload binaries to Artifactory
281 *
282 * @param server ArtifactoryServer, the instance of Artifactory server
283 * @param buildInfo BuildInfo, the instance of a build-info object which can be published
284 * @param uploadSpec String, a spec which is a JSON file that specifies which files should be
285 * uploaded or downloaded and the target path
286 * @param publishInfo Boolean, whether publish a build-info object to Artifactory
287 */
Sergey Kulanov91d8def2016-11-15 13:53:17 +0200288def uploadBinariesToArtifactory (ArtifactoryServer server, BuildInfo buildInfo, String uploadSpec,
289 Boolean publishInfo = false) {
Jakub Josefbefcf6c2017-11-14 18:03:10 +0100290 server.upload(uploadSpec, buildInfo)
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +0300291
292 if ( publishInfo ) {
293 buildInfo.env.capture = true
294 buildInfo.env.filter.addInclude("*")
295 buildInfo.env.filter.addExclude("*PASSWORD*")
296 buildInfo.env.filter.addExclude("*password*")
297 buildInfo.env.collect()
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +0300298 server.publishBuildInfo(buildInfo)
299 }
300}
301
302/**
303 * Promote Docker image artifact to release repo
304 *
305 * @param artifactoryURL String, an URL to Artifactory
306 * @param artifactoryDevRepo String, the source dev repository name
307 * @param artifactoryProdRepo String, the target repository for the move or copy
308 * @param dockerRepo String, the docker repository name to promote
309 * @param artifactTag String, an image tag name to promote
310 * @param targetTag String, target tag to assign the image after promotion
311 * @param copy Boolean, an optional value to set whether to copy instead of move
312 * Default: false
313 */
314def promoteDockerArtifact(String artifactoryURL, String artifactoryDevRepo,
315 String artifactoryProdRepo, String dockerRepo,
316 String artifactTag, String targetTag, Boolean copy = false) {
317 def url = "${artifactoryURL}/api/docker/${artifactoryDevRepo}/v2/promote"
Dmitry Burmistrov5deaa7d2017-05-30 17:12:54 +0400318 String queryFile = UUID.randomUUID().toString()
Dmitry Burmistrov97beb9b2017-05-29 17:21:34 +0400319 writeFile file: queryFile,
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +0300320 text: """{
321 \"targetRepo\": \"${artifactoryProdRepo}\",
322 \"dockerRepository\": \"${dockerRepo}\",
323 \"tag\": \"${artifactTag}\",
324 \"targetTag\" : \"${targetTag}\",
325 \"copy\": \"${copy}\"
326 }""".stripIndent()
Dmitry Burmistrov97beb9b2017-05-29 17:21:34 +0400327 sh "cat ${queryFile}"
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +0300328 withCredentials([
329 [$class : 'UsernamePasswordMultiBinding',
330 credentialsId : 'artifactory',
331 passwordVariable: 'ARTIFACTORY_PASSWORD',
332 usernameVariable: 'ARTIFACTORY_LOGIN']
333 ]) {
Sergey Reshetnyakf0775fb2018-06-28 14:54:01 +0400334 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 +0300335 }
Dmitry Burmistrov97beb9b2017-05-29 17:21:34 +0400336 sh "rm -v ${queryFile}"
Ruslan Kamaldinov90d4e672016-11-11 18:31:00 +0300337}
Denis Egorenko60f47c12019-03-11 20:54:13 +0400338
339/**
340 * Save job artifacts to Artifactory server if available.
341 * Returns link to Artifactory repo, where saved job artifacts.
342 *
343 * @param config LinkedHashMap which contains next parameters:
344 * @param artifactory String, Artifactory server id
345 * @param artifactoryRepo String, repo to save job artifacts
346 * @param buildProps ArrayList, additional props for saved artifacts. Optional, default: []
347 * @param artifactory_not_found_fail Boolean, whether to fail if provided artifactory
348 * id is not found or just print warning message. Optional, default: false
349 */
350def uploadJobArtifactsToArtifactory(LinkedHashMap config) {
351 def common = new com.mirantis.mk.Common()
352 def artifactsDescription = ''
353 def artifactoryServer
354 try {
355 artifactoryServer = Artifactory.server(config.get('artifactory'))
356 } catch (Exception e) {
357 if (config.get('artifactory_not_found_fail', false)) {
358 throw e
359 } else {
360 common.warningMsg(e)
361 return "Artifactory server is not found. Can't save artifacts in Artifactory."
362 }
363 }
364 def artifactDir = 'cur_build_artifacts'
365 def user = ''
366 wrap([$class: 'BuildUser']) {
367 user = env.BUILD_USER_ID
368 }
369 dir(artifactDir) {
370 try {
Denis Egorenko5fc40f82019-03-13 18:35:51 +0400371 unarchive(mapping: ['**/*' : '.'])
Denis Egorenko60f47c12019-03-11 20:54:13 +0400372 // Mandatory and additional properties
373 def properties = getBinaryBuildProperties(config.get('buildProps', []) << "buildUser=${user}")
374
375 // Build Artifactory spec object
376 def uploadSpec = """{
377 "files":
378 [
379 {
380 "pattern": "*",
381 "target": "${config.get('artifactoryRepo')}/",
Denis Egorenko850f56a2019-03-13 20:44:43 +0400382 "flat": false,
Denis Egorenko60f47c12019-03-11 20:54:13 +0400383 "props": "${properties}"
384 }
385 ]
386 }"""
387
388 artifactoryServer.upload(uploadSpec, newBuildInfo())
389 def linkUrl = "${artifactoryServer.getUrl()}/artifactory/${config.get('artifactoryRepo')}"
390 artifactsDescription = "Job artifacts uploaded to Artifactory: <a href=\"${linkUrl}\">${linkUrl}</a>"
391 } catch (Exception e) {
392 if (e =~ /no artifacts/) {
393 artifactsDescription = 'Build has no artifacts saved.'
394 } else {
395 throw e
396 }
397 } finally {
398 deleteDir()
399 }
400 }
401 return artifactsDescription
402}