-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
Copy pathconfig.go
2771 lines (2434 loc) · 95.9 KB
/
config.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
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
/*
Copyright 2017 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.
*/
// Package config knows how to read and parse config.yaml.
package config
import (
"bytes"
"compress/gzip"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/url"
"os"
"path"
"path/filepath"
"regexp"
"runtime/debug"
"sort"
"strconv"
"strings"
"sync"
"text/template"
"time"
"github.com/google/go-cmp/cmp"
"github.com/sirupsen/logrus"
pipelinev1alpha1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1"
"gopkg.in/robfig/cron.v2"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
utilerrors "k8s.io/apimachinery/pkg/util/errors"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/apimachinery/pkg/util/validation"
"sigs.k8s.io/yaml"
prowapi "k8s.io/test-infra/prow/apis/prowjobs/v1"
gerrit "k8s.io/test-infra/prow/gerrit/client"
"k8s.io/test-infra/prow/git/v2"
"k8s.io/test-infra/prow/github"
"k8s.io/test-infra/prow/kube"
"k8s.io/test-infra/prow/pod-utils/decorate"
"k8s.io/test-infra/prow/pod-utils/downwardapi"
)
const (
// DefaultJobTimeout represents the default deadline for a prow job.
DefaultJobTimeout = 24 * time.Hour
ProwImplicitGitResource = "PROW_IMPLICIT_GIT_REF"
// ConfigVersionFileName is the name of a file that will be added to
// all configmaps by the configupdater and contain the git sha that
// triggered said configupdate. The configloading in turn will pick
// it up if present. This allows components to include the config version
// in their logs, which can be useful for debugging.
ConfigVersionFileName = "VERSION"
)
// Config is a read-only snapshot of the config.
type Config struct {
JobConfig
ProwConfig
}
// JobConfig is config for all prow jobs
type JobConfig struct {
// Presets apply to all job types.
Presets []Preset `json:"presets,omitempty"`
// .PresubmitsStatic contains the presubmits in Prows main config.
// **Warning:** This does not return dynamic Presubmits configured
// inside the code repo, hence giving an incomplete view. Use
// `GetPresubmits` instead if possible.
PresubmitsStatic map[string][]Presubmit `json:"presubmits,omitempty"`
// .PostsubmitsStatic contains the Postsubmits in Prows main config.
// **Warning:** This does not return dynamic postsubmits configured
// inside the code repo, hence giving an incomplete view. Use
// `GetPostsubmits` instead if possible.
PostsubmitsStatic map[string][]Postsubmit `json:"postsubmits,omitempty"`
// Periodics are not associated with any repo.
Periodics []Periodic `json:"periodics,omitempty"`
// AllRepos contains all Repos that have one or more jobs configured or
// for which a tide query is configured.
AllRepos sets.String `json:"-"`
// ProwYAMLGetter is the function to get a ProwYAML. Tests should
// provide their own implementation.
ProwYAMLGetter ProwYAMLGetter `json:"-"`
// DecorateAllJobs determines whether all jobs are decorated by default
DecorateAllJobs bool `json:"decorate_all_jobs,omitempty"`
}
// ProwConfig is config for all prow controllers
type ProwConfig struct {
// The git sha from which this config was generated
ConfigVersionSHA string `json:"config_version_sha,omitempty"`
Tide Tide `json:"tide,omitempty"`
Plank Plank `json:"plank,omitempty"`
Sinker Sinker `json:"sinker,omitempty"`
Deck Deck `json:"deck,omitempty"`
BranchProtection BranchProtection `json:"branch-protection"`
Gerrit Gerrit `json:"gerrit"`
GitHubReporter GitHubReporter `json:"github_reporter"`
Horologium Horologium `json:"horologium"`
SlackReporterConfigs SlackReporterConfigs `json:"slack_reporter_configs,omitempty"`
InRepoConfig InRepoConfig `json:"in_repo_config"`
// TODO: Move this out of the main config.
JenkinsOperators []JenkinsOperator `json:"jenkins_operators,omitempty"`
// ProwJobNamespace is the namespace in the cluster that prow
// components will use for looking up ProwJobs. The namespace
// needs to exist and will not be created by prow.
// Defaults to "default".
ProwJobNamespace string `json:"prowjob_namespace,omitempty"`
// PodNamespace is the namespace in the cluster that prow
// components will use for looking up Pods owned by ProwJobs.
// The namespace needs to exist and will not be created by prow.
// Defaults to "default".
PodNamespace string `json:"pod_namespace,omitempty"`
// LogLevel enables dynamically updating the log level of the
// standard logger that is used by all prow components.
//
// Valid values:
//
// "debug", "info", "warn", "warning", "error", "fatal", "panic"
//
// Defaults to "info".
LogLevel string `json:"log_level,omitempty"`
// PushGateway is a prometheus push gateway.
PushGateway PushGateway `json:"push_gateway,omitempty"`
// OwnersDirDenylist is used to configure regular expressions matching directories
// to ignore when searching for OWNERS{,_ALIAS} files in a repo.
OwnersDirDenylist *OwnersDirDenylist `json:"owners_dir_denylist,omitempty"`
// OwnersDirBlacklist is deprecated, use OwnersDirDenylist instead
// TODO(chaodaiG, November 2021): Removed after October 2021
OwnersDirBlacklist *OwnersDirDenylist `json:"owners_dir_blacklist,omitempty"`
// Pub/Sub Subscriptions that we want to listen to
PubSubSubscriptions PubsubSubscriptions `json:"pubsub_subscriptions,omitempty"`
// PubSubTriggers defines Pub/Sub Subscriptions that we want to listen to,
// can be used to restrict build cluster on a topic
PubSubTriggers PubSubTriggers `json:"pubsub_triggers,omitempty"`
// GitHubOptions allows users to control how prow applications display GitHub website links.
GitHubOptions GitHubOptions `json:"github,omitempty"`
// StatusErrorLink is the url that will be used for jenkins prowJobs that can't be
// found, or have another generic issue. The default that will be used if this is not set
// is: https://github.com/kubernetes/test-infra/issues
StatusErrorLink string `json:"status_error_link,omitempty"`
// DefaultJobTimeout this is default deadline for prow jobs. This value is used when
// no timeout is configured at the job level. This value is set to 24 hours.
DefaultJobTimeout *metav1.Duration `json:"default_job_timeout,omitempty"`
// ManagedWebhooks contains information about all github repositories and organizations which are using
// non-global Hmac token.
ManagedWebhooks ManagedWebhooks `json:"managed_webhooks,omitempty"`
}
type InRepoConfig struct {
// Enabled describes whether InRepoConfig is enabled for a given repository. This can
// be set globally, per org or per repo using '*', 'org' or 'org/repo' as key. The
// narrowest match always takes precedence.
Enabled map[string]*bool `json:"enabled,omitempty"`
// AllowedClusters is a list of allowed clusternames that can be used for jobs on
// a given repo. All clusters that are allowed for the specific repo, its org or
// globally can be used.
AllowedClusters map[string][]string `json:"allowed_clusters,omitempty"`
}
// InRepoConfigEnabled returns whether InRepoConfig is enabled for a given repository.
func (c *Config) InRepoConfigEnabled(identifier string) bool {
if c.InRepoConfig.Enabled[identifier] != nil {
return *c.InRepoConfig.Enabled[identifier]
}
identifierSlashSplit := strings.Split(identifier, "/")
if len(identifierSlashSplit) == 2 && c.InRepoConfig.Enabled[identifierSlashSplit[0]] != nil {
return *c.InRepoConfig.Enabled[identifierSlashSplit[0]]
}
if c.InRepoConfig.Enabled["*"] != nil {
return *c.InRepoConfig.Enabled["*"]
}
return false
}
// InRepoConfigAllowsCluster determines if a given cluster may be used for a given repository
func (c *Config) InRepoConfigAllowsCluster(clusterName, repoIdentifier string) bool {
for _, allowedCluster := range c.InRepoConfig.AllowedClusters[repoIdentifier] {
if allowedCluster == clusterName {
return true
}
}
identifierSlashSplit := strings.Split(repoIdentifier, "/")
if len(identifierSlashSplit) == 2 {
for _, allowedCluster := range c.InRepoConfig.AllowedClusters[identifierSlashSplit[0]] {
if allowedCluster == clusterName {
return true
}
}
}
for _, allowedCluster := range c.InRepoConfig.AllowedClusters["*"] {
if allowedCluster == clusterName {
return true
}
}
return false
}
// RefGetter is used to retrieve a Git Reference. Its purpose is
// to be able to defer calling out to GitHub in the context of
// inrepoconfig to make sure its only done when we actually need
// to have that info.
type RefGetter = func() (string, error)
type refGetterForGitHubPullRequestClient interface {
GetPullRequest(org, repo string, number int) (*github.PullRequest, error)
GetRef(org, repo, ref string) (string, error)
}
// NewRefGetterForGitHubPullRequest returns a brand new RefGetterForGitHubPullRequest
func NewRefGetterForGitHubPullRequest(ghc refGetterForGitHubPullRequestClient, org, repo string, number int) *RefGetterForGitHubPullRequest {
return &RefGetterForGitHubPullRequest{
ghc: ghc,
org: org,
repo: repo,
number: number,
lock: &sync.Mutex{},
}
}
// RefGetterForGitHubPullRequest is used to get the Presubmits for a GitHub PullRequest
// when that PullRequest wasn't fetched yet. It will only fetch it if someone calls
// its .PullRequest() func. It is threadsafe.
type RefGetterForGitHubPullRequest struct {
ghc refGetterForGitHubPullRequestClient
org string
repo string
number int
lock *sync.Mutex
pr *github.PullRequest
baseSHA string
}
func (rg *RefGetterForGitHubPullRequest) PullRequest() (*github.PullRequest, error) {
rg.lock.Lock()
defer rg.lock.Unlock()
if rg.pr != nil {
return rg.pr, nil
}
pr, err := rg.ghc.GetPullRequest(rg.org, rg.repo, rg.number)
if err != nil {
return nil, err
}
rg.pr = pr
return rg.pr, nil
}
// HeadSHA is a RefGetter that returns the headSHA for the PullRequst
func (rg *RefGetterForGitHubPullRequest) HeadSHA() (string, error) {
if rg.pr == nil {
if _, err := rg.PullRequest(); err != nil {
return "", err
}
}
return rg.pr.Head.SHA, nil
}
// BaseSHA is a RefGetter that returns the baseRef for the PullRequest
func (rg *RefGetterForGitHubPullRequest) BaseSHA() (string, error) {
if rg.pr == nil {
if _, err := rg.PullRequest(); err != nil {
return "", err
}
}
// rg.PullRequest also wants the lock, so we must not acquire it before
// caling that
rg.lock.Lock()
defer rg.lock.Unlock()
if rg.baseSHA != "" {
return rg.baseSHA, nil
}
baseSHA, err := rg.ghc.GetRef(rg.org, rg.repo, "heads/"+rg.pr.Base.Ref)
if err != nil {
return "", err
}
rg.baseSHA = baseSHA
return rg.baseSHA, nil
}
// getProwYAML will load presubmits and postsubmits for the given identifier that are
// versioned inside the tested repo, if the inrepoconfig feature is enabled.
// Consumers that pass in a RefGetter implementation that does a call to GitHub and who
// also need the result of that GitHub call just keep a pointer to its result, but must
// nilcheck that pointer before accessing it.
func (c *Config) getProwYAML(gc git.ClientFactory, identifier string, baseSHAGetter RefGetter, headSHAGetters ...RefGetter) (*ProwYAML, error) {
if identifier == "" {
return nil, errors.New("no identifier for repo given")
}
if !c.InRepoConfigEnabled(identifier) {
return &ProwYAML{}, nil
}
baseSHA, err := baseSHAGetter()
if err != nil {
return nil, fmt.Errorf("failed to get baseSHA: %v", err)
}
var headSHAs []string
for _, headSHAGetter := range headSHAGetters {
headSHA, err := headSHAGetter()
if err != nil {
return nil, fmt.Errorf("failed to get headRef: %v", err)
}
headSHAs = append(headSHAs, headSHA)
}
prowYAML, err := c.ProwYAMLGetter(c, gc, identifier, baseSHA, headSHAs...)
if err != nil {
return nil, err
}
return prowYAML, nil
}
// GetPresubmits will return all presubmits for the given identifier. This includes
// Presubmits that are versioned inside the tested repo, if the inrepoconfig feature
// is enabled.
// Consumers that pass in a RefGetter implementation that does a call to GitHub and who
// also need the result of that GitHub call just keep a pointer to its result, but must
// nilcheck that pointer before accessing it.
func (c *Config) GetPresubmits(gc git.ClientFactory, identifier string, baseSHAGetter RefGetter, headSHAGetters ...RefGetter) ([]Presubmit, error) {
prowYAML, err := c.getProwYAML(gc, identifier, baseSHAGetter, headSHAGetters...)
if err != nil {
return nil, err
}
return append(c.GetPresubmitsStatic(identifier), prowYAML.Presubmits...), nil
}
// GetPresubmitsStatic will return presubmits for the given identifier that are versioned inside the tested repo
func (c *Config) GetPresubmitsStatic(identifier string) []Presubmit {
return c.PresubmitsStatic[identifier]
}
// GetPostsubmits will return all postsubmits for the given identifier. This includes
// Postsubmits that are versioned inside the tested repo, if the inrepoconfig feature
// is enabled.
// Consumers that pass in a RefGetter implementation that does a call to GitHub and who
// also need the result of that GitHub call just keep a pointer to its result, but must
// nilcheck that pointer before accessing it.
func (c *Config) GetPostsubmits(gc git.ClientFactory, identifier string, baseSHAGetter RefGetter, headSHAGetters ...RefGetter) ([]Postsubmit, error) {
prowYAML, err := c.getProwYAML(gc, identifier, baseSHAGetter, headSHAGetters...)
if err != nil {
return nil, err
}
return append(c.PostsubmitsStatic[identifier], prowYAML.Postsubmits...), nil
}
// OwnersDirDenylist is used to configure regular expressions matching directories
// to ignore when searching for OWNERS{,_ALIAS} files in a repo.
type OwnersDirDenylist struct {
// Repos configures a directory denylist per repo (or org)
Repos map[string][]string `json:"repos,omitempty"`
// Default configures a default denylist for all repos (or orgs).
// Some directories like ".git", "_output" and "vendor/.*/OWNERS"
// are already preconfigured to be denylisted, and need not be included here.
Default []string `json:"default,omitempty"`
// By default, some directories like ".git", "_output" and "vendor/.*/OWNERS"
// are preconfigured to be denylisted.
// If set, IgnorePreconfiguredDefaults will not add these preconfigured directories
// to the denylist.
IgnorePreconfiguredDefaults bool `json:"ignore_preconfigured_defaults,omitempty"`
}
// ListIgnoredDirs returns regular expressions matching directories to ignore when
// searching for OWNERS{,_ALIAS} files in a repo.
func (o OwnersDirDenylist) ListIgnoredDirs(org, repo string) (ignorelist []string) {
ignorelist = append(ignorelist, o.Default...)
if bl, ok := o.Repos[org]; ok {
ignorelist = append(ignorelist, bl...)
}
if bl, ok := o.Repos[org+"/"+repo]; ok {
ignorelist = append(ignorelist, bl...)
}
preconfiguredDefaults := []string{"\\.git$", "_output$", "vendor/.*/.*"}
if !o.IgnorePreconfiguredDefaults {
ignorelist = append(ignorelist, preconfiguredDefaults...)
}
return
}
// PushGateway is a prometheus push gateway.
type PushGateway struct {
// Endpoint is the location of the prometheus pushgateway
// where prow will push metrics to.
Endpoint string `json:"endpoint,omitempty"`
// Interval specifies how often prow will push metrics
// to the pushgateway. Defaults to 1m.
Interval *metav1.Duration `json:"interval,omitempty"`
// ServeMetrics tells if or not the components serve metrics
ServeMetrics bool `json:"serve_metrics"`
}
// Controller holds configuration applicable to all agent-specific
// prow controllers.
type Controller struct {
// JobURLTemplateString compiles into JobURLTemplate at load time.
JobURLTemplateString string `json:"job_url_template,omitempty"`
// JobURLTemplate is compiled at load time from JobURLTemplateString. It
// will be passed a prowapi.ProwJob and is used to set the URL for the
// "Details" link on GitHub as well as the link from deck.
JobURLTemplate *template.Template `json:"-"`
// ReportTemplateString compiles into ReportTemplate at load time.
ReportTemplateString string `json:"report_template,omitempty"`
// ReportTemplateStrings is a mapping of template comments.
// Use `org/repo`, `org` or `*` as a key.
ReportTemplateStrings map[string]string `json:"report_templates,omitempty"`
// ReportTemplates is a mapping of templates that is compliled at load
// time from ReportTemplateStrings.
ReportTemplates map[string]*template.Template `json:"-"`
// MaxConcurrency is the maximum number of tests running concurrently that
// will be allowed by the controller. 0 implies no limit.
MaxConcurrency int `json:"max_concurrency,omitempty"`
// MaxGoroutines is the maximum number of goroutines spawned inside the
// controller to handle tests. Defaults to 20. Needs to be a positive
// number.
MaxGoroutines int `json:"max_goroutines,omitempty"`
}
// ReportTemplateForRepo returns the template that belong to a specific repository.
// If the repository doesn't exist in the report_templates configuration it will
// inherit the values from its organization, otherwise the default values will be used.
func (c *Controller) ReportTemplateForRepo(refs *prowapi.Refs) *template.Template {
def := c.ReportTemplates["*"]
if refs == nil {
return def
}
orgRepo := fmt.Sprintf("%s/%s", refs.Org, refs.Repo)
if tmplByRepo, ok := c.ReportTemplates[orgRepo]; ok {
return tmplByRepo
}
if tmplByOrg, ok := c.ReportTemplates[refs.Org]; ok {
return tmplByOrg
}
return def
}
// Plank is config for the plank controller.
type Plank struct {
Controller `json:",inline"`
// PodPendingTimeout is after how long the controller will perform a garbage
// collection on pending pods. Defaults to 10 minutes.
PodPendingTimeout *metav1.Duration `json:"pod_pending_timeout,omitempty"`
// PodRunningTimeout is after how long the controller will abort a prowjob pod
// stuck in running state. Defaults to two days.
PodRunningTimeout *metav1.Duration `json:"pod_running_timeout,omitempty"`
// PodUnscheduledTimeout is after how long the controller will abort a prowjob
// stuck in an unscheduled state. Defaults to 5 minutes.
PodUnscheduledTimeout *metav1.Duration `json:"pod_unscheduled_timeout,omitempty"`
// DefaultDecorationConfigs holds the default decoration config for specific values.
// Each entry in the slice specifies Repo and Cluster regexp filter fields to
// match against jobs and a corresponding DecorationConfig. All entries that
// match a job are used. Later matching entries override the fields of earlier
// matching entries.
// This field is populated either directly from DefaultDecorationConfigEntries,
// or by converting DefaultDecorationConfigsMap, depending on which is specified.
// Alternatively this field may be type `map[string]*prowapi.DecorationConfig`
// Use `org/repo`, `org` or `*` as a key to match against jobs.
DefaultDecorationConfigs []*DefaultDecorationConfigEntry `json:"-"`
// DefaultDecorationConfigsMap is a mapping from 'org', 'org/repo', or the literal string '*',
// to the default decoration config to use for that key. The '*' key matches all jobs.
// (Periodics use extra_refs[0] for matching if present.)
// This field is mutually exclusive with the DefaultDecorationConfigEntries field.
DefaultDecorationConfigsMap map[string]*prowapi.DecorationConfig `json:"default_decoration_configs,omitempty"`
// DefaultDecorationConfigEntries holds the default decoration config for specific values.
// Each entry in the slice specifies Repo and Cluster regexp filter fields to
// match against jobs and a corresponding DecorationConfig. All entries that
// match a job are used. Later matching entries override the fields of earlier
// matching entries.
// This field is mutually exclusive with the DefaultDecorationConfigsMap field.
DefaultDecorationConfigEntries []*DefaultDecorationConfigEntry `json:"default_decoration_config_entries,omitempty"`
// JobURLPrefixConfig is the host and path prefix under which job details
// will be viewable. Use `org/repo`, `org` or `*`as key and an url as value
JobURLPrefixConfig map[string]string `json:"job_url_prefix_config,omitempty"`
// JobURLPrefixDisableAppendStorageProvider disables that the storageProvider is
// automatically appended to the JobURLPrefix
JobURLPrefixDisableAppendStorageProvider bool `json:"jobURLPrefixDisableAppendStorageProvider,omitempty"`
}
// DefaultDecorationConfigEntry contains a DecorationConfig and a set of
// filters to use to determine if the config should be used as a default for a
// given ProwJob. When multiple of these entries match a ProwJob, they are all
// merged with later entries overriding values from earlier entries.
type DefaultDecorationConfigEntry struct {
// Matching/filtering fields. All filters must match for an entry to match.
// OrgRepo matches against the "org" or "org/repo" that the presubmit or postsubmit
// is associated with. If the job is a periodic, extra_refs[0] is used. If the
// job is a periodic without extra_refs, the empty string will be used.
// If this field is omitted all jobs will match.
OrgRepo string `json:"repo,omitempty"`
// Cluster matches against the cluster alias of the build cluster that the
// ProwJob is configured to run on. Recall that ProwJobs default to running on
// the "default" build cluster if they omit the "cluster" field in config.
Cluster string `json:"cluster,omitempty"`
// Config is the DecorationConfig to apply if the filter fields all match the
// ProwJob. Note that when multiple entries match a ProwJob they are all used
// by sequentially merging with later entries overriding fields from earlier
// entries.
Config *prowapi.DecorationConfig `json:"config,omitempty"`
}
// matches returns true iff all the filters for the entry match a job.
func (d *DefaultDecorationConfigEntry) matches(repo, cluster string) bool {
repoMatch := d.OrgRepo == "" || d.OrgRepo == "*" || d.OrgRepo == repo || d.OrgRepo == strings.Split(repo, "/")[0]
clusterMatch := d.Cluster == "" || d.Cluster == "*" || d.Cluster == cluster
return repoMatch && clusterMatch
}
// mergeDefaultDecorationConfig finds all matching DefaultDecorationConfigEntry
// for a job and merges them sequentially before merging into the job's own
// DecorationConfig. Configs merged later override values from earlier configs.
func (p *Plank) mergeDefaultDecorationConfig(repo, cluster string, jobDC *prowapi.DecorationConfig) *prowapi.DecorationConfig {
var merged *prowapi.DecorationConfig
for _, entry := range p.DefaultDecorationConfigs {
if entry.matches(repo, cluster) {
merged = entry.Config.ApplyDefault(merged)
}
}
merged = jobDC.ApplyDefault(merged)
if merged == nil {
merged = &prowapi.DecorationConfig{}
}
return merged
}
// GuessDefaultDecorationConfig attempts to find the resolved default decoration
// config for a given repo and cluster. It is primarily used for best effort
// guesses about GCS configuration for undecorated jobs.
func (p *Plank) GuessDefaultDecorationConfig(repo, cluster string) *prowapi.DecorationConfig {
return p.mergeDefaultDecorationConfig(repo, cluster, nil)
}
// defaultDecorationMapToSlice converts the old DefaultDecorationConfigs format:
// map[string]*prowapi.DecorationConfig) to the new format: []*DefaultDecorationConfigEntry
func defaultDecorationMapToSlice(m map[string]*prowapi.DecorationConfig) []*DefaultDecorationConfigEntry {
var entries []*DefaultDecorationConfigEntry
add := func(repo string, dc *prowapi.DecorationConfig) {
entries = append(entries, &DefaultDecorationConfigEntry{
OrgRepo: repo,
Cluster: "",
Config: dc,
})
}
// Ensure "*" comes first...
if dc, exists := m["*"]; exists {
add("*", dc)
}
// then orgs...
for key, dc := range m {
if key == "*" || strings.Contains(key, "/") {
continue
}
add(key, dc)
}
// then repos.
for key, dc := range m {
if key == "*" || !strings.Contains(key, "/") {
continue
}
add(key, dc)
}
return entries
}
// DefaultDecorationMapToSliceTesting is a convenience function that is exposed
// to allow unit tests to convert the old map format to the new slice format.
// It should only be used in testing.
func DefaultDecorationMapToSliceTesting(m map[string]*prowapi.DecorationConfig) []*DefaultDecorationConfigEntry {
return defaultDecorationMapToSlice(m)
}
// FinalizeDefaultDecorationConfigs prepares the entries of
// Plank.DefaultDecorationConfigs for use finalizing job config.
// It parses the value of p.DefaultDecorationConfigsRaw into either the old map
// format or the new slice format:
// Old format: map[string]*prowapi.DecorationConfig where the key is org,
// org/repo, or "*".
// New format: []*DefaultDecorationConfigEntry
// If the old format is parsed it is converted to the new format, then all
// filter regexp are compiled.
func (p *Plank) FinalizeDefaultDecorationConfigs() error {
mapped, sliced := len(p.DefaultDecorationConfigsMap) > 0, len(p.DefaultDecorationConfigEntries) > 0
if mapped && sliced {
return fmt.Errorf("plank.default_decoration_configs and plank.default_decoration_config_entries are mutually exclusive, please use one or the other")
}
if mapped {
p.DefaultDecorationConfigs = defaultDecorationMapToSlice(p.DefaultDecorationConfigsMap)
} else {
p.DefaultDecorationConfigs = p.DefaultDecorationConfigEntries
}
return nil
}
// GetJobURLPrefix gets the job url prefix from the config
// for the given refs.
func (p Plank) GetJobURLPrefix(pj *prowapi.ProwJob) string {
if pj.Spec.DecorationConfig != nil && pj.Spec.DecorationConfig.GCSConfiguration != nil && pj.Spec.DecorationConfig.GCSConfiguration.JobURLPrefix != "" {
return pj.Spec.DecorationConfig.GCSConfiguration.JobURLPrefix
}
var org, repo string
if pj.Spec.Refs != nil {
org = pj.Spec.Refs.Org
repo = pj.Spec.Refs.Repo
} else if len(pj.Spec.ExtraRefs) > 0 {
org = pj.Spec.ExtraRefs[0].Org
repo = pj.Spec.ExtraRefs[0].Repo
}
if org == "" {
return p.JobURLPrefixConfig["*"]
}
if p.JobURLPrefixConfig[fmt.Sprintf("%s/%s", org, repo)] != "" {
return p.JobURLPrefixConfig[fmt.Sprintf("%s/%s", org, repo)]
}
if p.JobURLPrefixConfig[org] != "" {
return p.JobURLPrefixConfig[org]
}
return p.JobURLPrefixConfig["*"]
}
// Gerrit is config for the gerrit controller.
type Gerrit struct {
// TickInterval is how often we do a sync with binded gerrit instance
TickInterval *metav1.Duration `json:"tick_interval,omitempty"`
// RateLimit defines how many changes to query per gerrit API call
// default is 5
RateLimit int `json:"ratelimit,omitempty"`
// DeckURL is the root URL of Deck. This is used to construct links to
// job runs for a given CL.
DeckURL string `json:"deck_url,omitempty"`
}
// Horologium is config for the Horologium.
type Horologium struct {
// TickInterval is the interval in which we check if new jobs need to be
// created. Defaults to one minute.
TickInterval *metav1.Duration `json:"tick_interval,omitempty"`
}
// JenkinsOperator is config for the jenkins-operator controller.
type JenkinsOperator struct {
Controller `json:",inline"`
// LabelSelectorString compiles into LabelSelector at load time.
// If set, this option needs to match --label-selector used by
// the desired jenkins-operator. This option is considered
// invalid when provided with a single jenkins-operator config.
//
// For label selector syntax, see below:
// https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors
LabelSelectorString string `json:"label_selector,omitempty"`
// LabelSelector is used so different jenkins-operator replicas
// can use their own configuration.
LabelSelector labels.Selector `json:"-"`
}
// GitHubReporter holds the config for report behavior in github
type GitHubReporter struct {
// JobTypesToReport is used to determine which type of prowjob
// should be reported to github
//
// defaults to both presubmit and postsubmit jobs.
JobTypesToReport []prowapi.ProwJobType `json:"job_types_to_report,omitempty"`
}
// Sinker is config for the sinker controller.
type Sinker struct {
// ResyncPeriod is how often the controller will perform a garbage
// collection. Defaults to one hour.
ResyncPeriod *metav1.Duration `json:"resync_period,omitempty"`
// MaxProwJobAge is how old a ProwJob can be before it is garbage-collected.
// Defaults to one week.
MaxProwJobAge *metav1.Duration `json:"max_prowjob_age,omitempty"`
// MaxPodAge is how old a Pod can be before it is garbage-collected.
// Defaults to one day.
MaxPodAge *metav1.Duration `json:"max_pod_age,omitempty"`
// TerminatedPodTTL is how long a Pod can live after termination before it is
// garbage collected.
// Defaults to matching MaxPodAge.
TerminatedPodTTL *metav1.Duration `json:"terminated_pod_ttl,omitempty"`
// ExcludeClusters are build clusters that don't want to be managed by sinker
ExcludeClusters []string `json:"exclude_clusters,omitempty"`
}
// LensConfig names a specific lens, and optionally provides some configuration for it.
type LensConfig struct {
// Name is the name of the lens.
Name string `json:"name"`
// Config is some lens-specific configuration. Interpreting it is the responsibility of the
// lens in question.
Config json.RawMessage `json:"config,omitempty"`
}
// LensFileConfig is a single entry under Lenses, describing how to configure a lens
// to read a given set of files.
type LensFileConfig struct {
// RequiredFiles is a list of regexes of file paths that must all be present for a lens to appear.
// The list entries are ANDed together, i.e. all of them are required. You can achieve an OR
// by using a pipe in a regex.
RequiredFiles []string `json:"required_files"`
// OptionalFiles is a list of regexes of file paths that will be provided to the lens if they are
// present, but will not preclude the lens being rendered by their absence.
// The list entries are ORed together, so if only one of them is present it will be provided to
// the lens even if the others are not.
OptionalFiles []string `json:"optional_files,omitempty"`
// Lens is the lens to use, alongside any lens-specific configuration.
Lens LensConfig `json:"lens"`
// RemoteConfig specifies how to access remote lenses
RemoteConfig *LensRemoteConfig `json:"remote_config,omitempty"`
}
// LensRemoteConfig is the configuration for a remote lens.
type LensRemoteConfig struct {
// The endpoint for the lense
Endpoint string `json:"endpoint"`
// The parsed endpoint
ParsedEndpoint *url.URL `json:"-"`
// The endpoint for static resources
StaticRoot string `json:"static_root"`
// The human-readable title for the lens
Title string `json:"title"`
// Priority for lens ordering, lowest priority first
Priority *uint `json:"priority"`
// HideTitle defines if we will keep showing the title after lens loads
HideTitle *bool `json:"hide_title"`
}
// Spyglass holds config for Spyglass
type Spyglass struct {
// Lenses is a list of lens configurations.
Lenses []LensFileConfig `json:"lenses,omitempty"`
// Viewers is deprecated, prefer Lenses instead.
// Viewers was a map of Regexp strings to viewer names that defines which sets
// of artifacts need to be consumed by which viewers. It is copied in to Lenses at load time.
Viewers map[string][]string `json:"viewers,omitempty"`
// RegexCache is a map of lens regexp strings to their compiled equivalents.
RegexCache map[string]*regexp.Regexp `json:"-"`
// SizeLimit is the max size artifact in bytes that Spyglass will attempt to
// read in entirety. This will only affect viewers attempting to use
// artifact.ReadAll(). To exclude outlier artifacts, set this limit to
// expected file size + variance. To include all artifacts with high
// probability, use 2*maximum observed artifact size.
SizeLimit int64 `json:"size_limit,omitempty"`
// GCSBrowserPrefix is used to generate a link to a human-usable GCS browser.
// If left empty, the link will be not be shown. Otherwise, a GCS path (with no
// prefix or scheme) will be appended to GCSBrowserPrefix and shown to the user.
GCSBrowserPrefix string `json:"gcs_browser_prefix,omitempty"`
// GCSBrowserPrefixes are used to generate a link to a human-usable GCS browser.
// They are mapped by org, org/repo or '*' which is the default value.
GCSBrowserPrefixes GCSBrowserPrefixes `json:"gcs_browser_prefixes,omitempty"`
// If set, Announcement is used as a Go HTML template string to be displayed at the top of
// each spyglass page. Using HTML in the template is acceptable.
// Currently the only variable available is .ArtifactPath, which contains the GCS path for the job artifacts.
Announcement string `json:"announcement,omitempty"`
// TestGridConfig is the path to the TestGrid config proto. If the path begins with
// "gs://" it is assumed to be a GCS reference, otherwise it is read from the local filesystem.
// If left blank, TestGrid links will not appear.
TestGridConfig string `json:"testgrid_config,omitempty"`
// TestGridRoot is the root URL to the TestGrid frontend, e.g. "https://testgrid.k8s.io/".
// If left blank, TestGrid links will not appear.
TestGridRoot string `json:"testgrid_root,omitempty"`
}
type GCSBrowserPrefixes map[string]string
func (p GCSBrowserPrefixes) GetGCSBrowserPrefix(org, repo string) string {
if prefix, exists := p[fmt.Sprintf("%s/%s", org, repo)]; exists {
return prefix
}
if prefix, exists := p[org]; exists {
return prefix
}
return p["*"]
}
// Deck holds config for deck.
type Deck struct {
// Spyglass specifies which viewers will be used for which artifacts when viewing a job in Deck
Spyglass Spyglass `json:"spyglass,omitempty"`
// TideUpdatePeriod specifies how often Deck will fetch status from Tide. Defaults to 10s.
TideUpdatePeriod *metav1.Duration `json:"tide_update_period,omitempty"`
// HiddenRepos is a list of orgs and/or repos that should not be displayed by Deck.
HiddenRepos []string `json:"hidden_repos,omitempty"`
// ExternalAgentLogs ensures external agents can expose
// their logs in prow.
ExternalAgentLogs []ExternalAgentLog `json:"external_agent_logs,omitempty"`
// Branding of the frontend
Branding *Branding `json:"branding,omitempty"`
// GoogleAnalytics, if specified, include a Google Analytics tracking code on each page.
GoogleAnalytics string `json:"google_analytics,omitempty"`
// RerunAuthConfigs is a map of configs that specify who is able to trigger job reruns. The field
// accepts a key of: `org/repo`, `org` or `*` (wildcard) to define what GitHub org (or repo) a particular
// config applies to and a value of: `RerunAuthConfig` struct to define the users/groups authorized to rerun jobs.
RerunAuthConfigs RerunAuthConfigs `json:"rerun_auth_configs,omitempty"`
// SkipStoragePathValidation skips validation that restricts artifact requests to specific buckets.
// By default, buckets listed in the GCSConfiguration are automatically allowed.
// Additional locations can be allowed via `AdditionalAllowedBuckets` fields.
// When unspecified (nil), it defaults to true (until ~Jan 2021).
SkipStoragePathValidation *bool `json:"skip_storage_path_validation,omitempty"`
// AdditionalAllowedBuckets is a list of storage buckets to allow in artifact requests
// (in addition to those listed in the GCSConfiguration).
// Setting this field requires "SkipStoragePathValidation" also be set to `false`.
AdditionalAllowedBuckets []string `json:"additional_allowed_buckets,omitempty"`
// AllKnownStorageBuckets contains all storage buckets configured in all of the
// job configs.
AllKnownStorageBuckets sets.String `json:"-"`
}
// Validate performs validation and sanitization on the Deck object.
func (d *Deck) Validate() error {
if len(d.AdditionalAllowedBuckets) > 0 && !d.shouldValidateStorageBuckets() {
return fmt.Errorf("deck.skip_storage_path_validation is enabled despite deck.additional_allowed_buckets being configured: %v", d.AdditionalAllowedBuckets)
}
// Note: The RerunAuthConfigs logic isn't deprecated, only the above RerunAuthConfig stuff is
if d.RerunAuthConfigs != nil {
for k, config := range d.RerunAuthConfigs {
if err := config.Validate(); err != nil {
return fmt.Errorf("rerun_auth_configs[%s]: %v", k, err)
}
}
}
return nil
}
type notAllowedBucketError struct {
err error
}
func (ne notAllowedBucketError) Error() string {
return fmt.Sprintf("bucket not in allowed list; you may allow it by including it in `deck.additional_allowed_buckets`: %s", ne.err.Error())
}
func (notAllowedBucketError) Is(err error) bool {
_, ok := err.(notAllowedBucketError)
return ok
}
// NotAllowedBucketError wraps an error and return a notAllowedBucketError error
func NotAllowedBucketError(err error) error {
return ¬AllowedBucketError{err: err}
}
func IsNotAllowedBucketError(err error) bool {
return errors.Is(err, notAllowedBucketError{})
}
// ValidateStorageBucket validates a storage bucket (unless the `Deck.SkipStoragePathValidation` field is true).
// The bucket name must be included in any of the following:
// 1) Any job's `.DecorationConfig.GCSConfiguration.Bucket` (except jobs defined externally via InRepoConfig)
// 2) `Plank.DefaultDecorationConfigs.GCSConfiguration.Bucket`
// 3) `Deck.AdditionalAllowedBuckets`
func (c *Config) ValidateStorageBucket(bucketName string) error {
if !c.Deck.shouldValidateStorageBuckets() {
return nil
}
if !c.Deck.AllKnownStorageBuckets.Has(bucketName) {
return NotAllowedBucketError(fmt.Errorf("bucket %q not in allowed list (%v)", bucketName, c.Deck.AllKnownStorageBuckets.List()))
}
return nil
}
// shouldValidateStorageBuckets returns whether or not the Deck's storage path should be validated.
// Validation could be either enabled by default or explicitly turned off.
func (d *Deck) shouldValidateStorageBuckets() bool {
if d.SkipStoragePathValidation == nil {
return true
}
return !*d.SkipStoragePathValidation
}
func calculateStorageBuckets(c *Config) sets.String {
knownBuckets := sets.NewString(c.Deck.AdditionalAllowedBuckets...)
for _, dc := range c.Plank.DefaultDecorationConfigs {
if dc.Config != nil && dc.Config.GCSConfiguration != nil && dc.Config.GCSConfiguration.Bucket != "" {
knownBuckets.Insert(stripProviderPrefixFromBucket(dc.Config.GCSConfiguration.Bucket))
}
}
for _, j := range c.Periodics {
if j.DecorationConfig != nil && j.DecorationConfig.GCSConfiguration != nil {
knownBuckets.Insert(stripProviderPrefixFromBucket(j.DecorationConfig.GCSConfiguration.Bucket))
}
}
for _, jobs := range c.PresubmitsStatic {
for _, j := range jobs {
if j.DecorationConfig != nil && j.DecorationConfig.GCSConfiguration != nil {
knownBuckets.Insert(stripProviderPrefixFromBucket(j.DecorationConfig.GCSConfiguration.Bucket))
}
}
}
for _, jobs := range c.PostsubmitsStatic {
for _, j := range jobs {
if j.DecorationConfig != nil && j.DecorationConfig.GCSConfiguration != nil {
knownBuckets.Insert(stripProviderPrefixFromBucket(j.DecorationConfig.GCSConfiguration.Bucket))
}
}
}
return knownBuckets
}
func stripProviderPrefixFromBucket(bucket string) string {
if split := strings.Split(bucket, "://"); len(split) == 2 {
return split[1]
}
return bucket
}
// ExternalAgentLog ensures an external agent like Jenkins can expose
// its logs in prow.
type ExternalAgentLog struct {
// Agent is an external prow agent that supports exposing
// logs via deck.
Agent string `json:"agent,omitempty"`
// SelectorString compiles into Selector at load time.
SelectorString string `json:"selector,omitempty"`
// Selector can be used in prow deployments where the workload has
// been sharded between controllers of the same agent. For more info
// see https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors
Selector labels.Selector `json:"-"`
// URLTemplateString compiles into URLTemplate at load time.
URLTemplateString string `json:"url_template,omitempty"`
// URLTemplate is compiled at load time from URLTemplateString. It
// will be passed a prowapi.ProwJob and the generated URL should provide
// logs for the ProwJob.
URLTemplate *template.Template `json:"-"`
}
// Branding holds branding configuration for deck.
type Branding struct {
// Logo is the location of the logo that will be loaded in deck.
Logo string `json:"logo,omitempty"`
// Favicon is the location of the favicon that will be loaded in deck.
Favicon string `json:"favicon,omitempty"`
// BackgroundColor is the color of the background.
BackgroundColor string `json:"background_color,omitempty"`
// HeaderColor is the color of the header.
HeaderColor string `json:"header_color,omitempty"`
}
// RerunAuthConfigs represents the configs for rerun authorization in Deck.
// Use `org/repo`, `org` or `*` as key and a `RerunAuthConfig` struct as value.