forked from bcgov/gwells
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Jenkinsfile.ocp4
1445 lines (1290 loc) · 66.4 KB
/
Jenkinsfile.ocp4
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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!groovy
import groovy.json.JsonOutput
import bcgov.GitHubHelper
// Notify stage status and pass to Jenkins-GitHub library
void notifyStageStatus (String name, String status) {
GitHubHelper.createCommitStatus(
this,
GitHubHelper.getPullRequestLastCommitId(this),
status,
"${env.BUILD_URL}",
"Stage '${name}'",
"Stage: ${name}"
)
}
// Create deployment status and pass to Jenkins-GitHub library
void createDeploymentStatus (String suffix, String status, String stageUrl) {
def ghDeploymentId = new GitHubHelper().createDeployment(
this,
"pull/${env.CHANGE_ID}/head",
[
'environment':"${suffix}",
'task':"deploy:pull:${env.CHANGE_ID}"
]
)
// NOTE: this function in GitHubHelper no longer works.
// https://github.com/BCDevOps/jenkins-pipeline-shared-lib/issues/6
// TODO: convert to use GitHub REST API
// https://docs.github.com/en/rest/reference/repos#deployments
new GitHubHelper().createDeploymentStatus(
this,
ghDeploymentId,
"${status}",
['targetUrl':"https://${stageUrl}/gwells"]
)
if ('SUCCESS'.equalsIgnoreCase("${status}")) {
echo "${suffix} deployment successful!"
} else if ('PENDING'.equalsIgnoreCase("${status}")){
echo "${suffix} deployment pending."
}
}
// Print stack trace of error
@NonCPS
private static String stackTraceAsString(Throwable t) {
StringWriter sw = new StringWriter();
t.printStackTrace(new PrintWriter(sw));
return sw.toString()
}
// OpenShift wrapper
def _openshift(String name, String project, Closure body) {
script {
openshift.withCluster() {
openshift.withProject(project) {
echo "Running Stage '${name}'"
waitUntil {
notifyStageStatus (name, 'PENDING')
boolean isDone=false
try {
body()
isDone=true
notifyStageStatus(name, 'SUCCESS')
echo "Completed Stage '${name}'"
} catch (error){
notifyStageStatus(name, 'FAILURE')
echo "${stackTraceAsString(error)}"
def inputAction = input(
message: "This step (${name}) has failed. See related messages.",
ok: 'Confirm',
parameters: [
choice(
name: 'action',
choices: 'Re-run\nIgnore',
description: 'What would you like to do?'
)
]
)
if ('Ignore'.equalsIgnoreCase(inputAction)){
isDone=true
}
}
return isDone
}
}
}
}
}
// Functional test script
// Can be limited by assinging toTest var
def unitTestDjango (String stageName, String envProject, String envSuffix) {
_openshift(env.STAGE_NAME, envProject) {
def DB_target = envSuffix == "staging" ? "${appName}-pg12-${envSuffix}" : "${appName}-pg12-${envSuffix}-${prNumber}"
def DB_newVersion = openshift.selector("dc", "${DB_target}").object().status.latestVersion
def DB_pod = openshift.selector('pod', [deployment: "${DB_target}-${DB_newVersion}"])
echo "Temporarily granting elevated DB rights"
echo DB_target
sh "oc rsh -n ${envProject} dc/${DB_target} bash -c ' \
psql -c \"ALTER USER \\\"\${PG_USER}\\\" WITH SUPERUSER;\" \
'"
def target = envSuffix == "staging" ? "${appName}-${envSuffix}" : "${appName}-${envSuffix}-${prNumber}"
def newVersion = openshift.selector("dc", "${target}").object().status.latestVersion
def pods = openshift.selector('pod', [deployment: "${target}-${newVersion}"])
// Wait here and make sure the app pods are ready before running unit tests.
// We wait for both pods to be ready so that we can execute the test command
// on either one, without having to check which one was ready first.
timeout(15) {
pods.untilEach(2) {
return it.object().status.containerStatuses.every {
it.ready
}
}
}
echo "Running Django unit tests"
def ocoutput = openshift.exec(
pods.objects()[0].metadata.name,
"--",
"bash -c '\
cd \${APP_SOURCE_DIR:-\"\${APP_ROOT}/src\"}/backend; \
python manage.py test --noinput \
'"
)
echo "Django test results: "+ ocoutput.actions[0].out
echo "Revoking ADMIN rights"
sh "oc rsh -n ${envProject} dc/${DB_target} bash -c ' \
psql -c \"ALTER USER \\\"\${PG_USER}\\\" WITH NOSUPERUSER;\" \
'"
}
}
// API test function
def apiTest (String stageName, String stageUrl, String envSuffix) {
_openshift(env.STAGE_NAME, toolsProject) {
podTemplate(
label: "nodejs-${appName}-${envSuffix}-${prNumber}",
name: "nodejs-${appName}-${envSuffix}-${prNumber}",
serviceAccount: 'jenkins',
cloud: 'openshift',
activeDeadlineSeconds: 1800,
containers: [
containerTemplate(
name: 'jnlp',
image: 'registry.access.redhat.com/openshift3/jenkins-agent-nodejs-8-rhel7',
resourceRequestCpu: '500m',
resourceLimitCpu: '800m',
resourceRequestMemory: '512Mi',
resourceLimitMemory: '1Gi',
activeDeadlineSeconds: '600',
podRetention: 'never',
workingDir: '/tmp',
command: '',
args: '${computer.jnlpmac} ${computer.name}',
envVars: [
envVar(
key:'BASE_URL',
value: "https://${stageUrl}/gwells"
),
secretEnvVar(
key: 'GWELLS_API_TEST_USER',
secretName: 'apitest-secrets',
secretKey: 'username'
),
secretEnvVar(
key: 'GWELLS_API_TEST_PASSWORD',
secretName: 'apitest-secrets',
secretKey: 'password'
),
secretEnvVar(
key: 'GWELLS_API_TEST_AUTH_SERVER',
secretName: 'apitest-secrets',
secretKey: 'auth_server'
),
secretEnvVar(
key: 'GWELLS_API_TEST_CLIENT_ID',
secretName: 'apitest-secrets',
secretKey: 'client_id'
),
secretEnvVar(
key: 'GWELLS_API_TEST_CLIENT_SECRET',
secretName: 'apitest-secrets',
secretKey: 'client_secret'
)
]
)
]
) {
node("nodejs-${appName}-${envSuffix}-${prNumber}") {
checkout scm
dir('tests/api-tests') {
sh 'npm install -g [email protected]'
try {
sh """
newman run ./registries_api_tests.json \
--color on \
--disable-unicode \
--global-var test_user=\$GWELLS_API_TEST_USER \
--global-var test_password=\$GWELLS_API_TEST_PASSWORD \
--global-var base_url=\$BASE_URL \
--global-var auth_server=\$GWELLS_API_TEST_AUTH_SERVER \
--global-var client_id=\$GWELLS_API_TEST_CLIENT_ID \
--global-var client_secret=\$GWELLS_API_TEST_CLIENT_SECRET \
-r cli,junit,html
newman run ./registries_v2_api_tests.json \
--global-var test_user=\$GWELLS_API_TEST_USER \
--global-var test_password=\$GWELLS_API_TEST_PASSWORD \
--global-var base_url=\$BASE_URL \
--global-var auth_server=\$GWELLS_API_TEST_AUTH_SERVER \
--global-var client_id=\$GWELLS_API_TEST_CLIENT_ID \
--global-var client_secret=\$GWELLS_API_TEST_CLIENT_SECRET \
-r cli,junit,html
newman run ./wells_api_tests.json \
--global-var test_user=\$GWELLS_API_TEST_USER \
--global-var test_password=\$GWELLS_API_TEST_PASSWORD \
--global-var base_url=\$BASE_URL \
--global-var auth_server=\$GWELLS_API_TEST_AUTH_SERVER \
--global-var client_id=\$GWELLS_API_TEST_CLIENT_ID \
--global-var client_secret=\$GWELLS_API_TEST_CLIENT_SECRET \
-r cli,junit,html
newman run ./wells_v2_api_tests.json \
--global-var test_user=\$GWELLS_API_TEST_USER \
--global-var test_password=\$GWELLS_API_TEST_PASSWORD \
--global-var base_url=\$BASE_URL \
--global-var auth_server=\$GWELLS_API_TEST_AUTH_SERVER \
--global-var client_id=\$GWELLS_API_TEST_CLIENT_ID \
--global-var client_secret=\$GWELLS_API_TEST_CLIENT_SECRET \
-r cli,junit,html
newman run ./submissions_api_tests.json \
--global-var test_user=\$GWELLS_API_TEST_USER \
--global-var test_password=\$GWELLS_API_TEST_PASSWORD \
--global-var base_url=\$BASE_URL \
--global-var auth_server=\$GWELLS_API_TEST_AUTH_SERVER \
--global-var client_id=\$GWELLS_API_TEST_CLIENT_ID \
--global-var client_secret=\$GWELLS_API_TEST_CLIENT_SECRET \
-r cli,junit,html
newman run ./submissions_v2_api_tests.json \
--global-var test_user=\$GWELLS_API_TEST_USER \
--global-var test_password=\$GWELLS_API_TEST_PASSWORD \
--global-var base_url=\$BASE_URL \
--global-var auth_server=\$GWELLS_API_TEST_AUTH_SERVER \
--global-var client_id=\$GWELLS_API_TEST_CLIENT_ID \
--global-var client_secret=\$GWELLS_API_TEST_CLIENT_SECRET \
-r cli,junit,html
newman run ./aquifers_api_tests.json \
--global-var test_user=\$GWELLS_API_TEST_USER \
--global-var test_password=\$GWELLS_API_TEST_PASSWORD \
--global-var base_url=\$BASE_URL \
--global-var auth_server=\$GWELLS_API_TEST_AUTH_SERVER \
--global-var client_id=\$GWELLS_API_TEST_CLIENT_ID \
--global-var client_secret=\$GWELLS_API_TEST_CLIENT_SECRET \
-r cli,junit,html
newman run ./aquifers_v2_api_tests.json \
--global-var test_user=\$GWELLS_API_TEST_USER \
--global-var test_password=\$GWELLS_API_TEST_PASSWORD \
--global-var base_url=\$BASE_URL \
--global-var auth_server=\$GWELLS_API_TEST_AUTH_SERVER \
--global-var client_id=\$GWELLS_API_TEST_CLIENT_ID \
--global-var client_secret=\$GWELLS_API_TEST_CLIENT_SECRET \
-r cli,junit,html
"""
if ("dev".equalsIgnoreCase("${envSuffix}")) {
sh """
newman run ./wells_search_api_tests.json \
--global-var base_url=\$BASE_URL \
-r cli,junit,html
"""
}
} finally {
junit 'newman/*.xml'
publishHTML (
target: [
allowMissing: false,
alwaysLinkToLastBuild: false,
keepAll: true,
reportDir: 'newman',
reportFiles: 'newman*.html',
reportName: "API Test Report"
]
)
stash includes: 'newman/*.xml', name: 'api-tests'
}
}
}
}
}
return true
}
def deployToDev() {
// Process postgres deployment config (sub in vars, create list items)
echo "Processing database deployment (using folder ${templateDir}"
def deployDBTemplate = openshift.process("-f",
"${templateDir}/postgresql.dc.yml",
"DATABASE_SERVICE_NAME=gwells-pg12-${devSuffix}-${prNumber}",
"IMAGE_STREAM_NAMESPACE=${devProject}",
"IMAGE_STREAM_NAME=crunchy-postgres-gis",
"NAME_SUFFIX=-${devSuffix}-${prNumber}",
"POSTGRESQL_DATABASE=gwells",
"VOLUME_CAPACITY=1Gi",
"STORAGE_CLASS=netapp-file-standard",
"REQUEST_CPU=200m",
"REQUEST_MEMORY=512Mi",
"LIMIT_CPU=500m",
"LIMIT_MEMORY=1Gi"
)
// Process postgres deployment config (sub in vars, create list items)
echo "Processing deployment config for pull request ${prNumber}"
def deployTemplate = openshift.process("-f",
"${templateDir}/backend.dc.json",
"ENV_NAME=${devSuffix}",
"HOST=${devHost}",
"NAME_SUFFIX=-${devSuffix}-${prNumber}"
)
echo "Processing deployment config for tile server"
def pgtileservTemplate = openshift.process("-f",
"${templateDir}/pg_tileserv/pg_tileserv.dc.yaml",
"NAME_SUFFIX=-${devSuffix}-${prNumber}",
"DATABASE_SERVICE_NAME=gwells-pg12-${devSuffix}-${prNumber}",
"HOST=${devHost}",
)
echo "Processing Minio deployment config"
def minioTemplate = openshift.process("-f",
"${templateDir}/minio/minio.dc.yaml",
"NAME_SUFFIX=-${devSuffix}-${prNumber}",
"HOSTNAME=gwells-docs-${devSuffix}-${prNumber}.apps.silver.devops.gov.bc.ca",
"SRC_TAG=dev"
)
// some objects need to be copied from a base secret or configmap
// these objects have an annotation "as-copy-of" in their object spec (e.g. an object in backend.dc.json)
echo "Creating configmaps and secrets objects"
List newObjectCopies = []
for (o in (deployTemplate + deployDBTemplate)) {
// only perform this operation on objects with 'as-copy-of'
def sourceName = o.metadata && o.metadata.annotations && o.metadata.annotations['as-copy-of']
if (sourceName && sourceName.length() > 0) {
def selector = openshift.selector("${o.kind}/${sourceName}")
if (selector.count() == 1) {
// create a copy of the object and add it to the new list of objects to be applied
Map copiedModel = selector.object()
copiedModel.metadata.name = o.metadata.name
copiedModel.metadata.remove('annotations')
copiedModel.metadata.remove('creationTimestamp')
copiedModel.metadata.remove('resourceVersion')
copiedModel.metadata.remove('selfLink')
copiedModel.metadata.remove('uid')
// set Minio host for dev environments
if (sourceName == 'gwells-global-config') {
copiedModel.data['S3_PRIVATE_HOST'] = "gwells-docs-${devSuffix}-${prNumber}.apps.silver.devops.gov.bc.ca"
}
if (sourceName == 'gwells-minio-secrets') {
copiedModel.data.remove('S3_HOST')
copiedModel.stringData = [:]
copiedModel.stringData['S3_HOST'] = "gwells-docs-${devSuffix}-${prNumber}.apps.silver.devops.gov.bc.ca"
}
echo "[as-copy-of] Copying ${o.kind} ${o.metadata.name}"
newObjectCopies.add(copiedModel)
}
}
}
echo "Applying deployment configs for pull request ${prNumber} on ${devProject}"
// apply the templates, which will create new objects or modify existing ones as necessary.
// the copies of base objects (secrets, configmaps) are also applied.
openshift.apply(pgtileservTemplate).label(['app':"${devAppName}", 'app-name':"${appName}", 'env-name':"${devSuffix}"], "--overwrite")
openshift.apply(minioTemplate).label(['app':"${devAppName}", 'app-name':"${appName}", 'env-name':"${devSuffix}"], "--overwrite")
openshift.apply(deployTemplate).label(['app':"${devAppName}", 'app-name':"${appName}", 'env-name':"${devSuffix}"], "--overwrite")
openshift.apply(deployDBTemplate).label(['app':"${devAppName}", 'app-name':"${appName}", 'env-name':"${devSuffix}"], "--overwrite")
openshift.apply(newObjectCopies).label(['app':"${devAppName}", 'app-name':"${appName}", 'env-name':"${devSuffix}"], "--overwrite")
echo "Successfully applied deployment configs for ${prNumber}"
// promote the newly built image to DEV
echo "Tagging new image to DEV imagestream."
openshift.tag("${toolsProject}/gwells-application:${prNumber}", "${devProject}/${devAppName}:dev") // todo: clean up labels/tags
// post a notification to Github that this pull request is being deployed
createDeploymentStatus(devSuffix, 'PENDING', devHost)
// monitor the deployment status and wait until deployment is successful
echo "Waiting for deployment to dev..."
// wait until each container in this deployment's pod reports as ready
timeout(15) {
openshift.selector("dc", "${devAppName}").rollout().status()
openshift.selector("dc", "pgtileserv-${devSuffix}-${prNumber}").rollout().status()
}
// Report a pass to GitHub
createDeploymentStatus(devSuffix, 'SUCCESS', devHost)
}
def loadFixtures(String appName) {
// wait for deployment config to finish rolling out
openshift.selector("dc", "${appName}").rollout().status()
def pods = openshift.selector("dc", "${appName}").related("pods")
def podName = pods.objects()[0].metadata.name
echo "Loading fixtures using pod/${podName}"
// the dc rollout status above should be enough!
def waitStatus = openshift.raw('wait', '--for=condition=Ready', "pod/${podName}", '--timeout=300s')
echo "Wait for pod/${podName}: ${waitStatus.out}"
def ocoutput = openshift.exec(
podName,
"--",
"bash -c '\
cd \${APP_SOURCE_DIR:-\"\${APP_ROOT}/src\"}/backend; \
./load_fixtures.sh all \
'"
)
echo "Load Fixtures results: "+ ocoutput.actions[0].out
openshift.exec(
podName,
"--",
"bash -c '\
cd \${APP_SOURCE_DIR:-\"\${APP_ROOT}/src\"}/backend; \
python manage.py createinitialrevisions \
'"
)
}
def zapTests (String stageName, String envUrl, String envSuffix) {
_openshift(env.STAGE_NAME, toolsProject) {
def podName = envSuffix == "dev" ? "zap-${envSuffix}-${prNumber}" : "zap-${envSuffix}"
podTemplate(
label: "${podName}",
name: "${podName}",
serviceAccount: "jenkins",
cloud: "openshift",
containers: [
containerTemplate(
name: 'jnlp',
image: 'docker-registry.default.svc:5000/openshift/jenkins-slave-zap',
resourceRequestCpu: '1',
resourceLimitCpu: '1',
resourceRequestMemory: '2Gi',
resourceLimitMemory: '2Gi',
activeDeadlineSeconds: '600',
workingDir: '/home/jenkins',
command: '',
args: '${computer.jnlpmac} ${computer.name}',
envVars: [
envVar(
key:'BASE_URL',
value: "https://${envUrl}/gwells"
)
]
)
]
) {
node("${podName}") {
checkout scm
sh (
script: "/zap/zap-baseline.py -r index.html -t $BASE_URL",
returnStatus: true
)
publishHTML(
target: [
allowMissing: false,
alwaysLinkToLastBuild: false,
keepAll: true,
reportDir: '/zap/wrk',
reportFiles: 'index.html',
reportName: 'ZAP Baseline Scan',
reportTitles: 'ZAP Baseline Scan'
]
)
}
}
}
return true
}
// Database backup
def dbBackup (String envProject, String envSuffix) {
def dcName = envSuffix == "dev" ? "${appName}-pg12-${envSuffix}-${prNumber}" : "${appName}-pg12-${envSuffix}"
def dumpDir = "/pgdata/deployment-backups"
def dumpName = "${envSuffix}-\$( date +%Y-%m-%d-%H%M ).dump"
def dumpOpts = "--no-privileges --no-tablespaces --schema=public --exclude-table=spatial_ref_sys"
def dumpTemp = "/tmp/unverified.dump"
int maxBackups = 10
// Dump to temporary file
sh "oc rsh -n ${envProject} dc/${dcName} bash -c ' \
pg_dump -U \${PG_USER} -d \${PG_DATABASE} -Fc -f ${dumpTemp} ${dumpOpts} \
'"
// Verify dump size is at least 1M
int sizeAtLeast1M = sh (
script: "oc rsh -n ${envProject} dc/${dcName} bash -c ' \
du --threshold=1M ${dumpTemp} | wc -l \
'",
returnStdout: true
)
assert sizeAtLeast1M == 1
// Store verified dump
sh "oc rsh -n ${envProject} dc/${dcName} bash -c ' \
mkdir -p ${dumpDir}; \
mv ${dumpTemp} ${dumpDir}/${dumpName}; \
ls -lh ${dumpDir} \
'"
// Database purge
sh "oc rsh -n ${envProject} dc/${dcName} bash -c \" \
find ${dumpDir} -name *.dump -printf '%Ts\t%p\n' \
| sort -nr | cut -f2 | tail -n +${maxBackups} | xargs rm 2>/dev/null \
|| echo 'No extra backups to remove' \
\""
}
pipeline {
triggers {
cron(env.BRANCH_NAME == 'PR-1800' ? '0 7 * * 1-5' : '')
}
options {
timestamps()
ansiColor('xterm')
}
environment {
// Project-wide settings - app name, repo
appName = "gwells"
repository = 'https://www.github.com/bcgov/gwells.git'
platformEnv = "4"
platformDomain = "${platformEnv == '4' ? 'apps.silver.devops.gov.bc.ca' : 'pathfinder.gov.bc.ca'}"
// prNumber is the pull request number e.g. 'pr-4'
prNumber = "${env.JOB_BASE_NAME}".toLowerCase()
// toolsProject is where images are built
toolsProject = "${APP_TOOLS_NAMESPACE ?: "26e83e-tools"}"
// devProject is the project where individual development environments are spun up
devProject = "${APP_DEV_NAMESPACE ?: "26e83e-dev"}"
devSuffix = "dev"
devAppName = "${appName}-${devSuffix}-${prNumber}"
devHost = "${devAppName}.${platformDomain}"
// stagingProject contains the test deployment. The test image is a candidate for promotion to prod.
stagingProject = "${APP_STAGING_NAMESPACE ?: "26e83e-test"}"
stagingSuffix = "staging"
stagingHost = "gwells-staging.${platformDomain}"
// prodProject is the prod deployment.
// TODO: New production images can be deployed by tagging an existing "test" image as "prod".
prodProject = "${APP_PROD_NAMESPACE ?: "26e83e-prod"}"
prodSuffix = "production"
prodSubdomain = "${platformEnv == '4' ? 'gwells' : 'gwells-prod'}"
prodHost = "${prodSubdomain}.${platformDomain}"
// name of the provisioned PVC claim for NFS backup storage
// this will not be created during the pipeline; it must be created
// before running the production pipeline.
nfsProdBackupPVC = "gwells-backups"
nfsStagingBackupPVC = "gwells-backups"
// name of the PVC where documents are stored (e.g. Minio PVC)
// this should be the same across all environments.
minioDataPVC = "minio-data-vol"
templateDir = "${platformEnv == '4' ? 'openshift/ocp4' : 'openshift' }"
}
agent none
stages {
// the Start Pipeline stage will process and apply OpenShift build templates which will create
// buildconfigs and an imagestream for built images.
// each pull request gets its own buildconfig but all new builds are pushed to a single imagestream,
// to be tagged with the pull request number.
// e.g.: gwells-app:pr-999
stage('ALL - Prepare Templates') {
agent { label 'build' }
steps {
script {
echo "Starting deployment to OCP platform: ${platformEnv}"
echo "Cancelling previous builds..."
timeout(10) {
abortAllPreviousBuildInProgress(currentBuild)
}
echo "Previous builds cancelled"
echo "Processing/applying template: ${templateDir}/backend.bc.json"
_openshift(env.STAGE_NAME, toolsProject) {
// - variable substitution
def buildtemplate = openshift.process("-f",
"${templateDir}/backend.bc.json",
"ENV_NAME=${devSuffix}",
"NAME_SUFFIX=-${devSuffix}-${prNumber}",
"APP_IMAGE_TAG=${prNumber}",
"SOURCE_REPOSITORY_URL=${repository}",
"SOURCE_REPOSITORY_REF=pull/${CHANGE_ID}/head"
)
// Apply oc list objects
// - add docker image reference as tag in gwells-application
// - create build config
echo "Preparing backend imagestream and buildconfig"
openshift.apply(buildtemplate)
}
}
}
}
// the Build stage builds files; an image will be outputted to the app's imagestream,
// using the source-to-image (s2i) strategy. See /app/.s2i/assemble for image build script
stage('ALL - Build') {
agent { label 'build' }
steps {
script {
_openshift(env.STAGE_NAME, toolsProject) {
echo "Running unit tests and building images..."
echo "This may take several minutes. Logs are not forwarded to Jenkins by default (at this time)."
echo "Additional logs can be found by monitoring bc/${devAppName} in ${toolsProject}"
// Select appropriate buildconfig
def appBuild = openshift.selector("bc", "${devAppName}")
echo "Canceling all existing/running builds"
appBuild.cancelBuild()
echo "Starting a new build"
def newBuildSelector = appBuild.startBuild()
echo "Build Started: ${newBuildSelector.names()}"
newBuildSelector.logs("-f")
echo "Build Ended: ${newBuildSelector.names()}"
def buildStatus = ""
timeout(1) {
waitUntil {
buildStatus = newBuildSelector.object().status.phase
echo "Build Status: ${buildStatus}"
return buildStatus != "Running"
}
}
if (newBuildSelector.object().status.phase != "Complete") {
error("Build ${newBuildSelector.names()} has failed!")
}
}
}
}
}
// the Deploy to Dev stage creates a new dev environment for the pull request (if necessary), tagging
// the newly built application image into that environment. This stage monitors the newest deployment
// for pods/containers to report back as ready.
stage('DEV - Deploy') {
agent { label 'deploy' }
when {
beforeAgent true
expression { env.CHANGE_TARGET != 'master' }
}
steps {
script {
_openshift(env.STAGE_NAME, devProject) {
deployToDev()
}
}
}
}
// the Django Unit Tests stage runs backend unit tests using a test DB that is
// created and destroyed afterwards.
stage('DEV - Django Unit Tests') {
agent { label 'test' }
when {
beforeAgent true
expression { env.CHANGE_TARGET != 'master' }
}
steps {
script {
def result = unitTestDjango (env.STAGE_NAME, devProject, devSuffix)
}
}
}
stage('DEV - Load Fixtures') {
agent { label 'test' }
when {
beforeAgent true
expression { env.CHANGE_TARGET != 'master' }
}
steps {
script {
_openshift(env.STAGE_NAME, devProject) {
loadFixtures(devAppName)
}
}
}
}
stage('DEV - API Tests') {
agent { label 'test' }
when {
beforeAgent true
expression { env.CHANGE_TARGET != 'master' }
}
steps {
script {
def result = apiTest ('DEV - API Tests', devHost, devSuffix)
}
}
}
stage('STAGING - Backup') {
agent { label 'deploy' }
when {
beforeAgent true
expression { env.CHANGE_TARGET == 'master' }
}
steps {
script {
echo "backing up staging environment before deploying"
dbBackup (stagingProject, stagingSuffix)
}
}
}
// the Promote to Test stage allows approving the tagging of the newly built image into the test environment,
// which will trigger an automatic deployment of that image.
// this stage should only occur when the pull request is being made against the master branch.
stage('STAGING - Deploy') {
agent { label 'deploy' }
when {
beforeAgent true
expression { env.CHANGE_TARGET == 'master' }
}
steps {
script {
_openshift(env.STAGE_NAME, stagingProject) {
echo "Preparing..."
// Process db and app template into list objects
// TODO: Match docker-compose image from 26e83e-tools
echo "Updating staging deployment..."
def deployDBTemplate = openshift.process("-f",
"${templateDir}/postgresql.dc.yml",
"NAME_SUFFIX=-${stagingSuffix}",
"DATABASE_SERVICE_NAME=gwells-pg12-${stagingSuffix}",
"IMAGE_STREAM_NAMESPACE=${stagingProject}",
"IMAGE_STREAM_NAME=crunchy-postgres-gis",
"POSTGRESQL_DATABASE=gwells",
"VOLUME_CAPACITY=20Gi",
"STORAGE_CLASS=netapp-file-standard",
"REQUEST_CPU=400m",
"REQUEST_MEMORY=2Gi",
"LIMIT_CPU=400m",
"LIMIT_MEMORY=2Gi"
)
def deployTemplate = openshift.process("-f",
"${templateDir}/backend.dc.json",
"NAME_SUFFIX=-${stagingSuffix}",
"ENV_NAME=${stagingSuffix}",
"HOST=${stagingHost}",
"CPU_REQUEST=500m",
"CPU_LIMIT=2",
)
echo "Processing deployment config for tile server"
def pgtileservTemplate = openshift.process("-f",
"${templateDir}/pg_tileserv/pg_tileserv.dc.yaml",
"NAME_SUFFIX=-${stagingSuffix}",
"DATABASE_SERVICE_NAME=gwells-pg12-${stagingSuffix}",
"IMAGE_TAG=20201112",
"HOST=${stagingHost}",
)
echo "Processing Minio deployment config"
def minioTemplate = openshift.process("-f",
"${templateDir}/minio/minio.dc.yaml",
"NAME_SUFFIX=-${stagingSuffix}",
"DEST_PVC_SIZE=10Gi",
"HOSTNAME=gwells-docs-${stagingSuffix}.apps.silver.devops.gov.bc.ca"
)
echo "Processing backup volume config"
def backupVolConfig = openshift.process("-f",
"${templateDir}/backup.pvc.yaml",
"VOLUME_CAPACITY=20Gi",
"STORAGE_CLASS=netapp-file-backup"
)
// some objects need to be copied from a base secret or configmap
// these objects have an annotation "as-copy-of" in their object spec (e.g. an object in backend.dc.json)
echo "Creating configmaps and secrets objects"
List newObjectCopies = []
// todo: refactor to explicitly copy the objects we need
for (o in (deployTemplate + deployDBTemplate)) {
// only perform this operation on objects with 'as-copy-of'
def sourceName = o.metadata && o.metadata.annotations && o.metadata.annotations['as-copy-of']
if (sourceName && sourceName.length() > 0) {
def selector = openshift.selector("${o.kind}/${sourceName}")
if (selector.count() == 1) {
// create a copy of the object and add it to the new list of objects to be applied
Map copiedModel = selector.object()
copiedModel.metadata.remove('annotations')
copiedModel.metadata.remove('creationTimestamp')
copiedModel.metadata.remove('resourceVersion')
copiedModel.metadata.remove('selfLink')
copiedModel.metadata.remove('uid')
copiedModel.metadata.name = o.metadata.name
echo "Copying ${o.kind} ${o.metadata.name}"
newObjectCopies.add(copiedModel)
}
}
}
openshift.apply(deployDBTemplate).label(
[
'app':"gwells-${stagingSuffix}",
'app-name':"${appName}",
'env-name':"${stagingSuffix}"
],
"--overwrite"
)
// apply the templates, which will create new objects or modify existing ones as necessary.
// the copies of base objects (secrets, configmaps) are also applied.
echo "Applying deployment config for pull request ${prNumber} on ${stagingProject}"
openshift.apply(pgtileservTemplate).label(
[
'app':"gwells-${stagingSuffix}",
'app-name':"${appName}",
'env-name':"${stagingSuffix}"
],
"--overwrite"
)
openshift.apply(minioTemplate).label(
['app':"gwells-${stagingSuffix}", 'app-name':"${appName}", 'env-name':"${stagingSuffix}"],
"--overwrite"
)
openshift.apply(deployTemplate).label(
[
'app':"gwells-${stagingSuffix}",
'app-name':"${appName}",
'env-name':"${stagingSuffix}"
],
"--overwrite"
)
openshift.apply(backupVolConfig).label(
[
'app':"gwells-${stagingSuffix}",
'app-name':"${appName}",
'env-name':"${stagingSuffix}"
],
"--overwrite"
)
openshift.apply(newObjectCopies).label(
[
'app':"gwells-${stagingSuffix}",
'app-name':"${appName}",
'env-name':"${stagingSuffix}"
],
"--overwrite"
)
echo "Successfully applied TEST deployment config"
// promote the newly built image to DEV
echo "Tagging new image to TEST imagestream."
// Application/database images are tagged in the tools imagestream as the new test/prod image
openshift.tag(
"${toolsProject}/gwells-application:${prNumber}",
"${toolsProject}/gwells-application:${stagingSuffix}"
)
// Images are then tagged into the target environment namespace (test or prod)
openshift.tag(
"${toolsProject}/gwells-application:${stagingSuffix}",
"${stagingProject}/gwells-${stagingSuffix}:${stagingSuffix}"
) // todo: clean up labels/tags
createDeploymentStatus(stagingSuffix, 'PENDING', stagingHost)
// Create cronjob for well export
def exportWellCronTemplate = openshift.process("-f",
"${templateDir}/jobs/export-databc/export.cj.json",
"ENV_NAME=${stagingSuffix}",
"PROJECT=${stagingProject}",
"TAG=${stagingSuffix}",
"NAME=export",
"COMMAND=export",
"SCHEDULE=30 3 * * *"
)
openshift.apply(exportWellCronTemplate).label(
[
'app':"gwells-${stagingSuffix}",
'app-name':"${appName}",
'env-name':"${stagingSuffix}"
],
"--overwrite"
)
// Create cronjob for licence import
def importLicencesCronjob = openshift.process("-f",
"${templateDir}/jobs/import-licences/import-licences.cj.json",
"ENV_NAME=${stagingSuffix}",
"PROJECT=${stagingProject}",
"TAG=${stagingSuffix}",
"NAME=licences",
"COMMAND=import_licences",
"SCHEDULE=40 3 * * *"
)
openshift.apply(importLicencesCronjob).label(
[
'app':"gwells-${stagingSuffix}",
'app-name':"${appName}",
'env-name':"${stagingSuffix}"
],
"--overwrite"
)
// Create cronjob for aquifer demand calc update
def importUpdateAquiferCronjob = openshift.process("-f",
"${templateDir}/jobs/update-aquifer/update-aquifer.cj.json",
"ENV_NAME=${stagingSuffix}",
"PROJECT=${stagingProject}",
"TAG=${stagingSuffix}",
"NAME=demand",
"COMMAND=update_demand",
"SCHEDULE=50 3 * * *"
)
openshift.apply(importUpdateAquiferCronjob).label(
[
'app':"gwells-${stagingSuffix}",
'app-name':"${appName}",
'env-name':"${stagingSuffix}"
],
"--overwrite"
)
// Create cronjob for databc export
def exportDataBCTemplate = openshift.process("-f",
"${templateDir}/jobs/export-databc/export.cj.json",
"ENV_NAME=${stagingSuffix}",
"PROJECT=${stagingProject}",
"TAG=${stagingSuffix}",
"NAME=export-databc",
"COMMAND=export_databc",
"SCHEDULE=0 4 * * *"
)
openshift.apply(exportDataBCTemplate).label(
[
'app':"gwells-${stagingSuffix}",
'app-name':"${appName}",
'env-name':"${stagingSuffix}"
],
"--overwrite"
)
// automated minio backup
def docBackupCronjob = openshift.process("-f",
"${templateDir}/jobs/minio-backup/minio-backup.cj.yaml",