forked from kubernetes/test-infra
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
931 lines (840 loc) · 31.6 KB
/
main.go
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
/*
Copyright 2018 The Kubernetes Authors.
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
http://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.
*/
// checkconfig loads configuration for Prow to validate it
package main
import (
"errors"
"flag"
"fmt"
"io/ioutil"
"net/url"
"os"
"strings"
"github.com/sirupsen/logrus"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/apimachinery/pkg/util/validation"
"sigs.k8s.io/yaml"
v1 "k8s.io/test-infra/prow/apis/prowjobs/v1"
"k8s.io/test-infra/prow/config"
"k8s.io/test-infra/prow/config/secret"
"k8s.io/test-infra/prow/errorutil"
needsrebase "k8s.io/test-infra/prow/external-plugins/needs-rebase/plugin"
"k8s.io/test-infra/prow/flagutil"
"k8s.io/test-infra/prow/github"
_ "k8s.io/test-infra/prow/hook/plugin-imports"
"k8s.io/test-infra/prow/labels"
"k8s.io/test-infra/prow/logrusutil"
"k8s.io/test-infra/prow/plugins"
"k8s.io/test-infra/prow/plugins/approve"
"k8s.io/test-infra/prow/plugins/blockade"
"k8s.io/test-infra/prow/plugins/blunderbuss"
"k8s.io/test-infra/prow/plugins/bugzilla"
"k8s.io/test-infra/prow/plugins/cherrypickunapproved"
"k8s.io/test-infra/prow/plugins/hold"
"k8s.io/test-infra/prow/plugins/lgtm"
ownerslabel "k8s.io/test-infra/prow/plugins/owners-label"
"k8s.io/test-infra/prow/plugins/releasenote"
"k8s.io/test-infra/prow/plugins/trigger"
verifyowners "k8s.io/test-infra/prow/plugins/verify-owners"
"k8s.io/test-infra/prow/plugins/wip"
)
type options struct {
configPath string
jobConfigPath string
pluginConfig string
prowYAMLRepoName string
prowYAMLPath string
warnings flagutil.Strings
excludeWarnings flagutil.Strings
strict bool
expensive bool
github flagutil.GitHubOptions
}
func reportWarning(strict bool, errs errorutil.Aggregate) {
for _, item := range errs.Strings() {
logrus.Warn(item)
}
if strict {
logrus.Fatal("Strict is set and there were warnings")
}
}
func (o *options) warningEnabled(warning string) bool {
return sets.NewString(o.warnings.Strings()...).Difference(sets.NewString(o.excludeWarnings.Strings()...)).Has(warning)
}
const (
mismatchedTideWarning = "mismatched-tide"
mismatchedTideLenientWarning = "mismatched-tide-lenient"
tideStrictBranchWarning = "tide-strict-branch"
nonDecoratedJobsWarning = "non-decorated-jobs"
jobNameLengthWarning = "long-job-names"
jobRefsDuplicationWarning = "duplicate-job-refs"
needsOkToTestWarning = "needs-ok-to-test"
validateOwnersWarning = "validate-owners"
missingTriggerWarning = "missing-trigger"
validateURLsWarning = "validate-urls"
unknownFieldsWarning = "unknown-fields"
verifyOwnersFilePresence = "verify-owners-presence"
)
var defaultWarnings = []string{
mismatchedTideWarning,
tideStrictBranchWarning,
mismatchedTideLenientWarning,
nonDecoratedJobsWarning,
jobNameLengthWarning,
jobRefsDuplicationWarning,
needsOkToTestWarning,
validateOwnersWarning,
missingTriggerWarning,
validateURLsWarning,
unknownFieldsWarning,
}
var expensiveWarnings = []string{
verifyOwnersFilePresence,
}
func getAllWarnings() []string {
var all []string
all = append(all, defaultWarnings...)
all = append(all, expensiveWarnings...)
return all
}
func (o *options) DefaultAndValidate() error {
allWarnings := getAllWarnings()
if o.configPath == "" {
return errors.New("required flag --config-path was unset")
}
if o.prowYAMLPath != "" && o.prowYAMLRepoName == "" {
return errors.New("--prow-yaml-repo-path requires --prow-yaml-repo-name to be set")
}
if o.prowYAMLRepoName != "" {
if o.prowYAMLPath == "" {
o.prowYAMLPath = fmt.Sprintf("/home/prow/go/src/github.com/%s/.prow.yaml", o.prowYAMLRepoName)
}
}
for _, warning := range o.warnings.Strings() {
found := false
for _, registeredWarning := range allWarnings {
if warning == registeredWarning {
found = true
break
}
}
if !found {
return fmt.Errorf("no such warning %q, valid warnings: %v", warning, allWarnings)
}
}
return nil
}
func parseOptions() (options, error) {
o := options{}
if err := o.gatherOptions(flag.CommandLine, os.Args[1:]); err != nil {
return options{}, err
}
return o, nil
}
func (o *options) gatherOptions(flag *flag.FlagSet, args []string) error {
flag.StringVar(&o.configPath, "config-path", "", "Path to config.yaml.")
flag.StringVar(&o.jobConfigPath, "job-config-path", "", "Path to prow job configs.")
flag.StringVar(&o.pluginConfig, "plugin-config", "", "Path to plugin config file.")
flag.StringVar(&o.prowYAMLRepoName, "prow-yaml-repo-name", "", "Name of the repo whose .prow.yaml should be checked.")
flag.StringVar(&o.prowYAMLPath, "prow-yaml-path", "", "Path to the .prow.yaml file to check. Requires --prow-yaml-repo-name to be set. Defaults to `/home/prow/go/src/github.com/<< prow-yaml-repo-name >>/.prow.yaml`")
flag.Var(&o.warnings, "warnings", "Warnings to validate. Use repeatedly to provide a list of warnings")
flag.Var(&o.excludeWarnings, "exclude-warning", "Warnings to exclude. Use repeatedly to provide a list of warnings to exclude")
flag.BoolVar(&o.expensive, "expensive-checks", false, "If set, additional expensive warnings will be enabled")
flag.BoolVar(&o.strict, "strict", false, "If set, consider all warnings as errors.")
o.github.AddFlagsWithoutDefaultGitHubTokenPath(flag)
if err := flag.Parse(args); err != nil {
return fmt.Errorf("parse flags: %v", err)
}
if err := o.DefaultAndValidate(); err != nil {
return fmt.Errorf("Invalid options: %v", err)
}
return nil
}
func main() {
logrusutil.ComponentInit("checkconfig")
o, err := parseOptions()
if err != nil {
logrus.Fatalf("Error parsing options - %v", err)
}
// use all warnings by default
if len(o.warnings.Strings()) == 0 {
if o.expensive {
o.warnings = flagutil.NewStrings(getAllWarnings()...)
} else {
o.warnings = flagutil.NewStrings(defaultWarnings...)
}
}
configAgent := config.Agent{}
if err := configAgent.Start(o.configPath, o.jobConfigPath); err != nil {
logrus.WithError(err).Fatal("Error loading Prow config.")
}
cfg := configAgent.Config()
if o.prowYAMLRepoName != "" {
if err := validateInRepoConfig(cfg, o.prowYAMLPath, o.prowYAMLRepoName); err != nil {
logrus.WithError(err).Fatal("Error validating .prow.yaml")
}
}
pluginAgent := plugins.ConfigAgent{}
var pcfg *plugins.Configuration
if o.pluginConfig != "" {
if err := pluginAgent.Load(o.pluginConfig, true); err != nil {
logrus.WithError(err).Fatal("Error loading Prow plugin config.")
}
pcfg = pluginAgent.Config()
}
// the following checks are useful in finding user errors but their
// presence won't lead to strictly incorrect behavior, so we can
// detect them here but don't necessarily want to stop config re-load
// in all components on their failure.
var errs []error
if pcfg != nil && o.warningEnabled(verifyOwnersFilePresence) {
if o.github.TokenPath == "" {
logrus.Fatal("Cannot verify OWNERS file presence without a GitHub token")
}
secretAgent := &secret.Agent{}
if o.github.TokenPath != "" {
if err := secretAgent.Start([]string{o.github.TokenPath}); err != nil {
logrus.WithError(err).Fatal("Error starting secrets agent.")
}
}
githubClient, err := o.github.GitHubClient(secretAgent, false)
if err != nil {
logrus.WithError(err).Fatal("Error getting GitHub client.")
}
githubClient.Throttle(3000, 100) // 300 hourly tokens, bursts of 100
// 404s are expected to happen, no point in retrying
githubClient.SetMax404Retries(0)
if err := verifyOwnersPresence(pcfg, githubClient); err != nil {
errs = append(errs, err)
}
}
if pcfg != nil && o.warningEnabled(mismatchedTideWarning) {
if err := validateTideRequirements(cfg, pcfg, true); err != nil {
errs = append(errs, err)
}
} else if pcfg != nil && o.warningEnabled(mismatchedTideLenientWarning) {
if err := validateTideRequirements(cfg, pcfg, false); err != nil {
errs = append(errs, err)
}
}
if o.warningEnabled(nonDecoratedJobsWarning) {
if err := validateDecoratedJobs(cfg); err != nil {
errs = append(errs, err)
}
}
if o.warningEnabled(jobNameLengthWarning) {
if err := validateJobRequirements(cfg.JobConfig); err != nil {
errs = append(errs, err)
}
}
if o.warningEnabled(jobRefsDuplicationWarning) {
if err := validateJobExtraRefs(cfg.JobConfig); err != nil {
errs = append(errs, err)
}
}
if o.warningEnabled(needsOkToTestWarning) {
if err := validateNeedsOkToTestLabel(cfg); err != nil {
errs = append(errs, err)
}
}
if pcfg != nil && o.warningEnabled(validateOwnersWarning) {
if err := verifyOwnersPlugin(pcfg); err != nil {
errs = append(errs, err)
}
}
if pcfg != nil && o.warningEnabled(missingTriggerWarning) {
if err := validateTriggers(cfg, pcfg); err != nil {
errs = append(errs, err)
}
}
if pcfg != nil && o.warningEnabled(validateURLsWarning) {
if err := validateURLs(cfg.ProwConfig); err != nil {
errs = append(errs, err)
}
}
if o.warningEnabled(unknownFieldsWarning) {
cfgBytes, err := ioutil.ReadFile(o.configPath)
if err != nil {
logrus.WithError(err).Fatal("Error loading Prow config for validation.")
}
if err := validateUnknownFields(cfg, cfgBytes, o.configPath); err != nil {
errs = append(errs, err)
}
}
if pcfg != nil && o.warningEnabled(unknownFieldsWarning) {
pcfgBytes, err := ioutil.ReadFile(o.pluginConfig)
if err != nil {
logrus.WithError(err).Fatal("Error loading Prow plugin config for validation.")
}
if err := validateUnknownFields(pcfg, pcfgBytes, o.pluginConfig); err != nil {
errs = append(errs, err)
}
}
if o.warningEnabled(tideStrictBranchWarning) {
if err := validateStrictBranches(cfg.ProwConfig); err != nil {
errs = append(errs, err)
}
}
if len(errs) > 0 {
reportWarning(o.strict, errorutil.NewAggregate(errs...))
return
}
logrus.Info("checkconfig passes without any error!")
}
func policyIsStrict(p config.Policy) bool {
if p.Protect == nil || !*p.Protect {
return false
}
if p.RequiredStatusChecks == nil || p.RequiredStatusChecks.Strict == nil {
return false
}
return *p.RequiredStatusChecks.Strict
}
func strictBranchesConfig(c config.ProwConfig) (*orgRepoConfig, error) {
strictOrgExceptions := make(map[string]sets.String)
strictRepos := sets.NewString()
for orgName := range c.BranchProtection.Orgs {
org := c.BranchProtection.GetOrg(orgName)
// First find explicitly configured repos and partition based on strictness.
// If any branch in a repo is strict we assume that the whole repo is to
// simplify this validation.
strictExplicitRepos, nonStrictExplicitRepos := sets.NewString(), sets.NewString()
for repoName := range org.Repos {
repo := org.GetRepo(repoName)
strict := policyIsStrict(repo.Policy)
if !strict {
for branchName := range repo.Branches {
branch, err := repo.GetBranch(branchName)
if err != nil {
return nil, err
}
if policyIsStrict(branch.Policy) {
strict = true
break
}
}
}
fullRepoName := fmt.Sprintf("%s/%s", orgName, repoName)
if strict {
strictExplicitRepos.Insert(fullRepoName)
} else {
nonStrictExplicitRepos.Insert(fullRepoName)
}
}
// Done partitioning the repos.
if policyIsStrict(org.Policy) {
// This org is strict, record with repo exceptions (blacklist).
strictOrgExceptions[orgName] = nonStrictExplicitRepos
} else {
// The org is not strict, record member repos that are (whitelist).
strictRepos.Insert(strictExplicitRepos.UnsortedList()...)
}
}
return newOrgRepoConfig(strictOrgExceptions, strictRepos), nil
}
func validateStrictBranches(c config.ProwConfig) error {
const explanation = "See #5: https://github.com/kubernetes/test-infra/blob/master/prow/cmd/tide/maintainers.md#best-practices Also note that this validation is imperfect, see the check-config code for details"
if len(c.Tide.Queries) == 0 {
// Short circuit here so that we can allow global level branchprotector
// 'strict: true' if Tide is not enabled.
// Ignoring the case where Tide is enabled only on orgs/repos specifically
// exempted from the global setting simplifies validation immensely.
return nil
}
if policyIsStrict(c.BranchProtection.Policy) {
return fmt.Errorf("strict branchprotection context requirements cannot be globally enabled when Tide is configured for use. %s", explanation)
}
// The two assumptions below are not necessarily true, but they hold for all
// known instances and make this validation much simpler.
// Assumes if any branch is managed by Tide, the whole repo is.
overallTideConfig := newOrgRepoConfig(c.Tide.Queries.OrgExceptionsAndRepos())
// Assumes if any branch is strict the repo is strict.
strictBranchConfig, err := strictBranchesConfig(c)
if err != nil {
return err
}
conflicts := overallTideConfig.intersection(strictBranchConfig).items()
if len(conflicts) == 0 {
return nil
}
return fmt.Errorf(
"the following enable strict branchprotection context requirements even though Tide handles merges: [%s]. %s",
strings.Join(conflicts, "; "),
explanation,
)
}
func validateURLs(c config.ProwConfig) error {
var validationErrs []error
if _, err := url.Parse(c.StatusErrorLink); err != nil {
validationErrs = append(validationErrs, fmt.Errorf("status_error_link is not a valid url: %s", c.StatusErrorLink))
}
return errorutil.NewAggregate(validationErrs...)
}
func validateUnknownFields(cfg interface{}, cfgBytes []byte, filePath string) error {
err := yaml.Unmarshal(cfgBytes, &cfg, yaml.DisallowUnknownFields)
if err != nil {
return fmt.Errorf("unknown fields or bad config in %s: %v", filePath, err)
}
return nil
}
func validateJobRequirements(c config.JobConfig) error {
var validationErrs []error
for repo, jobs := range c.PresubmitsStatic {
for _, job := range jobs {
validationErrs = append(validationErrs, validatePresubmitJob(repo, job))
}
}
for repo, jobs := range c.PostsubmitsStatic {
for _, job := range jobs {
validationErrs = append(validationErrs, validatePostsubmitJob(repo, job))
}
}
for _, job := range c.Periodics {
validationErrs = append(validationErrs, validatePeriodicJob(job))
}
return errorutil.NewAggregate(validationErrs...)
}
func validatePresubmitJob(repo string, job config.Presubmit) error {
var validationErrs []error
// Prow labels k8s resources with job names. Labels are capped at 63 chars.
if job.Agent == string(v1.KubernetesAgent) && len(job.Name) > validation.LabelValueMaxLength {
validationErrs = append(validationErrs, fmt.Errorf("name of Presubmit job %q (for repo %q) too long (should be at most 63 characters)", job.Name, repo))
}
return errorutil.NewAggregate(validationErrs...)
}
func validatePostsubmitJob(repo string, job config.Postsubmit) error {
var validationErrs []error
// Prow labels k8s resources with job names. Labels are capped at 63 chars.
if job.Agent == string(v1.KubernetesAgent) && len(job.Name) > validation.LabelValueMaxLength {
validationErrs = append(validationErrs, fmt.Errorf("name of Postsubmit job %q (for repo %q) too long (should be at most 63 characters)", job.Name, repo))
}
return errorutil.NewAggregate(validationErrs...)
}
func validateJobExtraRefs(cfg config.JobConfig) error {
var validationErrs []error
for repo, presubmits := range cfg.PresubmitsStatic {
for _, presubmit := range presubmits {
if err := config.ValidateRefs(repo, presubmit.JobBase); err != nil {
validationErrs = append(validationErrs, err)
}
}
}
return errorutil.NewAggregate(validationErrs...)
}
func validatePeriodicJob(job config.Periodic) error {
var validationErrs []error
// Prow labels k8s resources with job names. Labels are capped at 63 chars.
if job.Agent == string(v1.KubernetesAgent) && len(job.Name) > validation.LabelValueMaxLength {
validationErrs = append(validationErrs, fmt.Errorf("name of Periodic job %q too long (should be at most 63 characters)", job.Name))
}
return errorutil.NewAggregate(validationErrs...)
}
func validateTideRequirements(cfg *config.Config, pcfg *plugins.Configuration, includeForbidden bool) error {
type matcher struct {
// matches determines if the tide query appropriately honors the
// label in question -- whether by requiring it or forbidding it
matches func(label string, query config.TideQuery) bool
// verb is used in forming error messages
verb string
}
requires := matcher{
matches: func(label string, query config.TideQuery) bool {
return sets.NewString(query.Labels...).Has(label)
},
verb: "require",
}
forbids := matcher{
matches: func(label string, query config.TideQuery) bool {
return sets.NewString(query.MissingLabels...).Has(label)
},
verb: "forbid",
}
type plugin struct {
// name and label identify the relationship we are validating
name, label string
// external indicates plugin is external or not
external bool
// matcher determines if the tide query appropriately honors the
// label in question -- whether by requiring it or forbidding it
matcher matcher
// config holds the orgs and repos for which tide does honor the
// label; this container is populated conditionally from queries
// using the matcher
config *orgRepoConfig
}
// configs list relationships between tide config
// and plugin enablement that we want to validate
configs := []plugin{
{name: lgtm.PluginName, label: labels.LGTM, matcher: requires},
{name: approve.PluginName, label: labels.Approved, matcher: requires},
}
if includeForbidden {
configs = append(configs,
plugin{name: hold.PluginName, label: labels.Hold, matcher: forbids},
plugin{name: wip.PluginName, label: labels.WorkInProgress, matcher: forbids},
plugin{name: bugzilla.PluginName, label: labels.InvalidBug, matcher: forbids},
plugin{name: verifyowners.PluginName, label: labels.InvalidOwners, matcher: forbids},
plugin{name: releasenote.PluginName, label: releasenote.ReleaseNoteLabelNeeded, matcher: forbids},
plugin{name: cherrypickunapproved.PluginName, label: labels.CpUnapproved, matcher: forbids},
plugin{name: blockade.PluginName, label: labels.BlockedPaths, matcher: forbids},
plugin{name: needsrebase.PluginName, label: labels.NeedsRebase, external: true, matcher: forbids},
)
}
for i := range configs {
// For each plugin determine the subset of tide queries that match and then
// the orgs and repos that the subset matches.
var matchingQueries config.TideQueries
for _, query := range cfg.Tide.Queries {
if configs[i].matcher.matches(configs[i].label, query) {
matchingQueries = append(matchingQueries, query)
}
}
configs[i].config = newOrgRepoConfig(matchingQueries.OrgExceptionsAndRepos())
}
overallTideConfig := newOrgRepoConfig(cfg.Tide.Queries.OrgExceptionsAndRepos())
// Now actually execute the checks we just configured.
var validationErrs []error
for _, pluginConfig := range configs {
err := ensureValidConfiguration(
pluginConfig.name,
pluginConfig.label,
pluginConfig.matcher.verb,
pluginConfig.config,
overallTideConfig,
enabledOrgReposForPlugin(pcfg, pluginConfig.name, pluginConfig.external),
)
validationErrs = append(validationErrs, err)
}
return errorutil.NewAggregate(validationErrs...)
}
func newOrgRepoConfig(orgExceptions map[string]sets.String, repos sets.String) *orgRepoConfig {
return &orgRepoConfig{
orgExceptions: orgExceptions,
repos: repos,
}
}
// orgRepoConfig describes a set of repositories with an explicit
// whitelist and a mapping of blacklists for owning orgs
type orgRepoConfig struct {
// orgExceptions holds explicit blacklists of repos for owning orgs
orgExceptions map[string]sets.String
// repos is a whitelist of repos
repos sets.String
}
func (c *orgRepoConfig) items() []string {
items := make([]string, 0, len(c.orgExceptions)+len(c.repos))
for org, excepts := range c.orgExceptions {
item := fmt.Sprintf("org: %s", org)
if excepts.Len() > 0 {
item = fmt.Sprintf("%s without repo(s) %s", item, strings.Join(excepts.List(), ", "))
for _, repo := range excepts.List() {
item = fmt.Sprintf("%s '%s'", item, repo)
}
}
items = append(items, item)
}
for _, repo := range c.repos.List() {
items = append(items, fmt.Sprintf("repo: %s", repo))
}
return items
}
// difference returns a new orgRepoConfig that represents the set difference of
// the repos specified by the receiver and the parameter orgRepoConfigs.
func (c *orgRepoConfig) difference(c2 *orgRepoConfig) *orgRepoConfig {
res := &orgRepoConfig{
orgExceptions: make(map[string]sets.String),
repos: sets.NewString().Union(c.repos),
}
for org, excepts1 := range c.orgExceptions {
if excepts2, ok := c2.orgExceptions[org]; ok {
res.repos.Insert(excepts2.Difference(excepts1).UnsortedList()...)
} else {
excepts := sets.NewString().Union(excepts1)
// Add any applicable repos in repos2 to excepts
for _, repo := range c2.repos.UnsortedList() {
if parts := strings.SplitN(repo, "/", 2); len(parts) == 2 && parts[0] == org {
excepts.Insert(repo)
}
}
res.orgExceptions[org] = excepts
}
}
res.repos = res.repos.Difference(c2.repos)
for _, repo := range res.repos.UnsortedList() {
if parts := strings.SplitN(repo, "/", 2); len(parts) == 2 {
if excepts2, ok := c2.orgExceptions[parts[0]]; ok && !excepts2.Has(repo) {
res.repos.Delete(repo)
}
}
}
return res
}
// intersection returns a new orgRepoConfig that represents the set intersection
// of the repos specified by the receiver and the parameter orgRepoConfigs.
func (c *orgRepoConfig) intersection(c2 *orgRepoConfig) *orgRepoConfig {
res := &orgRepoConfig{
orgExceptions: make(map[string]sets.String),
repos: sets.NewString(),
}
for org, excepts1 := range c.orgExceptions {
// Include common orgs, but union exceptions.
if excepts2, ok := c2.orgExceptions[org]; ok {
res.orgExceptions[org] = excepts1.Union(excepts2)
} else {
// Include right side repos that match left side org.
for _, repo := range c2.repos.UnsortedList() {
if parts := strings.SplitN(repo, "/", 2); len(parts) == 2 && parts[0] == org && !excepts1.Has(repo) {
res.repos.Insert(repo)
}
}
}
}
for _, repo := range c.repos.UnsortedList() {
if c2.repos.Has(repo) {
res.repos.Insert(repo)
} else if parts := strings.SplitN(repo, "/", 2); len(parts) == 2 {
// Include left side repos that match right side org.
if excepts2, ok := c2.orgExceptions[parts[0]]; ok && !excepts2.Has(repo) {
res.repos.Insert(repo)
}
}
}
return res
}
// union returns a new orgRepoConfig that represents the set union of the
// repos specified by the receiver and the parameter orgRepoConfigs
func (c *orgRepoConfig) union(c2 *orgRepoConfig) *orgRepoConfig {
res := &orgRepoConfig{
orgExceptions: make(map[string]sets.String),
repos: sets.NewString(),
}
for org, excepts1 := range c.orgExceptions {
// keep only items in both blacklists that are not in the
// explicit repo whitelists for the other configuration;
// we know from how the orgRepoConfigs are constructed that
// a org blacklist won't intersect it's own repo whitelist
pruned := excepts1.Difference(c2.repos)
if excepts2, ok := c2.orgExceptions[org]; ok {
res.orgExceptions[org] = pruned.Intersection(excepts2.Difference(c.repos))
} else {
res.orgExceptions[org] = pruned
}
}
for org, excepts2 := range c2.orgExceptions {
// update any blacklists not previously updated
if _, exists := res.orgExceptions[org]; !exists {
res.orgExceptions[org] = excepts2.Difference(c.repos)
}
}
// we need to prune out repos in the whitelists which are
// covered by an org already; we know from above that no
// org blacklist in the result will contain a repo whitelist
for _, repo := range c.repos.Union(c2.repos).UnsortedList() {
parts := strings.SplitN(repo, "/", 2)
if len(parts) != 2 {
logrus.Warnf("org/repo %q is formatted incorrectly", repo)
continue
}
if _, exists := res.orgExceptions[parts[0]]; !exists {
res.repos.Insert(repo)
}
}
return res
}
func enabledOrgReposForPlugin(c *plugins.Configuration, plugin string, external bool) *orgRepoConfig {
var (
orgs []string
repos []string
)
if external {
orgs, repos = c.EnabledReposForExternalPlugin(plugin)
} else {
orgs, repos = c.EnabledReposForPlugin(plugin)
}
orgMap := make(map[string]sets.String, len(orgs))
for _, org := range orgs {
orgMap[org] = nil
}
return newOrgRepoConfig(orgMap, sets.NewString(repos...))
}
// ensureValidConfiguration enforces rules about tide and plugin config.
// In this context, a subset is the set of repos or orgs for which a specific
// plugin is either enabled (for plugins) or required for merge (for tide). The
// tide superset is every org or repo that has any configuration at all in tide.
// Specifically:
// - every item in the tide subset must also be in the plugins subset
// - every item in the plugins subset that is in the tide superset must also be in the tide subset
// For example:
// - if org/repo is configured in tide to require lgtm, it must have the lgtm plugin enabled
// - if org/repo is configured in tide, the tide configuration must require the same set of
// plugins as are configured. If the repository has LGTM and approve enabled, the tide query
// must require both labels
func ensureValidConfiguration(plugin, label, verb string, tideSubSet, tideSuperSet, pluginsSubSet *orgRepoConfig) error {
notEnabled := tideSubSet.difference(pluginsSubSet).items()
notRequired := pluginsSubSet.intersection(tideSuperSet).difference(tideSubSet).items()
var configErrors []error
if len(notEnabled) > 0 {
configErrors = append(configErrors, fmt.Errorf("the following orgs or repos %s the %s label for merging but do not enable the %s plugin: %v", verb, label, plugin, notEnabled))
}
if len(notRequired) > 0 {
configErrors = append(configErrors, fmt.Errorf("the following orgs or repos enable the %s plugin but do not %s the %s label for merging: %v", plugin, verb, label, notRequired))
}
return errorutil.NewAggregate(configErrors...)
}
func validateDecoratedJobs(cfg *config.Config) error {
var nonDecoratedJobs []string
for _, presubmit := range cfg.AllStaticPresubmits([]string{}) {
if presubmit.Agent == string(v1.KubernetesAgent) && !presubmit.Decorate {
nonDecoratedJobs = append(nonDecoratedJobs, presubmit.Name)
}
}
for _, postsubmit := range cfg.AllStaticPostsubmits([]string{}) {
if postsubmit.Agent == string(v1.KubernetesAgent) && !postsubmit.Decorate {
nonDecoratedJobs = append(nonDecoratedJobs, postsubmit.Name)
}
}
for _, periodic := range cfg.AllPeriodics() {
if periodic.Agent == string(v1.KubernetesAgent) && !periodic.Decorate {
nonDecoratedJobs = append(nonDecoratedJobs, periodic.Name)
}
}
if len(nonDecoratedJobs) > 0 {
return fmt.Errorf("the following jobs use the kubernetes provider but do not use the pod utilities: %v", nonDecoratedJobs)
}
return nil
}
func validateNeedsOkToTestLabel(cfg *config.Config) error {
var queryErrors []error
for i, query := range cfg.Tide.Queries {
for _, label := range query.Labels {
if label == lgtm.LGTMLabel {
for _, label := range query.MissingLabels {
if label == labels.NeedsOkToTest {
queryErrors = append(queryErrors, fmt.Errorf(
"the tide query at position %d"+
"forbids the %q label and requires the %q label, "+
"which is not recommended; "+
"see https://github.com/kubernetes/test-infra/blob/master/prow/cmd/tide/maintainers.md#best-practices "+
"for more information",
i, labels.NeedsOkToTest, lgtm.LGTMLabel),
)
}
}
}
}
}
return errorutil.NewAggregate(queryErrors...)
}
func pluginsWithOwnersFile() string {
return strings.Join([]string{approve.PluginName, blunderbuss.PluginName, ownerslabel.PluginName}, ", ")
}
func orgReposUsingOwnersFile(cfg *plugins.Configuration) *orgRepoConfig {
// we do not know the set of repos that use OWNERS, but we
// can get a reasonable proxy for this by looking at where
// the `approve', `blunderbuss' and `owners-label' plugins
// are enabled
approveConfig := enabledOrgReposForPlugin(cfg, approve.PluginName, false)
blunderbussConfig := enabledOrgReposForPlugin(cfg, blunderbuss.PluginName, false)
ownersLabelConfig := enabledOrgReposForPlugin(cfg, ownerslabel.PluginName, false)
return approveConfig.union(blunderbussConfig).union(ownersLabelConfig)
}
type FileInRepoExistsChecker interface {
GetRepos(org string, isUser bool) ([]github.Repo, error)
GetFile(org, repo, filepath, commit string) ([]byte, error)
}
func verifyOwnersPresence(cfg *plugins.Configuration, rc FileInRepoExistsChecker) error {
ownersConfig := orgReposUsingOwnersFile(cfg)
var missing []string
for org, excluded := range ownersConfig.orgExceptions {
repos, err := rc.GetRepos(org, false)
if err != nil {
return err
}
for _, repo := range repos {
if excluded.Has(repo.FullName) || repo.Archived {
continue
}
if _, err := rc.GetFile(repo.Owner.Login, repo.Name, "OWNERS", ""); err != nil {
if _, nf := err.(*github.FileNotFound); nf {
missing = append(missing, repo.FullName)
} else {
return fmt.Errorf("got error: %v", err)
}
}
}
}
for repo := range ownersConfig.repos {
items := strings.Split(repo, "/")
if len(items) != 2 {
return fmt.Errorf("bad repository '%s', expected org/repo format", repo)
}
if _, err := rc.GetFile(items[0], items[1], "OWNERS", ""); err != nil {
if _, nf := err.(*github.FileNotFound); nf {
missing = append(missing, repo)
} else {
return fmt.Errorf("got error: %v", err)
}
}
}
if len(missing) > 0 {
return fmt.Errorf("the following orgs or repos enable at least one"+
" plugin that uses OWNERS files (%s), but its master branch does not contain"+
" a root level OWNERS file: %v", pluginsWithOwnersFile(), missing)
}
return nil
}
func verifyOwnersPlugin(cfg *plugins.Configuration) error {
ownersConfig := orgReposUsingOwnersFile(cfg)
validateOwnersConfig := enabledOrgReposForPlugin(cfg, verifyowners.PluginName, false)
invalid := ownersConfig.difference(validateOwnersConfig).items()
if len(invalid) > 0 {
return fmt.Errorf("the following orgs or repos "+
"enable at least one plugin that uses OWNERS files (%s) "+
"but do not enable the %s plugin to ensure validity of OWNERS files: %v",
pluginsWithOwnersFile(), verifyowners.PluginName, invalid,
)
}
return nil
}
func validateTriggers(cfg *config.Config, pcfg *plugins.Configuration) error {
configuredRepos := sets.NewString()
for orgRepo := range cfg.JobConfig.PresubmitsStatic {
configuredRepos.Insert(orgRepo)
}
for orgRepo := range cfg.JobConfig.PostsubmitsStatic {
configuredRepos.Insert(orgRepo)
}
configured := newOrgRepoConfig(map[string]sets.String{}, configuredRepos)
enabled := enabledOrgReposForPlugin(pcfg, trigger.PluginName, false)
if missing := configured.difference(enabled).items(); len(missing) > 0 {
return fmt.Errorf("the following repos have jobs configured but do not have the %s plugin enabled: %s", trigger.PluginName, strings.Join(missing, ", "))
}
return nil
}
func validateInRepoConfig(cfg *config.Config, filePath, repoIdentifier string) error {
data, err := ioutil.ReadFile(filePath)
if err != nil {
if !os.IsNotExist(err) {
return fmt.Errorf("failed to read file %q: %v", filePath, err)
}
return nil
}
prowYAML := &config.ProwYAML{}
if err := yaml.Unmarshal(data, prowYAML); err != nil {
return fmt.Errorf("failed to deserialize content of %q: %v", filePath, err)
}
if err := config.DefaultAndValidateProwYAML(cfg, prowYAML, repoIdentifier); err != nil {
return fmt.Errorf("failed to validate .prow.yaml: %v", err)
}
return nil
}