-
Notifications
You must be signed in to change notification settings - Fork 0
/
Jenkinsfile
451 lines (359 loc) · 17.5 KB
/
Jenkinsfile
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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
#!groovy
/*
* © 2022. TU Dortmund University,
* Institute of Energy Systems, Energy Efficiency and Energy Economics,
* Research group Distribution grid planning and operation
*/
////////////////////////////////
// general config values
////////////////////////////////
//// project build dir order
//// this list contains the build order
//// normally it *should* start with the project under investigation
//// but if this projects depends on some of our other projects, you have to *build the dependencies first*!
//// *IMPORTANT:* you *MUST* use exact repo names as this will used for checkout!
//// *IMPORTANT2:* you must provide exact 4 elements!
projects = ['mobilitysimulator']
orgNames = ['ie3-institute']
urls = [
'git@github.com:' + orgNames.get(0)
]
def sonarqubeProjectKey = "edu.ie3:mobilitySimulator"
//// internal jenkins credentials link for git ssh keys
//// requires the ssh key to be stored in the internal jenkins credentials keystore
def sshCredentialsId = "19f16959-8a0d-4a60-bd1f-5adb4572b702"
//// internal maven central credentials
def mavenCentralCredentialsId = "87bfb2d4-7613-4816-9fe1-70dfd7e6dec2"
def mavenCentralSignKeyFileId = "dc96216c-d20a-48ff-98c0-1c7ba096d08d"
def mavenCentralSignKeyId = "a1357827-1516-4fa2-ab8e-72cdea07a692"
//// define and setjava version ////
//// requires the java version to be set in the internal jenkins java version management
//// use identifier accordingly
def javaVersionId = 'jdk-17'
//// set java version method (needs node{} for execution)
void setJavaVersion(javaVersionId) {
env.JAVA_HOME = "${tool javaVersionId}"
env.PATH = "${env.JAVA_HOME}/bin:${env.PATH}"
}
/// global config variables that should be available during runtime
/// and will be overwritten during runtime -> DO NOT CHANGE THEM
String featureBranchName = ""
//// gradle tasks that are executed
def gradleTasks = "--refresh-dependencies clean spotlessCheck pmdMain pmdTest test reportScoverage checkScoverage" // the gradle tasks that are executed on ALL projects
def mainProjectGradleTasks = "" // additional tasks that are only executed on project 0 (== main project)
// if you need additional tasks for deployment add them here
// NOTE: artifactory task with credentials will be added below
def deployGradleTasks = ""
/// commit hash
def commitHash = ""
if (env.BRANCH_NAME == "main") {
// setup
getMasterBranchProps()
// pure deployment
if (params.deploy == "true") {
node {
ansiColor('xterm') {
// get the deployment version
def projectVersion = sh(returnStdout: true, script: "cd ${projects.get(0)}; set +x; ./gradlew -q printVersion")
try {
// set java version
setJavaVersion(javaVersionId)
// set build display name
currentBuild.displayName = "deployment v"+projectVersion +" (" + currentBuild.displayName + ")"
// checkout from scm
stage('checkout from scm') {
try {
// merged mode
commitHash = gitCheckout(projects.get(0), urls.get(0), 'refs/heads/main', sshCredentialsId).GIT_COMMIT
} catch (exc) {
sh 'exit 1' // failure due to not found main branch
}
}
// test the project
stage("gradle test ${projects.get(0)}") {
// build and test the project
gradle("${gradleTasks} ${mainProjectGradleTasks}")
}
// execute sonarqube code analysis
stage('SonarQube analysis') {
withSonarQubeEnv() {
// Will pick the global server connection from jenkins for sonarqube
gradle("sonar -Dsonar.branch.name=main -Dsonar.projectKey=$sonarqubeProjectKey")
}
}
// wait for the sonarqube quality gate
stage("Quality Gate") {
timeout(time: 1, unit: 'HOURS') {
// Just in case something goes wrong, pipeline will be killed after a timeout
def qg = waitForQualityGate() // Reuse taskId previously collected by withSonarQubeEnv
if (qg.status != 'OK') {
error "Pipeline aborted due to quality gate failure: ${qg.status}"
}
}
}
// publish report und coverage
stage('publish reports + coverage') {
// publish reports
publishReports(projects.get(0))
}
// deploy snapshot version to oss sonatype
stage('deploy') {
// get the sonatype credentials stored in the jenkins secure keychain
withCredentials([
usernamePassword(credentialsId: mavenCentralCredentialsId, usernameVariable: 'mavencentral_username', passwordVariable: 'mavencentral_password'),
file(credentialsId: mavenCentralSignKeyFileId, variable: 'mavenCentralKeyFile'),
usernamePassword(credentialsId: mavenCentralSignKeyId, passwordVariable: 'signingPassword', usernameVariable: 'signingKeyId')
]) {
deployGradleTasks = "--refresh-dependencies clean test " + deployGradleTasks + "publish -Puser=${env.mavencentral_username} -Ppassword=${env.mavencentral_password} -Psigning.keyId=${env.signingKeyId} -Psigning.password=${env.signingPassword} -Psigning.secretKeyRingFile=${env.mavenCentralKeyFile}"
// see https://docs.gradle.org/6.0.1/release-notes.html "Publication of SHA256 and SHA512 checksums"
def preventSHACheckSums = "-Dorg.gradle.internal.publish.checksums.insecure=true"
gradle("${deployGradleTasks} $preventSHACheckSums")
}
}
} catch (Exception e) {
// set build result to failure
currentBuild.result = 'FAILURE'
// publish reports even on failure
publishReports(projects.get(0))
// print exception
Date date = new Date()
println("[ERROR] [${date.format("dd/MM/yyyy")} - ${date.format("HH:mm:ss")}]" + e)
}
}
}
} else {
// merge of features
node {
ansiColor('xterm') {
try {
// set java version
setJavaVersion(javaVersionId)
// checkout from scm
stage('checkout from scm') {
try {
// merged mode
commitHash = gitCheckout(projects.get(0), urls.get(0), 'refs/heads/main', sshCredentialsId).GIT_COMMIT
} catch (exc) {
sh 'exit 1' // failure due to not found main branch
}
}
// get information based on commit hash
def jsonObject = getGithubCommitJsonObj(commitHash, orgNames.get(0), projects.get(0))
featureBranchName = splitStringToBranchName(jsonObject.commit.message)
def message = (featureBranchName?.trim()) ?
"main branch build triggered (incl. snapshot deploy) by merging pr from feature branch '${featureBranchName}'"
: "main branch build triggered (incl. snapshot deploy) for commit with message '${jsonObject.commit.message}'"
// set build display name
currentBuild.displayName = ((featureBranchName?.trim()) ? "merge pr branch '${featureBranchName}'" : "commit '" +
"${jsonObject.commit.message.length() <= 20 ? jsonObject.commit.message : jsonObject.commit.message.substring(0, 20)}...'") + " (" + currentBuild.displayName + ")"
// test the project
stage("gradle test ${projects.get(0)}") {
// build and test the project
gradle("${gradleTasks} ${mainProjectGradleTasks}")
}
// execute sonarqube code analysis
stage('SonarQube analysis') {
withSonarQubeEnv() {
// Will pick the global server connection from jenkins for sonarqube
gradle("sonar -Dsonar.branch.name=main -Dsonar.projectKey=$sonarqubeProjectKey ")
}
}
// wait for the sonarqube quality gate
stage("Quality Gate") {
timeout(time: 1, unit: 'HOURS') {
// Just in case something goes wrong, pipeline will be killed after a timeout
def qg = waitForQualityGate() // Reuse taskId previously collected by withSonarQubeEnv
if (qg.status != 'OK') {
error "Pipeline aborted due to quality gate failure: ${qg.status}"
}
}
}
// post processing
stage('publish reports + coverage') {
// publish reports
publishReports(projects.get(0))
}
// deploy snapshot version to oss sonatype
stage('deploy') {
// get the sonatype credentials stored in the jenkins secure keychain
withCredentials([
usernamePassword(credentialsId: mavenCentralCredentialsId, usernameVariable: 'mavencentral_username', passwordVariable: 'mavencentral_password'),
file(credentialsId: mavenCentralSignKeyFileId, variable: 'mavenCentralKeyFile'),
usernamePassword(credentialsId: mavenCentralSignKeyId, passwordVariable: 'signingPassword', usernameVariable: 'signingKeyId')
]) {
deployGradleTasks = "--refresh-dependencies clean test " + deployGradleTasks + "publish -Puser=${env.mavencentral_username} -Ppassword=${env.mavencentral_password} -Psigning.keyId=${env.signingKeyId} -Psigning.password=${env.signingPassword} -Psigning.secretKeyRingFile=${env.mavenCentralKeyFile}"
gradle("${deployGradleTasks}")
}
}
} catch (Exception e) {
// set build result to failure
currentBuild.result = 'FAILURE'
// publish reports even on failure
publishReports(projects.get(0))
// print exception
Date date = new Date()
println("[ERROR] [${date.format("dd/MM/yyyy")} - ${date.format("HH:mm:ss")}]" + e)
}
}
}
}
} else {
// setup
getFeatureBranchProps()
node {
def repoName = ""
// init variables depending of this build is triggered by a branch with PR or without PR
if (env.CHANGE_ID == null) {
// no PR exists
featureBranchName = env.BRANCH_NAME
repoName = orgNames.get(0) + "/" + projects.get(0)
} else {
// PR exists
/// curl the api to get debugging details
def jsonObj = getGithubPRJsonObj(env.CHANGE_ID, orgNames.get(0), projects.get(0))
featureBranchName = jsonObj.head.ref
repoName = jsonObj.head.repo.full_name
}
ansiColor('xterm') {
try {
// set java version
setJavaVersion(javaVersionId)
/// set the build name
currentBuild.displayName = featureBranchName + " (" + currentBuild.displayName + ")"
stage('checkout from scm') {
try {
commitHash = gitCheckout(projects.get(0), urls.get(0), featureBranchName, sshCredentialsId).GIT_COMMIT
} catch (exc) {
// our target repo failed during checkout
sh 'exit 1' // failure due to not found forcedPR branch
}
}
// test the project
stage("gradle test ${projects.get(0)}") {
// build and test the project
gradle("${gradleTasks} ${mainProjectGradleTasks}")
}
// execute sonarqube code analysis
stage('SonarQube analysis') {
withSonarQubeEnv() {
// Will pick the global server connection from jenkins for sonarqube
String gradleCommand = "sonar -Dsonar.projectKey=$sonarqubeProjectKey"
if (env.CHANGE_ID != null) {
gradleCommand = gradleCommand + " -Dsonar.pullrequest.branch=${featureBranchName} -Dsonar.pullrequest.key=${env.CHANGE_ID} -Dsonar.pullrequest.base=main -Dsonar.pullrequest.github.repository=${orgNames.get(0)}/${projects.get(0)} -Dsonar.pullrequest.provider=Github"
} else {
gradleCommand = gradleCommand + " -Dsonar.branch.name=$featureBranchName"
}
gradle(gradleCommand)
}
}
// wait for the sonarqube quality gate
stage("Quality Gate") {
timeout(time: 1, unit: 'HOURS') {
// Just in case something goes wrong, pipeline will be killed after a timeout
def qg = waitForQualityGate() // Reuse taskId previously collected by withSonarQubeEnv
if (qg.status != 'OK') {
error "Pipeline aborted due to quality gate failure: ${qg.status}"
}
}
}
// post processing
stage('post processing') {
// publish reports
publishReports(projects.get(0))
}
} catch (Exception e) {
// set build result to failure
currentBuild.result = 'FAILURE'
// publish reports even on failure
publishReports(projects.get(0))
// print exception
Date date = new Date()
println("[ERROR] [${date.format("dd/MM/yyyy")} - ${date.format("HH:mm:ss")}]" + e)
}
}
}
}
def getFeatureBranchProps() {
properties(
[
pipelineTriggers([
issueCommentTrigger('.*!test.*')
])
])
}
def getMasterBranchProps() {
properties([
parameters(
[
string(defaultValue: '', description: '', name: 'deploy', trim: true)
]),
[$class: 'RebuildSettings', autoRebuild: false, rebuildDisabled: false],
[$class: 'ThrottleJobProperty', categories: [], limitOneJobWithMatchingParams: false, maxConcurrentPerNode: 0, maxConcurrentTotal: 0, paramsToUseForLimit: '', throttleEnabled: true, throttleOption: 'project']
])
}
////////////////////////////////////
// git checkout
// NOTE: requires node {}
////////////////////////////////////
def gitCheckout(String relativeTargetDir, String baseUrl, String branch, String sshCredentialsId) {
checkout([
$class : 'GitSCM',
branches : [[name: branch]],
doGenerateSubmoduleConfigurations: false,
extensions : [
[$class: 'RelativeTargetDirectory', relativeTargetDir: relativeTargetDir]
],
submoduleCfg : [],
userRemoteConfigs : [
[credentialsId: sshCredentialsId, url: baseUrl + "/" + relativeTargetDir + ".git"]
]
])
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// publish reports
// IMPORTANT: has to be called inside the same node{} as where the build process (report generation) took place!
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
def publishReports(String relativeProjectDir) {
// publish test reports
publishHTML([allowMissing: true, alwaysLinkToLastBuild: true, escapeUnderscores: false, keepAll: true, reportDir: relativeProjectDir + '/build/reports/tests/test', reportFiles: 'index.html', reportName: "${relativeProjectDir}_java_tests_report", reportTitles: ''])
// publish pmd report for main project only
// publishHTML([allowMissing: true, alwaysLinkToLastBuild: true, escapeUnderscores: false, keepAll: true, reportDir: relativeProjectDir + '/build/reports/pmd', reportFiles: 'main.html', reportName: "${relativeProjectDir}_pmd_report", reportTitles: ''])
// publish scalatest reports for main project only (currently the only one with scala sources!)
// publishHTML([allowMissing: false, alwaysLinkToLastBuild: true, escapeUnderscores: false, keepAll: true, reportDir: relativeProjectDir + '/build/reports/tests/scalatest', reportFiles: 'index.html', reportName: "${relativeProjectDir}_scala_tests_report", reportTitles: ''])
// publish scapegoat src report for main project only
publishHTML([allowMissing: false, alwaysLinkToLastBuild: true, escapeUnderscores: false, keepAll: true, reportDir: relativeProjectDir + '/build/reports/scapegoat/src', reportFiles: 'scapegoat.html', reportName: "${relativeProjectDir}_scapegoat_src_report", reportTitles: ''])
// publish scapegoat testsrc report for main project only
publishHTML([allowMissing: false, alwaysLinkToLastBuild: true, escapeUnderscores: false, keepAll: true, reportDir: relativeProjectDir + '/build/reports/scapegoat/testsrc', reportFiles: 'scapegoat.html', reportName: "${relativeProjectDir}_scapegoat_testsrc_report", reportTitles: ''])
}
// gradle wrapper method for easy execution
// requires the gradle version to be configured with the same name under tools in jenkins configuration
def gradle(String command) {
env.JENKINS_NODE_COOKIE = 'dontKillMe' // this is necessary for the Gradle daemon to be kept alive
// switch directory to be able to use gradle wrapper
sh """cd ${projects.get(0)}""" + ''' set +x; ./gradlew ''' + """$command"""
}
def getGithubPRJsonObj(String prId, String orgName, String repoName) {
def jsonObj = readJSON text: curlByPR(prId, orgName, repoName)
return jsonObj
}
def curlByPR(String prId, String orgName, String repoName) {
def curlUrl = "curl https://api.github.com/repos/" + orgName + "/" + repoName + "/pulls/" + prId
String jsonResponseString = sh(script: curlUrl, returnStdout: true)
return jsonResponseString
}
def getGithubCommitJsonObj(String commit_sha, String orgName, String repoName) {
def jsonObj = readJSON text: curlByCSHA(commit_sha, orgName, repoName)
return jsonObj
}
def curlByCSHA(String commit_sha, String orgName, String repoName) {
def curlUrl = "curl https://api.github.com/repos/" + orgName + "/" + repoName + "/commits/" + commit_sha
String jsonResponseString = sh(script: curlUrl, returnStdout: true)
return jsonResponseString
}
def splitStringToBranchName(String string) {
def obj = string.split().find { it.startsWith("ie3-institute") }
if (obj)
return (obj as String).substring(14)
else
return ""
}