forked from golang/build
/
buildstats.go
303 lines (284 loc) · 7.4 KB
/
buildstats.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
// Copyright 2017 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package buildstats contains code to sync the coordinator's build
// logs from Datastore to BigQuery.
package buildstats // import "golang.org/x/build/internal/buildstats"
import (
"context"
"fmt"
"log"
"reflect"
"time"
"cloud.google.com/go/bigquery"
"cloud.google.com/go/datastore"
"golang.org/x/build/buildenv"
"golang.org/x/build/types"
"google.golang.org/api/googleapi"
"google.golang.org/api/iterator"
)
// Verbose controls logging verbosity.
var Verbose = false
// SyncBuilds syncs the datastore "Build" entities to the BigQuery "Builds" table.
// This stores information on each build as a whole, without details.
func SyncBuilds(ctx context.Context, env *buildenv.Environment) error {
bq, err := bigquery.NewClient(ctx, env.ProjectName)
if err != nil {
return err
}
buildsTable := bq.Dataset("builds").Table("Builds")
meta, err := buildsTable.Metadata(ctx)
if ae, ok := err.(*googleapi.Error); ok && ae.Code == 404 {
if Verbose {
log.Printf("Creating table Builds...")
}
err = buildsTable.Create(ctx)
if err == nil {
meta, err = buildsTable.Metadata(ctx)
}
}
if err != nil {
return fmt.Errorf("getting Builds table metadata: %v", err)
}
if Verbose {
log.Printf("buildstats: Builds metadata: %#v", meta)
}
if len(meta.Schema) == 0 {
if Verbose {
log.Printf("buildstats: builds table has empty schema")
}
schema, err := bigquery.InferSchema(types.BuildRecord{})
if err != nil {
return fmt.Errorf("InferSchema: %v", err)
}
blindWrite := ""
meta, err = buildsTable.Update(ctx, bigquery.TableMetadataToUpdate{Schema: schema}, blindWrite)
if err != nil {
return fmt.Errorf("table.Update schema: %v", err)
}
}
if Verbose {
for i, fs := range meta.Schema {
log.Printf(" schema[%v]: %+v", i, fs)
for j, fs := range fs.Schema {
log.Printf(" .. schema[%v]: %+v", j, fs)
}
}
}
q := bq.Query("SELECT MAX(EndTime) FROM [" + env.ProjectName + ":builds.Builds]")
it, err := q.Read(ctx)
if err != nil {
return fmt.Errorf("Read: %v", err)
}
var values []bigquery.Value
err = it.Next(&values)
if err == iterator.Done {
return fmt.Errorf("No result.")
}
if err != nil {
return fmt.Errorf("Next: %v", err)
}
var since time.Time
switch t := values[0].(type) {
case nil:
// NULL. No rows.
if Verbose {
log.Printf("buildstats: syncing Builds from the beginning")
}
case time.Time:
since = values[0].(time.Time)
default:
return fmt.Errorf("MAX(EndType) = %T: want nil or time.Time", t)
}
if Verbose {
log.Printf("Max is %v (%v)", since, since.Location())
}
ds, err := datastore.NewClient(ctx, env.ProjectName)
if err != nil {
return fmt.Errorf("datastore.NewClient: %v", err)
}
up := buildsTable.Uploader()
if Verbose {
log.Printf("buildstats: Builds max time: %v", since)
}
dsq := datastore.NewQuery("Build")
if !since.IsZero() {
dsq = dsq.Filter("EndTime >", since).Filter("EndTime <", since.Add(24*90*time.Hour))
} else {
// Ignore rows without endtime.
dsq = dsq.Filter("EndTime >", time.Unix(1, 0))
}
dsq = dsq.Order("EndTime")
dsit := ds.Run(ctx, dsq)
var maxPut time.Time
for {
n := 0
var rows []*bigquery.ValuesSaver
for {
var s types.BuildRecord
key, err := dsit.Next(&s)
if err == iterator.Done {
break
}
n++
if err != nil {
return fmt.Errorf("error querying max EndTime: %v", err)
}
if s.EndTime.IsZero() {
return fmt.Errorf("got zero EndTime")
}
var row []bigquery.Value
var putSchema bigquery.Schema
rv := reflect.ValueOf(s)
for _, fs := range meta.Schema {
if fs.Name[0] == '_' {
continue
}
putSchema = append(putSchema, fs)
row = append(row, rv.FieldByName(fs.Name).Interface())
maxPut = s.EndTime
}
rows = append(rows, &bigquery.ValuesSaver{
Schema: putSchema,
InsertID: key.Encode(),
Row: row,
})
if len(rows) == 1000 {
break
}
}
if n == 0 {
return nil
}
err = up.Put(ctx, rows)
log.Printf("buildstats: Build sync put %d rows, up to %v. error = %v", len(rows), maxPut, err)
return err
}
}
// SyncSpans syncs the datastore "Span" entities to the BigQuery "Spans" table.
// These contain the fine-grained timing details of how a build ran.
func SyncSpans(ctx context.Context, env *buildenv.Environment) error {
bq, err := bigquery.NewClient(ctx, env.ProjectName)
if err != nil {
log.Fatal(err)
}
table := bq.Dataset("builds").Table("Spans")
meta, err := table.Metadata(ctx)
if ae, ok := err.(*googleapi.Error); ok && ae.Code == 404 {
log.Printf("Creating table Spans...")
err = table.Create(ctx)
if err == nil {
meta, err = table.Metadata(ctx)
}
}
if err != nil {
return fmt.Errorf("Metadata: %#v", err)
}
if Verbose {
log.Printf("buildstats: Spans metadata: %#v", meta)
}
schema := meta.Schema
if len(schema) == 0 {
if Verbose {
log.Printf("EMPTY SCHEMA")
}
schema, err = bigquery.InferSchema(types.SpanRecord{})
if err != nil {
return fmt.Errorf("InferSchema: %v", err)
}
blindWrite := ""
meta, err := table.Update(ctx, bigquery.TableMetadataToUpdate{Schema: schema}, blindWrite)
if err != nil {
return fmt.Errorf("table.Update schema: %v", err)
}
schema = meta.Schema
}
if Verbose {
for i, fs := range schema {
log.Printf(" schema[%v]: %+v", i, fs)
for j, fs := range fs.Schema {
log.Printf(" .. schema[%v]: %+v", j, fs)
}
}
}
q := bq.Query("SELECT MAX(EndTime) FROM [" + env.ProjectName + ":builds.Spans]")
it, err := q.Read(ctx)
if err != nil {
return fmt.Errorf("Read: %v", err)
}
var since time.Time
var values []bigquery.Value
if err := it.Next(&values); err != nil {
if err == iterator.Done {
return fmt.Errorf("Expected at least one row fro MAX(EndTime) query; got none.")
}
return fmt.Errorf("Next: %v", err)
}
switch t := values[0].(type) {
case nil:
// NULL. No rows.
log.Printf("starting from the beginning...")
case time.Time:
since = values[0].(time.Time)
default:
return fmt.Errorf("MAX(EndType) = %T: want nil or time.Time", t)
}
if since.IsZero() {
since = time.Unix(1, 0) // arbitrary
}
ds, err := datastore.NewClient(ctx, env.ProjectName)
if err != nil {
return fmt.Errorf("datastore.NewClient: %v", err)
}
up := table.Uploader()
if Verbose {
log.Printf("buildstats: Span max time: %v", since)
}
dsit := ds.Run(ctx, datastore.NewQuery("Span").Filter("EndTime >", since).Order("EndTime"))
var maxPut time.Time
for {
n := 0
var rows []*bigquery.ValuesSaver
for {
var s types.SpanRecord
key, err := dsit.Next(&s)
if err == iterator.Done {
break
}
n++
if err != nil {
log.Fatal(err)
}
if s.EndTime.IsZero() {
return fmt.Errorf("got zero endtime")
}
var row []bigquery.Value
var putSchema bigquery.Schema
rv := reflect.ValueOf(s)
for _, fs := range meta.Schema {
if fs.Name[0] == '_' {
continue
}
putSchema = append(putSchema, fs)
row = append(row, rv.FieldByName(fs.Name).Interface())
maxPut = s.EndTime
}
rows = append(rows, &bigquery.ValuesSaver{
Schema: putSchema,
InsertID: key.Encode(),
Row: row,
})
if len(rows) == 1000 {
break
}
}
if n == 0 {
return nil
}
err = up.Put(ctx, rows)
log.Printf("buildstats: Spans sync put %d rows, up to %v. error = %v", len(rows), maxPut, err)
if err != nil {
return err
}
}
}