forked from kubernetes/test-infra
-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
311 lines (268 loc) · 7.37 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
/*
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.
*/
// Tot vends (rations) incrementing numbers for use in builds.
// https://en.wikipedia.org/wiki/Rum_ration
package main
import (
"encoding/json"
"errors"
"flag"
"fmt"
"io/ioutil"
"net/http"
"os"
"strconv"
"strings"
"sync"
"time"
"github.com/sirupsen/logrus"
"k8s.io/test-infra/prow/interrupts"
"k8s.io/test-infra/prow/config"
"k8s.io/test-infra/prow/logrusutil"
"k8s.io/test-infra/prow/pjutil"
"k8s.io/test-infra/prow/pod-utils/downwardapi"
"k8s.io/test-infra/prow/pod-utils/gcs"
)
type options struct {
port int
storagePath string
useFallback bool
fallbackURI string
configPath string
jobConfigPath string
fallbackBucket string
}
func gatherOptions() options {
o := options{}
flag.IntVar(&o.port, "port", 8888, "Port to listen on.")
flag.StringVar(&o.storagePath, "storage", "tot.json", "Where to store the results.")
flag.BoolVar(&o.useFallback, "fallback", false, "Fallback to GCS bucket for missing builds.")
flag.StringVar(&o.fallbackURI, "fallback-url-template",
"https://storage.googleapis.com/kubernetes-jenkins/logs/%s/latest-build.txt",
"URL template to fallback to for jobs that lack a last vended build number.",
)
flag.StringVar(&o.configPath, "config-path", "", "Path to prow config.")
flag.StringVar(&o.jobConfigPath, "job-config-path", "", "Path to prow job configs.")
flag.StringVar(&o.fallbackBucket, "fallback-bucket", "",
"Fallback to top-level bucket for jobs that lack a last vended build number. The bucket layout is expected to follow https://github.com/kubernetes/test-infra/tree/master/gubernator#gcs-bucket-layout",
)
flag.Parse()
return o
}
func (o *options) Validate() error {
if o.configPath != "" && o.fallbackBucket == "" {
return errors.New("you need to provide a bucket to fallback to when the prow config is specified")
}
if o.configPath == "" && o.fallbackBucket != "" {
return errors.New("you need to provide the prow config when a fallback bucket is specified")
}
return nil
}
type store struct {
Number map[string]int // job name -> last vended build number
mutex sync.Mutex
storagePath string
fallbackFunc func(string) int
}
func newStore(storagePath string) (*store, error) {
s := &store{
Number: make(map[string]int),
storagePath: storagePath,
}
buf, err := ioutil.ReadFile(storagePath)
if err == nil {
err = json.Unmarshal(buf, s)
if err != nil {
return nil, err
}
} else if !os.IsNotExist(err) {
return nil, err
}
return s, nil
}
func (s *store) save() error {
buf, err := json.Marshal(s)
if err != nil {
return err
}
err = ioutil.WriteFile(s.storagePath+".tmp", buf, 0644)
if err != nil {
return err
}
return os.Rename(s.storagePath+".tmp", s.storagePath)
}
func (s *store) vend(jobName string) int {
s.mutex.Lock()
defer s.mutex.Unlock()
n, ok := s.Number[jobName]
if !ok && s.fallbackFunc != nil {
n = s.fallbackFunc(jobName)
}
n++
s.Number[jobName] = n
err := s.save()
if err != nil {
logrus.Error(err)
}
return n
}
func (s *store) peek(jobName string) int {
s.mutex.Lock()
defer s.mutex.Unlock()
return s.Number[jobName]
}
func (s *store) set(jobName string, n int) {
s.mutex.Lock()
defer s.mutex.Unlock()
s.Number[jobName] = n
err := s.save()
if err != nil {
logrus.Error(err)
}
}
func (s *store) handle(w http.ResponseWriter, r *http.Request) {
jobName := r.URL.Path[len("/vend/"):]
switch r.Method {
case "GET":
n := s.vend(jobName)
logrus.Infof("Vending %s number %d to %s.", jobName, n, r.RemoteAddr)
fmt.Fprintf(w, "%d", n)
case "HEAD":
n := s.peek(jobName)
logrus.Infof("Peeking %s number %d to %s.", jobName, n, r.RemoteAddr)
fmt.Fprintf(w, "%d", n)
case "POST":
body, err := ioutil.ReadAll(r.Body)
if err != nil {
logrus.WithError(err).Error("Unable to read body.")
return
}
n, err := strconv.Atoi(string(body))
if err != nil {
logrus.WithError(err).Error("Unable to parse number.")
return
}
logrus.Infof("Setting %s to %d from %s.", jobName, n, r.RemoteAddr)
s.set(jobName, n)
}
}
type fallbackHandler struct {
template string
// in case a config agent is provided, tot will
// determine the GCS path that it needs to use
// based on the configured jobs in prow and
// bucket.
configAgent *config.Agent
bucket string
}
func (f fallbackHandler) get(jobName string) int {
url := f.getURL(jobName)
var body []byte
for i := 0; i < 10; i++ {
resp, err := http.Get(url)
if err == nil {
defer resp.Body.Close()
if resp.StatusCode == http.StatusOK {
body, err = ioutil.ReadAll(resp.Body)
if err == nil {
break
} else {
logrus.WithError(err).Error("Failed to read response body.")
}
} else if resp.StatusCode == http.StatusNotFound {
break
}
} else {
logrus.WithError(err).Errorf("Failed to GET %s.", url)
}
time.Sleep(2 * time.Second)
}
n, err := strconv.Atoi(strings.TrimSpace(string(body)))
if err != nil {
return 0
}
return n
}
func (f fallbackHandler) getURL(jobName string) string {
if f.configAgent == nil {
return fmt.Sprintf(f.template, jobName)
}
var spec *downwardapi.JobSpec
cfg := f.configAgent.Config()
for _, pre := range cfg.AllStaticPresubmits(nil) {
if jobName == pre.Name {
spec = pjutil.PresubmitToJobSpec(pre)
break
}
}
if spec == nil {
for _, post := range cfg.AllPostsubmits(nil) {
if jobName == post.Name {
spec = pjutil.PostsubmitToJobSpec(post)
break
}
}
}
if spec == nil {
for _, per := range cfg.AllPeriodics() {
if jobName == per.Name {
spec = pjutil.PeriodicToJobSpec(per)
break
}
}
}
// If spec is still nil, we know nothing about the requested job.
if spec == nil {
logrus.Errorf("requested job is unknown to prow: %s", jobName)
return ""
}
paths := gcs.LatestBuildForSpec(spec, nil)
if len(paths) != 1 {
logrus.Errorf("expected a single GCS path, got %v", paths)
return ""
}
return fmt.Sprintf("%s/%s", strings.TrimSuffix(f.bucket, "/"), paths[0])
}
func main() {
logrusutil.ComponentInit("tot")
o := gatherOptions()
if err := o.Validate(); err != nil {
logrus.Fatalf("Invalid options: %v", err)
}
defer interrupts.WaitForGracefulShutdown()
pjutil.ServePProf()
health := pjutil.NewHealth()
s, err := newStore(o.storagePath)
if err != nil {
logrus.WithError(err).Fatal("newStore failed")
}
if o.useFallback {
var configAgent *config.Agent
if o.configPath != "" {
configAgent = &config.Agent{}
if err := configAgent.Start(o.configPath, o.jobConfigPath); err != nil {
logrus.WithError(err).Fatal("Error starting config agent.")
}
}
s.fallbackFunc = fallbackHandler{
template: o.fallbackURI,
configAgent: configAgent,
bucket: o.fallbackBucket,
}.get
}
mux := http.NewServeMux()
mux.HandleFunc("/vend/", s.handle)
server := &http.Server{Addr: ":" + strconv.Itoa(o.port), Handler: mux}
health.ServeReady()
interrupts.ListenAndServe(server, 5*time.Second)
}