-
Notifications
You must be signed in to change notification settings - Fork 2
/
Jenkinsfile
384 lines (302 loc) · 13.8 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
#!groovy
/*
* © 2021. TU Dortmund University,
* Institute of Energy Systems, Energy Efficiency and Energy Economics,
* Research group Distribution grid planning and operation
*/
////////////////////////////////
// general config values
////////////////////////////////
projects = ['powerFactory2psdm']
orgNames = ['ie3-institute']
urls = [
'[email protected]:' + orgNames.get(0)
]
def sonarqubeProjectKey = "edu.ie3:powerFactory2psdm"
/// code coverage token id
codeCovTokenId = "powerfactory2psdm-codecov-token"
//// 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"
//// 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 check" // the gradle tasks that are executed on ALL projects
def mainProjectGradleTasks = "reportScoverage checkScoverage" // 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()
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 by merging pr from feature branch '${featureBranchName}'"
: "main branch build triggered for commit with message '${jsonObject.commit.message}'"
message: message + "\n"
rawMessage: true
// 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 check ${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, TODO: Remove exclusion, when removing deprecated quantity package
gradle("sonarqube -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()
// inform codecov.io
withCredentials([
string(credentialsId: codeCovTokenId, variable: 'codeCovToken')
]) {
// call codecov
sh "curl -s https://codecov.io/bash | bash -s - -t ${env.codeCovToken} -C ${commitHash}"
message = (featureBranchName?.trim()) ?
"main branch build successful! Merged pr from feature branch '${featureBranchName}'"
: "main branch build successful! Build commit with message is '${jsonObject.commit.message}'"
message: message + "\n" +
"*repo:* ${urls.get(0)}/${projects.get(0)}\n" +
"*branch:* main \n"
rawMessage: true
}
}
} catch (Exception e) {
// set build result to failure
currentBuild.result = 'FAILURE'
// publish reports even on failure
publishReports()
// print exception
Date date = new Date()
println("[ERROR] [${date.format("dd/MM/yyyy")} - ${date.format("HH:mm:ss")}]" + e)
message: "merge feature into main failed!\n" +
"*repo:* ${urls.get(0)}/${projects.get(0)}\n"
rawMessage: true
}
}
}
} 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 + ")"
message: "feature branch build triggered:\n" +
"*repo:* ${repoName}\n" +
"*branch:* ${featureBranchName}\n"
rawMessage: true
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 check ${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
// do we have a PR?, TODO: Remove with removal of deprecated quantity package
String gradleCommand = "sonarqube -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('publish reports + coverage') {
// publish reports
publishReports()
withCredentials([
string(credentialsId: codeCovTokenId, variable: 'codeCovToken')
]) {
// call codecov
sh "curl -s https://codecov.io/bash | bash -s - -t ${env.codeCovToken} -C ${commitHash}"
}
message: "feature branch test successful!\n" +
"*repo:* ${repoName}\n" +
"*branch:* ${featureBranchName}\n"
rawMessage: true
}
} catch (Exception e) {
// set build result to failure
currentBuild.result = 'FAILURE'
// publish reports even on failure
publishReports()
// print exception
Date date = new Date()
println("[ERROR] [${date.format("dd/MM/yyyy")} - ${date.format("HH:mm:ss")}]" + e)
message: "feature branch test failed!\n" +
"*repo:* ${repoName}\n" +
"*branch:* ${featureBranchName}\n"
rawMessage: true
}
}
}
}
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() {
// publish scalatest reports
publishHTML([allowMissing: false, alwaysLinkToLastBuild: true, escapeUnderscores: false, keepAll: true, reportDir: projects.get(0) + '/build/reports/tests/test', reportFiles: 'index.html', reportName: "${projects.get(0)}_scala_tests_report", reportTitles: ''])
// publish scoverage reports
publishHTML([allowMissing: false, alwaysLinkToLastBuild: true, escapeUnderscores: false, keepAll: true, reportDir: projects.get(0) + '/build/reports/scoverage', reportFiles: 'scoverage.xml', reportName: "${projects.get(0)}_scoverage_report", reportTitles: ''])
// publish pmd report
publishHTML([allowMissing: true, alwaysLinkToLastBuild: true, escapeUnderscores: false, keepAll: true, reportDir: projects.get(0) + '/build/reports/pmd', reportFiles: 'main.html', reportName: "${projects.get(0)}_pmd_report", reportTitles: ''])
// publish scapegoat src report
publishHTML([allowMissing: false, alwaysLinkToLastBuild: true, escapeUnderscores: false, keepAll: true, reportDir: projects.get(0) + '/build/reports/scapegoat/src', reportFiles: 'scapegoat.html', reportName: "${projects.get(0)}_scapegoat_src_report", reportTitles: ''])
// publish scapegoat testsrc report
publishHTML([allowMissing: false, alwaysLinkToLastBuild: true, escapeUnderscores: false, keepAll: true, reportDir: projects.get(0) + '/build/reports/scapegoat/testsrc', reportFiles: 'scapegoat.html', reportName: "${projects.get(0)}_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 bew 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 ""
}