This repository has been archived by the owner on Nov 20, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 137
/
Utilities.groovy
1367 lines (1235 loc) · 52.5 KB
/
Utilities.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
package jobs.generation;
// Import the newer utility APIs, which we call in a few selection methods.
import org.dotnet.ci.util.Agents
class Utilities {
private static String DefaultBranchOrCommitPR = '${sha1}'
private static String DefaultBranchOrCommitPush = 'refs/heads/master'
private static String DefaultRefSpec = '+refs/pull/${ghprbPullId}/*:refs/remotes/origin/pr/${ghprbPullId}/*'
/**
* Get the folder name for a job.
*
* @param project Project name (e.g. dotnet/coreclr)
* @return Folder name for the project. Typically project name with / turned to _
*/
def static getFolderName(String project) {
return project.replace('/', '_')
}
/**
* Get the standard job name of a job given the base job name, project, whether the
* job is a PR or not, and an optional folder
*
* @param jobName Base name of the job
* @param isPR True if PR job, false otherwise
* @param folder (optional) If folder is specified, project is not used as the folder name
* @return Full job name. If folder prefix is specified,
*/
def static getFullJobName(String jobName, boolean isPR, String folder = '') {
return getFullJobName('', jobName, isPR, folder);
}
/**
* Get the standard job name of a job given the base job name, project, whether the
* job is a PR or not, and an optional folder
*
* @param project Project name (e.g. dotnet/coreclr)
* @param jobName Base name of the job
* @param isPR True if PR job, false otherwise
* @param folder (optional) If folder is specified, project is not used as the folder name
*
* @return Full job name. If folder prefix is specified,
*/
def static getFullJobName(String project, String jobName, boolean isPR, String folder = '') {
def jobSuffix = ''
if (isPR) {
jobSuffix = '_prtest'
}
def folderPrefix = ''
if (folder != '') {
folderPrefix = "${folder}/"
}
def fullJobName = ''
if (jobName == '') {
fullJobName = "${folderPrefix}innerloop${jobSuffix}"
}
else {
fullJobName = "${folderPrefix}${jobName}${jobSuffix}"
}
// Add the job to the overall jobs
JobReport.Report.addJob(fullJobName, isPR)
return fullJobName
}
/**
* Given the full project + repo name (e.g. dotnet/coreclr or Tools/DotNet-CI-Trusted), get the
* repo name (coreclr or DotNet-CI-Trusted).
*
* @param project Qualified project name
*
* @return Project name
*/
def static getRepoName(String project) {
return project.split('/')[1];
}
/**
* Given the full project + repo name e.g. dotnet/coreclr or Tools/DotNet-CI-Trusted), get the
* org or project name (dotnet or Tools).
*
*
* @param project Qualified project name
*
* @return Org (Github) or project (VSTS) name
*/
def static getOrgOrProjectName(String project) {
return project.split('/')[0];
}
/**
* Given the full repo name (e.g. dotnet/coreclr), get the
* repo name (coreclr). For VSTS, the project name is the repo name.
* This method is being deprecated, replaced by the clearer name of getRepoName
*
* @param project Qualified project name
*
* @return Project name (GitHub)
*/
@Deprecated
def static getProjectName(String project) {
return project.split('/')[1];
}
/**
* Given the full project name (e.g. dotnet/coreclr), get the
* org name (dotnet). This method is being deprecated, replaced by the clearer name of getOrgOrProjectName.
*
*
* @param project Qualified project name
*
* @return Org name (GitHub)
*/
@Deprecated
def static getOrgName(String project) {
return project.split('/')[0];
}
/**
* Retrieve the branch name without the
*
* @param rawBranchName Branch name, potentially with star slash or with refs slash heads slash
*
* @return Branch namer without star slash or refs slash heads slash
*/
def private static getBranchName(String rawBranchName) {
// Remove */ for branch name
String branchName = rawBranchName
if (rawBranchName.indexOf("*/") == 0) {
branchName = rawBranchName.substring(2)
}
else if (rawBranchName.indexOf("refs/heads/") == 0) { // remove refs/heads/ for branch name
branchName = rawBranchName.substring(11)
}
return branchName
}
/**
* Define a set of OS names which can resore and use managed build tools with a non-default RID.
* This controls the __PUBLISH_RID environment variable which affects init-tools behavior.
* Entries placed in this list are temporary, and should be removed when NuGet packages are published
* for the new OS.
*
* @param os The name of the operating system. Ex: Windows_NT, OSX.
*
* @return The name of an alternate RID to use while bootstrapping. If no RID mapping exists, returns null.
*/
def static getBoostrapPublishRid(def os) {
def bootstrapRidMap = [
'Ubuntu16.10': 'ubuntu.16.04-x64',
'Fedora24': 'fedora.23-x64'
]
return bootstrapRidMap.get(os, null)
}
/**
* Given the direct name of a label, set the machine affinity for a job. This override is useful for Helix queues
*
* @param job Job to set affinity for
* @param labelName Label to set the job to. THis is useful for helix.
*/
def static setMachineAffinity(def job, String labelName) {
job.with {
label(labelName)
}
}
/**
* Given the name of an OS, set the nodes that this job runs on.
*
* @param job Job to set affinity for
* @param osName Name of OS to to run on.
* @param version Version of the image.
*/
def static setMachineAffinity(def job, String osName, String version) {
String machineLabel = Agents.getAgentLabel(osName, version)
job.with {
label(machineLabel)
}
// These are non-functioning images (were TP5), for now just disable the jobs till all the
// groovy files can be updated.
if (osName.equals('Windows 10')) {
job.with {
disabled(true)
}
}
}
/**
* Performs standard job setup for a newly created job.
* Includes: Basic parameters, Git SCM, and standard options
*
* @param job Job to set up.
* @param project Name of project
* @param isPR True if job is PR job, false otherwise.
* @param branch If not a PR job, the branch that we should be building.
*/
def static standardJobSetup(def job, String project, boolean isPR, String branch) {
String defaultRefSpec = getDefaultRefSpec(null)
if (isPR) {
branch = getDefaultBranchOrCommitPR(null)
}
standardJobSetupEx(job, project, isPR, branch, defaultRefSpec)
}
/**
* Performs standard job setup for a newly created push job.
* Includes: Basic parameters, Git SCM, and standard options
*
* @param job Job to set up.
* @param project Name of project
* @param defaultBranch Branch to build on push.
*/
def static standardJobSetupPush(def job, String project, String defaultBranch = null) {
defaultBranch = getDefaultBranchOrCommitPush(defaultBranch);
standardJobSetupEx(job, project, false, defaultBranch, null);
}
/**
* Performs standard job setup for a newly created push job.
* Includes: Basic parameters, Git SCM, and standard options
*
* @param job Job to set up.
* @param project Name of project
* @param defaultBranchOrCommit Commit / branch to build.
* @param defaultRefSpec the refs that Jenkins must sync on a PR job
*/
def static standardJobSetupPR(def job, String project, String defaultBranchOrCommit = null, String defaultRefSpec = null) {
defaultBranchOrCommit = getDefaultBranchOrCommitPR(defaultBranchOrCommit)
defaultRefSpec = getDefaultRefSpec(defaultRefSpec)
standardJobSetupEx(job, project, true, defaultBranchOrCommit, defaultRefSpec)
}
/**
* Performs standard job setup for a newly created job.
* Includes: Basic parameters, Git SCM, and standard options
*
* @param job Job to set up.
* @param project Name of project
* @param isPR True if job is PR job, false otherwise.
* @param defaultBranchOrCommit Commit / branch to build.
* @param defaultRefSpec the refs that Jenkins must sync on a PR job
*/
def private static standardJobSetupEx(def job, String project, boolean isPR, String defaultBranchOrCommit, String defaultRefSpec) {
Utilities.addStandardParametersEx(job, project, isPR, defaultBranchOrCommit, defaultRefSpec)
Utilities.addScm(job, project, isPR)
Utilities.addStandardOptions(job, isPR)
addReproBuild(job)
}
/**
* Set the job timeout to the specified value.
*
* @param job Input job to modify
* @param jobTimeout Set the job timeout.
*/
def static setJobTimeout(def job, int jobTimeout) {
job.with {
wrappers {
timeout {
absolute(jobTimeout)
}
}
}
}
/**
* Adds a retention policy for artifacts
*
* @param job Job to modify
* @param isPR True if the job is a pull request job, false otherwise. If isPR is true,
* a more restrictive retention policy is use.
*/
def static addRetentionPolicy(def job, boolean isPR = false) {
job.with {
// Enable the log rotator
logRotator {
if (isPR) {
artifactDaysToKeep(5)
daysToKeep(7)
artifactNumToKeep(25)
numToKeep(150)
}
else {
artifactDaysToKeep(5)
daysToKeep(21)
artifactNumToKeep(25)
numToKeep(100)
}
}
}
}
/**
* Add standard options to a job.
*
* @param job Input job
* @param isPR True if the job is a pull request job, false otherwise.
*/
def static addStandardOptions(def job, def isPR = false) {
job.with {
// Enable concurrent builds
concurrentBuild()
// 5 second quiet period before the job can be scheduled
quietPeriod(5)
wrappers {
timestamps()
// Add a pre-build wipe-out
preBuildCleanup()
}
// Add a post-build cleanup. Order that this post-build step doesn't matter.
// It runs after everything.
publishers {
wsCleanup {
cleanWhenFailure(true)
cleanWhenAborted(true)
cleanWhenUnstable(true)
includePattern('**/*')
deleteDirectories(true)
}
}
if (job instanceof javaposse.jobdsl.dsl.jobs.BuildFlowJob) {
// Needs a workspace to avoid building other branches when not needed.
configure {
def buildNeedsWorkspace = it / 'buildNeedsWorkspace'
buildNeedsWorkspace.setValue('true')
}
}
}
// Add netci.groovy as default. Only add if it's a PR.
if (isPR) {
Utilities.addIgnoredPaths(job, ['netci.groovy']);
}
// Check Generate Disabled setting (for pr tests)
if (GenerationSettings.isTestGeneration()) {
job.with {
disabled(true)
}
}
Utilities.setJobTimeout(job, 120)
Utilities.addRetentionPolicy(job, isPR)
// Add a webhook to gather job events for Jenkins monitoring.
// The event hook is the id of the event hook URL in the Jenkins store
// Remove build event webhooks to remote source of test result API calls.
// Utilities.setBuildEventWebHooks(job, ['helix-int-notification-url', 'helix-prod-notification-url'])
}
def private static String joinStrings(Iterable<String> strings, String combineDelim) {
// Doing this instead of String.join because for whatever reason it doesn't resolve
// in CI.
def combinedString = ''
strings.each { str ->
if (combinedString == '') {
combinedString = str
}
else {
combinedString += combineDelim + str
}
}
return combinedString
}
/**
* Sets up the job to fast exit if only certain paths were edited.
* <p>
* If only files in the paths were changed (these paths are evaluated as globs)
* then the build exits early. Multiple calls to this function will replace the original
* ignored paths.
* </p>
*
* @param job Input job to modify
* @param ignoredPaths Array of strings containing paths that should be ignored
*/
def static addIgnoredPaths(def job, Iterable<String> ignoredPaths) {
// Doing this instead of String.join because for whatever reason it doesn't resolve
// in CI.
/*
def ignoredPathsString = Utilities.joinStrings(ignoredPaths, ',')
def foundNetCi = false
// Put in the raw configure object
job.with {
// Add option to ignore changes to netci.groovy when building
configure {
it / 'buildWrappers' / 'ruby-proxy-object' {
'ruby-object' ('ruby-class': 'Jenkins::Plugin::Proxies::BuildWrapper', pluginid: 'pathignore') {
pluginid(pluginid: 'pathignore', 'ruby-class': 'String', 'pathignore' )
object('ruby-class': 'PathignoreWrapper', pluginid: 'pathignore') {
ignored__paths(pluginid: 'pathignore', 'ruby-class': 'String', ignoredPathsString)
invert__ignore(pluginid: 'pathignore', 'ruby-class': 'FalseClass')
}
}
}
}
}
*/
}
/**
* Adds an auto-retry to a job
*/
def private static addJobRetry(def job) {
List<String> expressionsToRetry = [
'channel is already closed',
'Connection aborted',
'Cannot delete workspace',
'failed to mkdirs',
'ERROR: Timeout after 10 minutes',
'Slave went offline during the build',
'\'type_traits\' file not found', // This is here for certain flavors of clang on Ubuntu, which can exhibit odd errors.
'\'typeinfo\' file not found', // This is here for certain flavors of clang on Ubuntu, which can exhibit odd errors.
'Only AMD64 and I386 are supported', // Appears to be a flaky CMAKE failure
'java.util.concurrent.ExecutionException: Invalid object ID',
'hexadecimal value.*is an invalid character.', // This is here until NuGet cache corruption issue is root caused and fixed.
'The plugin hasn\'t been performed correctly: Problem on deletion',
'No space left on device'
]
def regex = '(?i).*('
regex += Utilities.joinStrings(expressionsToRetry, '|')
regex += ').*'
def naginatorNode = new NodeBuilder().'com.chikli.hudson.plugin.naginator.NaginatorPublisher' {
regexpForRerun(regex)
rerunIfUnstable(false)
rerunMatrixPart(false)
checkRegexp(true)
maxSchedule(3)
}
def delayNode = new NodeBuilder().delay(class: 'com.chikli.hudson.plugin.naginator.FixedDelay') {
delegate.delay(15)
}
naginatorNode.append(delayNode)
job.with {
configure { proj ->
def currentPublishers = proj / publishers
currentPublishers << naginatorNode
}
}
}
def static addGithubPushTrigger(def job) {
job.with {
triggers {
githubPush()
}
}
// Record the push trigger. We look up in the side table to see what branches this
// job was set up to build
JobReport.Report.addPushTriggeredJob(job.name)
Utilities.addJobRetry(job)
}
def static addVSTSPushTrigger(def job, String contextString) {
job.with {
triggers {
teamPushTrigger {
jobContext(contextString)
}
}
JobReport.Report.addPushTriggeredJob(job.name)
}
Utilities.addJobRetry(job)
}
/**
* Adds a github PR trigger for a job
*
* @param job Job to add the PR trigger for
* @param contextString String to use as the context (appears in github as the name of the test being run).
* If empty, the job name is used.
* @param triggerPhraseString String to use to trigger the job. If empty, the PR is triggered by default.
* @param triggerOnPhraseOnly If true and trigger phrase string is non-empty, triggers only using the specified trigger
* phrase.
* @param permitAllSubmitters If true all PR submitters may run the job
* @param permittedOrgs If permitAllSubmitters is false, at least permittedOrgs or permittedUsers should be non-empty.
* @param permittedUsers If permitAllSubmitters is false, at least permittedOrgs or permittedUsers should be non-empty.
* @param branchName If null, all branches are tested. If not null, then is the target branch of this trigger
*/
def private static addGithubPRTriggerImpl(def job, String branchName, String contextString, String triggerPhraseString, boolean triggerOnPhraseOnly, boolean permitAllSubmitters, Iterable<String> permittedOrgs, Iterable<String> permittedUsers) {
job.with {
triggers {
githubPullRequest {
useGitHubHooks()
// Add default individual admins here
admin('mmitche')
if (permitAllSubmitters) {
permitAll()
}
else {
assert permittedOrgs != null || permittedUsers != null
permitAll(false)
if (permittedUsers != null) {
permittedUsers.each { permittedUser ->
admin(permittedUser)
}
}
if (permittedOrgs != null) {
String orgListString = Utilities.joinStrings(permittedOrgs, ',')
orgWhitelist(orgListString)
allowMembersOfWhitelistedOrgsAsAdmin(true)
}
}
extensions {
commitStatus {
context(contextString)
updateQueuePosition(true)
}
}
if (triggerOnPhraseOnly) {
onlyTriggerPhrase(triggerOnPhraseOnly)
}
triggerPhrase(triggerPhraseString)
if (branchName != null) {
// We should only have a flat branch name, no wildcards
assert branchName.indexOf('*') == -1
whiteListTargetBranches([branchName])
}
}
}
JobReport.Report.addPRTriggeredJob(job.name, (String[])[branchName], contextString, triggerPhraseString, !triggerOnPhraseOnly)
}
addJobRetry(job)
}
/**
* Adds a github PR trigger only triggerable by member of certain organizations. Either permittedOrgs or
* permittedUsers must be non-null.
*
* @param job Job to add the PR trigger for
* @param contextString String to use as the context (appears in github as the name of the test being run).
* If empty, the job name is used.
* @param triggerPhraseString String to use to trigger the job. If empty, the PR is triggered by default.
* @param triggerOnPhraseOnly If true and trigger phrase string is non-empty, triggers only using the specified trigger phrase.
* @param permittedOrgs orgs permitted to trigger the job
* @param permittedUsers users permitted to trigger the job
*/
def static addPrivateGithubPRTrigger(def job, String contextString, String triggerPhraseString, boolean triggerPhraseOnly, Iterable<String> permittedOrgs, Iterable<String> permittedUsers) {
assert contextString != ''
assert triggerPhraseString != ''
Utilities.addGithubPRTriggerImpl(job, null, contextString, triggerPhraseString, triggerPhraseOnly, false, permittedOrgs, permittedUsers)
}
/**
* Adds a github PR trigger only triggerable by member of certain organizations
*
* @param job Job to add the PR trigger for
* @param branchName If the target branch for the PR message matches this target branch, then the trigger is run.
* @param contextString String to use as the context (appears in github as the name of the test being run).
* If empty, the job name is used.
* @param triggerPhraseString String to use to trigger the job. If empty, the PR is triggered by default.
* @param permittedOrgs If permitAllSubmitters is false, permittedOrgs should be non-empty list of organizations
* @param branchName Branch that this trigger is specific to. If a PR comes in from another branch, this trigger is ignored.
*/
def static addPrivateGithubPRTriggerForBranch(def job, def branchName, String contextString, String triggerPhraseString, Iterable<String> permittedOrgs, Iterable<String> permittedUsers) {
assert contextString != ''
assert triggerPhraseString != ''
Utilities.addGithubPRTriggerImpl(job, branchName, contextString, triggerPhraseString, true, false, permittedOrgs, permittedUsers)
}
/**
* Adds a github PR trigger only triggerable by member of certain organizations
*
* @param job Job to add the PR trigger for
* @param branchName If the target branch for the PR message matches this target branch, then the trigger is run.
* @param contextString String to use as the context (appears in github as the name of the test being run).
* If empty, the job name is used.
* @param permittedOrgs If permitAllSubmitters is false, permittedOrgs should be non-empty list of organizations
* @param branchName Branch that this trigger is specific to. If a PR comes in from another branch, this trigger is ignored.
*/
def static addDefaultPrivateGithubPRTriggerForBranch(def job, def branchName, String contextString, Iterable<String> permittedOrgs, Iterable<String> permittedUsers) {
assert contextString != ''
String triggerPhraseString = "(?i).*test\\W+${java.util.regex.Pattern.quote(contextString)}.*"
Utilities.addGithubPRTriggerImpl(job, branchName, contextString, triggerPhraseString, false, false, permittedOrgs, permittedUsers)
}
/**
* Adds a github PR trigger for a job that is specific to a particular branch
*
* @param job Job to add the PR trigger for
* @param branchName If the target branch for the PR message matches this target branch, then the trigger is run.
* @param contextString String to use as the context (appears in github as the name of the test being run).
* If empty, the job name is used.
* @param triggerPhraseString String to use to trigger the job. If empty, the PR is triggered by default.
* @param triggerOnPhraseOnly If true and trigger phrase string is non-empty, triggers only using the specified trigger
* phrase.
*/
def static addGithubPRTriggerForBranch(def job, String branchName, String contextString,
String triggerPhraseString = '', boolean triggerOnPhraseOnly = true) {
assert contextString != ''
if (triggerPhraseString == '') {
triggerOnPhraseOnly = false
triggerPhraseString = "(?i).*test\\W+${java.util.regex.Pattern.quote(contextString)}.*"
}
Utilities.addGithubPRTriggerImpl(job, branchName, contextString, triggerPhraseString, triggerOnPhraseOnly, true, null, null)
}
/**
* Adds a github PR trigger for a job
*
* @param job Job to add the PR trigger for
* @param contextString String to use as the context (appears in github as the name of the test being run).
* If empty, the job name is used.
* @param triggerPhraseString String to use to trigger the job. If empty, the PR is triggered by default.
* @param triggerOnPhraseOnly If true and trigger phrase string is non-empty, triggers only using the specified trigger
* phrase.
*/
def static addGithubPRTrigger(def job, String contextString, String triggerPhraseString = '', boolean triggerOnPhraseOnly = true) {
assert contextString != ''
if (triggerPhraseString == '') {
triggerOnPhraseOnly = false
triggerPhraseString = "(?i).*test\\W+${java.util.regex.Pattern.quote(contextString)}.*"
}
Utilities.addGithubPRTriggerImpl(job, null, contextString, triggerPhraseString, triggerOnPhraseOnly, true, null, null)
}
/**
* Adds a VSTS PR trigger
*/
def static addVSTSPRTrigger(def job, String branchName, String contextString) {
job.with {
triggers {
teamPRPushTrigger {
targetBranches(branchName)
jobContext(contextString)
}
}
JobReport.Report.addPRTriggeredJob(job.name, (String[])[branchName], contextString, '', false)
}
Utilities.addJobRetry(job)
}
/**
* Calculates the github scm URL give a project name
*
* @param project Github project
* @param protocol Default HTTPS
*/
@Deprecated
def static calculateGitURL(def project, String protocol = 'https') {
// Example: git://github.com/dotnet/corefx.git
return calculateGitHubURL(project)
}
/**
* Calculates the github scm URL give a project name
*
* @param project Github project (org/repo)
*/
def static calculateGitHubURL(def project) {
// Example: git://github.com/dotnet/corefx.git
return "https://github.com/${project}"
}
/**
* Calculates the vsts scm URL give a collection, project, and repo name
*
* @param collection VSTS collection
* @param fullyQualifiedRepo (project/repo) combo
*/
def static calculateVSTSGitURL(String collection, String fullyQualifiedRepo) {
// If devdiv, DefaultCollection is also stuck into the URL
String project = getOrgOrProjectName(fullyQualifiedRepo)
String repo = getRepoName(fullyQualifiedRepo)
if (collection == 'devdiv') {
return "https://${collection}.visualstudio.com/DefaultCollection/${project}/_git/${repo}"
}
else {
return "https://${collection}.visualstudio.com/${project}/_git/${repo}"
}
}
/**
* Adds the standard parameters for PR and Push jobs.
*
* @param job Job to set up.
* @param project Name of project
* @param isPR True if job is PR job, false otherwise.
* @param defaultBranchOrCommit Commit / branch to build.
* @param defaultRefSpec the refs that Jenkins must sync on a PR job
*/
def static addStandardParametersEx(def job, String project, boolean isPR, String defaultBranchOrCommit, String defaultRefSpec) {
// Do not replace */ if there is another wildcard in the branch name (like */*)
if (defaultBranchOrCommit.indexOf('*/') == 0 && defaultBranchOrCommit.lastIndexOf('*') == 0){
defaultBranchOrCommit = defaultBranchOrCommit.replace('*/','refs/heads/')
}
if (isPR) {
addStandardPRParameters(job, project, defaultBranchOrCommit, defaultRefSpec)
}
else {
addStandardNonPRParameters(job, project, defaultBranchOrCommit)
// Add the size map info for the reporting
JobReport.Report.addTargetBranchForJob(job.name, defaultBranchOrCommit)
}
}
/**
* Adds parameters to a non-PR job. Right now this is only the git branch or commit.
* This is added so that downstream jobs get the same hash as the root job
*/
def private static addStandardNonPRParameters(def job, String project, String defaultBranch) {
job.with {
parameters {
stringParam('GitBranchOrCommit', defaultBranch, 'Git branch or commit to build. If a branch, builds the HEAD of that branch. If a commit, then checks out that specific commit.')
booleanParam('AutoSaveReproEnv', false, 'Save Repro Environment automatically for this job.')
// Telemetry
stringParam('DOTNET_CLI_TELEMETRY_PROFILE', "IsInternal_CIServer;${project}", 'This is used to differentiate the internal CI usage of CLI in telemetry. This gets exposed in the environment and picked up by the CLI product.')
// Project name (without org)
stringParam('GithubProjectName', Utilities.getProjectName(project), 'Project name ')
// Org name (without repo)
stringParam('GithubOrgName', Utilities.getOrgName(project), 'Project name passed to the DSL generator')
stringParam('QualifiedRepoName', project, 'Combined Github/VSTS project/org and repo name')
stringParam('BranchName', Utilities.getBranchName(defaultBranch), 'Branch name (without */)')
}
}
}
/**
* Adds the private job/PR parameters to a job. Note that currently this shouldn't used on a non-pr job because
* push triggering may not work.
*/
def static addStandardPRParameters(def job, String project, String defaultBranchOrCommit = null, String defaultRefSpec = null) {
defaultBranchOrCommit = getDefaultBranchOrCommitPR(defaultBranchOrCommit)
defaultRefSpec = getDefaultRefSpec(defaultRefSpec)
job.with {
parameters {
stringParam('GitBranchOrCommit', defaultBranchOrCommit, 'Git branch or commit to build. If a branch, builds the HEAD of that branch. If a commit, then checks out that specific commit.')
stringParam('GitRepoUrl', calculateGitURL(project), 'Git repo to clone.')
stringParam('GitRefSpec', defaultRefSpec, 'RefSpec. WHEN SUBMITTING PRIVATE JOB FROM YOUR OWN REPO, CLEAR THIS FIELD (or it won\'t find your code)')
stringParam('DOTNET_CLI_TELEMETRY_PROFILE', "IsInternal_CIServer;${project}", 'This is used to differentiate the internal CI usage of CLI in telemetry. This gets exposed in the environment and picked up by the CLI product.')
// Project name (without org)
stringParam('GithubProjectName', Utilities.getProjectName(project), 'Project name')
// Org name (without repo)
stringParam('GithubOrgName', Utilities.getOrgName(project), 'Project name passed to the DSL generator')
booleanParam('AutoSaveReproEnv', false, 'Save Repro Environment automatically for this job.')
stringParam('QualifiedRepoName', project, 'Combined Github/VSTS project/org and repo name')
stringParam('BranchName', Utilities.getBranchName(defaultBranchOrCommit), 'Branch name (without */)')
}
}
}
def public static addScm(def job, String project, boolean isPR) {
if (isPR) {
addPRTestSCM(job, project, null)
}
else {
addNonPRScm(job, project, null)
}
}
def public static addScmInSubDirectory(def job, String project, boolean isPR, String subdir) {
if (isPR) {
addPRTestSCM(job, project, subdir)
}
else {
addNonPRScm(job, project, subdir)
}
}
def private static addNonPRScm(def job, String project, String subdir) {
job.with {
scm {
git {
remote {
github(project)
}
branch('${GitBranchOrCommit}')
// Raise up the timeout
extensions {
if (subdir != null) {
relativeTargetDirectory(subdir)
}
cloneOptions {
timeout(90)
}
}
}
}
}
}
/**
* Adds private job/PR test SCM. This is slightly different than normal
* SCM since we use the parameterized fields for the refspec, repo, and branch
*/
def private static addPRTestSCM(def job, String project, String subdir) {
job.with {
scm {
git {
remote {
github(project)
// Set the refspec
refspec('${GitRefSpec}')
// Reset the url to the parameterized version
url('${GitRepoUrl}')
}
branch('${GitBranchOrCommit}')
// Raise up the timeout
extensions {
if (subdir != null) {
relativeTargetDirectory(subdir)
}
cloneOptions {
timeout(90)
}
}
}
}
}
}
/**
* Adds private permissions to a job, making it visible only to certain users
*
* @param job Job to modify
* @param permitted Array of groups and users that are permitted to view the job.
*/
def static addPrivatePermissions(def job, def permitted = ['mmitche', 'Microsoft']) {
job.with {
authorization {
blocksInheritance()
permitted.each { user ->
permissionAll(user)
}
permission('hudson.model.Item.Discover', 'anonymous')
permission('hudson.model.Item.ViewStatus', 'anonymous')
}
}
}
/**
* Add the ability to repro a failed job.
*
* @param job Job to modify
*/
def static addReproBuild(def job) {
job.with {
publishers {
reproToolPublisher {
StorageName("workspaceUpload")
StorageAccount("reproworkspace")
StorageContainer("workspace")
APIBaseURI("https://repro-tool.westus2.cloudapp.azure.com/")
CredentialsId("")
}
}
}
}
/**
* Archives data for a job when specific job result conditions are met.
*
* @param job Job to modify
* @param settings Archival settings
*/
def static addArchival(def job, ArchivalSettings settings) {
job.with {
publishers {
flexiblePublish {
conditionalAction {
condition {
status(settings.getArchiveStatusRange()[0],settings.getArchiveStatusRange()[1])
}
publishers {
archiveArtifacts {
allowEmpty(!settings.failIfNothingArchived)
pattern(joinStrings(Arrays.asList(settings.filesToArchive), ','))
if (settings.filesToExclude != null) {
exclude(joinStrings(Arrays.asList(settings.filesToExclude), ','))
} else {
exclude('')
}
// Always archive so that the flexible publishing
// handles pass/fail
onlyIfSuccessful(false)
}
}
}
}
}
}
}
/**
* Archives data in Azure for a job when specific job result conditions are met.
*
* @param job Job to modify
* @param storageAccount Storage account to use
* @param settings Archival settings
*/
def static addAzureArchival(def job, String storageAccount, ArchivalSettings settings) {
job.with {
publishers {
flexiblePublish {
conditionalAction {
condition {
status(settings.getArchiveStatusRange()[0],settings.getArchiveStatusRange()[1])
}
publishers {
azureStorageUpload {
doNotFailIfArchivingReturnsNothing(!settings.failIfNothingArchived)
filesToUpload(joinStrings(Arrays.asList(settings.filesToArchive), ','))
if (settings.filesToExclude != null) {
excludeFilesPattern(joinStrings(Arrays.asList(settings.filesToExclude), ','))
}
storageAccountName(storageAccount)
allowAnonymousAccess(true)
uploadArtifactsOnlyIfSuccessful(false)
manageArtifacts(true)
uploadZips(false)
}
}
}
}
}
}
}
/**
* Archives data for a job
*
* @param job Job to modify
* @param filesToArchive Files to archive. Comma separated glob syntax
* @param filesToExclude Files to exclude from archival. Defaults to no files excluded. Comma separated glob syntax
* @param doNotFailIfNothingArchived If true, and nothing is archived, will not fail the build.
* @param archiveOnlyIfSuccessful If true, will only archive if the build passes. If false, then will archive always
*/
@Deprecated
def static addArchival(def job, String filesToArchive, String filesToExclude = '',
def doNotFailIfNothingArchived = false, def archiveOnlyIfSuccessful = true) {
ArchivalSettings settings = new ArchivalSettings();
settings.addFiles(filesToArchive);
if (filesToExclude != '') {
settings.excludeFiles(filesToExclude);
}
if (doNotFailIfNothingArchived) {
settings.setDoNotFailIfNothingArchived()
} else {
settings.setFailIfNothingArchived()
}
if (archiveOnlyIfSuccessful) {
settings.setArchiveOnSuccess()
} else {
settings.setAlwaysArchive()
}
addArchival(job, settings)
}
def static addHtmlPublisher(def job, String reportDir, String name, String reportHtml, boolean keepAllReports = true) {
job.with {
publishers {
publishHtml {
report(reportDir) {
reportName(name)
keepAll(keepAllReports)
reportFiles(reportHtml)
}
}
}