blob: fcf1dec74f89397c81e7a4918265095a4c3e3705 [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/**
Sergey Kulanov4f2fbcb2016-10-28 14:25:20 +030066 * Generate current timestamp
67 *
68 * @param format Defaults to yyyyMMddHHmmss
69 */
70def getDatetime(format="yyyyMMddHHmmss") {
71 def now = new Date();
72 return now.format(format, TimeZone.getTimeZone('UTC'));
73}
74
75/**
Denis Egorenkoe3552682016-10-18 13:29:29 +030076* Get URL to artifact by properties
77* Returns String with URL to found artifact or null if nothing
78*
79* @param artifactoryURL String, an URL to Artifactory
80* @param properties LinkedHashMap, a Hash of properties (key-value) which
81* which should determine artifact in Artifactory
82*/
83def uriByProperties(String artifactoryURL, LinkedHashMap properties) {
84 def key, value
85 def properties_str = ''
86 for ( int i = 0; i < properties.size(); i++ ) {
87 // avoid serialization errors
88 key = properties.entrySet().toArray()[i].key
89 value = properties.entrySet().toArray()[i].value
90 properties_str += "${key}=${value}&"
91 }
92 def search_url = "${artifactoryURL}/api/search/prop?${properties_str}"
93
94 def result = sh(script: "bash -c \"curl -X GET \'${search_url}\'\"",
95 returnStdout: true).trim()
96 def content = new groovy.json.JsonSlurperClassic().parseText(result)
97 def uri = content.get("results")
98 if ( uri ) {
99 return uri.last().get("uri")
100 } else {
101 return null
102 }
103}
104
105/**
106* Set properties for artifact in Artifactory repo
107*
108* @param artifactUrl String, an URL to artifact in Artifactory repo
109* @param properties LinkedHashMap, a Hash of properties (key-value) which
110* should be assigned for choosen artifact
111* @param recursive Boolean, if artifact_url is a directory, whether to set
112* properties recursively or not
113*/
114def setProperties (String artifactUrl, LinkedHashMap properties, Boolean recursive=false) {
115 def properties_str = 'properties='
116 def key,value
117 if (recursive) {
118 recursive = 'recursive=1'
119 } else {
120 recursive = 'recursive=0'
121 }
122 for ( int i = 0; i < properties.size(); i++ ) {
123 // avoid serialization errors
124 key = properties.entrySet().toArray()[i].key
125 value = properties.entrySet().toArray()[i].value
126 properties_str += "${key}=${value}|"
127 }
128 def url = "${artifactUrl}?${properties_str}&${recursive}"
129 withCredentials([
130 [$class: 'UsernamePasswordMultiBinding',
131 credentialsId: 'artifactory',
132 passwordVariable: 'ARTIFACTORY_PASSWORD',
133 usernameVariable: 'ARTIFACTORY_LOGIN']
134 ]) {
135 sh "bash -c \"curl -X PUT -u ${ARTIFACTORY_LOGIN}:${ARTIFACTORY_PASSWORD} \'${url}\'\""
136 }
137}
138
139/**
140* Get properties for specified artifact in Artifactory
141* Returns LinkedHashMap of properties
142*
143* @param artifactUrl String, an URL to artifact in Artifactory repo
144*/
145def getPropertiesForArtifact(String artifactUrl) {
146 def url = "${artifactUrl}?properties"
147 def result
148 withCredentials([
149 [$class: 'UsernamePasswordMultiBinding',
150 credentialsId: 'artifactory',
151 passwordVariable: 'ARTIFACTORY_PASSWORD',
152 usernameVariable: 'ARTIFACTORY_LOGIN']
153 ]) {
154 result = sh(script: "bash -c \"curl -X GET -u ${ARTIFACTORY_LOGIN}:${ARTIFACTORY_PASSWORD} \'${url}\'\"",
155 returnStdout: true).trim()
156 }
157 def properties = new groovy.json.JsonSlurperClassic().parseText(result)
158 return properties.get("properties")
159}
160
161/**
162* Upload docker image to Artifactory
163*
164* @param artifactoryURL String, an URL to Artifactory
165* @param registry String, the name of Docker registry
166* @param image String, Docker image name
167* @param version String, Docker image version
168* @param repository String, The name of Artifactory Docker repository
169*/
170def uploadImageToArtifactory (String artifactoryURL, String registry, String image,
171 String version, String repository) {
172 // TODO Switch to Artifactoy image' pushing mechanism once we will
173 // prepare automatical way for enabling artifactory build-proxy
174 //def artDocker
175 withCredentials([
176 [$class: 'UsernamePasswordMultiBinding',
177 credentialsId: 'artifactory',
178 passwordVariable: 'ARTIFACTORY_PASSWORD',
179 usernameVariable: 'ARTIFACTORY_LOGIN']
180 ]) {
181 sh ("docker login -u ${ARTIFACTORY_LOGIN} -p ${ARTIFACTORY_PASSWORD} ${registry}")
182 //artDocker = Artifactory.docker("${env.ARTIFACTORY_LOGIN}", "${env.ARTIFACTORY_PASSWORD}")
183 }
184
185 sh ("docker push ${registry}/${image}:${version}")
186 //artDocker.push("${registry}/${image}:${version}", "${repository}")
187 def image_url = "${artifactoryURL}/api/storage/${repository}/${image}/${version}"
188
189 def properties = ['com.mirantis.build_name':"${env.JOB_NAME}",
190 'com.mirantis.build_id': "${env.BUILD_NUMBER}",
191 'com.mirantis.changeid': "${env.GERRIT_CHANGE_ID}",
192 'com.mirantis.patchset_number': "${env.GERRIT_PATCHSET_NUMBER}",
193 'com.mirantis.target_tag': "${version}"]
194 setProperties(image_url, properties)
195}
196
197/**
198* Upload binaries to Artifactory
199*
200* @param server ArtifactoryServer, the instance of Artifactory server
201* @param buildInfo BuildInfo, the instance of a build-info object which can be published
202* @param uploadSpec String, a spec which is a JSON file that specifies which files should be
203* uploaded or downloaded and the target path
204* @param publishInfo Boolean, whether publish a build-info object to Artifactory
205*/
206def uploadBinariesToArtifactory (server, buildInfo, String uploadSpec,
207 Boolean publishInfo=false) {
208 buildInfo.append(server.upload(uploadSpec))
209
210 if ( publishInfo ) {
211 buildInfo.env.capture = true
212 buildInfo.env.filter.addInclude("*")
213 buildInfo.env.filter.addExclude("*PASSWORD*")
214 buildInfo.env.filter.addExclude("*password*")
215 buildInfo.env.collect()
216 server.publishBuildInfo(buildInfo)
217 }
218}
219
220/**
221* Promote Docker image artifact to release repo
222*
223* @param artifactoryURL String, an URL to Artifactory
224* @param artifactoryDevRepo String, the source dev repository name
225* @param artifactoryProdRepo String, the target repository for the move or copy
226* @param dockerRepo String, the docker repository name to promote
227* @param artifactTag String, an image tag name to promote
228* @param targetTag String, target tag to assign the image after promotion
229* @param copy Boolean, an optional value to set whether to copy instead of move
230* Default: false
231*/
232def promoteDockerArtifact(String artifactoryURL, String artifactoryDevRepo,
233 String artifactoryProdRepo, String dockerRepo,
234 String artifactTag, String targetTag, Boolean copy=false) {
235 def url = "${artifactoryURL}/api/docker/${artifactoryDevRepo}/v2/promote"
236 writeFile file: "query.json",
237 text: """{
238 \"targetRepo\": \"${artifactoryProdRepo}\",
239 \"dockerRepository\": \"${dockerRepo}\",
240 \"tag\": \"${artifactTag}\",
241 \"targetTag\" : \"${targetTag}\",
242 \"copy\": \"${copy}\"
243 }""".stripIndent()
244 sh "cat query.json"
245 withCredentials([
246 [$class: 'UsernamePasswordMultiBinding',
247 credentialsId: 'artifactory',
248 passwordVariable: 'ARTIFACTORY_PASSWORD',
249 usernameVariable: 'ARTIFACTORY_LOGIN']
250 ]) {
251 sh "bash -c \"curl -u ${ARTIFACTORY_LOGIN}:${ARTIFACTORY_PASSWORD} -H \"Content-Type:application/json\" -X POST -d @query.json ${url}\""
252 }
253}