Debian Codegraph @

cmd/containerd-shim-runc-v2/process/io_test.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 process
20
21 import (
22 "context"
23 "net/url"
24 "os"
25 "path/filepath"
26 "strings"
27 "testing"
28
29 "github.com/containerd/containerd/v2/pkg/namespaces"
30 )
31
32 func TestNewBinaryIO(t *testing.T) {
33 ctx := namespaces.WithNamespace(context.Background(), "test")
34 uri, _ := url.Parse("binary:///bin/echo?test")
35
36 before := descriptorCount(t)
37
38 io, err := NewBinaryIO(ctx, "1", uri)
39 if err != nil {
40 t.Fatal(err)
41 }
42
43 err = io.Close()
44 if err != nil {
45 t.Fatal(err)
46 }
47
48 after := descriptorCount(t)
49 if before != after-1 { // one descriptor must be closed from shim logger side
50 t.Fatalf("some descriptors weren't closed (%d != %d -1)", before, after)
51 }
52 }
53
54 func TestNewBinaryIOCleanup(t *testing.T) {
55 ctx := namespaces.WithNamespace(context.Background(), "test")
56 uri, _ := url.Parse("binary:///not/existing")
57
58 before := descriptorCount(t)
59 _, err := NewBinaryIO(ctx, "2", uri)
60 if err == nil {
61 t.Fatal("error expected for invalid binary")
62 }
63
64 after := descriptorCount(t)
65 if before != after {
66 t.Fatalf("some descriptors weren't closed (%d != %d)", before, after)
67 }
68 }
69
70 func descriptorCount(t *testing.T) int {
71 t.Helper()
72 const dir = "/proc/self/fd"
73 files, _ := os.ReadDir(dir)
74
75 // Go 1.23+ uses pidfd instead of PID for processes started by a user,
76 // if possible (see https://go.dev/cl/570036). As a side effect, every
77 // os.StartProcess or os.FindProcess call results in an extra opened
78 // file descriptor, which is only closed in p.Wait or p.Release.
79 //
80 // To retain compatibility with previous Go versions (or Go 1.23+
81 // behavior on older kernels), let's not count pidfds.
82 //
83 // TODO: if the proposal to check for internal file descriptors
84 // (https://go.dev/issues/67639) is accepted, we can use that
85 // instead to detect internal fds in use by the Go runtime.
86 count := 0
87 for _, file := range files {
88 sym, err := os.Readlink(filepath.Join(dir, file.Name()))
89 // Either pidfd:[70517] or anon_inode:[pidfd] (on Linux 5.4).
90 if err == nil && strings.Contains(sym, "pidfd") {
91 continue
92 }
93 count++
94 }
95
96 return count
97 }