-
Notifications
You must be signed in to change notification settings - Fork 115
/
keeper.go
1939 lines (1764 loc) · 59 KB
/
keeper.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright 2017 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Package keeper contains a controller for managing a keeper pool of PRs. The
// controller will automatically retest PRs in the pool and merge them if they
// pass tests.
package keeper
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"os"
"sort"
"strings"
"sync"
"time"
"github.com/jenkins-x/go-scm/scm"
"github.com/jenkins-x/lighthouse/pkg/apis/lighthouse/v1alpha1"
clientset "github.com/jenkins-x/lighthouse/pkg/client/clientset/versioned"
"github.com/jenkins-x/lighthouse/pkg/config"
"github.com/jenkins-x/lighthouse/pkg/config/job"
"github.com/jenkins-x/lighthouse/pkg/config/keeper"
"github.com/jenkins-x/lighthouse/pkg/errorutil"
"github.com/jenkins-x/lighthouse/pkg/filebrowser"
"github.com/jenkins-x/lighthouse/pkg/git"
"github.com/jenkins-x/lighthouse/pkg/jobutil"
"github.com/jenkins-x/lighthouse/pkg/keeper/blockers"
"github.com/jenkins-x/lighthouse/pkg/keeper/history"
"github.com/jenkins-x/lighthouse/pkg/scmprovider"
"github.com/jenkins-x/lighthouse/pkg/triggerconfig/inrepo"
"github.com/jenkins-x/lighthouse/pkg/util"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
githubql "github.com/shurcooL/githubv4"
"github.com/sirupsen/logrus"
tektonclient "github.com/tektoncd/pipeline/pkg/client/clientset/versioned"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/sets"
)
// For mocking out sleep during unit tests.
var sleep = time.Sleep
type launcher interface {
Launch(*v1alpha1.LighthouseJob) (*v1alpha1.LighthouseJob, error)
}
type scmProviderClient interface {
CreateGraphQLStatus(string, string, string, *scmprovider.Status) (*scm.Status, error)
GetCombinedStatus(org, repo, ref string) (*scm.CombinedStatus, error)
CreateStatus(org, repo, ref string, s *scm.StatusInput) (*scm.Status, error)
GetPullRequestChanges(org, repo string, number int) ([]*scm.Change, error)
GetRef(string, string, string) (string, error)
Merge(string, string, int, scmprovider.MergeDetails) error
Query(context.Context, interface{}, map[string]interface{}) error
SupportsGraphQL() bool
ProviderType() string
PRRefFmt() string
GetRepositoryByFullName(string) (*scm.Repository, error)
ListAllPullRequestsForFullNameRepo(string, scm.PullRequestListOptions) ([]*scm.PullRequest, error)
CreateComment(owner, repo string, number int, isPR bool, comment string) error
GetFile(string, string, string, string) ([]byte, error)
ListFiles(string, string, string, string) ([]*scm.FileEntry, error)
GetIssueLabels(string, string, int, bool) ([]*scm.Label, error)
}
type contextChecker interface {
// IsOptional tells whether a context is optional.
IsOptional(string) bool
// MissingRequiredContexts tells if required contexts are missing from the list of contexts provided.
MissingRequiredContexts([]string) []string
}
// DefaultController knows how to sync PRs and PJs.
type DefaultController struct {
logger *logrus.Entry
config config.Getter
spc scmProviderClient
fileBrowsers *filebrowser.FileBrowsers
launcherClient launcher
gc git.Client
tektonClient tektonclient.Interface
lhClient clientset.Interface
ns string
sc *statusController
m sync.Mutex
pools []Pool
// changedFiles caches the names of files changed by PRs.
// Cache entries expire if they are not used during a sync loop.
changedFiles *changedFilesAgent
History *history.History
}
// Action represents what actions the controller can take. It will take
// exactly one action each sync.
type Action string
// Constants for various actions the controller might take
const (
Wait Action = "WAIT"
Trigger = "TRIGGER"
TriggerBatch = "TRIGGER_BATCH"
Merge = "MERGE"
MergeBatch = "MERGE_BATCH"
PoolBlocked = "BLOCKED"
)
// recordableActions is the subset of actions that we keep historical record of.
// Ignore idle actions to avoid flooding the records with useless data.
var recordableActions = map[Action]bool{
Trigger: true,
TriggerBatch: true,
Merge: true,
MergeBatch: true,
}
// Pool represents information about a keeper pool. There is one for every
// org/repo/branch combination that has PRs in the pool.
type Pool struct {
Org string
Repo string
Branch string
// PRs with passing tests, pending tests, and missing or failed tests.
// Note that these results are rolled up. If all tests for a PR are passing
// except for one pending, it will be in PendingPRs.
SuccessPRs []PullRequest
PendingPRs []PullRequest
MissingPRs []PullRequest
// Empty if there is no pending batch.
BatchPending []PullRequest
// Which action did we last take, and to what target(s), if any.
Action Action
Target []PullRequest
Blockers []blockers.Blocker
Error string
}
type prWithStatus struct {
pr PullRequest
success bool
waitingFor []int
waitingForBatch []int
blocks []blockers.Blocker
}
// Prometheus Metrics
var (
keeperMetrics = struct {
// Per pool
pooledPRs *prometheus.GaugeVec
updateTime *prometheus.GaugeVec
merges *prometheus.HistogramVec
// Singleton
syncDuration prometheus.Gauge
statusUpdateDuration prometheus.Gauge
}{
pooledPRs: prometheus.NewGaugeVec(prometheus.GaugeOpts{
Name: "pooledprs",
Help: "Number of PRs in each Keeper pool.",
}, []string{
"org",
"repo",
"branch",
}),
updateTime: prometheus.NewGaugeVec(prometheus.GaugeOpts{
Name: "updatetime",
Help: "The last time each subpool was synced. (Used to determine 'pooledprs' freshness.)",
}, []string{
"org",
"repo",
"branch",
}),
merges: prometheus.NewHistogramVec(prometheus.HistogramOpts{
Name: "merges",
Help: "Histogram of merges where values are the number of PRs merged together.",
Buckets: []float64{1, 2, 3, 4, 5, 7, 10, 15, 25},
}, []string{
"org",
"repo",
"branch",
}),
syncDuration: prometheus.NewGauge(prometheus.GaugeOpts{
Name: "syncdur",
Help: "The duration of the last loop of the sync controller.",
}),
statusUpdateDuration: prometheus.NewGauge(prometheus.GaugeOpts{
Name: "statusupdatedur",
Help: "The duration of the last loop of the status update controller.",
}),
}
)
func init() {
prometheus.MustRegister(keeperMetrics.pooledPRs)
prometheus.MustRegister(keeperMetrics.updateTime)
prometheus.MustRegister(keeperMetrics.merges)
prometheus.MustRegister(keeperMetrics.syncDuration)
prometheus.MustRegister(keeperMetrics.statusUpdateDuration)
}
// NewController makes a DefaultController out of the given clients.
func NewController(spcSync, spcStatus *scmprovider.Client, fileBrowsers *filebrowser.FileBrowsers, launcherClient launcher, tektonClient tektonclient.Interface, lighthouseClient clientset.Interface, ns string, cfg config.Getter, gc git.Client, maxRecordsPerPool int, historyURI, statusURI string, logger *logrus.Entry) (*DefaultController, error) {
if logger == nil {
logger = logrus.NewEntry(logrus.StandardLogger())
}
hist, err := history.New(maxRecordsPerPool, historyURI)
if err != nil {
return nil, fmt.Errorf("error initializing history client from %q: %v", historyURI, err)
}
sc := &statusController{
logger: logger.WithField("controller", "status-update"),
spc: spcStatus,
config: cfg,
newPoolPending: make(chan bool, 1),
shutDown: make(chan bool),
path: statusURI,
}
go sc.run()
return &DefaultController{
logger: logger.WithField("controller", "sync"),
spc: spcSync,
fileBrowsers: fileBrowsers,
launcherClient: launcherClient,
tektonClient: tektonClient,
lhClient: lighthouseClient,
ns: ns,
config: cfg,
gc: gc,
sc: sc,
changedFiles: &changedFilesAgent{
spc: spcSync,
nextChangeCache: make(map[changeCacheKey][]string),
},
History: hist,
}, nil
}
// Shutdown signals the statusController to stop working and waits for it to
// finish its last update loop before terminating.
// DefaultController.Sync() should not be used after this function is called.
func (c *DefaultController) Shutdown() {
err := c.gc.Clean()
if err != nil {
c.logger.Warnf("error cleaning local git cache: %s", err)
}
c.History.Flush()
c.sc.shutdown()
}
// GetHistory returns the history
func (c *DefaultController) GetHistory() *history.History {
return c.History
}
func (pr *PullRequest) prKey() string {
return fmt.Sprintf("%s#%d", string(pr.Repository.NameWithOwner), int(pr.Number))
}
// newExpectedContext creates a Context with Expected state.
func newExpectedContext(c string) Context {
return Context{
Context: githubql.String(c),
State: githubql.StatusStateExpected,
Description: githubql.String(""),
}
}
// contextsToStrings converts a list Context to a list of string
func contextsToStrings(contexts []Context) []string {
var names []string
for _, c := range contexts {
names = append(names, string(c.Context))
}
return names
}
// Sync runs one sync iteration.
func (c *DefaultController) Sync() error {
start := time.Now()
defer func() {
duration := time.Since(start)
c.logger.WithField("duration", duration.String()).Info("Synced")
keeperMetrics.syncDuration.Set(duration.Seconds())
}()
defer c.changedFiles.prune()
c.logger.Debug("Building keeper pool.")
prs := make(map[string]PullRequest)
if c.spc.SupportsGraphQL() {
for _, query := range c.config().Keeper.Queries {
q := query.Query()
results, err := graphQLSearch(c.spc.Query, c.logger, q, time.Time{}, time.Now())
if err != nil && len(results) == 0 {
return fmt.Errorf("query %q, err: %v", q, err)
}
if err != nil {
c.logger.WithError(err).WithField("query", q).Warning("found partial results")
}
for _, pr := range results {
p := pr
prs[p.prKey()] = pr
}
}
} else {
results, err := restAPISearch(c.spc, c.logger, c.config().Keeper.Queries, time.Time{}, time.Now())
if err != nil {
c.logger.WithError(err).Warnf("failed to perform REST query for PRs")
return errors.Wrapf(err, "failed to perform REST query for PRs")
}
for _, pr := range results {
p := pr
prs[p.prKey()] = pr
}
}
c.logger.WithField(
"duration", time.Since(start).String(),
).Debugf("Found %d (unfiltered) pool PRs.", len(prs))
var lhjs []v1alpha1.LighthouseJob
var blocks blockers.Blockers
var err error
if len(prs) > 0 {
start := time.Now()
lhjList, err := c.lhClient.LighthouseV1alpha1().LighthouseJobs(c.ns).List(context.TODO(), metav1.ListOptions{})
if err != nil {
c.logger.WithField("duration", time.Since(start).String()).Debug("Failed to list LighthouseJobs from the cluster.")
return err
}
if len(lhjList.Items) > 200 {
c.logger.Warn("Over 200+ lighthouse jobs in the cluster, this could lead to keeper failing readiness and liveness probes")
}
c.logger.WithField("duration", time.Since(start).String()).WithField("lighthouse-job-quantity", len(lhjList.Items)).Debug("Listed LighthouseJobs from the cluster.")
lhjs = lhjList.Items
// TODO: Support blockers with non-graphql
if c.spc.SupportsGraphQL() {
if label := c.config().Keeper.BlockerLabel; label != "" {
c.logger.Debugf("Searching for blocking issues (label %q).", label)
orgExcepts, repos := c.config().Keeper.Queries.OrgExceptionsAndRepos()
orgs := make([]string, 0, len(orgExcepts))
for org := range orgExcepts {
orgs = append(orgs, org)
}
orgRepoQuery := orgRepoQueryString(orgs, repos.UnsortedList(), orgExcepts)
blocks, err = blockers.FindAll(c.spc, c.logger, label, orgRepoQuery)
if err != nil {
return err
}
}
}
}
// Partition PRs into subpools and filter out non-pool PRs.
rawPools, err := c.dividePool(prs, lhjs)
if err != nil {
return err
}
filteredPools := c.filterSubpools(c.config().Keeper.MaxGoroutines, rawPools)
// Sync subpools in parallel.
poolChan := make(chan Pool, len(filteredPools))
subpoolsInParallel(
c.config().Keeper.MaxGoroutines,
filteredPools,
func(sp *subpool) {
pool, err := c.syncSubpool(*sp, blocks.GetApplicable(sp.org, sp.repo, sp.branch))
if err != nil {
sp.log.WithError(err).Errorf("Error syncing subpool.")
}
poolChan <- pool
},
)
close(poolChan)
pools := make([]Pool, 0, len(poolChan))
for pool := range poolChan {
pools = append(pools, pool)
}
sortPools(pools)
c.m.Lock()
c.pools = pools
// Notify statusController about the new pool.
c.sc.Lock()
c.sc.blocks = blocks
c.sc.poolPRs = poolsToStatusPRMap(pools)
select {
case c.sc.newPoolPending <- true:
default:
}
c.sc.Unlock()
// While we're locked, rerun failed-but-rerunnable PipelineRuns.
c.logger.WithField("duration", time.Since(start).String()).Debug("Rerunning PipelineRuns failed due to race condition.")
err = rerunPipelineRunsWithRaceConditionFailure(c.tektonClient, c.ns, c.logger)
if err != nil {
c.logger.WithError(err).Error("Error rerunning PipelineRuns failed by Tekton race condition")
}
c.logger.WithField("duration", time.Since(start).String()).Debug("Finished rerunning PipelineRuns failed due to race condition.")
c.m.Unlock()
c.History.Flush()
return nil
}
func poolsToStatusPRMap(pools []Pool) map[string]prWithStatus {
result := make(map[string]prWithStatus)
for _, p := range pools {
for k, v := range p.toPRsWithStatus() {
result[k] = v
}
}
return result
}
func (p *Pool) toPRsWithStatus() map[string]prWithStatus {
result := make(map[string]prWithStatus)
waitingFor := make(map[int]bool)
waitingForBatch := make(map[int]bool)
targets := make(map[int]bool)
if p.Action == Merge || p.Action == MergeBatch {
for _, t := range p.Target {
targets[int(t.Number)] = true
}
}
for _, w := range p.PendingPRs {
waitingFor[int(w.Number)] = true
result[w.prKey()] = prWithStatus{
pr: w,
success: false,
}
}
for _, b := range p.BatchPending {
waitingForBatch[int(b.Number)] = true
result[b.prKey()] = prWithStatus{
pr: b,
success: false,
}
}
for _, m := range p.MissingPRs {
result[m.prKey()] = prWithStatus{
pr: m,
success: false,
}
}
for _, s := range p.SuccessPRs {
out := prWithStatus{
pr: s,
success: true,
waitingFor: []int{},
waitingForBatch: []int{},
blocks: p.Blockers,
}
// Add waiting for information for succeeded PRs
_, inTargets := targets[int(s.Number)]
_, inPending := waitingFor[int(s.Number)]
_, inBatch := waitingFor[int(s.Number)]
if !inTargets && !inPending && !inBatch {
for k := range waitingFor {
out.waitingFor = append(out.waitingFor, k)
}
for k := range waitingForBatch {
out.waitingForBatch = append(out.waitingForBatch, k)
}
}
result[s.prKey()] = out
}
return result
}
func (c *DefaultController) ServeHTTP(w http.ResponseWriter, r *http.Request) {
c.m.Lock()
defer c.m.Unlock()
b, err := json.Marshal(c.pools)
if err != nil {
c.logger.WithError(err).Error("Encoding JSON.")
b = []byte("[]")
}
if _, err = w.Write(b); err != nil {
c.logger.WithError(err).Error("Writing JSON response.")
}
}
// GetPools returns the pool status
func (c *DefaultController) GetPools() []Pool {
c.m.Lock()
defer c.m.Unlock()
answer := []Pool{}
for _, p := range c.pools {
answer = append(answer, p)
}
return answer
}
func subpoolsInParallel(goroutines int, sps map[string]*subpool, process func(*subpool)) {
// Load the subpools into a channel for use as a work queue.
queue := make(chan *subpool, len(sps))
for _, sp := range sps {
queue <- sp
}
close(queue)
if goroutines > len(queue) {
goroutines = len(queue)
}
wg := &sync.WaitGroup{}
wg.Add(goroutines)
for i := 0; i < goroutines; i++ {
go func() {
defer wg.Done()
for sp := range queue {
process(sp)
}
}()
}
wg.Wait()
}
// filterSubpools filters non-pool PRs out of the initially identified subpools,
// deleting any pools that become empty.
// See filterSubpool for filtering details.
func (c *DefaultController) filterSubpools(goroutines int, raw map[string]*subpool) map[string]*subpool {
filtered := make(map[string]*subpool)
var lock sync.Mutex
subpoolsInParallel(
goroutines,
raw,
func(sp *subpool) {
if err := c.initSubpoolData(sp); err != nil {
sp.log.WithError(err).Error("Error initializing subpool.")
return
}
key := poolKey(sp.org, sp.repo, sp.branch)
if spFiltered := filterSubpool(c.spc, sp); spFiltered != nil {
sp.log.WithField("key", key).WithField("pool", spFiltered).Debug("filtered sub-pool")
lock.Lock()
filtered[key] = spFiltered
lock.Unlock()
} else {
sp.log.WithField("key", key).WithField("pool", spFiltered).Debug("filtering sub-pool removed all PRs")
}
},
)
return filtered
}
func (c *DefaultController) initSubpoolData(sp *subpool) error {
var err error
sp.presubmits, err = c.presubmitsByPull(sp)
if err != nil {
return fmt.Errorf("error determining required presubmit PipelineActivitys: %v", err)
}
sp.cc, err = c.config().GetKeeperContextPolicy(sp.org, sp.repo, sp.branch)
if err != nil {
return fmt.Errorf("error setting up context checker: %v", err)
}
return nil
}
// filterSubpool filters PRs from an initially identified subpool, returning the
// filtered subpool.
// If the subpool becomes empty 'nil' is returned to indicate that the subpool
// should be deleted.
func filterSubpool(spc scmProviderClient, sp *subpool) *subpool {
var toKeep []PullRequest
for _, pr := range sp.prs {
p := pr
if !filterPR(spc, sp, &p) {
toKeep = append(toKeep, pr)
}
}
if len(toKeep) == 0 {
return nil
}
sp.prs = toKeep
return sp
}
// filterPR indicates if a PR should be filtered out of the subpool.
// Specifically we filter out PRs that:
// - Have known merge conflicts.
// - Have failing or missing status contexts.
// - Have pending required status contexts that are not associated with a
// PipelineActivity. (This ensures that the 'keeper' context indicates that the pending
// status is preventing merge. Required PipelineActivity statuses are allowed to be
// 'pending' because this prevents kicking PRs from the pool when Keeper is
// retesting them.)
func filterPR(spc scmProviderClient, sp *subpool, pr *PullRequest) bool {
log := sp.log.WithFields(pr.logFields())
// Skip PRs that are known to be unmergeable.
if pr.Mergeable == githubql.MergeableStateConflicting {
log.Debug("filtering out PR as it is unmergeable")
return true
}
// Filter out PRs with unsuccessful contexts unless the only unsuccessful
// contexts are pending required PipelineActivitys.
contexts, err := headContexts(log, spc, pr)
if err != nil {
log.WithError(err).Error("Getting head contexts.")
return true
}
presubmitsHaveContext := func(context string) bool {
for _, job := range sp.presubmits[int(pr.Number)] {
if job.Context == context {
return true
}
}
return false
}
for _, ctx := range unsuccessfulContexts(contexts, sp.cc, log) {
if ctx.State != githubql.StatusStatePending {
log.WithField("context", ctx.Context).Debug("filtering out PR as unsuccessful context is not pending")
return true
}
if !presubmitsHaveContext(string(ctx.Context)) {
log.WithField("context", ctx.Context).Debug("filtering out PR as unsuccessful context is not Prow-controlled")
return true
}
}
return false
}
type simpleState string
const (
failureState simpleState = "failure"
pendingState simpleState = "pending"
successState simpleState = "success"
)
func toSimpleState(s v1alpha1.PipelineState) simpleState {
if s == v1alpha1.TriggeredState || s == v1alpha1.PendingState || s == v1alpha1.RunningState {
return pendingState
} else if s == v1alpha1.SuccessState {
return successState
}
return failureState
}
// isPassingTests returns whether or not all contexts set on the PR except for
// the keeper pool context are passing.
func isPassingTests(log *logrus.Entry, spc scmProviderClient, pr PullRequest, cc contextChecker) bool {
log = log.WithFields(pr.logFields())
contexts, err := headContexts(log, spc, &pr)
if err != nil {
log.WithError(err).Error("Getting head commit status contexts.")
// If we can't get the status of the commit, assume that it is failing.
return false
}
unsuccessful := unsuccessfulContexts(contexts, cc, log)
return len(unsuccessful) == 0
}
// unsuccessfulContexts determines which contexts from the list that we care about are
// failed. For instance, we do not care about our own context.
// If the branchProtection is set to only check for required checks, we will skip
// all non-required tests. If required tests are missing from the list, they will be
// added to the list of failed contexts.
func unsuccessfulContexts(contexts []Context, cc contextChecker, log *logrus.Entry) []Context {
var failed []Context
for _, ctx := range contexts {
if string(ctx.Context) == GetStatusContextLabel() {
continue
}
// Ignore legacy "tide" and "keeper" contexts
if string(ctx.Context) == "keeper" || string(ctx.Context) == "tide" {
continue
}
if cc.IsOptional(string(ctx.Context)) {
continue
}
if ctx.State != githubql.StatusStateSuccess {
failed = append(failed, ctx)
}
}
for _, c := range cc.MissingRequiredContexts(contextsToStrings(contexts)) {
failed = append(failed, newExpectedContext(c))
}
log.Debugf("from %d total contexts (%v) found %d failing contexts: %v", len(contexts), contextsToStrings(contexts), len(failed), contextsToStrings(failed))
return failed
}
func pickSmallestPassingNumber(log *logrus.Entry, spc scmProviderClient, prs []PullRequest, cc contextChecker) (bool, PullRequest) {
smallestNumber := -1
var smallestPR PullRequest
for _, pr := range prs {
if smallestNumber != -1 && int(pr.Number) >= smallestNumber {
continue
}
if len(pr.Commits.Nodes) < 1 {
continue
}
if !isPassingTests(log, spc, pr, cc) {
continue
}
smallestNumber = int(pr.Number)
smallestPR = pr
}
return smallestNumber > -1, smallestPR
}
// accumulateBatch returns a list of PRs that can be merged after passing batch
// testing, if any exist. It also returns a list of PRs currently being batch
// tested.
func accumulateBatch(presubmits map[int][]job.Presubmit, prs []PullRequest, pjs []v1alpha1.LighthouseJob, log *logrus.Entry) ([]PullRequest, []PullRequest) {
log.Debug("accumulating PRs for batch testing")
if len(presubmits) == 0 {
log.Debug("no presubmits configured, no batch can be triggered")
return nil, nil
}
prNums := make(map[int]PullRequest)
for _, pr := range prs {
prNums[int(pr.Number)] = pr
}
type accState struct {
prs []PullRequest
jobStates map[string]simpleState
// Are the pull requests in the ref still acceptable? That is, do they
// still point to the heads of the PRs?
validPulls bool
}
states := make(map[string]*accState)
for _, pj := range pjs {
if pj.Spec.Type != job.BatchJob {
continue
}
// First validate the batch job's refs.
ref := pj.Spec.Refs.String()
if _, ok := states[ref]; !ok {
state := &accState{
jobStates: make(map[string]simpleState),
validPulls: true,
}
for _, pull := range pj.Spec.Refs.Pulls {
if pr, ok := prNums[pull.Number]; ok && string(pr.HeadRefOID) == pull.SHA {
state.prs = append(state.prs, pr)
} else if !ok {
state.validPulls = false
log.WithField("batch", ref).WithFields(pr.logFields()).Debug("batch job invalid, PR left pool")
break
} else {
state.validPulls = false
log.WithField("batch", ref).WithFields(pr.logFields()).Debug("batch job invalid, PR HEAD changed")
break
}
}
states[ref] = state
}
if !states[ref].validPulls {
// The batch contains a PR ref that has changed. Skip it.
continue
}
// Batch job refs are valid. Now accumulate job states by batch ref.
context := pj.Spec.Context
jobState := toSimpleState(pj.Status.State)
// Store the best result for this ref+context.
if s, ok := states[ref].jobStates[context]; !ok || s == failureState || jobState == successState {
states[ref].jobStates[context] = jobState
}
}
var pendingBatch, successBatch []PullRequest
for ref, state := range states {
if !state.validPulls {
continue
}
requiredPresubmits := sets.NewString()
for _, pr := range state.prs {
for _, job := range presubmits[int(pr.Number)] {
requiredPresubmits.Insert(job.Context)
}
}
overallState := successState
for _, p := range requiredPresubmits.List() {
if s, ok := state.jobStates[p]; !ok || s == failureState {
overallState = failureState
log.WithField("batch", ref).Debugf("batch invalid, required presubmit %s is not passing", p)
break
} else if s == pendingState && overallState == successState {
overallState = pendingState
}
}
switch overallState {
// Currently we only consider 1 pending batch and 1 success batch at a time.
// If more are somehow present they will be ignored.
case pendingState:
pendingBatch = state.prs
case successState:
successBatch = state.prs
}
}
return successBatch, pendingBatch
}
// accumulate returns the supplied PRs sorted into three buckets based on their
// accumulated state across the presubmits.
func accumulate(presubmits map[int][]job.Presubmit, prs []PullRequest, pjs []v1alpha1.LighthouseJob, log *logrus.Entry) (successes, pendings, missings []PullRequest, missingTests map[int][]job.Presubmit) {
missingTests = map[int][]job.Presubmit{}
for _, pr := range prs {
// Accumulate the best result for each job (Passing > Pending > Failing/Unknown)
// We can ignore the baseSHA here because the subPool only contains PipelineActivitys with the correct baseSHA
psStates := make(map[string]simpleState)
for _, pj := range pjs {
if pj.Spec.Type != job.PresubmitJob {
continue
}
if len(pj.Spec.Refs.Pulls) == 0 || pj.Spec.Refs.Pulls[0].Number != int(pr.Number) {
continue
}
if pj.Spec.Refs.Pulls[0].SHA != string(pr.HeadRefOID) {
continue
}
name := pj.Spec.Context
oldState := psStates[name]
newState := toSimpleState(pj.Status.State)
if oldState == failureState || oldState == "" {
psStates[name] = newState
} else if oldState == pendingState && newState == successState {
psStates[name] = successState
}
}
// The overall result for the PR is the worst of the best of all its
// required Presubmits
overallState := successState
for _, ps := range presubmits[int(pr.Number)] {
if s, ok := psStates[ps.Context]; !ok {
// No PJ with correct baseSHA+headSHA exists
missingTests[int(pr.Number)] = append(missingTests[int(pr.Number)], ps)
log.WithFields(pr.logFields()).Debugf("missing presubmit %s", ps.Context)
} else if s == failureState {
// PJ with correct baseSHA+headSHA exists but failed
missingTests[int(pr.Number)] = append(missingTests[int(pr.Number)], ps)
log.WithFields(pr.logFields()).Debugf("presubmit %s not passing", ps.Context)
} else if s == pendingState {
log.WithFields(pr.logFields()).Debugf("presubmit %s pending", ps.Context)
overallState = pendingState
}
}
if len(missingTests[int(pr.Number)]) > 0 {
overallState = failureState
}
if overallState == successState {
successes = append(successes, pr)
} else if overallState == pendingState {
pendings = append(pendings, pr)
} else {
missings = append(missings, pr)
}
}
return
}
func prNumbers(prs []PullRequest) []int {
var nums []int
for _, pr := range prs {
nums = append(nums, int(pr.Number))
}
return nums
}
func (c *DefaultController) pickBatch(sp subpool, cc contextChecker) ([]PullRequest, error) {
batchLimit := c.config().Keeper.BatchSizeLimit(sp.org, sp.repo)
if batchLimit < 0 {
sp.log.Debug("Batch merges disabled by configuration in this repo.")
return nil, nil
}
// we must choose the oldest PRs for the batch
sort.Slice(sp.prs, func(i, j int) bool { return sp.prs[i].Number < sp.prs[j].Number })
var candidates []PullRequest
for _, pr := range sp.prs {
if isPassingTests(sp.log, c.spc, pr, cc) {
candidates = append(candidates, pr)
}
}
if len(candidates) == 0 {
sp.log.Debugf("of %d possible PRs, none were passing tests, no batch will be created", len(sp.prs))
return nil, nil
}
sp.log.Debugf("of %d possible PRs, %d are passing tests", len(sp.prs), len(candidates))
r, err := c.gc.Clone(sp.org + "/" + sp.repo)
if err != nil {
return nil, err
}
defer r.Clean()
if err := r.Config("user.name", "prow"); err != nil {
return nil, err
}
if err := r.Config("user.email", "prow@localhost"); err != nil {
return nil, err
}
if err := r.Config("commit.gpgsign", "false"); err != nil {
sp.log.Warningf("Cannot set gpgsign=false in gitconfig: %v", err)
}
if err := r.Checkout(sp.sha); err != nil {
return nil, err
}
var res []PullRequest
for _, pr := range candidates {
if ok, err := r.Merge(string(pr.HeadRefOID)); err != nil {
// we failed to abort the merge and our git client is
// in a bad state; it must be cleaned before we try again
return nil, err
} else if ok {
res = append(res, pr)
// TODO: Make this configurable per subpool.
if batchLimit > 0 && len(res) >= batchLimit {
break
}
}
}
return res, nil
}
func checkMergeLabels(pr PullRequest, squash, rebase, merge string, method keeper.PullRequestMergeType) (keeper.PullRequestMergeType, error) {
labelCount := 0
for _, prlabel := range pr.Labels.Nodes {
switch string(prlabel.Name) {
case squash:
method = keeper.MergeSquash
labelCount++
case rebase:
method = keeper.MergeRebase
labelCount++
case merge:
method = keeper.MergeMerge
labelCount++
}
if labelCount > 1 {
return "", fmt.Errorf("conflicting merge method override labels")
}
}
return method, nil
}
func (c *DefaultController) prepareMergeDetails(commitTemplates keeper.MergeCommitTemplate, pr PullRequest, mergeMethod keeper.PullRequestMergeType) scmprovider.MergeDetails {
ghMergeDetails := scmprovider.MergeDetails{
SHA: string(pr.HeadRefOID),
MergeMethod: string(mergeMethod),
}
if commitTemplates.Title != nil {
var b bytes.Buffer
if err := commitTemplates.Title.Execute(&b, pr); err != nil {
c.logger.Errorf("error executing commit title template: %v", err)
} else {
ghMergeDetails.CommitTitle = b.String()
}
}