-
Notifications
You must be signed in to change notification settings - Fork 8
/
invoke.go
340 lines (280 loc) · 9.31 KB
/
invoke.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
// Copyright 2022 Namespace Labs Inc; All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
package docker
import (
"context"
"errors"
"fmt"
"io"
"os/user"
"path/filepath"
"strings"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/network"
"github.com/docker/docker/api/types/strslice"
"github.com/docker/docker/client"
dockernames "github.com/docker/docker/daemon/names"
"github.com/docker/docker/errdefs"
"github.com/docker/docker/pkg/stdcopy"
"github.com/muesli/cancelreader"
specs "github.com/opencontainers/image-spec/specs-go/v1"
"namespacelabs.dev/foundation/framework/rpcerrors/multierr"
"namespacelabs.dev/foundation/internal/compute"
"namespacelabs.dev/foundation/internal/console"
"namespacelabs.dev/foundation/internal/fnerrors"
"namespacelabs.dev/foundation/internal/parsing/devhost"
"namespacelabs.dev/foundation/internal/runtime/rtypes"
"namespacelabs.dev/foundation/std/tasks"
"namespacelabs.dev/go-ids"
)
type ToolRuntime struct{}
func Impl() ToolRuntime { return ToolRuntime{} }
func (r ToolRuntime) CanConsumePublicImages() bool {
return false // This is not quite true but it's a simplification for now. // XXX support docker pull.
}
func (r ToolRuntime) Run(ctx context.Context, opts rtypes.RunToolOpts) error {
return r.RunWithOpts(ctx, opts, nil)
}
func (r ToolRuntime) RunWithOpts(ctx context.Context, opts rtypes.RunToolOpts, onStart func()) error {
digest, err := opts.Image.Digest()
if err != nil {
return err
}
config, err := opts.Image.ConfigName()
if err != nil {
return err
}
return tasks.Action("container.execute").
LogLevel(2).
Arg("command", opts.Command).
Arg("imageName", opts.ImageName).
Arg("digest", digest).
Arg("config", config).
Arg("args", opts.Args).
Run(ctx, func(ctx context.Context) error {
return runImpl(ctx, opts, onStart)
})
}
func HostPlatform() specs.Platform {
p := devhost.RuntimePlatform()
p.OS = "linux" // We always run on linux.
return p
}
func (r ToolRuntime) HostPlatform(context.Context) (specs.Platform, error) {
return HostPlatform(), nil
}
func runImpl(ctx context.Context, opts rtypes.RunToolOpts, onStart func()) error {
var cmd []string
cmd = append(cmd, opts.Command...)
cmd = append(cmd, opts.Args...)
containerConfig := &container.Config{
WorkingDir: opts.WorkingDir,
Tty: opts.AllocateTTY,
AttachStdout: true, // Stdout, Stderr is always attached, even if discarded later (see below).
AttachStderr: true,
Cmd: strslice.StrSlice(cmd),
}
if opts.Stdin != nil {
containerConfig.AttachStdin = true
containerConfig.OpenStdin = true
// After we're done with Attach, the container should observe a EOF on Stdin.
containerConfig.StdinOnce = true
}
if opts.RunAsUser {
uid, err := user.Current()
if err != nil {
return err
}
containerConfig.User = fmt.Sprintf("%s:%s", uid.Uid, uid.Gid)
}
for _, kv := range opts.Env {
if kv.ExperimentalFromSecret != "" {
return fnerrors.New("docker: doesn't support env.ExperimentalFromSecret")
}
if kv.FromSecretRef != nil {
return fnerrors.New("docker: doesn't support env.FromSecretRef")
}
if kv.FromServiceEndpoint != nil {
return fnerrors.New("docker: doesn't support env.FromServiceEndpoint")
}
if kv.FromResourceField != nil {
return fnerrors.New("docker: doesn't support env.FromResourceField")
}
containerConfig.Env = append(containerConfig.Env, fmt.Sprintf("%s=%s", kv.Name, kv.Value))
}
hostConfig := &container.HostConfig{
AutoRemove: true,
}
if opts.NoNetworking {
hostConfig.NetworkMode = "none"
}
for _, m := range opts.Mounts {
var absPath string
if m.HostPath != "" {
if !filepath.IsAbs(m.HostPath) {
return fnerrors.New("host_path must be absolute, got %q", m.HostPath)
}
absPath = m.HostPath
} else {
if opts.MountAbsRoot == "" {
return fnerrors.InternalError("container.exec: LocalPath mount without MountAbsRoot")
}
absPath = filepath.Join(opts.MountAbsRoot, m.LocalPath)
if _, err := filepath.Rel(opts.MountAbsRoot, absPath); err != nil {
return err
}
}
hostConfig.Binds = append(hostConfig.Binds, absPath+":"+m.ContainerPath)
}
computable, err := writeImageOnce(opts.ImageName, opts.Image)
if err != nil {
return err
}
config, err := compute.GetValue(ctx, computable)
if err != nil {
return err
}
containerConfig.Image = config.String()
cli, err := NewClient()
if err != nil {
return err
}
networkConfig := &network.NetworkingConfig{}
name := ""
if len(opts.Command) > 0 {
label := strings.Join(opts.Command, "-")
label = strings.ReplaceAll(label, "/", "")
if dockernames.RestrictedNamePattern.MatchString(label) {
// generate unique ID to avoid collisions
id := ids.NewRandomBase32ID(6)
name = fmt.Sprintf("ns-%s-%s", label, id)
} else {
fmt.Fprintf(console.Debug(ctx), "%s is not a valid docker container name", label)
}
}
created, err := cli.ContainerCreate(ctx, containerConfig, hostConfig, networkConfig, nil, name)
if err != nil {
return fnerrors.New("failed to create container: %w", err)
}
fmt.Fprintf(console.Debug(ctx), "docker: created container %q (image=%s args=%v)\n",
created.ID, containerConfig.Image, containerConfig.Cmd)
compute.On(ctx).Cleanup(tasks.Action("docker.container.remove"), func(ctx context.Context) error {
if err := cli.ContainerRemove(ctx, created.ID, types.ContainerRemoveOptions{}); err != nil {
// If the docker daemon is already removing the container, because
// e.g. it has returned from execution, then we may observe a
// conflict with `removal of container XYZ is already in progress`.
// We ignore that error here.
if !client.IsErrNotFound(err) && !errdefs.IsConflict(err) {
return fnerrors.New("failed to remove container: %w", err)
}
}
return nil
})
resp, err := cli.ContainerAttach(ctx, created.ID, types.ContainerAttachOptions{
Stream: true,
Stdin: containerConfig.AttachStdin,
Stdout: containerConfig.AttachStdout,
Stderr: containerConfig.AttachStderr,
})
if err != nil {
return fnerrors.New("failed to attach to container: %w", err)
}
if err := cli.ContainerStart(ctx, created.ID, types.ContainerStartOptions{}); err != nil {
return fnerrors.New("failed to start container: %w", err)
}
var errChs []chan error
var stdin cancelreader.CancelReader
if opts.Stdin != nil {
inerr := make(chan error)
errChs = append(errChs, inerr)
stdin, err = cancelreader.NewReader(opts.Stdin)
if err != nil {
return err
}
go func() {
defer close(inerr)
// This would typically block forever, but we cancel the reader
// below when the container returns. That path also handles
// cancelation as the ContainerWait() call should observe
// cancelation, which will then lead to canceling reads.
if _, err := io.Copy(resp.Conn, stdin); err != nil {
if !errors.Is(err, cancelreader.ErrCanceled) {
inerr <- err
}
return
}
// If we reached expected EOF, signal that to the underlying container.
if err := resp.CloseWrite(); err != nil {
fmt.Fprintln(console.Errors(ctx), "Failed to close stdin", err)
}
}()
}
go func() {
outerr := make(chan error)
defer close(outerr)
errChs = append(errChs, outerr)
stdout := writerOrDiscard(opts.Stdout)
stderr := writerOrDiscard(opts.Stderr)
// Following Docker's implementation here. When AllocateTTY is set,
// Docker multiplexes both output streams into stdout.
if opts.AllocateTTY {
_, err := io.Copy(stdout, resp.Reader)
outerr <- err
} else {
_, err := stdcopy.StdCopy(stdout, stderr, resp.Reader)
outerr <- err
}
}()
if onStart != nil {
// Signal OnStart after the various IO-related pipes started getting established.
onStart()
}
waitErr := func() error {
if stdin != nil {
// Very important to cancel stdin when we're done, else we'll block forever.
defer stdin.Cancel()
}
// After we're done waiting, we close the connection, which will lead
// the stdout/stderr goroutine to exit.
defer resp.Close()
results, errs := cli.ContainerWait(ctx, created.ID, container.WaitConditionNextExit)
select {
case result := <-results:
// An error is used to signal the parent in order to comply with the
// Executor protocol. We want the first error to be recorded as
// primary, and in this case that would be the observed exit code.
// If for example we fail to read from a stream after observing exit
// code 0, we should still not return an error.
return fnerrors.ExitWithCode(fmt.Errorf("docker: container exit code %d", result.StatusCode), int(result.StatusCode))
case err := <-errs:
if client.IsErrNotFound(err) {
// We schedule containers with AutoRemove so they might disappear before we get a chance to wait for them.
return nil
}
return err
}
}()
// Wait until the goroutines are done.
goroutineErrs := make([]error, len(errChs))
for i, errCh := range errChs {
goroutineErrs[i] = <-errCh
}
if waitErr != nil {
switch err := waitErr.(type) {
case fnerrors.ExitError:
if err.ExitCode() == 0 {
return nil
}
}
return fnerrors.New("failed to wait for container: %w", waitErr)
}
return multierr.New(goroutineErrs...)
}
func writerOrDiscard(w io.Writer) io.Writer {
if w == nil {
return io.Discard
}
return w
}