-
Notifications
You must be signed in to change notification settings - Fork 22
/
Jenkinsfile.dev
244 lines (227 loc) · 9.29 KB
/
Jenkinsfile.dev
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
// Switch to using https://github.com/BCDevOps/jenkins-pipeline-shared-lib when stable.
@NonCPS
import groovy.json.JsonOutput
/*
* Sends a slack notification
*/
def notifySlack(text, url, channel, attachments) {
def slackURL = url
def jenkinsIcon = 'https://wiki.jenkins-ci.org/download/attachments/2916393/logo.png'
def payload = JsonOutput.toJson([text: text,
channel: channel,
username: "Jenkins",
icon_url: jenkinsIcon,
attachments: attachments
])
def encodedReq = URLEncoder.encode(payload, "UTF-8")
sh("curl -s -S -X POST --data \'payload=${encodedReq}\' ${slackURL}")
}
/*
* Sends a rocket chat notification
*/
def notifyRocketChat(text, url) {
def rocketChatURL = url
def payload = JsonOutput.toJson([
"username":"Jenkins",
"icon_url":"https://wiki.jenkins.io/download/attachments/2916393/headshot.png",
"text": text
])
sh("curl -X POST -H 'Content-Type: application/json' --data \'${payload}\' ${rocketChatURL}")
}
/*
* Updates the global pastBuilds array: it will iterate recursively
* and add all the builds prior to the current one that had a result
* different than 'SUCCESS'.
*/
def buildsSinceLastSuccess(previousBuild, build) {
if ((build != null) && (build.result != 'SUCCESS')) {
pastBuilds.add(build)
buildsSinceLastSuccess(pastBuilds, build.getPreviousBuild())
}
}
/*
* Generates a string containing all the commit messages from
* the builds in pastBuilds.
*/
@NonCPS
def getChangeLog(pastBuilds) {
def log = ""
for (int x = 0; x < pastBuilds.size(); x++) {
for (int i = 0; i < pastBuilds[x].changeSets.size(); i++) {
def entries = pastBuilds[x].changeSets[i].items
for (int j = 0; j < entries.length; j++) {
def entry = entries[j]
log += "* ${entry.msg} by ${entry.author} \n"
}
}
}
return log;
}
def CHANGELOG = "No new changes"
def IMAGE_HASH = "latest"
node('master') {
/*
* Extract secrets and create relevant environment variables.
* The contents of the secret are extracted in as many files as the keys contained in the secret.
* The files are named as the key, and contain the corresponding value.
*/
sh("oc extract secret/slack-secrets --to=${env.WORKSPACE} --confirm")
SLACK_HOOK = sh(script: "cat webhook", returnStdout: true)
DEV_CHANNEL = sh(script: "cat dev-channel", returnStdout: true)
withEnv(["SLACK_HOOK=${SLACK_HOOK}", "DEV_CHANNEL=${DEV_CHANNEL}"]){
stage('Build'){
// isolate last successful builds and then get the changelog
pastBuilds = []
buildsSinceLastSuccess(pastBuilds, currentBuild);
CHANGELOG = getChangeLog(pastBuilds);
echo ">>>>>>Changelog: \n ${CHANGELOG}"
try {
echo "Building..."
openshiftBuild bldCfg: 'mem-admin-dev', showBuildLogs: 'true'
echo "Build done"
echo "Tagging image..."
// Don't tag with BUILD_ID so the pruner can do it's job; it won't delete tagged images.
// Tag the images for deployment based on the image's hash
IMAGE_HASH = sh (
script: """oc get istag mem-admin-dev:latest -o template --template=\"{{.image.dockerImageReference}}\"|awk -F \":\" \'{print \$3}\'""",
returnStdout: true).trim()
echo ">> IMAGE_HASH: ${IMAGE_HASH}"
echo "Tagging done"
} catch (error) {
notifySlack(
"The latest mem-admin-dev build seems to have broken\n'${error.message}'",
SLACK_HOOK,
DEV_CHANNEL,
[]
)
throw error
}
}
}
}
node('master'){
/*
* Extract secrets and create relevant environment variables.
* The contents of the secret are extracted in as many files as the keys contained in the secret.
* The files are named as the key, and contain the corresponding value.
*/
sh("oc extract secret/slack-secrets --to=${env.WORKSPACE} --confirm")
SLACK_HOOK = sh(script: "cat webhook", returnStdout: true)
DEPLOY_CHANNEL = sh(script: "cat deploy-channel", returnStdout: true)
sh("oc extract secret/rocket-chat-secrets --to=${env.WORKSPACE} --confirm")
ROCKET_DEPLOY_WEBHOOK = sh(script: "cat rocket-deploy-webhook", returnStdout: true)
withEnv(["SLACK_HOOK=${SLACK_HOOK}", "DEPLOY_CHANNEL=${DEPLOY_CHANNEL}", "ROCKET_DEPLOY_WEBHOOK=${ROCKET_DEPLOY_WEBHOOK}"]){
stage('Deploy to Dev'){
try {
echo "Deploying to dev..."
openshiftTag destStream: 'mem-admin-dev', verbose: 'false', destTag: 'dev', srcStream: 'mem-admin-dev', srcTag: "${IMAGE_HASH}"
sleep 5
openshiftVerifyDeployment depCfg: 'mem-mmt-dev', namespace: 'mem-mmt-dev', replicaCount: 1, verbose: 'false', verifyReplicaCount: 'false', waitTime: 600000
echo ">>>> Deployment Complete"
notifyRocketChat(
"A new version of mem-admin-dev is now in Dev. \n Changes: \n ${CHANGELOG}",
ROCKET_DEPLOY_WEBHOOK
)
notifySlack(
"A new version of mem-admin-dev is now in Dev. \n Changes: \n ${CHANGELOG}",
SLACK_HOOK,
DEPLOY_CHANNEL,
[]
)
} catch (error) {
notifyRocketChat(
"The latest deployment of mem-admin-dev to Dev seems to have failed\n'${error.message}'",
ROCKET_DEPLOY_WEBHOOK
)
notifySlack(
"The latest deployment of mem-admin-dev to Dev seems to have failed\n'${error.message}'",
SLACK_HOOK,
DEPLOY_CHANNEL,
[]
)
}
}
}
}
// def bddPodLabel = "mem-admin-bdd-${UUID.randomUUID().toString()}"
// podTemplate(label: bddPodLabel, name: bddPodLabel, serviceAccount: 'jenkins', cloud: 'openshift', containers: [
// containerTemplate(
// name: 'jnlp',
// image: 'docker-registry.default.svc:5000/bcgov/jenkins-slave-bddstack:v1-stable',
// resourceRequestCpu: '500m',
// resourceLimitCpu: '1000m',
// resourceRequestMemory: '1Gi',
// resourceLimitMemory: '4Gi',
// workingDir: '/home/jenkins',
// command: '',
// args: '${computer.jnlpmac} ${computer.name}',
// envVars: [
// secretEnvVar(key: 'MONGODB_USER', secretName: 'bddstack-mongodb', secretKey: 'database-user'),
// secretEnvVar(key: 'MONGODB_PASSWORD', secretName: 'bddstack-mongodb', secretKey: 'database-password'),
// secretEnvVar(key: 'MONGODB_FUNC_DATABASE', secretName: 'bddstack-mongodb', secretKey: 'database-name')
// ]
// )
// ])
// {
// stage('FT on Dev') {
// node(bddPodLabel) {
// //the checkout is mandatory, otherwise functional test would fail
// echo "checking out source"
// echo "Build: ${BUILD_ID}"
// checkout scm
// try {
// // enable node for the current shell, then build the code and run the flow tests
// sh ". /opt/rh/rh-nodejs6/enable; npm install yarn; ./node_modules/yarn/bin/yarn install; npm run e2e -- --MONGODB_FUNC_HOST=bddstack-mongodb --MONGODB_USER=${MONGODB_USER} --MONGODB_PASSWORD=${MONGODB_PASSWORD} --MONGODB_FUNC_DATABASE=${MONGODB_FUNC_DATABASE} --NO_DB_DROP=true"
// } finally {
// archiveArtifacts allowEmptyArchive: true, artifacts: 'functional-tests/build/reports/geb/**/*'
// junit 'functional-tests/build/test-results/**/*.xml'
// publishHTML (target: [
// allowMissing: false,
// alwaysLinkToLastBuild: false,
// keepAll: true,
// reportDir: 'functional-tests/build/reports/spock',
// reportFiles: 'index.html',
// reportName: "BDD Spock Report"
// ])
// publishHTML (target: [
// allowMissing: false,
// alwaysLinkToLastBuild: false,
// keepAll: true,
// reportDir: 'functional-tests/build/reports/test-results/chromeHeadlessTest',
// reportFiles: 'index.html',
// reportName: "Full Test Report"
// ])
// perfReport compareBuildPrevious: true, excludeResponseTime: true, ignoreFailedBuilds: true, ignoreUnstableBuilds: true, modeEvaluation: true, modePerformancePerTestCase: true, percentiles: '0,50,90,100', relativeFailedThresholdNegative: 80.0, relativeFailedThresholdPositive: 20.0, relativeUnstableThresholdNegative: 50.0, relativeUnstableThresholdPositive: 50.0, sourceDataFiles: 'build/test-results/**/*.xml'
// }
// }
// }
// }
def zapPodLabel = "mem-admin-owasp-zap-${UUID.randomUUID().toString()}"
podTemplate(label: zapPodLabel, name: zapPodLabel, serviceAccount: 'jenkins', cloud: 'openshift', containers: [
containerTemplate(
name: 'jnlp',
image: '172.50.0.2:5000/openshift/jenkins-slave-zap',
resourceRequestCpu: '500m',
resourceLimitCpu: '1000m',
resourceRequestMemory: '3Gi',
resourceLimitMemory: '4Gi',
workingDir: '/home/jenkins',
command: '',
args: '${computer.jnlpmac} ${computer.name}'
)
])
{
stage('ZAP Security Scan') {
node(zapPodLabel) {
//the checkout is mandatory
echo "checking out source"
echo "Build: ${BUILD_ID}"
checkout scm
dir('zap') {
def retVal = sh returnStatus: true, script: './runzap.sh'
publishHTML([allowMissing: false, alwaysLinkToLastBuild: false, keepAll: true, reportDir: '/zap/wrk', reportFiles: 'index.html', reportName: 'ZAP Full Scan', reportTitles: 'ZAP Full Scan'])
echo "Return value is: ${retVal}"
}
}
}
}