-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJenkinsfile_PRs
413 lines (386 loc) · 19 KB
/
Jenkinsfile_PRs
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
import groovy.json.JsonOutput
def RELEASE_ID
def TEST_STATUS = 0
def prName
/*
pathmind-webapp pipeline
The pipeline is made up of following steps
1. Git clone and setup
2. Build and local tests
3. Publish Docker and Helm
4. Optionally deploy to production and test
*/
/*
Build a docker image
*/
def buildDockerImage(image_name) {
echo "Building the pathmind Docker Image"
sh "docker build -t base -f ${WORKSPACE}/Dockerfile-cache ${WORKSPACE}/"
sh "docker build -t ${image_name} -f ${WORKSPACE}/Dockerfile ${WORKSPACE}/"
}
/*
Build a docker image
*/
def createSecrets() {
sh """
set +x
kubectl create secret generic dburl --from-literal DB_URL='jdbc:postgresql://postgres/pathminddb?user=pathminddb&password=Asdf1234' -n ${env.BUILD_NUMBER}
kubectl create -f /tmp/secrets_pr.yaml -n ${env.BUILD_NUMBER}
"""
}
/*
run migrations
*/
def runMigrations() {
sh """
cd ${WORKSPACE}
mvn clean install
set +x
export DB_URL='jdbc:postgresql://postgres.${env.BUILD_NUMBER}/pathminddb?user=pathminddb&password=Asdf1234'
cd ${WORKSPACE}/pathmind-database && mvn liquibase:update
"""
}
/*
Publish a docker image
*/
def publishDockerImage(image_name, DOCKER_TAG) {
echo "Logging to aws ecr"
sh "aws ecr get-login --no-include-email --region us-east-1 | sh"
echo "Creating ECR ${image_name}"
sh "aws ecr create-repository --repository-name ${image_name}"
echo "Tagging and pushing the pathmind Docker Image"
sh "docker tag ${image_name} ${DOCKER_REG}/${image_name}:${DOCKER_TAG}"
sh "docker push ${DOCKER_REG}/${image_name}:${DOCKER_TAG}"
}
/*
Delete docker image
*/
def deleteDockerImage(image_name) {
echo "Logging to aws ecr"
sh "aws ecr get-login --no-include-email --region us-east-1 | sh"
echo "Deleting ECR ${image_name}"
sh "aws ecr delete-repository --repository-name ${image_name} --force"
}
/*
Send slack notification
*/
def notifySlack(text, channel, attachments) {
def slackURL = 'https://hooks.slack.com/services/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'
def jenkinsIcon = 'https://jenkins.io/images/logos/actor/actor.png'
def payload = JsonOutput.toJson([text : text,
channel : channel,
username : "Jenkins Test_PRs Build #${env.BUILD_NUMBER}",
icon_url : jenkinsIcon,
link_names : 1,
attachments: attachments
])
sh "curl -X POST --data-urlencode \'payload=${payload}\' ${slackURL}"
}
/*
Set the github status
*/
def setGitHubStatus(state) {
repoUrl = "https://api.github.com/repos/SkymindIO/pathmind-webapp"
token = sh(returnStdout: true, script: 'kubectl get secret githubtoken -o=jsonpath=\'{.data.GITHUBTOKEN}\' | base64 --decode')
isDraft = sh(returnStdout: true, script: "curl -H \"Authorization: token ${token}\" \"${repoUrl}/pulls/${ghprbPullId}\" | jq -r '.draft'").trim()
if (isDraft=="true"){
//Exit on draft PR
currentBuild.result = 'ABORTED'
error('Aborting a Draft PR')
}
commitSha = sh(returnStdout: true, script: "curl -H \"Authorization: token ${token}\" \"${repoUrl}/pulls/${ghprbPullId}/commits\" | grep '^ \"sha\"' | cut -f4 -d'\"' | tail -1").trim()
status="error"
if (state=="SUCCESS"){
status="success"
}
if (state=="PENDING"){
status="pending"
}
sh """
set -x
curl -H \"Authorization: token ${token}\" \"${repoUrl}/statuses/${commitSha}" \
-H \"Content-Type: application/json\" \
-X POST -d '{\"state\": \"${status}\", \"description\": \"BDD tests\", \"target_url\": \"${env.RUN_DISPLAY_URL}\", \"context\": \"Jenkins\" }'
"""
}
/*
Flaky tests
*/
def flakyTests() {
sh """
ls -1 ${WORKSPACE}/pathmind-bdd-tests/target/site/serenity/SERENITY-JUNIT*xml | xargs -I {} /usr/bin/xml2json.py -t xml2json {} -o {}.json
mkdir -p ${WORKSPACE}/pathmind-bdd-tests/target/site/serenity/out
/usr/bin/flaky.py --input ${WORKSPACE}/pathmind-bdd-tests/target/site/serenity/
cd ${WORKSPACE}/pathmind-bdd-tests/target/site/serenity/out
ls -1 SERENITY-JUNIT*xml.json | xargs -I {} /usr/bin/xml2json.py {} -t json2xml -o {}.xml
ls -1 SERENITY-JUNIT*xml.json.xml | xargs -I {} sh -c 'mv {} `echo {} | sed "s@.json.xml@@g"`'
"""
}
/*
Create PG dump
*/
def createPgDump() {
// Get db url ans pass
sh "echo ${env.ghprbTargetBranch}"
branch = "${env.ghprbTargetBranch}"
//Temporal until we peer production with dev
if (branch=="prod"){
branch="dev"
}
dbpass = sh(returnStdout: true, script: "kubectl get secret dburlcli -o=jsonpath='{.data.DB_URL_CLI}' -n \"${branch}\" | base64 --decode | rev | cut -f1 -d'=' | rev | tr -d '\n'")
dburl = sh(returnStdout: true, script: "kubectl get secret dburlcli -o=jsonpath='{.data.DB_URL_CLI}' -n \"${branch}\" | base64 --decode | sed 's@ *password=.*@@g' | sed 's@ @ --@g'")
sh """
set -x
export PGPASSWORD="${dbpass}"
/usr/lib/postgresql/11/bin/pg_dump -C -w --format=c --blobs --${dburl} > /tmp/${env.ghprbTargetBranch}_dump_${env.BUILD_NUMBER}.sql
"""
}
/*
Load PG dump
*/
def loadPgDump() {
// Get db url
dburl = "--host=postgres.${env.BUILD_NUMBER} --port=5432 --dbname=pathminddb --user=pathminddb"
sh """
set -x
PGPASSWORD='Asdf1234' /usr/lib/postgresql/11/bin/pg_restore ${dburl} < /tmp/${env.ghprbTargetBranch}_dump_${env.BUILD_NUMBER}.sql || echo 0
"""
}
/*
This is the main pipeline section with the stages of the CI/CD
*/
pipeline {
options {
// Build auto timeout
timeout(time: 1440, unit: 'MINUTES')
buildDiscarder(logRotator(daysToKeepStr: '15', artifactDaysToKeepStr: '15'))
}
// Some global default variables
environment {
IMAGE_NAME = 'pathmind'
DOCKER_REG = "839270835622.dkr.ecr.us-east-1.amazonaws.com"
HELM_FILE = "values_${env.ghprbTargetBranch}.yaml"
HELM_FILE_UPDATER = "values_${env.ghprbTargetBranch}-updater.yaml"
HELM_FILE_API = "values_${env.ghprbTargetBranch}-api.yaml"
DEPLOY_PROD = false
}
parameters {
string(name: 'GIT_BRANCH', defaultValue: 'test', description: 'Git branch to build')
booleanParam(name: 'DEPLOY_TO_PROD', defaultValue: false, description: 'If build and tests are good, proceed and deploy to production without manual approval')
}
//all is built and run from the master
agent {
node {
label 'master'
customWorkspace "${env.BUILD_NUMBER}"
}
}
// Pipeline stages
stages {
stage('Initialize') {
steps {
buildDescription "#${ghprbPullId} - ${env.ghprbPullTitle}"
}
}
stage('Git clone and setup') {
when {
allOf{
expression { env.GIT_BRANCH != 'prod' }
expression { env.GIT_BRANCH != 'dev' }
expression { env.GIT_BRANCH != 'test' }
}
}
steps {
setGitHubStatus("PENDING")
echo "Check out code"
checkout scm
script {
// Define a unique name for the tests container and helm release
RELEASE_ID = "${IMAGE_NAME}-${env.BUILD_NUMBER}"
RELEASE_ID_API = "${IMAGE_NAME}-api-${env.BUILD_NUMBER}"
echo "Global pathmind Id set to ${RELEASE_ID}"
echo "Merging with dev"
sh "cd ${WORKSPACE} && git merge origin/dev"
}
}
}
stage('Build Docker Images') {
when {
allOf{
expression { env.GIT_BRANCH != 'prod' }
expression { env.GIT_BRANCH != 'dev' }
expression { env.GIT_BRANCH != 'test' }
}
}
parallel {
stage('Build pathmind image') {
steps {
buildDockerImage("${RELEASE_ID}")
}
}
}
}
stage('Publish Docker Images') {
when {
allOf{
expression { env.GIT_BRANCH != 'prod' }
expression { env.GIT_BRANCH != 'dev' }
expression { env.GIT_BRANCH != 'test' }
}
}
parallel {
stage('Publish pathmind image') {
steps {
publishDockerImage("${RELEASE_ID}", "latest")
}
}
}
}
stage('Deploying helm chart') {
when {
allOf{
expression { env.GIT_BRANCH != 'prod' }
expression { env.GIT_BRANCH != 'dev' }
expression { env.GIT_BRANCH != 'test' }
}
}
steps {
script {
echo "Creating name space ${env.BUILD_NUMBER}"
sh "kubectl create namespace ${env.BUILD_NUMBER}"
echo "Creating selenium hub"
sh "helm install selenium-hub ${WORKSPACE}/infra/helm/selenium-hub -n ${env.BUILD_NUMBER} --set namespace=${env.BUILD_NUMBER}"
sh "helm install selenium-node ${WORKSPACE}/infra/helm/selenium-node -n ${env.BUILD_NUMBER}"
echo "Installing postgresql postgres-${env.BUILD_NUMBER}"
sh "helm upgrade --install postgres ${WORKSPACE}/infra/helm/postgres --set namespace=${env.BUILD_NUMBER} -n ${env.BUILD_NUMBER}"
echo "Waiting for psql to come up"
sh "timeout 900 bash -c 'while ! pg_isready -h postgres-${env.BUILD_NUMBER} -q; do sleep 5; done'"
}
//Create a dump from ${env.ghprbTargetBranch}
createPgDump()
//Load Dev Dump
loadPgDump()
createSecrets()
script {
echo "Creating updater resources"
sh "aws sqs create-queue --queue-name ${env.BUILD_ID}-updater-queue --attributes \"{\\\"MessageRetentionPeriod\\\":\\\"60\\\"}\""
sh "cat /tmp/sqs_policy.json | sed \"s/BUILD_ID/${env.BUILD_NUMBER}/g\" > /tmp/${env.BUILD_NUMBER}-sqs_policy.json"
sh "aws sqs set-queue-attributes --queue-url https://sqs.us-east-1.amazonaws.com/839270835622/${env.BUILD_NUMBER}-updater-queue --attributes file:///tmp/${env.BUILD_NUMBER}-sqs_policy.json"
sh "rm /tmp/${env.BUILD_NUMBER}-sqs_policy.json"
sh "aws sns subscribe --topic-arn arn:aws:sns:us-east-1:839270835622:${env.ghprbTargetBranch}-updater-topic --protocol sqs --notification-endpoint arn:aws:sqs:us-east-1:839270835622:${env.BUILD_ID}-updater-queue --attributes \"{\\\"RawMessageDelivery\\\":\\\"true\\\"}\""
echo "Creating S3 bucket for tests"
sh "aws s3api create-bucket --bucket ${env.BUILD_ID}-training-dynamic-files.pathmind.com --region us-east-1"
echo "Running db migrations"
}
runMigrations()
script {
echo "Installing ${RELEASE_ID}"
sh "helm upgrade --install ${RELEASE_ID} ${WORKSPACE}/infra/helm/pathmind -f ${WORKSPACE}/infra/helm/pathmind/${HELM_FILE} --set image.repository=${DOCKER_REG}/${RELEASE_ID} --set image.tag=latest --set env.APPLICATION_URL=http://${RELEASE_ID} --set namespace=${env.BUILD_NUMBER} --set env.JOB_MOCK_CYCLE=3 --set env.JOB_MOCK_MAX_MIN=5 --set env.SQS_UPDATER_URL=https://sqs.us-east-1.amazonaws.com/839270835622/${env.BUILD_ID}-updater-queue --set env.S3_BUCKET=${env.BUILD_ID}-training-dynamic-files.pathmind.com --set env.SNS_UPDATER_SQS_FILTER_ATTR=${env.BUILD_NUMBER}prtest --set env.PATHMIND_API_URL=http://${RELEASE_ID}-api:8081 -n ${env.BUILD_NUMBER}"
echo "Waiting for webapp to come up"
sh "timeout 300 bash -c 'while ! curl http://${RELEASE_ID}; do sleep 5; done'"
echo "Installing updater ${RELEASE_ID}"
sh "helm upgrade --install ${RELEASE_ID}-updater ${WORKSPACE}/infra/helm/pathmind -f ${WORKSPACE}/infra/helm/pathmind/${HELM_FILE_UPDATER} --set image.repository=${DOCKER_REG}/${RELEASE_ID} --set image.tag=latest --set env.APPLICATION_URL=http://${RELEASE_ID} --set namespace=${env.BUILD_NUMBER} --set env.JOB_MOCK_CYCLE=3 --set env.JOB_MOCK_MAX_MIN=5 --set env.SQS_UPDATER_URL=https://sqs.us-east-1.amazonaws.com/839270835622/${env.BUILD_ID}-updater-queue --set env.S3_BUCKET=${env.BUILD_ID}-training-dynamic-files.pathmind.com --set env.SNS_UPDATER_SQS_FILTER_ATTR=${env.BUILD_NUMBER}prtest -n ${env.BUILD_NUMBER}"
echo "Installing api ${RELEASE_ID}"
sh "helm upgrade --install ${RELEASE_ID}-api ${WORKSPACE}/infra/helm/pathmind-api -f ${WORKSPACE}/infra/helm/pathmind-api/${HELM_FILE_API} --set image.repository=${DOCKER_REG}/${RELEASE_ID} --set image.tag=latest --set namespace=${env.BUILD_NUMBER} -n ${env.BUILD_NUMBER}"
sh "sleep 30"
}
}
}
stage('Testing') {
when {
allOf{
expression { env.GIT_BRANCH != 'prod' }
expression { env.GIT_BRANCH != 'dev' }
expression { env.GIT_BRANCH != 'test' }
}
}
steps {
script {
try {
echo "Running smoke tests"
TEST_STATUS = sh(returnStatus: true, script: "mvn clean verify -Dheadless=true -Denvironments.default.base.url=http://pathmind/ -Dpostgresql.host=postgres -Dpostgresql.port=5432 -Dpostgresql.db=pathminddb -Dpostgresql.username=pathminddb -Dpostgresql.password=Asdf1234 -Dhttp.keepAlive=false -Dwebdriver.driver=remote -Dwebdriver.remote.url=http://selenium-hub-${env.BUILD_NUMBER}:4444/wd/hub -Dwebdriver.remote.driver=chrome -DforkNumber=6 -Dfailsafe.rerunFailingTestsCount=3 -Dapi.url=http://pathmind-api-${env.BUILD_NUMBER}:8081/ -Dpathmind.pathmind-api.url=http://pathmind-api-${env.BUILD_NUMBER}:8081/ -Dpathmind.api.key=`kubectl get secret apipassword -o=jsonpath='{.data.APIPASSWORD}' -n ${env.ghprbTargetBranch} | base64 --decode` -Dtags=smoke -f pom.xml -P bdd-tests")
publishHTML(target: [
reportDir: 'pathmind-bdd-tests/target/site/serenity',
reportFiles: 'index.html',
reportName: "SmokeTests",
keepAll: true,
alwaysLinkToLastBuild: true,
allowMissing: false
])
flakyTests()
junit 'pathmind-bdd-tests/target/site/serenity/out/SERENITY-JUNIT*xml'
if ( TEST_STATUS == 0 && "${env.ghprbPullTitle}".contains("HOTFIX") != true ) {
sh "rm -rf pathmind-bdd-tests/target/"
echo "Running full tests"
TEST_STATUS = sh(returnStatus: true, script: "mvn clean verify -Dheadless=true -Denvironments.default.base.url=http://pathmind/ -Dpostgresql.host=postgres -Dpostgresql.port=5432 -Dpostgresql.db=pathminddb -Dpostgresql.username=pathminddb -Dpostgresql.password=Asdf1234 -Dhttp.keepAlive=false -Dwebdriver.driver=remote -Dwebdriver.remote.url=http://selenium-hub-${env.BUILD_NUMBER}:4444/wd/hub -Dwebdriver.remote.driver=chrome -DforkNumber=6 -Dfailsafe.rerunFailingTestsCount=3 -Dapi.url=http://pathmind-api-${env.BUILD_NUMBER}:8081/ -Dpathmind.pathmind-api.url=http://pathmind-api-${env.BUILD_NUMBER}:8081/ -Dpathmind.api.key=`kubectl get secret apipassword -o=jsonpath='{.data.APIPASSWORD}' -n ${env.ghprbTargetBranch} | base64 --decode` -f pom.xml -P bdd-tests")
publishHTML(target: [
reportDir: 'pathmind-bdd-tests/target/site/serenity',
reportFiles: 'index.html',
reportName: "FullTests",
keepAll: true,
alwaysLinkToLastBuild: true,
allowMissing: false
])
flakyTests()
junit 'pathmind-bdd-tests/target/site/serenity/out/SERENITY-JUNIT*xml'
}
} catch (err) {
}
}
}
}
stage('Set pipeline status') {
when {
allOf{
expression { env.GIT_BRANCH != 'prod' }
expression { env.GIT_BRANCH != 'dev' }
expression { env.GIT_BRANCH != 'test' }
}
}
steps {
script {
if (TEST_STATUS != 0) {
echo "Some bdd tests failed ${TEST_STATUS}"
currentBuild.result = 'UNSTABLE'
prName="${env.ghprbPullTitle}".replaceAll('\'', '').replaceAll('"', '')
}
}
}
}
}
post {
always {
echo "Deleting image"
deleteDockerImage("${RELEASE_ID}")
echo "Deleting name space ${env.BUILD_NUMBER}"
sh "helm delete postgres -n ${env.BUILD_NUMBER} || true"
sh "helm delete ${RELEASE_ID} -n ${env.BUILD_NUMBER} || true"
sh "helm delete ${RELEASE_ID}-updater -n ${env.BUILD_NUMBER} || true"
sh "helm delete ${RELEASE_ID}-api -n ${env.BUILD_NUMBER} || true"
sh "helm delete selenium-hub -n ${env.BUILD_NUMBER} || true"
sh "helm delete selenium-node -n ${env.BUILD_NUMBER} || true"
sh "kubectl delete namespace ${env.BUILD_NUMBER} || true"
sh "aws sqs delete-queue --queue-url https://sqs.us-east-1.amazonaws.com/839270835622/${env.BUILD_NUMBER}-updater-queue || true"
sh "aws sns unsubscribe --subscription-arn `aws sns list-subscriptions | jq -r \".[] | .[] | select(.Endpoint ==\\\"arn:aws:sqs:us-east-1:839270835622:${env.BUILD_ID}-updater-queue\\\").SubscriptionArn\"` || true"
sh "/usr/bin/clean_test_s3.sh ${env.BUILD_NUMBER} || true"
setGitHubStatus(currentBuild.result)
}
unstable {
echo 'Send slack notification if build unstable'
script {
notifySlack("", "#tests", [[
title : "Test_PRs » Build #${env.BUILD_NUMBER} - Failed",
title_link : "${env.BUILD_URL}",
color : "#CF0000",
"mrkdwn_in": ["fields"],
fields : [
[
value: "<${env.BUILD_URL}Tests|Tests report>\nPull request <${env.ghprbPullLink}|${prName}>",
short: false
]
]
],])
}
}
}
}