forked from kubernetes/test-infra
-
Notifications
You must be signed in to change notification settings - Fork 5
/
main.go
1507 lines (1360 loc) · 50.3 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
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 2016 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 main
import (
"bytes"
"context"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"errors"
"flag"
"fmt"
"html/template"
"io/ioutil"
"net/http"
"net/url"
"os"
"path"
"strconv"
"strings"
"time"
"cloud.google.com/go/storage"
"github.com/NYTimes/gziphandler"
"github.com/gorilla/csrf"
"github.com/gorilla/sessions"
"github.com/prometheus/client_golang/prometheus"
"github.com/sirupsen/logrus"
"golang.org/x/oauth2"
"google.golang.org/api/option"
coreapi "k8s.io/api/core/v1"
kerrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/util/sets"
corev1 "k8s.io/client-go/kubernetes/typed/core/v1"
"k8s.io/test-infra/prow/interrupts"
"k8s.io/test-infra/prow/simplifypath"
ctrlruntimeclient "sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/manager"
"sigs.k8s.io/yaml"
prowapi "k8s.io/test-infra/prow/apis/prowjobs/v1"
prowv1 "k8s.io/test-infra/prow/client/clientset/versioned/typed/prowjobs/v1"
"k8s.io/test-infra/prow/config"
"k8s.io/test-infra/prow/config/secret"
"k8s.io/test-infra/prow/deck/jobs"
prowflagutil "k8s.io/test-infra/prow/flagutil"
"k8s.io/test-infra/prow/git/v2"
prowgithub "k8s.io/test-infra/prow/github"
"k8s.io/test-infra/prow/githuboauth"
"k8s.io/test-infra/prow/kube"
"k8s.io/test-infra/prow/logrusutil"
"k8s.io/test-infra/prow/metrics"
"k8s.io/test-infra/prow/pjutil"
"k8s.io/test-infra/prow/pluginhelp"
"k8s.io/test-infra/prow/plugins"
"k8s.io/test-infra/prow/plugins/trigger"
"k8s.io/test-infra/prow/prstatus"
"k8s.io/test-infra/prow/spyglass"
// Import standard spyglass viewers
"k8s.io/test-infra/prow/spyglass/lenses"
_ "k8s.io/test-infra/prow/spyglass/lenses/buildlog"
_ "k8s.io/test-infra/prow/spyglass/lenses/coverage"
_ "k8s.io/test-infra/prow/spyglass/lenses/junit"
_ "k8s.io/test-infra/prow/spyglass/lenses/metadata"
_ "k8s.io/test-infra/prow/spyglass/lenses/restcoverage"
)
// Omittable ProwJob fields.
const (
// Annotations maps to the serialized value of <ProwJob>.Annotations.
Annotations string = "annotations"
// Labels maps to the serialized value of <ProwJob>.Labels.
Labels string = "labels"
// DecorationConfig maps to the serialized value of <ProwJob>.Spec.DecorationConfig.
DecorationConfig string = "decoration_config"
// PodSpec maps to the serialized value of <ProwJob>.Spec.PodSpec.
PodSpec string = "pod_spec"
)
type options struct {
configPath string
jobConfigPath string
buildCluster string
kubernetes prowflagutil.KubernetesOptions
github prowflagutil.GitHubOptions
tideURL string
hookURL string
oauthURL string
githubOAuthConfigFile string
cookieSecretFile string
redirectHTTPTo string
hiddenOnly bool
pregeneratedData string
staticFilesLocation string
templateFilesLocation string
showHidden bool
spyglass bool
spyglassFilesLocation string
gcsCredentialsFile string
rerunCreatesJob bool
allowInsecure bool
dryRun bool
pluginConfig string
}
func (o *options) Validate() error {
if err := o.kubernetes.Validate(false); err != nil {
return err
}
if err := o.github.Validate(o.dryRun); err != nil {
return err
}
if o.configPath == "" {
return errors.New("required flag --config-path was unset")
}
// TODO(Katharine): remove this handling after 2019-10-31
// We used to set a default value for --cookie-secret-file, but we also have code that
// assumes we don't. If it's not set, but it is required that it is, and a file exists
// at the old default, we set it back to that default and emit an error.
if o.cookieSecretFile == "" && o.oauthURL != "" {
if _, err := os.Stat("/etc/cookie/secret"); err == nil {
o.cookieSecretFile = "/etc/cookie/secret"
logrus.Error("You haven't set --cookie-secret, but you're assuming it is set to '/etc/cookie/secret'. Add --cookie-secret=/etc/cookie/secret to your deck instance's arguments. Your configuration will stop working at the end of October 2019.")
}
}
if o.oauthURL != "" {
if o.githubOAuthConfigFile == "" {
return errors.New("an OAuth URL was provided but required flag --github-oauth-config-file was unset")
}
if o.cookieSecretFile == "" {
return errors.New("an OAuth URL was provided but required flag --cookie-secret was unset")
}
}
if o.hiddenOnly && o.showHidden {
return errors.New("'--hidden-only' and '--show-hidden' are mutually exclusive, the first one shows only hidden job, the second one shows both hidden and non-hidden jobs")
}
return nil
}
func gatherOptions(fs *flag.FlagSet, args ...string) options {
var o options
fs.StringVar(&o.configPath, "config-path", "", "Path to config.yaml.")
fs.StringVar(&o.jobConfigPath, "job-config-path", "", "Path to prow job configs.")
fs.StringVar(&o.tideURL, "tide-url", "", "Path to tide. If empty, do not serve tide data.")
fs.StringVar(&o.hookURL, "hook-url", "", "Path to hook plugin help endpoint.")
fs.StringVar(&o.oauthURL, "oauth-url", "", "Path to deck user dashboard endpoint.")
fs.StringVar(&o.githubOAuthConfigFile, "github-oauth-config-file", "/etc/github/secret", "Path to the file containing the GitHub App Client secret.")
fs.StringVar(&o.cookieSecretFile, "cookie-secret", "", "Path to the file containing the cookie secret key.")
// use when behind a load balancer
fs.StringVar(&o.redirectHTTPTo, "redirect-http-to", "", "Host to redirect http->https to based on x-forwarded-proto == http.")
// use when behind an oauth proxy
fs.BoolVar(&o.hiddenOnly, "hidden-only", false, "Show only hidden jobs. Useful for serving hidden jobs behind an oauth proxy.")
fs.StringVar(&o.pregeneratedData, "pregenerated-data", "", "Use API output from another prow instance. Used by the prow/cmd/deck/runlocal script")
fs.BoolVar(&o.showHidden, "show-hidden", false, "Show all jobs, including hidden ones")
fs.BoolVar(&o.spyglass, "spyglass", false, "Use Prow built-in job viewing instead of Gubernator")
fs.StringVar(&o.spyglassFilesLocation, "spyglass-files-location", "/lenses", "Location of the static files for spyglass.")
fs.StringVar(&o.staticFilesLocation, "static-files-location", "/static", "Path to the static files")
fs.StringVar(&o.templateFilesLocation, "template-files-location", "/template", "Path to the template files")
fs.StringVar(&o.gcsCredentialsFile, "gcs-credentials-file", "", "Path to the GCS credentials file")
fs.BoolVar(&o.rerunCreatesJob, "rerun-creates-job", false, "Change the re-run option in Deck to actually create the job. **WARNING:** Only use this with non-public deck instances, otherwise strangers can DOS your Prow instance")
fs.BoolVar(&o.allowInsecure, "allow-insecure", false, "Allows insecure requests for CSRF and GitHub oauth.")
fs.BoolVar(&o.dryRun, "dry-run", false, "Whether or not to make mutating API calls to GitHub.")
fs.StringVar(&o.pluginConfig, "plugin-config", "", "Path to plugin config file, probably /etc/plugins/plugins.yaml")
o.kubernetes.AddFlags(fs)
o.github.AddFlagsWithoutDefaultGitHubTokenPath(fs)
fs.Parse(args)
o.configPath = config.ConfigPath(o.configPath)
return o
}
func staticHandlerFromDir(dir string) http.Handler {
return gziphandler.GzipHandler(handleCached(http.FileServer(http.Dir(dir))))
}
var (
httpRequestDuration = metrics.HttpRequestDuration("deck", 0.005, 20)
httpResponseSize = metrics.HttpResponseSize("deck", 16384, 33554432)
traceHandler = metrics.TraceHandler(simplifier, httpRequestDuration, httpResponseSize)
)
type authCfgGetter func() *prowapi.RerunAuthConfig
func init() {
prometheus.MustRegister(httpRequestDuration)
prometheus.MustRegister(httpResponseSize)
}
var simplifier = simplifypath.NewSimplifier(l("", // shadow element mimicing the root
l("badge.svg"),
l("command-help"),
l("config"),
l("data.js"),
l("favicon.ico"),
l("github-login",
l("redirect")),
l("job-history",
v("job")),
l("log"),
l("plugin-config"),
l("plugin-help"),
l("plugins"),
l("pr"),
l("pr-data.js"),
l("pr-history"),
l("prowjob"),
l("prowjobs.js"),
l("rerun"),
l("spyglass",
l("static",
v("path")),
l("lens",
v("lens",
v("job")),
)),
l("static",
v("path")),
l("tide"),
l("tide-history"),
l("tide-history.js"),
l("tide.js"),
l("view",
v("job")),
))
// l and v keep the tree legible
func l(fragment string, children ...simplifypath.Node) simplifypath.Node {
return simplifypath.L(fragment, children...)
}
func v(fragment string, children ...simplifypath.Node) simplifypath.Node {
return simplifypath.V(fragment, children...)
}
func main() {
logrusutil.ComponentInit("deck")
o := gatherOptions(flag.NewFlagSet(os.Args[0], flag.ExitOnError), os.Args[1:]...)
if err := o.Validate(); err != nil {
logrus.WithError(err).Fatal("Invalid options")
}
defer interrupts.WaitForGracefulShutdown()
pjutil.ServePProf()
// setup config agent, pod log clients etc.
configAgent := &config.Agent{}
if err := configAgent.Start(o.configPath, o.jobConfigPath); err != nil {
logrus.WithError(err).Fatal("Error starting config agent.")
}
cfg := configAgent.Config
var pluginAgent *plugins.ConfigAgent
if o.pluginConfig != "" {
pluginAgent = &plugins.ConfigAgent{}
if err := pluginAgent.Start(o.pluginConfig, false); err != nil {
logrus.WithError(err).Fatal("Error loading Prow plugin config.")
}
} else {
logrus.Info("No plugins configuration was provided to deck. You must provide one to reuse /test checks for rerun")
}
metrics.ExposeMetrics("deck", cfg().PushGateway)
// signal to the world that we are healthy
// this needs to be in a separate port as we don't start the
// main server with the main mux until we're ready
health := pjutil.NewHealth()
mux := http.NewServeMux()
// setup common handlers for local and deployed runs
mux.Handle("/static/", http.StripPrefix("/static", staticHandlerFromDir(o.staticFilesLocation)))
mux.Handle("/config", gziphandler.GzipHandler(handleConfig(cfg, logrus.WithField("handler", "/config"))))
mux.Handle("/plugin-config", gziphandler.GzipHandler(handlePluginConfig(pluginAgent, logrus.WithField("handler", "/plugin-config"))))
mux.Handle("/favicon.ico", gziphandler.GzipHandler(handleFavicon(o.staticFilesLocation, cfg)))
// Set up handlers for template pages.
mux.Handle("/pr", gziphandler.GzipHandler(handleSimpleTemplate(o, cfg, "pr.html", nil)))
mux.Handle("/command-help", gziphandler.GzipHandler(handleSimpleTemplate(o, cfg, "command-help.html", nil)))
mux.Handle("/plugin-help", http.RedirectHandler("/command-help", http.StatusMovedPermanently))
mux.Handle("/tide", gziphandler.GzipHandler(handleSimpleTemplate(o, cfg, "tide.html", nil)))
mux.Handle("/tide-history", gziphandler.GzipHandler(handleSimpleTemplate(o, cfg, "tide-history.html", nil)))
mux.Handle("/plugins", gziphandler.GzipHandler(handleSimpleTemplate(o, cfg, "plugins.html", nil)))
runLocal := o.pregeneratedData != ""
var fallbackHandler func(http.ResponseWriter, *http.Request)
if runLocal {
localDataHandler := staticHandlerFromDir(o.pregeneratedData)
fallbackHandler = localDataHandler.ServeHTTP
} else {
fallbackHandler = http.NotFound
}
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
fallbackHandler(w, r)
return
}
indexHandler := handleSimpleTemplate(o, cfg, "index.html", struct {
SpyglassEnabled bool
ReRunCreatesJob bool
AllowAnyone bool
}{
SpyglassEnabled: o.spyglass,
ReRunCreatesJob: o.rerunCreatesJob,
AllowAnyone: cfg().Deck.RerunAuthConfig.AllowAnyone})
indexHandler(w, r)
})
if runLocal {
mux = localOnlyMain(cfg, o, mux)
} else {
mux = prodOnlyMain(cfg, pluginAgent, o, mux)
}
// signal to the world that we're ready
health.ServeReady()
// cookie secret will be used for CSRF protection and should be exactly 32 bytes
// we sometimes accept different lengths to stay backwards compatible
var csrfToken []byte
if o.cookieSecretFile != "" {
cookieSecretRaw, err := loadToken(o.cookieSecretFile)
if err != nil {
logrus.WithError(err).Fatal("Could not read cookie secret file")
}
decodedSecret, err := base64.StdEncoding.DecodeString(string(cookieSecretRaw))
if err != nil {
logrus.WithError(err).Fatal("Error decoding cookie secret")
}
if len(decodedSecret) == 32 {
csrfToken = decodedSecret
}
if len(decodedSecret) > 32 {
logrus.Warning("Cookie secret should be exactly 32 bytes. Consider truncating the existing cookie to that length")
hash := sha256.Sum256(decodedSecret)
csrfToken = hash[:]
}
if len(decodedSecret) < 32 {
if o.rerunCreatesJob {
logrus.Fatal("Cookie secret must be exactly 32 bytes")
return
}
logrus.Warning("Cookie secret should be exactly 32 bytes")
}
}
// if we allow direct reruns, we must protect against CSRF in all post requests using the cookie secret as a token
// for more information about CSRF, see https://github.com/kubernetes/test-infra/blob/master/prow/cmd/deck/csrf.md
if o.rerunCreatesJob && csrfToken == nil && !cfg().Deck.RerunAuthConfig.AllowAnyone {
logrus.Fatal("Rerun creates job cannot be enabled without CSRF protection, which requires --cookie-secret to be exactly 32 bytes")
return
}
if csrfToken != nil {
CSRF := csrf.Protect(csrfToken, csrf.Path("/"), csrf.Secure(!o.allowInsecure))
logrus.WithError(http.ListenAndServe(":8080", CSRF(traceHandler(mux)))).Fatal("ListenAndServe returned.")
return
}
// setup done, actually start the server
server := &http.Server{Addr: ":8080", Handler: traceHandler(mux)}
interrupts.ListenAndServe(server, 5*time.Second)
}
// localOnlyMain contains logic used only when running locally, and is mutually exclusive with
// prodOnlyMain.
func localOnlyMain(cfg config.Getter, o options, mux *http.ServeMux) *http.ServeMux {
mux.Handle("/github-login", gziphandler.GzipHandler(handleSimpleTemplate(o, cfg, "github-login.html", nil)))
if o.spyglass {
initSpyglass(cfg, o, mux, nil, nil, nil)
}
return mux
}
type podLogClient struct {
client corev1.PodInterface
}
func (c *podLogClient) GetLogs(name string, opts *coreapi.PodLogOptions) ([]byte, error) {
reader, err := c.client.GetLogs(name, &coreapi.PodLogOptions{Container: kube.TestContainerName}).Stream()
if err != nil {
return nil, err
}
defer reader.Close()
return ioutil.ReadAll(reader)
}
type pjListingClient interface {
List(context.Context, *prowapi.ProwJobList, ...ctrlruntimeclient.ListOption) error
}
type filteringProwJobLister struct {
ctx context.Context
client pjListingClient
hiddenRepos func() sets.String
hiddenOnly bool
showHidden bool
}
func (c *filteringProwJobLister) ListProwJobs(selector string) ([]prowapi.ProwJob, error) {
prowJobList := &prowapi.ProwJobList{}
parsedSelector, err := labels.Parse(selector)
if err != nil {
return nil, fmt.Errorf("failed to parse selector: %v", err)
}
listOpts := &ctrlruntimeclient.ListOptions{LabelSelector: parsedSelector}
if err := c.client.List(c.ctx, prowJobList, listOpts); err != nil {
return nil, err
}
var filtered []prowapi.ProwJob
for _, item := range prowJobList.Items {
shouldHide := item.Spec.Hidden || c.pjHasHiddenRefs(item)
if shouldHide && c.showHidden {
filtered = append(filtered, item)
} else if shouldHide == c.hiddenOnly {
// this is a hidden job, show it if we're asked
// to only show hidden jobs otherwise hide it
filtered = append(filtered, item)
}
}
return filtered, nil
}
func (c *filteringProwJobLister) pjHasHiddenRefs(pj prowapi.ProwJob) bool {
allRefs := pj.Spec.ExtraRefs
if pj.Spec.Refs != nil {
allRefs = append(allRefs, *pj.Spec.Refs)
}
for _, refs := range allRefs {
if c.hiddenRepos().HasAny(fmt.Sprintf("%s/%s", refs.Org, refs.Repo), refs.Org) {
return true
}
}
return false
}
type pjListingClientWrapper struct {
reader ctrlruntimeclient.Reader
}
func (w *pjListingClientWrapper) List(
ctx context.Context,
pjl *prowapi.ProwJobList,
opts ...ctrlruntimeclient.ListOption) error {
return w.reader.List(ctx, pjl, opts...)
}
// prodOnlyMain contains logic only used when running deployed, not locally
func prodOnlyMain(cfg config.Getter, pluginAgent *plugins.ConfigAgent, o options, mux *http.ServeMux) *http.ServeMux {
prowJobClient, err := o.kubernetes.ProwJobClient(cfg().ProwJobNamespace, false)
if err != nil {
logrus.WithError(err).Fatal("Error getting ProwJob client for infrastructure cluster.")
}
restCfg, err := o.kubernetes.InfrastructureClusterConfig(false)
if err != nil {
logrus.WithError(err).Fatal("Error getting infrastructure cluster config.")
}
mgr, err := manager.New(restCfg, manager.Options{
Namespace: cfg().ProwJobNamespace,
MetricsBindAddress: "0",
LeaderElection: false},
)
if err != nil {
logrus.WithError(err).Fatal("Error getting manager.")
}
go func() {
if err := mgr.Start(make(chan struct{})); err != nil {
logrus.WithError(err).Fatal("Error starting manager.")
} else {
logrus.Info("Manager stopped gracefully.")
}
}()
mgrSyncCtx, mgrSyncCtxCancel := context.WithTimeout(context.Background(), 30*time.Second)
defer mgrSyncCtxCancel()
if synced := mgr.GetCache().WaitForCacheSync(mgrSyncCtx.Done()); !synced {
logrus.Fatal("Timed out waiting for cachesync")
}
buildClusterClients, err := o.kubernetes.BuildClusterClients(cfg().PodNamespace, false)
if err != nil {
logrus.WithError(err).Fatal("Error getting Kubernetes client.")
}
podLogClients := map[string]jobs.PodLogClient{}
for clusterContext, client := range buildClusterClients {
podLogClients[clusterContext] = &podLogClient{client: client}
}
ja := jobs.NewJobAgent(&filteringProwJobLister{
client: &pjListingClientWrapper{mgr.GetClient()},
hiddenRepos: func() sets.String {
return sets.NewString(cfg().Deck.HiddenRepos...)
},
hiddenOnly: o.hiddenOnly,
showHidden: o.showHidden,
}, podLogClients, cfg)
ja.Start()
cfgGetter := func() *prowapi.RerunAuthConfig { return &cfg().Deck.RerunAuthConfig }
// setup prod only handlers
mux.Handle("/data.js", gziphandler.GzipHandler(handleData(ja, logrus.WithField("handler", "/data.js"))))
mux.Handle("/prowjobs.js", gziphandler.GzipHandler(handleProwJobs(ja, logrus.WithField("handler", "/prowjobs.js"))))
mux.Handle("/badge.svg", gziphandler.GzipHandler(handleBadge(ja)))
mux.Handle("/log", gziphandler.GzipHandler(handleLog(ja, logrus.WithField("handler", "/log"))))
mux.Handle("/prowjob", gziphandler.GzipHandler(handleProwJob(prowJobClient, logrus.WithField("handler", "/prowjob"))))
// We use the GH client to resolve GH teams when determining who is permitted to rerun a job.
// When inrepoconfig is enabled, both the GitHubClient and the gitClient are used to resolve
// presubmits dynamically which we need for the PR history page.
var githubClient deckGitHubClient
var gitClient git.ClientFactory
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, o.dryRun)
if err != nil {
logrus.WithError(err).Fatal("Error getting GitHub client.")
}
g, err := o.github.GitClient(secretAgent, o.dryRun)
if err != nil {
logrus.WithError(err).Fatal("Error getting Git client.")
}
gitClient = git.ClientFactoryFrom(g)
} else {
if len(cfg().InRepoConfig.Enabled) > 0 {
logrus.Fatal("--github-token-path must be configured with a valid token when using the inrepoconfig feature")
}
}
if o.spyglass {
initSpyglass(cfg, o, mux, ja, githubClient, gitClient)
}
if o.hookURL != "" {
mux.Handle("/plugin-help.js",
gziphandler.GzipHandler(handlePluginHelp(newHelpAgent(o.hookURL), logrus.WithField("handler", "/plugin-help.js"))))
}
if o.tideURL != "" {
ta := &tideAgent{
log: logrus.WithField("agent", "tide"),
path: o.tideURL,
updatePeriod: func() time.Duration {
return cfg().Deck.TideUpdatePeriod.Duration
},
hiddenRepos: func() []string {
return cfg().Deck.HiddenRepos
},
hiddenOnly: o.hiddenOnly,
showHidden: o.showHidden,
}
ta.start()
mux.Handle("/tide.js", gziphandler.GzipHandler(handleTidePools(cfg, ta, logrus.WithField("handler", "/tide.js"))))
mux.Handle("/tide-history.js", gziphandler.GzipHandler(handleTideHistory(ta, logrus.WithField("handler", "/tide-history.js"))))
}
// Enable Git OAuth feature if oauthURL is provided.
var goa *githuboauth.Agent
if o.oauthURL != "" {
githubOAuthConfigRaw, err := loadToken(o.githubOAuthConfigFile)
if err != nil {
logrus.WithError(err).Fatal("Could not read github oauth config file.")
}
cookieSecretRaw, err := loadToken(o.cookieSecretFile)
if err != nil {
logrus.WithError(err).Fatal("Could not read cookie secret file.")
}
var githubOAuthConfig githuboauth.Config
if err := yaml.Unmarshal(githubOAuthConfigRaw, &githubOAuthConfig); err != nil {
logrus.WithError(err).Fatal("Error unmarshalling github oauth config")
}
if !isValidatedGitOAuthConfig(&githubOAuthConfig) {
logrus.Fatal("Error invalid github oauth config")
}
decodedSecret, err := base64.StdEncoding.DecodeString(string(cookieSecretRaw))
if err != nil {
logrus.WithError(err).Fatal("Error decoding cookie secret")
}
if len(decodedSecret) == 0 {
logrus.Fatal("Cookie secret should not be empty")
}
cookie := sessions.NewCookieStore(decodedSecret)
githubOAuthConfig.InitGitHubOAuthConfig(cookie)
goa = githuboauth.NewAgent(&githubOAuthConfig, logrus.WithField("client", "githuboauth"))
oauthClient := o.github.GitHubOAuthClient(&oauth2.Config{
ClientID: githubOAuthConfig.ClientID,
ClientSecret: githubOAuthConfig.ClientSecret,
RedirectURL: githubOAuthConfig.RedirectURL,
Scopes: githubOAuthConfig.Scopes,
})
repos := cfg().AllRepos.List()
prStatusAgent := prstatus.NewDashboardAgent(
repos,
&githubOAuthConfig,
&o.github,
logrus.WithField("client", "pr-status"))
secure := !o.allowInsecure
mux.Handle("/pr-data.js", handleNotCached(
prStatusAgent.HandlePrStatus(prStatusAgent)))
// Handles login request.
mux.Handle("/github-login", goa.HandleLogin(oauthClient, secure))
// Handles redirect from GitHub OAuth server.
mux.Handle("/github-login/redirect", goa.HandleRedirect(oauthClient, &o.github, secure))
}
mux.Handle("/rerun", gziphandler.GzipHandler(handleRerun(prowJobClient, o.rerunCreatesJob, cfgGetter, goa, &o.github, githubClient, pluginAgent, logrus.WithField("handler", "/rerun"))))
// optionally inject http->https redirect handler when behind loadbalancer
if o.redirectHTTPTo != "" {
redirectMux := http.NewServeMux()
redirectMux.Handle("/", func(oldMux *http.ServeMux, host string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("x-forwarded-proto") == "http" {
redirectURL, err := url.Parse(r.URL.String())
if err != nil {
logrus.Errorf("Failed to parse URL: %s.", r.URL.String())
http.Error(w, "Failed to perform https redirect.", http.StatusInternalServerError)
return
}
redirectURL.Scheme = "https"
redirectURL.Host = host
http.Redirect(w, r, redirectURL.String(), http.StatusMovedPermanently)
} else {
oldMux.ServeHTTP(w, r)
}
}
}(mux, o.redirectHTTPTo))
mux = redirectMux
}
return mux
}
func initSpyglass(cfg config.Getter, o options, mux *http.ServeMux, ja *jobs.JobAgent, gitHubClient deckGitHubClient, gitClient git.ClientFactory) {
var c *storage.Client
var err error
if o.gcsCredentialsFile == "" {
c, err = storage.NewClient(context.Background(), option.WithoutAuthentication())
} else {
c, err = storage.NewClient(context.Background(), option.WithCredentialsFile(o.gcsCredentialsFile))
}
if err != nil {
logrus.WithError(err).Fatal("Error getting GCS client")
}
sg := spyglass.New(ja, cfg, c, o.gcsCredentialsFile, context.Background())
sg.Start()
mux.Handle("/spyglass/static/", http.StripPrefix("/spyglass/static", staticHandlerFromDir(o.spyglassFilesLocation)))
mux.Handle("/spyglass/lens/", gziphandler.GzipHandler(http.StripPrefix("/spyglass/lens/", handleArtifactView(o, sg, cfg))))
mux.Handle("/view/", gziphandler.GzipHandler(handleRequestJobViews(sg, cfg, o, logrus.WithField("handler", "/view"))))
mux.Handle("/job-history/", gziphandler.GzipHandler(handleJobHistory(o, cfg, c, logrus.WithField("handler", "/job-history"))))
mux.Handle("/pr-history/", gziphandler.GzipHandler(handlePRHistory(o, cfg, c, gitHubClient, gitClient, logrus.WithField("handler", "/pr-history"))))
}
func loadToken(file string) ([]byte, error) {
raw, err := ioutil.ReadFile(file)
if err != nil {
return []byte{}, err
}
return bytes.TrimSpace(raw), nil
}
// copy a http.Request
// see: https://go-review.googlesource.com/c/go/+/36483/3/src/net/http/server.go
func dupeRequest(original *http.Request) *http.Request {
r2 := new(http.Request)
*r2 = *original
r2.URL = new(url.URL)
*r2.URL = *original.URL
return r2
}
func handleCached(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// This looks ridiculous but actually no-cache means "revalidate" and
// "max-age=0" just means there is no time in which it can skip
// revalidation. We also need to set must-revalidate because no-cache
// doesn't imply must-revalidate when using the back button
// https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9.1
// TODO: consider setting a longer max-age
// setting it this way means the content is always revalidated
w.Header().Set("Cache-Control", "public, max-age=0, no-cache, must-revalidate")
next.ServeHTTP(w, r)
})
}
func setHeadersNoCaching(w http.ResponseWriter) {
// Note that we need to set both no-cache and no-store because only some
// browsers decided to (incorrectly) treat no-cache as "never store"
// IE "no-store". for good measure to cover older browsers we also set
// expires and pragma: https://stackoverflow.com/a/2068407
w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
w.Header().Set("Pragma", "no-cache")
w.Header().Set("Expires", "0")
}
func writeJSONResponse(w http.ResponseWriter, r *http.Request, d []byte) {
// If we have a "var" query, then write out "var value = {...};".
// Otherwise, just write out the JSON.
if v := r.URL.Query().Get("var"); v != "" {
w.Header().Set("Content-Type", "application/javascript")
fmt.Fprintf(w, "var %s = %s;", v, string(d))
} else {
w.Header().Set("Content-Type", "application/json")
fmt.Fprint(w, string(d))
}
}
func handleNotCached(next http.Handler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
setHeadersNoCaching(w)
next.ServeHTTP(w, r)
}
}
func handleProwJobs(ja *jobs.JobAgent, log *logrus.Entry) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
setHeadersNoCaching(w)
jobs := ja.ProwJobs()
omit := r.URL.Query().Get("omit")
if set := sets.NewString(strings.Split(omit, ",")...); set.Len() > 0 {
for i := range jobs {
if set.Has(Annotations) {
jobs[i].Annotations = nil
}
if set.Has(Labels) {
jobs[i].Labels = nil
}
if set.Has(DecorationConfig) {
jobs[i].Spec.DecorationConfig = nil
}
if set.Has(PodSpec) {
jobs[i].Spec.PodSpec = nil
}
}
}
jd, err := json.Marshal(struct {
Items []prowapi.ProwJob `json:"items"`
}{jobs})
if err != nil {
log.WithError(err).Error("Error marshaling jobs.")
jd = []byte("{}")
}
writeJSONResponse(w, r, jd)
}
}
func handleData(ja *jobs.JobAgent, log *logrus.Entry) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
setHeadersNoCaching(w)
jobs := ja.Jobs()
jd, err := json.Marshal(jobs)
if err != nil {
log.WithError(err).Error("Error marshaling jobs.")
jd = []byte("[]")
}
writeJSONResponse(w, r, jd)
}
}
// handleBadge handles requests to get a badge for one or more jobs
// The url must look like this, where `jobs` is a comma-separated
// list of globs:
//
// /badge.svg?jobs=<glob>[,<glob2>]
//
// Examples:
// - /badge.svg?jobs=pull-kubernetes-bazel-build
// - /badge.svg?jobs=pull-kubernetes-*
// - /badge.svg?jobs=pull-kubernetes-e2e*,pull-kubernetes-*,pull-kubernetes-integration-*
func handleBadge(ja *jobs.JobAgent) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
setHeadersNoCaching(w)
wantJobs := r.URL.Query().Get("jobs")
if wantJobs == "" {
http.Error(w, "missing jobs query parameter", http.StatusBadRequest)
return
}
w.Header().Set("Content-Type", "image/svg+xml")
allJobs := ja.ProwJobs()
_, _, svg := renderBadge(pickLatestJobs(allJobs, wantJobs))
w.Write(svg)
}
}
// handleJobHistory handles requests to get the history of a given job
// The url must look like this for presubmits:
//
// /job-history/<gcs-bucket-name>/pr-logs/directory/<job-name>
//
// Example:
// - /job-history/kubernetes-jenkins/pr-logs/directory/pull-test-infra-verify-gofmt
//
// For periodics or postsubmits, the url must look like this:
//
// /job-history/<gcs-bucket-name>/logs/<job-name>
//
// Example:
// - /job-history/kubernetes-jenkins/logs/ci-kubernetes-e2e-prow-canary
func handleJobHistory(o options, cfg config.Getter, gcsClient *storage.Client, log *logrus.Entry) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
setHeadersNoCaching(w)
tmpl, err := getJobHistory(r.URL, cfg(), gcsClient)
if err != nil {
msg := fmt.Sprintf("failed to get job history: %v", err)
log.WithField("url", r.URL.String()).Error(msg)
http.Error(w, msg, http.StatusInternalServerError)
return
}
handleSimpleTemplate(o, cfg, "job-history.html", tmpl)(w, r)
}
}
// handlePRHistory handles requests to get the test history if a given PR
// The url must look like this:
//
// /pr-history?org=<org>&repo=<repo>&pr=<pr number>
func handlePRHistory(o options, cfg config.Getter, gcsClient *storage.Client, gitHubClient deckGitHubClient, gitClient git.ClientFactory, log *logrus.Entry) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
setHeadersNoCaching(w)
tmpl, err := getPRHistory(r.URL, cfg(), gcsClient, gitHubClient, gitClient)
if err != nil {
msg := fmt.Sprintf("failed to get PR history: %v", err)
log.WithField("url", r.URL.String()).Info(msg)
http.Error(w, msg, http.StatusInternalServerError)
return
}
handleSimpleTemplate(o, cfg, "pr-history.html", tmpl)(w, r)
}
}
// handleRequestJobViews handles requests to get all available artifact views for a given job.
// The url must specify a storage key type, such as "prowjob" or "gcs":
//
// /view/<key-type>/<key>
//
// Examples:
// - /view/gcs/kubernetes-jenkins/pr-logs/pull/test-infra/9557/pull-test-infra-verify-gofmt/15688/
// - /view/prowjob/echo-test/1046875594609922048
func handleRequestJobViews(sg *spyglass.Spyglass, cfg config.Getter, o options, log *logrus.Entry) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
setHeadersNoCaching(w)
src := strings.TrimPrefix(r.URL.Path, "/view/")
csrfToken := csrf.Token(r)
page, err := renderSpyglass(sg, cfg, src, o, csrfToken, log)
if err != nil {
log.WithError(err).Error("error rendering spyglass page")
message := fmt.Sprintf("error rendering spyglass page: %v", err)
http.Error(w, message, http.StatusInternalServerError)
return
}
fmt.Fprint(w, page)
elapsed := time.Since(start)
log.WithFields(logrus.Fields{
"duration": elapsed.String(),
"endpoint": r.URL.Path,
"source": src,
}).Info("Loading view completed.")
}
}
// renderSpyglass returns a pre-rendered Spyglass page from the given source string
func renderSpyglass(sg *spyglass.Spyglass, cfg config.Getter, src string, o options, csrfToken string, log *logrus.Entry) (string, error) {
renderStart := time.Now()
src = strings.TrimSuffix(src, "/")
realPath, err := sg.ResolveSymlink(src)
if err != nil {
return "", fmt.Errorf("error when resolving real path %s: %v", src, err)
}
src = realPath
artifactNames, err := sg.ListArtifacts(src)
if err != nil {
return "", fmt.Errorf("error listing artifacts: %v", err)
}
if len(artifactNames) == 0 {
return "", fmt.Errorf("found no artifacts for %s", src)
}
regexCache := cfg().Deck.Spyglass.RegexCache
lensCache := map[int][]string{}
var lensIndexes []int
lensesLoop:
for i, lfc := range cfg().Deck.Spyglass.Lenses {
matches := map[string]struct{}{}
for _, re := range lfc.RequiredFiles {
found := false
for _, a := range artifactNames {
if regexCache[re].MatchString(a) {
matches[a] = struct{}{}
found = true
}
}
if !found {
continue lensesLoop
}
}
for _, re := range lfc.OptionalFiles {
for _, a := range artifactNames {
if regexCache[re].MatchString(a) {
matches[a] = struct{}{}
}
}
}
matchSlice := make([]string, 0, len(matches))
for k := range matches {
matchSlice = append(matchSlice, k)
}
lensCache[i] = matchSlice
lensIndexes = append(lensIndexes, i)
}
lensIndexes, ls := sg.Lenses(lensIndexes)
jobHistLink := ""
jobPath, err := sg.JobPath(src)
if err == nil {
jobHistLink = path.Join("/job-history", jobPath)
}
var prowJobLink string
prowJobName, err := sg.ProwJobName(src)
if err == nil {
if prowJobName != "" {
u, err := url.Parse("/prowjob")
if err != nil {
return "", fmt.Errorf("error parsing prowjob path: %v", err)
}
query := url.Values{}
query.Set("prowjob", prowJobName)
u.RawQuery = query.Encode()
prowJobLink = u.String()
}
} else {
log.WithError(err).Warningf("Error getting ProwJob name for source %q.", src)
}
artifactsLink := ""
gcswebPrefix := cfg().Deck.Spyglass.GCSBrowserPrefix
if gcswebPrefix != "" {
runPath, err := sg.RunPath(src)
if err == nil {
artifactsLink = gcswebPrefix + runPath
// gcsweb wants us to end URLs with a trailing slash
if !strings.HasSuffix(artifactsLink, "/") {
artifactsLink += "/"
}
}
}