-
Notifications
You must be signed in to change notification settings - Fork 20
/
Matrix.groovy
1595 lines (1339 loc) · 51.7 KB
/
Matrix.groovy
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
#!/usr/bin/groovy
/* groovylint-disable BlockEndsWithBlankLine, BlockStartsWithBlankLine, ClassStartsWithBlankLine, CompileStatic, DuplicateListLiteral, DuplicateNumberLiteral, DuplicateStringLiteral, FactoryMethodName, FieldTypeRequired, GStringExpressionWithinString, ImplicitClosureParameter, Instanceof, LineLength, MethodCount, MethodParameterTypeRequired, MethodReturnTypeRequired, NestedForLoop, ParameterCount, ParameterName, PrintStackTrace, SpaceAroundOperator, TrailingWhitespace, UnnecessaryGString, UnnecessaryGetter, UnnecessaryNullCheck, UnusedMethodParameter, VariableTypeRequired */
/* groovylint-disable ConsecutiveBlankLines, ImplicitReturnStatement */
/* groovylint-disable LineLength, NoDef, UnnecessarySemicolon, VariableName */
package com.mellanox.cicd;
import jenkins.model.Jenkins
class Logger {
def ctx
def cat
def traceLevel
Logger(ctx) {
this.ctx = ctx
this.cat = "matrix_job"
this.traceLevel = ctx.getDebugLevel()
}
def info(String message) {
this.ctx.echo this.cat + " INFO: ${message}"
}
def error(String message) {
this.ctx.echo this.cat + " ERROR: ${message}"
}
def warn(String message) {
this.ctx.echo this.cat + " WARN: ${message}"
}
def debug(String message) {
if (this.ctx.isDebugMode()) {
this.ctx.echo this.cat + " DEBUG: ${message}"
}
}
def trace(int level, String message) {
if (level <= this.traceLevel) {
this.ctx.echo this.cat + " TRACE[${level}]: ${message}"
}
}
}
@NonCPS
List getMatrixAxes(matrix_axes) {
List axes = []
matrix_axes.each { axis, values ->
List axisList = []
values.each { value ->
axisList << [(axis): value]
}
axes << axisList
}
// calculate cartesian product
axes.combinations()*.sum()
}
// hack to avoid Serializble errors as intermediate access to entrySet returns non-serializable objects
@NonCPS
def entrySet(m) {
m.collect { k, v -> [key: k, value: v] }
}
def run_shell(cmd, title, retOut=false) {
def text = ""
def rc
def err = null
try {
if (retOut) {
text = sh(script: cmd, label: title, returnStdout: true)
rc = 0
} else {
rc = sh(script: cmd, label: title, returnStatus: true)
}
} catch (e) {
err = e
org.codehaus.groovy.runtime.StackTraceUtils.printSanitizedStackTrace(e)
}
return ['text': text, 'rc': rc, 'exception': err]
}
def run_step_shell(image, cmd, title, oneStep, config) {
def vars = []
vars += toEnvVars(config, config.env)
vars += toEnvVars(config, oneStep.env)
def names = ['registry_host', 'registry_path', 'job']
for (int i=0; i<names.size(); i++) {
vars.add(names[i] + "=" + config.get(names[i]) ?: '')
}
withEnv(vars) {
def ret = run_shell(cmd, title)
if (ret.rc != 0) {
if (oneStep["onfail"] != null) {
run_shell(oneStep.onfail, "onfail command for ${title}")
}
}
if (oneStep["always"] != null) {
run_shell(oneStep.always, "always command for ${title}")
}
attachResults(config, oneStep, ret)
attachHTML(image, config, oneStep)
if (ret.rc != 0) {
def msg = "Step ${title} failed with exit code=${ret.rc}"
if (ret.exception != null) {
msg += " exception=${ret.exception}"
}
reportFail(title, msg)
}
}
}
def forceCleanup(prefix='', redirect='') {
env.WORKSPACE = pwd()
def cmd = """
if [ -x /bin/bash ]; then
$prefix bash -eE -c 'shopt -s dotglob; rm -rf ${env.WORKSPACE}/*' ${redirect}
else
$prefix find ${env.WORKSPACE} -depth ! -path . ! -path .. ! -path ${env.WORKSPACE} -exec rm -rf {} \\; ${redirect}
fi
"""
return run_shell(cmd, "Clean workspace $prefix")
}
def forceCleanupWS() {
def res = forceCleanup('','&>/dev/null')
if (res.rc != 0) {
res = forceCleanup('sudo','')
if (res.rc != 0) {
reportFail('clean workspace', "Unable to cleanup workspace rc=" + res)
}
}
}
def getArchConf(config, arch) {
def k8sArchConfTable = [:]
config.logger.trace(4, "getArchConf: arch=" + arch)
config.registry_jnlp_path = getConfigVal(config, ['registry_jnlp_path'], 'swx-infra')
k8sArchConfTable['x86_64'] = [
nodeSelector: 'kubernetes.io/arch=amd64',
jnlpImage: 'jenkins/inbound-agent:latest',
dockerImage: 'quay.io/podman/stable:v5.0.2'
]
k8sArchConfTable['aarch64'] = [
nodeSelector: 'kubernetes.io/arch=arm64',
jnlpImage: "jenkins/inbound-agent:latest",
dockerImage: 'quay.io/podman/stable:v5.0.2'
]
k8sArchConfTable['ppc64le'] = [
nodeSelector: 'kubernetes.io/arch=ppc64le',
jnlpImage: "${config.registry_host}/${config.registry_jnlp_path}/jenkins-ppc64le-agent-jnlp:latest",
dockerImage: 'quay.io/podman/stable:v5.0.2'
]
def aTable = getConfigVal(config, ['kubernetes', 'arch_table'], null)
if (aTable != null && aTable.containsKey(arch)) {
if (k8sArchConfTable[arch] != null) {
k8sArchConfTable[arch] += aTable[arch]
} else {
k8sArchConfTable[arch] = aTable[arch]
}
}
def vars = ['arch':arch]
k8sArchConfTable[arch].each { key, val ->
k8sArchConfTable[arch][key] = resolveTemplate(vars, val, config)
}
config.logger.trace(2, "getArchConf[${arch}] " + k8sArchConfTable[arch])
return k8sArchConfTable[arch]
}
def gen_image_map(config) {
def image_map = [:]
def arch_list = getConfigVal(config, ['matrix', 'axes', 'arch'], null, false)
if (!config.runs_on_dockers) {
config.runs_on_dockers = []
}
if (arch_list) {
for (int i=0; i<arch_list.size(); i++) {
def arch = arch_list[i]
image_map[arch] = []
}
} else {
for (int i=0; i<config.runs_on_dockers.size(); i++) {
def dfile = config.runs_on_dockers[i]
if (dfile.arch) {
image_map["${dfile.arch}"] = []
} else {
reportFail('config', "Please define tag 'arch' for image ${dfile.name} in 'runs_on_dockers' section of yaml file")
}
}
}
image_map.each { arch, images ->
def k8sArchConf = getArchConf(config, arch)
if (!k8sArchConf) {
config.logger.trace(3, "gen_image_map | skipped unsupported arch (${arch})")
return
}
config.runs_on_dockers.each { item ->
def dfile = item.clone()
config.logger.debug("run on dockers item: " + dfile)
if (dfile.enable == null) {
dfile.enable = "true"
config.logger.debug("run on dockers item.enable: " + dfile.enable)
}
if (dfile.enable == "auto") {
dfile.enable = '${' + dfile.name + '}'
config.logger.debug("run on dockers item.enable: " + dfile.enable)
}
def enable = resolveTemplate(dfile, dfile.enable, config)
config.logger.debug("run on dockers enable: " + enable)
if (enable.toBoolean()) {
dfile.arch = dfile.arch ?: arch
if (dfile.arch && dfile.arch != arch) {
config.logger.trace(3, "skipped conf: " + arch + " name: " + dfile.name)
return
}
dfile.file = dfile.file ?: ''
if (dfile.url) {
parts = dfile.url.tokenize('/').last().tokenize(':')
if (parts.size() == 2) {
dfile.tag = parts[1]
tag_size = dfile.tag.size() + 1
len = dfile.url.size() - tag_size
dfile.uri = dfile.url.substring(0,len)
}
}
dfile.tag = dfile.tag ?: 'latest'
dfile.build_args = dfile.build_args ?: ''
dfile.build_args = resolveTemplate(dfile, dfile.build_args, config)
dfile.uri = dfile.uri ?: "${arch}/${dfile.name}"
dfile.filename = dfile.file
dfile.uri = resolveTemplate(dfile, dfile.uri, config)
dfile.url = dfile.url ?: "${config.registry_host}${config.registry_path}/${dfile.uri}:${dfile.tag}"
dfile.url = resolveTemplate(dfile, dfile.url, config)
config.logger.debug("Adding docker to image_map for " + dfile.arch + ' name: ' + dfile.name)
images.add(dfile)
}
}
}
return image_map
}
def matchMapEntry(filters, entry) {
def match
for (int i=0; i<filters.size(); i++) {
match = true
filters[i].each { k, v ->
String ek = entry[k] + ''
if (entry[k] == null || !ek.matches(v + "")) {
match = false
}
}
if (match) {
break
}
}
return match
}
def onUnstash() {
def cmd = """#!/bin/sh
export PATH='/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin'
hash -r
tar xf scm-repo.tar
rm -f scm-repo.tar
"""
run_shell(cmd, "Extracting project files into workspace")
}
def attachArtifacts(config, args) {
if (args != null) {
try {
archiveArtifacts(artifacts: args, allowEmptyArchive: true )
} catch (e) {
config.logger.warn("Failed to add artifacts: " + args + " reason: " + e)
}
}
}
def attachJunit(config, args) {
if (args != null) {
try {
junit(testResults: args, allowEmptyResults: true)
} catch (e) {
config.logger.warn("Failed to add junit results: " + args + " reason: " + e)
}
}
}
def attachTap(config, args) {
if (args != null) {
try {
step([$class: "TapPublisher",
failedTestsMarkBuildAsFailure: true,
planRequired: false,
failIfNoResults: false,
testResults: args])
} catch (e) {
config.logger.warn("Failed to add tap results: " + args + " reason: " + e)
}
}
}
def attachHTML(image, config, oneStep) {
def reportDir, reportFiles, reportName, allowMissing
if (oneStep.publishHTML) {
reportDir = resolveTemplate(image, oneStep.publishHTML.reportDir, config)
reportFiles = resolveTemplate(image, oneStep.publishHTML.reportFiles, config)
reportName = resolveTemplate(image, oneStep.publishHTML.reportName, config)
allowMissing = oneStep.publishHTML.allowMissing
} else if (oneStep.run == 'coverity.sh' || oneStep.resource == 'actions/coverity.sh') {
reportDir = 'cov_build/output/errors/'
reportFiles = 'index.html'
reportName = 'Coverity Report'
allowMissing = false
} else {
return
}
publishHTML (target : [allowMissing: allowMissing,
alwaysLinkToLastBuild: true,
keepAll: true,
reportDir: reportDir,
reportFiles: reportFiles,
reportName: reportName,
])
}
def attachResults(config, oneStep=null, res=null) {
def obj = oneStep? oneStep : config
if (res && res.rc != 0) {
attachArtifacts(config, obj["archiveArtifacts-onfail"])
attachJunit(config, obj["archiveJunit-onfail"])
attachTap(config, obj["archiveTap-onfail"])
}
attachArtifacts(config, obj["archiveArtifacts"])
attachJunit(config, obj["archiveJunit"])
attachTap(config, obj["archiveTap"])
}
@NonCPS
int getDebugLevel() {
def val = env.DEBUG
def intValue = 0
if (val != null) {
if (val == "true") {
intValue = 1
} else {
intValue = val.isInteger()? val.toInteger() : 0
}
}
return intValue
}
def isDebugMode() {
def mode = (getDebugLevel())? true : false
return mode
}
def getDefaultShell(config=null, step=null, shell=null) {
def cmd = """#!/bin/sh
if [ -x /bin/bash ]; then
echo '#!/bin/bash -elE'
else
echo '#!/bin/sh -el'
fi
"""
def res = run_shell(cmd, "Detect shell", true)
shell = res.text.trim()
if (isDebugMode()) {
shell += 'x'
}
def ret = shell
if ((step != null) && (step.shell != null)) {
ret = step.shell
} else if ((config != null) && (config.shell != null)) {
ret = config.shell
}
if (ret != "action") {
if (ret.substring(0,1) == '/') {
ret = '#!' + ret
} else if (ret.substring(0,2) != '#!') {
reportFail("config", "Unsupported value for shell parameter: " + ret + " should be '#!/path/to/shell'")
}
}
return ret
}
Map toStringMap(String param) {
Map ret = [:]
String strMap = param
if (strMap != null) {
strMap = '[' + strMap.replaceAll('[\\{\\}]', ' ') + ']'
ret = evaluate(strMap)
}
return ret
}
def stringToList(selector) {
def customSel = []
if (selector && selector.size() > 0) {
if (selector.getClass() == String) {
customSel.add(toStringMap(selector))
} else {
// groovy casts yaml Map definition to LinkedHashMap type
// which is not serializable and causes Jenkins pipeline to fail
// on non-serializable error, this is a reason for ugle hack to
// convert LinkedHashMap to Map which is serializable
for (int i=0; i<selector.size(); i++) {
customSel.add(toStringMap(selector[i].toString()))
}
}
}
return customSel
}
def check_skip_stage(image, config, title, oneStep, axis, runtime=null) {
def stepEnabled = getConfigVal(config, ['enable'], true, true, oneStep, true).toString()
if (!stepEnabled.toBoolean()) {
config.logger.trace(2, "Step '${oneStep.name}' is disabled in project yaml file, skipping")
return true
}
def selectors = [oneStep.containerSelector, oneStep.agentSelector]
// check if two selectors configured and only one allowed
def singleSelector = getConfigVal(config, ['step_allow_single_selector'], false)
if ((singleSelector == true) && (oneStep.containerSelector != null) && (oneStep.agentSelector != null)) {
reportFail('config', "Step='${oneStep.name}' has both containerSelector and agentSelector configured, step_allow_single_selector=${singleSelector}, set `step_allow_single_selector: false` to disable")
}
def skip = false
if (runtime) {
if(runtime == 'k8') {
if (singleSelector && oneStep.agentSelector) { // skip if wrong selector
return true
}
selectors = [oneStep.containerSelector]
} else {
if (singleSelector && oneStep.containerSelector) { // skip if wrong selector
return true
}
selectors = [oneStep.agentSelector]
}
}
config.logger.trace(2, "check_skip_stage step='${oneStep.name}' runtime=${runtime} selectors=${selectors}")
// tools by default should be skipped, unless explicitly requested by selectors below
if (image['category'] == 'tool') {
skip = true
}
for (int i=0; i<selectors.size(); i++) {
selector = selectors[i]
if (selector && selector.size() > 0) {
def customSel = stringToList(selector)
config.logger.trace(2, "Selector=" + selector + " custom=" + customSel + " name=" + image.name)
if (matchMapEntry(customSel, axis)) {
config.logger.trace(2, "Step '" + oneStep.name + " matched with axis=" + axis + " selector=" + selector)
skip = false
break
} else {
skip = true
}
}
}
config.logger.trace(2, "${oneStep.name} - Step '" + oneStep.name + "' skip=" + skip)
return skip
}
void reportFail(String stage, String msg) {
currentBuild.result = 'FAILURE'
error(stage + " failed with msg: " + msg)
}
def toEnvVars(config, vars) {
def map = []
if (vars) {
for (def entry in entrySet(vars)) {
map.add(entry.key + "=" + resolveTemplate(vars, '' + entry.value, config))
}
}
return map
}
def run_step(image, config, title, oneStep, axis, runtime=null) {
if ((image != null) &&
(axis != null) &&
check_skip_stage(image, config, title, oneStep, axis, runtime)) {
return
}
stage("${title}") {
def shell = getDefaultShell(config, oneStep)
env.WORKSPACE = pwd()
if (oneStep.resource) {
def actionScript = libraryResource "${oneStep.resource}"
def idx = oneStep.resource.lastIndexOf('/')
def dirname = '.ci/' + oneStep.resource.substring(0, idx)
def filename = oneStep.resource.substring(idx+1)
def toFile = "${dirname}/${filename}"
sh(script: "mkdir -p $dirname", label: "Create action dir $dirname", returnStatus: true)
writeFile(file: toFile, text: actionScript)
sh(script: "chmod +x " + toFile, label: "Set script $toFile permissions", returnStatus: true)
}
if (shell == "action") {
if (oneStep.module == null) {
reportFail(title, "Step is type of action but has no 'module' defined")
}
config.logger.trace(4, "Running step action module=" + oneStep.module + " args=" + oneStep.args + " run=" + oneStep.run)
int rc = this."${oneStep.module}"(this, oneStep, config)
if (rc != 0) {
reportFail(oneStep.name, "exit with error code=${rc}")
}
} else {
def String cmd = shell + "\n" + oneStep.run
config.logger.trace(4, "Running step script=" + cmd)
if (oneStep.credentialsId) {
def credentialsIdList = []
// credentialsId can be string or list of strings
if (oneStep.credentialsId instanceof List) {
credentialsIdList.addAll(oneStep.credentialsId)
} else if (oneStep.credentialsId instanceof String) {
credentialsIdList.add(oneStep.credentialsId)
} else {
reportFail(title, "credentialsId should be either a List or a String")
}
def foundList = []
for (credentialsId in credentialsIdList) {
def found = false
for (int i=0; i<config.credentials.size(); i++) {
Map entry = config.credentials[i]
if (entry.credentialsId == credentialsId) {
foundList.add(entry)
found = true
break
}
}
if (!found) {
reportFail(title, "credentialsId '${credentialsId}' requested but undefined in yaml file ")
}
}
def credentials = []
for (Map found in foundList) {
if (found.get('type') && found.get('type') != 'usernamePassword') {
if (found.type == 'sshUserPrivateKey') {
credentials.add(sshUserPrivateKey(credentialsId: found.credentialsId,
keyFileVariable: found.keyFileVariable,
passphraseVariable: found.get('passphraseVariable'),
usernameVariable: found.get('usernameVariable')))
}
if (found.type == 'file') {
credentials.add(file(credentialsId: found.credentialsId,
variable: found.variable))
}
} else {
// usernamePassword by default
if (!found.usernameVariable || !found.passwordVariable) {
reportFail(title, "credentialsId '${found.credentialsId}' has unsupported format (${found})!")
}
credentials.add(usernamePassword(credentialsId: found.credentialsId,
passwordVariable: found.passwordVariable,
usernameVariable: found.usernameVariable))
}
}
withCredentials(credentials) {
run_step_shell(image, cmd, title, oneStep, config)
}
} else {
run_step_shell(image, cmd, title, oneStep, config)
}
}
}
}
def runSteps(image, config, branchName, axis, steps=config.steps, runtime) {
forceCleanupWS()
// fetch .git from server and unpack
unstash getStashName()
onUnstash()
def parallelNestedSteps = [:]
for (int i = 0; i < steps.size(); i++) {
def one = steps[i]
def par = one["parallel"]
def oneStep = one
// collect parallel steps (if any) and run it when non-parallel step discovered or last element.
// Skip parallel stages if not used. Fix for Blueocean UI.
if ( par != null && par == true && !check_skip_stage(image, config, branchName, oneStep, axis)) {
def stepName = branchName + "->" + one.name
parallelNestedSteps[stepName] = { run_step(image, config, stepName, oneStep, axis, runtime) }
// last element - run and flush
if (i == steps.size() - 1) {
parallel(parallelNestedSteps)
parallelNestedSteps = [:]
}
continue
}
// non-parallel step discovered, need to flush all parallel
// steps collected previously to keep ordering.
// run non-parallel step right after
if (parallelNestedSteps.size() > 0) {
parallel(parallelNestedSteps)
parallelNestedSteps = [:]
}
run_step(image, config, one.name, oneStep, axis, runtime)
}
attachResults(config)
}
def getConfigVal(config, list, defaultVal=null, toString=true, oneStep=null, useTemplate=false) {
def val = oneStep ?: config
for (int i=0; i<list.size(); i++) {
def item = list[i]
config.logger.trace(5, "getConfigVal: Checking $item in config file")
val = val[item]
if (val == null) {
config.logger.trace(5, "getConfigVal: Defaulting " + list + " = " + defaultVal)
return defaultVal
}
}
def ret
if (toString && (val instanceof ArrayList) && (val.size() == 1)) {
config.logger.trace(5, "getConfigVal: arraylist hack "+ val[0])
ret = val[0]
} else {
ret = val
}
if (useTemplate) {
ret = resolveTemplate([:], ret, config)
}
config.logger.trace(5, "getConfigVal: Found " + list + " = " + ret)
return ret
}
def parseListV(volumes) {
def listV = []
volumes.each { vol ->
hostPath = vol.get("hostPath")
mountPath = vol.get("mountPath")
hpv = hostPathVolume(hostPath: hostPath, mountPath: mountPath)
listV.add(hpv)
}
return listV
}
def parseListNfsV(volumes) {
def listV = []
volumes.each { vol ->
serverAddress = vol.get("serverAddress")
serverPath = vol.get("serverPath")
mountPath = vol.get("mountPath")
readOnly = vol.get("readOnly", false)
nfsv = nfsVolume(serverAddress: serverAddress,
serverPath: serverPath,
mountPath: mountPath,
readOnly: readOnly)
listV.add(nfsv)
}
return listV
}
def parseListPVC(volumes) {
def listV = []
volumes.each { vol ->
claimName = vol.get("claimName")
mountPath = vol.get("mountPath")
readOnly = vol.get("readOnly", false)
PVCv = persistentVolumeClaim(claimName: claimName,
mountPath: mountPath,
readOnly: readOnly)
listV.add(PVCv)
}
return listV
}
def parseSecretV(volumes) {
def listV = []
volumes.each { vol ->
secretName = vol.get("secretName")
mountPath = vol.get("mountPath")
optional = vol.get("optional")
defaultMode = vol.get("defaultMode")
secretV = secretVolume(secretName: secretName,
mountPath: mountPath,
optional: optional,
defaultMode: defaultMode)
listV.add(secretV)
}
return listV
}
def parseEmptyDirV(volumes) {
def listV = []
volumes.each { vol ->
mountPath = vol.get("mountPath")
memoryFlag = vol.get("memory", false)
EmptyDirV = emptyDirVolume( mountPath: mountPath,
memory: memoryFlag)
listV.add(EmptyDirV)
}
return listV
}
def parseListA(annotations) {
def listA = []
annotations.each { an ->
key = an.get("key")
value = an.get("value")
pan = podAnnotation(key: key, value: value)
listA.add(pan)
}
return listA
}
def runK8(image, branchName, config, axis, steps=config.steps) {
def cloudName = image.cloud ?: getConfigVal(config, ['kubernetes', 'cloud'], null)
if (!cloudName) {
reportFail('config', "kubernetes run requested but kubernetes.cloud name is not defined in yaml file")
}
config.logger.trace(2, "Using kubernetes ${cloudName}, axis=" + axis)
def listV = parseListV(config.volumes)
listV.addAll(parseListNfsV(config.nfs_volumes))
listV.addAll(parseListPVC(config.pvc_volumes))
listV.addAll(parseSecretV(config.secret_volumes))
listV.addAll(parseEmptyDirV(config.empty_volumes))
def cname = image.get("name").replaceAll("[\\.:/_]", "")
def pod_name = config.job + "-" + cname + "-" + env.BUILD_NUMBER
def k8sArchConf = getArchConf(config, axis.arch)
def nodeSelector = ''
if (!k8sArchConf) {
config.logger.error("runK8 | arch conf is not defined for ${axis.arch}")
return
}
nodeSelector = k8sArchConf.nodeSelector
config.logger.trace(2, "runK8 ${branchName} | nodeSelector: ${nodeSelector}")
if (axis.nodeSelector) {
if (nodeSelector) {
nodeSelector = nodeSelector + ',' + axis.nodeSelector
} else {
nodeSelector = axis.nodeSelector
}
}
def hostNetwork = image.hostNetwork ?: getConfigVal(config, ['kubernetes', 'hostNetwork'], false)
def runAsUser = image.runAsUser ?: getConfigVal(config, ['kubernetes', 'runAsUser'], "0")
def runAsGroup = image.runAsGroup ?: getConfigVal(config, ['kubernetes', 'runAsGroup'], "0")
def privileged = image.privileged ?: getConfigVal(config, ['kubernetes', 'privileged'], false)
def limits = image.limits ?: getConfigVal(config, ['kubernetes', 'limits'], "{memory: 8Gi, cpu: 4000m}")
def requests = image.requests ?: getConfigVal(config, ['kubernetes', 'requests'], "{memory: 8Gi, cpu: 4000m}")
def annotations = image.annotations ?: getConfigVal(config, ['kubernetes', 'annotations'], [], false)
def caps_add = image.caps_add ?: getConfigVal(config, ['kubernetes', 'caps_add'], "[]")
def service_account = getConfigVal(config, ['kubernetes', 'serviceAccount'], "default")
def namespace = image.namespace ?: getConfigVal(config, ['kubernetes', 'namespace'], "default")
def tolerations = image.tolerations ?: getConfigVal(config, ['kubernetes', 'tolerations'], "[]")
def yaml = """
spec:
containers:
- name: ${cname}
env:
- name: K8S_NODE_NAME
valueFrom:
fieldRef:
fieldPath: spec.nodeName
resources:
limits: ${limits}
requests: ${requests}
securityContext:
capabilities:
add: ${caps_add}
tolerations: ${tolerations}
"""
podTemplate(
cloud: cloudName,
runAsUser: runAsUser,
runAsGroup: runAsGroup,
nodeSelector: nodeSelector,
hostNetwork: hostNetwork,
annotations: parseListA(annotations),
yamlMergeStrategy: merge(),
serviceAccount: service_account,
namespace: namespace,
name: pod_name,
yaml: yaml,
containers: [
containerTemplate(name: 'jnlp', image: k8sArchConf.jnlpImage, args: '${computer.jnlpmac} ${computer.name}'),
containerTemplate(privileged: privileged, name: cname, image: image.url, ttyEnabled: true, alwaysPullImage: true, command: 'cat')
],
volumes: listV
)
{
node(POD_LABEL) {
stage (branchName) {
container(cname) {
runSteps(image, config, branchName, axis, steps, 'k8')
}
}
}
}
config.logger.trace(2, "runK8 ${branchName} done")
}
@NonCPS
def replaceVars(vars, str) {
def res = str.toString()
for (def entry in entrySet(vars)) {
if (entry.key == "" || entry.key == null || entry.value == "" || entry.value == null) {
continue;
}
if (!res.contains('$')) {
return res
}
def opts = ['$' + entry.key, '${' + entry.key + '}']
for (int i=0; i<opts.size(); i++) {
if (res.contains(opts[i])) {
res = res.replace(opts[i], entry.value + '')
break
}
}
}
return res
}
@NonCPS
def resolveTemplate(vars, str, config) {
def res = str
def varsMap = vars
if (config.env) {
res = replaceVars(config.env, res)
varsMap += config.env
}
varsMap += config
varsMap += env.getEnvironment()
res = replaceVars(varsMap, res)
return res
}
def getDockerOpt(config) {
def opts = getConfigVal(config, ['docker_opt'], "")
if (config.get("volumes")) {
for (int i=0; i<config.volumes.size(); i++) {
def vol = config.volumes[i]
hostPath = vol.get("hostPath")? vol.hostPath : vol.mountPath
opts += " -v ${vol.mountPath}:${hostPath}"
}
}
return opts
}
def runAgent(image, config, branchName=null, axis=null, Closure func, runInDocker=true) {
def nodeName = image.nodeLabel
config.logger.debug("Running on agent with label: ${nodeName} branch: ${branchName} - docker: " + runInDocker)
node(nodeName) {
forceCleanupWS()
unstash getStashName()
onUnstash()
stage(branchName) {
env.WORKSPACE = pwd()
if (runInDocker) {
def opts = getDockerOpt(config)
if (image.privileged && image.privileged == 'true') {
opts += " --privileged "
}
docker.image(image.url).inside(opts) {
func(image, config, branchName, axis, "docker")
}
} else {
func(image, config, branchName, axis, "baremetal")
}
}
}
}
Map getTasks(axes, image, config, include, exclude) {
config.logger.trace(3, "getTasks() --> image=" + image)
int serialNum = 1
Map tasks = [:]
for (int i = 0; i < axes.size(); i++) {
Map axis = axes[i]
if (axis.arch != image.arch) {
config.logger.debug("getTasks: skipping axis=" + axis + " as its arch does not match image=" + image)
continue
}
// todo: some keys from matrix can be same as in image map and it will cause confusion
// maybe need to prefix image keys with special prefix to distinguish or copy only non-existing keys
axis += image
axis.put("job", config.job)
if (exclude.size() && matchMapEntry(exclude, axis)) {
config.logger.debug("Skipping by 'exclude' rule, axis " + axis.toMapString())
continue
} else if (include.size() && ! matchMapEntry(include, axis)) {
config.logger.debug("Skipping by 'include' rule, axis " + axis.toMapString())
continue
}
if (!config.steps) {
continue
}
axis.put("variant", serialNum)
axis.put("axis_index", serialNum)
serialNum++
config.logger.debug("Working on axis " + axis.toMapString())