blob: 0de5590bd07e509a299398e45c658fa30867abd3 [file] [log] [blame]
Richard Felkle90ef1c2017-12-08 00:13:56 +01001/**
2 *
3 * Mirror Docker images
4 *
5 * Expected parameters:
6 * TARGET_REGISTRY_CREDENTIALS_ID Credentials for target Docker Registry
7 * TARGET_REGISTRY Target Docker Registry name
8 * REGISTRY_URL Target Docker Registry URL
9 * IMAGE_TAG Tag to use when pushing images
azvyagintsevd162b912018-07-26 10:52:14 +020010 * SOURCE_IMAGE_TAG Tag to use when pulling images(optional,if SOURCE_IMAGE_TAG has been found)
azvyagintsev388a1bd2018-09-06 12:39:49 +030011 * SET_DEFAULT_ARTIFACTORY_PROPERTIES Add extra props. directly to artifactory,
Richard Felkle90ef1c2017-12-08 00:13:56 +010012 * IMAGE_LIST List of images to mirror
azvyagintsev388a1bd2018-09-06 12:39:49 +030013 * Example: docker.elastic.co/elasticsearch/elasticsearch:5.4.1 docker-prod-local.docker.mirantis.net/mirantis/external/docker.elastic.co/elasticsearch
14 * docker.elastic.co/elasticsearch/elasticsearch:SUBS_SOURCE_IMAGE_TAG docker-prod-local.docker.mirantis.net/mirantis/external/elasticsearch:${IMAGE_TAG}* Will be proceed like:
15 * docker tag docker.elastic.co/elasticsearch/elasticsearch:5.4.1 docker-prod-local.docker.mirantis.net/mirantis/external/docker.elastic.co/elasticsearch/elasticsearch:5.4.1
16 *
Richard Felkle90ef1c2017-12-08 00:13:56 +010017 *
18 */
azvyagintsev388a1bd2018-09-06 12:39:49 +030019import java.util.regex.Pattern
Alexander Evseev89b0da42018-12-10 13:14:04 +000020import groovy.json.JsonSlurper
Richard Felkle90ef1c2017-12-08 00:13:56 +010021
azvyagintsev388a1bd2018-09-06 12:39:49 +030022common = new com.mirantis.mk.Common()
23external = false
24externalMarker = '/mirantis/external/'
Richard Felkle90ef1c2017-12-08 00:13:56 +010025
azvyagintsev388a1bd2018-09-06 12:39:49 +030026slaveNode = env.SLAVE_NODE ?: 'docker'
27setDefaultArtifactoryProperties = env.SET_DEFAULT_ARTIFACTORY_PROPERTIES ?: true
28
Richard Felkle90ef1c2017-12-08 00:13:56 +010029def getImageName(String image) {
30 def regex = Pattern.compile('(?:.+/)?([^:]+)(?::.+)?')
31 def matcher = regex.matcher(image)
azvyagintsev388a1bd2018-09-06 12:39:49 +030032 if (matcher.find()) {
Richard Felkle90ef1c2017-12-08 00:13:56 +010033 def imageName = matcher.group(1)
34 return imageName
azvyagintsev388a1bd2018-09-06 12:39:49 +030035 } else {
36 error("Wrong format of image name.")
Richard Felkle90ef1c2017-12-08 00:13:56 +010037 }
38}
azvyagintsev388a1bd2018-09-06 12:39:49 +030039
Denis Egorenko343a5712018-12-10 19:08:45 +040040def getImageInfo(String imageName) {
41 String unique_image_id = sh(
Kyrylo Mashchenkoa86912d2018-12-21 08:31:47 +000042 script: "docker inspect --format='{{index .RepoDigests 0}}' '${imageName}'",
43 returnStdout: true,
Denis Egorenko343a5712018-12-10 19:08:45 +040044 ).trim()
45 String imageSha256 = unique_image_id.tokenize(':')[1]
46 common.infoMsg("Docker ${imageName} image sha256 is ${imageSha256}")
Kyrylo Mashchenkoa86912d2018-12-21 08:31:47 +000047 return [ 'id': unique_image_id, 'sha256': imageSha256 ]
Denis Egorenko343a5712018-12-10 19:08:45 +040048}
49
50def imageURL(String registry, String imageName, String sha256) {
51 def ret = new URL("https://${registry}/artifactory/api/search/checksum?sha256=${sha256}").getText()
52 // Most probably, we would get many images, especially for external images. We need to guess
53 // exactly one, which we pushing now
54 def tgtGuessImage = imageName.replace(':', '/').replace(registry, '')
55 ArrayList img_data = new JsonSlurper().parseText(ret)['results']
56 def tgtImgUrl = img_data*.uri.find { it.contains(tgtGuessImage) }
57 if (tgtImgUrl) {
58 return tgtImgUrl
59 } else {
60 error("Can't find image ${imageName} in registry ${registry} with sha256: ${sha256}!")
61 }
62}
63
azvyagintsev388a1bd2018-09-06 12:39:49 +030064timeout(time: 4, unit: 'HOURS') {
65 node(slaveNode) {
Denis Egorenko899ee322018-11-19 17:35:50 +040066 def user = ''
67 wrap([$class: 'BuildUser']) {
68 user = env.BUILD_USER_ID
69 }
70 currentBuild.description = "${user}: [${env.SOURCE_IMAGE_TAG} => ${env.IMAGE_TAG}]\n${env.IMAGE_LIST}"
Jakub Josefa63f9862018-01-11 17:58:38 +010071 try {
azvyagintsev388a1bd2018-09-06 12:39:49 +030072 stage("Mirror Docker Images") {
73
Jakub Josefa63f9862018-01-11 17:58:38 +010074 def images = IMAGE_LIST.tokenize('\n')
azvyagintsev388a1bd2018-09-06 12:39:49 +030075 def imageName, sourceImage, targetRegistryPath, imageArray
76 for (image in images) {
77 if (image.trim().indexOf(' ') == -1) {
78 error("Wrong format of image and target repository input")
Jakub Josefa63f9862018-01-11 17:58:38 +010079 }
80 imageArray = image.trim().tokenize(' ')
azvyagintsev388a1bd2018-09-06 12:39:49 +030081 sourceImage = imageArray[0]
82 if (sourceImage.contains('SUBS_SOURCE_IMAGE_TAG')) {
83 common.warningMsg("Replacing SUBS_SOURCE_IMAGE_TAG => ${env.SOURCE_IMAGE_TAG}")
84 sourceImage = sourceImage.replace('SUBS_SOURCE_IMAGE_TAG', env.SOURCE_IMAGE_TAG)
azvyagintsevd162b912018-07-26 10:52:14 +020085 }
azvyagintsev388a1bd2018-09-06 12:39:49 +030086 targetRegistryPath = imageArray[1]
87 targetRegistry = imageArray[1].split('/')[0]
88 imageName = getImageName(sourceImage)
89 targetImageFull = "${targetRegistryPath}/${imageName}:${env.IMAGE_TAG}"
Denis Egorenko2ee651c2018-11-23 17:41:38 +040090
91 def mcp_artifactory = new com.mirantis.mcp.MCPArtifactory()
92 if (targetImageFull.contains(externalMarker)) {
93 external = true
94 // check if images exists - raise error, as we don't want to rewrite existing one
95 def imageRepo = targetRegistryPath - targetRegistry
Denis Egorenko1b207d12018-11-26 15:35:21 +040096 if (mcp_artifactory.imageExists(env.REGISTRY_URL, "${imageRepo}/${imageName}", env.IMAGE_TAG)) {
Denis Egorenko2ee651c2018-11-23 17:41:38 +040097 error("Image ${targetImageFull} already exists!")
98 }
99 }
100
azvyagintsev388a1bd2018-09-06 12:39:49 +0300101 srcImage = docker.image(sourceImage)
azvyagintsev86ba4a02018-10-03 19:21:28 +0300102 common.retry(3, 5) {
103 srcImage.pull()
104 }
Denis Egorenko343a5712018-12-10 19:08:45 +0400105 source_image_sha256 = getImageInfo(sourceImage)['sha256']
azvyagintsev388a1bd2018-09-06 12:39:49 +0300106 // Use sh-docker call for tag, due magic code in plugin:
107 // https://github.com/jenkinsci/docker-workflow-plugin/blob/docker-workflow-1.17/src/main/resources/org/jenkinsci/plugins/docker/workflow/Docker.groovy#L168-L170
108 sh("docker tag ${srcImage.id} ${targetImageFull}")
109 common.infoMsg("Attempt to push docker image into remote registry: ${env.REGISTRY_URL}")
azvyagintsev86ba4a02018-10-03 19:21:28 +0300110 common.retry(3, 5) {
111 docker.withRegistry(env.REGISTRY_URL, env.TARGET_REGISTRY_CREDENTIALS_ID) {
Alexander Evseev3a37d082018-12-10 12:46:39 +0000112 sh("docker push ${targetImageFull}")
azvyagintsev86ba4a02018-10-03 19:21:28 +0300113 }
Alexander Evseevd70ef002018-10-02 13:01:27 +0200114 }
Denis Egorenkoa0f1b2f2018-11-23 17:24:35 +0000115 def buildTime = new Date().format("yyyyMMdd-HH:mm:ss.SSS", TimeZone.getTimeZone('UTC'))
azvyagintsev388a1bd2018-09-06 12:39:49 +0300116
117 if (setDefaultArtifactoryProperties) {
118 common.infoMsg("Processing artifactory props for : ${targetImageFull}")
119 LinkedHashMap artifactoryProperties = [:]
Denis Egorenko343a5712018-12-10 19:08:45 +0400120 def tgtImageInfo = getImageInfo(targetImageFull)
121 def tgt_image_sha256 = tgtImageInfo['sha256']
122 def unique_image_id = tgtImageInfo['id']
123 def tgtImgUrl = imageURL(targetRegistry, targetImageFull, tgt_image_sha256) - '/manifest.json'
Denis Egorenkoa0f1b2f2018-11-23 17:24:35 +0000124 artifactoryProperties = [
Kyrylo Mashchenkoa86912d2018-12-21 08:31:47 +0000125 'com.mirantis.targetTag' : env.IMAGE_TAG,
126 'com.mirantis.uniqueImageId': unique_image_id,
Denis Egorenkoa0f1b2f2018-11-23 17:24:35 +0000127 ]
128 if (external) {
129 artifactoryProperties << ['com.mirantis.externalImage': external]
130 }
Denis Egorenko5b1ab7f2018-12-10 15:21:35 +0400131 def sourceRegistry = sourceImage.split('/')[0]
Denis Egorenko343a5712018-12-10 19:08:45 +0400132 def sourceImgUrl = imageURL(sourceRegistry, sourceImage, source_image_sha256) - '/manifest.json'
Denis Egorenko01918392018-12-10 12:28:46 +0400133 def existingProps = mcp_artifactory.getPropertiesForArtifact(sourceImgUrl)
Denis Egorenkoa0f1b2f2018-11-23 17:24:35 +0000134 def historyProperties = []
Denis Egorenko01918392018-12-10 12:28:46 +0400135 // check does the source image have already history props
Denis Egorenkoa0f1b2f2018-11-23 17:24:35 +0000136 if (existingProps) {
137 historyProperties = existingProps.get('com.mirantis.versionHistory', [])
138 }
139 // %5C - backslash symbol is needed
140 historyProperties.add("${buildTime}%5C=${sourceImage}")
Kyrylo Mashchenkoa86912d2018-12-21 08:31:47 +0000141 artifactoryProperties << [ 'com.mirantis.versionHistory': historyProperties.join(',') ]
Denis Egorenkoa0f1b2f2018-11-23 17:24:35 +0000142 common.infoMsg("artifactoryProperties=> ${artifactoryProperties}")
143 common.retry(3, 5) {
Denis Egorenko01918392018-12-10 12:28:46 +0400144 mcp_artifactory.setProperties(tgtImgUrl, artifactoryProperties)
azvyagintsev388a1bd2018-09-06 12:39:49 +0300145 }
146 }
Richard Felkl7c920d02017-12-11 15:28:18 +0100147 }
Richard Felkle90ef1c2017-12-08 00:13:56 +0100148 }
Jakub Josefa63f9862018-01-11 17:58:38 +0100149 } catch (Throwable e) {
azvyagintsev388a1bd2018-09-06 12:39:49 +0300150 // Stub for future processing
Jakub Josefa63f9862018-01-11 17:58:38 +0100151 currentBuild.result = "FAILURE"
152 throw e
Richard Felkle90ef1c2017-12-08 00:13:56 +0100153 }
Richard Felkle90ef1c2017-12-08 00:13:56 +0100154 }
azvyagintsevd162b912018-07-26 10:52:14 +0200155}