forked from kubernetes/test-infra
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
1695 lines (1522 loc) · 57.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/http/httputil"
"net/url"
"os"
"path"
"strings"
"time"
"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"
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/util/sets"
corev1 "k8s.io/client-go/kubernetes/typed/core/v1"
"k8s.io/test-infra/prow/flagutil"
"k8s.io/test-infra/prow/pjutil/pprof"
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/deck/jobs"
prowflagutil "k8s.io/test-infra/prow/flagutil"
configflagutil "k8s.io/test-infra/prow/flagutil/config"
pluginsflagutil "k8s.io/test-infra/prow/flagutil/plugins"
"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/interrupts"
"k8s.io/test-infra/prow/io"
"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/simplifypath"
"k8s.io/test-infra/prow/spyglass"
spyglassapi "k8s.io/test-infra/prow/spyglass/api"
"k8s.io/test-infra/prow/spyglass/lenses/common"
// 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/html"
_ "k8s.io/test-infra/prow/spyglass/lenses/junit"
_ "k8s.io/test-infra/prow/spyglass/lenses/links"
_ "k8s.io/test-infra/prow/spyglass/lenses/metadata"
_ "k8s.io/test-infra/prow/spyglass/lenses/podinfo"
_ "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"
defaultPRHistLinkTemplate = "/pr-history?org={{.Org}}&repo={{.Repo}}&pr={{.Number}}"
)
type options struct {
config configflagutil.ConfigOptions
pluginsConfig pluginsflagutil.PluginOptions
instrumentation prowflagutil.InstrumentationOptions
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
storage prowflagutil.StorageClientOptions
gcsCookieAuth bool
rerunCreatesJob bool
allowInsecure bool
dryRun bool
tenantIDs flagutil.Strings
}
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 err := o.config.Validate(o.dryRun); err != nil {
return err
}
if err := o.pluginsConfig.Validate(o.dryRun); err != nil {
return err
}
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) || (o.tenantIDs.Strings() != nil && (o.hiddenOnly || o.showHidden)) {
return errors.New("'--hidden-only', '--tenant-id', and '--show-hidden' are mutually exclusive, 'hidden-only' shows only hidden job, '--tenant-id' shows all jobs with matching ID and 'show-hidden' shows both hidden and non-hidden jobs")
}
return nil
}
func gatherOptions(fs *flag.FlagSet, args ...string) options {
var o options
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.BoolVar(&o.gcsCookieAuth, "gcs-cookie-auth", false, "Use storage.cloud.google.com instead of signed URLs")
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.Var(&o.tenantIDs, "tenant-id", "The tenantID(s) used by the ProwJobs that should be displayed by this instance of Deck. This flag can be repeated.")
o.config.AddFlags(fs)
o.instrumentation.AddFlags(fs)
o.kubernetes.AddFlags(fs)
o.github.AddFlags(fs)
o.github.AllowAnonymous = true
o.github.AllowDirectAccess = true
o.storage.AddFlags(fs)
o.pluginsConfig.AddFlags(fs)
fs.Parse(args)
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.Refs) *prowapi.RerunAuthConfig
func init() {
prometheus.MustRegister(httpRequestDuration)
prometheus.MustRegister(httpResponseSize)
}
var simplifier = simplifypath.NewSimplifier(l("", // shadow element mimicing the root
l(""),
l("badge.svg"),
l("command-help"),
l("config"),
l("data.js"),
l("favicon.ico"),
l("github-login",
l("redirect")),
l("github-link"),
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",
simplifypath.VGreedy("path")),
l("lens",
v("lens",
v("job")),
)),
l("static",
simplifypath.VGreedy("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()
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()
pprof.Instrument(o.instrumentation)
// setup config agent, pod log clients etc.
configAgent, err := o.config.ConfigAgentWithAdditionals(&config.Agent{}, []func(*config.Config) error{spglassConfigDefaulting})
if err != nil {
logrus.WithError(err).Fatal("Error starting config agent.")
}
cfg := configAgent.Config
var pluginAgent *plugins.ConfigAgent
if o.pluginsConfig.PluginConfigPath != "" {
pluginAgent, err = o.pluginsConfig.PluginAgent()
if 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, o.instrumentation.MetricsPort)
// 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.NewHealthOnPort(o.instrumentation.HealthPort)
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)
var pjListingClient jobs.PJListingClient
var githubClient deckGitHubClient
var gitClient git.ClientFactory
var podLogClients map[string]jobs.PodLogClient
if runLocal {
localDataHandler := staticHandlerFromDir(o.pregeneratedData)
fallbackHandler = localDataHandler.ServeHTTP
var fjc fakePjListingClientWrapper
var pjs prowapi.ProwJobList
staticPjsPath := path.Join(o.pregeneratedData, "prowjobs.json")
content, err := ioutil.ReadFile(staticPjsPath)
if err != nil {
logrus.WithError(err).Fatal("Failed to read jobs from prowjobs.json.")
}
if err = json.Unmarshal(content, &pjs); err != nil {
logrus.WithError(err).Fatal("Failed to unmarshal jobs from prowjobs.json.")
}
fjc.pjs = &pjs
pjListingClient = &fjc
} else {
fallbackHandler = http.NotFound
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.")
}
// Force a cache for ProwJobs
if _, err := mgr.GetCache().GetInformer(interrupts.Context(), &prowapi.ProwJob{}); err != nil {
logrus.WithError(err).Fatal("Failed to get prowjob informer")
}
go func() {
if err := mgr.Start(interrupts.Context()); 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); !synced {
logrus.Fatal("Timed out waiting for cachesync")
}
// The watch apimachinery doesn't support restarts, so just exit the binary if a kubeconfig changes
// to make the kubelet restart us.
if err := o.kubernetes.AddKubeconfigChangeCallback(func() {
logrus.Info("Kubeconfig changed, exiting to trigger a restart")
interrupts.Terminate()
}); err != nil {
logrus.WithError(err).Fatal("Failed to register kubeconfig change callback")
}
pjListingClient = &pjListingClientWrapper{mgr.GetClient()}
// 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.
if o.github.TokenPath != "" || o.github.AppID != "" {
githubClient, err = o.github.GitHubClient(o.dryRun)
if err != nil {
logrus.WithError(err).Fatal("Error getting GitHub client.")
}
g, err := o.github.GitClient(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")
}
}
buildClusterClients, err := o.kubernetes.BuildClusterClients(cfg().PodNamespace, false)
if err != nil {
logrus.WithError(err).Fatal("Error getting Kubernetes client.")
}
podLogClients = make(map[string]jobs.PodLogClient)
for clusterContext, client := range buildClusterClients {
podLogClients[clusterContext] = &podLogClient{client: client}
}
}
authCfgGetter := func(refs *prowapi.Refs) *prowapi.RerunAuthConfig {
rac := cfg().Deck.RerunAuthConfigs.GetRerunAuthConfig(refs)
return &rac
}
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
}{
SpyglassEnabled: o.spyglass,
ReRunCreatesJob: o.rerunCreatesJob})
indexHandler(w, r)
})
ja := jobs.NewJobAgent(context.Background(), pjListingClient, o.hiddenOnly, o.showHidden, o.tenantIDs.Strings(), podLogClients, cfg)
ja.Start()
// setup prod only handlers. These handlers can work with runlocal as long
// as ja is properly mocked, more specifically pjListingClient inside ja
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"))))
if o.spyglass {
initSpyglass(cfg, o, mux, ja, githubClient, gitClient)
}
if runLocal {
mux = localOnlyMain(cfg, o, mux)
} else {
mux = prodOnlyMain(cfg, pluginAgent, authCfgGetter, githubClient, 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
empty := prowapi.Refs{}
if o.rerunCreatesJob && csrfToken == nil && !authCfgGetter(&empty).IsAllowAnyone() {
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)))
return mux
}
type podLogClient struct {
client corev1.PodInterface
}
func (c *podLogClient) GetLogs(name, container string) ([]byte, error) {
reader, err := c.client.GetLogs(name, &coreapi.PodLogOptions{Container: container}).Stream(context.TODO())
if err != nil {
return nil, err
}
defer reader.Close()
return ioutil.ReadAll(reader)
}
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...)
}
// fakePjListingClientWrapper implements pjListingClient for runlocal
type fakePjListingClientWrapper struct {
pjs *prowapi.ProwJobList
}
func (fjc *fakePjListingClientWrapper) List(ctx context.Context, pjl *prowapi.ProwJobList, lo ...ctrlruntimeclient.ListOption) error {
*pjl = *fjc.pjs
return nil
}
// prodOnlyMain contains logic only used when running deployed, not locally
func prodOnlyMain(cfg config.Getter, pluginAgent *plugins.ConfigAgent, authCfgGetter authCfgGetter, githubClient deckGitHubClient, 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.")
}
// prowjob still needs prowJobClient for retrieving log
mux.Handle("/prowjob", gziphandler.GzipHandler(handleProwJob(prowJobClient, logrus.WithField("handler", "/prowjob"))))
if o.hookURL != "" {
mux.Handle("/plugin-help.js",
gziphandler.GzipHandler(handlePluginHelp(newHelpAgent(o.hookURL), logrus.WithField("handler", "/plugin-help.js"))))
}
// tide could potentially be mocked by static data
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,
tenantIDs: sets.NewString(o.tenantIDs.Strings()...),
cfg: cfg,
}
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"))))
}
secure := !o.allowInsecure
// Handles link to github
mux.HandleFunc("/github-link", HandleGitHubLink(o.github.Host, secure))
// 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 := githuboauth.NewClient(&oauth2.Config{
ClientID: githubOAuthConfig.ClientID,
ClientSecret: githubOAuthConfig.ClientSecret,
RedirectURL: githubOAuthConfig.RedirectURL,
Scopes: githubOAuthConfig.Scopes,
Endpoint: oauth2.Endpoint{
AuthURL: fmt.Sprintf("https://%s/login/oauth/authorize", o.github.Host),
TokenURL: fmt.Sprintf("https://%s/login/oauth/access_token", o.github.Host),
},
})
repos := cfg().AllRepos.List()
prStatusAgent := prstatus.NewDashboardAgent(
repos,
&githubOAuthConfig,
&o.github,
logrus.WithField("client", "pr-status"))
clientCreator := func(accessToken string) prstatus.GitHubClient {
return o.github.GitHubClientWithAccessToken(accessToken)
}
mux.Handle("/pr-data.js", handleNotCached(
prStatusAgent.HandlePrStatus(prStatusAgent, clientCreator)))
// 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, githuboauth.NewAuthenticatedUserIdentifier(&o.github), secure))
}
mux.Handle("/rerun", gziphandler.GzipHandler(handleRerun(prowJobClient, o.rerunCreatesJob, authCfgGetter, goa, githuboauth.NewAuthenticatedUserIdentifier(&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) {
ctx := context.TODO()
opener, err := io.NewOpener(ctx, o.storage.GCSCredentialsFile, o.storage.S3CredentialsFile)
if err != nil {
logrus.WithError(err).Fatal("Error creating opener")
}
sg := spyglass.New(ctx, ja, cfg, opener, o.gcsCookieAuth)
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, opener, logrus.WithField("handler", "/job-history"))))
mux.Handle("/pr-history/", gziphandler.GzipHandler(handlePRHistory(o, cfg, opener, gitHubClient, gitClient, logrus.WithField("handler", "/pr-history"))))
if err := initLocalLensHandler(cfg, o, sg); err != nil {
logrus.WithError(err).Fatal("Failed to initialize local lens handler")
}
}
func initLocalLensHandler(cfg config.Getter, o options, sg *spyglass.Spyglass) error {
var localLenses []common.LensWithConfiguration
for _, lfc := range cfg().Deck.Spyglass.Lenses {
if !strings.HasPrefix(strings.TrimPrefix(lfc.RemoteConfig.Endpoint, "http://"), spyglassLocalLensListenerAddr) {
continue
}
lens, err := lenses.GetLens(lfc.Lens.Name)
if err != nil {
return fmt.Errorf("couldn't find local lens %q: %w", lfc.Lens.Name, err)
}
localLenses = append(localLenses, common.LensWithConfiguration{
Config: common.LensOpt{
LensResourcesDir: lenses.ResourceDirForLens(o.spyglassFilesLocation, lfc.Lens.Name),
LensName: lfc.Lens.Name,
LensTitle: lfc.RemoteConfig.Title,
},
Lens: lens,
})
}
lensServer, err := common.NewLensServer(spyglassLocalLensListenerAddr, sg.JobAgent, sg.StorageArtifactFetcher, sg.PodLogArtifactFetcher, cfg, localLenses)
if err != nil {
return fmt.Errorf("constructing local lens server: %w", err)
}
interrupts.ListenAndServe(lensServer, 5*time.Second)
return nil
}
func loadToken(file string) ([]byte, error) {
raw, err := ioutil.ReadFile(file)
if err != nil {
return []byte{}, err
}
return bytes.TrimSpace(raw), nil
}
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 {
jobs[i].ManagedFields = nil
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) {
// when we omit the podspec, we don't set it completely to nil
// instead, we set it to a new podspec that just has an empty container for each container that exists in the actual podspec
// this is so we can determine how many containers there are for a given prowjob without fetching all of the podspec details
// this is necessary for prow/cmd/deck/static/prow/prow.ts to determine whether the logIcon should link to a log endpoint or to spyglass
if jobs[i].Spec.PodSpec != nil {
emptyContainers := []coreapi.Container{}
for range jobs[i].Spec.PodSpec.Containers {
emptyContainers = append(emptyContainers, coreapi.Container{})
}
jobs[i].Spec.PodSpec = &coreapi.PodSpec{
Containers: emptyContainers,
}
}
}
}
}
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
// There is also a new format since we started supporting other storageProvider
// like s3 and not only GCS.
// The url must look like one of these for presubmits:
//
// - /job-history/<gcs-bucket-name>/pr-logs/directory/<job-name>
// - /job-history/<storage-provider>/<bucket-name>/pr-logs/directory/<job-name>
//
// Example:
// - /job-history/kubernetes-jenkins/pr-logs/directory/pull-test-infra-verify-gofmt
// - /job-history/gs/kubernetes-jenkins/pr-logs/directory/pull-test-infra-verify-gofmt
//
// For periodics or postsubmits, the url must look like one of these:
//
// - /job-history/<gcs-bucket-name>/logs/<job-name>
// - /job-history/<storage-provider>/<bucket-name>/logs/<job-name>
//
// Example:
// - /job-history/kubernetes-jenkins/logs/ci-kubernetes-e2e-prow-canary
// - /job-history/gs/kubernetes-jenkins/logs/ci-kubernetes-e2e-prow-canary
func handleJobHistory(o options, cfg config.Getter, opener io.Opener, log *logrus.Entry) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
setHeadersNoCaching(w)
tmpl, err := getJobHistory(r.Context(), r.URL, cfg, opener)
if err != nil {
msg := fmt.Sprintf("failed to get job history: %v", err)
if shouldLogHTTPErrors(err) {
log.WithField("url", r.URL.String()).WithError(err).Warn(msg)
} else {
log.WithField("url", r.URL.String()).WithError(err).Debug(msg)
}
http.Error(w, msg, httpStatusForError(err))
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, opener io.Opener, gitHubClient deckGitHubClient, gitClient git.ClientFactory, log *logrus.Entry) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
setHeadersNoCaching(w)
tmpl, err := getPRHistory(r.Context(), r.URL, cfg(), opener, gitHubClient, gitClient, o.github.Host)
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(r.Context(), sg, cfg, src, o, csrfToken, log)
if err != nil {
msg := fmt.Sprintf("error rendering spyglass page: %v", err)
if shouldLogHTTPErrors(err) {
log.WithError(err).Warn(msg)
}
http.Error(w, msg, httpStatusForError(err))
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(ctx context.Context, 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: %w", src, err)
}
src = realPath
artifactNames, err := sg.ListArtifacts(ctx, src)
if err != nil {
return "", fmt.Errorf("error listing artifacts: %w", err)
}
if len(artifactNames) == 0 {
log.Infof("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 := sets.String{}
for _, re := range lfc.RequiredFiles {
found := false
for _, a := range artifactNames {
if regexCache[re].MatchString(a) {
matches.Insert(a)
found = true
}
}
if !found {
continue lensesLoop
}
}
for _, re := range lfc.OptionalFiles {
for _, a := range artifactNames {
if regexCache[re].MatchString(a) {
matches.Insert(a)
}
}
}
lensCache[i] = matches.List()
lensIndexes = append(lensIndexes, i)
}
lensIndexes, ls := sg.Lenses(lensIndexes)
jobHistLink := ""