-
Notifications
You must be signed in to change notification settings - Fork 86
/
local.go
125 lines (98 loc) · 2.5 KB
/
local.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
package backend
import (
"bytes"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"time"
gocontext "context"
"github.com/travis-ci/worker/config"
)
var (
errNoScriptUploaded = fmt.Errorf("no script uploaded")
localHelp = map[string]string{
"SCRIPTS_DIR": "directory where generated scripts will be written",
}
)
func init() {
Register("local", "Local", localHelp, newLocalProvider)
}
type localProvider struct {
cfg *config.ProviderConfig
scriptsDir string
}
func newLocalProvider(cfg *config.ProviderConfig) (Provider, error) {
scriptsDir, _ := os.Getwd()
if cfg.IsSet("SCRIPTS_DIR") {
scriptsDir = cfg.Get("SCRIPTS_DIR")
}
if scriptsDir == "" {
scriptsDir = os.TempDir()
}
return &localProvider{cfg: cfg, scriptsDir: scriptsDir}, nil
}
func (p *localProvider) Start(ctx gocontext.Context, startAttributes *StartAttributes) (Instance, error) {
return newLocalInstance(p)
}
func (p *localProvider) Setup(ctx gocontext.Context) error { return nil }
type localInstance struct {
p *localProvider
scriptPath string
}
func newLocalInstance(p *localProvider) (*localInstance, error) {
return &localInstance{
p: p,
}, nil
}
func (i *localInstance) UploadScript(ctx gocontext.Context, script []byte) error {
scriptPath := filepath.Join(i.p.scriptsDir, fmt.Sprintf("build-%v.sh", time.Now().UTC().UnixNano()))
f, err := os.Create(scriptPath)
if err != nil {
return err
}
i.scriptPath = scriptPath
scriptBuf := bytes.NewBuffer(script)
_, err = io.Copy(f, scriptBuf)
return err
}
func (i *localInstance) RunScript(ctx gocontext.Context, writer io.Writer) (*RunResult, error) {
if i.scriptPath == "" {
return &RunResult{Completed: false}, errNoScriptUploaded
}
cmd := exec.Command("bash", i.scriptPath)
cmd.Stdout = writer
cmd.Stderr = writer
err := cmd.Start()
if err != nil {
return &RunResult{Completed: false}, err
}
errChan := make(chan error)
go func() {
errChan <- cmd.Wait()
}()
select {
case err := <-errChan:
if err != nil {
return &RunResult{Completed: false}, err
}
return &RunResult{Completed: true}, nil
case <-ctx.Done():
err = ctx.Err()
if err != nil {
return &RunResult{Completed: false}, err
}
return &RunResult{Completed: true}, nil
}
}
func (i *localInstance) Stop(ctx gocontext.Context) error {
return nil
}
func (i *localInstance) ID() string {
return fmt.Sprintf("local:%s", i.scriptPath)
}
func (i *localInstance) ImageName() string {
return ""
}
func (i *localInstance) StartupDuration() time.Duration { return zeroDuration }