forked from golang/build
-
Notifications
You must be signed in to change notification settings - Fork 0
/
coordinator.go
1283 lines (1152 loc) · 34.2 KB
/
coordinator.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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2014 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.
// The coordinator runs on GCE and coordinates builds in Docker containers.
package main // import "golang.org/x/build/cmd/coordinator"
import (
"archive/tar"
"bytes"
"compress/gzip"
"crypto/sha1"
"crypto/tls"
"encoding/json"
"errors"
"flag"
"fmt"
"html"
"io"
"io/ioutil"
"log"
"net"
"net/http"
"os"
"os/exec"
"path"
"runtime"
"sort"
"strings"
"sync"
"time"
"camlistore.org/pkg/syncutil"
"golang.org/x/build/buildlet"
"golang.org/x/build/dashboard"
"golang.org/x/build/gerrit"
"golang.org/x/build/types"
"google.golang.org/cloud/storage"
)
func init() {
// Disabled until we have test sharding. This takes 85+ minutes.
// Test sharding is https://github.com/golang/go/issues/10029
delete(dashboard.Builders, "linux-arm-qemu")
}
var (
masterKeyFile = flag.String("masterkey", "", "Path to builder master key. Else fetched using GCE project attribute 'builder-master-key'.")
// TODO(bradfitz): remove this list and just query it from the compute API:
// http://godoc.org/google.golang.org/api/compute/v1#RegionsService.Get
// and Region.Zones: http://godoc.org/google.golang.org/api/compute/v1#Region
cleanZones = flag.String("zones", "us-central1-a,us-central1-b,us-central1-f", "Comma-separated list of zones to periodically clean of stale build VMs (ones that failed to shut themselves down)")
buildLogBucket = flag.String("logbucket", "go-build-log", "GCS bucket to put trybot build failures in")
mode = flag.String("mode", "", "valid modes are 'dev', 'prod', or '' for auto-detect")
)
// LOCK ORDER:
// statusMu, buildStatus.mu, trySet.mu
// TODO(bradfitz,adg): rewrite the coordinator
var (
startTime = time.Now()
statusMu sync.Mutex // guards the following four structures; see LOCK ORDER comment above
status = map[builderRev]*buildStatus{}
statusDone []*buildStatus // finished recently, capped to maxStatusDone
tries = map[tryKey]*trySet{} // trybot builds
tryList []tryKey
)
// tryBuilders must be VMs. The Docker container builds are going away.
var tryBuilders []dashboard.BuildConfig
func init() {
tryList := []string{
"linux-386",
"linux-amd64",
"linux-amd64-race",
"freebsd-386-gce101",
"freebsd-amd64-gce101",
"windows-386-gce",
"windows-amd64-gce",
"openbsd-386-gce56",
"openbsd-amd64-gce56",
"plan9-386-gcepartial",
"nacl-386",
"nacl-amd64p32",
}
for _, bname := range tryList {
conf, ok := dashboard.Builders[bname]
if ok {
tryBuilders = append(tryBuilders, conf)
} else {
log.Printf("ignoring invalid try builder config %q", bname)
}
}
}
const (
maxStatusDone = 30
// vmDeleteTimeout is how long before we delete a VM.
// In practice this need only be as long as the slowest
// builder (plan9 currently), because on startup this program
// already deletes all buildlets it doesn't know about
// (i.e. ones from a previous instance of the coordinator).
vmDeleteTimeout = 45 * time.Minute
)
func readGCSFile(name string) ([]byte, error) {
if *mode == "dev" {
b, ok := testFiles[name]
if !ok {
return nil, &os.PathError{
Op: "open",
Path: name,
Err: os.ErrNotExist,
}
}
return []byte(b), nil
}
r, err := storage.NewReader(serviceCtx, "go-builder-data", name)
if err != nil {
return nil, err
}
defer r.Close()
return ioutil.ReadAll(r)
}
// Fake keys signed by a fake CA.
var testFiles = map[string]string{
"farmer-cert.pem": `-----BEGIN CERTIFICATE-----
MIICljCCAX4CCQCoS+/smvkG2TANBgkqhkiG9w0BAQUFADANMQswCQYDVQQDEwJn
bzAeFw0xNTA0MDYwMzE3NDJaFw0xNzA0MDUwMzE3NDJaMA0xCzAJBgNVBAMTAmdv
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA1NMaVxX8RfCMtQB18azV
hL6/U7C8W2G+8WXYeFuOpgP2SHnMbsUeTiUYWS1xqAxUh3Vl/TT1HIASRDL7kBis
yj+drspafnCr4Yp9oJx1xlIhVXGD/SyHk5oewkjkNEmrFtUT07mT2lmZqD3XJ+6V
aQslRxhPEkLGsXIA/hCucPIplI9jgLY8TmOBhQ7RzXAnk/ayAzDkCgkWB4k/zaFy
LiHjEkE7O7PIjjY51btCLep9QSts98zojY5oYNj2RdQOZa56MHAlh9hbdpm+P1vp
2QBpsDbVpH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ode == "dev" {
addr = ":8119"
}
ln, err := net.Listen("tcp", addr)
if err != nil {
log.Fatalf("net.Listen(%s): %v", addr, err)
}
serveTLS(ln)
}
func serveTLS(ln net.Listener) {
certPEM, err := readGCSFile("farmer-cert.pem")
if err != nil {
log.Printf("cannot load TLS cert, skipping https: %v", err)
return
}
keyPEM, err := readGCSFile("farmer-key.pem")
if err != nil {
log.Printf("cannot load TLS key, skipping https: %v", err)
return
}
cert, err := tls.X509KeyPair(certPEM, keyPEM)
if err != nil {
log.Printf("bad TLS cert: %v", err)
return
}
server := &http.Server{Addr: ln.Addr().String()}
config := &tls.Config{
NextProtos: []string{"http/1.1"},
Certificates: []tls.Certificate{cert},
}
tlsLn := tls.NewListener(tcpKeepAliveListener{ln.(*net.TCPListener)}, config)
log.Printf("Coordinator serving on: %v", tlsLn.Addr())
if err := server.Serve(tlsLn); err != nil {
log.Fatalf("serve https: %v", err)
}
}
type tcpKeepAliveListener struct {
*net.TCPListener
}
func (ln tcpKeepAliveListener) Accept() (c net.Conn, err error) {
tc, err := ln.AcceptTCP()
if err != nil {
return
}
tc.SetKeepAlive(true)
tc.SetKeepAlivePeriod(3 * time.Minute)
return tc, nil
}
func main() {
flag.Parse()
err := initGCE()
if err != nil {
if *mode == "" {
*mode = "dev"
}
log.Printf("VM support disabled due to error initializing GCE: %v", err)
} else {
if *mode == "" {
*mode = "prod"
}
}
switch *mode {
case "dev", "prod":
log.Printf("Running in %s mode", *mode)
default:
log.Fatalf("Unknown mode: %q", *mode)
}
http.HandleFunc("/", handleStatus)
http.HandleFunc("/try", handleTryStatus)
http.HandleFunc("/logs", handleLogs)
http.HandleFunc("/debug/goroutines", handleDebugGoroutines)
http.HandleFunc("/reverse", handleReverse)
go func() {
if *mode == "dev" {
return
}
err := http.ListenAndServe(":80", nil)
if err != nil {
log.Fatalf("http.ListenAndServe:80: %v", err)
}
}()
go listenAndServeTLS()
if *mode == "dev" {
// TODO(crawshaw): do more in test mode
select {}
}
go gcePool.cleanUpOldVMs()
// Start the Docker processes on this host polling Gerrit and
// pinging build.golang.org when new commits are available.
startWatchers() // in watcher.go
workc := make(chan builderRev)
go findWorkLoop(workc)
go findTryWorkLoop()
// TODO(cmang): gccgo will need its own findWorkLoop
ticker := time.NewTicker(1 * time.Minute)
for {
select {
case work := <-workc:
log.Printf("workc received %+v; len(status) = %v, cur = %p", work, len(status), status[work])
if !mayBuildRev(work) {
continue
}
st, err := newBuild(work)
if err != nil {
log.Printf("Bad build work params %v: %v", work, err)
} else {
st.start()
}
case <-ticker.C:
if numCurrentBuilds() == 0 && time.Now().After(startTime.Add(10*time.Minute)) {
// TODO: halt the whole machine to kill the VM or something
}
}
}
}
func numCurrentBuilds() int {
statusMu.Lock()
defer statusMu.Unlock()
return len(status)
}
func isBuilding(work builderRev) bool {
statusMu.Lock()
defer statusMu.Unlock()
_, building := status[work]
return building
}
// mayBuildRev reports whether the build type & revision should be started.
// It returns true if it's not already building, and there is capacity.
func mayBuildRev(work builderRev) bool {
statusMu.Lock()
_, building := status[work]
statusMu.Unlock()
return !building
}
func setStatus(work builderRev, st *buildStatus) {
statusMu.Lock()
defer statusMu.Unlock()
// TODO: panic if status[work] already exists. audit all callers.
// For instance, what if a trybot is running, and then the CL is merged
// and the findWork goroutine picks it up and it has the same commit,
// because it didn't need to be rebased in Gerrit's cherrypick?
// Could we then have two running with the same key?
status[work] = st
}
func markDone(work builderRev) {
statusMu.Lock()
defer statusMu.Unlock()
st, ok := status[work]
if !ok {
return
}
delete(status, work)
if len(statusDone) == maxStatusDone {
copy(statusDone, statusDone[1:])
statusDone = statusDone[:len(statusDone)-1]
}
statusDone = append(statusDone, st)
}
// statusPtrStr disambiguates which status to return if there are
// multiple in the history (e.g. recent failures where the build
// didn't finish for reasons outside of all.bash failing)
func getStatus(work builderRev, statusPtrStr string) *buildStatus {
statusMu.Lock()
defer statusMu.Unlock()
match := func(st *buildStatus) bool {
return statusPtrStr == "" || fmt.Sprintf("%p", st) == statusPtrStr
}
if st, ok := status[work]; ok && match(st) {
return st
}
for _, st := range statusDone {
if st.builderRev == work && match(st) {
return st
}
}
return nil
}
type byAge []*buildStatus
func (s byAge) Len() int { return len(s) }
func (s byAge) Less(i, j int) bool { return s[i].startTime.Before(s[j].startTime) }
func (s byAge) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func handleStatus(w http.ResponseWriter, r *http.Request) {
var active []*buildStatus
var recent []*buildStatus
statusMu.Lock()
for _, st := range status {
active = append(active, st)
}
recent = append(recent, statusDone...)
numTotal := len(status)
// TODO: make this prettier.
var tryBuf bytes.Buffer
for _, key := range tryList {
if ts := tries[key]; ts != nil {
state := ts.state()
fmt.Fprintf(&tryBuf, "Change-ID: %v Commit: %v\n", key.ChangeID, key.Commit)
fmt.Fprintf(&tryBuf, " Remain: %d, fails: %v\n", state.remain, state.failed)
for _, bs := range ts.builds {
fmt.Fprintf(&tryBuf, " %s: running=%v\n", bs.name, bs.isRunning())
}
}
}
statusMu.Unlock()
sort.Sort(byAge(active))
sort.Sort(sort.Reverse(byAge(recent)))
io.WriteString(w, "<html><body><h1>Go build coordinator</h1>")
fmt.Fprintf(w, "<h2>running</h2><p>%d total builds active; VM capacity: %d/%d", numTotal, len(gcePool.vmCap), cap(gcePool.vmCap))
io.WriteString(w, "<pre>")
for _, st := range active {
io.WriteString(w, st.htmlStatusLine())
}
io.WriteString(w, "</pre>")
io.WriteString(w, "<h2>trybot state</h2><pre>")
if errTryDeps != nil {
fmt.Fprintf(w, "<b>trybots disabled: </b>: %v\n", html.EscapeString(errTryDeps.Error()))
} else {
w.Write(tryBuf.Bytes())
}
io.WriteString(w, "</pre>")
io.WriteString(w, "<h2>recently completed</h2><pre>")
for _, st := range recent {
io.WriteString(w, st.htmlStatusLine())
}
io.WriteString(w, "</pre>")
fmt.Fprintf(w, "<h2>disk space</h2><pre>%s</pre></body></html>", html.EscapeString(diskFree()))
}
func handleTryStatus(w http.ResponseWriter, r *http.Request) {
ts := trySetOfCommitPrefix(r.FormValue("commit"))
if ts == nil {
http.Error(w, "TryBot result not found (already done, invalid, or not yet discovered from Gerrit). Check Gerrit for results.", http.StatusNotFound)
return
}
ts.mu.Lock()
tss := ts.trySetState.clone()
ts.mu.Unlock()
w.Header().Set("Content-Type", "text/html; charset=utf-8")
fmt.Fprintf(w, "<html><head><title>trybot status</title></head><body>[<a href='/'>overall status</a>] > %s\n", ts.ChangeID)
fmt.Fprintf(w, "<h1>trybot status</h1>")
fmt.Fprintf(w, "Change-ID: <a href='https://go-review.googlesource.com/#/q/%s'>%s</a><br>\n", ts.ChangeID, ts.ChangeID)
fmt.Fprintf(w, "Commit: <a href='https://go-review.googlesource.com/#/q/%s'>%s</a><br>\n", ts.Commit, ts.Commit)
fmt.Fprintf(w, "<p>Builds remain: %d</p>\n", tss.remain)
fmt.Fprintf(w, "<p>Builds failed: %v</p>\n", tss.failed)
fmt.Fprintf(w, "<p>Builds</p><table cellpadding=5 border=1>\n")
for _, bs := range tss.builds {
status := "<i>(running)</i>"
bs.mu.Lock()
if !bs.done.IsZero() {
if bs.succeeded {
status = "pass"
} else {
status = "<b>FAIL</b>"
}
}
bs.mu.Unlock()
fmt.Fprintf(w, "<tr valign=top><td align=left>%s</td><td align=center>%s</td><td><pre>%s</pre></td></tr>\n",
bs.name,
status,
bs.htmlStatusLine())
}
fmt.Fprintf(w, "</table></body></html>")
}
func trySetOfCommitPrefix(commitPrefix string) *trySet {
if commitPrefix == "" {
return nil
}
statusMu.Lock()
defer statusMu.Unlock()
for k, ts := range tries {
if strings.HasPrefix(k.Commit, commitPrefix) {
return ts
}
}
return nil
}
func diskFree() string {
out, _ := exec.Command("df", "-h").Output()
return string(out)
}
func handleLogs(w http.ResponseWriter, r *http.Request) {
st := getStatus(builderRev{r.FormValue("name"), r.FormValue("rev")}, r.FormValue("st"))
if st == nil {
http.NotFound(w, r)
return
}
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.Header().Set("X-Content-Type-Options", "nosniff")
writeStatusHeader(w, st)
if !st.hasEvent("pre_exec") {
fmt.Fprintf(w, "\n\n(buildlet still starting; no live streaming. reload manually to see status)\n")
return
}
w.(http.Flusher).Flush()
logs := st.watchLogs()
defer st.unregisterWatcher(logs)
closed := w.(http.CloseNotifier).CloseNotify()
for {
select {
case b, ok := <-logs:
if !ok {
return
}
w.Write(b)
w.(http.Flusher).Flush()
case <-closed:
return
}
}
}
func handleDebugGoroutines(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
buf := make([]byte, 1<<20)
buf = buf[:runtime.Stack(buf, true)]
w.Write(buf)
}
func writeStatusHeader(w http.ResponseWriter, st *buildStatus) {
st.mu.Lock()
defer st.mu.Unlock()
fmt.Fprintf(w, " builder: %s\n", st.name)
fmt.Fprintf(w, " rev: %s\n", st.rev)
fmt.Fprintf(w, " buildlet: %s\n", st.bc)
fmt.Fprintf(w, " started: %v\n", st.startTime)
done := !st.done.IsZero()
if done {
fmt.Fprintf(w, " started: %v\n", st.done)
fmt.Fprintf(w, " success: %v\n", st.succeeded)
} else {
fmt.Fprintf(w, " status: still running\n")
}
if len(st.events) > 0 {
io.WriteString(w, "\nEvents:\n")
st.writeEventsLocked(w, false)
}
io.WriteString(w, "\nBuild log:\n")
}
// findWorkLoop polls http://build.golang.org/?mode=json looking for new work
// for the main dashboard. It does not support gccgo.
// TODO(bradfitz): it also currently does not support subrepos.
func findWorkLoop(work chan<- builderRev) {
ticker := time.NewTicker(15 * time.Second)
for {
if err := findWork(work); err != nil {
log.Printf("failed to find new work: %v", err)
}
<-ticker.C
}
}
func findWork(work chan<- builderRev) error {
var bs types.BuildStatus
res, err := http.Get("https://build.golang.org/?mode=json")
if err != nil {
return err
}
defer res.Body.Close()
if err := json.NewDecoder(res.Body).Decode(&bs); err != nil {
return err
}
if res.StatusCode != 200 {
return fmt.Errorf("unexpected http status %v", res.Status)
}
knownToDashboard := map[string]bool{} // keys are builder
for _, b := range bs.Builders {
knownToDashboard[b] = true
}
var goRevisions []string
for _, br := range bs.Revisions {
if br.Repo == "go" {
goRevisions = append(goRevisions, br.Revision)
} else {
// TODO(bradfitz): support these: golang.org/issue/9506
continue
}
if len(br.Results) != len(bs.Builders) {
return errors.New("bogus JSON response from dashboard: results is too long.")
}
for i, res := range br.Results {
if res != "" {
// It's either "ok" or a failure URL.
continue
}
builder := bs.Builders[i]
if _, ok := dashboard.Builders[builder]; !ok {
// Not managed by the coordinator.
continue
}
br := builderRev{bs.Builders[i], br.Revision}
if !isBuilding(br) {
work <- br
}
}
}
// And to bootstrap new builders, see if we have any builders
// that the dashboard doesn't know about.
for b := range dashboard.Builders {
if knownToDashboard[b] {
continue
}
for _, rev := range goRevisions {
br := builderRev{b, rev}
if !isBuilding(br) {
work <- br
}
}
}
return nil
}
// findTryWorkLoop is a goroutine which loops periodically and queries
// Gerrit for TryBot work.
func findTryWorkLoop() {
if errTryDeps != nil {
return
}
ticker := time.NewTicker(60 * time.Second)
for {
if err := findTryWork(); err != nil {
log.Printf("failed to find trybot work: %v", err)
}
<-ticker.C
}
}
func findTryWork() error {
cis, err := gerritClient.QueryChanges("label:Run-TryBot=1 label:TryBot-Result=0 project:go status:open", gerrit.QueryChangesOpt{
Fields: []string{"CURRENT_REVISION"},
})
if err != nil {
return err
}
if len(cis) == 0 {
return nil
}
statusMu.Lock()
defer statusMu.Unlock()
tryList = make([]tryKey, 0, len(cis))
wanted := map[tryKey]bool{}
for _, ci := range cis {
if ci.ChangeID == "" || ci.CurrentRevision == "" {
log.Printf("Warning: skipping incomplete %#v", ci)
continue
}
key := tryKey{
ChangeID: ci.ChangeID,
Commit: ci.CurrentRevision,
}
tryList = append(tryList, key)
wanted[key] = true
if _, ok := tries[key]; ok {
// already in progress
continue
}
tries[key] = newTrySet(key)
}
for k, ts := range tries {
if !wanted[k] {
delete(tries, k)
go ts.cancelBuilds()
}
}
return nil
}
type tryKey struct {
ChangeID string // I1a27695838409259d1586a0adfa9f92bccf7ceba
Commit string // ecf3dffc81dc21408fb02159af352651882a8383
}
// trySet is a the state of a set of builds of different
// configurations, all for the same (Change-ID, Commit) pair. The
// sets which are still wanted (not already submitted or canceled) are
// stored in the global 'tries' map.
type trySet struct {
// immutable
tryKey
// mu guards state.
// See LOCK ORDER comment above.
mu sync.Mutex
trySetState
}
type trySetState struct {
remain int
failed []string // build names
builds []*buildStatus
}
func (ts trySetState) clone() trySetState {
return trySetState{
remain: ts.remain,
failed: append([]string(nil), ts.failed...),
builds: append([]*buildStatus(nil), ts.builds...),
}
}
// newTrySet creates a new trySet group of builders for a given key,
// the (Change-ID, Commit) pair. It also starts goroutines for each
// build.
//
// Must hold statusMu.
func newTrySet(key tryKey) *trySet {
log.Printf("Starting new trybot set for %v", key)
ts := &trySet{
tryKey: key,
trySetState: trySetState{
remain: len(tryBuilders),
builds: make([]*buildStatus, len(tryBuilders)),
},
}
go ts.notifyStarting()
for i, bconf := range tryBuilders {
brev := builderRev{name: bconf.Name, rev: key.Commit}
bs, _ := newBuild(brev)
bs.trySet = ts
status[brev] = bs
ts.builds[i] = bs
go bs.start() // acquires statusMu itself, so in a goroutine
go ts.awaitTryBuild(i, bconf, bs)
}
return ts
}
// state returns a copy of the trySet's state.
func (ts *trySet) state() trySetState {
ts.mu.Lock()
defer ts.mu.Unlock()
return ts.trySetState.clone()
}
// notifyStarting runs in its own goroutine and posts to Gerrit that
// the trybots have started on the user's CL with a link of where to watch.
func (ts *trySet) notifyStarting() {
// Ignore error. This isn't critical.
gerritClient.SetReview(ts.ChangeID, ts.Commit, gerrit.ReviewInput{
// TODO: good hostname, SSL, and pretty handler for just this tryset
Message: "TryBots beginning. Status page: http://farmer.golang.org/try?commit=" + ts.Commit[:8],
})
}
// awaitTryBuild runs in its own goroutine and waits for a build in a
// trySet to complete.
//
// If the build fails without getting to the end, it sleeps and
// reschedules it, as long as it's still wanted.
func (ts *trySet) awaitTryBuild(idx int, bconf dashboard.BuildConfig, bs *buildStatus) {
for {
WaitCh:
for {
timeout := time.NewTimer(10 * time.Minute)
select {
case <-bs.donec:
timeout.Stop()
break WaitCh
case <-timeout.C:
if !ts.wanted() {
// Build was canceled.
return
}
}
}
if bs.hasEvent("done") {
ts.noteBuildComplete(bconf, bs)
return
}
// TODO(bradfitz): rethink this logic. we should only
// start a new build if the old one appears dead or
// hung.
// Sleep a bit and retry.
time.Sleep(30 * time.Second)
if !ts.wanted() {
return
}
brev := builderRev{name: bconf.Name, rev: ts.Commit}
bs, _ = newBuild(brev)
bs.trySet = ts
go bs.start()
ts.mu.Lock()
ts.builds[idx] = bs
ts.mu.Unlock()
}
}
// wanted reports whether this trySet is still active.
//
// If the commmit has been submitted, or change abandoned, or the
// checkbox unchecked, wanted returns false.
func (ts *trySet) wanted() bool {
statusMu.Lock()
defer statusMu.Unlock()
_, ok := tries[ts.tryKey]
return ok
}
// cancelBuilds run in its own goroutine and cancels this trySet's
// currently-active builds because they're no longer wanted.
func (ts *trySet) cancelBuilds() {
// TODO(bradfitz): implement
}
func (ts *trySet) noteBuildComplete(bconf dashboard.BuildConfig, bs *buildStatus) {
bs.mu.Lock()
succeeded := bs.succeeded
var buildLog string
if !succeeded {
buildLog = bs.output.String()
}
bs.mu.Unlock()
ts.mu.Lock()
ts.remain--
remain := ts.remain
if !succeeded {
ts.failed = append(ts.failed, bconf.Name)
}
anyFail := len(ts.failed) > 0
var failList []string
if remain == 0 {
// Copy of it before we unlock mu, even though it's gone down to 0.
failList = append([]string(nil), ts.failed...)
}
ts.mu.Unlock()
if !succeeded {
s1 := sha1.New()
io.WriteString(s1, buildLog)
objName := fmt.Sprintf("%s/%s_%x.log", bs.rev[:8], bs.name, s1.Sum(nil)[:4])
wr := storage.NewWriter(serviceCtx, *buildLogBucket, objName)
wr.ContentType = "text/plain; charset=utf-8"
wr.ACL = append(wr.ACL, storage.ACLRule{Entity: storage.AllUsers, Role: storage.RoleReader})
if _, err := io.WriteString(wr, buildLog); err != nil {
log.Printf("Failed to write to GCS: %v", err)
return
}
if err := wr.Close(); err != nil {
log.Printf("Failed to write to GCS: %v", err)
return
}
if err := gerritClient.SetReview(ts.ChangeID, ts.Commit, gerrit.ReviewInput{
Message: fmt.Sprintf(
"This change failed on %s:\n"+
"See https://storage.googleapis.com/%s/%s\n\n"+
"Consult https://build.golang.org/ to see whether it's a new failure.",
bs.name, *buildLogBucket, objName),
}); err != nil {
log.Printf("Failed to call Gerrit: %v", err)
return
}
}
if remain == 0 {
score, msg := 1, "TryBots are happy."
if anyFail {
score, msg = -1, fmt.Sprintf("%d of %d TryBots failed: %s", len(failList), len(ts.builds), strings.Join(failList, ", "))
}
if err := gerritClient.SetReview(ts.ChangeID, ts.Commit, gerrit.ReviewInput{
Message: msg,
Labels: map[string]int{
"TryBot-Result": score,
},
}); err != nil {
log.Printf("Failed to call Gerrit: %v", err)
return
}
}
}
// builderRev is a build configuration type and a revision.
type builderRev struct {
name string // e.g. "linux-amd64-race"
rev string // lowercase hex git hash
// TODO: optional subrepo name/hash
}
type eventTimeLogger interface {
logEventTime(name string)
}
type BuildletPool interface {
// GetBuildlet returns a new buildlet client.
//
// The machineType is the machine type (e.g. "linux-amd64-race").
//
// The rev is git hash. Implementations should not use it for
// anything except for log messages or VM naming.
//
// Clients must Close when done with the client.
GetBuildlet(machineType, rev string, el eventTimeLogger) (*buildlet.Client, error)
String() string // TODO(bradfitz): more status stuff
}
func poolForConf(conf dashboard.BuildConfig) (BuildletPool, error) {
if conf.VMImage != "" {
return gcePool, nil
}
return nil, fmt.Errorf("unknown buildlet pool type for builder %q", conf.Name)
}
func newBuild(rev builderRev) (*buildStatus, error) {
// Note: can't acquire statusMu in newBuild, as this is called
// from findTryWork -> newTrySet, which holds statusMu.
conf, ok := dashboard.Builders[rev.name]
if !ok {
return nil, fmt.Errorf("unknown builder type %q", rev.name)
}
return &buildStatus{
builderRev: rev,
conf: conf,
donec: make(chan struct{}),
startTime: time.Now(),
}, nil
}
// start sets the st.startTime and starts the build in a new goroutine.
// If it returns an error, st is not modified and a new goroutine has not
// been started.
// The build status's donec channel is closed on when the build is complete
// in either direction.
func (st *buildStatus) start() {
setStatus(st.builderRev, st)
go st.pingDashboard()
go func() {
err := st.build()
if err != nil {
fmt.Fprintf(st, "\n\nError: %v\n", err)
}
st.setDone(err == nil)
markDone(st.builderRev)
}()
}
func (st *buildStatus) build() (retErr error) {
pool, err := poolForConf(st.conf)
if err != nil {
return err
}
st.logEventTime("get_buildlet")
bc, err := pool.GetBuildlet(st.conf.Name, st.rev, st)
if err != nil {
return fmt.Errorf("failed to get a buildlet: %v", err)
}
defer bc.Close()
st.mu.Lock()
st.bc = bc
st.mu.Unlock()
st.logEventTime("got_buildlet")
goodRes := func(res *http.Response, err error, what string) bool {
if err != nil {
retErr = fmt.Errorf("%s: %v", what, err)
return false
}
if res.StatusCode/100 != 2 {
slurp, _ := ioutil.ReadAll(io.LimitReader(res.Body, 4<<10))
retErr = fmt.Errorf("%s: %v; body: %s", what, res.Status, slurp)
res.Body.Close()
return false
}
return true
}
// Write the VERSION file.
st.logEventTime("start_write_version_tar")
if err := bc.PutTar(versionTgz(st.rev), "go"); err != nil {
return fmt.Errorf("writing VERSION tgz: %v", err)
}