Debian Codegraph @

cmd/containerd-shim-runc-v2/process/init.go

raw
1 //go:build !windows
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 process
20
21 import (
22 "context"
23 "encoding/json"
24 "fmt"
25 "io"
26 "os"
27 "path/filepath"
28 "strings"
29 "sync"
30 "sync/atomic"
31 "time"
32
33 "github.com/containerd/console"
34 "github.com/containerd/containerd/v2/core/mount"
35 google_protobuf "github.com/containerd/containerd/v2/pkg/protobuf/types"
36 "github.com/containerd/containerd/v2/pkg/stdio"
37 "github.com/containerd/fifo"
38 runc "github.com/containerd/go-runc"
39 "github.com/containerd/log"
40 specs "github.com/opencontainers/runtime-spec/specs-go"
41 "golang.org/x/sys/unix"
42 )
43
44 // Init represents an initial process for a container
45 type Init struct {
46 wg sync.WaitGroup
47 initState initState
48
49 // mu is used to ensure that `Start()` and `Exited()` calls return in
50 // the right order when invoked in separate goroutines.
51 // This is the case within the shim implementation as it makes use of
52 // the reaper interface.
53 mu sync.Mutex
54
55 waitBlock chan struct{}
56
57 WorkDir string
58
59 id string
60 Bundle string
61 console console.Console
62 Platform stdio.Platform
63 io *processIO
64 runtime *runc.Runc
65 // pausing preserves the pausing state.
66 pausing atomic.Bool
67 status int
68 exited time.Time
69 pid int
70 closers []io.Closer
71 stdin io.Closer
72 stdio stdio.Stdio
73 Rootfs string
74 IoUID int
75 IoGID int
76 NoPivotRoot bool
77 NoNewKeyring bool
78 CriuWorkPath string
79 }
80
81 // NewRunc returns a new runc instance for a process
82 func NewRunc(root, path, namespace, runtime string, systemd bool) *runc.Runc {
83 if root == "" {
84 root = RuncRoot
85 }
86 return &runc.Runc{
87 Command: runtime,
88 Log: filepath.Join(path, "log.json"),
89 LogFormat: runc.JSON,
90 PdeathSignal: unix.SIGKILL,
91 Root: filepath.Join(root, namespace),
92 SystemdCgroup: systemd,
93 }
94 }
95
96 // New returns a new process
97 func New(id string, runtime *runc.Runc, stdio stdio.Stdio) *Init {
98 p := &Init{
99 id: id,
100 runtime: runtime,
101 stdio: stdio,
102 status: 0,
103 waitBlock: make(chan struct{}),
104 }
105 p.initState = &createdState{p: p}
106 return p
107 }
108
109 // Create the process with the provided config
110 func (p *Init) Create(ctx context.Context, r *CreateConfig) (retError error) {
111 var (
112 err error
113 socket *runc.Socket
114 pio *processIO
115 pidFile = newPidFile(p.Bundle)
116 )
117
118 if r.Terminal {
119 if socket, err = runc.NewTempConsoleSocket(); err != nil {
120 return fmt.Errorf("failed to create OCI runtime console socket: %w", err)
121 }
122 defer socket.Close()
123 } else {
124 if pio, err = createIO(ctx, p.id, p.IoUID, p.IoGID, p.stdio); err != nil {
125 return fmt.Errorf("failed to create init process I/O: %w", err)
126 }
127 p.io = pio
128 defer func() {
129 if retError != nil && p.io != nil {
130 p.io.Close()
131 }
132 }()
133 }
134 if r.Checkpoint != "" {
135 return p.createCheckpointedState(r, pidFile)
136 }
137 opts := &runc.CreateOpts{
138 PidFile: pidFile.Path(),
139 NoPivot: p.NoPivotRoot,
140 NoNewKeyring: p.NoNewKeyring,
141 }
142 if p.io != nil {
143 opts.IO = p.io.IO()
144 }
145 if socket != nil {
146 opts.ConsoleSocket = socket
147 }
148
149 if err := p.runtime.Create(ctx, r.ID, r.Bundle, opts); err != nil {
150 return p.runtimeError(err, "OCI runtime create failed")
151 }
152 if r.Stdin != "" {
153 if err := p.openStdin(r.Stdin); err != nil {
154 return err
155 }
156 }
157 ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
158 defer cancel()
159 if socket != nil {
160 console, err := socket.ReceiveMaster()
161 if err != nil {
162 return fmt.Errorf("failed to retrieve console master: %w", err)
163 }
164 console, err = p.Platform.CopyConsole(ctx, console, p.id, r.Stdin, r.Stdout, r.Stderr, &p.wg)
165 if err != nil {
166 return fmt.Errorf("failed to start console copy: %w", err)
167 }
168 p.console = console
169 } else {
170 if err := pio.Copy(ctx, &p.wg); err != nil {
171 return fmt.Errorf("failed to start io pipe copy: %w", err)
172 }
173 }
174 pid, err := pidFile.Read()
175 if err != nil {
176 return fmt.Errorf("failed to retrieve OCI runtime container pid: %w", err)
177 }
178 p.pid = pid
179 return nil
180 }
181
182 func (p *Init) openStdin(path string) error {
183 sc, err := fifo.OpenFifo(context.Background(), path, unix.O_WRONLY|unix.O_NONBLOCK, 0)
184 if err != nil {
185 return fmt.Errorf("failed to open stdin fifo %s: %w", path, err)
186 }
187 p.stdin = sc
188 p.closers = append(p.closers, sc)
189 return nil
190 }
191
192 func (p *Init) createCheckpointedState(r *CreateConfig, pidFile *pidFile) error {
193 opts := &runc.RestoreOpts{
194 CheckpointOpts: runc.CheckpointOpts{
195 ImagePath: r.Checkpoint,
196 WorkDir: p.CriuWorkPath,
197 ParentPath: r.ParentCheckpoint,
198 },
199 PidFile: pidFile.Path(),
200 NoPivot: p.NoPivotRoot,
201 Detach: true,
202 NoSubreaper: true,
203 }
204
205 if p.io != nil {
206 opts.IO = p.io.IO()
207 }
208
209 p.initState = &createdCheckpointState{
210 p: p,
211 opts: opts,
212 }
213 return nil
214 }
215
216 // Wait for the process to exit
217 func (p *Init) Wait() {
218 <-p.waitBlock
219 }
220
221 // ID of the process
222 func (p *Init) ID() string {
223 return p.id
224 }
225
226 // Pid of the process
227 func (p *Init) Pid() int {
228 return p.pid
229 }
230
231 // ExitStatus of the process
232 func (p *Init) ExitStatus() int {
233 p.mu.Lock()
234 defer p.mu.Unlock()
235
236 return p.status
237 }
238
239 // ExitedAt at time when the process exited
240 func (p *Init) ExitedAt() time.Time {
241 p.mu.Lock()
242 defer p.mu.Unlock()
243
244 return p.exited
245 }
246
247 // Status of the process
248 func (p *Init) Status(ctx context.Context) (string, error) {
249 if p.pausing.Load() {
250 return "pausing", nil
251 }
252
253 p.mu.Lock()
254 defer p.mu.Unlock()
255
256 return p.initState.Status(ctx)
257 }
258
259 // Start the init process
260 func (p *Init) Start(ctx context.Context) error {
261 p.mu.Lock()
262 defer p.mu.Unlock()
263
264 return p.initState.Start(ctx)
265 }
266
267 func (p *Init) start(ctx context.Context) error {
268 err := p.runtime.Start(ctx, p.id)
269 return p.runtimeError(err, "OCI runtime start failed")
270 }
271
272 // SetExited of the init process with the next status
273 func (p *Init) SetExited(status int) {
274 p.mu.Lock()
275 defer p.mu.Unlock()
276
277 p.initState.SetExited(status)
278 }
279
280 func (p *Init) setExited(status int) {
281 p.exited = time.Now()
282 p.status = status
283 p.Platform.ShutdownConsole(context.Background(), p.console)
284 close(p.waitBlock)
285 }
286
287 // Delete the init process
288 func (p *Init) Delete(ctx context.Context) error {
289 p.mu.Lock()
290 defer p.mu.Unlock()
291
292 return p.initState.Delete(ctx)
293 }
294
295 func (p *Init) delete(ctx context.Context) error {
296 if err := waitTimeout(ctx, &p.wg, 10*time.Second); err != nil {
297 log.G(ctx).WithError(err).Errorf("failed to drain init process %s io", p.id)
298 }
299 err := p.runtime.Delete(ctx, p.id, nil)
300 // ignore errors if a runtime has already deleted the process
301 // but we still hold metadata and pipes
302 //
303 // this is common during a checkpoint, runc will delete the container state
304 // after a checkpoint and the container will no longer exist within runc
305 if err != nil {
306 if strings.Contains(err.Error(), "does not exist") {
307 err = nil
308 } else {
309 err = p.runtimeError(err, "failed to delete task")
310 }
311 }
312 if p.io != nil {
313 for _, c := range p.closers {
314 c.Close()
315 }
316 p.io.Close()
317 }
318 if err2 := mount.UnmountRecursive(p.Rootfs, 0); err2 != nil {
319 log.G(ctx).WithError(err2).Warn("failed to cleanup rootfs mount")
320 if err == nil {
321 err = fmt.Errorf("failed rootfs umount: %w", err2)
322 }
323 }
324 return err
325 }
326
327 // Resize the init processes console
328 func (p *Init) Resize(ws console.WinSize) error {
329 p.mu.Lock()
330 defer p.mu.Unlock()
331
332 if p.console == nil {
333 return nil
334 }
335 return p.console.Resize(ws)
336 }
337
338 // Pause the init process and all its child processes
339 func (p *Init) Pause(ctx context.Context) error {
340 p.mu.Lock()
341 defer p.mu.Unlock()
342
343 return p.initState.Pause(ctx)
344 }
345
346 // Resume the init process and all its child processes
347 func (p *Init) Resume(ctx context.Context) error {
348 p.mu.Lock()
349 defer p.mu.Unlock()
350
351 return p.initState.Resume(ctx)
352 }
353
354 // Kill the init process
355 func (p *Init) Kill(ctx context.Context, signal uint32, all bool) error {
356 p.mu.Lock()
357 defer p.mu.Unlock()
358
359 return p.initState.Kill(ctx, signal, all)
360 }
361
362 func (p *Init) kill(ctx context.Context, signal uint32, all bool) error {
363 err := p.runtime.Kill(ctx, p.id, int(signal), &runc.KillOpts{
364 All: all,
365 })
366 return checkKillError(err)
367 }
368
369 // KillAll processes belonging to the init process
370 func (p *Init) KillAll(ctx context.Context) error {
371 p.mu.Lock()
372 defer p.mu.Unlock()
373
374 err := p.runtime.Kill(ctx, p.id, int(unix.SIGKILL), &runc.KillOpts{
375 All: true,
376 })
377 return p.runtimeError(err, "OCI runtime killall failed")
378 }
379
380 // Stdin of the process
381 func (p *Init) Stdin() io.Closer {
382 return p.stdin
383 }
384
385 // Runtime returns the OCI runtime configured for the init process
386 func (p *Init) Runtime() *runc.Runc {
387 return p.runtime
388 }
389
390 // Exec returns a new child process
391 func (p *Init) Exec(ctx context.Context, path string, r *ExecConfig) (Process, error) {
392 p.mu.Lock()
393 defer p.mu.Unlock()
394
395 return p.initState.Exec(ctx, path, r)
396 }
397
398 // exec returns a new exec'd process
399 func (p *Init) exec(ctx context.Context, path string, r *ExecConfig) (Process, error) {
400 // process exec request
401 var spec specs.Process
402 if err := json.Unmarshal(r.Spec.Value, &spec); err != nil {
403 return nil, err
404 }
405 spec.Terminal = r.Terminal
406
407 e := &execProcess{
408 id: r.ID,
409 path: path,
410 parent: p,
411 spec: spec,
412 stdio: stdio.Stdio{
413 Stdin: r.Stdin,
414 Stdout: r.Stdout,
415 Stderr: r.Stderr,
416 Terminal: r.Terminal,
417 },
418 waitBlock: make(chan struct{}),
419 }
420 e.execState = &execCreatedState{p: e}
421 return e, nil
422 }
423
424 // Checkpoint the init process
425 func (p *Init) Checkpoint(ctx context.Context, r *CheckpointConfig) error {
426 p.mu.Lock()
427 defer p.mu.Unlock()
428
429 return p.initState.Checkpoint(ctx, r)
430 }
431
432 func (p *Init) checkpoint(ctx context.Context, r *CheckpointConfig) error {
433 var actions []runc.CheckpointAction
434 if !r.Exit {
435 actions = append(actions, runc.LeaveRunning)
436 }
437 // keep criu work directory if criu work dir is set
438 work := r.WorkDir
439 if work == "" {
440 work = filepath.Join(p.WorkDir, "criu-work")
441 defer os.RemoveAll(work)
442 }
443 if err := p.runtime.Checkpoint(ctx, p.id, &runc.CheckpointOpts{
444 WorkDir: work,
445 ImagePath: r.Path,
446 AllowOpenTCP: r.AllowOpenTCP,
447 AllowExternalUnixSockets: r.AllowExternalUnixSockets,
448 AllowTerminal: r.AllowTerminal,
449 FileLocks: r.FileLocks,
450 EmptyNamespaces: r.EmptyNamespaces,
451 }, actions...); err != nil {
452 dumpLog := filepath.Join(p.Bundle, "criu-dump.log")
453 if cerr := copyFile(dumpLog, filepath.Join(work, "dump.log")); cerr != nil {
454 log.G(ctx).WithError(cerr).Error("failed to copy dump.log to criu-dump.log")
455 }
456 return fmt.Errorf("%s path= %s", criuError(err), dumpLog)
457 }
458 return nil
459 }
460
461 // Update the processes resource configuration
462 func (p *Init) Update(ctx context.Context, r *google_protobuf.Any) error {
463 p.mu.Lock()
464 defer p.mu.Unlock()
465
466 return p.initState.Update(ctx, r)
467 }
468
469 func (p *Init) update(ctx context.Context, r *google_protobuf.Any) error {
470 var resources specs.LinuxResources
471 if err := json.Unmarshal(r.Value, &resources); err != nil {
472 return err
473 }
474 return p.runtime.Update(ctx, p.id, &resources)
475 }
476
477 // Stdio of the process
478 func (p *Init) Stdio() stdio.Stdio {
479 return p.stdio
480 }
481
482 func (p *Init) runtimeError(rErr error, msg string) error {
483 if rErr == nil {
484 return nil
485 }
486
487 rMsg, err := getLastRuntimeError(p.runtime)
488 switch {
489 case err != nil:
490 return fmt.Errorf("%s: %s (%s): %w", msg, "unable to retrieve OCI runtime error", err.Error(), rErr)
491 case rMsg == "":
492 return fmt.Errorf("%s: %w", msg, rErr)
493 default:
494 return fmt.Errorf("%s: %s", msg, rMsg)
495 }
496 }
497
498 func withConditionalIO(c stdio.Stdio) runc.IOOpt {
499 return func(o *runc.IOOption) {
500 o.OpenStdin = c.Stdin != ""
501 o.OpenStdout = c.Stdout != ""
502 o.OpenStderr = c.Stderr != ""
503 }
504 }