forked from nagiesek/hcsshim
-
Notifications
You must be signed in to change notification settings - Fork 1
/
shim.go
323 lines (279 loc) · 6.85 KB
/
shim.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
package main
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net"
"os"
"strings"
"sync"
"time"
winio "github.com/Microsoft/go-winio"
"github.com/Microsoft/hcsshim/internal/appargs"
"github.com/Microsoft/hcsshim/internal/hcs"
"github.com/Microsoft/hcsshim/internal/lcow"
"github.com/Microsoft/hcsshim/internal/runhcs"
"github.com/Microsoft/hcsshim/internal/schema2"
specs "github.com/opencontainers/runtime-spec/specs-go"
"github.com/sirupsen/logrus"
"github.com/urfave/cli"
"golang.org/x/sys/windows"
)
func containerPipePath(id string) string {
return runhcs.SafePipePath("runhcs-shim-" + id)
}
func newFile(context *cli.Context, param string) *os.File {
fd := uintptr(context.Int(param))
if fd == 0 {
return nil
}
return os.NewFile(fd, "")
}
var shimCommand = cli.Command{
Name: "shim",
Usage: `launch the process and proxy stdio (do not call it outside of runhcs)`,
Hidden: true,
Flags: []cli.Flag{
&cli.IntFlag{Name: "stdin", Hidden: true},
&cli.IntFlag{Name: "stdout", Hidden: true},
&cli.IntFlag{Name: "stderr", Hidden: true},
&cli.BoolFlag{Name: "exec", Hidden: true},
cli.StringFlag{Name: "log-pipe", Hidden: true},
},
Before: appargs.Validate(argID),
Action: func(context *cli.Context) error {
logPipe := context.String("log-pipe")
if logPipe != "" {
lpc, err := winio.DialPipe(logPipe, nil)
if err != nil {
return err
}
defer lpc.Close()
logrus.SetOutput(lpc)
} else {
logrus.SetOutput(os.Stderr)
}
fatalWriter.Writer = os.Stdout
id := context.Args().First()
c, err := getContainer(id, true)
if err != nil {
return err
}
defer c.Close()
// Asynchronously wait for the container to exit.
containerExitCh := make(chan error)
go func() {
containerExitCh <- c.hc.WaitExpectedError(hcs.ErrAlreadyClosed)
}()
// Get File objects for the open stdio files passed in as arguments.
stdin := newFile(context, "stdin")
stdout := newFile(context, "stdout")
stderr := newFile(context, "stderr")
exec := context.Bool("exec")
terminateOnFailure := false
errorOut := io.WriteCloser(os.Stdout)
var spec *specs.Process
if exec {
// Read the process spec from stdin.
specj, err := ioutil.ReadAll(os.Stdin)
if err != nil {
return err
}
os.Stdin.Close()
spec = new(specs.Process)
err = json.Unmarshal(specj, spec)
if err != nil {
return err
}
} else {
// Stdin is not used.
os.Stdin.Close()
// Listen on the named pipe associated with this container.
l, err := winio.ListenPipe(c.ShimPipePath(), nil)
if err != nil {
return err
}
// Alert the parent process that initialization has completed
// successfully.
errorOut.Write(runhcs.ShimSuccess)
errorOut.Close()
fatalWriter.Writer = ioutil.Discard
// When this process exits, clear this process's pid in the registry.
defer func() {
stateKey.Set(id, keyShimPid, 0)
}()
defer func() {
if terminateOnFailure {
if err = c.hc.Terminate(); hcs.IsPending(err) {
<-containerExitCh
}
}
}()
terminateOnFailure = true
// Wait for a connection to the named pipe, exiting if the container
// exits before this happens.
var pipe net.Conn
pipeCh := make(chan error)
go func() {
var err error
pipe, err = l.Accept()
pipeCh <- err
}()
select {
case err = <-pipeCh:
if err != nil {
return err
}
case err = <-containerExitCh:
if err != nil {
return err
}
return cli.NewExitError("", 1)
}
// The next set of errors goes to the open pipe connection.
errorOut = pipe
fatalWriter.Writer = pipe
// The process spec comes from the original container spec.
spec = c.Spec.Process
}
// Create the process in the container.
var wpp *hcsschema.ProcessParameters // Windows Process Parameters
var lpp *lcow.ProcessParameters // Linux Process Parameters
var p *hcs.Process
if c.Spec.Linux == nil {
environment := make(map[string]string)
for _, v := range spec.Env {
s := strings.SplitN(v, "=", 2)
if len(s) == 2 && len(s[1]) > 0 {
environment[s[0]] = s[1]
}
}
wpp = &hcsschema.ProcessParameters{
WorkingDirectory: spec.Cwd,
EmulateConsole: spec.Terminal,
Environment: environment,
User: spec.User.Username,
}
for i, arg := range spec.Args {
e := windows.EscapeArg(arg)
if i == 0 {
wpp.CommandLine = e
} else {
wpp.CommandLine += " " + e
}
}
if spec.ConsoleSize != nil {
wpp.ConsoleSize = []int32{
int32(spec.ConsoleSize.Height),
int32(spec.ConsoleSize.Width),
}
}
wpp.CreateStdInPipe = stdin != nil
wpp.CreateStdOutPipe = stdout != nil
wpp.CreateStdErrPipe = stderr != nil
p, err = c.hc.CreateProcess(wpp)
} else {
lpp = &lcow.ProcessParameters{}
if exec {
lpp.OCIProcess = spec
}
lpp.CreateStdInPipe = stdin != nil
lpp.CreateStdOutPipe = stdout != nil
lpp.CreateStdErrPipe = stderr != nil
p, err = c.hc.CreateProcess(lpp)
}
if err != nil {
return err
}
cstdin, cstdout, cstderr, err := p.Stdio()
if err != nil {
return err
}
if !exec {
err = stateKey.Set(c.ID, keyInitPid, p.Pid())
if err != nil {
return err
}
}
// Store the Guest pid map
err = stateKey.Set(c.ID, fmt.Sprintf(keyPidMapFmt, os.Getpid()), p.Pid())
if err != nil {
return err
}
defer func() {
// Remove the Guest pid map when this process is cleaned up
stateKey.Clear(c.ID, fmt.Sprintf(keyPidMapFmt, os.Getpid()))
}()
terminateOnFailure = false
// Alert the connected process that the process was launched
// successfully.
errorOut.Write(runhcs.ShimSuccess)
errorOut.Close()
fatalWriter.Writer = ioutil.Discard
// Relay stdio.
var wg sync.WaitGroup
if cstdin != nil {
go func() {
io.Copy(cstdin, stdin)
cstdin.Close()
p.CloseStdin()
}()
}
if cstdout != nil {
wg.Add(1)
go func() {
io.Copy(stdout, cstdout)
stdout.Close()
cstdout.Close()
wg.Done()
}()
}
if cstderr != nil {
wg.Add(1)
go func() {
io.Copy(stderr, cstderr)
stderr.Close()
cstderr.Close()
wg.Done()
}()
}
err = p.Wait()
wg.Wait()
// Attempt to get the exit code from the process.
code := 1
if err == nil {
code, err = p.ExitCode()
if err != nil {
code = 1
}
}
if !exec {
// Shutdown the container, waiting 5 minutes before terminating is
// forcefully.
const shutdownTimeout = time.Minute * 5
waited := false
err = c.hc.Shutdown()
if hcs.IsPending(err) {
select {
case err = <-containerExitCh:
waited = true
case <-time.After(shutdownTimeout):
err = hcs.ErrTimeout
}
}
if hcs.IsAlreadyStopped(err) {
err = nil
}
if err != nil {
err = c.hc.Terminate()
if waited {
err = c.hc.Wait()
} else {
err = <-containerExitCh
}
}
}
return cli.NewExitError("", code)
},
}