forked from perkeep/perkeep
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot.go
1237 lines (1152 loc) · 26.3 KB
/
bot.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 2012 The Camlistore 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 (
"bytes"
"flag"
"fmt"
"html/template"
"io/ioutil"
"log"
"math/rand"
"net/http"
"os"
"os/exec"
"os/signal"
"path/filepath"
"regexp"
"runtime"
"strings"
"sync"
"syscall"
"time"
)
const (
interval = 60 * time.Second // polling frequency
warmup = 60 * time.Second // duration before we test if dev-server has started properly
historySize = 30
)
var (
fast = flag.Bool("fast", false, "run dummy steps instead of the actual tasks, for debugging")
gotipdir = flag.String("gotip", "./go", "path to the Go tip tree")
help = flag.Bool("h", false, "show this help")
host = flag.String("host", "0.0.0.0:8080", "listening hostname and port")
nocleanup = flag.Bool("nocleanup", false, "do not clean up the tmp gopath when failing")
verbose = flag.Bool("verbose", false, "print what's going on")
)
var (
testFile = []string{"AUTHORS", "CONTRIBUTORS"}
camliHeadHash string
cachedCamliRoot string
camliRoot string
camputCacheDir string
currentTask task
dbg *debugger
defaultDir string
defaultPATH string
// doBuildCamli0 is for when we're in the go 1 test suite, and
// doBuildCamli1 for the go tip test suite. They are set when
// the camli source tree has been updated and indicate that
// 'make' should be run.
// doBuildGo indicates the go source tree has changed, hence
// go tip should be rebuilt, and in the go tip test suite case
// camlistore should be cleaned (pkg and bin) and rebuilt.
doBuildGo, doBuildCamli0, doBuildCamli1 bool
goPath string
go1Path string
goTipPath string
goTipDir string
goTipHash string
lastErr error
historylk sync.Mutex
currentTestSuite *testSuite
history History
)
var NameToCmd = map[string]string{
"prepRepo1": "hg pull",
"prepRepo2": "hg update -C default",
"prepRepo3": "hg --config extensions.purge= purge --all",
"prepRepo4": "hg log -r tip --template {node}",
"prepRepo5": "git reset --hard HEAD",
"prepRepo6": "git clean -Xdf",
"prepRepo7": "git pull",
"prepRepo8": "git rev-parse HEAD",
"buildGoTip1": "./make.bash",
"buildCamli1": "make forcefull",
"buildCamli2": "make presubmit",
"runCamli": "./dev-server --wipe --mysql --staticres --offline",
"hitCamliUi1": "http://localhost:3179/ui/",
"camget": "./dev-camget ",
"camput1": "./dev-camput file --permanode " + testFile[0],
"camput2": "./dev-camput file --vivify " + testFile[1],
"camput3": "./dev-camput file --filenodes pkg",
}
func usage() {
fmt.Fprintf(os.Stderr, "\t buildbot \n")
flag.PrintDefaults()
os.Exit(2)
}
type debugger struct {
lg *log.Logger
}
func (dbg *debugger) Printf(format string, v ...interface{}) {
if *verbose {
dbg.lg.Printf(format, v...)
}
}
func (dbg *debugger) Println(v ...interface{}) {
if v == nil {
return
}
if *verbose {
dbg.lg.Println(v...)
}
}
func setup() {
var err error
defaultDir, err = os.Getwd()
if err != nil {
log.Fatal(err)
}
defaultPATH = os.Getenv("PATH")
if defaultPATH == "" {
log.Fatal("PATH not set")
}
dbg = &debugger{log.New(os.Stderr, "", log.LstdFlags)}
// check go tip tree
goTipDir, err = filepath.Abs(*gotipdir)
if err != nil {
log.Fatalf("Problem with Go tip dir: %v", err)
}
if _, err := os.Stat(goTipDir); err != nil {
log.Fatalf("Problem with Go tip dir: %v", err)
}
// setup temp gopath(s)
goTipPath, err = ioutil.TempDir("", "camlibot-gotippath")
if err != nil {
log.Fatalf("problem with tempdir: %v", err)
}
srcDir := filepath.Join(goTipPath, "src")
err = os.Mkdir(srcDir, 0755)
if err != nil {
log.Fatalf("problem with src dir: %v", err)
}
go1Path, err = ioutil.TempDir("", "camlibot-go1path")
if err != nil {
log.Fatalf("problem with tempdir: %v", err)
}
srcDir = filepath.Join(go1Path, "src")
err = os.Mkdir(srcDir, 0755)
if err != nil {
log.Fatalf("problem with src dir: %v", err)
}
goPath = go1Path
err = os.Setenv("GOPATH", goPath)
if err != nil {
log.Fatalf("problem setting up GOPATH: %v", err)
}
// set up the camlistore tree
camliRoot = filepath.Join(srcDir, "camlistore.org")
cacheDir := filepath.Join(os.TempDir(), "camlibot-cache")
cachedCamliRoot = filepath.Join(cacheDir, "camlistore.org")
if _, err := os.Stat(cachedCamliRoot); err != nil {
// git clone
if _, err := os.Stat(cacheDir); err != nil {
err = os.Mkdir(cacheDir, 0755)
if err != nil {
log.Fatalf("problem with cache dir: %v", err)
}
}
setCurrentTask("git clone https://camlistore.org/r/p/camlistore " + camliRoot)
_, err = runCmd(getCurrentTask().Cmd)
if err != nil {
log.Fatalf("problem with git clone: %v", err)
}
} else {
// get cache
err = os.Rename(cachedCamliRoot, camliRoot)
if err != nil {
log.Fatal(err)
}
}
// recording camput cache dir, so we can clean it up fast everytime
homeDir := os.Getenv("HOME")
if homeDir == "" {
log.Fatal("HOME not set")
}
camputCacheDir = filepath.Join(homeDir, ".cache", "camlistore")
}
func cleanTempGopath() {
if *nocleanup {
return
}
err := os.Rename(camliRoot, cachedCamliRoot)
if err != nil {
panic(err)
}
err = os.RemoveAll(go1Path)
if err != nil {
panic(err)
}
err = os.RemoveAll(goTipPath)
if err != nil {
panic(err)
}
}
func switchGoPath(isTip bool) {
if isTip {
goPath = goTipPath
} else {
goPath = go1Path
}
newRoot := filepath.Join(goPath, "src", "camlistore.org")
if newRoot != camliRoot {
err := os.Rename(camliRoot, newRoot)
if err != nil {
panic(err)
}
camliRoot = newRoot
err = os.Setenv("GOPATH", goPath)
if err != nil {
log.Fatalf("problem setting up GOPATH: %v", err)
}
}
}
func handleSignals() {
c := make(chan os.Signal)
sigs := []os.Signal{syscall.SIGINT, syscall.SIGTERM}
signal.Notify(c, sigs...)
for {
sig := <-c
sysSig, ok := sig.(syscall.Signal)
if !ok {
log.Fatal("Not a unix signal")
}
switch sysSig {
case syscall.SIGINT, syscall.SIGTERM:
log.Printf("SIGINT: cleaning up %v before terminating", goPath)
cleanTempGopath()
os.Exit(0)
default:
panic("should not get other signals here")
}
}
}
func prepRepo() {
doBuildGo, doBuildCamli0, doBuildCamli1 = false, false, false
if *fast {
if currentTestSuite == nil {
currentTestSuite = &testSuite{
Run: make([]*task, 0, 1),
GoHash: goTipHash,
CamliHash: camliHeadHash,
IsTip: false,
}
}
return
}
// gotip
err := os.Chdir(goTipDir)
if err != nil {
log.Fatal(err)
}
defer func() {
err := os.Chdir(defaultDir)
if err != nil {
panic(err)
}
}()
tasks := []string{
NameToCmd["prepRepo1"],
NameToCmd["prepRepo2"],
NameToCmd["prepRepo4"],
}
hash := ""
for _, v := range tasks {
setCurrentTask(v)
out, err := runCmd(v)
if err != nil {
if v == NameToCmd["prepRepo1"] {
dbg.Printf("Go repo could not be updated: %v\n", err)
continue
}
log.Fatal(err)
}
hash = strings.TrimRight(out, "\n")
}
dbg.Println("previous head in go tree: " + goTipHash)
dbg.Println("current head in go tree: " + hash)
if hash != "" && hash != goTipHash {
goTipHash = hash
doBuildGo = true
dbg.Println("Changes in go tree detected, go tip will be rebuilt")
}
// camli
err = os.Chdir(camliRoot)
if err != nil {
log.Fatal(err)
}
tasks = []string{
NameToCmd["prepRepo5"],
NameToCmd["prepRepo6"],
NameToCmd["prepRepo7"],
NameToCmd["prepRepo8"],
}
hash = ""
for _, v := range tasks {
setCurrentTask(v)
out, err := runCmd(v)
if err != nil {
if v == NameToCmd["prepRepo7"] {
dbg.Printf("Camli repo could not be updated: %v\n", err)
continue
}
log.Fatal(err)
}
hash = strings.TrimRight(out, "\n")
}
dbg.Println("previous head in camli tree: " + camliHeadHash)
dbg.Println("current head in camli tree: " + hash)
if hash != "" && hash != camliHeadHash {
camliHeadHash = hash
doBuildCamli0, doBuildCamli1 = true, true
dbg.Println("Changes in camli tree detected, camlistore will be rebuilt")
}
}
func addToPATH(gobin string) {
splitter := ":"
switch runtime.GOOS {
case "windows":
splitter = ";"
case "plan9":
panic("unsupported")
}
p := gobin + splitter + defaultPATH
err := os.Setenv("PATH", p)
if err != nil {
log.Fatalf("Could not set PATH to %v: %v", p, err)
}
}
func restorePATH() {
err := os.Setenv("PATH", defaultPATH)
if err != nil {
log.Fatalf("Could not set PATH to %v: %v", defaultPATH, err)
}
}
type task struct {
lk sync.Mutex
// actual command that is run for this task. it includes the command and
// all the arguments, space separated. shell metacharacters not supported.
Cmd string
start time.Time
Duration time.Duration
}
func getCurrentTask() *task {
currentTask.lk.Lock()
defer currentTask.lk.Unlock()
return &task{Cmd: currentTask.Cmd, start: currentTask.start}
}
func setCurrentTask(cmd string) {
currentTask.lk.Lock()
defer currentTask.lk.Unlock()
currentTask.Cmd = cmd
currentTask.start = time.Now()
}
type testSuite struct {
Run []*task
CamliHash string
GoHash string
failedTask int
Err error
Start time.Time
IsTip bool
}
type History [][2]*testSuite
func addRun(tsk *task, tskErr error) {
historylk.Lock()
defer historylk.Unlock()
duration := time.Now().Sub(tsk.start)
tsk.Duration = duration
if len(currentTestSuite.Run) == 0 {
currentTestSuite.Start = tsk.start
}
if tskErr != nil && currentTestSuite.Err == nil {
currentTestSuite.Err = tskErr
currentTestSuite.failedTask = len(currentTestSuite.Run)
}
currentTestSuite.Run = append(currentTestSuite.Run, tsk)
}
func addTestSuite() {
historylk.Lock()
defer historylk.Unlock()
if len(currentTestSuite.Run) < 1 {
return
}
if !currentTestSuite.IsTip {
// Go 1
entry := [2]*testSuite{currentTestSuite, nil}
history = append(history, entry)
} else {
// Go tip
entry := [2]*testSuite{history[len(history)-1][0], currentTestSuite}
if len(history) > historySize {
history = append(history[1:historySize], entry)
} else {
history[len(history)-1] = entry
}
}
}
func runCmd(tsk string) (string, error) {
dbg.Println(getCurrentTask().Cmd)
fields := strings.Fields(tsk)
var args []string
if len(fields) > 1 {
args = fields[1:]
}
cmd := exec.Command(fields[0], args...)
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err := cmd.Run()
if err != nil {
return "", fmt.Errorf("%v: %v\n", stdout.String(), stderr.String())
}
return stdout.String(), nil
}
func gofast(n int) {
for i := 0; i < n; i++ {
tsk := &task{start: time.Now()}
fail := rand.Intn(10)
if fail < 1 {
dbg.Println("random fail")
addRun(tsk, fmt.Errorf("random fail"))
continue
}
addRun(tsk, nil)
}
}
func buildGoTip() error {
if *fast {
gofast(3)
return nil
}
err := os.Chdir(goTipDir)
if err != nil {
log.Fatal(err)
}
defer func() {
err := os.Chdir(defaultDir)
if err != nil {
panic(err)
}
}()
tasks := []string{
NameToCmd["prepRepo3"],
}
for _, v := range tasks {
setCurrentTask(v)
tsk := getCurrentTask()
_, err := runCmd(tsk.Cmd)
addRun(tsk, err)
if err != nil {
return err
}
}
err = os.Chdir(filepath.Join(goTipDir, "src"))
if err != nil {
log.Fatal(err)
}
defer func() {
err := os.Chdir(defaultDir)
if err != nil {
panic(err)
}
}()
setCurrentTask(NameToCmd["buildGoTip1"])
tsk := getCurrentTask()
_, err = runCmd(tsk.Cmd)
addRun(tsk, err)
if err != nil {
return err
}
return nil
}
func buildCamli(isTip bool) error {
if *fast {
gofast(5)
return nil
}
switchGoPath(isTip)
err := os.Chdir(camliRoot)
if err != nil {
log.Fatal(err)
}
defer func() {
err := os.Chdir(defaultDir)
if err != nil {
panic(err)
}
}()
if doBuildGo && isTip {
if *verbose {
dbg.Println("cleaning up gopath/pkg and gopath/bin for full rebuild")
}
// erase and rebuild everything
pkgdir := filepath.Join("..", "..", "pkg")
err := os.RemoveAll(pkgdir)
if err != nil {
log.Fatalf("failed to remove %v: %v", pkgdir, err)
}
bindir := filepath.Join("..", "..", "bin")
err = os.RemoveAll(bindir)
if err != nil {
log.Fatalf("failed to remove %v: %v", bindir, err)
}
}
if *verbose {
setCurrentTask("go version")
out, err := runCmd(getCurrentTask().Cmd)
if err != nil {
log.Fatalf("failed to run 'go version': %v", err)
}
out = strings.TrimRight(out, "\n")
dbg.Printf("Building camlistore in %v with: %v\n", goPath, out)
}
tasks := []string{}
if doBuildCamli0 || doBuildCamli1 || (doBuildGo && isTip) {
tasks = append(tasks, NameToCmd["buildCamli1"])
}
tasks = append(tasks, NameToCmd["buildCamli2"])
for _, v := range tasks {
setCurrentTask(v)
tsk := getCurrentTask()
_, err := runCmd(tsk.Cmd)
addRun(tsk, err)
if err != nil {
return err
}
}
if doBuildGo && isTip {
doBuildGo = false
doBuildCamli1 = false
}
if isTip {
doBuildCamli1 = false
} else {
doBuildCamli0 = false
}
return nil
}
func runCamli() (*os.Process, error) {
if *fast {
gofast(1)
return nil, nil
}
err := os.Chdir(camliRoot)
if err != nil {
log.Fatal(err)
}
defer func() {
err := os.Chdir(defaultDir)
if err != nil {
panic(err)
}
}()
setCurrentTask(NameToCmd["runCamli"])
dbg.Println(getCurrentTask().Cmd)
fields := strings.Fields(getCurrentTask().Cmd)
args := fields[1:]
cmd := exec.Command(fields[0], args...)
var output []byte
errc := make(chan error, 1)
go func() {
output, err = cmd.CombinedOutput()
errc <- err
}()
select {
case err := <-errc:
dbg.Printf("dev server DEAD:\n%s\n", output)
tsk := getCurrentTask()
addRun(tsk, err)
return nil, fmt.Errorf("%v: server failed to start\n", tsk.Cmd)
case <-time.After(warmup):
dbg.Println("dev server OK")
addRun(getCurrentTask(), nil)
}
return cmd.Process, nil
}
func killCamli(proc *os.Process) {
if *fast {
return
}
dbg.Println("killing dev server")
err := proc.Kill()
if err != nil {
log.Fatalf("Could not kill dev-server: %v", err)
}
dbg.Println("")
}
func hitURL(url string) error {
setCurrentTask(fmt.Sprintf("http.Get(\"%s\")", url))
dbg.Println(getCurrentTask().Cmd)
resp, err := http.Get(url)
if err != nil {
return fmt.Errorf("%v: %v\n", getCurrentTask().Cmd, err)
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return fmt.Errorf("%v, got StatusCode: %d\n", getCurrentTask().Cmd, resp.StatusCode)
}
return nil
}
func hitCamliUi() error {
if *fast {
gofast(2)
return nil
}
urls := []string{
NameToCmd["hitCamliUi1"],
}
var err error
for _, v := range urls {
lerr := hitURL(v)
addRun(getCurrentTask(), lerr)
if lerr != nil {
err = lerr
}
}
return err
}
func camputOne(vivify bool) error {
if *fast {
gofast(3)
return nil
}
err := os.Chdir(camliRoot)
if err != nil {
log.Fatal(err)
}
defer func() {
err := os.Chdir(defaultDir)
if err != nil {
panic(err)
}
}()
// clean up camput caches
err = os.RemoveAll(camputCacheDir)
if err != nil {
log.Fatalf("Problem cleaning up camputCacheDir %v: %v", camputCacheDir, err)
}
// push the file to camli
tskString := NameToCmd["camput1"]
if vivify {
tskString = NameToCmd["camput2"]
}
setCurrentTask(tskString)
tsk := getCurrentTask()
out, err := runCmd(tsk.Cmd)
addRun(tsk, err)
if err != nil {
return err
}
// TODO(mpl): parsing camput output is kinda weak.
firstSHA1 := regexp.MustCompile(`.*(sha1-[a-zA-Z0-9]+)\nsha1-[a-zA-Z0-9]+\nsha1-[a-zA-Z0-9]+\n.*`)
if vivify {
firstSHA1 = regexp.MustCompile(`.*(sha1-[a-zA-Z0-9]+)\n.*`)
}
m := firstSHA1.FindStringSubmatch(out)
if m == nil {
return fmt.Errorf("%v: unexpected camput output\n", getCurrentTask().Cmd)
}
blobref := m[1]
// get the file's json to find out the file's blobref
setCurrentTask(NameToCmd["camget"] + blobref)
tsk = getCurrentTask()
out, err = runCmd(tsk.Cmd)
addRun(tsk, err)
if err != nil {
return err
}
blobrefPattern := regexp.MustCompile(`"blobRef": "(sha1-[a-zA-Z0-9]+)",\n.*`)
m = blobrefPattern.FindStringSubmatch(out)
if m == nil {
return fmt.Errorf("%v: unexpected camget output\n", getCurrentTask().Cmd)
}
blobref = m[1]
// finally, get the file back
setCurrentTask(NameToCmd["camget"] + blobref)
tsk = getCurrentTask()
out, err = runCmd(tsk.Cmd)
addRun(tsk, err)
if err != nil {
return err
}
// and compare it with the original
wantFile := testFile[0]
if vivify {
wantFile = testFile[1]
}
fileContents, err := ioutil.ReadFile(wantFile)
if err != nil {
log.Fatalf("Could not read %v: %v", wantFile, err)
}
if string(fileContents) != out {
return fmt.Errorf("%v: contents fetched with camget differ from %v contents", getCurrentTask().Cmd, wantFile)
}
return nil
}
func camputMany() error {
if *fast {
gofast(1)
return nil
}
err := os.Chdir(camliRoot)
if err != nil {
log.Fatal(err)
}
defer func() {
err := os.Chdir(defaultDir)
if err != nil {
panic(err)
}
}()
// upload the full camli pkg tree
setCurrentTask(NameToCmd["camput3"])
tsk := getCurrentTask()
_, err = runCmd(tsk.Cmd)
addRun(tsk, err)
if err != nil {
return err
}
return nil
}
func handleErr(err error, proc *os.Process) {
lastErr = err
dbg.Printf("%v", err)
if proc != nil {
killCamli(proc)
}
addTestSuite()
}
func main() {
flag.Usage = usage
flag.Parse()
if *help {
usage()
}
setup()
defer cleanTempGopath()
go handleSignals()
http.HandleFunc(okPrefix, okHandler)
http.HandleFunc(failPrefix, failHandler)
http.HandleFunc(currentPrefix, progressHandler)
http.HandleFunc("/", statusHandler)
go http.ListenAndServe(*host, nil)
tryCount := 0
for {
if lastErr == nil || tryCount > 1 {
tryCount = 0
lastErr = nil
prepRepo()
}
if doBuildGo || doBuildCamli0 || doBuildCamli1 || lastErr != nil {
for _, isTip := range [2]bool{false, true} {
restorePATH()
currentTestSuite = &testSuite{
Run: make([]*task, 0, 1),
GoHash: goTipHash,
CamliHash: camliHeadHash,
IsTip: isTip,
}
if isTip {
addToPATH(filepath.Join(goTipDir, "bin"))
if doBuildGo {
err := buildGoTip()
if err != nil {
handleErr(err, nil)
continue
}
}
}
err := buildCamli(isTip)
if err != nil {
handleErr(err, nil)
continue
}
proc, err := runCamli()
if err != nil {
handleErr(err, nil)
continue
}
err = hitCamliUi()
if err != nil {
handleErr(err, proc)
continue
}
doVivify := false
err = camputOne(doVivify)
if err != nil {
handleErr(err, proc)
continue
}
doVivify = true
err = camputOne(doVivify)
if err != nil {
handleErr(err, proc)
continue
}
err = camputMany()
if err != nil {
handleErr(err, proc)
continue
}
dbg.Println("All good.")
killCamli(proc)
addTestSuite()
}
tryCount++
}
setCurrentTask(fmt.Sprintf("time.Sleep(%d)", interval))
dbg.Println(getCurrentTask().Cmd)
time.Sleep(interval)
}
}
var (
okPrefix = "/ok/"
failPrefix = "/fail/"
currentPrefix = "/current"
statusTpl = template.Must(template.New("status").Funcs(tmplFuncs).Parse(reportHTML))
taskTpl = template.Must(template.New("task").Parse(taskHTML))
testSuiteTpl = template.Must(template.New("ok").Parse(testSuiteHTML))
)
var tmplFuncs = template.FuncMap{
"camliRepoURL": camliRepoURL,
"goRepoURL": goRepoURL,
"shortHash": shortHash,
}
// unlocked; history needs to be protected from the caller.
func getPastTestSuite(key string) (*testSuite, error) {
idx := 0
date := ""
if strings.HasPrefix(key, "gotip-") {
date = strings.Replace(key, "gotip-", "", -1)
idx = 1
} else {
date = strings.Replace(key, "go1-", "", -1)
}
for _, v := range history {
if v[idx].Start.String() == date {
return v[idx], nil
}
}
return nil, fmt.Errorf("%v not found in history", date)
}
type progressData struct {
Ts *testSuite
Current string
}
func okHandler(w http.ResponseWriter, r *http.Request) {
t := strings.Replace(r.URL.Path, okPrefix, "", -1)
historylk.Lock()
defer historylk.Unlock()
ts, err := getPastTestSuite(t)
if err != nil {
http.NotFound(w, r)
return
}
dat := &progressData{
Ts: ts,
}
err = testSuiteTpl.Execute(w, dat)
if err != nil {
log.Printf("ok template: %v\n", err)
}
}
func progressHandler(w http.ResponseWriter, r *http.Request) {
historylk.Lock()
defer historylk.Unlock()
dat := &progressData{
Ts: currentTestSuite,
Current: getCurrentTask().Cmd,
}
err := testSuiteTpl.Execute(w, dat)
if err != nil {
log.Printf("progress template: %v\n", err)
}
}
type TaskReport struct {
Cmd string
Err error
}
func failHandler(w http.ResponseWriter, r *http.Request) {
t := strings.Replace(r.URL.Path, failPrefix, "", -1)
historylk.Lock()
defer historylk.Unlock()
ts, err := getPastTestSuite(t)
if err != nil {
http.NotFound(w, r)
return
}
taskReport := &TaskReport{Cmd: ts.Run[ts.failedTask].Cmd, Err: ts.Err}
err = taskTpl.Execute(w, taskReport)
if err != nil {
log.Printf("fail template: %v\n", err)
}
}
type status struct {
Hs History
Ts *testSuite
}
func invertedHistory() (inverted History) {
historylk.Lock()
defer historylk.Unlock()
inverted = make(History, len(history))
endpos := len(history) - 1
for k, v := range history {
inverted[endpos-k] = v
}
return inverted
}
func statusHandler(w http.ResponseWriter, r *http.Request) {
stat := &status{
Hs: invertedHistory(),
Ts: currentTestSuite,
}
err := statusTpl.Execute(w, stat)