| 1 | // Copyright 2015-2017 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 ns |
| 16 | |
| 17 | import ( |
| 18 | "fmt" |
| 19 | "os" |
| 20 | "runtime" |
| 21 | "sync" |
| 22 | "syscall" |
| 23 | |
| 24 | "golang.org/x/sys/unix" |
| 25 | ) |
| 26 | |
| 27 | // Returns an object representing the current OS thread's network namespace |
| 28 | func GetCurrentNS() (NetNS, error) { |
| 29 | // Lock the thread in case other goroutine executes in it and changes its |
| 30 | // network namespace after getCurrentThreadNetNSPath(), otherwise it might |
| 31 | // return an unexpected network namespace. |
| 32 | runtime.LockOSThread() |
| 33 | defer runtime.UnlockOSThread() |
| 34 | return getCurrentNSNoLock() |
| 35 | } |
| 36 | |
| 37 | func getCurrentNSNoLock() (NetNS, error) { |
| 38 | return GetNS(getCurrentThreadNetNSPath()) |
| 39 | } |
| 40 | |
| 41 | func getCurrentThreadNetNSPath() string { |
| 42 | // /proc/self/ns/net returns the namespace of the main thread, not |
| 43 | // of whatever thread this goroutine is running on. Make sure we |
| 44 | // use the thread's net namespace since the thread is switching around |
| 45 | return fmt.Sprintf("/proc/%d/task/%d/ns/net", os.Getpid(), unix.Gettid()) |
| 46 | } |
| 47 | |
| 48 | func (ns *netNS) Close() error { |
| 49 | if err := ns.errorIfClosed(); err != nil { |
| 50 | return err |
| 51 | } |
| 52 | |
| 53 | if err := ns.file.Close(); err != nil { |
| 54 | return fmt.Errorf("Failed to close %q: %v", ns.file.Name(), err) |
| 55 | } |
| 56 | ns.closed = true |
| 57 | |
| 58 | return nil |
| 59 | } |
| 60 | |
| 61 | func (ns *netNS) Set() error { |
| 62 | if err := ns.errorIfClosed(); err != nil { |
| 63 | return err |
| 64 | } |
| 65 | |
| 66 | if err := unix.Setns(int(ns.Fd()), unix.CLONE_NEWNET); err != nil { |
| 67 | return fmt.Errorf("Error switching to ns %v: %v", ns.file.Name(), err) |
| 68 | } |
| 69 | |
| 70 | return nil |
| 71 | } |
| 72 | |
| 73 | type NetNS interface { |
| 74 | // Executes the passed closure in this object's network namespace, |
| 75 | // attempting to restore the original namespace before returning. |
| 76 | // However, since each OS thread can have a different network namespace, |
| 77 | // and Go's thread scheduling is highly variable, callers cannot |
| 78 | // guarantee any specific namespace is set unless operations that |
| 79 | // require that namespace are wrapped with Do(). Also, no code called |
| 80 | // from Do() should call runtime.UnlockOSThread(), or the risk |
| 81 | // of executing code in an incorrect namespace will be greater. See |
| 82 | // https://github.com/golang/go/wiki/LockOSThread for further details. |
| 83 | Do(toRun func(NetNS) error) error |
| 84 | |
| 85 | // Sets the current network namespace to this object's network namespace. |
| 86 | // Note that since Go's thread scheduling is highly variable, callers |
| 87 | // cannot guarantee the requested namespace will be the current namespace |
| 88 | // after this function is called; to ensure this wrap operations that |
| 89 | // require the namespace with Do() instead. |
| 90 | Set() error |
| 91 | |
| 92 | // Returns the filesystem path representing this object's network namespace |
| 93 | Path() string |
| 94 | |
| 95 | // Returns a file descriptor representing this object's network namespace |
| 96 | Fd() uintptr |
| 97 | |
| 98 | // Cleans up this instance of the network namespace; if this instance |
| 99 | // is the last user the namespace will be destroyed |
| 100 | Close() error |
| 101 | } |
| 102 | |
| 103 | type netNS struct { |
| 104 | file *os.File |
| 105 | closed bool |
| 106 | } |
| 107 | |
| 108 | // netNS implements the NetNS interface |
| 109 | var _ NetNS = &netNS{} |
| 110 | |
| 111 | const ( |
| 112 | // https://github.com/torvalds/linux/blob/master/include/uapi/linux/magic.h |
| 113 | NSFS_MAGIC = unix.NSFS_MAGIC |
| 114 | PROCFS_MAGIC = unix.PROC_SUPER_MAGIC |
| 115 | ) |
| 116 | |
| 117 | type NSPathNotExistErr struct{ msg string } |
| 118 | |
| 119 | func (e NSPathNotExistErr) Error() string { return e.msg } |
| 120 | |
| 121 | type NSPathNotNSErr struct{ msg string } |
| 122 | |
| 123 | func (e NSPathNotNSErr) Error() string { return e.msg } |
| 124 | |
| 125 | func IsNSorErr(nspath string) error { |
| 126 | stat := syscall.Statfs_t{} |
| 127 | if err := syscall.Statfs(nspath, &stat); err != nil { |
| 128 | if os.IsNotExist(err) { |
| 129 | err = NSPathNotExistErr{msg: fmt.Sprintf("failed to Statfs %q: %v", nspath, err)} |
| 130 | } else { |
| 131 | err = fmt.Errorf("failed to Statfs %q: %v", nspath, err) |
| 132 | } |
| 133 | return err |
| 134 | } |
| 135 | |
| 136 | switch stat.Type { |
| 137 | case PROCFS_MAGIC, NSFS_MAGIC: |
| 138 | return nil |
| 139 | default: |
| 140 | return NSPathNotNSErr{msg: fmt.Sprintf("unknown FS magic on %q: %x", nspath, stat.Type)} |
| 141 | } |
| 142 | } |
| 143 | |
| 144 | // Returns an object representing the namespace referred to by @path |
| 145 | func GetNS(nspath string) (NetNS, error) { |
| 146 | err := IsNSorErr(nspath) |
| 147 | if err != nil { |
| 148 | return nil, err |
| 149 | } |
| 150 | |
| 151 | fd, err := os.Open(nspath) |
| 152 | if err != nil { |
| 153 | return nil, err |
| 154 | } |
| 155 | |
| 156 | return &netNS{file: fd}, nil |
| 157 | } |
| 158 | |
| 159 | // Returns a new empty NetNS. |
| 160 | // Calling Close() let the kernel garbage collect the network namespace. |
| 161 | func TempNetNS() (NetNS, error) { |
| 162 | var tempNS NetNS |
| 163 | var err error |
| 164 | var wg sync.WaitGroup |
| 165 | wg.Add(1) |
| 166 | |
| 167 | // Create the new namespace in a new goroutine so that if we later fail |
| 168 | // to switch the namespace back to the original one, we can safely |
| 169 | // leave the thread locked to die without a risk of the current thread |
| 170 | // left lingering with incorrect namespace. |
| 171 | go func() { |
| 172 | defer wg.Done() |
| 173 | runtime.LockOSThread() |
| 174 | |
| 175 | var threadNS NetNS |
| 176 | // save a handle to current network namespace |
| 177 | threadNS, err = getCurrentNSNoLock() |
| 178 | if err != nil { |
| 179 | err = fmt.Errorf("failed to open current namespace: %v", err) |
| 180 | return |
| 181 | } |
| 182 | defer threadNS.Close() |
| 183 | |
| 184 | // create the temporary network namespace |
| 185 | err = unix.Unshare(unix.CLONE_NEWNET) |
| 186 | if err != nil { |
| 187 | return |
| 188 | } |
| 189 | |
| 190 | // get a handle to the temporary network namespace |
| 191 | tempNS, err = getCurrentNSNoLock() |
| 192 | |
| 193 | err2 := threadNS.Set() |
| 194 | if err2 == nil { |
| 195 | // Unlock the current thread only when we successfully switched back |
| 196 | // to the original namespace; otherwise leave the thread locked which |
| 197 | // will force the runtime to scrap the current thread, that is maybe |
| 198 | // not as optimal but at least always safe to do. |
| 199 | runtime.UnlockOSThread() |
| 200 | } |
| 201 | }() |
| 202 | |
| 203 | wg.Wait() |
| 204 | return tempNS, err |
| 205 | } |
| 206 | |
| 207 | func (ns *netNS) Path() string { |
| 208 | return ns.file.Name() |
| 209 | } |
| 210 | |
| 211 | func (ns *netNS) Fd() uintptr { |
| 212 | return ns.file.Fd() |
| 213 | } |
| 214 | |
| 215 | func (ns *netNS) errorIfClosed() error { |
| 216 | if ns.closed { |
| 217 | return fmt.Errorf("%q has already been closed", ns.file.Name()) |
| 218 | } |
| 219 | return nil |
| 220 | } |
| 221 | |
| 222 | func (ns *netNS) Do(toRun func(NetNS) error) error { |
| 223 | if err := ns.errorIfClosed(); err != nil { |
| 224 | return err |
| 225 | } |
| 226 | |
| 227 | containedCall := func(hostNS NetNS) error { |
| 228 | threadNS, err := getCurrentNSNoLock() |
| 229 | if err != nil { |
| 230 | return fmt.Errorf("failed to open current netns: %v", err) |
| 231 | } |
| 232 | defer threadNS.Close() |
| 233 | |
| 234 | // switch to target namespace |
| 235 | if err = ns.Set(); err != nil { |
| 236 | return fmt.Errorf("error switching to ns %v: %v", ns.file.Name(), err) |
| 237 | } |
| 238 | defer func() { |
| 239 | err := threadNS.Set() // switch back |
| 240 | if err == nil { |
| 241 | // Unlock the current thread only when we successfully switched back |
| 242 | // to the original namespace; otherwise leave the thread locked which |
| 243 | // will force the runtime to scrap the current thread, that is maybe |
| 244 | // not as optimal but at least always safe to do. |
| 245 | runtime.UnlockOSThread() |
| 246 | } |
| 247 | }() |
| 248 | |
| 249 | return toRun(hostNS) |
| 250 | } |
| 251 | |
| 252 | // save a handle to current network namespace |
| 253 | hostNS, err := GetCurrentNS() |
| 254 | if err != nil { |
| 255 | return fmt.Errorf("Failed to open current namespace: %v", err) |
| 256 | } |
| 257 | defer hostNS.Close() |
| 258 | |
| 259 | var wg sync.WaitGroup |
| 260 | wg.Add(1) |
| 261 | |
| 262 | // Start the callback in a new green thread so that if we later fail |
| 263 | // to switch the namespace back to the original one, we can safely |
| 264 | // leave the thread locked to die without a risk of the current thread |
| 265 | // left lingering with incorrect namespace. |
| 266 | var innerError error |
| 267 | go func() { |
| 268 | defer wg.Done() |
| 269 | runtime.LockOSThread() |
| 270 | innerError = containedCall(hostNS) |
| 271 | }() |
| 272 | wg.Wait() |
| 273 | |
| 274 | return innerError |
| 275 | } |
| 276 | |
| 277 | // WithNetNSPath executes the passed closure under the given network |
| 278 | // namespace, restoring the original namespace afterwards. |
| 279 | func WithNetNSPath(nspath string, toRun func(NetNS) error) error { |
| 280 | ns, err := GetNS(nspath) |
| 281 | if err != nil { |
| 282 | return err |
| 283 | } |
| 284 | defer ns.Close() |
| 285 | return ns.Do(toRun) |
| 286 | } |