Debian Codegraph @

cmd/containerd-shim-runc-v2/process/io.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 "errors"
24 "fmt"
25 "io"
26 "net/url"
27 "os"
28 "os/exec"
29 "path/filepath"
30 "sync"
31 "sync/atomic"
32 "syscall"
33 "time"
34
35 "github.com/containerd/containerd/v2/pkg/namespaces"
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 )
41
42 const binaryIOProcTermTimeout = 12 * time.Second // Give logger process solid 10 seconds for cleanup
43
44 var bufPool = sync.Pool{
45 New: func() interface{} {
46 // setting to 4096 to align with PIPE_BUF
47 // http://man7.org/linux/man-pages/man7/pipe.7.html
48 buffer := make([]byte, 4096)
49 return &buffer
50 },
51 }
52
53 type processIO struct {
54 io runc.IO
55
56 uri *url.URL
57 copy bool
58 stdio stdio.Stdio
59 }
60
61 func (p *processIO) Close() error {
62 if p.io != nil {
63 return p.io.Close()
64 }
65 return nil
66 }
67
68 func (p *processIO) IO() runc.IO {
69 return p.io
70 }
71
72 func (p *processIO) Copy(ctx context.Context, wg *sync.WaitGroup) error {
73 if !p.copy {
74 return nil
75 }
76 var cwg sync.WaitGroup
77 if err := copyPipes(ctx, p.IO(), p.stdio.Stdin, p.stdio.Stdout, p.stdio.Stderr, wg, &cwg); err != nil {
78 return fmt.Errorf("unable to copy pipes: %w", err)
79 }
80 cwg.Wait()
81 return nil
82 }
83
84 func createIO(ctx context.Context, id string, ioUID, ioGID int, stdio stdio.Stdio) (*processIO, error) {
85 pio := &processIO{
86 stdio: stdio,
87 }
88 if stdio.IsNull() {
89 i, err := runc.NewNullIO()
90 if err != nil {
91 return nil, err
92 }
93 pio.io = i
94 return pio, nil
95 }
96 u, err := url.Parse(stdio.Stdout)
97 if err != nil {
98 return nil, fmt.Errorf("unable to parse stdout uri: %w", err)
99 }
100 if u.Scheme == "" {
101 u.Scheme = "fifo"
102 }
103 pio.uri = u
104 switch u.Scheme {
105 case "fifo":
106 pio.copy = true
107 pio.io, err = runc.NewPipeIO(ioUID, ioGID, withConditionalIO(stdio))
108 case "binary":
109 pio.io, err = NewBinaryIO(ctx, id, u)
110 case "file":
111 filePath := u.Path
112 if err := os.MkdirAll(filepath.Dir(filePath), 0755); err != nil {
113 return nil, err
114 }
115 var f *os.File
116 f, err = os.OpenFile(filePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
117 if err != nil {
118 return nil, err
119 }
120 f.Close()
121 pio.stdio.Stdout = filePath
122 pio.stdio.Stderr = filePath
123 pio.copy = true
124 pio.io, err = runc.NewPipeIO(ioUID, ioGID, withConditionalIO(stdio))
125 default:
126 return nil, fmt.Errorf("unknown STDIO scheme %s", u.Scheme)
127 }
128 if err != nil {
129 return nil, err
130 }
131 return pio, nil
132 }
133
134 func copyPipes(ctx context.Context, rio runc.IO, stdin, stdout, stderr string, wg, cwg *sync.WaitGroup) error {
135 var sameFile *countingWriteCloser
136 for _, i := range []struct {
137 name string
138 dest func(wc io.WriteCloser, rc io.Closer)
139 }{
140 {
141 name: stdout,
142 dest: func(wc io.WriteCloser, rc io.Closer) {
143 wg.Add(1)
144 cwg.Add(1)
145 go func() {
146 cwg.Done()
147 p := bufPool.Get().(*[]byte)
148 defer bufPool.Put(p)
149 if _, err := io.CopyBuffer(wc, rio.Stdout(), *p); err != nil {
150 log.G(ctx).Warn("error copying stdout")
151 }
152 wg.Done()
153 wc.Close()
154 if rc != nil {
155 rc.Close()
156 }
157 }()
158 },
159 }, {
160 name: stderr,
161 dest: func(wc io.WriteCloser, rc io.Closer) {
162 wg.Add(1)
163 cwg.Add(1)
164 go func() {
165 cwg.Done()
166 p := bufPool.Get().(*[]byte)
167 defer bufPool.Put(p)
168 if _, err := io.CopyBuffer(wc, rio.Stderr(), *p); err != nil {
169 log.G(ctx).Warn("error copying stderr")
170 }
171 wg.Done()
172 wc.Close()
173 if rc != nil {
174 rc.Close()
175 }
176 }()
177 },
178 },
179 } {
180 ok, err := fifo.IsFifo(i.name)
181 if err != nil {
182 return err
183 }
184 var (
185 fw io.WriteCloser
186 fr io.Closer
187 )
188 if ok {
189 if fw, err = fifo.OpenFifo(ctx, i.name, syscall.O_WRONLY, 0); err != nil {
190 return fmt.Errorf("containerd-shim: opening w/o fifo %q failed: %w", i.name, err)
191 }
192 if fr, err = fifo.OpenFifo(ctx, i.name, syscall.O_RDONLY, 0); err != nil {
193 return fmt.Errorf("containerd-shim: opening r/o fifo %q failed: %w", i.name, err)
194 }
195 } else {
196 if sameFile != nil {
197 sameFile.bumpCount(1)
198 i.dest(sameFile, nil)
199 continue
200 }
201 if fw, err = os.OpenFile(i.name, syscall.O_WRONLY|syscall.O_APPEND, 0); err != nil {
202 return fmt.Errorf("containerd-shim: opening file %q failed: %w", i.name, err)
203 }
204 if stdout == stderr {
205 sameFile = newCountingWriteCloser(fw, 1)
206 }
207 }
208 i.dest(fw, fr)
209 }
210 if stdin == "" {
211 return nil
212 }
213 f, err := fifo.OpenFifo(context.Background(), stdin, syscall.O_RDONLY|syscall.O_NONBLOCK, 0)
214 if err != nil {
215 return fmt.Errorf("containerd-shim: opening %s failed: %s", stdin, err)
216 }
217 cwg.Add(1)
218 go func() {
219 cwg.Done()
220 p := bufPool.Get().(*[]byte)
221 defer bufPool.Put(p)
222
223 io.CopyBuffer(rio.Stdin(), f, *p)
224 rio.Stdin().Close()
225 f.Close()
226 }()
227 return nil
228 }
229
230 // countingWriteCloser masks io.Closer() until close has been invoked a certain number of times.
231 type countingWriteCloser struct {
232 io.WriteCloser
233 count atomic.Int64
234 }
235
236 func newCountingWriteCloser(c io.WriteCloser, count int64) *countingWriteCloser {
237 cwc := &countingWriteCloser{
238 c,
239 atomic.Int64{},
240 }
241 cwc.bumpCount(count)
242 return cwc
243 }
244
245 func (c *countingWriteCloser) bumpCount(delta int64) int64 {
246 return c.count.Add(delta)
247 }
248
249 func (c *countingWriteCloser) Close() error {
250 if c.bumpCount(-1) > 0 {
251 return nil
252 }
253 return c.WriteCloser.Close()
254 }
255
256 // NewBinaryIO runs a custom binary process for pluggable shim logging
257 func NewBinaryIO(ctx context.Context, id string, uri *url.URL) (_ runc.IO, err error) {
258 ns, err := namespaces.NamespaceRequired(ctx)
259 if err != nil {
260 return nil, err
261 }
262
263 var closers []func() error
264 defer func() {
265 if err == nil {
266 return
267 }
268 result := []error{err}
269 for _, fn := range closers {
270 result = append(result, fn())
271 }
272 err = errors.Join(result...)
273 }()
274
275 out, err := newPipe()
276 if err != nil {
277 return nil, fmt.Errorf("failed to create stdout pipes: %w", err)
278 }
279 closers = append(closers, out.Close)
280
281 serr, err := newPipe()
282 if err != nil {
283 return nil, fmt.Errorf("failed to create stderr pipes: %w", err)
284 }
285 closers = append(closers, serr.Close)
286
287 r, w, err := os.Pipe()
288 if err != nil {
289 return nil, err
290 }
291 closers = append(closers, r.Close, w.Close)
292
293 cmd := NewBinaryCmd(uri, id, ns)
294 cmd.ExtraFiles = append(cmd.ExtraFiles, out.r, serr.r, w)
295 // don't need to register this with the reaper or wait when
296 // running inside a shim
297 if err := cmd.Start(); err != nil {
298 return nil, fmt.Errorf("failed to start binary process: %w", err)
299 }
300 closers = append(closers, func() error { return cmd.Process.Kill() })
301
302 // close our side of the pipe after start
303 if err := w.Close(); err != nil {
304 return nil, fmt.Errorf("failed to close write pipe after start: %w", err)
305 }
306
307 // wait for the logging binary to be ready
308 b := make([]byte, 1)
309 if _, err := r.Read(b); err != nil && err != io.EOF {
310 return nil, fmt.Errorf("failed to read from logging binary: %w", err)
311 }
312
313 return &binaryIO{
314 cmd: cmd,
315 out: out,
316 err: serr,
317 }, nil
318 }
319
320 type binaryIO struct {
321 cmd *exec.Cmd
322 out, err *pipe
323 }
324
325 func (b *binaryIO) CloseAfterStart() error {
326 var result []error
327
328 for _, v := range []*pipe{b.out, b.err} {
329 if v != nil {
330 if err := v.r.Close(); err != nil {
331 result = append(result, err)
332 }
333 }
334 }
335
336 return errors.Join(result...)
337 }
338
339 func (b *binaryIO) Close() error {
340 var result []error
341
342 for _, v := range []*pipe{b.out, b.err} {
343 if v != nil {
344 if err := v.Close(); err != nil {
345 result = append(result, err)
346 }
347 }
348 }
349
350 if err := b.cancel(); err != nil {
351 result = append(result, err)
352 }
353
354 return errors.Join(result...)
355 }
356
357 func (b *binaryIO) cancel() error {
358 if b.cmd == nil || b.cmd.Process == nil {
359 return nil
360 }
361
362 // Send SIGTERM first, so logger process has a chance to flush and exit properly
363 if err := b.cmd.Process.Signal(syscall.SIGTERM); err != nil {
364 result := []error{fmt.Errorf("failed to send SIGTERM: %w", err)}
365
366 log.L.WithError(err).Warn("failed to send SIGTERM signal, killing logging shim")
367
368 if err := b.cmd.Process.Kill(); err != nil {
369 result = append(result, fmt.Errorf("failed to kill process after faulty SIGTERM: %w", err))
370 }
371
372 return errors.Join(result...)
373 }
374
375 done := make(chan error, 1)
376 go func() {
377 done <- b.cmd.Wait()
378 }()
379
380 select {
381 case err := <-done:
382 return err
383 case <-time.After(binaryIOProcTermTimeout):
384 log.L.Warn("failed to wait for shim logger process to exit, killing")
385
386 err := b.cmd.Process.Kill()
387 if err != nil {
388 return fmt.Errorf("failed to kill shim logger process: %w", err)
389 }
390
391 return nil
392 }
393 }
394
395 func (b *binaryIO) Stdin() io.WriteCloser {
396 return nil
397 }
398
399 func (b *binaryIO) Stdout() io.ReadCloser {
400 return nil
401 }
402
403 func (b *binaryIO) Stderr() io.ReadCloser {
404 return nil
405 }
406
407 func (b *binaryIO) Set(cmd *exec.Cmd) {
408 if b.out != nil {
409 cmd.Stdout = b.out.w
410 }
411 if b.err != nil {
412 cmd.Stderr = b.err.w
413 }
414 }
415
416 func newPipe() (*pipe, error) {
417 r, w, err := os.Pipe()
418 if err != nil {
419 return nil, err
420 }
421 return &pipe{
422 r: r,
423 w: w,
424 }, nil
425 }
426
427 type pipe struct {
428 r *os.File
429 w *os.File
430 }
431
432 func (p *pipe) Close() error {
433 var result []error
434
435 if err := p.w.Close(); err != nil {
436 result = append(result, fmt.Errorf("pipe: failed to close write pipe: %w", err))
437 }
438
439 if err := p.r.Close(); err != nil {
440 result = append(result, fmt.Errorf("pipe: failed to close read pipe: %w", err))
441 }
442
443 return errors.Join(result...)
444 }