Debian Codegraph @

cmd/ctr-remote/commands/flags.go

raw
1 /*
2 Copyright The containerd Authors.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 package commands
18
19 import (
20 "bytes"
21 gocontext "context"
22 "encoding/csv"
23 "encoding/json"
24 "fmt"
25 "os"
26 "path/filepath"
27 "runtime"
28 "strings"
29
30 "github.com/containerd/containerd"
31 "github.com/containerd/containerd/containers"
32 "github.com/containerd/containerd/content"
33 "github.com/containerd/containerd/contrib/nvidia"
34 "github.com/containerd/containerd/images"
35 "github.com/containerd/containerd/oci"
36 "github.com/containerd/containerd/pkg/netns"
37 gocni "github.com/containerd/go-cni"
38 "github.com/hashicorp/go-multierror"
39 imagespec "github.com/opencontainers/image-spec/specs-go/v1"
40 runtimespec "github.com/opencontainers/runtime-spec/specs-go"
41 "github.com/rs/xid"
42 "github.com/sirupsen/logrus"
43 "github.com/urfave/cli"
44 )
45
46 const netnsMountDir = "/var/run/netns"
47
48 var samplerFlags = []cli.Flag{
49 cli.BoolFlag{
50 Name: "terminal,t",
51 Usage: "enable terminal for sample container. must be specified with i option",
52 },
53 cli.BoolFlag{
54 Name: "i",
55 Usage: "attach stdin to the container",
56 },
57 cli.IntFlag{
58 Name: "period",
59 Usage: "time period to monitor access log",
60 Value: defaultPeriod,
61 },
62 cli.StringFlag{
63 Name: "user",
64 Usage: "user/group name to override image's default config(user[:group])",
65 },
66 cli.StringFlag{
67 Name: "cwd",
68 Usage: "working dir to override image's default config",
69 },
70 cli.StringFlag{
71 Name: "args",
72 Usage: "command arguments to override image's default config(in JSON array)",
73 },
74 cli.StringFlag{
75 Name: "entrypoint",
76 Usage: "entrypoint to override image's default config(in JSON array)",
77 },
78 cli.StringSliceFlag{
79 Name: "env",
80 Usage: "environment valulable to add or override to the image's default config",
81 },
82 cli.StringFlag{
83 Name: "env-file",
84 Usage: "specify additional container environment variables in a file(i.e. FOO=bar, one per line)",
85 },
86 cli.StringSliceFlag{
87 Name: "mount",
88 Usage: "additional mounts for the container (e.g. type=foo,source=/path,destination=/target,options=bind)",
89 },
90 cli.StringFlag{
91 Name: "dns-nameservers",
92 Usage: "comma-separated nameservers added to the container's /etc/resolv.conf",
93 Value: "8.8.8.8",
94 },
95 cli.StringFlag{
96 Name: "dns-search-domains",
97 Usage: "comma-separated search domains added to the container's /etc/resolv.conf",
98 },
99 cli.StringFlag{
100 Name: "dns-options",
101 Usage: "comma-separated options added to the container's /etc/resolv.conf",
102 },
103 cli.StringFlag{
104 Name: "add-hosts",
105 Usage: "comma-separated hosts configuration (host:IP) added to container's /etc/hosts",
106 },
107 cli.BoolFlag{
108 Name: "cni",
109 Usage: "enable CNI-based networking",
110 },
111 cli.StringFlag{
112 Name: "cni-plugin-conf-dir",
113 Usage: "path to the CNI plugins configuration directory",
114 },
115 cli.StringFlag{
116 Name: "cni-plugin-dir",
117 Usage: "path to the CNI plugins binary directory",
118 },
119 cli.IntSliceFlag{
120 Name: "gpus",
121 Usage: "add gpus to the container",
122 },
123 cli.BoolFlag{
124 Name: "net-host",
125 Usage: "enable host networking in the container",
126 },
127 }
128
129 func getSpecOpts(clicontext *cli.Context) func(image containerd.Image, rootfs string) (opts []oci.SpecOpts, done func() error, rErr error) {
130 return func(image containerd.Image, rootfs string) (opts []oci.SpecOpts, done func() error, rErr error) {
131 var cleanups []func() error
132 done = func() (allErr error) {
133 for i := len(cleanups) - 1; i >= 0; i-- {
134 if err := cleanups[i](); err != nil {
135 allErr = multierror.Append(allErr, err)
136 }
137 }
138 return
139 }
140 defer func() {
141 if rErr != nil {
142 if err := done(); err != nil {
143 rErr = fmt.Errorf("failed to cleanup: %w", rErr)
144 }
145 }
146 }()
147
148 entrypointOpt, err := withEntrypointArgs(clicontext, image)
149 if err != nil {
150 rErr = fmt.Errorf("failed to parse entrypoint and arg flags: %w", err)
151 return
152 }
153 resolverOpt, cleanup, err := withResolveConfig(clicontext)
154 if err != nil {
155 rErr = fmt.Errorf("failed to parse DNS-related flags: %w", err)
156 return
157 }
158 cleanups = append(cleanups, cleanup)
159 var mounts []runtimespec.Mount
160 for _, mount := range clicontext.StringSlice("mount") {
161 m, err := parseMountFlag(mount)
162 if err != nil {
163 rErr = fmt.Errorf("failed to parse mount flag %q: %w", mount, err)
164 return
165 }
166 mounts = append(mounts, m)
167 }
168 opts = append(opts,
169 oci.WithDefaultSpec(),
170 oci.WithDefaultUnixDevices,
171 oci.WithRootFSPath(rootfs),
172 oci.WithImageConfig(image),
173 oci.WithEnv(clicontext.StringSlice("env")),
174 oci.WithMounts(mounts),
175 resolverOpt,
176 entrypointOpt,
177 )
178 if envFile := clicontext.String("env-file"); envFile != "" {
179 opts = append(opts, oci.WithEnvFile(envFile))
180 }
181 if username := clicontext.String("user"); username != "" {
182 opts = append(opts, oci.WithUser(username))
183 }
184 if cwd := clicontext.String("cwd"); cwd != "" {
185 opts = append(opts, oci.WithProcessCwd(cwd))
186 }
187 if clicontext.Bool("terminal") {
188 if !clicontext.Bool("i") {
189 rErr = fmt.Errorf("terminal flag must be specified with \"-i\"")
190 return
191 }
192 opts = append(opts, oci.WithTTY)
193 }
194 if clicontext.Bool("cni") {
195 var nOpt oci.SpecOpts
196 nOpt, cleanup, err = withCNI(clicontext)
197 if err != nil {
198 rErr = fmt.Errorf("failed to parse CNI-related flags: %w", err)
199 return
200 }
201 cleanups = append(cleanups, cleanup)
202 opts = append(opts, nOpt)
203 }
204 if clicontext.Bool("net-host") {
205 if runtime.GOOS == "windows" {
206 logrus.Warn("option --net-host is not supported on Windows")
207 } else {
208 opts = append(opts, oci.WithHostNamespace(runtimespec.NetworkNamespace), oci.WithHostHostsFile, oci.WithHostResolvconf)
209 }
210 }
211 if clicontext.IsSet("gpus") {
212 if runtime.GOOS == "windows" {
213 logrus.Warn("option --gpus is not supported on Windows")
214 } else {
215 opts = append(opts, nvidia.WithGPUs(nvidia.WithDevices(clicontext.IntSlice("gpus")...), nvidia.WithAllCapabilities))
216 }
217 }
218
219 return
220 }
221 }
222
223 func withEntrypointArgs(clicontext *cli.Context, image containerd.Image) (oci.SpecOpts, error) {
224 var eFlag []string
225 if eStr := clicontext.String("entrypoint"); eStr != "" {
226 if err := json.Unmarshal([]byte(eStr), &eFlag); err != nil {
227 return nil, fmt.Errorf("invalid option \"entrypoint\": %w", err)
228 }
229 }
230 var aFlag []string
231 if aStr := clicontext.String("args"); aStr != "" {
232 if err := json.Unmarshal([]byte(aStr), &aFlag); err != nil {
233 return nil, fmt.Errorf("invalid option \"args\": %w", err)
234 }
235 }
236 return func(ctx gocontext.Context, client oci.Client, container *containers.Container, s *runtimespec.Spec) error {
237 configDesc, err := image.Config(ctx)
238 if err != nil {
239 return err
240 }
241 var ociimage imagespec.Image
242 switch configDesc.MediaType {
243 case imagespec.MediaTypeImageConfig, images.MediaTypeDockerSchema2Config:
244 p, err := content.ReadBlob(ctx, image.ContentStore(), configDesc)
245 if err != nil {
246 return err
247 }
248 if err := json.Unmarshal(p, &ociimage); err != nil {
249 return err
250 }
251 default:
252 return fmt.Errorf("unknown image config media type %s", configDesc.MediaType)
253 }
254 entrypoint := ociimage.Config.Entrypoint
255 if len(eFlag) > 0 {
256 entrypoint = eFlag
257 }
258 args := ociimage.Config.Cmd
259 if len(aFlag) > 0 {
260 args = aFlag
261 }
262 return oci.WithProcessArgs(append(entrypoint, args...)...)(ctx, client, container, s)
263 }, nil
264 }
265
266 func withCNI(clicontext *cli.Context) (specOpt oci.SpecOpts, done func() error, rErr error) {
267 var cleanups []func() error
268 done = func() (allErr error) {
269 for i := len(cleanups) - 1; i >= 0; i-- {
270 if err := cleanups[i](); err != nil {
271 allErr = multierror.Append(allErr, err)
272 }
273 }
274 return
275 }
276 defer func() {
277 if rErr != nil {
278 if err := done(); err != nil {
279 rErr = fmt.Errorf("failed to cleanup: %w", rErr)
280 }
281 }
282 }()
283
284 // Create a new network namespace for configuring it with CNI plugins
285 ns, err := netns.NewNetNS(netnsMountDir)
286 if err != nil {
287 rErr = fmt.Errorf("failed to prepare netns: %w", err)
288 return
289 }
290 cleanups = append(cleanups, ns.Remove)
291
292 // Configure the namespace with CNI plugins
293 var cniopts []gocni.Opt
294 if cdir := clicontext.String("cni-plugin-conf-dir"); cdir != "" {
295 cniopts = append(cniopts, gocni.WithPluginConfDir(cdir))
296 }
297 if pdir := clicontext.String("cni-plugin-dir"); pdir != "" {
298 cniopts = append(cniopts, gocni.WithPluginDir([]string{pdir}))
299 }
300 // The first-found configration file will be effective
301 // TODO: Should we make the number of reading files configurable?
302 cniopts = append(cniopts, gocni.WithDefaultConf)
303 network, err := gocni.New(cniopts...)
304 if err != nil {
305 rErr = fmt.Errorf("failed to prepare CNI plugins: %w", err)
306 return
307 }
308 id := xid.New().String()
309 ctx := gocontext.Background()
310 if _, err := network.Setup(ctx, id, ns.GetPath()); err != nil {
311 rErr = fmt.Errorf("failed to setup netns with CNI plugins: %w", err)
312 return
313 }
314 cleanups = append(cleanups, func() error {
315 return network.Remove(ctx, id, ns.GetPath())
316 })
317
318 // Make the container use this network namespace
319 return oci.WithLinuxNamespace(runtimespec.LinuxNamespace{
320 Type: runtimespec.NetworkNamespace,
321 Path: ns.GetPath(),
322 }), done, nil
323 }
324
325 func withResolveConfig(clicontext *cli.Context) (specOpt oci.SpecOpts, cleanup func() error, rErr error) {
326 defer func() {
327 if rErr != nil {
328 if err := cleanup(); err != nil {
329 rErr = fmt.Errorf("failed to cleanup: %w", rErr)
330 }
331 }
332 }()
333
334 extrahosts, nameservers, searches, dnsopts, err := parseResolveFlag(clicontext)
335 if err != nil {
336 return nil, nil, err
337 }
338
339 // Generate /etc/hosts and /etc/resolv.conf
340 resolvDir, err := os.MkdirTemp("", "tmpetc")
341 if err != nil {
342 return nil, nil, err
343 }
344 cleanup = func() error { return os.RemoveAll(resolvDir) }
345 var (
346 etcHostsPath = filepath.Join(resolvDir, "hosts")
347 etcResolvConfPath = filepath.Join(resolvDir, "resolv.conf")
348 buf = new(bytes.Buffer)
349 )
350 for _, n := range nameservers {
351 if _, err := fmt.Fprintf(buf, "nameserver %s\n", n); err != nil {
352 rErr = fmt.Errorf("failed to prepare nameserver of /etc/resolv.conf: %w", err)
353 return
354 }
355 }
356
357 if len(searches) > 0 {
358 _, err := fmt.Fprintf(buf, "search %s\n", strings.Join(searches, " "))
359 if err != nil {
360 rErr = fmt.Errorf("failed to prepare search contents of /etc/resolv.conf: %w", err)
361 return
362 }
363 }
364 if len(dnsopts) > 0 {
365 _, err := fmt.Fprintf(buf, "options %s\n", strings.Join(dnsopts, " "))
366 if err != nil {
367 rErr = fmt.Errorf("failed to prepare options contents of /etc/resolv.conf: %w", err)
368 return
369 }
370 }
371 if err := os.WriteFile(etcResolvConfPath, buf.Bytes(), 0644); err != nil {
372 rErr = fmt.Errorf("failed to write contents to /etc/resolv.conf: %w", err)
373 return
374 }
375 buf.Reset() // Reusing for /etc/hosts
376 for _, h := range []struct {
377 host string
378 ip string
379 }{
380 // Configuration compatible to docker's config
381 // https://github.com/moby/libnetwork/blob/535ef365dc1dd82a5135803a58bc6198a3b9aa27/etchosts/etchosts.go#L28-L36
382 {"localhost", "127.0.0.1"},
383 {"localhost ip6-localhost ip6-loopback", "::1"},
384 {"ip6-localnet", "fe00::0"},
385 {"ip6-mcastprefix", "ff00::0"},
386 {"ip6-allnodes", "ff02::1"},
387 {"ip6-allrouters", "ff02::2"},
388 } {
389 if _, err := fmt.Fprintf(buf, "%s\t%s\n", h.ip, h.host); err != nil {
390 rErr = fmt.Errorf("failed to write default hosts to /etc/hosts: %w", err)
391 return
392 }
393 }
394 for _, h := range extrahosts {
395 parts := strings.SplitN(h, ":", 2) // host:IP
396 if len(parts) != 2 {
397 rErr = fmt.Errorf("cannot parse %q as extra host; must be \"host:IP\"", h)
398 return
399 }
400 // TODO: Validate them
401 if _, err := fmt.Fprintf(buf, "%s\t%s\n", parts[1], parts[0]); err != nil {
402 rErr = fmt.Errorf("failed to write extra hosts to /etc/hosts: %w", err)
403 return
404 }
405 }
406 if err := os.WriteFile(etcHostsPath, buf.Bytes(), 0644); err != nil {
407 rErr = fmt.Errorf("failed to write contents to /etc/hosts: %w", err)
408 return
409 }
410
411 return oci.WithMounts([]runtimespec.Mount{
412 {
413 Destination: "/etc/resolv.conf",
414 Source: etcResolvConfPath,
415 Options: []string{"bind"},
416 },
417 {
418 Destination: "/etc/hosts",
419 Source: etcHostsPath,
420 Options: []string{"bind"},
421 },
422 }), cleanup, nil
423
424 }
425
426 // parseMountFlag parses a mount string in the form "type=foo,source=/path,destination=/target,options=rbind:rw"
427 func parseMountFlag(m string) (runtimespec.Mount, error) {
428 mount := runtimespec.Mount{}
429 r := csv.NewReader(strings.NewReader(m))
430
431 fields, err := r.Read()
432 if err != nil {
433 return mount, err
434 }
435
436 for _, field := range fields {
437 v := strings.Split(field, "=")
438 if len(v) != 2 {
439 return mount, fmt.Errorf("invalid mount specification: expected key=val")
440 }
441
442 key := v[0]
443 val := v[1]
444 switch key {
445 case "type":
446 mount.Type = val
447 case "source", "src":
448 mount.Source = val
449 case "destination", "dst":
450 mount.Destination = val
451 case "options":
452 mount.Options = strings.Split(val, ":")
453 default:
454 return mount, fmt.Errorf("mount option %q not supported", key)
455 }
456 }
457
458 return mount, nil
459 }
460
461 func parseResolveFlag(clicontext *cli.Context) (hosts []string, nameservers []string, searches []string, dnsopts []string, _ error) {
462 if nFlag := clicontext.String("dns-nameservers"); nFlag != "" {
463 fields, err := csv.NewReader(strings.NewReader(nFlag)).Read()
464 if err != nil {
465 return nil, nil, nil, nil, err
466 }
467 nameservers = append(nameservers, fields...)
468 }
469 if sFlag := clicontext.String("dns-search-domains"); sFlag != "" {
470 fields, err := csv.NewReader(strings.NewReader(sFlag)).Read()
471 if err != nil {
472 return nil, nil, nil, nil, err
473 }
474 searches = append(searches, fields...)
475 }
476 if oFlag := clicontext.String("dns-options"); oFlag != "" {
477 fields, err := csv.NewReader(strings.NewReader(oFlag)).Read()
478 if err != nil {
479 return nil, nil, nil, nil, err
480 }
481 dnsopts = append(dnsopts, fields...)
482 }
483 if hFlag := clicontext.String("add-hosts"); hFlag != "" {
484 fields, err := csv.NewReader(strings.NewReader(hFlag)).Read()
485 if err != nil {
486 return nil, nil, nil, nil, err
487 }
488 hosts = append(hosts, fields...)
489 }
490 return
491 }