Debian Codegraph @

internal/testutils/netns_linux.go

raw symbols SCIP
1 //go:build linux
2
3 // The netns implementation in this file was taken from cilium/cilium.
4 package testutils
5
6 import (
7 "fmt"
8 "os"
9 "runtime"
10 "testing"
11
12 "golang.org/x/sync/errgroup"
13
14 "github.com/cilium/ebpf/internal/unix"
15 )
16
17 type NetNS struct {
18 f *os.File
19 }
20
21 // NewNetNS returns a new network namespace.
22 func NewNetNS(tb testing.TB) *NetNS {
23 tb.Helper()
24
25 ns, err := newNetNS()
26 if err != nil {
27 tb.Fatal(err)
28 }
29
30 tb.Cleanup(func() {
31 ns.close()
32 })
33
34 return ns
35 }
36
37 // Do runs the provided func in the netns without changing the calling thread's
38 // netns.
39 //
40 // The code in f and any code called by f must NOT call [runtime.LockOSThread],
41 // as this could leave the goroutine created by Do permanently pinned to an OS
42 // thread.
43 func (h *NetNS) Do(f func() error) error {
44
45 // Start the func in a new goroutine and lock it to an exclusive thread. This
46 // ensures that if execution of the goroutine fails unexpectedly before we
47 // call UnlockOSThread, the go runtime will ensure the underlying OS thread is
48 // disposed of, rather than reused in a potentially undefined state.
49 //
50 // See also: https://pkg.go.dev/runtime#UnlockOSThread
51 var g errgroup.Group
52 g.Go(func() error {
53 // Lock the newly-created goroutine to the OS thread it's running on so we
54 // can safely move it into another network namespace. (per-thread state)
55 restoreUnlock, err := lockOSThread()
56 if err != nil {
57 return err
58 }
59
60 if err := set(h.f); err != nil {
61 return fmt.Errorf("set netns: %w (terminating OS thread)", err)
62 }
63
64 ferr := f()
65
66 // Attempt to restore the underlying OS thread to its original network
67 // namespace and unlock the running goroutine from its OS thread. Any
68 // failures during this process will leave the goroutine locked, making the
69 // underlying OS thread terminate when this function returns.
70 if err := restoreUnlock(); err != nil {
71 return fmt.Errorf("restore original netns: %w (terminating OS thread)", err)
72 }
73 return ferr
74 })
75
76 return g.Wait()
77 }
78
79 func newNetNS() (*NetNS, error) {
80 var f *os.File
81
82 // Perform network namespace creation in a new goroutine to give us the
83 // possibility of terminating the underlying OS thread (by terminating the
84 // goroutine) if something goes wrong.
85 var g errgroup.Group
86 g.Go(func() error {
87 restoreUnlock, err := lockOSThread()
88 if err != nil {
89 return fmt.Errorf("lock OS thread: %w", err)
90 }
91
92 // Move the underlying OS thread to a new network namespace. This can be
93 // undone by calling restoreUnlock().
94 if err := unshare(); err != nil {
95 return fmt.Errorf("create new netns: %w", err)
96 }
97
98 // Take out a reference to the new netns.
99 f, err = getCurrent()
100 if err != nil {
101 return fmt.Errorf("get current netns: %w (terminating OS thread)", err)
102 }
103
104 // Restore the OS thread to its original network namespace or implicitly
105 // terminate it if something went wrong.
106 if err := restoreUnlock(); err != nil {
107 return fmt.Errorf("restore current netns: %w (terminating OS thread)", err)
108 }
109
110 return nil
111 })
112
113 if err := g.Wait(); err != nil {
114 return nil, err
115 }
116
117 ns := &NetNS{f: f}
118
119 // Prevent resource leaks by eventually closing the underlying file descriptor
120 // after ns is garbage collected.
121 runtime.SetFinalizer(ns, (*NetNS).close)
122
123 return ns, nil
124 }
125
126 func (h *NetNS) close() error {
127 if h.f == nil {
128 return nil
129 }
130
131 // Close closes the handle to the network namespace. This does not necessarily
132 // mean destroying the network namespace itself, which only happens when all
133 // references to it are gone and all of its processes have been terminated.
134 if err := h.f.Close(); err != nil {
135 return err
136 }
137 h.f = nil
138
139 return nil
140 }
141
142 func lockOSThread() (func() error, error) {
143 runtime.LockOSThread()
144
145 orig, err := getCurrent()
146 if err != nil {
147 runtime.UnlockOSThread()
148 return nil, fmt.Errorf("get current namespace: %w", err)
149 }
150
151 return func() error {
152 defer orig.Close()
153
154 if err := set(orig); err != nil {
155 // We didn't manage to restore the OS thread to its original namespace.
156 // Don't unlock the current goroutine from its thread, so the thread will
157 // terminate when the current goroutine does.
158 return err
159 }
160
161 // Original netns was restored, release the OS thread back into the
162 // schedulable pool.
163 runtime.UnlockOSThread()
164
165 return nil
166 }, nil
167 }
168
169 // unshare moves the calling OS thread of the calling goroutine to a new network
170 // namespace. Must only be called after a prior call to lockOSThread().
171 func unshare() error {
172 if err := unix.Unshare(unix.CLONE_NEWNET); err != nil {
173 return err
174 }
175 return nil
176 }
177
178 // set sets the underlying OS thread of the calling goroutine to the netns
179 // pointed at by f.
180 func set(f *os.File) error {
181 return unix.Setns(int(f.Fd()), unix.CLONE_NEWNET)
182 }
183
184 // getCurrent gets a file descriptor to the current thread network namespace.
185 func getCurrent() (*os.File, error) {
186 return getFromThread(os.Getpid(), unix.Gettid())
187 }
188
189 // getFromPath gets a file descriptor to the network namespace pinned at path.
190 func getFromPath(path string) (*os.File, error) {
191 return os.OpenFile(path, unix.O_RDONLY|unix.O_CLOEXEC, 0)
192 }
193
194 // getFromThread gets a file descriptor to the network namespace of a given pid
195 // and tid.
196 func getFromThread(pid, tid int) (*os.File, error) {
197 return getFromPath(fmt.Sprintf("/proc/%d/task/%d/ns/net", pid, tid))
198 }