forked from kubernetes-retired/contrib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
submit-queue.go
1391 lines (1223 loc) · 43.8 KB
/
submit-queue.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 2015 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 mungers
import (
"bytes"
"encoding/json"
"fmt"
"math"
"net/http"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
utilclock "k8s.io/kubernetes/pkg/util/clock"
"k8s.io/contrib/mungegithub/admin"
"k8s.io/contrib/mungegithub/features"
"k8s.io/contrib/mungegithub/github"
"k8s.io/contrib/mungegithub/mungers/e2e"
fake_e2e "k8s.io/contrib/mungegithub/mungers/e2e/fake"
"k8s.io/contrib/mungegithub/mungers/mungerutil"
"k8s.io/contrib/mungegithub/mungers/shield"
"k8s.io/contrib/test-utils/utils"
"github.com/NYTimes/gziphandler"
"github.com/golang/glog"
githubapi "github.com/google/go-github/github"
"github.com/spf13/cobra"
)
const (
approvedLabel = "approved"
lgtmLabel = "lgtm"
retestNotRequiredLabel = "retest-not-required"
retestNotRequiredDocsOnlyLabel = "retest-not-required-docs-only"
doNotMergeLabel = "do-not-merge"
claYesLabel = "cla: yes"
claNoLabel = "cla: no"
cncfClaYesLabel = "cncf-cla: yes"
cncfClaNoLabel = "cncf-cla: no"
claHumanLabel = "cla: human-approved"
sqContext = "Submit Queue"
retestNotRequiredMergePriority = -1 // used for retestNotRequiredLabel
defaultMergePriority = 3 // when an issue is unlabeled
githubE2EPollTime = 30 * time.Second
)
var (
_ = fmt.Print
// This MUST cause a RETEST of everything in the sq.RequiredRetestContexts
retestBody = fmt.Sprintf("@%s test this [submit-queue is verifying that this PR is safe to merge]", jenkinsBotName)
)
type submitStatus struct {
Time time.Time
statusPullRequest
Reason string
}
type statusPullRequest struct {
Number int
URL string
Title string
Login string
AvatarURL string
Additions int
Deletions int
ExtraInfo []string
}
type e2eQueueStatus struct {
E2ERunning *statusPullRequest
E2EQueue []*statusPullRequest
}
type submitQueueStatus struct {
PRStatus map[string]submitStatus
}
// Information about the e2e test health. Call updateHealth on the SubmitQueue
// at roughly constant intervals to keep this up to date. The mergeable fraction
// of time for the queue as a whole and the individual jobs will then be
// NumStable[PerJob] / TotalLoops.
type submitQueueHealth struct {
TotalLoops int
NumStable int
NumStablePerJob map[string]int
MergePossibleNow bool
}
// Generate health information using a queue of healthRecords. The bools are
// true for stable and false otherwise.
type healthRecord struct {
Time time.Time
Overall bool
Jobs map[string]bool
}
// information about the sq itself including how fast things are merging and
// how long since the last merge
type submitQueueStats struct {
Added int // Number of items added to the queue since restart
FlakesIgnored int
Initialized bool // true if we've made at least one complete pass
InstantMerges int // Number of commits without retests required
LastMergeTime time.Time
MergeRate float64
MergesSinceRestart int
Removed int // Number of items dequeued since restart
RetestsAvoided int
StartTime time.Time
Tested int // Number of e2e tests completed
}
// pull-request that has been tested as successful, but interrupted because head flaked
type submitQueueInterruptedObject struct {
obj *github.MungeObject
// If these two items match when we're about to kick off a retest, it's safe to skip the retest.
interruptedMergeHeadSHA string
interruptedMergeBaseSHA string
}
// Contains metadata about this instance of the submit queue such as URLs.
// Consumed by the template system.
type submitQueueMetadata struct {
ProjectName string
ChartUrl string
HistoryUrl string
RepoPullUrl string
}
// SubmitQueue will merge PR which meet a set of requirements.
// PR must have LGTM after the last commit
// PR must have passed all github CI checks
// The google internal jenkins instance must be passing the BlockingJobNames e2e tests
type SubmitQueue struct {
githubConfig *github.Config
BlockingJobNames []string
NonBlockingJobNames []string
PresubmitJobNames []string
WeakStableJobNames []string
// If FakeE2E is true, don't try to connect to JenkinsHost, all jobs are passing.
FakeE2E bool
Committers string
RequiredStatusContexts []string
DoNotMergeMilestones []string
RequiredRetestContexts []string
RetestBody string
Metadata submitQueueMetadata
AdminPort int
sync.Mutex
lastPRStatus map[string]submitStatus
prStatus map[string]submitStatus // protected by sync.Mutex
statusHistory []submitStatus // protected by sync.Mutex
clock utilclock.Clock
startTime time.Time // when the queue started (duh)
lastMergeTime time.Time
totalMerges int32
mergeRate float64 // per 24 hours
loopStarts int32 // if > 1, then we must have made a complete pass.
githubE2ERunning *github.MungeObject // protect by sync.Mutex!
githubE2EQueue map[int]*github.MungeObject // protected by sync.Mutex!
githubE2EPollTime time.Duration
lgtmTimeCache *mungerutil.LabelTimeCache
lastE2EStable bool // was e2e stable last time they were checked, protect by sync.Mutex
e2e e2e.E2ETester
interruptedObj *submitQueueInterruptedObject
flakesIgnored int32 // Increments for each merge while 1+ job is flaky
instantMerges int32 // Increments whenever we commit without retesting
prsAdded int32 // Increments whenever an items queues
prsRemoved int32 // Increments whenever an item dequeues
prsTested int32 // Number of prs that completed second testing
retestsAvoided int32 // Increments whenever we skip due to head not changing.
health submitQueueHealth
healthHistory []healthRecord
emergencyMergeStopFlag int32
features *features.Features
}
func init() {
clock := utilclock.RealClock{}
sq := &SubmitQueue{
clock: clock,
startTime: clock.Now(),
lastMergeTime: clock.Now(),
lastE2EStable: true,
prStatus: map[string]submitStatus{},
lastPRStatus: map[string]submitStatus{},
githubE2EQueue: map[int]*github.MungeObject{},
}
RegisterMungerOrDie(sq)
RegisterStaleComments(sq)
}
// Name is the name usable in --pr-mungers
func (sq *SubmitQueue) Name() string { return "submit-queue" }
// RequiredFeatures is a slice of 'features' that must be provided
func (sq *SubmitQueue) RequiredFeatures() []string {
return []string{features.GCSFeature, features.TestOptionsFeature}
}
func (sq *SubmitQueue) emergencyMergeStop() bool {
return atomic.LoadInt32(&sq.emergencyMergeStopFlag) != 0
}
func (sq *SubmitQueue) setEmergencyMergeStop(stopMerges bool) {
if stopMerges {
atomic.StoreInt32(&sq.emergencyMergeStopFlag, 1)
} else {
atomic.StoreInt32(&sq.emergencyMergeStopFlag, 0)
}
}
// EmergencyStopHTTP sets the emergency stop flag. It expects the path of
// req.URL to contain either "emergency/stop", "emergency/resume", or "emergency/status".
func (sq *SubmitQueue) EmergencyStopHTTP(res http.ResponseWriter, req *http.Request) {
switch {
case strings.Contains(req.URL.Path, "emergency/stop"):
sq.setEmergencyMergeStop(true)
case strings.Contains(req.URL.Path, "emergency/resume"):
sq.setEmergencyMergeStop(false)
case strings.Contains(req.URL.Path, "emergency/status"):
default:
http.NotFound(res, req)
return
}
sq.serve(sq.marshal(struct{ EmergencyInProgress bool }{sq.emergencyMergeStop()}), res, req)
}
func round(num float64) int {
return int(num + math.Copysign(0.5, num))
}
func toFixed(num float64) float64 {
output := math.Pow(10, float64(3))
return float64(round(num*output)) / output
}
// This is the calculation of the exponential smoothing factor. It tries to
// make sure that if we get lots of fast merges we don't race the 'daily'
// avg really high really fast. But more importantly it means that if merges
// start going slowly the 'daily' average will get pulled down a lot by one
// slow merge instead of requiring numerous merges to get pulled down
func getSmoothFactor(dur time.Duration) float64 {
hours := dur.Hours()
smooth := .155*math.Log(hours) + .422
if smooth < .1 {
return .1
}
if smooth > .999 {
return .999
}
return smooth
}
// This calculates an exponentially smoothed merge Rate based on the formula
// newRate = (1-smooth)oldRate + smooth*newRate
// Which is really great and simple for constant time series data. But of course
// ours isn't time series data so I vary the smoothing factor based on how long
// its been since the last entry. See the comments on the `getSmoothFactor` for
// a discussion of why.
// This whole thing was dreamed up by eparis one weekend via a combination
// of guess-and-test and intuition. Someone who knows about this stuff
// is likely to laugh at the naivete. Point him to where someone intelligent
// has thought about this stuff and he will gladly do something smart.
// Merges that took less than 5 minutes are ignored completely for the rate
// calculation.
func calcMergeRate(oldRate float64, last, now time.Time) float64 {
since := now.Sub(last)
if since <= 5*time.Minute {
// retest-not-required PR merges shouldn't affect our best
// guess about the rate.
return oldRate
}
var rate float64
if since == 0 {
rate = 96
} else {
rate = 24.0 * time.Hour.Hours() / since.Hours()
}
smoothingFactor := getSmoothFactor(since)
mergeRate := ((1.0 - smoothingFactor) * oldRate) + (smoothingFactor * rate)
return toFixed(mergeRate)
}
// Updates a smoothed rate at which PRs are merging per day.
// Updates merge stats. Should be called once for every merge.
func (sq *SubmitQueue) updateMergeRate() {
now := sq.clock.Now()
sq.mergeRate = calcMergeRate(sq.mergeRate, sq.lastMergeTime, now)
// Update stats
atomic.AddInt32(&sq.totalMerges, 1)
sq.lastMergeTime = now
}
// This calculated the smoothed merge rate BUT it looks at the time since
// the last merge vs 'Now'. If we have not passed the next 'expected' time
// for a merge this just returns previous calculations. If 'Now' is later
// than we would expect given the existing mergeRate then pretend a merge
// happened right now and return the new merge rate. This way the merge rate
// is lower even if no merge has happened in a long time.
func (sq *SubmitQueue) calcMergeRateWithTail() float64 {
now := sq.clock.Now()
if sq.mergeRate == 0 {
return 0
}
// Figure out when we think the next merge would happen given the history
next := time.Duration(24/sq.mergeRate*time.Hour.Hours()) * time.Hour
expectedMergeTime := sq.lastMergeTime.Add(next)
// If we aren't there yet, just return the history
if !now.After(expectedMergeTime) {
return sq.mergeRate
}
// Pretend as though a merge happened right now to pull down the rate
return calcMergeRate(sq.mergeRate, sq.lastMergeTime, now)
}
// Given a string slice with a single empty value this function will return a empty slice.
// This is extremely useful for StringSlice flags, so the user can do --flag="" and instead
// of getting []string{""} they will get []string{}
func cleanStringSlice(in []string) []string {
if len(in) == 1 && len(in[0]) == 0 {
return []string{}
}
return in
}
// Initialize will initialize the munger
func (sq *SubmitQueue) Initialize(config *github.Config, features *features.Features) error {
sq.features = features
sq.RequiredRetestContexts = features.TestOptions.RequiredRetestContexts
return sq.internalInitialize(config, features, "")
}
// internalInitialize will initialize the munger.
// if overrideUrl is specified, will create testUtils
func (sq *SubmitQueue) internalInitialize(config *github.Config, features *features.Features, overrideUrl string) error {
sq.Lock()
defer sq.Unlock()
// Clean up all of our flags which we wish --flag="" to mean []string{}
sq.BlockingJobNames = cleanStringSlice(sq.BlockingJobNames)
sq.NonBlockingJobNames = cleanStringSlice(sq.NonBlockingJobNames)
sq.PresubmitJobNames = cleanStringSlice(sq.PresubmitJobNames)
sq.WeakStableJobNames = cleanStringSlice(sq.WeakStableJobNames)
sq.RequiredStatusContexts = cleanStringSlice(sq.RequiredStatusContexts)
sq.RequiredRetestContexts = cleanStringSlice(sq.RequiredRetestContexts)
sq.DoNotMergeMilestones = cleanStringSlice(sq.DoNotMergeMilestones)
sq.Metadata.RepoPullUrl = fmt.Sprintf("https://github.com/%s/%s/pulls/", config.Org, config.Project)
sq.Metadata.ProjectName = strings.Title(config.Project)
sq.githubConfig = config
// TODO: This is not how injection for tests should work.
if sq.FakeE2E {
sq.e2e = &fake_e2e.FakeE2ETester{
JobNames: sq.BlockingJobNames,
WeakStableJobNames: sq.WeakStableJobNames,
}
} else {
var gcs *utils.Utils
if overrideUrl != "" {
gcs = utils.NewTestUtils("bucket", "logs", overrideUrl)
} else {
gcs = utils.NewWithPresubmitDetection(
sq.features.GCSInfo.BucketName, sq.features.GCSInfo.LogDir,
sq.features.GCSInfo.PullKey, sq.features.GCSInfo.PullLogDir,
)
}
sq.e2e = (&e2e.RealE2ETester{
BlockingJobNames: sq.BlockingJobNames,
NonBlockingJobNames: sq.NonBlockingJobNames,
WeakStableJobNames: sq.WeakStableJobNames,
BuildStatus: map[string]e2e.BuildInfo{},
GoogleGCSBucketUtils: gcs,
}).Init(admin.Mux)
}
sq.lgtmTimeCache = mungerutil.NewLabelTimeCache(lgtmLabel)
if len(config.Address) > 0 {
if len(config.WWWRoot) > 0 {
http.Handle("/", gziphandler.GzipHandler(http.FileServer(http.Dir(config.WWWRoot))))
}
http.Handle("/prs", gziphandler.GzipHandler(http.HandlerFunc(sq.servePRs)))
http.Handle("/history", gziphandler.GzipHandler(http.HandlerFunc(sq.serveHistory)))
http.Handle("/github-e2e-queue", gziphandler.GzipHandler(http.HandlerFunc(sq.serveGithubE2EStatus)))
http.Handle("/google-internal-ci", gziphandler.GzipHandler(http.HandlerFunc(sq.serveGoogleInternalStatus)))
http.Handle("/merge-info", gziphandler.GzipHandler(http.HandlerFunc(sq.serveMergeInfo)))
http.Handle("/priority-info", gziphandler.GzipHandler(http.HandlerFunc(sq.servePriorityInfo)))
http.Handle("/health", gziphandler.GzipHandler(http.HandlerFunc(sq.serveHealth)))
http.Handle("/health.svg", gziphandler.GzipHandler(http.HandlerFunc(sq.serveHealthSVG)))
http.Handle("/sq-stats", gziphandler.GzipHandler(http.HandlerFunc(sq.serveSQStats)))
http.Handle("/flakes", gziphandler.GzipHandler(http.HandlerFunc(sq.serveFlakes)))
http.Handle("/metadata", gziphandler.GzipHandler(http.HandlerFunc(sq.serveMetadata)))
config.ServeDebugStats("/stats")
go http.ListenAndServe(config.Address, nil)
}
admin.Mux.HandleFunc("/api/emergency/stop", sq.EmergencyStopHTTP)
admin.Mux.HandleFunc("/api/emergency/resume", sq.EmergencyStopHTTP)
admin.Mux.HandleFunc("/api/emergency/status", sq.EmergencyStopHTTP)
if sq.githubE2EPollTime == 0 {
sq.githubE2EPollTime = githubE2EPollTime
}
sq.healthHistory = make([]healthRecord, 0)
go sq.handleGithubE2EAndMerge()
go sq.updateGoogleE2ELoop()
if sq.AdminPort != 0 {
go http.ListenAndServe(fmt.Sprintf("0.0.0.0:%v", sq.AdminPort), admin.Mux)
}
return nil
}
// EachLoop is called at the start of every munge loop
func (sq *SubmitQueue) EachLoop() error {
sq.Lock()
sq.updateHealth()
sq.lastPRStatus = sq.prStatus
sq.prStatus = map[string]submitStatus{}
objs := []*github.MungeObject{}
for _, obj := range sq.githubE2EQueue {
objs = append(objs, obj)
}
sq.Unlock()
for _, obj := range objs {
obj.Refresh()
// This should recheck it and clean up the queue, we don't care about the result
_ = sq.validForMerge(obj)
}
atomic.AddInt32(&sq.loopStarts, 1)
return nil
}
// AddFlags will add any request flags to the cobra `cmd`
func (sq *SubmitQueue) AddFlags(cmd *cobra.Command, config *github.Config) {
cmd.Flags().StringSliceVar(&sq.NonBlockingJobNames, "nonblocking-jenkins-jobs", []string{}, "Comma separated list of jobs that don't block merges, but will have status reported and issues filed.")
cmd.Flags().StringSliceVar(&sq.BlockingJobNames, "jenkins-jobs", []string{}, "Comma separated list of jobs in Jenkins that should block merges if failing.")
cmd.Flags().StringSliceVar(&sq.PresubmitJobNames, "presubmit-jobs", []string{""}, "Comma separated list of jobs in Jenkins that run presubmit and should have issues filed for flakes.")
cmd.Flags().StringSliceVar(&sq.WeakStableJobNames, "weak-stable-jobs",
[]string{},
"Comma separated list of jobs in Jenkins to use for stability testing that needs only weak success")
cmd.Flags().StringSliceVar(&sq.RequiredStatusContexts, "required-contexts", []string{}, "Comma separate list of status contexts required for a PR to be considered ok to merge")
cmd.Flags().StringVar(&sq.RetestBody, "retest-body", retestBody, "message which, when posted to the PR, will cause ALL `required-retest-contexts` to be re-tested")
cmd.Flags().BoolVar(&sq.FakeE2E, "fake-e2e", false, "Whether to use a fake for testing E2E stability.")
cmd.Flags().StringSliceVar(&sq.DoNotMergeMilestones, "do-not-merge-milestones", []string{}, "List of milestones which, when applied, will cause the PR to not be merged")
cmd.Flags().IntVar(&sq.AdminPort, "admin-port", 9999, "If non-zero, will serve administrative actions on this port.")
// If you create a StringSliceVar you may wish to check out 'cleanStringSliceVar()'
cmd.Flags().StringVar(&sq.Metadata.HistoryUrl, "history-url", "", "URL to access the submit-queue instance's health history.")
cmd.Flags().StringVar(&sq.Metadata.ChartUrl, "chart-url", "", "URL to access the submit-queue instance's health charts.")
}
// Hold the lock
func (sq *SubmitQueue) updateHealth() {
// Remove old entries from the front.
for len(sq.healthHistory) > 0 && time.Since(sq.healthHistory[0].Time).Hours() > 24.0 {
sq.healthHistory = sq.healthHistory[1:]
}
// Make the current record
stable, _ := sq.e2e.GCSBasedStable()
emergencyStop := sq.emergencyMergeStop()
newEntry := healthRecord{
Time: time.Now(),
Overall: stable && !emergencyStop,
Jobs: map[string]bool{},
}
for job, status := range sq.e2e.GetBuildStatus() {
// Ignore flakes.
newEntry.Jobs[job] = status.Status != "Not Stable"
}
if emergencyStop {
// invent an "emergency stop" job that's failing.
newEntry.Jobs["Emergency Stop"] = false
}
sq.healthHistory = append(sq.healthHistory, newEntry)
// Now compute the health structure so we don't have to do it on page load
sq.health.TotalLoops = len(sq.healthHistory)
sq.health.NumStable = 0
sq.health.NumStablePerJob = map[string]int{}
sq.health.MergePossibleNow = stable && !emergencyStop
for _, record := range sq.healthHistory {
if record.Overall {
sq.health.NumStable += 1
}
for job, stable := range record.Jobs {
if _, ok := sq.health.NumStablePerJob[job]; !ok {
sq.health.NumStablePerJob[job] = 0
}
if stable {
sq.health.NumStablePerJob[job]++
}
}
}
}
func (sq *SubmitQueue) e2eStable(aboutToMerge bool) bool {
wentStable := false
wentUnstable := false
stable, ignorableFlakes := sq.e2e.GCSBasedStable()
if stable && sq.emergencyMergeStop() {
stable = false
}
weakStable := sq.e2e.GCSWeakStable()
if !weakStable {
stable = weakStable
glog.Errorf("E2E is not stable because weak stable check failed.")
}
if aboutToMerge && stable && ignorableFlakes {
atomic.AddInt32(&sq.flakesIgnored, 1)
}
sq.Lock()
last := sq.lastE2EStable
if last && !stable {
wentUnstable = true
} else if !last && stable {
wentStable = true
}
sq.lastE2EStable = stable
sq.Unlock()
reason := ""
avatar := ""
if wentStable {
reason = e2eRecover
avatar = "success.png"
} else if wentUnstable {
reason = e2eFailure
avatar = "error.png"
}
if reason != "" {
submitStatus := submitStatus{
Time: sq.clock.Now(),
statusPullRequest: statusPullRequest{
Title: reason,
AvatarURL: avatar,
},
Reason: reason,
}
sq.Lock()
sq.statusHistory = append(sq.statusHistory, submitStatus)
sq.Unlock()
}
return stable
}
// This serves little purpose other than to show updates every minute in the
// web UI. Stable() will get called as needed against individual PRs as well.
func (sq *SubmitQueue) updateGoogleE2ELoop() {
for {
_ = sq.e2eStable(false)
time.Sleep(1 * time.Minute)
}
}
func objToStatusPullRequest(obj *github.MungeObject) *statusPullRequest {
if obj == nil {
return &statusPullRequest{}
}
res := statusPullRequest{
Number: *obj.Issue.Number,
URL: *obj.Issue.HTMLURL,
Title: *obj.Issue.Title,
Login: *obj.Issue.User.Login,
AvatarURL: *obj.Issue.User.AvatarURL,
}
pr, err := obj.GetPR()
if err != nil {
return &res
}
if pr.Additions != nil {
res.Additions = *pr.Additions
}
if pr.Deletions != nil {
res.Deletions = *pr.Deletions
}
prio, ok := obj.Annotations["priority"]
if !ok {
var prio string
p := priority(obj)
if p == retestNotRequiredMergePriority {
prio = retestNotRequiredLabel
} else {
prio = fmt.Sprintf("P%d", p) // store it a P1, P2, P3. Not just 1,2,3
}
obj.Annotations["priority"] = prio
}
if prio != "" {
res.ExtraInfo = append(res.ExtraInfo, prio)
}
milestone, ok := obj.Annotations["milestone"]
if !ok {
milestone = obj.ReleaseMilestone()
obj.Annotations["milestone"] = milestone
}
if milestone != "" {
res.ExtraInfo = append(res.ExtraInfo, milestone)
}
return &res
}
func reasonToState(reason string) string {
switch reason {
case merged:
return "success"
case mergedByHand:
return "success"
case e2eFailure:
return "success"
case ghE2EQueued:
return "success"
case ghE2EWaitingStart:
return "success"
case ghE2ERunning:
return "success"
case unknown:
return "failure"
default:
return "pending"
}
}
// SetMergeStatus will set the status given a particular PR. This function should
// be used instead of manipulating the prStatus directly as sq.Lock() must be
// called when manipulating that structure
// `obj` is the active github object
// `reason` is the new 'status' for this object
func (sq *SubmitQueue) SetMergeStatus(obj *github.MungeObject, reason string) {
glog.V(4).Infof("SubmitQueue not merging %d because %q", *obj.Issue.Number, reason)
submitStatus := submitStatus{
Time: sq.clock.Now(),
statusPullRequest: *objToStatusPullRequest(obj),
Reason: reason,
}
status := obj.GetStatus(sqContext)
if status == nil || *status.Description != reason {
state := reasonToState(reason)
url := fmt.Sprintf("http://submit-queue.k8s.io/#/prs/?prDisplay=%d&historyDisplay=%d", *obj.Issue.Number, *obj.Issue.Number)
_ = obj.SetStatus(state, url, reason, sqContext)
}
sq.Lock()
defer sq.Unlock()
// If we are currently retesting E2E the normal munge loop might find
// that the ci tests are not green. That's normal and expected and we
// should just ignore that status update entirely.
if sq.githubE2ERunning != nil && *sq.githubE2ERunning.Issue.Number == *obj.Issue.Number && reason == ciFailure {
return
}
if sq.onQueue(obj) {
sq.statusHistory = append(sq.statusHistory, submitStatus)
if len(sq.statusHistory) > 128 {
sq.statusHistory = sq.statusHistory[1:]
}
}
sq.prStatus[strconv.Itoa(*obj.Issue.Number)] = submitStatus
sq.cleanupOldE2E(obj, reason)
}
// sq.Lock() MUST be held!
func (sq *SubmitQueue) getE2EQueueStatus() []*statusPullRequest {
queue := []*statusPullRequest{}
keys := sq.orderedE2EQueue()
for _, k := range keys {
obj := sq.githubE2EQueue[k]
request := objToStatusPullRequest(obj)
queue = append(queue, request)
}
return queue
}
func (sq *SubmitQueue) marshal(data interface{}) []byte {
b, err := json.Marshal(data)
if err != nil {
glog.Errorf("Unable to Marshal data: %#v: %v", data, err)
return nil
}
return b
}
func (sq *SubmitQueue) getQueueHistory() []byte {
sq.Lock()
defer sq.Unlock()
return sq.marshal(sq.statusHistory)
}
// GetQueueStatus returns a json representation of the state of the submit
// queue. This can be used to generate web pages about the submit queue.
func (sq *SubmitQueue) getQueueStatus() []byte {
status := submitQueueStatus{}
sq.Lock()
defer sq.Unlock()
outputStatus := sq.lastPRStatus
for key, value := range sq.prStatus {
outputStatus[key] = value
}
status.PRStatus = outputStatus
return sq.marshal(status)
}
func (sq *SubmitQueue) getGithubE2EStatus() []byte {
sq.Lock()
defer sq.Unlock()
status := e2eQueueStatus{
E2EQueue: sq.getE2EQueueStatus(),
E2ERunning: objToStatusPullRequest(sq.githubE2ERunning),
}
return sq.marshal(status)
}
func (sq *SubmitQueue) getGoogleInternalStatus() []byte {
sq.Lock()
defer sq.Unlock()
return sq.marshal(sq.e2e.GetBuildStatus())
}
func (sq *SubmitQueue) getHealth() []byte {
sq.Lock()
defer sq.Unlock()
return sq.marshal(sq.health)
}
func (sq *SubmitQueue) getMetaData() []byte {
sq.Lock()
defer sq.Unlock()
return sq.marshal(sq.Metadata)
}
const (
unknown = "unknown failure"
noCLA = "PR is missing CLA label; needs one of " + claYesLabel + ", " + cncfClaYesLabel + " or " + claHumanLabel
noLGTM = "PR does not have LGTM."
lgtmEarly = "The PR was changed after the LGTM label was added."
unmergeable = "PR is unable to be automatically merged. Needs rebase."
undeterminedMergability = "Unable to determine is PR is mergeable. Will try again later."
noMerge = "Will not auto merge because " + doNotMergeLabel + " is present"
ciFailure = "Github CI tests are not green."
e2eFailure = "The e2e tests are failing. The entire submit queue is blocked."
e2eRecover = "The e2e tests started passing. The submit queue is unblocked."
merged = "MERGED!"
mergedByHand = "MERGED! (by hand outside of submit queue)"
ghE2EQueued = "Queued to run github e2e tests a second time."
ghE2EWaitingStart = "Requested and waiting for github e2e test to start running a second time."
ghE2ERunning = "Running github e2e tests a second time."
ghE2EFailed = "Second github e2e run failed."
unmergeableMilestone = "Milestone is for a future release and cannot be merged"
)
// validForMerge is the base logic about what PR can be automatically merged.
// PRs must pass this logic to be placed on the queue and they must pass this
// logic a second time to be retested/merged after they get to the top of
// the queue.
//
// If you update the logic PLEASE PLEASE PLEASE update serveMergeInfo() as well.
func (sq *SubmitQueue) validForMerge(obj *github.MungeObject) bool {
// Can't merge an issue!
if !obj.IsPR() {
return false
}
// Can't merge something already merged.
if m, err := obj.IsMerged(); err != nil {
glog.Errorf("%d: unknown err: %v", *obj.Issue.Number, err)
sq.SetMergeStatus(obj, unknown)
return false
} else if m {
sq.SetMergeStatus(obj, mergedByHand)
return false
}
if milestone := obj.Issue.Milestone; true {
title := ""
// Net set means the empty milestone, ""
if milestone != nil && milestone.Title != nil {
title = *milestone.Title
}
for _, blocked := range sq.DoNotMergeMilestones {
if title == blocked {
sq.SetMergeStatus(obj, unmergeableMilestone)
return false
}
}
}
// Must pass CLA checks
if !obj.HasLabel(claYesLabel) && !obj.HasLabel(claHumanLabel) && !obj.HasLabel(cncfClaYesLabel) {
sq.SetMergeStatus(obj, noCLA)
return false
}
// Obviously must be mergeable
if mergeable, err := obj.IsMergeable(); err != nil {
sq.SetMergeStatus(obj, undeterminedMergability)
return false
} else if !mergeable {
sq.SetMergeStatus(obj, unmergeable)
return false
}
// Validate the status information for this PR
if len(sq.RequiredStatusContexts) > 0 {
if ok := obj.IsStatusSuccess(sq.RequiredStatusContexts); !ok {
sq.SetMergeStatus(obj, ciFailure)
return false
}
}
if len(sq.RequiredRetestContexts) > 0 {
if ok := obj.IsStatusSuccess(sq.RequiredRetestContexts); !ok {
sq.SetMergeStatus(obj, ciFailure)
return false
}
}
// Clearly
if !obj.HasLabel(lgtmLabel) {
sq.SetMergeStatus(obj, noLGTM)
return false
}
// PR cannot change since LGTM was added
lastModifiedTime := obj.LastModifiedTime()
lgtmTime := obj.LabelTime(lgtmLabel)
if lastModifiedTime == nil || lgtmTime == nil {
glog.Errorf("PR %d was unable to determine when LGTM was added or when last modified", *obj.Issue.Number)
sq.SetMergeStatus(obj, unknown)
return false
}
if lastModifiedTime.After(*lgtmTime) {
sq.SetMergeStatus(obj, lgtmEarly)
return false
}
// PR cannot have the label which prevents merging.
if obj.HasLabel(doNotMergeLabel) {
sq.SetMergeStatus(obj, noMerge)
return false
}
return true
}
// Munge is the workhorse the will actually make updates to the PR
func (sq *SubmitQueue) Munge(obj *github.MungeObject) {
if !sq.validForMerge(obj) {
return
}
added := false
sq.Lock()
if _, ok := sq.githubE2EQueue[*obj.Issue.Number]; !ok {
atomic.AddInt32(&sq.prsAdded, 1)
added = true
}
// Add this most-recent object in place of the existing object. It will
// have more up2date information. Even though we explicitly refresh the
// PR information before do anything with it, this allow things like the
// queue order to change dynamically as labels are added/removed.
sq.githubE2EQueue[*obj.Issue.Number] = obj
sq.Unlock()
if added {
sq.SetMergeStatus(obj, ghE2EQueued)
}
return
}
func (sq *SubmitQueue) deleteQueueItem(obj *github.MungeObject) {
if sq.onQueue(obj) {
atomic.AddInt32(&sq.prsRemoved, 1)
}
delete(sq.githubE2EQueue, *obj.Issue.Number)
}
// If the PR was put in the github e2e queue previously, but now we don't
// think it should be in the e2e queue, remove it. MUST be called with sq.Lock()
// held.
func (sq *SubmitQueue) cleanupOldE2E(obj *github.MungeObject, reason string) {
switch reason {
case e2eFailure:
case ghE2EQueued:
case ghE2EWaitingStart:
case ghE2ERunning:
// Do nothing
case ciFailure:
// ciFailure is intersting. If the PR is being actively retested and then the
// time based loop finds the same PR it will try to set ciFailure. We should in fact
// not ever call this function in this case, but if we do call here, log it.
if sq.githubE2ERunning != nil && *sq.githubE2ERunning.Issue.Number == *obj.Issue.Number {
glog.Errorf("Trying to clean up %d due to ciFailure while it is being tested")
return
}
fallthrough
default:
if sq.githubE2ERunning != nil && *sq.githubE2ERunning.Issue.Number == *obj.Issue.Number {
sq.githubE2ERunning = nil
}
sq.deleteQueueItem(obj)
}
}
func priority(obj *github.MungeObject) int {
// jump to the front of the queue if you don't need retested
if obj.HasLabel(retestNotRequiredLabel) || obj.HasLabel(retestNotRequiredDocsOnlyLabel) {
return retestNotRequiredMergePriority
}
prio := obj.Priority()
// eparis randomly decided that unlabel issues count at p3
if prio == math.MaxInt32 {
return defaultMergePriority
}
return prio
}
type queueSorter struct {
queue []*github.MungeObject
labelTimeCache *mungerutil.LabelTimeCache
}
func (s queueSorter) Len() int { return len(s.queue) }
func (s queueSorter) Swap(i, j int) { s.queue[i], s.queue[j] = s.queue[j], s.queue[i] }
// If you update the function PLEASE PLEASE PLEASE also update servePriorityInfo()
func (s queueSorter) Less(i, j int) bool {
a := s.queue[i]
b := s.queue[j]
aPrio := priority(a)
bPrio := priority(b)
if aPrio < bPrio {
return true
} else if aPrio > bPrio {
return false
}
aDue := a.ReleaseMilestoneDue()
bDue := b.ReleaseMilestoneDue()
if aDue.Before(bDue) {
return true
} else if aDue.After(bDue) {
return false