forked from kubernetes/test-infra
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tide.go
265 lines (235 loc) · 6.83 KB
/
tide.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
/*
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 main
import (
"encoding/json"
"fmt"
"net/http"
"strings"
"sync"
"time"
"github.com/sirupsen/logrus"
utilerrors "k8s.io/apimachinery/pkg/util/errors"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/test-infra/prow/config"
"k8s.io/test-infra/prow/tide"
"k8s.io/test-infra/prow/tide/history"
)
type tidePools struct {
Queries []string
TideQueries []config.TideQuery
Pools []tide.Pool
}
type tideHistory struct {
History map[string][]history.Record
}
type tideAgent struct {
log *logrus.Entry
path string
updatePeriod func() time.Duration
// Config for hiding repos
hiddenRepos func() []string
hiddenOnly bool
showHidden bool
tenantIDs sets.String
cfg func() *config.Config
sync.Mutex
pools []tide.Pool
history map[string][]history.Record
}
func (ta *tideAgent) start() {
startTimePool := time.Now()
if err := ta.updatePools(); err != nil {
ta.log.WithError(err).Error("Updating pools the first time.")
}
startTimeHistory := time.Now()
if err := ta.updateHistory(); err != nil {
ta.log.WithError(err).Error("Updating history the first time.")
}
go func() {
for {
time.Sleep(time.Until(startTimePool.Add(ta.updatePeriod())))
startTimePool = time.Now()
if err := ta.updatePools(); err != nil {
ta.log.WithError(err).Error("Updating pools.")
}
}
}()
go func() {
for {
time.Sleep(time.Until(startTimeHistory.Add(ta.updatePeriod())))
startTimeHistory = time.Now()
if err := ta.updateHistory(); err != nil {
ta.log.WithError(err).Error("Updating history.")
}
}
}()
}
func fetchTideData(log *logrus.Entry, path string, data interface{}) error {
var prevErrs []error
var err error
backoff := 5 * time.Second
for i := 0; i < 4; i++ {
var resp *http.Response
if err != nil {
prevErrs = append(prevErrs, err)
time.Sleep(backoff)
backoff *= 4
}
resp, err = http.Get(path)
if err == nil {
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
err = fmt.Errorf("response has status code %d", resp.StatusCode)
continue
}
if err = json.NewDecoder(resp.Body).Decode(data); err != nil {
break
}
break
}
}
// Either combine previous errors with the returned error, or if we succeeded
// log once about any errors we saw before succeeding.
prevErr := utilerrors.NewAggregate(prevErrs)
if err != nil {
return utilerrors.NewAggregate([]error{err, prevErr})
}
if prevErr != nil {
log.WithError(prevErr).Infof(
"Failed %d retries fetching Tide data before success: %v.",
len(prevErrs),
prevErr,
)
}
return nil
}
func (ta *tideAgent) updatePools() error {
var pools []tide.Pool
if err := fetchTideData(ta.log, ta.path, &pools); err != nil {
return err
}
pools = ta.filterPools(pools)
ta.Lock()
defer ta.Unlock()
ta.pools = pools
return nil
}
func (ta *tideAgent) updateHistory() error {
path := strings.TrimSuffix(ta.path, "/") + "/history"
var history map[string][]history.Record
if err := fetchTideData(ta.log, path, &history); err != nil {
return err
}
history = ta.filterHistory(history)
ta.Lock()
defer ta.Unlock()
ta.history = history
return nil
}
func (ta *tideAgent) matchingIDs(ids []string) bool {
return len(ids) > 0 && ta.tenantIDs.HasAll(ids...)
}
func (ta *tideAgent) filterPools(pools []tide.Pool) []tide.Pool {
filtered := make([]tide.Pool, 0, len(pools))
for _, pool := range pools {
// curIDs are the IDs associated with all PJs in the Pool
// We want to add the ID associated with the OrgRepo for extra protection
curIDs := sets.NewString(pool.TenantIDs...)
orgRepoID := ta.cfg().GetProwJobDefault(pool.Org+"/"+pool.Repo, "*").TenantID
needsHide := matches(pool.Org+"/"+pool.Repo, ta.hiddenRepos())
if match := ta.filter(orgRepoID, curIDs, needsHide); match {
filtered = append(filtered, pool)
}
}
return filtered
}
func noTenantIDOrDefaultTenantID(ids []string) bool {
for _, id := range ids {
if id != "" && id != config.DefaultTenantID {
return false
}
}
return true
}
func recordIDs(records []history.Record) sets.String {
res := sets.String{}
for _, record := range records {
res.Insert(record.TenantIDs...)
}
return res
}
func (ta *tideAgent) filterHistory(hist map[string][]history.Record) map[string][]history.Record {
filtered := make(map[string][]history.Record, len(hist))
for pool, records := range hist {
orgRepo := strings.Split(pool, ":")[0]
curIDs := recordIDs(records).Insert()
orgRepoID := ta.cfg().GetProwJobDefault(orgRepo, "*").TenantID
needsHide := matches(orgRepo, ta.hiddenRepos())
if match := ta.filter(orgRepoID, curIDs, needsHide); match {
filtered[pool] = records
}
}
return filtered
}
func (ta *tideAgent) filter(orgRepoID string, curIDs sets.String, needsHide bool) bool {
// If the orgrepo is associated with no tenantID OR the default tenantID we ignore it here.
// This prevents already IDd History from getting the default ID assigned to them when their orgrepo is not associated with an OrgRepo.
// History with no tenantID and with default tenantID behave the same, so adding the default ID just causes issues
if orgRepoID != "" && orgRepoID != config.DefaultTenantID {
curIDs.Insert(orgRepoID)
}
if len(ta.tenantIDs) > 0 {
if ta.matchingIDs(curIDs.List()) {
// Deck has tenantIDs and they match with the History
return true
}
} else if needsHide {
if ta.showHidden || ta.hiddenOnly {
return true
}
} else if !ta.hiddenOnly && noTenantIDOrDefaultTenantID(curIDs.List()) {
return true
}
return false
}
func (ta *tideAgent) filterQueries(queries []config.TideQuery) []config.TideQuery {
filtered := make([]config.TideQuery, 0, len(queries))
for _, qc := range queries {
curIDs := qc.TenantIDs(*ta.cfg())
needsHide := false
for _, repo := range qc.Repos {
if matches(repo, ta.hiddenRepos()) {
needsHide = true
break
}
}
orgRepoID := ""
if match := ta.filter(orgRepoID, sets.NewString(curIDs...), needsHide); match {
filtered = append(filtered, qc)
}
}
return filtered
}
// matches returns whether the provided repo intersects
// with repos. repo has always the "org/repo" format but
// repos can include both orgs and repos.
func matches(repo string, repos []string) bool {
org := strings.Split(repo, "/")[0]
for _, r := range repos {
if r == repo || r == org {
return true
}
}
return false
}