forked from perkeep/perkeep
-
Notifications
You must be signed in to change notification settings - Fork 0
/
builder.go
1120 lines (1038 loc) · 29.2 KB
/
builder.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.
*/
// The buildbot is Camlistore's continuous builder.
// This builder program is started by the master. It then rebuilds
// Go 1, GoTip, Camlistore, and runs a battery of tests for Camlistore.
// It then sends a report to the master and terminates.
// It can also respond to progress requests from the master.
package main
import (
"bufio"
"bytes"
"crypto/tls"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"os/exec"
"os/signal"
"path/filepath"
"regexp"
"runtime"
"strings"
"sync"
"syscall"
"time"
"camlistore.org/pkg/netutil"
"camlistore.org/pkg/osutil"
)
const (
interval = 60 * time.Second // polling frequency
warmup = 30 * time.Second // duration before we test if devcam server has started properly
camlistoredTimeOut = time.Minute // how long we try to dial camlistored after warmup
go1BaseURL = "https://storage.googleapis.com/golang/"
go1Tarball = "go1.5.linux-amd64.tar.gz"
go1URL = go1BaseURL + go1Tarball
)
var (
// TODO(mpl): use that one, same as in master.
altCamliRevURL = flag.String("camlirevurl", "", "alternative URL to query about the latest camlistore revision hash (e.g camlistore.org/latesthash), to alleviate hitting too often the Camlistore git repo.")
arch = flag.String("arch", "", "The arch we report the master(s). Defaults to runtime.GOARCH.")
fakeTests = flag.Bool("faketests", false, "Run fast fake tests instead of the real ones, for faster debugging.")
help = flag.Bool("h", false, "show this help")
host = flag.String("host", "0.0.0.0:8081", "listening hostname and port")
masterHosts = flag.String("masterhosts", "localhost:8080", "listening hostname and port of the master bots, i.e where to send the test suite reports. Comma separated list.")
ourOS = flag.String("os", "", "The OS we report the master(s). Defaults to runtime.GOOS.")
skipGo1Build = flag.Bool("skipgo1build", true, "skip initial go1 build, for debugging and quickly going to the next steps.")
skip = flag.String("skip", "gotip", "Test suite to skip. Valid values are \"go1\", \"gotip\", or \"all\".")
verbose = flag.Bool("verbose", false, "print what's going on")
skipTLSCheck = flag.Bool("skiptlscheck", false, "accept any certificate presented by server when uploading results.")
taskLifespan = flag.Int("timeout", 600, "Lifespan (in seconds) for each task run by this builder, after which the task automatically terminates. 0 or negative means infinite.")
)
var (
testFile = []string{"AUTHORS", "CONTRIBUTORS"}
cacheDir string
camliHeadHash string
camliRoot string
camputCacheDir string
client = http.DefaultClient
dbg *debugger
defaultPATH string
go1Dir string
goTipDir string
goTipHash string
biSuitelk sync.Mutex
currentTestSuite *testSuite
currentBiSuite *biTestSuite
// Process of the camlistore server, so we can kill it when
// we get killed ourselves.
camliProc *os.Process
// For "If-Modified-Since" requests asking for progress.
// Updated every time a new test task/run is added to the test suite.
lastModified time.Time
)
var devcamBin = filepath.Join("bin", "devcam")
var (
fetchGo1Cmd = newTask("wget", go1URL)
untarGo1Cmd = newTask("tar", "xzf", go1Tarball)
hgCloneGo1Cmd = newTask("hg", "clone", "-u", "release", "https://code.google.com/p/go")
hgCloneGoTipCmd = newTask("hg", "clone", "-u", "tip", "https://code.google.com/p/go")
hgPullCmd = newTask("hg", "pull")
hgUpdateCmd = newTask("hg", "update", "-C", "default")
hgLogCmd = newTask("hg", "log", "-r", "tip", "--template", "{node}")
hgConfigCmd = newTask("hg", "--config", "extensions.purge=", "purge", "--all")
gitCloneCmd = newTask("git", "clone", "https://camlistore.googlesource.com/camlistore")
gitResetCmd = newTask("git", "reset", "--hard")
gitCleanCmd = newTask("git", "clean", "-Xdf")
gitPullCmd = newTask("git", "pull")
gitRevCmd = newTask("git", "rev-parse", "HEAD")
buildGoCmd = newTask("./make.bash")
buildCamliCmd = newTask("go", "run", "make.go", "-v")
runTestsCmd = newTask(devcamBin, "test")
runCamliCmd = newTask(devcamBin, "server", "--wipe", "--mysql")
camgetCmd = newTask(devcamBin, "get")
camputCmd = newTask(devcamBin, "put", "file", "--permanode", testFile[0])
camputVivifyCmd = newTask(devcamBin, "put", "file", "--vivify", testFile[1])
camputFilenodesCmd = newTask(devcamBin, "put", "file", "--filenodes", "pkg")
)
func usage() {
fmt.Fprintf(os.Stderr, "\t builderBot \n")
flag.PrintDefaults()
os.Exit(2)
}
type debugger struct {
lg *log.Logger
}
func (dbg *debugger) Printf(format string, v ...interface{}) {
if dbg != nil && *verbose {
dbg.lg.Printf(format, v...)
}
}
func (dbg *debugger) Println(v ...interface{}) {
if v == nil {
return
}
if dbg != nil && *verbose {
dbg.lg.Println(v...)
}
}
type task struct {
Program string
Args []string
Start time.Time
Duration time.Duration
Err string
hidden bool
}
func newTask(program string, args ...string) *task {
return &task{Program: program, Args: args}
}
// because sometimes we do not want to modify the tsk template
// so we make a copy of it
func newTaskFrom(tsk *task) *task {
return newTask(tsk.Program, tsk.Args...)
}
func (t *task) String() string {
return fmt.Sprintf("%v %v", t.Program, t.Args)
}
func (t *task) Error() string {
return t.Err
}
func (t *task) run() (string, error) {
var err error
defer func() {
t.Duration = time.Now().Sub(t.Start)
if !t.hidden {
biSuitelk.Lock()
currentTestSuite.addRun(t)
biSuitelk.Unlock()
}
}()
dbg.Println(t.String())
cmd := exec.Command(t.Program, t.Args...)
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
t.Start = time.Now()
setTaskErr := func() {
var sout, serr string
if sout = stdout.String(); sout == "" {
sout = "(empty)"
}
if serr = stderr.String(); serr == "" {
serr = "(empty)"
}
t.Err = fmt.Sprintf("Stdout:\n%s\n\nStderr:\n%s", sout, serr)
if err != nil {
t.Err = fmt.Sprintf("%v\n\n%v", err, t.Err)
}
}
// TODO(mpl, wathiede): make it learn about task durations.
errc := make(chan error)
go func() {
errc <- cmd.Run()
}()
if *taskLifespan > 0 {
select {
case <-time.After(time.Duration(*taskLifespan) * time.Second):
setTaskErr()
t.Err = fmt.Sprintf("%v\n\nTask %q took too long. Giving up after %v seconds.\n",
t.Err, t.String(), *taskLifespan)
if cmd.Process != nil {
if err := cmd.Process.Signal(syscall.SIGTERM); err != nil {
dbg.Printf("Could not terminate process for task %q: %v", t.String(), err)
}
}
return "", t
case err = <-errc:
break
}
} else {
err = <-errc
}
if err != nil {
setTaskErr()
return "", t
}
return stdout.String(), nil
}
type testSuite struct {
Run []*task
CamliHash string
GoHash string
Err string
Start time.Time
IsTip bool
}
func (ts *testSuite) addRun(tsk *task) {
if ts == nil {
panic("Tried adding a run to a nil testSuite")
}
if ts.Start.IsZero() && len(ts.Run) == 0 {
ts.Start = tsk.Start
}
if tsk.Err != "" && ts.Err == "" {
ts.Err = tsk.Err
}
ts.Run = append(ts.Run, tsk)
lastModified = time.Now()
}
type biTestSuite struct {
Local bool
Go1 testSuite
GoTip testSuite
}
func main() {
flag.Usage = usage
flag.Parse()
if *help {
usage()
}
if *skipTLSCheck {
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client = &http.Client{Transport: tr}
}
go handleSignals()
http.HandleFunc("/progress", progressHandler)
go func() {
log.Printf("Now starting to listen on %v", *host)
if err := http.ListenAndServe(*host, nil); err != nil {
log.Fatalf("Could not start listening on %v: %v", *host, err)
}
}()
setup()
biSuitelk.Lock()
currentBiSuite = &biTestSuite{}
biSuitelk.Unlock()
for _, isTip := range [2]bool{false, true} {
currentTestSuite = &testSuite{
Run: make([]*task, 0, 1),
IsTip: isTip,
Start: time.Now(),
}
// We prepare the Go tip tree as soon as in the Go 1 run, so
// we can set GoTipHash in the test suite.
if !isTip {
if err := prepGoTipTree(); err != nil {
endOfSuite(err)
// If we failed with that in the Go 1 run, we just restart
// from scratch instead of trying to cope with it in the Gotip run.
// Same for buildGoTip and prepCamliTree.
break
}
}
biSuitelk.Lock()
currentTestSuite.GoHash = goTipHash
biSuitelk.Unlock()
if isTip && !*fakeTests {
if err := buildGoTip(); err != nil {
endOfSuite(err)
break
}
}
if err := prepCamliTree(isTip); err != nil {
endOfSuite(err)
break
}
biSuitelk.Lock()
currentTestSuite.CamliHash = camliHeadHash
biSuitelk.Unlock()
restorePATH()
goDir := go1Dir
if isTip {
goDir = goTipDir
}
switchGo(goDir)
if doSkip(isTip) {
endOfSuite(nil)
continue
}
if *fakeTests {
if err := fakeRun(); err != nil {
endOfSuite(err)
continue
}
endOfSuite(nil)
if isTip {
break
}
continue
}
if err := buildCamli(); err != nil {
endOfSuite(err)
continue
}
if err := runTests(); err != nil {
endOfSuite(err)
continue
}
if err := runCamli(); err != nil {
endOfSuite(err)
continue
}
if err := hitCamliUi(); err != nil {
endOfSuite(err)
continue
}
doVivify := false
if err := camputOne(doVivify); err != nil {
endOfSuite(err)
continue
}
doVivify = true
if err := camputOne(doVivify); err != nil {
endOfSuite(err)
continue
}
if err := camputMany(); err != nil {
endOfSuite(err)
continue
}
endOfSuite(nil)
}
sanitizeRevs()
sendReport()
}
func doSkip(isTip bool) bool {
return *skip == "all" || (isTip && *skip == "gotip") || (!isTip && *skip == "go1")
}
func sanitizeRevs() {
if currentBiSuite == nil {
return
}
if currentBiSuite.GoTip.Start.IsZero() {
return
}
if currentBiSuite.GoTip.CamliHash == "" && currentBiSuite.Go1.CamliHash == "" {
dbg.Printf("CamliHash not set in both Go1 and GoTip test suites")
return
}
if currentBiSuite.GoTip.CamliHash == "" && currentBiSuite.Go1.CamliHash == "" {
dbg.Printf("GoHash not set in both Go1 and GoTip test suites")
return
}
if currentBiSuite.GoTip.CamliHash != "" && currentBiSuite.Go1.CamliHash != "" &&
currentBiSuite.GoTip.CamliHash != currentBiSuite.Go1.CamliHash {
panic("CamliHash in GoTip suite and in Go1 suite differ; should not happen.")
}
if currentBiSuite.GoTip.GoHash != "" && currentBiSuite.Go1.GoHash != "" &&
currentBiSuite.GoTip.GoHash != currentBiSuite.Go1.GoHash {
panic("GoHash in GoTip suite and in Go1 suite differ; should not happen.")
}
if currentBiSuite.GoTip.GoHash == "" {
currentBiSuite.GoTip.GoHash = currentBiSuite.Go1.GoHash
}
if currentBiSuite.Go1.GoHash == "" {
currentBiSuite.Go1.GoHash = currentBiSuite.GoTip.GoHash
}
if currentBiSuite.GoTip.CamliHash == "" {
currentBiSuite.GoTip.CamliHash = currentBiSuite.Go1.CamliHash
}
if currentBiSuite.Go1.CamliHash == "" {
currentBiSuite.Go1.CamliHash = currentBiSuite.GoTip.CamliHash
}
}
func endOfSuite(err error) {
biSuitelk.Lock()
defer biSuitelk.Unlock()
if currentTestSuite.IsTip {
currentBiSuite.GoTip = *currentTestSuite
} else {
currentBiSuite.Go1 = *currentTestSuite
}
killCamli()
if err != nil {
log.Printf("%v", err)
} else {
dbg.Println("All good.")
}
}
func masterHostsReader(r io.Reader) ([]string, error) {
hosts := []string{}
scanner := bufio.NewScanner(r)
for scanner.Scan() {
l := scanner.Text()
u, err := url.Parse(l)
if err != nil {
return nil, err
}
if u.Host == "" {
return nil, fmt.Errorf("URL missing Host: %q", l)
}
hosts = append(hosts, u.String())
}
if err := scanner.Err(); err != nil {
return nil, err
}
return hosts, nil
}
var masterHostsFile = filepath.Join(osutil.CamliConfigDir(), "builderbot-config")
func loadMasterHosts() error {
r, err := os.Open(masterHostsFile)
if err != nil {
return err
}
defer r.Close()
hosts, err := masterHostsReader(r)
if err != nil {
return err
}
if *masterHosts != "" {
*masterHosts += ","
}
log.Println("Additional host(s) to send our build reports:", hosts)
*masterHosts += strings.Join(hosts, ",")
return nil
}
func setup() {
var err error
defaultPATH = os.Getenv("PATH")
if defaultPATH == "" {
log.Fatal("PATH not set")
}
log.SetPrefix("BUILDER: ")
dbg = &debugger{log.New(os.Stderr, "BUILDER: ", log.LstdFlags)}
err = loadMasterHosts()
if err != nil {
if os.IsNotExist(err) {
log.Printf("%q missing. No additional remote master(s) will receive build report.", masterHostsFile)
} else {
log.Printf("Error parsing master hosts file %q: %v",
masterHostsFile, err)
}
}
// the OS we run on
if *ourOS == "" {
*ourOS = runtime.GOOS
if *ourOS == "" {
// Can this happen? I don't think so, but just in case...
panic("runtime.GOOS was not set")
}
}
// the arch we run on
if *arch == "" {
*arch = runtime.GOARCH
if *arch == "" {
panic("runtime.GOARCH was not set")
}
}
// cacheDir
cacheDir = filepath.Join(os.TempDir(), "camlibot-cache")
if err := os.MkdirAll(cacheDir, 0755); err != nil {
log.Fatalf("Could not create cache dir %v: %v", cacheDir, err)
}
// get go1 and gotip source
if err := os.Chdir(cacheDir); err != nil {
log.Fatalf("Could not cd to %v: %v", cacheDir, err)
}
go1Dir, err = filepath.Abs("go1")
if err != nil {
log.Fatalf("Problem with Go 1 dir: %v", err)
}
goTipDir, err = filepath.Abs("gotip")
if err != nil {
log.Fatalf("Problem with Go tip dir: %v", err)
}
// if go1 dir exist, just reuse it
if _, err := os.Stat(go1Dir); err != nil {
if !os.IsNotExist(err) {
log.Fatalf("Could not stat %v: %v", go1Dir, err)
}
tsk := newTaskFrom(fetchGo1Cmd)
tsk.hidden = true
if _, err := tsk.run(); err != nil {
log.Fatalf("Could not git clone %v: %v", go1URL, err)
}
tsk = newTaskFrom(untarGo1Cmd)
tsk.hidden = true
if _, err := tsk.run(); err != nil {
log.Fatalf("Could not untar %v: %v", go1Tarball, err)
}
if err := os.Rename("go", go1Dir); err != nil {
log.Fatalf("Could not rename go dir into %v: %v", go1Dir, err)
}
}
if !*skipGo1Build {
// build Go1
if err := buildGo1(); err != nil {
log.Fatal(err)
}
}
// get camlistore source
if err := os.Chdir(cacheDir); err != nil {
log.Fatalf("Could not cd to %v: %v", cacheDir, err)
}
camliRoot, err = filepath.Abs("camlistore.org")
if err != nil {
log.Fatal(err)
}
// if camlistore dir already exists, reuse it
if _, err := os.Stat(camliRoot); err != nil {
if !os.IsNotExist(err) {
log.Fatalf("Could not stat %v: %v", camliRoot, err)
}
cloneCmd := newTask(gitCloneCmd.Program, append(gitCloneCmd.Args, camliRoot)...)
cloneCmd.hidden = true
if _, err := cloneCmd.run(); err != nil {
log.Fatalf("Could not git clone into %v: %v", camliRoot, 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 buildGo1() error {
return errors.New("building Go1 from source not supported anymore, use -skipgo1build")
if err := os.Chdir(filepath.Join(go1Dir, "src")); err != nil {
log.Fatalf("Could not cd to %v: %v", go1Dir, err)
}
tsk := newTask(buildGoCmd.Program, buildGoCmd.Args...)
tsk.hidden = true
if _, err := tsk.run(); err != nil {
return err
}
return nil
}
func handleSignals() {
c := make(chan os.Signal)
sigs := []os.Signal{syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT}
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, syscall.SIGQUIT:
log.Printf("Received %v signal, terminating.", sig)
killCamli()
os.Exit(0)
default:
panic("should not get other signals here")
}
}
}
var plausibleHashRx = regexp.MustCompile(`^[a-f0-9]{40}$`)
func prepGoTipTree() error {
// Doing go tip disabled as of 20140126, because we'd need to fix the hg->git change,
// and deal with go 1.4 bootstrapping. Not worth the trouble since we're going to
// redo the bot soon with gomote and buildlet.
goTipHash = "Disabled"
return nil
if err := os.Chdir(goTipDir); err != nil {
return fmt.Errorf("Could not cd to %v: %v", goTipDir, err)
}
tasks := []*task{
newTaskFrom(hgPullCmd),
newTaskFrom(hgUpdateCmd),
newTaskFrom(hgLogCmd),
newTaskFrom(hgConfigCmd),
}
hash := ""
for _, t := range tasks {
out, err := t.run()
if err != nil {
return fmt.Errorf("Could not prepare the Go tip tree with %v: %v", t.String(), err)
}
if t.String() == hgLogCmd.String() {
hash = strings.TrimRight(out, "\n")
}
}
if !plausibleHashRx.MatchString(hash) {
return fmt.Errorf("Go rev %q does not look like an hg hash.", hash)
}
goTipHash = hash
dbg.Println("current head in go tree: " + goTipHash)
return nil
}
func buildGoTip() error {
// not building go tip anymore
return nil
srcDir := filepath.Join(goTipDir, "src")
if err := os.Chdir(srcDir); err != nil {
return fmt.Errorf("Could not cd to %v: %v", srcDir, err)
}
if _, err := newTaskFrom(buildGoCmd).run(); err != nil {
return err
}
return nil
}
func prepCamliTree(isTip bool) error {
if err := os.Chdir(camliRoot); err != nil {
return fmt.Errorf("Could not cd to %v: %v", camliRoot, err)
}
rev := "HEAD"
if isTip {
if !plausibleHashRx.MatchString(camliHeadHash) {
// the run with Go 1 should have taken care of setting camliHeadHash
return errors.New("camliHeadHash hasn't been set properly in the Go 1 run")
}
// we reset to the rev that was noted at the previous run with Go 1
// because we want to do both runs at the same rev
rev = camliHeadHash
}
resetCmd := newTask(gitResetCmd.Program, append(gitResetCmd.Args, rev)...)
tasks := []*task{
resetCmd,
newTaskFrom(gitCleanCmd),
}
for _, t := range tasks {
_, err := t.run()
if err != nil {
return fmt.Errorf("Could not prepare the Camli tree with %v: %v\n", t.String(), err)
}
}
if isTip {
// We only need to pull and get the camli head hash when in the Go 1 run
return nil
}
tasks = []*task{
newTaskFrom(gitPullCmd),
newTaskFrom(gitRevCmd),
}
hash := ""
for _, t := range tasks {
out, err := t.run()
if err != nil {
return fmt.Errorf("Could not prepare the Camli tree with %v: %v\n", t.String(), err)
}
hash = strings.TrimRight(out, "\n")
}
if !plausibleHashRx.MatchString(hash) {
return fmt.Errorf("Camlistore rev %q does not look like a git hash.", hash)
}
camliHeadHash = hash
return nil
}
func restorePATH() {
err := os.Setenv("PATH", defaultPATH)
if err != nil {
log.Fatalf("Could not set PATH to %v: %v", defaultPATH, err)
}
}
func switchGo(goDir string) {
if runtime.GOOS == "plan9" {
panic("plan 9 not unsupported")
}
if goDir == goTipDir {
// not doing gotip anymore
return
}
gobin := filepath.Join(goDir, "bin", "go")
if _, err := os.Stat(gobin); err != nil {
log.Fatalf("Could not stat 'go' bin at %q: %v", gobin, err)
}
p := filepath.Join(goDir, "bin") + string(filepath.ListSeparator) + defaultPATH
if err := os.Setenv("PATH", p); err != nil {
log.Fatalf("Could not set PATH to %v: %v", p, err)
}
if err := os.Setenv("GOROOT", goDir); err != nil {
log.Fatalf("Could not set GOROOT to %v: %v", goDir, err)
}
}
func cleanBuildGopaths() {
tmpDir := filepath.Join(camliRoot, "tmp")
if _, err := os.Stat(tmpDir); err != nil {
if !os.IsNotExist(err) {
log.Fatalf("Could not stat %v: %v", tmpDir, err)
}
// Does not exist, we only have to recreate it
// TODO(mpl): hmm maybe it should be an error that
// it does not exist, since it also contains the
// closure stuff?
if err := os.MkdirAll(tmpDir, 0755); err != nil {
log.Fatalf("Could not mkdir %v: %v", tmpDir, err)
}
return
}
f, err := os.Open(tmpDir)
if err != nil {
log.Fatalf("Could not open %v: %v", tmpDir, err)
}
defer f.Close()
names, err := f.Readdirnames(-1)
if err != nil {
log.Fatalf("Could not read %v: %v", tmpDir, err)
}
for _, v := range names {
if strings.HasPrefix(v, "build-gopath") {
if err := os.RemoveAll(filepath.Join(tmpDir, v)); err != nil {
log.Fatalf("Could not remove %v: %v", v, err)
}
}
}
}
func fakeRun() error {
if _, err := newTask("sleep", "1").run(); err != nil {
return err
}
return nil
}
func buildCamli() error {
if err := os.Chdir(camliRoot); err != nil {
log.Fatalf("Could not cd to %v: %v", camliRoot, err)
}
// Clean up Camlistore's hermetic gopaths
cleanBuildGopaths()
if *verbose {
tsk := newTask("go", "version")
out, err := tsk.run()
tsk.hidden = true
if err != nil {
return fmt.Errorf("failed to run 'go version': %v", err)
}
out = strings.TrimRight(out, "\n")
dbg.Printf("Building Camlistore with: %v\n", out)
}
if _, err := newTaskFrom(buildCamliCmd).run(); err != nil {
return err
}
return nil
}
func runCamli() error {
if err := os.Chdir(camliRoot); err != nil {
log.Fatal(err)
}
t := newTaskFrom(runCamliCmd)
dbg.Println(t.String())
cmd := exec.Command(t.Program, t.Args...)
var output []byte
errc := make(chan error, 1)
t.Start = time.Now()
go func() {
var err error
output, err = cmd.CombinedOutput()
if err != nil {
err = fmt.Errorf("%v: %v", err, string(output))
}
errc <- err
}()
select {
case err := <-errc:
t.Err = fmt.Sprintf("%v terminated early:\n%v\n", t.String(), err)
biSuitelk.Lock()
currentTestSuite.addRun(t)
biSuitelk.Unlock()
log.Println(t.Err)
return t
case <-time.After(warmup):
biSuitelk.Lock()
currentTestSuite.addRun(t)
camliProc = cmd.Process
biSuitelk.Unlock()
dbg.Printf("%v running OK so far\n", t.String())
}
return nil
}
func killCamli() {
if camliProc == nil {
return
}
dbg.Println("killing Camlistore server")
if err := camliProc.Kill(); err != nil {
log.Fatalf("Could not kill server with pid %v: %v", camliProc.Pid, err)
}
camliProc = nil
dbg.Println("")
}
func hitCamliUi() error {
if err := hitURL("http://localhost:3179/ui/"); err != nil {
return fmt.Errorf("could not reach camlistored UI page (dead server?): %v", err)
}
return nil
}
func hitURL(uri string) (err error) {
tsk := newTask("http.Get", uri)
defer func() {
if err != nil {
tsk.Err = fmt.Sprintf("%v", err)
}
biSuitelk.Lock()
currentTestSuite.addRun(tsk)
biSuitelk.Unlock()
}()
dbg.Println(tsk.String())
tsk.Start = time.Now()
u, err := url.Parse(uri)
if err != nil {
return fmt.Errorf("%v: could not get host:port to dial from %v: %v\n", tsk.String(), uri, err)
}
hostPort := u.Host
err = netutil.AwaitReachable(hostPort, camlistoredTimeOut)
if err != nil {
return fmt.Errorf("%v: camlistored unreachable at %v after %v: %v\n", tsk.String(), hostPort, camlistoredTimeOut, err)
}
var resp *http.Response
resp, err = http.Get(uri)
if err != nil {
return fmt.Errorf("%v: %v\n", tsk.String(), err)
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return fmt.Errorf("%v, got StatusCode: %d\n", tsk.String(), resp.StatusCode)
}
return nil
}
func camputOne(vivify bool) error {
if err := os.Chdir(camliRoot); err != nil {
log.Fatalf("Could not cd to %v: %v", camliRoot, err)
}
// clean up camput caches
if err := os.RemoveAll(camputCacheDir); err != nil {
log.Fatalf("Problem cleaning up camputCacheDir %v: %v", camputCacheDir, err)
}
// push the file to camli
tsk := newTaskFrom(camputCmd)
if vivify {
tsk = newTaskFrom(camputVivifyCmd)
}
out, err := tsk.run()
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", tsk.String())
}
blobref := m[1]
// get the file's json to find out the file's blobref
tsk = newTask(camgetCmd.Program, append(camgetCmd.Args, blobref)...)
out, err = tsk.run()
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", tsk.String())
}
blobref = m[1]
// finally, get the file back
tsk = newTask(camgetCmd.Program, append(camgetCmd.Args, blobref)...)
out, err = tsk.run()
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", tsk.String(), wantFile)
}
return nil
}
func camputMany() error {
err := os.Chdir(camliRoot)
if err != nil {
log.Fatalf("Could not cd to %v: %v", camliRoot, err)
}
// upload the full camli pkg tree
if _, err := newTaskFrom(camputFilenodesCmd).run(); err != nil {
return err
}
return nil
}
func runTests() error {
if err := os.Chdir(camliRoot); err != nil {
log.Fatal(err)
}
if _, err := newTaskFrom(runTestsCmd).run(); err != nil {
return err
}
return nil
}
const reportPrefix = "/report"
func postToURL(u string, r io.Reader) (*http.Response, error) {
// Default to plain HTTP.
if !(strings.HasPrefix(u, "http://") || strings.HasPrefix(u, "https://")) {
u = "http://" + u
}
uri, err := url.Parse(u)
if err != nil {
return nil, err