-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathutil.groovy
More file actions
2619 lines (2375 loc) · 62.6 KB
/
util.groovy
File metadata and controls
2619 lines (2375 loc) · 62.6 KB
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
import java.nio.file.Path
import java.time.Instant
import java.time.format.DateTimeFormatter
import java.time.ZoneId
import groovy.transform.Field
import java.security.MessageDigest
/**
* Remove leading whitespace from a multi-line String (probably a shellscript).
*/
@NonCPS
def String dedent(String text) {
if (text == null) {
return null
}
text.replaceFirst("\n","").stripIndent()
}
/**
* Thin wrapper around {@code sh} step that strips leading whitspace.
*/
def void posixSh(script) {
script = dedent(script)
sh shebangerize(script, '/bin/sh -xe')
}
/**
* Thin wrapper around {@code sh} step that strips leading whitspace.
*/
def void bash(script) {
script = dedent(script)
sh shebangerize(script, '/bin/bash -xe')
}
/**
* Prepend a shebang to a String that does not already have one.
*
* @param script String Text to prepend a shebang to
* @return shebangerized String
*/
@NonCPS
def String shebangerize(String script, String prog = '/bin/sh -xe') {
if (!script.startsWith('#!')) {
script = "#!${prog}\n${script}"
}
script
}
/**
* Hash a String using the SHA1 algorithm.
*
* @param path String representing the path to be hashed
* @return hashed path String
*/
@NonCPS
def String hashpath(String path) {
def digest = MessageDigest.getInstance('SHA-1')
digest.update(path.bytes)
def hashpathstr = digest.digest().encodeHex().toString()
return hashpathstr
}
/**
* Build a docker image, constructing the `Dockerfile` from `config`.
*
* Example:
*
* util.buildImage(
* config: dockerfileText,
* tag: 'example/foo:bar',
* pull: true,
* )
*
* @param p Map
* @param p.config String literal text of Dockerfile (required)
* @param p.tag String name of tag to apply to generated image (required)
* @param p.pull Boolean always pull docker base image (optional)
*/
def void buildImage(Map p) {
requireMapKeys(p, [
'config',
'tag',
])
String config = p.config
String tag = p.tag
Boolean pull = p.pull ?: false
def opt = []
opt << "--pull=${pull}"
opt << '--build-arg D_USER="$(id -un)"'
opt << '--build-arg D_UID="$(id -u)"'
opt << '--build-arg D_GROUP="$(id -gn)"'
opt << '--build-arg D_GID="$(id -g)"'
opt << '--build-arg D_HOME="$HOME"'
opt << '--load'
opt << '.'
writeFile(file: 'Dockerfile', text: config)
docker.build(tag, opt.join(' '))
} // buildImage
/**
* Create a thin "wrapper" container around {@code image} to map uid/gid of
* the user invoking docker into the container.
*
* Example:
*
* util.wrapDockerImage(
* image: 'example/foo:bar',
* tag: 'example/foo:bar-local',
* pull: true,
* )
*
* @param p Map
* @param p.image String name of docker base image (required)
* @param p.tag String name of tag to apply to generated image
* @param p.pull Boolean always pull docker base image. Defaults to `false`
*/
def void wrapDockerImage(Map p) {
requireMapKeys(p, [
'image',
'tag',
])
String image = p.image
String tag = p.tag
Boolean pull = p.pull ?: false
def buildDir = 'docker'
def config = dedent("""
FROM ${image}
ARG D_USER
ARG D_UID
ARG D_GROUP
ARG D_GID
ARG D_HOME
USER root
RUN mkdir -p "\$(dirname \$D_HOME)"
RUN groupadd \$D_GROUP || echo \$D_GROUP already exist
RUN useradd -d \$D_HOME -g \$D_GROUP \$D_USER || echo \$D_USER already exist
USER \$D_USER
WORKDIR \$D_HOME
""")
// docker insists on recusrively checking file access under its execution
// path -- so run it from a dedicated dir
dir(buildDir) {
buildImage(
config: config,
tag: tag,
pull: pull,
)
deleteDir()
}
} // wrapDockerImage
/**
* Invoke block inside of a "wrapper" container. See: wrapDockerImage
*
* Example:
*
* util.insideDockerWrap(
* image: 'example/foo:bar',
* args: '-e HOME=/baz',
* pull: true,
* )
*
* @param p Map
* @param p.image String name of docker image (required)
* @param p.args String docker run args (optional)
* @param p.pull Boolean always pull docker image. Defaults to `false`
* @param run Closure Invoked inside of wrapper container
*/
def insideDockerWrap(Map p, Closure run) {
requireMapKeys(p, [
'image',
])
String image = p.image
String args = p.args ?: null
Boolean pull = p.pull ?: false
def imageLocal = "${image}-local"
wrapDockerImage(
image: image,
tag: imageLocal,
pull: pull,
)
docker.image(imageLocal).inside(args) { run() }
}
/**
* Join multiple String args togther with '/'s to resemble a filesystem path.
*/
// The groovy String#join method is not working under the security sandbox
// https://issues.jenkins-ci.org/browse/JENKINS-43484
@NonCPS
def String joinPath(String ... parts) {
String text = null
def n = parts.size()
parts.eachWithIndex { x, i ->
if (text == null) {
text = x
} else {
text += x
}
if (i < (n - 1)) {
text += '/'
}
}
return text
} // joinPath
/**
* Serialize a Map to a JSON string and write it to a file.
*
* @param filename output filename
* @param data Map to serialize
*/
@NonCPS
def dumpJson(String filename, Map data) {
def json = new groovy.json.JsonBuilder(data)
def pretty = groovy.json.JsonOutput.prettyPrint(json.toString())
echo pretty
writeFile file: filename, text: pretty
}
/**
* Parse a JSON string.
*
* @param data String to parse.
* @return Object parsed JSON object
*/
@NonCPS
def slurpJson(String data) {
new groovy.json.JsonSlurperClassic().parseText(data)
}
/**
* Run a command, that is assumed to return JSON, and parse the stdout.
*
* @param script String shell script to execute.
* @return Object parsed JSON object
*/
def shJson(String script) {
def stdout = sh(returnStdout: true, script: script).trim()
slurpJson(stdout)
}
/**
* Create an EUPS distrib tag
*
* Example:
*
* util.runPublish(
* parameters: [
* EUPSPKG_SOURCE: 'git',
* MANIFEST_ID: manifestId,
* EUPS_TAG: eupsTag,
* PRODUCTS: products,
* ],
* )
*
* @param p Map
* @param p.job String job to trigger. Defaults to `release/run-publish`.
* @param p.parameters.EUPSPKG_SOURCE String
* @param p.parameters.MANIFEST_ID String
* @param p.parameters.EUPS_TAG String
* @param p.parameters.PRODUCTS String
* @param p.parameters.TIMEOUT String Defaults to `'1'`.
* @param p.parameters.SPLENV_REF String Optional
*/
def void runPublish(Map p) {
requireMapKeys(p, [
'parameters',
])
def useP = [
job: 'release/run-publish',
] + p
requireMapKeys(p.parameters, [
'EUPSPKG_SOURCE',
'MANIFEST_ID',
'EUPS_TAG',
'PRODUCTS',
])
useP.parameters = [
TIMEOUT: '1' // should be string
] + p.parameters
def jobParameters = [
string(name: 'EUPSPKG_SOURCE', value: useP.parameters.EUPSPKG_SOURCE),
string(name: 'MANIFEST_ID', value: useP.parameters.MANIFEST_ID),
string(name: 'EUPS_TAG', value: useP.parameters.EUPS_TAG),
string(name: 'PRODUCTS', value: useP.parameters.PRODUCTS),
string(name: 'TIMEOUT', value: useP.parameters.TIMEOUT.toString()),
]
// Optional parameter. Set 'em if you got 'em
if (useP.parameters.SPLENV_REF) {
jobParameters += string(name: 'SPLENV_REF', value: useP.parameters.SPLENV_REF)
}
if (useP.parameters.RUBINENV_VER) {
jobParameters += string(name: 'RUBINENV_VER', value: useP.parameters.RUBINENV_VER)
}
build(
job: useP.job,
parameters: jobParameters,
)
} // runPublish
/**
* Loads LSSTCAM test data
* @param buildDir where to run this
* @param testDir where to place the test data
* @return full path of test data
*/
def loadLSSTCamTestData(
String buildDir,
String testDir){
def gcp_repo = 'ghcr.io/lsst-dm/docker-gcloudcli'
def testdata // Assigning location of data later
dir(buildDir) {
def cwd = pwd()
testdata = "${cwd}/${testDir}"
dir(testdata){
withCredentials([
[
$class: 'StringBinding',
credentialsId: 'weka-bucket-secret',
variable: 'RCLONE_CONFIG_WEKA_SECRET_ACCESS_KEY'
], [
$class: 'StringBinding',
credentialsId: 'weka-access-key',
variable: 'RCLONE_CONFIG_WEKA_ACCESS_KEY_ID'
], [
$class: 'StringBinding',
credentialsId: 'weka-bucket-url',
variable: 'RCLONE_CONFIG_WEKA_ENDPOINT'
]]){
withEnv([
"RCLONE_CONFIG_WEKA_TYPE=s3",
"RCLONE_CONFIG_WEKA_PROVIDER=Other",
"LSSTCAM_BUCKET=rubin-ci-lsst/testdata_ci_lsstcam_m49"
]){
insideDockerWrap(
image: "${gcp_repo}:latest",
pull: true,
args: "-v ${cwd}:/home",
) {
bash """
rclone copy weka:"${LSSTCAM_BUCKET}" .
"""
}
}
}
}
}
return testdata
}
/**
* Loads Cache
* @param buildDir where to place the loaded file
* @param tag Which eups tag to load
*/
def loadCache(
String buildDir,
String tag="d_latest"
) {
def gcp_repo = 'ghcr.io/lsst-dm/docker-gcloudcli'
dir(buildDir) {
def cwd = pwd()
def ciDir = "${cwd}/ci-scripts"
dir(ciDir){
cloneCiScripts()
}
withCredentials([file(
credentialsId: 'gs-eups-push',
variable: 'GOOGLE_APPLICATION_CREDENTIALS'
)]) {
withEnv([
"SERVICEACCOUNT=eups-dev@prompt-proto.iam.gserviceaccount.com",
"DATE_TAG=${tag}",
]) {
insideDockerWrap(
image: "${gcp_repo}:latest",
pull: true,
args: "-v ${cwd}:/home",
) {
bash """
gcloud auth activate-service-account $SERVICEACCOUNT --key-file=$GOOGLE_APPLICATION_CREDENTIALS;
cd /home/ci-scripts
./loadlsststack.sh $DATE_TAG
"""
}
}
}
}
}
/**
* Save Cache
* @param buildDir where to place the loaded file
* @param tag Which eups tag to load
*/
def saveCache(
String tag="d_latest"
) {
def cwd = pwd()
bash '''
cd lsstsw
source bin/envconfig
conda install google-cloud-sdk
'''
withCredentials([file(
credentialsId: 'gs-eups-push',
variable: 'GOOGLE_APPLICATION_CREDENTIALS'
)]) {
withEnv([
"SERVICEACCOUNT=eups-dev@prompt-proto.iam.gserviceaccount.com",
"DATE_TAG=${tag}",
]) {
bash """
cd lsstsw
source bin/envconfig
gcloud auth activate-service-account $SERVICEACCOUNT --key-file=$GOOGLE_APPLICATION_CREDENTIALS;
cd ../ci-scripts
./backuplsststack.sh $DATE_TAG
"""
}
}
}
def labelPod(){
if (env.NODE_NAME && (env.NODE_NAME =~ /(manager|snowflake)/)) {
echo "Skipping pod label: ${env.NODE_NAME} is a static manager/snowflake node."
return
}
def JOB = env.JOB_NAME ? env.JOB_NAME.replace('/', '.') : "unknown"
def BUILD_NUMBER = env.BUILD_NUMBER ? env.BUILD_NUMBER.toString() : "unknown"
def labels = [
"jenkins-job": JOB,
"jenkins-build": BUILD_NUMBER
]
def upstream = currentBuild.upstreamBuilds
def upstreamFields = ""
if (upstream) {
def tJob = upstream[0].projectName.replace('/', '.')
def tNum = upstream[0].number.toString()
echo "Upstream Trigger: ${tJob} #${tNum}"
labels["triggered-by"] = tJob
labels["triggered-build"] = tNum
}
def jsonLabels = groovy.json.JsonOutput.toJson([metadata: [labels: labels]])
echo "jsonLabels: ${jsonLabels}"
writeFile file: '/tmp/patch.json', text: jsonLabels
bash '''
set -eu
set +x
SA=/var/run/secrets/kubernetes.io/serviceaccount
[ -r "$SA/token" ] || { echo "not in k8s; skipping pod label"; exit 0; }
NS=$(cat $SA/namespace)
POD=${HOSTNAME}
TOKEN=$(cat $SA/token)
CA=$SA/ca.crt
if curl -sS --fail \
--cacert "$CA" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/merge-patch+json" \
-X PATCH \
"https://kubernetes.default.svc/api/v1/namespaces/\$NS/pods/\$POD" \
--data-binary @/tmp/patch.json >/dev/null
then
echo "labeled for pod $NS/$POD"
else
echo "pod label skipped for $NS/$POD"
exit 0
fi
set -x
'''
}
/**
* Run a lsstsw build.
*
* @param lsstswConfig Map
* @param buildParams Map
* @param wipeout Delete all existing state before starting build
*/
def lsstswBuild(
Map lsstswConfig,
Map buildParams,
Boolean wipeout=false,
Boolean fetchCache=false,
Boolean cachelsstsw=false
) {
validateLsstswConfig(lsstswConfig)
def slug = lsstswConfigSlug(lsstswConfig)
buildParams = [
LSST_COMPILER: lsstswConfig.compiler,
LSST_JUNIT_PREFIX: slug,
LSST_PYTHON_VERSION: lsstswConfig.python,
LSST_SPLENV_REF: lsstswConfig.splenv_ref,
] + buildParams
def run = {
if (cachelsstsw){ // runs only if we want to cache the work
buildParams = [SCONSFLAGS: "--no-tests"] + buildParams
jenkinsWrapper(buildParams)
saveCache("d_latest")
} // if saveCacheRun
else {
jenkinsWrapper(buildParams)
} // else
} // run
def runDocker = {
insideDockerWrap(
image: lsstswConfig.image,
pull: true,
) {
withCredentials([[
$class: 'StringBinding',
credentialsId: 'github-api-token-checks',
variable: 'GITHUB_TOKEN'
]]){
run()
} // withCredentials
} // insideDockerWrap
} // runDocker
def runEnv = { doRun ->
// No longer need hashpath as slug is short enough
def buildDirHash = slug
try {
dir(buildDirHash) {
if (wipeout) {
deleteDir()
}
try {
timeout(time: 12, unit: 'HOURS') {
doRun()
} // timeout
} catch (e) {
if (!lsstswConfig.allow_fail) {
throw e
}
echo "giving up on build but suppressing error"
echo e.toString()
} // try
} // dir
} finally {
// needs to be called in the parent dir of jenkinsWrapper() in order to
// add the slug as a prefix to the archived files.
jenkinsWrapperPost(buildDirHash)
}
} // runEnv
def agent = lsstswConfig.label
def task = null
if (lsstswConfig.image) {
task = {
if (fetchCache){
loadCache(slug,"d_latest")
}
if (buildParams['CI_LSSTCAM']){
def testdatadir = loadLSSTCamTestData(slug,"lsstcam_testdata")
buildParams['LSSTCAM_TESTDATA_DIR'] = testdatadir
}
if (buildParams['CI_LSSTCAM'] && lsstswConfig.label != 'linux-64'){
return
}
runEnv(runDocker)
}
} else {
if (cachelsstsw || buildParams['CI_LSSTCAM']){
// runs only if we are not running a caching job. Since this isn't on
// docker we do not need to store cache for them.
return
}
else {
task = { runEnv(run) }
}
}
nodeWrap(agent) {
task()
} // nodeWrap
} // lsstswBuild
/**
* Run a build using ci-scripts/jenkins_wrapper.sh
*
* Required keys are listed below. Any additional keys will also be set as env
* vars.
* @param buildParams map
* @param buildParams.LSST_COMPILER String
* @param buildParams.LSST_PRODUCTS String
* @param buildParams.LSST_REFS String
* @param buildParams.LSST_SPLENV_REF String
*/
def void jenkinsWrapper(Map buildParams) {
// minimum set of required keys -- additional are allowed
requireMapKeys(buildParams, [
'LSST_COMPILER',
'LSST_PRODUCTS',
'LSST_REFS',
'LSST_SPLENV_REF',
])
def scipipe = scipipeConfig()
buildParams = [
// XXX this should be renamed in lsstsw to make it clear that its setting a
// github repo slug
REPOSFILE_REPO: scipipe.repos.github_repo,
] + buildParams
def cwd = pwd()
def homeDir = "${cwd}/home"
try {
dir('lsstsw') {
cloneLsstsw()
}
dir('ci-scripts') {
cloneCiScripts()
}
// workspace relative dir for dot files to prevent bleed through between
// jobs and subsequent builds.
emptyDirs([homeDir])
// cleanup *all* conda cached package info
[
'lsstsw/miniconda/conda-meta',
'lsstsw/miniconda/pkgs',
].each { it ->
dir(it) {
deleteDir()
}
}
// This file is needed for conda to know it has a base environment.
bash '''
mkdir -p lsstsw/miniconda/conda-meta
touch lsstsw/miniconda/conda-meta/history
'''
// This line uses k8s to set EUPSPKG_NJOBS
def njobs = 16
// Check if NODE_LABELS is set in the environment
def nodeLabels = env.NODE_LABELS
def buildEnv = [
"WORKSPACE=${cwd}",
"HOME=${homeDir}",
"EUPS_USERDATA=${homeDir}/.eups_userdata",
"EUPSPKG_NJOBS=${njobs}",
"NODE_LABELS=${nodeLabels}"
]
// Map -> List
buildParams.each { pair ->
buildEnv += pair.toString()
}
withEnv(buildEnv) {
bash './ci-scripts/jenkins_wrapper.sh'
}
} finally {
withEnv(["WORKSPACE=${cwd}"]) {
bash '''
if hash lsof 2>/dev/null; then
Z=$(lsof -d 200 -t)
if [[ ! -z $Z ]]; then
kill -9 $Z
fi
else
echo "lsof is missing; unable to kill rebuild related processes."
fi
rm -rf "${WORKSPACE}/lsstsw/stack/.lockDir"
'''
}
} // try
} // jenkinsWrapper
def jenkinsWrapperPost(String baseDir = null, boolean prepOnly = false) {
def lsstsw = 'lsstsw'
if (baseDir) {
lsstsw = "${baseDir}/${lsstsw}"
}
// note that archive does not like a leading `./`
def lsstsw_build_dir = "${lsstsw}/build"
def manifestPath = "${lsstsw_build_dir}/manifest.txt"
def statusPath = "${lsstsw_build_dir}/status.yaml"
def archive = [
manifestPath,
statusPath,
]
def archive_exclude = []
def record = [
'*.log',
'*.failed',
]
def failed_record = [
'_build.log',
'config.log',
'tests/.tests/pytest-*.xml',
'*.failed',
]
def failed_exclude = [
'tests/.tests/pytest-*.xml-cov-*.xml',
]
try {
if (!prepOnly) {
// if only prepare, skip junit
if (fileExists(statusPath)) {
def status = readYaml(file: statusPath)
def products = status['built']
// if there is a "failed_at" product, check it for a junit file too
if (status['failed_at']) {
products << status['failed_at']
}
def reports = []
products.each { item ->
def name = item['name']
def xml = "${lsstsw_build_dir}/${name}/tests/.tests/pytest-${name}.xml"
reports << xml
record.each { pattern ->
archive += "${lsstsw_build_dir}/${name}/**/${pattern}"
}
}
if (reports) {
// note that junit will ignore files with timestamps before the start
// of the build
junit([
testResults: reports.join(', '),
allowEmptyResults: true,
])
archive += reports
}
} else {
// handle case when there is no status.yaml due to timeouts
// match logs for products that are not part of the current build
failed_record.each { pattern ->
archive += "${lsstsw_build_dir}/**/${pattern}"
}
failed_exclude.each { pattern ->
archive_exclude += "${lsstsw_build_dir}/**/${pattern}"
}
}
}
} catch (e) {
// As a last resort, find product build dirs with a wildcard. This might
// match logs for products that _are not_ part of the current build.
record.each { pattern ->
archive += "${lsstsw_build_dir}/**/${pattern}"
}
throw e
} finally {
archiveArtifacts([
artifacts: archive.join(', '),
excludes: archive_exclude.join(', '),
allowEmptyArchive: true,
fingerprint: true
])
} // try
} // jenkinsWrapperPost
/**
* Parse manifest id out of a manifest.txt format String.
*
* @param manifest.txt as a String
* @return manifestId String
*/
@NonCPS
def String parseManifestId(String manifest) {
def m = manifest =~ /(?m)^BUILD=(b.*)/
m ? m[0][1] : null
}
/**
* Validate that required parameters were passed from the job and raise an
* error on any that are missing.
*
* @param rps List of required job parameters
*/
def void requireParams(List rps) {
rps.each { it ->
if (params.get(it) == null) {
error "${it} parameter is required"
}
}
}
/**
* Validate that required env vars were passed from the job and raise an
* error on any that are missing.
*
* @param rev List of required env vars
*/
def void requireEnvVars(List rev) {
// note that `env` isn't a map and #get doesn't work as expected
rev.each { it ->
if (env."${it}" == null) {
error "${it} environment variable is required"
}
}
}
/**
* Validate that map contains AT LEAST the specified list of keys and raise
* an error on any that are missing.
*
* @param check Map object to inspect
* @param key List of required map keys
*/
def void requireMapKeys(Map check, List keys) {
keys.each { k ->
if (! check.containsKey(k)) {
error "${k} key is missing from Map"
}
}
}
/**
* Empty directories by deleting and recreating them.
*
* @param dirs List of directories to empty
*/
def void emptyDirs(List eds) {
eds.each { d ->
dir(d) {
deleteDir()
// a file operation is needed to cause the dir() step to recreate the dir
writeFile(file: '.dummy', text: '')
}
}
}
/**
* Ensure directories exist and create any that are absent.
*
* @param dirs List of directories to ensure/create
*/
def void createDirs(List eds) {
eds.each { d ->
dir(d) {
// a file operation is needed to cause the dir() step to recreate the dir
writeFile(file: '.dummy', text: '')
}
}
}
/**
* XXX this method was developed during the validate_drp conversion to pipeline
* but is currently unusued. It has been preserved as it might be useful in
* other jobs.
*
* Write a copy of `manifest.txt`.
*
* @param rebuildId String `run-rebuild` build id.
* @param filename String Output filename.
*/
def void getManifest(String rebuildId, String filename) {
def manifest_artifact = 'lsstsw/build/manifest.txt'
def buildJob = 'release/run-rebuild'
step([$class: 'CopyArtifact',
projectName: buildJob,
filter: manifest_artifact,
selector: [
$class: 'SpecificBuildSelector',
buildNumber: rebuildId // wants a string
],
])
def manifest = readFile manifest_artifact
writeFile(file: filename, text: manifest)
} // getManifest
/**
* Run the `github-tag-release` script from `sqre-codekit` with parameters.
*
* Example:
*
* util.githubTagRelease(
* options: [
* '--dry-run': true,
* '--org': 'myorg'
* '--manifest': 'b1234',
* '--eups-tag': 'v999_0_0',
* ],
* args: ['999.0.0'],
* )
*
* @param p Map
* @param p.options Map CLI --<options>. Required. See `makeCliCmd`
* @param p.options.'--org' String Required.
* @param p.options.'--manifest' String Required.
* @param p.options.'--eups-tag' String Required.
* @param p.args List Eg., `[<git tag>]` Required.
*/
def void githubTagRelease(Map p) {
requireMapKeys(p, [
'args',
'options',
])
requireMapKeys(p.options, [
'--org',
'--manifest',
])
// compute versiondb url
def scipipe = scipipeConfig()
def vdbUrl = "https://raw.githubusercontent.com/${scipipe.versiondb.github_repo}/main/manifests"
// --eupstag-base-url is needed [when running under a "test" env] if git tags
// are being generated from an existing eups tag. If all workflows are
// changed to git tag from a versiondb manifest prior to the build, it may be
// removed.
def eupsUrl = scipipe.eups.base_url
def etbUrl = "${eupsUrl}/src/tags"
def prog = 'github-tag-release'
def defaultOptions = [
'--debug': true,
'--dry-run': true,
'--token': '$GITHUB_TOKEN',
'--user': 'sqreadmin',
'--email': 'sqre-admin@lists.lsst.org',
'--versiondb-base-url': vdbUrl,
'--eupstag-base-url': etbUrl,
'--allow-team': ['Data Management', 'DM Externals'],
'--external-team': 'DM Externals',
'--deny-team': 'DM Auxilliaries',
'--fail-fast': true,
]
runCodekitCmd(prog, defaultOptions, p.options, p.args)
} // githubTagRelease
/**
* Run the `github-tag-teams` script from `sqre-codekit` with parameters.
*
* Example:
*
* util.githubTagTeams(
* options: [
* '--dry-run': true,
* '--org': 'myorg',
* '--tag': '999.0.0',
* ],
* args: ['-r', 'v998.0.0.rc1']
* )
*
* @param p Map
* @param p.options Map CLI --<options>. Required. See `makeCliCmd`
* @param p.options.'--org' String Required.
* @param p.options.'--tag' String|List Required.
* @param p.args List Eg., `['-r', '<git refs>']` Optional.
*/