forked from hyperledger-iroha/iroha-dco
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdocker-pull-or-build.groovy
57 lines (53 loc) · 2.39 KB
/
docker-pull-or-build.groovy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#!/usr/bin/env groovy
def remoteFilesDiffer(f1, f2) {
sh "curl -L -o /tmp/${env.GIT_COMMIT}/f1 --create-dirs ${f1}"
sh "curl -L -o /tmp/${env.GIT_COMMIT}/f2 ${f2}"
diffExitCode = sh(script: "diff -q /tmp/${env.GIT_COMMIT}/f1 /tmp/${env.GIT_COMMIT}/f2", returnStatus: true)
return diffExitCode != 0
}
def buildOptionsString(options) {
def s = ''
if (options) {
options.each { k, v ->
s += "--build-arg ${k}=${v} "
}
}
return s
}
def dockerPullOrUpdate(imageName, currentDockerfileURL, previousDockerfileURL, referenceDockerfileURL, buildOptions=null) {
buildOptions = buildOptionsString(buildOptions)
def commit = sh(script: "echo ${GIT_LOCAL_BRANCH} | md5sum | cut -c 1-8", returnStdout: true).trim()
if (remoteFilesDiffer(currentDockerfileURL, previousDockerfileURL)) {
// Dockerfile has been changed compared to the previous commit
// Worst case scenario. We cannot count on the local cache
// because Dockerfile may contain apt-get entries that would try to update
// from invalid (stale) addresses
iC = docker.build("${DOCKER_REGISTRY_BASENAME}:${commit}-${BUILD_NUMBER}", "${buildOptions} --no-cache -f /tmp/${env.GIT_COMMIT}/f1 /tmp/${env.GIT_COMMIT}")
}
else {
// first commit in this branch or Dockerfile modified
if (remoteFilesDiffer(currentDockerfileURL, referenceDockerfileURL)) {
// if we're lucky to build on the same agent, image will be built using cache
iC = docker.build("${DOCKER_REGISTRY_BASENAME}:${commit}-${BUILD_NUMBER}", "$buildOptions -f /tmp/${env.GIT_COMMIT}/f1 /tmp/${env.GIT_COMMIT}")
}
else {
// try pulling image from Dockerhub, probably image is already there
def testExitCode = sh(script: "docker pull ${DOCKER_REGISTRY_BASENAME}:${imageName}", returnStatus: true)
if (testExitCode != 0) {
// image does not (yet) exist on Dockerhub. Build it
iC = docker.build("${DOCKER_REGISTRY_BASENAME}:${commit}-${BUILD_NUMBER}", "$buildOptions --no-cache -f /tmp/${env.GIT_COMMIT}/f1 /tmp/${env.GIT_COMMIT}")
}
else {
// no difference found compared to both previous and reference Dockerfile
iC = docker.image("${DOCKER_REGISTRY_BASENAME}:${imageName}")
}
}
}
if (GIT_LOCAL_BRANCH ==~ /develop|master/) {
docker.withRegistry('https://registry.hub.docker.com', 'docker-hub-credentials') {
iC.push(imageName)
}
}
return iC
}
return this