Debian Codegraph @

pkg/testutils/netns_linux.go

raw symbols SCIP
1 // Copyright 2018 CNI authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package testutils
16
17 import (
18 "crypto/rand"
19 "fmt"
20 "os"
21 "path"
22 "runtime"
23 "strings"
24 "sync"
25 "syscall"
26
27 "golang.org/x/sys/unix"
28
29 "github.com/containernetworking/plugins/pkg/ns"
30 )
31
32 func getNsRunDir() string {
33 xdgRuntimeDir := os.Getenv("XDG_RUNTIME_DIR")
34
35 /// If XDG_RUNTIME_DIR is set, check if the current user owns /var/run. If
36 // the owner is different, we are most likely running in a user namespace.
37 // In that case use $XDG_RUNTIME_DIR/netns as runtime dir.
38 if xdgRuntimeDir != "" {
39 if s, err := os.Stat("/var/run"); err == nil {
40 st, ok := s.Sys().(*syscall.Stat_t)
41 if ok && int(st.Uid) != os.Geteuid() {
42 return path.Join(xdgRuntimeDir, "netns")
43 }
44 }
45 }
46
47 return "/var/run/netns"
48 }
49
50 // Creates a new persistent (bind-mounted) network namespace and returns an object
51 // representing that namespace, without switching to it.
52 func NewNS() (ns.NetNS, error) {
53 nsRunDir := getNsRunDir()
54
55 b := make([]byte, 16)
56 _, err := rand.Read(b)
57 if err != nil {
58 return nil, fmt.Errorf("failed to generate random netns name: %v", err)
59 }
60
61 // Create the directory for mounting network namespaces
62 // This needs to be a shared mountpoint in case it is mounted in to
63 // other namespaces (containers)
64 err = os.MkdirAll(nsRunDir, 0o755)
65 if err != nil {
66 return nil, err
67 }
68
69 // Remount the namespace directory shared. This will fail if it is not
70 // already a mountpoint, so bind-mount it on to itself to "upgrade" it
71 // to a mountpoint.
72 err = unix.Mount("", nsRunDir, "none", unix.MS_SHARED|unix.MS_REC, "")
73 if err != nil {
74 if err != unix.EINVAL {
75 return nil, fmt.Errorf("mount --make-rshared %s failed: %q", nsRunDir, err)
76 }
77
78 // Recursively remount /var/run/netns on itself. The recursive flag is
79 // so that any existing netns bindmounts are carried over.
80 err = unix.Mount(nsRunDir, nsRunDir, "none", unix.MS_BIND|unix.MS_REC, "")
81 if err != nil {
82 return nil, fmt.Errorf("mount --rbind %s %s failed: %q", nsRunDir, nsRunDir, err)
83 }
84
85 // Now we can make it shared
86 err = unix.Mount("", nsRunDir, "none", unix.MS_SHARED|unix.MS_REC, "")
87 if err != nil {
88 return nil, fmt.Errorf("mount --make-rshared %s failed: %q", nsRunDir, err)
89 }
90
91 }
92
93 nsName := fmt.Sprintf("cnitest-%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:])
94
95 // create an empty file at the mount point
96 nsPath := path.Join(nsRunDir, nsName)
97 mountPointFd, err := os.Create(nsPath)
98 if err != nil {
99 return nil, err
100 }
101 mountPointFd.Close()
102
103 // Ensure the mount point is cleaned up on errors; if the namespace
104 // was successfully mounted this will have no effect because the file
105 // is in-use
106 defer os.RemoveAll(nsPath)
107
108 var wg sync.WaitGroup
109 wg.Add(1)
110
111 // do namespace work in a dedicated goroutine, so that we can safely
112 // Lock/Unlock OSThread without upsetting the lock/unlock state of
113 // the caller of this function
114 go (func() {
115 defer wg.Done()
116 runtime.LockOSThread()
117 // Don't unlock. By not unlocking, golang will kill the OS thread when the
118 // goroutine is done (for go1.10+)
119
120 var origNS ns.NetNS
121 origNS, err = ns.GetNS(getCurrentThreadNetNSPath())
122 if err != nil {
123 return
124 }
125 defer origNS.Close()
126
127 // create a new netns on the current thread
128 err = unix.Unshare(unix.CLONE_NEWNET)
129 if err != nil {
130 return
131 }
132
133 // Put this thread back to the orig ns, since it might get reused (pre go1.10)
134 defer origNS.Set()
135
136 // bind mount the netns from the current thread (from /proc) onto the
137 // mount point. This causes the namespace to persist, even when there
138 // are no threads in the ns.
139 err = unix.Mount(getCurrentThreadNetNSPath(), nsPath, "none", unix.MS_BIND, "")
140 if err != nil {
141 err = fmt.Errorf("failed to bind mount ns at %s: %v", nsPath, err)
142 }
143 })()
144 wg.Wait()
145
146 if err != nil {
147 return nil, fmt.Errorf("failed to create namespace: %v", err)
148 }
149
150 return ns.GetNS(nsPath)
151 }
152
153 // UnmountNS unmounts the NS held by the netns object
154 func UnmountNS(ns ns.NetNS) error {
155 nsPath := ns.Path()
156 // Only unmount if it's been bind-mounted (don't touch namespaces in /proc...)
157 if strings.HasPrefix(nsPath, getNsRunDir()) {
158 if err := unix.Unmount(nsPath, 0); err != nil {
159 return fmt.Errorf("failed to unmount NS: at %s: %v", nsPath, err)
160 }
161
162 if err := os.Remove(nsPath); err != nil {
163 return fmt.Errorf("failed to remove ns path %s: %v", nsPath, err)
164 }
165 }
166
167 return nil
168 }
169
170 // getCurrentThreadNetNSPath copied from pkg/ns
171 func getCurrentThreadNetNSPath() string {
172 // /proc/self/ns/net returns the namespace of the main thread, not
173 // of whatever thread this goroutine is running on. Make sure we
174 // use the thread's net namespace since the thread is switching around
175 return fmt.Sprintf("/proc/%d/task/%d/ns/net", os.Getpid(), unix.Gettid())
176 }