forked from sonatype/docker-nexus3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Jenkinsfile-Release
329 lines (292 loc) · 14.9 KB
/
Jenkinsfile-Release
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
/*
* Copyright (c) 2016-present Sonatype, Inc. All rights reserved.
* Includes the third-party code listed at http://links.sonatype.com/products/nexus/attributions.
* "Sonatype" is a trademark of Sonatype, Inc.
*/
@Library(['private-pipeline-library', 'jenkins-shared']) _
import com.sonatype.jenkins.pipeline.GitHub
import com.sonatype.jenkins.pipeline.OsTools
import com.sonatype.jenkins.shared.Expectation
String OPENJDK8 = 'OpenJDK 8'
String OPENJDK11 = 'OpenJDK 11'
String OPENJDK17 = 'OpenJDK 17'
List<String> javaVersions = [OPENJDK8, OPENJDK11, OPENJDK17]
properties([
parameters([
string(defaultValue: '', description: 'New Nexus Repository Manager Version', name: 'nexus_repository_manager_version'),
string(defaultValue: '', description: 'New Nexus Repository Manager Version Sha256', name: 'nexus_repository_manager_version_sha'),
string(defaultValue: '', description: 'New Nexus Repository Manager Cookbook Version', name: 'nexus_repository_manager_cookbook_version'),
choice(name: 'java_version', choices: javaVersions, description: 'Java version to run Nexus Repository Manager'),
booleanParam(defaultValue: false, description: 'Skip Pushing of Docker Image and Tags', name: 'skip_push'),
booleanParam(defaultValue: false, description: 'Only update the latest tag', name: 'update_latest_only')
])
])
node('ubuntu-zion') {
def commitId, commitDate, version, imageId, branch, dockerFileLocations, dockerJava11FileLocations, dockerJava17FileLocations
def organization = 'sonatype',
gitHubRepository = 'docker-nexus3',
credentialsId = 'jenkins-github',
imageName = 'sonatype/nexus3',
archiveName = 'docker-nexus3',
dockerHubRepository = 'nexus3',
java8 = 'java8',
java11 = 'java11',
java17 = 'java17'
GitHub gitHub
try {
stage('Preparation') {
deleteDir()
OsTools.runSafe(this, "docker system prune -a -f")
def checkoutDetails = checkout scm
dockerFileLocations = [
"${pwd()}/Dockerfile",
"${pwd()}/Dockerfile.rh.centos",
"${pwd()}/Dockerfile.rh.el",
"${pwd()}/Dockerfile.rh.ubi"
]
dockerJava11FileLocations = [
"${pwd()}/Dockerfile.java11",
"${pwd()}/Dockerfile.rh.ubi.java11"
]
dockerJava17FileLocations = [
"${pwd()}/Dockerfile.java17",
"${pwd()}/Dockerfile.rh.ubi.java17"
]
branch = checkoutDetails.GIT_BRANCH == 'origin/main' ? 'main' : checkoutDetails.GIT_BRANCH
commitId = checkoutDetails.GIT_COMMIT
commitDate = OsTools.runSafe(this, "git show -s --format=%cd --date=format:%Y%m%d-%H%M%S ${commitId}")
OsTools.runSafe(this, 'git config --global user.email [email protected]')
OsTools.runSafe(this, 'git config --global user.name Sonatype CI')
version = readVersion()
def apiToken
withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: credentialsId,
usernameVariable: 'GITHUB_API_USERNAME', passwordVariable: 'GITHUB_API_PASSWORD']]) {
apiToken = env.GITHUB_API_PASSWORD
}
gitHub = new GitHub(this, "${organization}/${gitHubRepository}", apiToken)
if (params.nexus_repository_manager_version && params.nexus_repository_manager_version_sha) {
stage('Update Repository Manager Version') {
OsTools.runSafe(this, "git checkout ${branch}")
if (params.java_version == OPENJDK11) {
dockerJava11FileLocations.each { updateRepositoryManagerVersion(it) }
} else if (params.java_version == OPENJDK17) {
dockerJava17FileLocations.each { updateRepositoryManagerVersion(it) }
} else {
dockerFileLocations.each { updateRepositoryManagerVersion(it) }
}
version = getShortVersion(params.nexus_repository_manager_version)
}
}
if (params.nexus_repository_manager_cookbook_version) {
stage('Update Repository Manager Cookbook Version') {
OsTools.runSafe(this, "git checkout ${branch}")
if (params.java_version == OPENJDK11) {
dockerJava11FileLocations.each { updateRepositoryCookbookVersion(it) }
} else if (params.java_version == OPENJDK17) {
dockerJava17FileLocations.each { updateRepositoryCookbookVersion(it) }
} else {
dockerFileLocations.each { updateRepositoryCookbookVersion(it) }
}
}
}
}
stage('Build') {
gitHub.statusUpdate commitId, 'pending', 'build', 'Build is running'
def dockerfilePath = 'Dockerfile'
if (params.java_version == OPENJDK11) {
dockerfilePath = 'Dockerfile.java11'
} else if (params.java_version == OPENJDK17) {
dockerfilePath = 'Dockerfile.java17'
}
def baseImage = extractBaseImage(dockerfilePath)
def baseImageRefFactory = load 'scripts/BaseImageReference.groovy'
def baseImageReference = baseImageRefFactory.build(this, baseImage as String)
def baseImageReferenceStr = baseImageReference.getReference()
def hash = OsTools.runSafe(this, "docker build --quiet --label base-image-ref='${baseImageReferenceStr}' --no-cache --tag ${imageName} . -f ${dockerfilePath}")
imageId = hash.split(':')[1]
if (currentBuild.result == 'FAILURE') {
gitHub.statusUpdate commitId, 'failure', 'build', 'Build failed'
return
} else {
gitHub.statusUpdate commitId, 'success', 'build', 'Build succeeded'
}
}
stage('Test') {
gitHub.statusUpdate commitId, 'pending', 'test', 'Tests are running'
validateExpectations([
new Expectation('Has user nexus in group nexus present',
'id', '-ng nexus', 'nexus'),
new Expectation('Has nexus user java process present',
'ps', '-e -o command,user | grep -q ^/usr/lib/jvm/java.*nexus$ | echo $?', '0')
])
if (currentBuild.result == 'FAILURE') {
gitHub.statusUpdate commitId, 'failure', 'test', 'Tests failed'
return
} else {
gitHub.statusUpdate commitId, 'success', 'test', 'Tests succeeded'
}
}
stage('Evaluate Policies') {
runEvaluation({ stage ->
nexusPolicyEvaluation(
iqStage: stage,
iqApplication: 'docker-nexus3',
iqScanPatterns: [[scanPattern: "container:${imageName}"]],
failBuildOnNetworkError: true,
)}, 'release')
}
if (currentBuild.result == 'FAILURE') {
return
}
if (params.nexus_repository_manager_version && params.nexus_repository_manager_version_sha
|| params.nexus_repository_manager_cookbook_version) {
stage('Commit Automated Code Update') {
withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: 'jenkins-github',
usernameVariable: 'GITHUB_API_USERNAME', passwordVariable: 'GITHUB_API_PASSWORD']]) {
def commitMessage = [
params.nexus_repository_manager_version && params.nexus_repository_manager_version_sha ?
"Update Repository Manager to ${params.nexus_repository_manager_version}." : "",
params.nexus_repository_manager_cookbook_version ?
"Update Repository Manager Cookbook to ${params.nexus_repository_manager_cookbook_version}." : ""
].findAll({ it }).join(' ')
if (!params.update_latest_only) {
OsTools.runSafe(this, """
git add .
git commit -m '${commitMessage}'
git push https://${env.GITHUB_API_USERNAME}:${env.GITHUB_API_PASSWORD}@github.com/${organization}/${gitHubRepository}.git ${branch}
""")
}
}
}
}
stage('Archive') {
dir('build/target') {
OsTools.runSafe(this, "docker save ${imageName} | gzip > ${archiveName}.tar.gz")
archiveArtifacts artifacts: "${archiveName}.tar.gz", onlyIfSuccessful: true
}
}
if (branch == 'main' && !params.skip_push && !params.update_latest_only) {
input 'Push image and tags?'
stage('Push image') {
def dockerhubApiToken
withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: 'docker-hub-credentials',
usernameVariable: 'DOCKERHUB_API_USERNAME', passwordVariable: 'DOCKERHUB_API_PASSWORD']]) {
if (params.java_version == OPENJDK11) {
OsTools.runSafe(this, "docker tag ${imageId} ${organization}/${dockerHubRepository}:${version}-${java11}")
} else if (params.java_version == OPENJDK17) {
OsTools.runSafe(this, "docker tag ${imageId} ${organization}/${dockerHubRepository}:${version}-${java17}")
} else {
OsTools.runSafe(this, "docker tag ${imageId} ${organization}/${dockerHubRepository}:${version}")
OsTools.runSafe(this, "docker tag ${imageId} ${organization}/${dockerHubRepository}:${version}-${java8}")
OsTools.runSafe(this, "docker tag ${imageId} ${organization}/${dockerHubRepository}:latest")
}
OsTools.runSafe(this, """
docker login --username ${env.DOCKERHUB_API_USERNAME} --password ${env.DOCKERHUB_API_PASSWORD}
""")
if (params.java_version == OPENJDK11) {
OsTools.runSafe(this, "docker push ${organization}/${dockerHubRepository}:${version}-${java11}")
} else if (params.java_version == OPENJDK17) {
OsTools.runSafe(this, "docker push ${organization}/${dockerHubRepository}:${version}-${java17}")
} else {
OsTools.runSafe(this, "docker push --all-tags ${organization}/${dockerHubRepository}")
}
response = OsTools.runSafe(this, """
curl -X POST https://hub.docker.com/v2/users/login/ \
-H 'cache-control: no-cache' -H 'content-type: application/json' \
-d '{ "username": "${env.DOCKERHUB_API_USERNAME}", "password": "${env.DOCKERHUB_API_PASSWORD}" }'
""")
token = readJSON text: response
dockerhubApiToken = token.token
def readme = readFile file: 'README.md', encoding: 'UTF-8'
readme = readme.replaceAll("(?s)<!--.*?-->", "")
readme = readme.replace("\"", "\\\"")
readme = readme.replace("\n", "\\n")
response = httpRequest customHeaders: [[name: 'authorization', value: "JWT ${dockerhubApiToken}"]],
acceptType: 'APPLICATION_JSON', contentType: 'APPLICATION_JSON', httpMode: 'PATCH',
requestBody: "{ \"full_description\": \"${readme}\" }",
url: "https://hub.docker.com/v2/repositories/${organization}/${dockerHubRepository}/"
// push to internal repos
withSonatypeDockerRegistry() {
if (params.java_version == OPENJDK11) {
sh "docker tag ${imageId} docker-all.repo.sonatype.com/sonatype-internal/${dockerHubRepository}:${version}-${java11}"
sh "docker push docker-all.repo.sonatype.com/sonatype-internal/${dockerHubRepository}:${version}-${java11}"
} else if (params.java_version == OPENJDK17) {
sh "docker tag ${imageId} docker-all.repo.sonatype.com/sonatype-internal/${dockerHubRepository}:${version}-${java17}"
sh "docker push docker-all.repo.sonatype.com/sonatype-internal/${dockerHubRepository}:${version}-${java17}"
} else {
sh "docker tag ${imageId} docker-all.repo.sonatype.com/sonatype-internal/${dockerHubRepository}:${version}"
sh "docker push docker-all.repo.sonatype.com/sonatype-internal/${dockerHubRepository}:${version}"
sh "docker tag ${imageId} docker-all.repo.sonatype.com/sonatype-internal/${dockerHubRepository}:${version}-${java8}"
sh "docker push docker-all.repo.sonatype.com/sonatype-internal/${dockerHubRepository}:${version}-${java8}"
}
}
}
}
stage('Push tags') {
withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: credentialsId,
usernameVariable: 'GITHUB_API_USERNAME', passwordVariable: 'GITHUB_API_PASSWORD']]) {
OsTools.runSafe(this, "git tag ${version}")
OsTools.runSafe(this, """
git push \
https://${env.GITHUB_API_USERNAME}:${env.GITHUB_API_PASSWORD}@github.com/${organization}/${gitHubRepository}.git \
${version}
""")
}
OsTools.runSafe(this, "git tag -d ${version}")
}
}
else if(params.update_latest_only) {
stage('Push tags') {
withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: 'docker-hub-credentials',
usernameVariable: 'DOCKERHUB_API_USERNAME', passwordVariable: 'DOCKERHUB_API_PASSWORD']]) {
OsTools.runSafe(this, "docker tag ${imageId} ${organization}/${dockerHubRepository}:latest")
OsTools.runSafe(this, """
docker login --username ${env.DOCKERHUB_API_USERNAME} --password ${env.DOCKERHUB_API_PASSWORD}
""")
OsTools.runSafe(this, "docker push --all-tags ${organization}/${dockerHubRepository}")
}
}
}
} finally {
OsTools.runSafe(this, "docker logout")
OsTools.runSafe(this, "docker system prune -a -f")
OsTools.runSafe(this, 'git clean -f && git reset --hard origin/main')
}
}
def readVersion() {
def content = readFile 'Dockerfile'
for (line in content.split('\n')) {
if (line.startsWith('ARG NEXUS_VERSION=')) {
return getShortVersion(line.substring(18))
}
}
error 'Could not determine version.'
}
def getShortVersion(version) {
return version.split('-')[0]
}
def updateRepositoryManagerVersion(dockerFileLocation) {
def dockerFile = readFile(file: dockerFileLocation)
def metaVersionRegex = /(version=")(\d\.\d{1,3}\.\d\-\d{2})(" \\)/
def metaShortVersionRegex = /(release=")(\d\.\d{1,3}\.\d)(" \\)/
def versionRegex = /(ARG NEXUS_VERSION=)(\d\.\d{1,3}\.\d\-\d{2})/
def shaRegex = /(ARG NEXUS_DOWNLOAD_SHA256_HASH=)([A-Fa-f0-9]{64})/
dockerFile = dockerFile.replaceAll(metaVersionRegex, "\$1${params.nexus_repository_manager_version}\$3")
dockerFile = dockerFile.replaceAll(metaShortVersionRegex,
"\$1${params.nexus_repository_manager_version.substring(0, params.nexus_repository_manager_version.indexOf('-'))}\$3")
dockerFile = dockerFile.replaceAll(versionRegex, "\$1${params.nexus_repository_manager_version}")
dockerFile = dockerFile.replaceAll(shaRegex, "\$1${params.nexus_repository_manager_version_sha}")
writeFile(file: dockerFileLocation, text: dockerFile)
}
def updateRepositoryCookbookVersion(dockerFileLocation) {
def dockerFile = readFile(file: dockerFileLocation)
def cookbookVersionRegex = /(ARG NEXUS_REPOSITORY_MANAGER_COOKBOOK_VERSION=")(release-\d\.\d\.\d{8}\-\d{6}\.[a-z0-9]{7})(")/
dockerFile = dockerFile.replaceAll(cookbookVersionRegex, "\$1${params.nexus_repository_manager_cookbook_version}\$3")
writeFile(file: dockerFileLocation, text: dockerFile)
}
def extractBaseImage (dockerFileLocation) {
def dockerFile = readFile(file: dockerFileLocation)
def baseImageRegex = "FROM\\s+([^\\s]+)"
def usedImages = dockerFile =~ baseImageRegex
return usedImages[0][1]
}