-
Notifications
You must be signed in to change notification settings - Fork 14
/
main.go
252 lines (216 loc) · 5.3 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
package main
import (
"fmt"
"golang.org/x/crypto/ssh/terminal"
"log"
"os"
"regexp"
"strconv"
"time"
docker "github.com/fsouza/go-dockerclient"
)
const timeoutStatusCode = 124
// RunDexecContainer runs an anonymous Docker container with a Docker Exec
// image, mounting the specified sources and includes and passing the
// list of sources and arguments to the entrypoint.
func RunDexecContainer(cliParser CLI) int {
options := cliParser.Options
shouldClean := len(options[CleanFlag]) > 0
updateImage := len(options[UpdateFlag]) > 0
client, err := docker.NewClientFromEnv()
if err != nil {
log.Fatal(err)
}
if shouldClean {
images, err := client.ListImages(docker.ListImagesOptions{
All: true,
})
if err != nil {
log.Fatal(err)
}
for _, image := range images {
for _, tag := range image.RepoTags {
repoRegex := regexp.MustCompile("^dexec/lang-[^:\\s]+(:.+)?$")
if match := repoRegex.MatchString(tag); match {
if err := client.RemoveImage(image.ID); err != nil {
log.Fatalf("cannot remove image %s", image.ID)
}
}
}
}
}
dexecImage, err := ImageFromOptions(options)
if err != nil {
log.Fatal(err)
}
dockerImage := fmt.Sprintf("%s:%s", dexecImage.Image, dexecImage.Version)
if err = FetchImage(
dexecImage.Image,
dexecImage.Version,
updateImage,
client); err != nil {
log.Fatal(err)
}
var sourceBasenames []string
for _, source := range options[Source] {
basename, _ := ExtractBasenameAndPermission(source)
sourceBasenames = append(sourceBasenames, []string{basename}...)
}
entrypointArgs := JoinStringSlices(
sourceBasenames,
AddPrefix(options[BuildArg], "-b"),
AddPrefix(options[Arg], "-a"),
)
readFromStdin := false
if stat, _ := os.Stdin.Stat(); (stat.Mode() & os.ModeCharDevice) == 0 {
readFromStdin = true
} else {
fd := int(os.Stdin.Fd())
if terminal.IsTerminal(fd) {
oldState, err := terminal.MakeRaw(fd)
if err != nil {
log.Fatalf("could not make terminal raw: %s", err)
}
defer func() {
if err := terminal.Restore(fd, oldState); err != nil {
log.Fatalf("couldn't restore terminal: %s", err)
}
}()
}
}
container, err := client.CreateContainer(docker.CreateContainerOptions{
Config: &docker.Config{
Image: dockerImage,
Cmd: entrypointArgs,
StdinOnce: true,
OpenStdin: true,
AttachStdin: true,
AttachStderr: true,
AttachStdout: true,
Tty: !readFromStdin,
},
HostConfig: &docker.HostConfig{
Binds: BuildVolumeArgs(
RetrievePath(options[TargetDir]),
append(options[Source], options[Include]...)),
},
})
if err != nil {
log.Fatal(err)
}
defer func() {
if err = client.RemoveContainer(docker.RemoveContainerOptions{
ID: container.ID,
}); err != nil {
log.Fatal(err)
}
}()
success := make(chan struct{})
waiter, err := client.AttachToContainerNonBlocking(docker.AttachToContainerOptions{
Container: container.ID,
InputStream: os.Stdin,
OutputStream: os.Stdout,
ErrorStream: os.Stderr,
Stream: true,
Stdin: true,
Stdout: true,
Stderr: true,
Logs: false,
RawTerminal: !readFromStdin,
Success: success,
})
if err != nil {
log.Fatalf("unable to send attach to container request: %s", err)
}
<-success
close(success)
if err = client.StartContainer(container.ID, &docker.HostConfig{}); err != nil {
log.Fatalf("unable to start container: %s", err)
}
if timeout, ok := options[Timeout]; ok && len(timeout) == 1 {
type ClientRunResult struct {
Code int
Error error
}
done := make(chan ClientRunResult)
go func() {
if err := waiter.Wait(); err != nil {
log.Fatalf("unable to attach to container: %s", err)
}
code, err := client.WaitContainer(container.ID)
result := ClientRunResult{
code,
err,
}
done <- result
}()
num, _ := strconv.Atoi(timeout[0])
t := time.Duration(num) * time.Second
timeout := time.After(t)
select {
case <-timeout:
err := client.KillContainer(docker.KillContainerOptions{ID: container.ID})
if err != nil {
log.Fatal(err)
}
return timeoutStatusCode
case result := <-done:
code := result.Code
err := result.Error
if err != nil {
log.Fatal(err)
}
return code
}
} else {
if err := waiter.Wait(); err != nil {
log.Fatalf("unable to attach to container: %s", err)
}
code, err := client.WaitContainer(container.ID)
if err != nil {
log.Fatal(err)
}
return code
}
}
func validate(cliParser CLI) bool {
options := cliParser.Options
hasVersionFlag := len(options[VersionFlag]) == 1
hasSources := len(options[Source]) > 0
shouldClean := len(options[CleanFlag]) > 0
if hasSources || shouldClean {
return true
}
if hasVersionFlag {
DisplayVersion(cliParser.Filename)
return false
}
DisplayHelp(cliParser.Filename)
return false
}
func validateDocker() error {
client, err := docker.NewClientFromEnv()
if err != nil {
return err
}
ping := make(chan error, 1)
go func() {
ping <- client.Ping()
}()
select {
case err := <-ping:
return err
case <-time.After(5 * time.Second):
return fmt.Errorf("request to Docker host timed out")
}
}
func main() {
cliParser := ParseOsArgs(os.Args)
if validate(cliParser) {
if err := validateDocker(); err != nil {
log.Fatal(err)
} else {
os.Exit(RunDexecContainer(cliParser))
}
}
}