-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
config.go
1841 lines (1612 loc) · 61 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/filepath"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"text/template"
"time"
"github.com/sirupsen/logrus"
"gopkg.in/robfig/cron.v2"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/apimachinery/pkg/util/validation"
"sigs.k8s.io/yaml"
pipelinev1alpha1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1"
prowapi "k8s.io/test-infra/prow/apis/prowjobs/v1"
"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"
)
// 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"`
// Full repo name (such as "kubernetes/kubernetes") -> list of jobs.
Postsubmits 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:"-"`
// FakeInRepoConfig is used for tests. Its key is the headSHA.
FakeInRepoConfig map[string][]Presubmit `json:"-"`
}
// ProwConfig is config for all prow controllers
type ProwConfig struct {
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,omitempty"`
Gerrit Gerrit `json:"gerrit,omitempty"`
GitHubReporter GitHubReporter `json:"github_reporter,omitempty"`
SlackReporter *SlackReporter `json:"slack_reporter,omitempty"`
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"`
// OwnersDirBlacklist is used to configure regular expressions matching directories
// to ignore when searching for OWNERS{,_ALIAS} files in a repo.
OwnersDirBlacklist OwnersDirBlacklist `json:"owners_dir_blacklist,omitempty"`
// Pub/Sub Subscriptions that we want to listen to
PubSubSubscriptions PubsubSubscriptions `json:"pubsub_subscriptions,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"`
}
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"`
}
// InRepoConfigEnabled returns whether InRepoConfig is enabled. Currently
// a no-op that always returns false, as the underlying feature is not implemented
// yet. See https://github.com/kubernetes/test-infra/issues/13370 for a current
// status.
func (c *Config) InRepoConfigEnabled(identifier string) bool {
// Used in tests
if c.FakeInRepoConfig != nil {
return true
}
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
}
// 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
}
// GetPresubmits will return all presumits for the given identifier.
// Once https://github.com/kubernetes/test-infra/issues/13370 is resolved, it will
// also return Presubmits that are versioned inside the tested repo, if that 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, bust must
// nilcheck that pointer before accessing it.
func (c *Config) GetPresubmits(gc git.ClientFactory, identifier string, baseSHAGetter RefGetter, headSHAGetters ...RefGetter) ([]Presubmit, error) {
if identifier == "" {
return nil, errors.New("no identifier for repo given")
}
if !c.InRepoConfigEnabled(identifier) {
return c.PresubmitsStatic[identifier], 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)
}
// Pending implementation of https://github.com/kubernetes/test-infra/issues/13370
// Currently, only a fake implementation exists for tests.
_ = baseSHA
if c.FakeInRepoConfig != nil {
return append(c.PresubmitsStatic[identifier], c.FakeInRepoConfig[strings.Join(headSHAs, "")]...), nil
}
return nil, errors.New("inrepoconfig is not yet implemented :/")
}
// OwnersDirBlacklist is used to configure regular expressions matching directories
// to ignore when searching for OWNERS{,_ALIAS} files in a repo.
type OwnersDirBlacklist struct {
// Repos configures a directory blacklist per repo (or org)
Repos map[string][]string `json:"repos,omitempty"`
// Default configures a default blacklist for all repos (or orgs).
// Some directories like ".git", "_output" and "vendor/.*/OWNERS"
// are already preconfigured to be blacklisted, 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 blacklisted.
// If set, IgnorePreconfiguredDefaults will not add these preconfigured directories
// to the blacklist.
IgnorePreconfiguredDefaults bool `json:"ignore_preconfigured_defaults,omitempty"`
}
// DirBlacklist returns regular expressions matching directories to ignore when
// searching for OWNERS{,_ALIAS} files in a repo.
func (ownersDirBlacklist OwnersDirBlacklist) DirBlacklist(org, repo string) (blacklist []string) {
blacklist = append(blacklist, ownersDirBlacklist.Default...)
if bl, ok := ownersDirBlacklist.Repos[org]; ok {
blacklist = append(blacklist, bl...)
}
if bl, ok := ownersDirBlacklist.Repos[org+"/"+repo]; ok {
blacklist = append(blacklist, bl...)
}
preconfiguredDefaults := []string{"\\.git$", "_output$", "vendor/.*/.*"}
if !ownersDirBlacklist.IgnorePreconfiguredDefaults {
blacklist = append(blacklist, 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"`
// ReportTemplate is compiled at load time from ReportTemplateString. It
// will be passed a prowapi.ProwJob and can provide an optional blurb below
// the test failures comment.
ReportTemplate *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"`
// Deprecated: AllowCancellations enables aborting presubmit jobs for
// commits that have been superseded by newer commits in GitHub pull
// requests.
// This option will be removed and set to always true in March 2020.
AllowCancellations bool `json:"allow_cancellations,omitempty"`
}
// 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 one day.
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"`
// DefaultDecorationConfig are defaults for shared fields for ProwJobs
// that request to have their PodSpecs decorated.
// This will be deprecated on April 2020, and it will be replaces with DefaultDecorationConfigs['*'] instead.
DefaultDecorationConfig *prowapi.DecorationConfig `json:"default_decoration_config,omitempty"`
// DefaultDecorationConfigs holds the default decoration config for specific values.
// This config will be used on each Presubmit and Postsubmit's corresponding org/repo, and on Periodics
// if extraRefs[0] exists. The missing fields will be merged with the DefaultDecorationConfig.
// Use `org/repo`, `org` or `*` as a key.
DefaultDecorationConfigs map[string]*prowapi.DecorationConfig `json:"default_decoration_configs,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"`
}
func (p Plank) GetDefaultDecorationConfigs(repo string) *prowapi.DecorationConfig {
def := p.DefaultDecorationConfigs["*"]
if dcByRepo, ok := p.DefaultDecorationConfigs[repo]; ok {
return dcByRepo.ApplyDefault(def)
}
org := strings.Split(repo, "/")[0]
if dcByOrg, ok := p.DefaultDecorationConfigs[org]; ok {
return dcByOrg.ApplyDefault(def)
}
return def
}
func (p Plank) GetJobURLPrefix(refs *prowapi.Refs) string {
if refs == nil {
return p.JobURLPrefixConfig["*"]
}
if p.JobURLPrefixConfig[fmt.Sprintf("%s/%s", refs.Org, refs.Repo)] != "" {
return p.JobURLPrefixConfig[fmt.Sprintf("%s/%s", refs.Org, refs.Repo)]
}
if p.JobURLPrefixConfig[refs.Org] != "" {
return p.JobURLPrefixConfig[refs.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"`
}
// 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"`
}
// 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"`
}
// 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"`
// 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"`
}
// 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"`
// RerunAuthConfig specifies who is able to trigger job reruns if that feature is enabled.
// The permissions here apply to all jobs. GitHub teams are not yet supported
// for the global Deck config.
RerunAuthConfig prowapi.RerunAuthConfig `json:"rerun_auth_config,omitempty"`
}
// 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"`
}
// PubSubSubscriptions maps GCP projects to a list of Topics.
type PubsubSubscriptions map[string][]string
// GitHubOptions allows users to control how prow applications display GitHub website links.
type GitHubOptions struct {
// LinkURLFromConfig is the string representation of the link_url config parameter.
// This config parameter allows users to override the default GitHub link url for all plugins.
// If this option is not set, we assume "https://github.com".
LinkURLFromConfig string `json:"link_url,omitempty"`
// LinkURL is the url representation of LinkURLFromConfig. This variable should be used
// in all places internally.
LinkURL *url.URL `json:"-"`
}
// SlackReporter represents the config for the Slack reporter. The channel can be overridden
// on the job via the .reporter_config.slack.channel property
type SlackReporter struct {
JobTypesToReport []prowapi.ProwJobType `json:"job_types_to_report"`
JobStatesToReport []prowapi.ProwJobState `json:"job_states_to_report"`
Channel string `json:"channel"`
ReportTemplate string `json:"report_template"`
}
// SlackReporterConfigs represents the config for the Slack reporter(s).
// Use `org/repo`, `org` or `*` as key and an `SlackReporter` struct as value.
type SlackReporterConfigs map[string]SlackReporter
func (cfg SlackReporterConfigs) GetSlackReporter(refs *prowapi.Refs) SlackReporter {
if refs == nil {
return cfg["*"]
}
if slack, exists := cfg[fmt.Sprintf("%s/%s", refs.Org, refs.Repo)]; exists {
return slack
}
if slack, exists := cfg[refs.Org]; exists {
return slack
}
return cfg["*"]
}
func (cfg *SlackReporter) DefaultAndValidate() error {
// Default ReportTemplate
if cfg.ReportTemplate == "" {
cfg.ReportTemplate = `Job {{.Spec.Job}} of type {{.Spec.Type}} ended with state {{.Status.State}}. <{{.Status.URL}}|View logs>`
}
if cfg.Channel == "" {
return errors.New("channel must be set")
}
// Validate ReportTemplate
tmpl, err := template.New("").Parse(cfg.ReportTemplate)
if err != nil {
return fmt.Errorf("failed to parse template: %v", err)
}
if err := tmpl.Execute(&bytes.Buffer{}, &prowapi.ProwJob{}); err != nil {
return fmt.Errorf("failed to execute report_template: %v", err)
}
return nil
}
// Load loads and parses the config at path.
func Load(prowConfig, jobConfig string) (c *Config, err error) {
// we never want config loading to take down the prow components
defer func() {
if r := recover(); r != nil {
c, err = nil, fmt.Errorf("panic loading config: %v", r)
}
}()
c, err = loadConfig(prowConfig, jobConfig)
if err != nil {
return nil, err
}
if err := c.finalizeJobConfig(); err != nil {
return nil, err
}
if err := c.validateComponentConfig(); err != nil {
return nil, err
}
if err := c.validateJobConfig(); err != nil {
return nil, err
}
return c, nil
}
// ReadJobConfig reads the JobConfig yaml, but does not expand or validate it.
func ReadJobConfig(jobConfig string) (JobConfig, error) {
stat, err := os.Stat(jobConfig)
if err != nil {
return JobConfig{}, err
}
if !stat.IsDir() {
// still support a single file
var jc JobConfig
if err := yamlToConfig(jobConfig, &jc); err != nil {
return JobConfig{}, err
}
return jc, nil
}
// we need to ensure all config files have unique basenames,
// since updateconfig plugin will use basename as a key in the configmap
uniqueBasenames := sets.String{}
jc := JobConfig{}
err = filepath.Walk(jobConfig, func(path string, info os.FileInfo, err error) error {
if err != nil {
logrus.WithError(err).Errorf("walking path %q.", path)
// bad file should not stop us from parsing the directory
return nil
}
if strings.HasPrefix(info.Name(), "..") {
// kubernetes volumes also include files we
// should not look be looking into for keys
if info.IsDir() {
return filepath.SkipDir
}
return nil
}
if filepath.Ext(path) != ".yaml" && filepath.Ext(path) != ".yml" {
return nil
}
if info.IsDir() {
return nil
}
base := filepath.Base(path)
if uniqueBasenames.Has(base) {
return fmt.Errorf("duplicated basename is not allowed: %s", base)
}
uniqueBasenames.Insert(base)
var subConfig JobConfig
if err := yamlToConfig(path, &subConfig); err != nil {
return err
}
jc, err = mergeJobConfigs(jc, subConfig)
return err
})
if err != nil {
return JobConfig{}, err
}
return jc, nil
}
// loadConfig loads one or multiple config files and returns a config object.
func loadConfig(prowConfig, jobConfig string) (*Config, error) {
stat, err := os.Stat(prowConfig)
if err != nil {
return nil, err
}
if stat.IsDir() {
return nil, fmt.Errorf("prowConfig cannot be a dir - %s", prowConfig)
}
var nc Config
if err := yamlToConfig(prowConfig, &nc); err != nil {
return nil, err
}
if err := parseProwConfig(&nc); err != nil {
return nil, err
}
nc.AllRepos = sets.String{}
for _, query := range nc.Tide.Queries {
for _, repo := range query.Repos {
nc.AllRepos.Insert(repo)
}
}
// TODO(krzyzacy): temporary allow empty jobconfig
// also temporary allow job config in prow config
if jobConfig == "" {
return &nc, nil
}
jc, err := ReadJobConfig(jobConfig)
if err != nil {
return nil, err
}
if err := nc.mergeJobConfig(jc); err != nil {
return nil, err
}
return &nc, nil
}
// yamlToConfig converts a yaml file into a Config object
func yamlToConfig(path string, nc interface{}) error {
b, err := ReadFileMaybeGZIP(path)
if err != nil {
return fmt.Errorf("error reading %s: %v", path, err)
}
if err := yaml.Unmarshal(b, nc); err != nil {
return fmt.Errorf("error unmarshaling %s: %v", path, err)
}
var jc *JobConfig
switch v := nc.(type) {
case *JobConfig:
jc = v
case *Config:
jc = &v.JobConfig
}
for rep := range jc.PresubmitsStatic {
var fix func(*Presubmit)
fix = func(job *Presubmit) {
job.SourcePath = path
}
for i := range jc.PresubmitsStatic[rep] {
fix(&jc.PresubmitsStatic[rep][i])
}
}
for rep := range jc.Postsubmits {
var fix func(*Postsubmit)
fix = func(job *Postsubmit) {
job.SourcePath = path
}
for i := range jc.Postsubmits[rep] {
fix(&jc.Postsubmits[rep][i])
}
}
var fix func(*Periodic)
fix = func(job *Periodic) {
job.SourcePath = path
}
for i := range jc.Periodics {
fix(&jc.Periodics[i])
}
return nil
}
// ReadFileMaybeGZIP wraps ioutil.ReadFile, returning the decompressed contents
// if the file is gzipped, or otherwise the raw contents
func ReadFileMaybeGZIP(path string) ([]byte, error) {
b, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
// check if file contains gzip header: http://www.zlib.org/rfc-gzip.html
if !bytes.HasPrefix(b, []byte("\x1F\x8B")) {
// go ahead and return the contents if not gzipped
return b, nil
}
// otherwise decode
gzipReader, err := gzip.NewReader(bytes.NewBuffer(b))
if err != nil {
return nil, err
}
return ioutil.ReadAll(gzipReader)
}
func (c *Config) mergeJobConfig(jc JobConfig) error {
m, err := mergeJobConfigs(JobConfig{
Presets: c.Presets,
PresubmitsStatic: c.PresubmitsStatic,
Periodics: c.Periodics,
Postsubmits: c.Postsubmits,
}, jc)
if err != nil {
return err
}
c.Presets = m.Presets
c.PresubmitsStatic = m.PresubmitsStatic
c.Periodics = m.Periodics
c.Postsubmits = m.Postsubmits
return nil
}
// mergeJobConfigs merges two JobConfig together
// It will try to merge:
// - Presubmits
// - Postsubmits
// - Periodics
// - PodPresets
func mergeJobConfigs(a, b JobConfig) (JobConfig, error) {
// Merge everything
// *** Presets ***
c := JobConfig{}
c.Presets = append(a.Presets, b.Presets...)
// validate no duplicated preset key-value pairs
validLabels := map[string]bool{}
for _, preset := range c.Presets {
for label, val := range preset.Labels {
pair := label + ":" + val
if _, ok := validLabels[pair]; ok {
return JobConfig{}, fmt.Errorf("duplicated preset 'label:value' pair : %s", pair)
}
validLabels[pair] = true
}
}
// *** Periodics ***
c.Periodics = append(a.Periodics, b.Periodics...)
// *** Presubmits ***
c.PresubmitsStatic = make(map[string][]Presubmit)
for repo, jobs := range a.PresubmitsStatic {
c.PresubmitsStatic[repo] = jobs
}
for repo, jobs := range b.PresubmitsStatic {
c.PresubmitsStatic[repo] = append(c.PresubmitsStatic[repo], jobs...)
}
// *** Postsubmits ***
c.Postsubmits = make(map[string][]Postsubmit)
for repo, jobs := range a.Postsubmits {
c.Postsubmits[repo] = jobs
}
for repo, jobs := range b.Postsubmits {
c.Postsubmits[repo] = append(c.Postsubmits[repo], jobs...)
}
return c, nil
}
func setPresubmitDecorationDefaults(c *Config, ps *Presubmit, repo string) {
if ps.Decorate {
def := c.Plank.GetDefaultDecorationConfigs(repo)
ps.DecorationConfig = ps.DecorationConfig.ApplyDefault(def)
}
}
func setPostsubmitDecorationDefaults(c *Config, ps *Postsubmit, repo string) {
if ps.Decorate {
def := c.Plank.GetDefaultDecorationConfigs(repo)
ps.DecorationConfig = ps.DecorationConfig.ApplyDefault(def)
}
}
func setPeriodicDecorationDefaults(c *Config, ps *Periodic) {
if ps.Decorate {
var orgRepo string
if len(ps.UtilityConfig.ExtraRefs) > 0 {
orgRepo = fmt.Sprintf("%s/%s", ps.UtilityConfig.ExtraRefs[0].Org, ps.UtilityConfig.ExtraRefs[0].Repo)
}
def := c.Plank.GetDefaultDecorationConfigs(orgRepo)
ps.DecorationConfig = ps.DecorationConfig.ApplyDefault(def)
}
}
// defaultPresubmits defaults the presubmits for one repo
func defaultPresubmits(presubmits []Presubmit, c *Config, repo string) error {
for idx, ps := range presubmits {
setPresubmitDecorationDefaults(c, &presubmits[idx], repo)
if err := resolvePresets(ps.Name, ps.Labels, ps.Spec, c.Presets); err != nil {
return err
}
}
c.defaultPresubmitFields(presubmits)
if err := SetPresubmitRegexes(presubmits); err != nil {
return fmt.Errorf("could not set regex: %v", err)
}
return nil
}
// defaultPostsubmits defaults the postsubmits for one repo
func defaultPostsubmits(postsubmits []Postsubmit, c *Config, repo string) error {
for idx, ps := range postsubmits {
setPostsubmitDecorationDefaults(c, &postsubmits[idx], repo)
if err := resolvePresets(ps.Name, ps.Labels, ps.Spec, c.Presets); err != nil {
return err
}
}
c.defaultPostsubmitFields(postsubmits)
if err := SetPostsubmitRegexes(postsubmits); err != nil {
return fmt.Errorf("could not set regex: %v", err)
}
return nil
}
// defaultPeriodics defaults periodics
func defaultPeriodics(periodics []Periodic, c *Config) error {
c.defaultPeriodicFields(periodics)
for _, periodic := range periodics {
if err := resolvePresets(periodic.Name, periodic.Labels, periodic.Spec, c.Presets); err != nil {
return err
}
}
return nil
}
// finalizeJobConfig mutates and fixes entries for jobspecs
func (c *Config) finalizeJobConfig() error {
if c.decorationRequested() {
if c.Plank.DefaultDecorationConfig != nil {
if len(c.Plank.DefaultDecorationConfigs) > 0 {
return errors.New("both default_decoration_config and default_decoration_configs are specified")
}
logrus.Warning("default_decoration_config will be deprecated on April 2020, and it will be replaced with default_decoration_configs['*'].")
c.Plank.DefaultDecorationConfigs = make(map[string]*prowapi.DecorationConfig)
c.Plank.DefaultDecorationConfigs["*"] = c.Plank.DefaultDecorationConfig
}
if len(c.Plank.DefaultDecorationConfigs) == 0 {