forked from adoptium/ci-jenkins-pipelines
-
Notifications
You must be signed in to change notification settings - Fork 0
/
build_base_file.groovy
1134 lines (1004 loc) · 50.8 KB
/
build_base_file.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
/*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/* groovylint-disable MethodCount */
import common.IndividualBuildConfig
import groovy.json.*
import java.util.regex.Matcher
import org.jenkinsci.plugins.workflow.steps.FlowInterruptedException
/**
* Represents parameters that get past to each individual build
*/
/**
* This file starts a high level job, it is called from openjdk_pipeline.groovy.
*
* This:
*
* 1. Generate job for each configuration based on create_job_from_template.groovy
* 2. Execute job
* 3. Push generated artifacts to github
*/
//@CompileStatic(extensions = "JenkinsTypeCheckHelperExtension")
class Builder implements Serializable {
String javaToBuild
Map<String, Map<String, ?>> buildConfigurations
Map<String, List<String>> targetConfigurations
Map<String, ?> DEFAULTS_JSON
String activeNodeTimeout
Map<String, List<String>> dockerExcludes
boolean enableReproducibleCompare
boolean enableTests
boolean enableTestDynamicParallel
boolean enableInstallers
boolean enableSigner
boolean publish
boolean release
String releaseType
String scmReference
String buildReference
String ciReference
String helperReference
String aqaReference
boolean aqaAutoGen
String publishName
String additionalConfigureArgs
def scmVars
String additionalBuildArgs
String overrideFileNameVersion
String adoptBuildNumber
boolean useAdoptShellScripts
boolean cleanWorkspaceBeforeBuild
boolean cleanWorkspaceAfterBuild
boolean cleanWorkspaceBuildOutputAfterBuild
boolean propagateFailures
boolean keepTestReportDir
boolean keepReleaseLogs
def currentBuild
def context
def env
// Declare timeouts for each critical stage (unit is HOURS)
Map pipelineTimeouts = [
API_REQUEST_TIMEOUT : 1,
REMOVE_ARTIFACTS_TIMEOUT : 2,
COPY_ARTIFACTS_TIMEOUT : 6,
ARCHIVE_ARTIFACTS_TIMEOUT : 6,
PUBLISH_ARTIFACTS_TIMEOUT : 3
]
/*
Returns an IndividualBuildConfig that is passed down to the downstream job.
It uses several helper functions to pull in and parse the build configuration for the job.
This overrides the default IndividualBuildConfig generated in config_regeneration.groovy.
*/
IndividualBuildConfig buildConfiguration(Map<String, ?> platformConfig, String variant) {
// Query the Adopt api to get the "tip_version"
String helperRef = DEFAULTS_JSON['repository']['helper_ref']
def JobHelper = context.library(identifier: "openjdk-jenkins-helper@${helperRef}").JobHelper
context.println 'Querying Adoptium API for the JDK-Head number (tip_version)...'
def response = JobHelper.getAvailableReleases(context)
int headVersion = (int) response[('tip_version')]
context.println "Found Java Version Number: ${headVersion}"
if (javaToBuild == "jdk${headVersion}") {
javaToBuild = 'jdk'
}
Boolean isWeekly = (releaseType == "Weekly") ? true : false
def additionalNodeLabels = formAdditionalBuildNodeLabels(platformConfig, variant)
def additionalTestLabels = formAdditionalTestLabels(platformConfig, variant)
def archLabel = getArchLabel(platformConfig, variant)
def dockerImage = getDockerImage(platformConfig, variant)
def dockerArgs = getDockerArgs(platformConfig, variant)
def dockerFile = getDockerFile(platformConfig, variant)
def dockerNode = getDockerNode(platformConfig, variant)
def dockerRegistry = getDockerRegistry(platformConfig, variant)
def dockerCredential = getDockerCredential(platformConfig, variant)
def platformSpecificConfigPath = getPlatformSpecificConfigPath(platformConfig)
def buildArgs = getBuildArgs(platformConfig, variant)
if (additionalBuildArgs) {
buildArgs += ' ' + additionalBuildArgs
}
def enableReproducibleCompare = isEnableReproducibleCompare(platformConfig, variant)
def testList = getTestList(platformConfig, variant)
def dynamicTestsParameters = getDynamicParams(platformConfig, variant)
def dynamicList = dynamicTestsParameters.get('testLists')
def numMachines = dynamicTestsParameters.get('numMachines')
def platformCleanWorkspaceAfterBuild = getCleanWorkspaceAfterBuild(platformConfig)
// Always clean on mac due to https://github.com/adoptium/temurin-build/issues/1980
def cleanWorkspace = cleanWorkspaceBeforeBuild
if (platformConfig.os == 'mac') {
cleanWorkspace = true
}
def cleanWsAfter = cleanWorkspaceAfterBuild
if (platformCleanWorkspaceAfterBuild) {
// Platform override specified
cleanWsAfter = platformCleanWorkspaceAfterBuild
}
// We need to ensure that _adopt is stripped from any tags used in hotspot variant builds, as *_adopt tags do not exist upstream.
def adjustedScmReference = scmReference
if (variant.equals("hotspot")) {
adjustedScmReference = scmReference - ('_adopt')
}
return new IndividualBuildConfig(
JAVA_TO_BUILD: javaToBuild,
ARCHITECTURE: platformConfig.arch as String,
TARGET_OS: platformConfig.os as String,
VARIANT: variant,
TEST_LIST: testList,
DYNAMIC_LIST: dynamicList,
NUM_MACHINES: numMachines,
SCM_REF: adjustedScmReference,
BUILD_REF: buildReference,
CI_REF: ciReference,
HELPER_REF: helperReference,
AQA_REF: aqaReference,
AQA_AUTO_GEN: aqaAutoGen,
BUILD_ARGS: buildArgs,
NODE_LABEL: "${additionalNodeLabels}&&${platformConfig.os}&&${archLabel}",
ADDITIONAL_TEST_LABEL: "${additionalTestLabels}",
KEEP_TEST_REPORTDIR: keepTestReportDir,
ACTIVE_NODE_TIMEOUT: activeNodeTimeout,
CODEBUILD: platformConfig.codebuild as Boolean,
DOCKER_IMAGE: dockerImage,
DOCKER_ARGS: dockerArgs,
DOCKER_FILE: dockerFile,
DOCKER_NODE: dockerNode,
DOCKER_REGISTRY: dockerRegistry,
DOCKER_CREDENTIAL: dockerCredential,
PLATFORM_CONFIG_LOCATION: platformSpecificConfigPath,
CONFIGURE_ARGS: getConfigureArgs(platformConfig, additionalConfigureArgs, variant),
OVERRIDE_FILE_NAME_VERSION: overrideFileNameVersion,
USE_ADOPT_SHELL_SCRIPTS: useAdoptShellScripts,
ADDITIONAL_FILE_NAME_TAG: platformConfig.additionalFileNameTag as String,
JDK_BOOT_VERSION: platformConfig.bootJDK as String,
RELEASE: release,
WEEKLY: isWeekly,
PUBLISH_NAME: publishName,
ADOPT_BUILD_NUMBER: adoptBuildNumber,
ENABLE_REPRODUCIBLE_COMPARE: enableReproducibleCompare,
ENABLE_TESTS: enableTests,
ENABLE_TESTDYNAMICPARALLEL: enableTestDynamicParallel,
ENABLE_INSTALLERS: enableInstallers,
ENABLE_SIGNER: enableSigner,
CLEAN_WORKSPACE: cleanWorkspace,
CLEAN_WORKSPACE_AFTER: cleanWsAfter,
CLEAN_WORKSPACE_BUILD_OUTPUT_ONLY_AFTER: cleanWorkspaceBuildOutputAfterBuild
)
}
/*
Returns true if possibleMap is a Map. False otherwise.
*/
static isMap(possibleMap) {
return Map.isInstance(possibleMap)
}
/*
Retrieves the buildArgs attribute from the build configurations.
These eventually get passed to ./makejdk-any-platform.sh and make images.
*/
String getBuildArgs(Map<String, ?> configuration, variant) {
if (configuration.containsKey('buildArgs')) {
if (isMap(configuration.buildArgs)) {
Map<String, ?> buildArgs = configuration.buildArgs as Map<String, ?>
if (buildArgs.containsKey(variant)) {
return buildArgs.get(variant)
}
} else {
return configuration.buildArgs
}
}
return ''
}
/*
Get reproduciableCompare flag from the build configurations.
*/
Boolean isEnableReproducibleCompare(Map<String, ?> configuration, String variant) {
Boolean enableReproducibleCompare = DEFAULTS_JSON['testDetails']['enableReproducibleCompare'] as Boolean
if ( env.JOB_NAME.contains('pr-tester') || env.JOB_NAME.contains('release')) {
enableReproducibleCompare = false
} else {
if (configuration.containsKey('reproducibleCompare')) {
def reproducibleCompare
if (isMap(configuration.reproducibleCompare)) {
reproducibleCompare = (configuration.reproducibleCompare as Map).get(variant)
} else {
reproducibleCompare = configuration.reproducibleCompare
}
if (reproducibleCompare != null) {
enableReproducibleCompare = reproducibleCompare
}
}
}
return enableReproducibleCompare
}
/*
Get the list of tests to run from the build configurations.
We run different test categories depending on if this build is a release or nightly. This function parses and applies this to the individual build config.
*/
List<String> getTestList(Map<String, ?> configuration, String variant) {
List<String> testList = []
/*
* No test key or key value is test: false --- test disabled
* Key value is test: 'default' --- nightly build trigger 'nightly' test set, weekly build trigger 'weekly' or release build trigger 'release' test sets
* Key value is test: [customized map] specified nightly, weekly, release test lists
* Key value is test: [customized map] specified for different variant
*/
if (configuration.containsKey('test') && configuration.get('test')) {
def testJobType = 'nightly'
if (releaseType.startsWith('Weekly')) {
testJobType = 'weekly'
} else if (releaseType.equals('Release')){
testJobType = 'release'
}
if (isMap(configuration.test)) {
if (configuration.test.containsKey(variant)) {
//Test is enabled for the variant
if (configuration.test.get(variant)) {
def testObj = configuration.test.get(variant)
if (isMap(testObj)) {
if (testObj.containsKey(testJobType)) {
testList = (configuration.test as Map).get(testJobType) as List<String>
} else {
testList = getDefaultTestList(testJobType)
}
} else if (testObj instanceof List) {
testList = (configuration.test as Map).get(variant) as List<String>
} else {
testList = getDefaultTestList(testJobType)
}
}
} else {
if (configuration.test.containsKey(testJobType)) {
testList = (configuration.test as Map).get(testJobType) as List<String>
} else {
testList = getDefaultTestList(testJobType)
}
}
} else {
// Default to the test sets declared if one isn't set in the build configuration
testList = getDefaultTestList(testJobType)
}
}
testList.unique()
return testList
}
/*
Get default test list
*/
List<String> getDefaultTestList(String testJobType) {
final List<String> nightly = DEFAULTS_JSON['testDetails']['nightlyDefault']
final List<String> weekly = DEFAULTS_JSON['testDetails']['weeklyDefault']
final List<String> release = DEFAULTS_JSON['testDetails']['releaseDefault']
List<String> testList = []
if (testJobType == 'nightly') {
testList = nightly
} else if (testJobType == 'weekly') {
testList = weekly
} else {
testList = release
}
return testList
}
/*
Get the list of tests to dynamically run parallel builds from the build configurations.
This function parses and applies this to the individual build config.
*/
Map<String, ?> getDynamicParams(Map<String, ?> configuration, String variant) {
List<String> testLists = []
List<String> numMachines = []
def testDynamicMap
if (configuration.containsKey('testDynamic')) {
// fetch from buildConfigurations for target
// testDynamic could be map, list or boolean
if (configuration.containsKey('testDynamic') && configuration.get('testDynamic')) {
// fetch variant options
testDynamicMap = configuration.get('testDynamic').get(variant)
} else {
// fetch generic options
testDynamicMap = configuration.get('testDynamic')
}
} else if (DEFAULTS_JSON['testDetails']['defaultDynamicParas']) {
// fetch default options
testDynamicMap = DEFAULTS_JSON['testDetails']['defaultDynamicParas']
}
if (testDynamicMap) {
if (testDynamicMap.containsKey('testLists')) {
testLists.addAll(testDynamicMap.get('testLists'))
}
if (testDynamicMap.containsKey('numMachines')) {
// populate the list of number of machines per tests
if (List.isInstance(testDynamicMap.get('numMachines'))) {
// the size of the numMachines List should match the testLists size
// otherwize throw an error
// e.g.
// testLists = ['extended.openjdk', 'extended.jck', 'special.jck']
// numMachines = ['3', '2', '5']
numMachines.addAll(testDynamicMap.get('numMachines'))
if (numMachines.size() < testLists.size()) {
throw new Exception("Configuration error for dynamic testing: missmatch between dymanic parallel test targets testListing: ${testListing} and numMachines: ${numMachines}")
}
} else {
if (!testLists.isEmpty()) {
// work-around for numMachines as a String
// populate the List<String> number of machines with duplicates
numMachines.addAll(Collections.nCopies(testLists.size(), "${testDynamicMap.get('numMachines')}"))
}
}
}
}
return ['testLists': testLists, 'numMachines': numMachines]
}
/*
Get the cleanWorkspaceAfterBuild override for this platform configuration
*/
Boolean getCleanWorkspaceAfterBuild(Map<String, ?> configuration) {
Boolean cleanWorkspaceAfterBuild = null
if (configuration.containsKey('cleanWorkspaceAfterBuild') && configuration.get('cleanWorkspaceAfterBuild')) {
cleanWorkspaceAfterBuild = configuration.cleanWorkspaceAfterBuild as Boolean
}
return cleanWorkspaceAfterBuild
}
/*
Parses and applies the dockerExcludes parameter.
Any platforms/variants that are declared in this parameter are marked as excluded from docker building via this function. Even if they have a docker image or file declared in the build configurations!
*/
def dockerOverride(Map<String, ?> configuration, String variant) {
Boolean overrideDocker = false
if (dockerExcludes == { }) {
return overrideDocker
}
String stringArch = configuration.arch as String
String stringOs = configuration.os as String
String estimatedKey = stringArch + stringOs.capitalize()
if (dockerExcludes.containsKey(estimatedKey)) {
if (dockerExcludes[estimatedKey].contains(variant)) {
overrideDocker = true
}
}
return overrideDocker
}
def getArchLabel(Map<String, ?> configuration, String variant) {
// Default to arch
def archLabelVal = configuration.arch
// Workaround for cross compiled architectures
if (configuration.containsKey('crossCompile')) {
def configArchLabelVal
if (isMap(configuration.crossCompile)) {
configArchLabelVal = (configuration.crossCompile as Map<String, ?>).get(variant)
} else {
configArchLabelVal = configuration.crossCompile
}
if (configArchLabelVal != null) {
archLabelVal = configArchLabelVal
}
}
return archLabelVal
}
/*
Retrieves the dockerImage attribute from the build configurations.
This specifies the DockerHub org and image to pull or build in case we don't have one stored in this repository.
If this isn't specified, the openjdk_build_pipeline.groovy will assume we are not building the jdk inside of a container.
*/
def getDockerImage(Map<String, ?> configuration, String variant) {
def dockerImageValue = ''
if (configuration.containsKey('dockerImage') && !dockerOverride(configuration, variant)) {
if (isMap(configuration.dockerImage)) {
dockerImageValue = (configuration.dockerImage as Map<String, ?>).get(variant)
} else {
dockerImageValue = configuration.dockerImage
}
}
return dockerImageValue
}
def getDockerArgs(Map<String, ?> configuration, String variant) {
def dockerArgsValue = ''
if (configuration.containsKey('dockerArgs') && !dockerOverride(configuration, variant)) {
if (isMap(configuration.dockerArgs)) {
dockerArgsValue = (configuration.dockerArgs as Map<String, ?>).get(variant)
} else {
dockerArgsValue = configuration.dockerArgs
}
}
return dockerArgsValue
}
/*
Retrieves the dockerFile attribute from the build configurations.
This specifies the path of the dockerFile relative to this repository.
If a dockerFile is not specified, the openjdk_build_pipeline.groovy will attempt to pull one from DockerHub.
*/
def getDockerFile(Map<String, ?> configuration, String variant) {
def dockerFileValue = ''
if (configuration.containsKey('dockerFile') && !dockerOverride(configuration, variant)) {
if (isMap(configuration.dockerFile)) {
dockerFileValue = (configuration.dockerFile as Map<String, ?>).get(variant)
} else {
dockerFileValue = configuration.dockerFile
}
}
return dockerFileValue
}
/*
Retrieves the dockerNode attribute from the build configurations.
This determines what the additional label will be if we are building the jdk in a docker container.
Defaults to &&dockerBuild in openjdk_build_pipeline.groovy if it's not supplied in the build configuration.
*/
def getDockerNode(Map<String, ?> configuration, String variant) {
def dockerNodeValue = ''
if (configuration.containsKey('dockerNode')) {
if (isMap(configuration.dockerNode)) {
dockerNodeValue = (configuration.dockerNode as Map<String, ?>).get(variant)
} else {
dockerNodeValue = configuration.dockerNode
}
}
return dockerNodeValue
}
/*
Retrieves the dockerRegistry attribute from the build configurations.
This is used to pull dockerImage from a custom registry.
If not specified, defaults to '' which will be DockerHub.
*/
def getDockerRegistry(Map<String, ?> configuration, String variant) {
def dockerRegistryValue = ''
if (configuration.containsKey('dockerRegistry')) {
if (isMap(configuration.dockerRegistry)) {
dockerRegistryValue = (configuration.dockerRegistry as Map<String, ?>).get(variant)
} else {
dockerRegistryValue = configuration.dockerRegistry
}
}
return dockerRegistryValue
}
/*
Retrieves the dockerCredential attribute from the build configurations.
If used, this will wrap the docker pull with a docker login.
*/
def getDockerCredential(Map<String, ?> configuration, String variant) {
def dockerCredentialValue = ''
if (configuration.containsKey('dockerCredential')) {
if (isMap(configuration.dockerCredential)) {
dockerCredentialValue = (configuration.dockerCredential as Map<String, ?>).get(variant)
} else {
dockerCredentialValue = configuration.dockerCredential
}
}
return dockerCredentialValue
}
/*
Retrieves the platformSpecificConfigPath from the build configurations.
This determines where the location of the operating system setup files are in comparison to the repository root.
The param is formatted like this because we need to download and source the file from the bash scripts.
*/
def getPlatformSpecificConfigPath(Map<String, ?> configuration) {
def splitUserUrl = ((String)DEFAULTS_JSON['repository']['build_url']) - ('.git').split('/')
// e.g. https://github.com/adoptium/temurin-build.git will produce adoptium/temurin-build
String userOrgRepo = "${splitUserUrl[splitUserUrl.size() - 2]}/${splitUserUrl[splitUserUrl.size() - 1]}"
def buildRef = configuration.buildRef ?: DEFAULTS_JSON['repository']['build_branch']
// e.g. adoptium/temurin-build/master/build-farm/platform-specific-configurations
def platformSpecificConfigPath = "${userOrgRepo}/${buildRef}/${DEFAULTS_JSON['configDirectories']['platform']}"
if (configuration.containsKey('platformSpecificConfigPath')) {
// e.g. adoptium/temurin-build/master/build-farm/platform-specific-configurations.linux.sh
platformSpecificConfigPath = "${userOrgRepo}/${buildRef}/${configuration.platformSpecificConfigPath}"
}
return platformSpecificConfigPath
}
/*
Constructs any necessary additional build labels from the build configurations.
This builds up a node param string that defines what nodes are eligible to run the given job.
*/
def formAdditionalBuildNodeLabels(Map<String, ?> configuration, String variant) {
def buildTag = 'build'
def labels = "${buildTag}"
if (configuration.containsKey('additionalNodeLabels')) {
def additionalNodeLabels
if (isMap(configuration.additionalNodeLabels)) {
additionalNodeLabels = (configuration.additionalNodeLabels as Map<String, ?>).get(variant)
} else {
additionalNodeLabels = configuration.additionalNodeLabels
}
if (additionalNodeLabels != null) {
labels = "${additionalNodeLabels}&&${labels}"
}
}
return labels
}
/**
* Builds up additional test labels
* @param configuration
* @param variant
* @return
*/
def formAdditionalTestLabels(Map<String, ?> configuration, String variant) {
def labels = ''
if (configuration.containsKey('additionalTestLabels')) {
def additionalTestLabels
if (isMap(configuration.additionalTestLabels)) {
additionalTestLabels = (configuration.additionalTestLabels as Map<String, ?>).get(variant)
} else {
additionalTestLabels = configuration.additionalTestLabels
}
if (additionalTestLabels != null) {
labels = "${additionalTestLabels}"
}
}
return labels
}
/*
Retrieves the configureArgs attribute from the build configurations.
These eventually get passed to ./makejdk-any-platform.sh and bash configure.
*/
static String getConfigureArgs(Map<String, ?> configuration, String additionalConfigureArgs, String variant) {
def configureArgs = ''
if (configuration.containsKey('configureArgs')) {
def configConfigureArgs
if (isMap(configuration.configureArgs)) {
configConfigureArgs = (configuration.configureArgs as Map<String, ?>).get(variant)
} else {
configConfigureArgs = configuration.configureArgs
}
if (configConfigureArgs != null) {
configureArgs += configConfigureArgs
}
}
if (additionalConfigureArgs) {
if (configureArgs) {
configureArgs += ' '
}
configureArgs += additionalConfigureArgs
}
return configureArgs
}
/*
Imports the build configurations for the target version based off its key and variant.
E.g. { "x64Linux" : [ "hotspot", "openj9" ] }
*/
Map<String, IndividualBuildConfig> getJobConfigurations() {
Map<String, IndividualBuildConfig> jobConfigurations = [:]
//Parse nightly config passed to jenkins job
targetConfigurations
.each { target ->
//For each requested build type, generate a configuration
if (buildConfigurations.containsKey(target.key)) {
def platformConfig = buildConfigurations.get(target.key) as Map<String, ?>
target.value.each { variant ->
// Construct a rough job name from the build config and variant
String name = "${platformConfig.os}-${platformConfig.arch}-${variant}"
if (platformConfig.containsKey('additionalFileNameTag')) {
name += "-${platformConfig.additionalFileNameTag}"
}
// Fill in the name's value with an IndividualBuildConfig
jobConfigurations[name] = buildConfiguration(platformConfig, variant)
}
}
}
return jobConfigurations
}
/*
Returns the JDK head number from the Adopt API
*/
Integer getHeadVersionNumber() {
try {
context.timeout(time: pipelineTimeouts.API_REQUEST_TIMEOUT, unit: 'HOURS') {
// Query the Adopt api to get the "tip_version"
String helperRef = DEFAULTS_JSON['repository']['helper_ref']
def JobHelper = context.library(identifier: "openjdk-jenkins-helper@${helperRef}").JobHelper
context.println 'Querying Adopt Api for the JDK-Head number (tip_version)...'
def response = JobHelper.getAvailableReleases(context)
return (int) response[('tip_version')]
}
} catch (FlowInterruptedException e) {
throw new Exception("[ERROR] Adopt API Request timeout (${pipelineTimeouts.API_REQUEST_TIMEOUT} HOURS) has been reached. Exiting...")
}
}
/*
Returns the java version number for this pipeline (e.g. 8, 11, 15, 16)
*/
Integer getJavaVersionNumber() {
// version should be something like "jdk8u" or "jdk" for HEAD
Matcher matcher = javaToBuild =~ /.*?(?<version>\d+).*?/
if (matcher.matches()) {
return Integer.parseInt(matcher.group('version'))
} else if ('jdk'.equalsIgnoreCase(javaToBuild.trim())) {
return getHeadVersionNumber()
} else {
throw new Exception("Failed to read java version '${javaToBuild}'")
}
}
/*
Returns the release tool version string to use in the release job
*/
def determineReleaseToolRepoVersion() {
def number = getJavaVersionNumber()
return "jdk${number}"
}
/*
Returns the downstream build job's type by checking job folder's path
can be "evaluation" or "release" or null (in this case it is for the nightly or pr-tester)
*/
def getBuildJobType() {
if (currentBuild.fullProjectName.contains("evaluation")){
return "evaluation"
} else if (currentBuild.fullProjectName.contains("release")) {
return "release"
}
return
}
/*
Returns the job name of the target downstream job
*/
def getJobName(displayName) {
// if getBuildJobType return null, it is nightly or pr-tester
def buildJobType = getBuildJobType() ? getBuildJobType() + "-" : ""
return "${javaToBuild}-${buildJobType}${displayName}"
}
/*
Returns the jenkins folder of where we assume the downstream build jobs have been regenerated
e.g:
nightly: build-scripts/jobs/jdk11u/jdk11u-linux-aarch64-temurin
evaluation: build-scripts/jobs/evaluation/jobs/jdk17u/jdk17u-evaluation-mac-x64-openj9
release: build-scripts/jobs/release/jobs/jdk21/jdk21-release-aix-ppc64-temurin
*/
def getJobFolder() {
def parentDir = currentBuild.fullProjectName.substring(0, currentBuild.fullProjectName.lastIndexOf('/'))
def buildJobType = getBuildJobType() ? "/jobs/" + getBuildJobType() : ""
return parentDir + buildJobType + '/jobs/' + javaToBuild
}
/*
Ensures that we don't release multiple variants at the same time
Unless this is the weekend weekly release build that won't have a publishName
*/
def checkConfigIsSane(Map<String, IndividualBuildConfig> jobConfigurations) {
if (release && publishName) {
// Doing a release
def variants = jobConfigurations
.values()
.collect({ it.VARIANT })
.unique()
if (variants.size() > 1) {
context.error('Trying to release multiple variants at the same time, this is unusual')
return false
}
}
return true
}
/*
Call job to push artifacts to github. Usually it's only executed on a nightly build
*/
def publishBinary(IndividualBuildConfig config=null) {
def timestamp = new Date().format('yyyy-MM-dd-HH-mm', TimeZone.getTimeZone('UTC'))
def javaVersion=determineReleaseToolRepoVersion()
def stageName = 'BETA publish'
def releaseComment = 'BETA publish'
def tag = "${javaToBuild}-${timestamp}"
if (publishName) {
tag = publishName
}
def osArch = 'all available OS&ARCHs'
def artifactsToCopy = '**/temurin/*.tar.gz,**/temurin/*.zip,**/temurin/*.sha256.txt,**/temurin/*.msi,**/temurin/*.pkg,**/temurin/*.json,**/temurin/*.sig'
def dryRun = false
def String releaseToolUrl = "${context.HUDSON_URL}job/build-scripts/job/release/job/refactor_openjdk_release_tool/parambuild?"
if ( config != null ) {
def prefixOfArtifactsToCopy = "**/${config.TARGET_OS}/${config.ARCHITECTURE}/${config.VARIANT}"
artifactsToCopy = "${prefixOfArtifactsToCopy}/*.tar.gz,${prefixOfArtifactsToCopy}/*.zip,${prefixOfArtifactsToCopy}/*.sha256.txt,${prefixOfArtifactsToCopy}/*.msi,${prefixOfArtifactsToCopy}/*.pkg,${prefixOfArtifactsToCopy}/*.json,${prefixOfArtifactsToCopy}/*.sig"
osArch = "${config.TARGET_OS} ${config.ARCHITECTURE}"
dryRun = true
timestamp = ''
stageName = 'Dry run RELEASE publish'
}
context.stage("${stageName}") {
context.println "${stageName} with publishName: ${tag} ${osArch}"
def releaseJob = context.build job: 'build-scripts/release/refactor_openjdk_release_tool',
parameters: [
['$class': 'BooleanParameterValue', name: 'RELEASE', value: release],
['$class': 'BooleanParameterValue', name: 'DRY_RUN', value: dryRun],
context.string(name: 'TAG', value: tag),
context.string(name: 'TIMESTAMP', value: timestamp),
context.string(name: 'UPSTREAM_JOB_NAME', value: env.JOB_NAME),
context.string(name: 'UPSTREAM_JOB_NUMBER', value: "${currentBuild.getNumber()}"),
context.string(name: 'VERSION', value: javaVersion),
context.string(name: 'ARTIFACTS_TO_COPY', value: "${artifactsToCopy}")
]
if (release) {
releaseComment = 'RELEASE Publish'
if (releaseJob.getResult()) {
releaseToolUrl += 'DRY_RUN=false&'
} else {
releaseToolUrl += 'DRY_RUN=true&'
releaseComment = 'Dry run RELEASE Publish'
}
}
}
releaseToolUrl += "VERSION=${javaVersion}&RELEASE=${release}&UPSTREAM_JOB_NUMBER=${currentBuild.getNumber()}"
tag = URLEncoder.encode(tag, 'UTF-8')
artifactsToCopy = URLEncoder.encode(artifactsToCopy, 'UTF-8')
def urlJobName = URLEncoder.encode("${env.JOB_NAME}", 'UTF-8')
releaseToolUrl += "&TAG=${tag}&UPSTREAM_JOB_NAME=${urlJobName}&ARTIFACTS_TO_COPY=${artifactsToCopy}"
context.echo "return releaseToolUrl is ${releaseToolUrl}"
return ["${releaseToolUrl}", "${releaseComment}"]
}
/*
Main function. This is what is executed remotely via the [release-|evaluation-]openjdkxx-pipeline and pr-tester jobs
Running in the *openjdkX-pipeline
*/
@SuppressWarnings('unused')
def doBuild() {
context.timestamps {
Map<String, IndividualBuildConfig> jobConfigurations = getJobConfigurations()
if (!checkConfigIsSane(jobConfigurations)) {
return
}
def releaseSummary
if ( publish || release ) {
releaseSummary = context.manager.createSummary('next.svg')
if (release) {
if (publishName) {
// Keep Jenkins release logs for real releases
currentBuild.setKeepLog(keepReleaseLogs)
currentBuild.setDisplayName(publishName)
}
releaseSummary.appendText('<b>RELEASE PUBLISH BINARIES:</b><ul>', false)
} else {
releaseSummary.appendText('<b>NIGHTLY PUBLISH BINARIES:</b><ul>', false)
}
}
def jobs = [:]
// Special case for JDK head where the jobs are called jdk-os-arch-variant
if (javaToBuild == "jdk${getHeadVersionNumber()}") {
javaToBuild = 'jdk'
}
context.echo "Java: ${javaToBuild}"
context.echo "OS: ${targetConfigurations}"
context.echo "Enable reproducible compare: ${enableReproducibleCompare}"
context.echo "Enable tests: ${enableTests}"
context.echo "Enable Installers: ${enableInstallers}"
context.echo "Enable Signer: ${enableSigner}"
context.echo "Use Adopt's Scripts: ${useAdoptShellScripts}"
context.echo "Publish: ${publish}"
context.echo "Release: ${release}"
context.echo "OpenJDK Tag/Branch name: ${scmReference}"
context.echo "Temurin-build Tag/Branch name: ${buildReference}"
context.echo "Ci-jenkins-pipeline Tag/Branch name: ${ciReference}"
context.echo "Jenkins-helper Tag/Branch name: ${helperReference}"
context.echo "AQA tests Release/Branch name: ${aqaReference}"
context.echo "Force auto generate AQA test jobs: ${aqaAutoGen}"
context.echo "Keep test reportdir: ${keepTestReportDir}"
context.echo "Keep release logs: ${keepReleaseLogs}"
jobConfigurations.each { configuration ->
jobs[configuration.key] = {
IndividualBuildConfig config = configuration.value
// jdk21-linux-x64-temurin
def jobTopName = getJobName(configuration.key)
def jobFolder = getJobFolder()
/*
build-scripts/jobs/jdk21/jdk21-linux-x64-temurin for nightly
build-scripts/evaluation/jobs/jdk21/jdk21-evaluation-linux-aarch64-hotspot for evaluation
*/
def downstreamJobName = "${jobFolder}/${jobTopName}"
context.echo 'build name ' + downstreamJobName
context.catchError {
// Execute build job for configuration i.e jdk11u/job/jdk11u-linux-x64-hotspot
context.stage(configuration.key) {
// Triggering downstream job ${downstreamJobName}
def buildJobParams = config.toBuildParams()
// Pass down constructed USER_REMOTE_CONFIGS if useAdoptShellScripts is false
// But not for pr-tester as it generates target jobs with required remoteConfigs
if (!useAdoptShellScripts && !env.JOB_NAME.contains('pr-tester')) {
def user_ci_branch = ciReference ?: DEFAULTS_JSON["repository"]["pipeline_branch"]
def user_ci_url = DEFAULTS_JSON["repository"]["pipeline_url"]
Map<String, ?> USER_REMOTE_CONFIGS = ["branch": user_ci_branch, "remotes": ["url": user_ci_url]]
buildJobParams.add(['$class': 'TextParameterValue', name: 'USER_REMOTE_CONFIGS', value: JsonOutput.prettyPrint(JsonOutput.toJson(USER_REMOTE_CONFIGS)) ])
}
// Pass down DEFAULTS_JSON
buildJobParams.add(['$class': 'TextParameterValue', name: 'DEFAULTS_JSON', value: JsonOutput.prettyPrint(JsonOutput.toJson(DEFAULTS_JSON)) ])
def copyArtifactSuccess = false
def downstreamJob = context.build job: downstreamJobName, propagate: false, parameters: buildJobParams
context.println "Downstream job ${downstreamJobName} completed, result = "+downstreamJob.getResult()
// copy artifacts from build regardless of job result
context.println '[NODE SHIFT] MOVING INTO CONTROLLER NODE...'
context.node('worker') {
context.catchError(message: "Error during copy and archive artifacts for build job: ${downstreamJobName}") {
//Remove the previous artifacts
try {
context.timeout(time: pipelineTimeouts.REMOVE_ARTIFACTS_TIMEOUT, unit: 'HOURS') {
if ( ! ( "${config.TARGET_OS}" ==~ /^[A-Za-z0-9\/\.\-_]*$/ ) ||
! ( "${config.ARCHITECTURE}" ==~ /^[A-Za-z0-9\/\.\-_]*$/ ) ||
! ( "${config.VARIANT}" ==~ /^[A-Za-z0-9\/\.\-_]*$/ ) ) {
throw new Exception('[ERROR] Dubious character in TARGET_OS, ARCHITECTURE or VARIANT - aborting')
}
context.sh "rm -rf target/${config.TARGET_OS}/${config.ARCHITECTURE}/${config.VARIANT}/"
}
} catch (FlowInterruptedException e) {
throw new Exception("[ERROR] Previous artifact removal timeout (${pipelineTimeouts.REMOVE_ARTIFACTS_TIMEOUT} HOURS) for ${downstreamJobName} has been reached. Exiting...")
}
try {
context.timeout(time: pipelineTimeouts.COPY_ARTIFACTS_TIMEOUT, unit: 'HOURS') {
context.copyArtifacts(
projectName: downstreamJobName,
selector: context.specific("${downstreamJob.getNumber()}"),
filter: 'workspace/target/*',
fingerprintArtifacts: true,
target: "target/${config.TARGET_OS}/${config.ARCHITECTURE}/${config.VARIANT}/",
flatten: true
)
context.copyArtifacts(
projectName: downstreamJobName,
selector: context.specific("${downstreamJob.getNumber()}"),
filter: 'workspace/target/AQAvitTaps/*.tap',
fingerprintArtifacts: true,
target: "target/${config.TARGET_OS}/${config.ARCHITECTURE}/${config.VARIANT}/AQAvitTaps/",
flatten: true,
optional: true
)
}
} catch (FlowInterruptedException e) {
throw new Exception("[ERROR] Copy artifact timeout (${pipelineTimeouts.COPY_ARTIFACTS_TIMEOUT} HOURS) for ${downstreamJobName} has been reached. Exiting...")
}
// Checksum
context.sh 'for file in $(ls target/*/*/*/*.tar.gz target/*/*/*/*.zip); do sha256sum "$file" > $file.sha256.txt ; done'
// Archive in Jenkins
try {
context.timeout(time: pipelineTimeouts.ARCHIVE_ARTIFACTS_TIMEOUT, unit: 'HOURS') {
context.archiveArtifacts artifacts: "target/${config.TARGET_OS}/${config.ARCHITECTURE}/${config.VARIANT}/**/*"
}
} catch (FlowInterruptedException e) {
throw new Exception("[ERROR] Archive artifact timeout (${pipelineTimeouts.ARCHIVE_ARTIFACTS_TIMEOUT} HOURS) for ${downstreamJobName}has been reached. Exiting...")
}
// Archive tap files as a single tar file
context.sh "find . -type f -name '*.tap' -exec tar -czf AQAvitTapFiles.tar.gz {} + "
try {
context.timeout(time: pipelineTimeouts.ARCHIVE_ARTIFACTS_TIMEOUT, unit: 'HOURS') {
context.archiveArtifacts artifacts: "AQAvitTapFiles.tar.gz"
}
} catch (FlowInterruptedException e) {
throw new Exception("[ERROR] Archive AQAvitTapFiles.tar.gz timeout Exiting...")
}
copyArtifactSuccess = true
if (release) {
def (String releaseToolUrl, String releaseComment) = publishBinary(config)
releaseSummary.appendText("<li><a href=${releaseToolUrl}> ${releaseComment} ${config.VARIANT} ${publishName} ${config.TARGET_OS} ${config.ARCHITECTURE}</a></li>")
}
}
}
context.println '[NODE SHIFT] OUT OF CONTROLLER NODE!'
if (propagateFailures) {
String previousPipelineStatus = currentBuild.result
context.println("Propagating downstream job result: ${downstreamJobName}, Result: "+downstreamJob.getResult()+" CopyArtifactsSuccess: "+copyArtifactSuccess)
if (copyArtifactSuccess) {
// currentBuild.result only allows itself to be set if the new status is worse than its current status.
// So FAILURE overrides UNSTABLE, and UNSTABLE overrides SUCCESS.
context.println("Attempting to set pipeline result to \""+downstreamJob.getResult()+"\".")
currentBuild.result = downstreamJob.getResult()
} else {
context.println("Attempting to set pipeline result to \"FAILURE\".")
currentBuild.result = 'FAILURE'