-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjob_history.go
397 lines (361 loc) · 10.4 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
/*
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/deck/jobs"
)
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 = "logs"
symLinkPrefix = "pr-logs/directory"
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
SpyglassLink string
ID string
Started time.Time
Duration time.Duration
Result string
}
type jobHistoryTemplate struct {
OlderLink string
NewerLink string
LatestLink string
Name string
ResultsShown int
ResultsTotal int
Builds []buildData
}
func readObject(obj *storage.ObjectHandle) ([]byte, error) {
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 readLatestBuild(bkt *storage.BucketHandle, root string) (int64, error) {
path := path.Join(root, latestBuildFile)
data, err := readObject(bkt.Object(path))
if err != nil {
return -1, fmt.Errorf("failed to read %s: %v", path, err)
}
n, err := strconv.ParseInt(string(data), 10, 64)
if err != nil {
return -1, fmt.Errorf("failed to parse %s: %v", path, err)
}
return n, nil
}
// resolve sym links into the actual log directory for a particular test run
func resolveSymLink(bkt *storage.BucketHandle, symLink string) (string, error) {
data, err := readObject(bkt.Object(symLink))
if err != nil {
return "", fmt.Errorf("failed to read %s: %v", symLink, err)
}
// strip gs://<bucket-name> from global address `u`
u := string(data)
return prefixRe.ReplaceAllString(u, ""), nil
}
func spyglassLink(bkt *storage.BucketHandle, root, id string) (string, error) {
bAttrs, err := bkt.Attrs(context.Background())
if err != nil {
return "", fmt.Errorf("failed to get bucket name: %v", err)
}
bktName := bAttrs.Name
p, err := getPath(bkt, root, id, "")
if err != nil {
return "", fmt.Errorf("failed to get path: %v", err)
}
return path.Join(spyglassPrefix, bktName, p), nil
}
func getPath(bkt *storage.BucketHandle, 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 := resolveSymLink(bkt, 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(bkt *storage.BucketHandle, root, id, fname string, data interface{}) error {
p, err := getPath(bkt, root, id, fname)
if err != nil {
return fmt.Errorf("failed to get path: %v", err)
}
rawData, err := readObject(bkt.Object(p))
if err != nil {
return fmt.Errorf("failed to read %s for build %s: %v", fname, id, err)
}
err = json.Unmarshal(rawData, &data)
if err != nil {
return fmt.Errorf("failed to parse %s for build %s: %v", fname, id, err)
}
return nil
}
// Lists the GCS "directory paths" immediately under prefix.
func listSubDirs(bkt *storage.BucketHandle, prefix string) ([]string, error) {
if !strings.HasSuffix(prefix, "/") {
prefix += "/"
}
dirs := []string{}
it := bkt.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 listAll(bkt *storage.BucketHandle, prefix string) ([]string, error) {
keys := []string{}
it := bkt.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 listBuildIDs(bkt *storage.BucketHandle, root string) ([]int64, error) {
ids := []int64{}
if strings.HasPrefix(root, logsPrefix) {
dirs, err := listSubDirs(bkt, 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 := listAll(bkt, 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 jobHistURL(url *url.URL) (string, string, int64, error) {
p := strings.TrimPrefix(url.Path, "/job-history/")
s := strings.SplitN(p, "/", 2)
if len(s) < 2 {
return "", "", emptyID, fmt.Errorf("invalid path (expected /job-history/<gcs-path>): %v", url.Path)
}
bucketName := s[0]
root := s[1]
if bucketName == "" {
return bucketName, root, emptyID, fmt.Errorf("missing GCS bucket name: %v", url.Path)
}
if root == "" {
return bucketName, root, emptyID, fmt.Errorf("invalid GCS path for job: %v", url.Path)
}
buildID := emptyID
if idVals := url.Query()[idParam]; len(idVals) >= 1 && idVals[0] != "" {
var err error
buildID, err = strconv.ParseInt(idVals[0], 10, 64)
if err != nil {
return bucketName, root, buildID, fmt.Errorf("invalid value for %s: %v", idParam, err)
}
if buildID < 0 {
return bucketName, root, buildID, fmt.Errorf("invalid value %s = %d", idParam, buildID)
}
}
return bucketName, root, buildID, nil
}
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(bkt *storage.BucketHandle, root string, buildID int64, index int) (buildData, error) {
b := buildData{
index: index,
ID: strconv.FormatInt(buildID, 10),
Result: "Unknown",
}
link, err := spyglassLink(bkt, root, b.ID)
if err != nil {
return b, fmt.Errorf("failed to get spyglass link: %v", err)
}
b.SpyglassLink = link
started := jobs.Started{}
err = readJSON(bkt, root, b.ID, "started.json", &started)
if err != nil {
return b, fmt.Errorf("failed to get job metadata: %v", err)
}
b.Result = "Unfinished"
b.Started = time.Unix(started.Timestamp, 0)
finished := jobs.Finished{}
err = readJSON(bkt, root, b.ID, "finished.json", &finished)
if err != nil {
logrus.Warningf("failed to read finished.json (job might be unfinished): %v", err)
}
if finished.Timestamp != 0 {
b.Duration = time.Unix(finished.Timestamp, 0).Sub(b.Started)
}
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 := jobHistURL(url)
if err != nil {
return tmpl, fmt.Errorf("invalid url %s: %v", url.String(), err)
}
tmpl.Name = root
bkt := gcsClient.Bucket(bucketName)
latest, err := readLatestBuild(bkt, 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 := listBuildIDs(bkt, root)
if err != nil {
return tmpl, fmt.Errorf("failed to get build ids: %v", err)
}
sort.Sort(sort.Reverse(int64slice(buildIDs)))
shownIDs, firstIndex, lastIndex := cropResults(buildIDs, top)
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)
bch := make(chan buildData)
for i, buildID := range shownIDs {
go func(i int, buildID int64) {
bd, err := getBuildData(bkt, root, buildID, i)
if err != nil {
logrus.Warningf("build %d information incomplete: %v", buildID, err)
}
bch <- bd
}(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
}