Debian Codegraph @

cmd/containerd-shim-runc-v2/runc/container.go

raw
1 //go:build linux
2
3 /*
4 Copyright The containerd Authors.
5
6 Licensed under the Apache License, Version 2.0 (the "License");
7 you may not use this file except in compliance with the License.
8 You may obtain a copy of the License at
9
10 http://www.apache.org/licenses/LICENSE-2.0
11
12 Unless required by applicable law or agreed to in writing, software
13 distributed under the License is distributed on an "AS IS" BASIS,
14 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 See the License for the specific language governing permissions and
16 limitations under the License.
17 */
18
19 package runc
20
21 import (
22 "context"
23 "encoding/json"
24 "fmt"
25 "os"
26 "path/filepath"
27 "sync"
28
29 "github.com/containerd/cgroups/v3"
30 "github.com/containerd/cgroups/v3/cgroup1"
31 cgroupsv2 "github.com/containerd/cgroups/v3/cgroup2"
32 "github.com/containerd/console"
33 "github.com/containerd/containerd/api/runtime/task/v3"
34 "github.com/containerd/containerd/api/types/runc/options"
35 "github.com/containerd/errdefs"
36 "github.com/containerd/errdefs/pkg/errgrpc"
37 "github.com/containerd/log"
38 "github.com/containerd/typeurl/v2"
39
40 "github.com/containerd/containerd/v2/cmd/containerd-shim-runc-v2/process"
41 "github.com/containerd/containerd/v2/core/mount"
42 "github.com/containerd/containerd/v2/pkg/namespaces"
43 "github.com/containerd/containerd/v2/pkg/stdio"
44 )
45
46 // NewContainer returns a new runc container
47 func NewContainer(ctx context.Context, platform stdio.Platform, r *task.CreateTaskRequest) (_ *Container, retErr error) {
48 ns, err := namespaces.NamespaceRequired(ctx)
49 if err != nil {
50 return nil, fmt.Errorf("create namespace: %w", err)
51 }
52
53 opts := &options.Options{}
54 if r.Options.GetValue() != nil {
55 v, err := typeurl.UnmarshalAny(r.Options)
56 if err != nil {
57 return nil, err
58 }
59 if v != nil {
60 opts = v.(*options.Options)
61 }
62 }
63
64 var pmounts []process.Mount
65 for _, m := range r.Rootfs {
66 pmounts = append(pmounts, process.Mount{
67 Type: m.Type,
68 Source: m.Source,
69 Target: m.Target,
70 Options: m.Options,
71 })
72 }
73
74 rootfs := ""
75 if len(pmounts) > 0 {
76 rootfs = filepath.Join(r.Bundle, "rootfs")
77 if err := os.Mkdir(rootfs, 0711); err != nil && !os.IsExist(err) {
78 return nil, err
79 }
80 }
81
82 config := &process.CreateConfig{
83 ID: r.ID,
84 Bundle: r.Bundle,
85 Runtime: opts.BinaryName,
86 Rootfs: pmounts,
87 Terminal: r.Terminal,
88 Stdin: r.Stdin,
89 Stdout: r.Stdout,
90 Stderr: r.Stderr,
91 Checkpoint: r.Checkpoint,
92 ParentCheckpoint: r.ParentCheckpoint,
93 Options: r.Options,
94 }
95
96 if err := WriteOptions(r.Bundle, opts); err != nil {
97 return nil, err
98 }
99 // For historical reason, we write opts.BinaryName as well as the entire opts
100 if err := WriteRuntime(r.Bundle, opts.BinaryName); err != nil {
101 return nil, err
102 }
103
104 var mounts []mount.Mount
105 for _, pm := range pmounts {
106 mounts = append(mounts, mount.Mount{
107 Type: pm.Type,
108 Source: pm.Source,
109 Target: pm.Target,
110 Options: pm.Options,
111 })
112 }
113 defer func() {
114 if retErr != nil {
115 if err := mount.UnmountMounts(mounts, rootfs, 0); err != nil {
116 log.G(ctx).WithError(err).Warn("failed to cleanup rootfs mount")
117 }
118 }
119 }()
120 if err := mount.All(mounts, rootfs); err != nil {
121 return nil, fmt.Errorf("failed to mount rootfs component: %w", err)
122 }
123
124 p, err := newInit(
125 ctx,
126 r.Bundle,
127 filepath.Join(r.Bundle, "work"),
128 ns,
129 platform,
130 config,
131 opts,
132 rootfs,
133 )
134 if err != nil {
135 return nil, errgrpc.ToGRPC(err)
136 }
137 if err := p.Create(ctx, config); err != nil {
138 return nil, errgrpc.ToGRPC(err)
139 }
140 container := &Container{
141 ID: r.ID,
142 Bundle: r.Bundle,
143 process: p,
144 processes: make(map[string]process.Process),
145 reservedProcess: make(map[string]struct{}),
146 }
147 pid := p.Pid()
148 if pid > 0 {
149 if cg, err := loadProcessCgroup(ctx, pid); err == nil {
150 container.cgroup = cg
151 }
152 }
153 return container, nil
154 }
155
156 const optionsFilename = "options.json"
157
158 // ReadOptions reads the option information from the path.
159 // When the file does not exist, ReadOptions returns nil without an error.
160 func ReadOptions(path string) (*options.Options, error) {
161 filePath := filepath.Join(path, optionsFilename)
162 if _, err := os.Stat(filePath); err != nil {
163 if os.IsNotExist(err) {
164 return nil, nil
165 }
166 return nil, err
167 }
168
169 data, err := os.ReadFile(filePath)
170 if err != nil {
171 return nil, err
172 }
173 var opts options.Options
174 if err := json.Unmarshal(data, &opts); err != nil {
175 return nil, err
176 }
177 return &opts, nil
178 }
179
180 // WriteOptions writes the options information into the path
181 func WriteOptions(path string, opts *options.Options) error {
182 data, err := json.Marshal(opts)
183 if err != nil {
184 return err
185 }
186 return os.WriteFile(filepath.Join(path, optionsFilename), data, 0600)
187 }
188
189 // ReadRuntime reads the runtime information from the path
190 func ReadRuntime(path string) (string, error) {
191 data, err := os.ReadFile(filepath.Join(path, "runtime"))
192 if err != nil {
193 return "", err
194 }
195 return string(data), nil
196 }
197
198 // WriteRuntime writes the runtime information into the path
199 func WriteRuntime(path, runtime string) error {
200 return os.WriteFile(filepath.Join(path, "runtime"), []byte(runtime), 0600)
201 }
202
203 func newInit(ctx context.Context, path, workDir, namespace string, platform stdio.Platform,
204 r *process.CreateConfig, options *options.Options, rootfs string) (*process.Init, error) {
205 runtime := process.NewRunc(options.Root, path, namespace, options.BinaryName, options.SystemdCgroup)
206 p := process.New(r.ID, runtime, stdio.Stdio{
207 Stdin: r.Stdin,
208 Stdout: r.Stdout,
209 Stderr: r.Stderr,
210 Terminal: r.Terminal,
211 })
212 p.Bundle = r.Bundle
213 p.Platform = platform
214 p.Rootfs = rootfs
215 p.WorkDir = workDir
216 p.IoUID = int(options.IoUid)
217 p.IoGID = int(options.IoGid)
218 p.NoPivotRoot = options.NoPivotRoot
219 p.NoNewKeyring = options.NoNewKeyring
220 p.CriuWorkPath = options.CriuWorkPath
221 if p.CriuWorkPath == "" {
222 // if criu work path not set, use container WorkDir
223 p.CriuWorkPath = p.WorkDir
224 }
225 return p, nil
226 }
227
228 // Container for operating on a runc container and its processes
229 type Container struct {
230 mu sync.Mutex
231
232 // ID of the container
233 ID string
234 // Bundle path
235 Bundle string
236
237 // cgroup is either cgroups.Cgroup or *cgroupsv2.Manager
238 cgroup interface{}
239 process process.Process
240 processes map[string]process.Process
241 reservedProcess map[string]struct{}
242 }
243
244 // All processes in the container
245 func (c *Container) All() (o []process.Process) {
246 c.mu.Lock()
247 defer c.mu.Unlock()
248
249 for _, p := range c.processes {
250 o = append(o, p)
251 }
252 if c.process != nil {
253 o = append(o, c.process)
254 }
255 return o
256 }
257
258 // ExecdProcesses added to the container
259 func (c *Container) ExecdProcesses() (o []process.Process) {
260 c.mu.Lock()
261 defer c.mu.Unlock()
262 for _, p := range c.processes {
263 o = append(o, p)
264 }
265 return o
266 }
267
268 // Pid of the main process of a container
269 func (c *Container) Pid() int {
270 c.mu.Lock()
271 defer c.mu.Unlock()
272 return c.process.Pid()
273 }
274
275 // Cgroup of the container
276 func (c *Container) Cgroup() interface{} {
277 c.mu.Lock()
278 defer c.mu.Unlock()
279 return c.cgroup
280 }
281
282 // CgroupSet sets the cgroup to the container
283 func (c *Container) CgroupSet(cg interface{}) {
284 c.mu.Lock()
285 c.cgroup = cg
286 c.mu.Unlock()
287 }
288
289 // Process returns the process by id
290 func (c *Container) Process(id string) (process.Process, error) {
291 c.mu.Lock()
292 defer c.mu.Unlock()
293 if id == "" {
294 if c.process == nil {
295 return nil, fmt.Errorf("container must be created: %w", errdefs.ErrFailedPrecondition)
296 }
297 return c.process, nil
298 }
299 p, ok := c.processes[id]
300 if !ok {
301 return nil, fmt.Errorf("process does not exist %s: %w", id, errdefs.ErrNotFound)
302 }
303 return p, nil
304 }
305
306 // ReserveProcess checks for the existence of an id and atomically
307 // reserves the process id if it does not already exist
308 //
309 // Returns true if the process id was successfully reserved and a
310 // cancel func to release the reservation
311 func (c *Container) ReserveProcess(id string) (bool, func()) {
312 c.mu.Lock()
313 defer c.mu.Unlock()
314
315 if _, ok := c.processes[id]; ok {
316 return false, nil
317 }
318 if _, ok := c.reservedProcess[id]; ok {
319 return false, nil
320 }
321 c.reservedProcess[id] = struct{}{}
322 return true, func() {
323 c.mu.Lock()
324 defer c.mu.Unlock()
325 delete(c.reservedProcess, id)
326 }
327 }
328
329 // ProcessAdd adds a new process to the container
330 func (c *Container) ProcessAdd(process process.Process) {
331 c.mu.Lock()
332 defer c.mu.Unlock()
333
334 delete(c.reservedProcess, process.ID())
335 c.processes[process.ID()] = process
336 }
337
338 // ProcessRemove removes the process by id from the container
339 func (c *Container) ProcessRemove(id string) {
340 c.mu.Lock()
341 defer c.mu.Unlock()
342 delete(c.processes, id)
343 }
344
345 // Start a container process
346 func (c *Container) Start(ctx context.Context, r *task.StartRequest) (process.Process, error) {
347 p, err := c.Process(r.ExecID)
348 if err != nil {
349 return nil, err
350 }
351 if err := p.Start(ctx); err != nil {
352 return p, err
353 }
354 if c.Cgroup() == nil && p.Pid() > 0 {
355 if cg, err := loadProcessCgroup(ctx, p.Pid()); err == nil {
356 c.cgroup = cg
357 }
358 }
359 return p, nil
360 }
361
362 // Delete the container or a process by id
363 func (c *Container) Delete(ctx context.Context, r *task.DeleteRequest) (process.Process, error) {
364 p, err := c.Process(r.ExecID)
365 if err != nil {
366 return nil, err
367 }
368 if err := p.Delete(ctx); err != nil {
369 return nil, err
370 }
371 if r.ExecID != "" {
372 c.ProcessRemove(r.ExecID)
373 }
374 return p, nil
375 }
376
377 // Exec an additional process
378 func (c *Container) Exec(ctx context.Context, r *task.ExecProcessRequest) (process.Process, error) {
379 process, err := c.process.(*process.Init).Exec(ctx, c.Bundle, &process.ExecConfig{
380 ID: r.ExecID,
381 Terminal: r.Terminal,
382 Stdin: r.Stdin,
383 Stdout: r.Stdout,
384 Stderr: r.Stderr,
385 Spec: r.Spec,
386 })
387 if err != nil {
388 return nil, err
389 }
390 c.ProcessAdd(process)
391 return process, nil
392 }
393
394 // Pause the container
395 func (c *Container) Pause(ctx context.Context) error {
396 return c.process.(*process.Init).Pause(ctx)
397 }
398
399 // Resume the container
400 func (c *Container) Resume(ctx context.Context) error {
401 return c.process.(*process.Init).Resume(ctx)
402 }
403
404 // ResizePty of a process
405 func (c *Container) ResizePty(ctx context.Context, r *task.ResizePtyRequest) error {
406 p, err := c.Process(r.ExecID)
407 if err != nil {
408 return err
409 }
410 ws := console.WinSize{
411 Width: uint16(r.Width),
412 Height: uint16(r.Height),
413 }
414 return p.Resize(ws)
415 }
416
417 // Kill a process
418 func (c *Container) Kill(ctx context.Context, r *task.KillRequest) error {
419 p, err := c.Process(r.ExecID)
420 if err != nil {
421 return err
422 }
423 return p.Kill(ctx, r.Signal, r.All)
424 }
425
426 // CloseIO of a process
427 func (c *Container) CloseIO(ctx context.Context, r *task.CloseIORequest) error {
428 p, err := c.Process(r.ExecID)
429 if err != nil {
430 return err
431 }
432 if stdin := p.Stdin(); stdin != nil {
433 if err := stdin.Close(); err != nil {
434 return fmt.Errorf("close stdin: %w", err)
435 }
436 }
437 return nil
438 }
439
440 // Checkpoint the container
441 func (c *Container) Checkpoint(ctx context.Context, r *task.CheckpointTaskRequest) error {
442 p, err := c.Process("")
443 if err != nil {
444 return err
445 }
446
447 var opts options.CheckpointOptions
448 if r.Options != nil {
449 if err := typeurl.UnmarshalTo(r.Options, &opts); err != nil {
450 return err
451 }
452 }
453 return p.(*process.Init).Checkpoint(ctx, &process.CheckpointConfig{
454 Path: r.Path,
455 Exit: opts.Exit,
456 AllowOpenTCP: opts.OpenTcp,
457 AllowExternalUnixSockets: opts.ExternalUnixSockets,
458 AllowTerminal: opts.Terminal,
459 FileLocks: opts.FileLocks,
460 EmptyNamespaces: opts.EmptyNamespaces,
461 WorkDir: opts.WorkPath,
462 })
463 }
464
465 // Update the resource information of a running container
466 func (c *Container) Update(ctx context.Context, r *task.UpdateTaskRequest) error {
467 p, err := c.Process("")
468 if err != nil {
469 return err
470 }
471 return p.(*process.Init).Update(ctx, r.Resources)
472 }
473
474 // HasPid returns true if the container owns a specific pid
475 func (c *Container) HasPid(pid int) bool {
476 if c.Pid() == pid {
477 return true
478 }
479 for _, p := range c.All() {
480 if p.Pid() == pid {
481 return true
482 }
483 }
484 return false
485 }
486
487 func loadProcessCgroup(ctx context.Context, pid int) (cg interface{}, err error) {
488 if cgroups.Mode() == cgroups.Unified {
489 g, err := cgroupsv2.PidGroupPath(pid)
490 if err != nil {
491 log.G(ctx).WithError(err).Errorf("loading cgroup2 for %d", pid)
492 return nil, err
493 }
494 cg, err = cgroupsv2.Load(g)
495 if err != nil {
496 log.G(ctx).WithError(err).Errorf("loading cgroup2 for %d", pid)
497 return nil, err
498 }
499 } else {
500 cg, err = cgroup1.Load(cgroup1.PidPath(pid))
501 if err != nil {
502 log.G(ctx).WithError(err).Errorf("loading cgroup for %d", pid)
503 return nil, err
504 }
505 }
506 return cg, nil
507 }