blob: 19941b4e22d3060eda2cfb12ea09486bde8fb45f [file] [log] [blame]
Sergey Kulanov1bbd3612016-09-30 11:40:11 +03001package ci.mcp
2
3/**
4 * https://issues.jenkins-ci.org/browse/JENKINS-26481
5 * fix groovy List.collect()
Sergey Kulanov56d0d052016-10-13 15:48:56 +03006**/
7@NonCPS
8def constructString(ArrayList options, String keyOption, String separator = " ") {
9 return options.collect{ keyOption + it }.join(separator).replaceAll("\n", "")
10}
11
12/**
Sergey Kulanov1bbd3612016-09-30 11:40:11 +030013 * Build command line options, e.g:
14 * cmd_opts=["a=b", "c=d", "e=f"]
15 * key = "--build-arg "
16 * separator = " "
17 * def options = getCommandBuilder(cmd_opts, key, separator)
18 * println options
19 * > --build-arg a=b --build-arg c=d --build-arg e=f
20 *
21 * @param options List of Strings (options that should be populated)
22 * @param keyOption key that should be added before each option
23 * @param separator Separator between key+Option pairs
24 */
Sergey Kulanov1bbd3612016-09-30 11:40:11 +030025def getCommandBuilder(ArrayList options, String keyOption, String separator = " ") {
Sergey Kulanov56d0d052016-10-13 15:48:56 +030026 return constructString(options, keyOption)
27}
28
29/**
30* Return string of mandatory build properties for binaries
31* User can also add some custom properties
32*
33* @param customProperties a Array of Strings that should be added to mandatory props
34* in format ["prop1=value1", "prop2=value2"]
35**/
36def getBinaryBuildProperties(ArrayList customProperties) {
37
38 def namespace = "com.mirantis."
39 def properties = [
40 "gerritProject=${env.GERRIT_PROJECT}",
41 "gerritChangeNumber=${env.GERRIT_CHANGE_NUMBER}",
42 "gerritPatchsetNumber=${env.GERRIT_PATCHSET_NUMBER}",
43 "gerritChangeId=${env.GERRIT_CHANGE_ID}",
Sergey Kulanov64bc88a2016-10-18 16:26:34 +030044 "gerritPatchsetRevision=${env.GERRIT_PATCHSET_REVISION}"
Sergey Kulanov56d0d052016-10-13 15:48:56 +030045 ]
46
47 if (customProperties){
48 properties.addAll(customProperties)
49 }
50
51 return constructString(properties, namespace, ";")
Sergey Kulanov1bbd3612016-09-30 11:40:11 +030052}
Sergey Kulanov1835afe2016-10-19 16:53:14 +030053
54/**
55 * Parse HEAD of current directory and return commit hash
56 */
57def getGitCommit() {
58 git_commit = sh (
59 script: 'git rev-parse HEAD',
60 returnStdout: true
61 ).trim()
62 return git_commit
63}
Denis Egorenkoe3552682016-10-18 13:29:29 +030064
65/**
66* Get URL to artifact by properties
67* Returns String with URL to found artifact or null if nothing
68*
69* @param artifactoryURL String, an URL to Artifactory
70* @param properties LinkedHashMap, a Hash of properties (key-value) which
71* which should determine artifact in Artifactory
72*/
73def uriByProperties(String artifactoryURL, LinkedHashMap properties) {
74 def key, value
75 def properties_str = ''
76 for ( int i = 0; i < properties.size(); i++ ) {
77 // avoid serialization errors
78 key = properties.entrySet().toArray()[i].key
79 value = properties.entrySet().toArray()[i].value
80 properties_str += "${key}=${value}&"
81 }
82 def search_url = "${artifactoryURL}/api/search/prop?${properties_str}"
83
84 def result = sh(script: "bash -c \"curl -X GET \'${search_url}\'\"",
85 returnStdout: true).trim()
86 def content = new groovy.json.JsonSlurperClassic().parseText(result)
87 def uri = content.get("results")
88 if ( uri ) {
89 return uri.last().get("uri")
90 } else {
91 return null
92 }
93}
94
95/**
96* Set properties for artifact in Artifactory repo
97*
98* @param artifactUrl String, an URL to artifact in Artifactory repo
99* @param properties LinkedHashMap, a Hash of properties (key-value) which
100* should be assigned for choosen artifact
101* @param recursive Boolean, if artifact_url is a directory, whether to set
102* properties recursively or not
103*/
104def setProperties (String artifactUrl, LinkedHashMap properties, Boolean recursive=false) {
105 def properties_str = 'properties='
106 def key,value
107 if (recursive) {
108 recursive = 'recursive=1'
109 } else {
110 recursive = 'recursive=0'
111 }
112 for ( int i = 0; i < properties.size(); i++ ) {
113 // avoid serialization errors
114 key = properties.entrySet().toArray()[i].key
115 value = properties.entrySet().toArray()[i].value
116 properties_str += "${key}=${value}|"
117 }
118 def url = "${artifactUrl}?${properties_str}&${recursive}"
119 withCredentials([
120 [$class: 'UsernamePasswordMultiBinding',
121 credentialsId: 'artifactory',
122 passwordVariable: 'ARTIFACTORY_PASSWORD',
123 usernameVariable: 'ARTIFACTORY_LOGIN']
124 ]) {
125 sh "bash -c \"curl -X PUT -u ${ARTIFACTORY_LOGIN}:${ARTIFACTORY_PASSWORD} \'${url}\'\""
126 }
127}
128
129/**
130* Get properties for specified artifact in Artifactory
131* Returns LinkedHashMap of properties
132*
133* @param artifactUrl String, an URL to artifact in Artifactory repo
134*/
135def getPropertiesForArtifact(String artifactUrl) {
136 def url = "${artifactUrl}?properties"
137 def result
138 withCredentials([
139 [$class: 'UsernamePasswordMultiBinding',
140 credentialsId: 'artifactory',
141 passwordVariable: 'ARTIFACTORY_PASSWORD',
142 usernameVariable: 'ARTIFACTORY_LOGIN']
143 ]) {
144 result = sh(script: "bash -c \"curl -X GET -u ${ARTIFACTORY_LOGIN}:${ARTIFACTORY_PASSWORD} \'${url}\'\"",
145 returnStdout: true).trim()
146 }
147 def properties = new groovy.json.JsonSlurperClassic().parseText(result)
148 return properties.get("properties")
149}
150
151/**
152* Upload docker image to Artifactory
153*
154* @param artifactoryURL String, an URL to Artifactory
155* @param registry String, the name of Docker registry
156* @param image String, Docker image name
157* @param version String, Docker image version
158* @param repository String, The name of Artifactory Docker repository
159*/
160def uploadImageToArtifactory (String artifactoryURL, String registry, String image,
161 String version, String repository) {
162 // TODO Switch to Artifactoy image' pushing mechanism once we will
163 // prepare automatical way for enabling artifactory build-proxy
164 //def artDocker
165 withCredentials([
166 [$class: 'UsernamePasswordMultiBinding',
167 credentialsId: 'artifactory',
168 passwordVariable: 'ARTIFACTORY_PASSWORD',
169 usernameVariable: 'ARTIFACTORY_LOGIN']
170 ]) {
171 sh ("docker login -u ${ARTIFACTORY_LOGIN} -p ${ARTIFACTORY_PASSWORD} ${registry}")
172 //artDocker = Artifactory.docker("${env.ARTIFACTORY_LOGIN}", "${env.ARTIFACTORY_PASSWORD}")
173 }
174
175 sh ("docker push ${registry}/${image}:${version}")
176 //artDocker.push("${registry}/${image}:${version}", "${repository}")
177 def image_url = "${artifactoryURL}/api/storage/${repository}/${image}/${version}"
178
179 def properties = ['com.mirantis.build_name':"${env.JOB_NAME}",
180 'com.mirantis.build_id': "${env.BUILD_NUMBER}",
181 'com.mirantis.changeid': "${env.GERRIT_CHANGE_ID}",
182 'com.mirantis.patchset_number': "${env.GERRIT_PATCHSET_NUMBER}",
183 'com.mirantis.target_tag': "${version}"]
184 setProperties(image_url, properties)
185}
186
187/**
188* Upload binaries to Artifactory
189*
190* @param server ArtifactoryServer, the instance of Artifactory server
191* @param buildInfo BuildInfo, the instance of a build-info object which can be published
192* @param uploadSpec String, a spec which is a JSON file that specifies which files should be
193* uploaded or downloaded and the target path
194* @param publishInfo Boolean, whether publish a build-info object to Artifactory
195*/
196def uploadBinariesToArtifactory (server, buildInfo, String uploadSpec,
197 Boolean publishInfo=false) {
198 buildInfo.append(server.upload(uploadSpec))
199
200 if ( publishInfo ) {
201 buildInfo.env.capture = true
202 buildInfo.env.filter.addInclude("*")
203 buildInfo.env.filter.addExclude("*PASSWORD*")
204 buildInfo.env.filter.addExclude("*password*")
205 buildInfo.env.collect()
206 server.publishBuildInfo(buildInfo)
207 }
208}
209
210/**
211* Promote Docker image artifact to release repo
212*
213* @param artifactoryURL String, an URL to Artifactory
214* @param artifactoryDevRepo String, the source dev repository name
215* @param artifactoryProdRepo String, the target repository for the move or copy
216* @param dockerRepo String, the docker repository name to promote
217* @param artifactTag String, an image tag name to promote
218* @param targetTag String, target tag to assign the image after promotion
219* @param copy Boolean, an optional value to set whether to copy instead of move
220* Default: false
221*/
222def promoteDockerArtifact(String artifactoryURL, String artifactoryDevRepo,
223 String artifactoryProdRepo, String dockerRepo,
224 String artifactTag, String targetTag, Boolean copy=false) {
225 def url = "${artifactoryURL}/api/docker/${artifactoryDevRepo}/v2/promote"
226 writeFile file: "query.json",
227 text: """{
228 \"targetRepo\": \"${artifactoryProdRepo}\",
229 \"dockerRepository\": \"${dockerRepo}\",
230 \"tag\": \"${artifactTag}\",
231 \"targetTag\" : \"${targetTag}\",
232 \"copy\": \"${copy}\"
233 }""".stripIndent()
234 sh "cat query.json"
235 withCredentials([
236 [$class: 'UsernamePasswordMultiBinding',
237 credentialsId: 'artifactory',
238 passwordVariable: 'ARTIFACTORY_PASSWORD',
239 usernameVariable: 'ARTIFACTORY_LOGIN']
240 ]) {
241 sh "bash -c \"curl -u ${ARTIFACTORY_LOGIN}:${ARTIFACTORY_PASSWORD} -H \"Content-Type:application/json\" -X POST -d @query.json ${url}\""
242 }
243}