forked from kubernetes/test-infra
-
Notifications
You must be signed in to change notification settings - Fork 0
/
job_history.go
432 lines (392 loc) · 11 KB
/
job_history.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
/*
Copyright 2018 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 (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/url"
"path"
"regexp"
"sort"
"strconv"
"strings"
"time"
"cloud.google.com/go/storage"
"github.com/sirupsen/logrus"
"google.golang.org/api/iterator"
"k8s.io/test-infra/prow/config"
"k8s.io/test-infra/prow/pod-utils/gcs"
)
const (
resultsPerPage = 20
idParam = "buildId"
latestBuildFile = "latest-build.txt"
// ** Job history assumes the GCS layout specified here:
// https://github.com/kubernetes/test-infra/tree/master/gubernator#gcs-bucket-layout
logsPrefix = gcs.NonPRLogs
spyglassPrefix = "/view/gcs"
emptyID = int64(-1) // indicates no build id was specified
)
var (
prefixRe = regexp.MustCompile("gs://.*?/")
linkRe = regexp.MustCompile("/([0-9]+)\\.txt$")
)
type buildData struct {
index int
jobName string
prefix string
SpyglassLink string
ID string
Started time.Time
Duration time.Duration
Result string
commitHash string
}
// storageBucket is an abstraction for unit testing
type storageBucket interface {
getName() string
listSubDirs(prefix string) ([]string, error)
listAll(prefix string) ([]string, error)
readObject(key string) ([]byte, error)
}
// gcsBucket is our real implementation of storageBucket
type gcsBucket struct {
name string
*storage.BucketHandle
}
type jobHistoryTemplate struct {
OlderLink string
NewerLink string
LatestLink string
Name string
ResultsShown int
ResultsTotal int
Builds []buildData
}
func (bucket gcsBucket) readObject(key string) ([]byte, error) {
obj := bucket.Object(key)
rc, err := obj.NewReader(context.Background())
if err != nil {
return []byte{}, fmt.Errorf("failed to get reader for GCS object: %v", err)
}
return ioutil.ReadAll(rc)
}
func (bucket gcsBucket) getName() string {
return bucket.name
}
func readLatestBuild(bucket storageBucket, root string) (int64, error) {
key := path.Join(root, latestBuildFile)
data, err := bucket.readObject(key)
if err != nil {
return -1, fmt.Errorf("failed to read %s: %v", key, err)
}
n, err := strconv.ParseInt(strings.TrimSpace(string(data)), 10, 64)
if err != nil {
return -1, fmt.Errorf("failed to parse %s: %v", key, err)
}
return n, nil
}
// resolve sym links into the actual log directory for a particular test run
func (bucket gcsBucket) resolveSymLink(symLink string) (string, error) {
data, err := bucket.readObject(symLink)
if err != nil {
return "", fmt.Errorf("failed to read %s: %v", symLink, err)
}
// strip gs://<bucket-name> from global address `u`
u := strings.TrimSpace(string(data))
return prefixRe.ReplaceAllString(u, ""), nil
}
func (bucket gcsBucket) spyglassLink(root, id string) (string, error) {
p, err := bucket.getPath(root, id, "")
if err != nil {
return "", fmt.Errorf("failed to get path: %v", err)
}
return path.Join(spyglassPrefix, bucket.getName(), p), nil
}
func (bucket gcsBucket) getPath(root, id, fname string) (string, error) {
if strings.HasPrefix(root, logsPrefix) {
return path.Join(root, id, fname), nil
}
symLink := path.Join(root, id+".txt")
dir, err := bucket.resolveSymLink(symLink)
if err != nil {
return "", fmt.Errorf("failed to resolve sym link: %v", err)
}
return path.Join(dir, fname), nil
}
// reads specified JSON file in to `data`
func readJSON(bucket storageBucket, key string, data interface{}) error {
rawData, err := bucket.readObject(key)
if err != nil {
return fmt.Errorf("failed to read %s: %v", key, err)
}
err = json.Unmarshal(rawData, &data)
if err != nil {
return fmt.Errorf("failed to parse %s: %v", key, err)
}
return nil
}
// Lists the GCS "directory paths" immediately under prefix.
func (bucket gcsBucket) listSubDirs(prefix string) ([]string, error) {
if !strings.HasSuffix(prefix, "/") {
prefix += "/"
}
dirs := []string{}
it := bucket.Objects(context.Background(), &storage.Query{
Prefix: prefix,
Delimiter: "/",
})
for {
attrs, err := it.Next()
if err == iterator.Done {
break
}
if err != nil {
return dirs, err
}
if attrs.Prefix != "" {
dirs = append(dirs, attrs.Prefix)
}
}
return dirs, nil
}
// Lists all GCS keys with given prefix.
func (bucket gcsBucket) listAll(prefix string) ([]string, error) {
keys := []string{}
it := bucket.Objects(context.Background(), &storage.Query{
Prefix: prefix,
})
for {
attrs, err := it.Next()
if err == iterator.Done {
break
}
if err != nil {
return keys, err
}
keys = append(keys, attrs.Name)
}
return keys, nil
}
// Gets all build ids for a job.
func (bucket gcsBucket) listBuildIDs(root string) ([]int64, error) {
ids := []int64{}
if strings.HasPrefix(root, logsPrefix) {
dirs, err := bucket.listSubDirs(root)
if err != nil {
return ids, fmt.Errorf("failed to list GCS directories: %v", err)
}
for _, dir := range dirs {
i, err := strconv.ParseInt(path.Base(dir), 10, 64)
if err == nil {
ids = append(ids, i)
} else {
logrus.Warningf("unrecognized directory name (expected int64): %s", dir)
}
}
} else {
keys, err := bucket.listAll(root)
if err != nil {
return ids, fmt.Errorf("failed to list GCS keys: %v", err)
}
for _, key := range keys {
matches := linkRe.FindStringSubmatch(key)
if len(matches) == 2 {
i, err := strconv.ParseInt(matches[1], 10, 64)
if err == nil {
ids = append(ids, i)
} else {
logrus.Warningf("unrecognized file name (expected <int64>.txt): %s", key)
}
}
}
}
return ids, nil
}
func parseJobHistURL(url *url.URL) (bucketName, root string, buildID int64, err error) {
buildID = emptyID
p := strings.TrimPrefix(url.Path, "/job-history/")
s := strings.SplitN(p, "/", 2)
if len(s) < 2 {
err = fmt.Errorf("invalid path (expected /job-history/<gcs-path>): %v", url.Path)
return
}
bucketName = s[0]
root = s[1] // `root` is the root GCS "directory" prefix for this job's results
if bucketName == "" {
err = fmt.Errorf("missing GCS bucket name: %v", url.Path)
return
}
if root == "" {
err = fmt.Errorf("invalid GCS path for job: %v", url.Path)
return
}
if idVals := url.Query()[idParam]; len(idVals) >= 1 && idVals[0] != "" {
buildID, err = strconv.ParseInt(idVals[0], 10, 64)
if err != nil {
err = fmt.Errorf("invalid value for %s: %v", idParam, err)
return
}
if buildID < 0 {
err = fmt.Errorf("invalid value %s = %d", idParam, buildID)
return
}
}
return
}
func linkID(url *url.URL, id int64) string {
u := *url
q := u.Query()
var val string
if id != emptyID {
val = strconv.FormatInt(id, 10)
}
q.Set(idParam, val)
u.RawQuery = q.Encode()
return u.String()
}
func getBuildData(bucket storageBucket, dir string) (buildData, error) {
b := buildData{
Result: "Unknown",
commitHash: "Unknown",
}
started := gcs.Started{}
err := readJSON(bucket, path.Join(dir, "started.json"), &started)
if err != nil {
return b, fmt.Errorf("failed to read started.json: %v", err)
}
b.Started = time.Unix(started.Timestamp, 0)
if commitHash, err := getPullCommitHash(started.Pull); err == nil {
b.commitHash = commitHash
}
finished := gcs.Finished{}
err = readJSON(bucket, path.Join(dir, "finished.json"), &finished)
if err != nil {
b.Result = "Pending"
logrus.Debugf("failed to read finished.json (job might be unfinished): %v", err)
}
if finished.Revision != "" {
b.commitHash = finished.Revision
}
if finished.Timestamp != nil {
b.Duration = time.Unix(*finished.Timestamp, 0).Sub(b.Started)
} else {
b.Duration = time.Now().Sub(b.Started).Round(time.Second)
}
if finished.Result != "" {
b.Result = finished.Result
}
return b, nil
}
// assumes a to be sorted in descending order
// returns a subslice of a along with its indices (inclusive)
func cropResults(a []int64, max int64) ([]int64, int, int) {
res := []int64{}
firstIndex := -1
lastIndex := 0
for i, v := range a {
if v <= max {
res = append(res, v)
if firstIndex == -1 {
firstIndex = i
}
lastIndex = i
if len(res) >= resultsPerPage {
break
}
}
}
return res, firstIndex, lastIndex
}
// golang <3
type int64slice []int64
func (a int64slice) Len() int { return len(a) }
func (a int64slice) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a int64slice) Less(i, j int) bool { return a[i] < a[j] }
// Gets job history from the GCS bucket specified in config.
func getJobHistory(url *url.URL, config *config.Config, gcsClient *storage.Client) (jobHistoryTemplate, error) {
start := time.Now()
tmpl := jobHistoryTemplate{}
bucketName, root, top, err := parseJobHistURL(url)
if err != nil {
return tmpl, fmt.Errorf("invalid url %s: %v", url.String(), err)
}
tmpl.Name = root
bucket := gcsBucket{bucketName, gcsClient.Bucket(bucketName)}
latest, err := readLatestBuild(bucket, root)
if err != nil {
return tmpl, fmt.Errorf("failed to locate build data: %v", err)
}
if top == emptyID || top > latest {
top = latest
}
if top != latest {
tmpl.LatestLink = linkID(url, emptyID)
}
buildIDs, err := bucket.listBuildIDs(root)
if err != nil {
return tmpl, fmt.Errorf("failed to get build ids: %v", err)
}
sort.Sort(sort.Reverse(int64slice(buildIDs)))
// determine which results to display on this page
shownIDs, firstIndex, lastIndex := cropResults(buildIDs, top)
// get links to the neighboring pages
if firstIndex > 0 {
nextIndex := firstIndex - resultsPerPage
// here emptyID indicates the most recent build, which will not necessarily be buildIDs[0]
next := emptyID
if nextIndex >= 0 {
next = buildIDs[nextIndex]
}
tmpl.NewerLink = linkID(url, next)
}
if lastIndex < len(buildIDs)-1 {
tmpl.OlderLink = linkID(url, buildIDs[lastIndex+1])
}
tmpl.Builds = make([]buildData, len(shownIDs))
tmpl.ResultsShown = len(shownIDs)
tmpl.ResultsTotal = len(buildIDs)
// concurrently fetch data for all of the builds to be shown
bch := make(chan buildData)
for i, buildID := range shownIDs {
go func(i int, buildID int64) {
id := strconv.FormatInt(buildID, 10)
dir, err := bucket.getPath(root, id, "")
if err != nil {
logrus.Errorf("failed to get path: %v", err)
bch <- buildData{}
return
}
b, err := getBuildData(bucket, dir)
if err != nil {
logrus.Warningf("build %d information incomplete: %v", buildID, err)
}
b.index = i
b.ID = id
b.SpyglassLink, err = bucket.spyglassLink(root, id)
if err != nil {
logrus.Errorf("failed to get spyglass link: %v", err)
}
bch <- b
}(i, buildID)
}
for i := 0; i < len(shownIDs); i++ {
b := <-bch
tmpl.Builds[b.index] = b
}
elapsed := time.Now().Sub(start)
logrus.Infof("loaded %s in %v", url.Path, elapsed)
return tmpl, nil
}