This repository has been archived by the owner on May 6, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 70
/
Copy pathexec.go
273 lines (235 loc) · 6.98 KB
/
exec.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
// Copyright (c) 2014,2015,2016 Docker, Inc.
// Copyright (c) 2017 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"syscall"
vc "github.com/kata-containers/runtime/virtcontainers"
"github.com/kata-containers/runtime/virtcontainers/pkg/oci"
specs "github.com/opencontainers/runtime-spec/specs-go"
"github.com/urfave/cli"
)
type execParams struct {
ociProcess oci.CompatOCIProcess
cID string
pidFile string
console string
consoleSock string
processLabel string
noSubreaper bool
detach bool
}
var execCLICommand = cli.Command{
Name: "exec",
Usage: "Execute new process inside the container",
ArgsUsage: `<container-id> <command> [command options] || -p process.json <container-id>
<container-id> is the name for the instance of the container and <command>
is the command to be executed in the container. <command> can't be empty
unless a "-p" flag provided.
EXAMPLE:
If the container is configured to run the linux ps command the following
will output a list of processes running in the container:
# ` + name + ` <container-id> ps`,
Flags: []cli.Flag{
cli.StringFlag{
Name: "console",
Usage: "path to a pseudo terminal",
},
cli.StringFlag{
Name: "console-socket",
Value: "",
Usage: "path to an AF_UNIX socket which will receive a file descriptor referencing the master end of the console's pseudoterminal",
},
cli.StringFlag{
Name: "cwd",
Usage: "current working directory in the container",
},
cli.StringSliceFlag{
Name: "env, e",
Usage: "set environment variables",
},
cli.BoolFlag{
Name: "tty, t",
Usage: "allocate a pseudo-TTY",
},
cli.StringFlag{
Name: "user, u",
Usage: "UID (format: <uid>[:<gid>])",
},
cli.StringFlag{
Name: "process, p",
Usage: "path to the process.json",
},
cli.BoolFlag{
Name: "detach,d",
Usage: "detach from the container's process",
},
cli.StringFlag{
Name: "pid-file",
Value: "",
Usage: "specify the file to write the process id to",
},
cli.StringFlag{
Name: "process-label",
Usage: "set the asm process label for the process commonly used with selinux",
},
cli.StringFlag{
Name: "apparmor",
Usage: "set the apparmor profile for the process",
},
cli.BoolFlag{
Name: "no-new-privs",
Usage: "set the no new privileges value for the process",
},
cli.StringSliceFlag{
Name: "cap, c",
Value: &cli.StringSlice{},
Usage: "add a capability to the bounding set for the process",
},
cli.BoolFlag{
Name: "no-subreaper",
Usage: "disable the use of the subreaper used to reap reparented processes",
Hidden: true,
},
},
Action: func(context *cli.Context) error {
return execute(context)
},
}
func generateExecParams(context *cli.Context, specProcess *oci.CompatOCIProcess) (execParams, error) {
ctxArgs := context.Args()
params := execParams{
cID: ctxArgs.First(),
pidFile: context.String("pid-file"),
console: context.String("console"),
consoleSock: context.String("console-socket"),
detach: context.Bool("detach"),
processLabel: context.String("process-label"),
noSubreaper: context.Bool("no-subreaper"),
}
if context.String("process") != "" {
var ociProcess oci.CompatOCIProcess
fileContent, err := ioutil.ReadFile(context.String("process"))
if err != nil {
return execParams{}, err
}
if err := json.Unmarshal(fileContent, &ociProcess); err != nil {
return execParams{}, err
}
params.ociProcess = ociProcess
} else {
params.ociProcess = *specProcess
// Override terminal
if context.IsSet("tty") {
params.ociProcess.Terminal = context.Bool("tty")
}
// Override user
if context.String("user") != "" {
params.ociProcess.User = specs.User{
// This field is a Windows-only field
// according to the specification. However, it
// is abused here to allow the username
// specified in the OCI runtime configuration
// file to be overridden by a CLI request.
Username: context.String("user"),
}
}
// Override env
params.ociProcess.Env = append(params.ociProcess.Env, context.StringSlice("env")...)
// Override cwd
if context.String("cwd") != "" {
params.ociProcess.Cwd = context.String("cwd")
}
// Override no-new-privs
if context.IsSet("no-new-privs") {
params.ociProcess.NoNewPrivileges = context.Bool("no-new-privs")
}
// Override apparmor
if context.String("apparmor") != "" {
params.ociProcess.ApparmorProfile = context.String("apparmor")
}
params.ociProcess.Args = ctxArgs.Tail()
}
return params, nil
}
func execute(context *cli.Context) error {
containerID := context.Args().First()
status, podID, err := getExistingContainerInfo(containerID)
if err != nil {
return err
}
// Retrieve OCI spec configuration.
ociSpec, err := oci.GetOCIConfig(status)
if err != nil {
return err
}
params, err := generateExecParams(context, ociSpec.Process)
if err != nil {
return err
}
params.cID = status.ID
// container MUST be running
if status.State.State != vc.StateRunning {
return fmt.Errorf("Container %s is not running", params.cID)
}
envVars, err := oci.EnvVars(params.ociProcess.Env)
if err != nil {
return err
}
consolePath, err := setupConsole(params.console, params.consoleSock)
if err != nil {
return err
}
user := fmt.Sprintf("%d:%d", params.ociProcess.User.UID, params.ociProcess.User.GID)
if params.ociProcess.User.Username != "" {
user = params.ociProcess.User.Username
}
cmd := vc.Cmd{
Args: params.ociProcess.Args,
Envs: envVars,
WorkDir: params.ociProcess.Cwd,
User: user,
Interactive: params.ociProcess.Terminal,
Console: consolePath,
Detach: noNeedForOutput(params.detach, params.ociProcess.Terminal),
}
_, _, process, err := vci.EnterContainer(podID, params.cID, cmd)
if err != nil {
return err
}
// Creation of PID file has to be the last thing done in the exec
// because containerd considers the exec to have finished starting
// after this file is created.
if err := createPIDFile(params.pidFile, process.Pid); err != nil {
return err
}
if params.detach {
return nil
}
p, err := os.FindProcess(process.Pid)
if err != nil {
return err
}
ps, err := p.Wait()
if err != nil {
return fmt.Errorf("Process state %s, container info %+v: %v",
ps.String(), status, err)
}
// Exit code has to be forwarded in this case.
return cli.NewExitError("", ps.Sys().(syscall.WaitStatus).ExitStatus())
}