This repository has been archived by the owner on Mar 15, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
1300 lines (1203 loc) · 30.5 KB
/
main.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
package main
import (
"bufio"
"context"
"encoding/hex"
"encoding/json"
"flag"
"fmt"
"io"
"io/ioutil"
"os/signal"
"os"
"os/exec"
"path"
"sort"
"strings"
"syscall"
"time"
log "github.com/sirupsen/logrus"
"github.com/spf13/viper"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/mount"
"github.com/docker/docker/client"
// "github.com/docker/docker/pkg/stdcopy"
"gopkg.in/src-d/go-git.v4"
"gopkg.in/src-d/go-git.v4/config"
"gopkg.in/src-d/go-git.v4/plumbing"
)
var panicCh chan interface{}
func panicMain() {
if x := recover(); x != nil {
log.Debugf("Recovered from panic, terminating...")
panicCh <- x
}
}
type Result string
const (
ResultUnk Result = "UNK"
ResultPass Result = "PASS"
ResultErr Result = "ERR"
ResultReady Result = "READY"
ResultReadyErr Result = "READYERR"
ResultRun Result = "RUNNING"
ResultUnfinished Result = "UNFINISHED"
)
type ScriptCfg struct {
ReadyStr string
}
type RepoCfg struct {
Branch string
}
type DockerCfg struct {
Image string
Pull bool
Binds map[string]string
}
type Config struct {
WorkDir string
CitrusDir string `mapstructure:"-"`
CfgDir string `mapstructure:"-"`
Debug bool `mapstructure:"-"`
Force bool `mapstructure:"-"`
Docker bool `mapstructure:"-"`
Listen string
ReposUrl []string `mapstructure:"repos"`
Timeouts struct {
Loop int64
Setup int64
Ready int64
Test int64
Stop int64
Hook int64
}
ScriptsCfg map[string]map[string]ScriptCfg `mapstructure:"script"`
ReposCfg map[string]RepoCfg `mapstructure:"repo"`
DockerCfg DockerCfg `mapstructure:"docker"`
}
type Timeouts struct {
Loop time.Duration
Setup time.Duration
Ready time.Duration
Test time.Duration
Stop time.Duration
Hook time.Duration
}
type Script struct {
//Path string
ReadyStr string
Cmd *exec.Cmd
Result Result
waitCh chan error
// Running bool
PreludePath *string
RunDir *string
outDir *string
CfgDir *string
repoName *string
FileName string
}
// func (s *Script) FileName() string {
// return s.Path[strings.LastIndex(s.Path, "/")+1:]
// }
func (s *Script) RepoName() string {
if s.repoName == nil {
return ""
}
return *s.repoName
}
func (s *Script) Path() string {
return path.Join(*s.CfgDir, s.RepoName(), s.FileName)
}
func (s *Script) OutDir(ts string) string {
return path.Join(*s.outDir, ts, s.RepoName())
}
type ByFileName []*Script
func (s ByFileName) Len() int { return len(s) }
func (s ByFileName) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s ByFileName) Less(i, j int) bool { return s[i].FileName < s[j].FileName }
func (s *Script) Start(ctx context.Context, args []string,
ts string, readyCh chan bool) {
if err := os.MkdirAll(s.OutDir(ts), 0777); err != nil {
log.Panic(err)
}
outFileName := fmt.Sprintf("%s.out.txt", path.Base(s.Path()))
outFilePath := path.Join(s.OutDir(ts), outFileName)
log.WithField("log", outFilePath).Debugf("Running %s", s.Path())
s.Cmd = exec.CommandContext(ctx, *s.PreludePath, append([]string{s.Path()}, args...)...)
s.Cmd.Dir = *s.RunDir
s.Cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
stdout, err := s.Cmd.StdoutPipe()
if err != nil {
log.Panic(err)
}
stderr, err := s.Cmd.StderrPipe()
if err != nil {
log.Panic(err)
}
// stdoutBuf := bufio.NewReader(stdout)
// stderrBuf := bufio.NewReader(stderr)
endCh := make(chan bool)
go outputWrite(stdout, stderr, outFilePath, s.ReadyStr, readyCh, endCh)
if err := s.Cmd.Start(); err != nil {
log.Panic(err)
}
s.waitCh = make(chan error)
go func() {
defer panicMain()
// s.Running = true
<-endCh
s.waitCh <- s.Cmd.Wait()
// s.Running = false
}()
}
func (s *Script) Run(ctx context.Context, args []string,
ts string, readyCh chan bool) error {
s.Start(ctx, args, ts, readyCh)
return s.Wait()
}
func (s *Script) Wait() error {
if s.Cmd == nil {
return fmt.Errorf("Script.Cmd is nil")
}
err := <-s.waitCh
log.Debugf("Finished %s with err: %v", s.Path(), err)
return err
}
func (s *Script) Stop() error {
if s.Cmd == nil {
return fmt.Errorf("Script.Cmd is nil")
}
defer func() { s.Cmd = nil }()
select {
case res := <-s.waitCh:
log.Debugf("DBG script PID: %v", s.Cmd.Process.Pid)
return fmt.Errorf("Script exited prematurely with error %v",
res)
default:
}
pgid, err := syscall.Getpgid(s.Cmd.Process.Pid)
if err != nil {
return fmt.Errorf("Unable to get script process pgid")
}
if err := syscall.Kill(-pgid, syscall.SIGINT); err != nil {
return err
}
log.Debugf("SIGINT to %v", -pgid)
select {
case <-s.waitCh:
return nil
case <-time.After(30 * time.Second):
syscall.Kill(-pgid, syscall.SIGKILL)
return fmt.Errorf("Script took more than 30 seconds to terminate, killed")
}
}
type Scripts struct {
Setup []*Script
Start []*Script
Test []*Script
Stop []*Script
Hooks []*Script
PreludePath string
RunDir string
OutDir string
CfgDir string
repoName *string
}
func NewScriptsFromDir(dir, preludePath, runDir, outDir, cfgDir string, repoName *string,
scriptsCfg map[string]ScriptCfg) (*Scripts, error) {
files, err := ioutil.ReadDir(dir)
if err != nil {
return nil, err
}
scripts := Scripts{
PreludePath: preludePath,
RunDir: runDir,
OutDir: outDir,
CfgDir: cfgDir,
repoName: repoName,
}
for _, file := range files {
filePath := path.Join(dir, file.Name())
script := Script{
PreludePath: &scripts.PreludePath,
RunDir: &scripts.RunDir,
outDir: &scripts.OutDir,
CfgDir: &scripts.CfgDir,
repoName: scripts.repoName,
FileName: file.Name(),
}
var scriptSlice *[]*Script
if strings.HasPrefix(file.Name(), "setup") {
scriptSlice = &scripts.Setup
} else if strings.HasPrefix(file.Name(), "start") {
scriptSlice = &scripts.Start
if scriptsCfg == nil || scriptsCfg[file.Name()].ReadyStr == "" {
return nil, fmt.Errorf("Start script %v hasn't specified a readystr",
filePath)
}
script.ReadyStr = scriptsCfg[file.Name()].ReadyStr
} else if strings.HasPrefix(file.Name(), "test") {
scriptSlice = &scripts.Test
} else if strings.HasPrefix(file.Name(), "stop") {
scriptSlice = &scripts.Stop
} else if strings.HasPrefix(file.Name(), "hook") {
scriptSlice = &scripts.Hooks
}
if scriptSlice != nil {
*scriptSlice = append(*scriptSlice, &script)
}
}
return &scripts, nil
}
type Repo struct {
GitRepo *git.Repository
URL string
Branch string
Scripts Scripts
// OutDir string
Dir string
}
// func (r *Repo) URL() (string, error) {
// remotes, err := r.GitRepo.Remotes()
// if err != nil {
// return "", err
// }
// return remotes[0].Config().URLs[0], nil
// }
func (r *Repo) HeadHash() (plumbing.Hash, error) {
ref, err := r.GitRepo.Head()
if err != nil {
return plumbing.Hash{}, err
}
return ref.Hash(), nil
}
func (r *Repo) Name() string {
return strings.TrimSuffix(r.URL[strings.LastIndex(r.URL, "/")+1:], ".git")
}
type Repos struct {
Dir string
CfgDir string
OutDir string
Timeouts Timeouts
Result Result
Repos []*Repo
Scripts Scripts
scriptsSetup []*Script
scriptsStart []*Script
scriptsTest []*Script
scriptsStop []*Script
scriptsHooks []*Script
}
func NewRepos(cfgDir, outDir, reposDir string, reposUrl []string,
scriptsCfg map[string]map[string]ScriptCfg, reposCfg map[string]RepoCfg,
timeouts Timeouts, skipClone bool) (*Repos, error) {
repos := []*Repo{}
for _, repoUrl := range reposUrl {
repoUrl = strings.TrimSuffix(repoUrl, "/")
repoUrl = strings.TrimSuffix(repoUrl, ".git")
repoUrl = fmt.Sprintf("%v.git", repoUrl)
name := repoUrl[strings.LastIndex(repoUrl, "/")+1:]
repoDir := path.Join(reposDir, name)
repo := Repo{URL: repoUrl, Branch: "master", Dir: repoDir}
repoDirLink := strings.TrimSuffix(repoDir, ".git")
if err := os.Symlink(name, repoDirLink); err != nil {
if !os.IsExist(err) {
return nil, err
}
}
// repo.OutDir = path.Join(outDir, repo.Name())
if reposCfg[repo.Name()].Branch != "" {
repo.Branch = reposCfg[repo.Name()].Branch
}
var err error
if skipClone {
repo.GitRepo, err = git.PlainOpen(repo.Dir)
if err != nil {
return nil, err
}
} else {
log.Infof("Cloning %s into %s", repo.URL, repo.Dir)
repo.GitRepo, err = git.PlainClone(repo.Dir, false, &git.CloneOptions{
URL: repo.URL,
// SingleBranch: true,
ReferenceName: plumbing.NewBranchReferenceName(repo.Branch),
Progress: os.Stdout,
})
if err == git.ErrRepositoryAlreadyExists {
log.Infof("Repository %s already exists", repo.URL)
repo.GitRepo, err = git.PlainOpen(repo.Dir)
if err != nil {
return nil, err
}
} else if err != nil {
return nil, err
}
}
repoCfgDir := path.Join(cfgDir, repo.Name())
repoName := repo.Name()
scripts, err := NewScriptsFromDir(repoCfgDir,
path.Join(cfgDir, "prelude"), repo.Dir, outDir,
cfgDir, &repoName, scriptsCfg[repo.Name()])
if err != nil {
return nil, err
}
log.Infof("Loaded repository scripts at %v", repoCfgDir)
repo.Scripts = *scripts
repos = append(repos, &repo)
}
scripts, err := NewScriptsFromDir(cfgDir,
path.Join(cfgDir, "prelude"), cfgDir, outDir, cfgDir, nil, scriptsCfg["global"])
if err != nil {
return nil, err
}
scriptsSetup := scripts.Setup
for _, repo := range repos {
scriptsSetup = append(scriptsSetup, repo.Scripts.Setup...)
}
scriptsStart := scripts.Start
for _, repo := range repos {
scriptsStart = append(scriptsStart, repo.Scripts.Start...)
}
scriptsTest := scripts.Test
for _, repo := range repos {
scriptsTest = append(scriptsTest, repo.Scripts.Test...)
}
scriptsStop := scripts.Stop
for _, repo := range repos {
scriptsStop = append(scriptsStop, repo.Scripts.Stop...)
}
scriptsHooks := scripts.Hooks
for _, repo := range repos {
scriptsHooks = append(scriptsHooks, repo.Scripts.Hooks...)
}
sort.Sort(ByFileName(scriptsSetup))
sort.Sort(ByFileName(scriptsStart))
sort.Sort(ByFileName(scriptsTest))
sort.Sort(ByFileName(scriptsStop))
sort.Sort(ByFileName(scriptsHooks))
return &Repos{
Repos: repos,
Dir: reposDir,
CfgDir: cfgDir,
OutDir: outDir,
Timeouts: timeouts,
Scripts: *scripts,
scriptsSetup: scriptsSetup,
scriptsStart: scriptsStart,
scriptsTest: scriptsTest,
scriptsStop: scriptsStop,
scriptsHooks: scriptsHooks,
}, nil
}
func (rs *Repos) Update() (bool, error) {
updated := false
for _, repo := range rs.Repos {
repoUrl := repo.URL
oldHead, err := repo.HeadHash()
if err != nil {
return false, err
}
log.Infof("Updating %s", repoUrl)
wt, err := repo.GitRepo.Worktree()
if err != nil {
return false, err
}
if err := repo.GitRepo.Fetch(&git.FetchOptions{
Force: true,
RefSpecs: []config.RefSpec{"refs/*:refs/*",
"HEAD:refs/heads/HEAD"},
}); err == git.NoErrAlreadyUpToDate {
log.Infof("Repository %s already up-to-date", repoUrl)
} else if err != nil {
return false, err
}
if err := wt.Checkout(&git.CheckoutOptions{
Branch: plumbing.NewBranchReferenceName(repo.Branch),
Force: true,
}); err != nil {
return false, err
}
head, err := repo.HeadHash()
if err != nil {
return false, err
}
if oldHead != head {
updated = true
}
log.Infof("Repository %s at commit %s", repoUrl, head)
}
return updated, nil
}
func outputWrite(stdout io.ReadCloser, stderr io.ReadCloser, filePath string,
readyStr string, readyCh chan bool, endCh chan bool) {
// log.Debugf("DBG Storing script output at %s", filePath)
defer panicMain()
f, err := os.OpenFile(filePath, os.O_RDWR|os.O_CREATE, 0666)
if err != nil {
log.Panic(err)
}
defer f.Close()
lineCh := make(chan string)
stdoutEndCh := make(chan error)
stderrEndCh := make(chan error)
readLine := func(rd io.Reader, prefix string, endCh chan error) {
defer panicMain()
reader := bufio.NewReader(rd)
for {
line, err := reader.ReadString('\n')
if !strings.HasSuffix(line, "\n") {
line = fmt.Sprintf("%v\n", line)
}
lineCh <- fmt.Sprintf("%v%v", prefix, line)
if err != nil {
break
}
}
endCh <- err
}
go readLine(stdout, "stdout: ", stdoutEndCh)
go readLine(stderr, "stderr: ", stderrEndCh)
ready := false
if readyStr == "" {
ready = true
}
stdoutClosed, stderrClosed := false, false
for {
select {
case line := <-lineCh:
if !ready && strings.Contains(line, readyStr) {
readyCh <- true
ready = true
}
_, err := io.WriteString(f, line)
if err != nil {
log.Panicf("Can't write output to file %v: %v", filePath, err)
}
f.Sync()
case err := <-stdoutEndCh:
if err != nil && err != io.EOF {
log.Errorf("Process stdout error: %v", err)
}
stdoutClosed = true
if stderrClosed {
endCh <- true
return
}
case err := <-stderrEndCh:
if err != nil && err != io.EOF {
log.Errorf("Process stderr error: %v", err)
}
stderrClosed = true
if stdoutClosed {
endCh <- true
return
}
}
}
}
func (rs *Repos) ClearResults() {
clearScripts := func(s *Scripts) {
for _, script := range s.Setup {
script.Result = ResultUnk
}
for _, script := range s.Start {
script.Result = ResultUnk
}
for _, script := range s.Test {
script.Result = ResultUnk
}
for _, script := range s.Stop {
script.Result = ResultUnk
}
for _, script := range s.Hooks {
script.Result = ResultUnk
}
}
clearScripts(&rs.Scripts)
for _, repo := range rs.Repos {
clearScripts(&repo.Scripts)
}
rs.Result = ResultUnk
}
func (rs *Repos) ArchiveOld() {
curLen := 16
archiveDir := path.Join(rs.OutDir, "archive")
if err := os.MkdirAll(archiveDir, 0777); err != nil {
log.Panic(err)
}
resultDirs, err := getResultsDir(rs.OutDir)
if err != nil {
log.Panic(err)
}
if len(resultDirs) <= curLen {
return
}
for _, file := range resultDirs[curLen:] {
if err := os.Rename(path.Join(rs.OutDir, file), path.Join(archiveDir, file)); err != nil {
log.Panic(err)
}
}
}
type WriteChan chan *[]byte
func NewWriteChan() WriteChan {
return WriteChan(make(chan *[]byte))
}
func (w *WriteChan) Write(p []byte) (n int, err error) {
*w <- &p
return len(p), nil
}
func (w *WriteChan) Close() {
// close(*w)
*w <- nil
}
var dockerContainerID string
func (rs *Repos) DockerRun(cfg *Config) {
ctx := context.Background()
cli, err := client.NewClientWithOpts(client.FromEnv, client.WithVersion("1.39"))
if err != nil {
log.Panic(err)
}
cli.NegotiateAPIVersion(ctx)
if cfg.DockerCfg.Pull {
log.Infof("Pulling docker image %v", cfg.DockerCfg.Image)
rd, err := cli.ImagePull(ctx, cfg.DockerCfg.Image, types.ImagePullOptions{})
if err != nil {
log.Panic(err)
}
reader := bufio.NewReader(rd)
for {
line, err := reader.ReadString('\n')
if len(line) > 0 {
log.Debugf("docker image pull: %s", line)
}
if err != nil {
break
}
}
rd.Close()
}
info := rs.NewInfo()
containerName := fmt.Sprintf("citrus-%08d", info.Ts)
// args := []string{"/bin/sh", "+ex", "-c", "/bin/ls -l /etc/ssl/certs"}
args := []string{"/citrus/citrus", "-conf", "/citrus-cfg", "-no-web", "-no-update", "-one-shot"}
if cfg.Debug {
args = append(args, "-debug")
}
if cfg.Force {
args = append(args, "-force")
}
mounts := []mount.Mount{
{
Type: mount.TypeBind,
Source: cfg.CitrusDir,
Target: "/citrus",
ReadOnly: true,
},
{
Type: mount.TypeBind,
Source: cfg.CfgDir,
Target: "/citrus-cfg",
ReadOnly: true,
},
{
Type: mount.TypeBind,
Source: fmt.Sprintf("%s/out", cfg.WorkDir),
Target: fmt.Sprintf("%s/out", cfg.WorkDir),
},
{
Type: mount.TypeBind,
Source: fmt.Sprintf("%s/git", cfg.WorkDir),
Target: fmt.Sprintf("%s/git", cfg.WorkDir),
},
}
for source, target := range cfg.DockerCfg.Binds {
mounts = append(mounts, mount.Mount{Type: mount.TypeBind,
Source: source, Target: target, ReadOnly: true})
}
log.Infof("Creating docker container with name %s", containerName)
resp, err := cli.ContainerCreate(ctx,
&container.Config{
Hostname: "citrus",
User: "root",
WorkingDir: "/citrus",
Image: cfg.DockerCfg.Image,
Cmd: args,
Tty: true,
AttachStdout: true,
AttachStderr: true,
},
&container.HostConfig{
Mounts: mounts,
},
nil, containerName)
if err != nil {
log.Panic(err)
}
dockerContainerID = resp.ID
defer func() {
if err := cli.ContainerRemove(ctx, resp.ID,
types.ContainerRemoveOptions{Force: true}); err != nil {
log.Panic(err)
}
dockerContainerID = ""
}()
cont, err := cli.ContainerAttach(ctx, resp.ID, types.ContainerAttachOptions{
Stdout: true,
Stderr: true,
Stream: true,
})
if err != nil {
log.Panic(err)
}
log.Infof("Starting docker container with name %s, id %s", containerName, resp.ID)
if err := cli.ContainerStart(ctx, resp.ID, types.ContainerStartOptions{}); err != nil {
log.Panic(err)
}
reader := bufio.NewReader(cont.Reader)
stdLog := log.StandardLogger()
for {
line, err := reader.ReadString('\n')
if len(line) > 0 {
io.WriteString(stdLog.Out, fmt.Sprintf("DOCKER %s", line))
}
if err != nil {
break
}
}
cont.Close()
cont.CloseWrite()
statusCh, errCh := cli.ContainerWait(ctx, resp.ID, container.WaitConditionNotRunning)
select {
case err := <-errCh:
if err != nil {
log.Panic(err)
}
case status := <-statusCh:
if status.StatusCode != 0 {
log.Panicf("docker process terminated with exit code %v (%v)",
status.StatusCode, status.Error)
}
}
}
func (rs *Repos) Run() {
info := rs.NewInfo()
outDir := path.Join(rs.OutDir, fmt.Sprintf("%08d", info.Ts))
if err := os.MkdirAll(outDir, 0777); err != nil {
log.Panic(err)
}
if err := rs.StoreInfo(&info, outDir); err != nil {
log.Panic(err)
}
rs.ClearResults()
f, err := os.Create(path.Join(outDir, ".running"))
if err != nil {
log.Panic(err)
}
f.Close()
rs.run(&info, outDir)
err = os.Remove(path.Join(outDir, ".running"))
if err != nil {
log.Panic(err)
}
log.Infof("Tests %08d (%s) result: %s", info.Ts, info.TsRFC3339, rs.Result)
// rs.PrintResults()
rs.ArchiveOld()
}
// NOTE: canceling the context of a script cmd only kills the parent but not
// the children, so cancelling is not a reliable way to stop everything that
// was started. In the future, replace all cancel() by a robust Stop().
func (rs *Repos) run(info *Info, outDir string) {
defer rs.StoreMapResult(outDir)
ts := fmt.Sprintf("%08d", info.Ts)
//// Hooks
defer func() {
for _, s := range rs.scriptsHooks {
ctx, cancel := context.WithTimeout(context.Background(),
rs.Timeouts.Hook*time.Second)
defer cancel()
if err := s.Run(ctx, []string{path.Join(outDir, "info.json"),
path.Join(outDir, "result.json")}, ts, nil); err != nil {
log.Errorf("Hook script %v error: %v", s.Path(), err)
}
}
}()
//// Setup
log.Infof("--- Setup ---")
for _, s := range rs.scriptsSetup {
s.Result = ResultRun
rs.StoreMapResult(outDir)
ctx, cancel := context.WithTimeout(context.Background(),
rs.Timeouts.Setup*time.Second)
defer cancel()
if err := s.Run(ctx, nil, ts, nil); err != nil {
log.Errorf("Setup script %v error: %v", s.Path(), err)
s.Result = ResultErr
rs.Result = ResultErr
return
}
s.Result = ResultPass
rs.StoreMapResult(outDir)
}
//// Start
log.Infof("--- Start ---")
for _, s := range rs.scriptsStart {
s.Result = ResultRun
rs.StoreMapResult(outDir)
readyCh := make(chan bool)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
s.Start(ctx, nil, ts, readyCh)
select {
case <-readyCh:
s.Result = ResultReady
log.Debugf("Start script %v is ready", s.Path())
case <-time.After(rs.Timeouts.Ready * time.Second):
cancel()
log.Errorf("Start script %v timed out at ready", s.Path())
s.Result = ResultErr
rs.Result = ResultReadyErr
}
rs.StoreMapResult(outDir)
}
//// Test
if rs.Result == ResultUnk {
log.Infof("--- Test ---")
for _, s := range rs.scriptsTest {
s.Result = ResultRun
rs.StoreMapResult(outDir)
ctx, cancel := context.WithTimeout(context.Background(),
rs.Timeouts.Test*time.Second)
defer cancel()
if err := s.Run(ctx, nil, ts, nil); err != nil {
log.Errorf("Test script %v error: %v", s.Path(), err)
s.Result = ResultErr
rs.Result = ResultErr
} else {
s.Result = ResultPass
}
rs.StoreMapResult(outDir)
}
}
//// Stop
log.Infof("--- Stop ---")
// Stop Start scripts
for _, s := range rs.scriptsStart {
s.Result = ResultRun
rs.StoreMapResult(outDir)
if err := s.Stop(); err != nil {
log.Errorf("Error stopping Start script %v: %v", s.Path(), err)
s.Result = ResultErr
rs.Result = ResultErr
} else {
s.Result = ResultPass
}
rs.StoreMapResult(outDir)
}
for _, s := range rs.scriptsStop {
s.Result = ResultRun
rs.StoreMapResult(outDir)
ctx, cancel := context.WithTimeout(context.Background(),
rs.Timeouts.Stop*time.Second)
defer cancel()
if err := s.Run(ctx, nil, ts, nil); err != nil {
log.Errorf("Stop script %v error: %v", s.Path(), err)
s.Result = ResultErr
rs.Result = ResultErr
} else {
s.Result = ResultPass
}
rs.StoreMapResult(outDir)
}
if rs.Result == ResultUnk {
rs.Result = ResultPass
}
rs.StoreMapResult(outDir)
return
}
// func (rs *Repos) PrintResults() {
// printOne := func(s *Script) {
// res := "UNK "
// switch s.Result {
// case ResultPass:
// res = "PASS"
// case ResultErr:
// res = "ERR "
// }
// fmt.Printf("%v - %v\n", res, strings.TrimPrefix(s.Path, rs.ConfDir))
// }
// printLoop := func(ss []*Script) {
// for _, s := range ss {
// printOne(s)
// }
// }
// printMaybe := func(s *Script) {
// if s != nil {
// printOne(s)
// }
// }
// fmt.Println("=== Setup ===")
// printMaybe(rs.Scripts.Setup)
// for _, r := range rs.Repos {
// fmt.Printf("= %v =\n", r.Name())
// printMaybe(r.Scripts.Setup)
// }
// fmt.Println("=== Start ===")
// for _, r := range rs.Repos {
// fmt.Printf("= %v =\n", r.Name())
// printLoop(r.Scripts.Start)
// }
// fmt.Println("=== Test ===")
// for _, r := range rs.Repos {
// fmt.Printf("= %v =\n", r.Name())
// printLoop(r.Scripts.Test)
// }
// fmt.Println("=== Stop ===")
// printMaybe(rs.Scripts.Stop)
// for _, r := range rs.Repos {
// fmt.Printf("= %v =\n", r.Name())
// printMaybe(r.Scripts.Stop)
// }
// }
type PhaseResults struct {
Result map[string]Result
Repos map[string]map[string]Result
}
type MapResult struct {
Result Result
Setup PhaseResults
Start PhaseResults
Test PhaseResults
Stop PhaseResults
}
func (rs *Repos) NewMapResult() MapResult {
getPhaseResults := func(scripts []*Script) PhaseResults {
result := make(map[string]Result)
repos := make(map[string]map[string]Result)
for _, s := range scripts {
relPath := strings.Split(strings.TrimPrefix(
strings.TrimPrefix(s.Path(), rs.CfgDir), "/"), "/")
// log.Debugf("DBG NewMapResult s.Path: %v", s.Path())
// log.Debugf("DBG NewMapResult rs.CfgDir: %v", rs.CfgDir)
// log.Debugf("DBG NewMapResult relPath: %v", relPath)
if len(relPath) == 1 {
result[relPath[0]] = s.Result
} else if len(relPath) == 2 {
if _, ok := repos[relPath[0]]; !ok {
repos[relPath[0]] = make(map[string]Result)
}
repos[relPath[0]][relPath[1]] = s.Result
} else {
panic("Unexpected relPath length")
}
}
return PhaseResults{result, repos}
}
var result MapResult
result.Setup = getPhaseResults(rs.scriptsSetup)
result.Start = getPhaseResults(rs.scriptsStart)
result.Test = getPhaseResults(rs.scriptsTest)
result.Stop = getPhaseResults(rs.scriptsStop)
result.Result = rs.Result
return result
}
// StoreMapResult panics on error
func (rs *Repos) StoreMapResult(outDir string) {
mapResult := rs.NewMapResult()
resultJSON, err := json.Marshal(mapResult)
if err != nil {
log.Panic(err)
}
if err := ioutil.WriteFile(path.Join(outDir, "result.json"), resultJSON, 0666); err != nil {
log.Panic(err)
}
}
type InfoRepo struct {
CommitHash string
Branch string
URL string
}
type Info struct {
Repos []InfoRepo
Ts int64