├── .github ├── dependabot.yml └── workflows │ ├── test.yml │ └── validate.yml ├── .golangci.yml ├── .yamllint.yml ├── LICENSE ├── README.md ├── doc.go ├── go.mod ├── go.sum ├── netns_linux.go ├── netns_linux_test.go ├── netns_others.go ├── nshandle_linux.go └── nshandle_others.go /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: "github-actions" 4 | directory: "/" 5 | schedule: 6 | interval: "monthly" 7 | 8 | - package-ecosystem: "gomod" # Dependencies listed in go.mod 9 | directory: "/" # Location of package manifests 10 | schedule: 11 | interval: "weekly" 12 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: test 2 | on: # yamllint disable-line rule:truthy 3 | push: 4 | tags: 5 | - v* 6 | branches: 7 | - master 8 | - main 9 | pull_request: 10 | branches: 11 | - master 12 | - main 13 | 14 | jobs: 15 | test: 16 | permissions: 17 | contents: read # for actions/checkout to fetch code 18 | timeout-minutes: 10 19 | 20 | strategy: 21 | matrix: 22 | # test against the "oldest" supported version and the current version 23 | # of go. 24 | go-version: [1.23.x, stable] 25 | os: [ubuntu-24.04, ubuntu-22.04, windows-2025] 26 | runs-on: ${{ matrix.os }} 27 | steps: 28 | - uses: actions/setup-go@v5 29 | with: 30 | go-version: ${{ matrix.go-version }} 31 | 32 | - uses: actions/checkout@v4 33 | 34 | - run: go test -exec "sudo -n" -v ./... 35 | 36 | - run: go mod tidy -diff 37 | -------------------------------------------------------------------------------- /.github/workflows/validate.yml: -------------------------------------------------------------------------------- 1 | name: validate 2 | on: # yamllint disable-line rule:truthy 3 | push: 4 | tags: 5 | - v* 6 | branches: 7 | - master 8 | - main 9 | pull_request: 10 | branches: 11 | - master 12 | - main 13 | 14 | jobs: 15 | linters: 16 | permissions: 17 | contents: read # for actions/checkout to fetch code 18 | pull-requests: read # for golangci/golangci-lint-action to fetch pull requests 19 | timeout-minutes: 10 20 | 21 | strategy: 22 | matrix: 23 | # We only run on the latest version of go, as some linters may be 24 | # version-dependent (for example gofmt can change between releases). 25 | go-version: [stable] 26 | os: [ubuntu-24.04, windows-2025] 27 | runs-on: ${{ matrix.os }} 28 | steps: 29 | - uses: actions/setup-go@v5 30 | with: 31 | go-version: ${{ matrix.go-version }} 32 | 33 | - uses: actions/checkout@v4 34 | 35 | - name: YAML Lint 36 | if: runner.os == 'Linux' 37 | # yamllint is installed in GitHub Actions base runner image: https://github.com/adrienverge/yamllint/pull/588 38 | run: yamllint . 39 | 40 | - name: Golangci-lint 41 | uses: golangci/golangci-lint-action@v8 42 | with: 43 | version: latest 44 | skip-cache: true 45 | args: --print-resources-usage --verbose 46 | 47 | # Optional: show only new issues if it's a pull request. The default value is `false`. 48 | # only-new-issues: true 49 | 50 | # Optional: if set to true then the action don't cache or restore ~/go/pkg. 51 | # skip-pkg-cache: true 52 | 53 | # Optional: if set to true then the action don't cache or restore ~/.cache/go-build. 54 | # skip-build-cache: true 55 | -------------------------------------------------------------------------------- /.golangci.yml: -------------------------------------------------------------------------------- 1 | version: "2" 2 | linters: 3 | enable: 4 | - errorlint 5 | - gocritic 6 | - gosec 7 | - misspell 8 | - nonamedreturns 9 | - unconvert 10 | - unparam 11 | - whitespace 12 | exclusions: 13 | generated: lax 14 | presets: 15 | - comments 16 | - common-false-positives 17 | - legacy 18 | - std-error-handling 19 | paths: 20 | - third_party$ 21 | - builtin$ 22 | - examples$ 23 | formatters: 24 | enable: 25 | - gci 26 | settings: 27 | gci: 28 | sections: 29 | - standard 30 | - default 31 | - prefix(github.com/vishvananda) 32 | exclusions: 33 | generated: lax 34 | paths: 35 | - third_party$ 36 | - builtin$ 37 | - examples$ 38 | -------------------------------------------------------------------------------- /.yamllint.yml: -------------------------------------------------------------------------------- 1 | --- 2 | extends: default 3 | 4 | rules: 5 | document-start: disable 6 | line-length: disable 7 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | Copyright 2014 Vishvananda Ishaya. 180 | Copyright 2014 Docker, Inc. 181 | 182 | Licensed under the Apache License, Version 2.0 (the "License"); 183 | you may not use this file except in compliance with the License. 184 | You may obtain a copy of the License at 185 | 186 | http://www.apache.org/licenses/LICENSE-2.0 187 | 188 | Unless required by applicable law or agreed to in writing, software 189 | distributed under the License is distributed on an "AS IS" BASIS, 190 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 191 | See the License for the specific language governing permissions and 192 | limitations under the License. 193 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # netns - network namespaces in go # 2 | 3 | The netns package provides an ultra-simple interface for handling 4 | network namespaces in go. Changing namespaces requires elevated 5 | privileges, so in most cases this code needs to be run as root. 6 | 7 | ## Local Build and Test ## 8 | 9 | You can use go get command: 10 | 11 | go get github.com/vishvananda/netns 12 | 13 | Testing (requires root): 14 | 15 | sudo -E go test github.com/vishvananda/netns 16 | 17 | ## Example ## 18 | 19 | ```go 20 | package main 21 | 22 | import ( 23 | "fmt" 24 | "net" 25 | "runtime" 26 | 27 | "github.com/vishvananda/netns" 28 | ) 29 | 30 | func main() { 31 | // Lock the OS Thread so we don't accidentally switch namespaces 32 | runtime.LockOSThread() 33 | defer runtime.UnlockOSThread() 34 | 35 | // Save the current network namespace 36 | origns, _ := netns.Get() 37 | defer origns.Close() 38 | 39 | // Create a new network namespace 40 | newns, _ := netns.New() 41 | defer newns.Close() 42 | 43 | // Do something with the network namespace 44 | ifaces, _ := net.Interfaces() 45 | fmt.Printf("Interfaces: %v\n", ifaces) 46 | 47 | // Switch back to the original namespace 48 | netns.Set(origns) 49 | } 50 | 51 | ``` 52 | -------------------------------------------------------------------------------- /doc.go: -------------------------------------------------------------------------------- 1 | // Package netns allows ultra-simple network namespace handling. NsHandles 2 | // can be retrieved and set. Note that the current namespace is thread 3 | // local so actions that set and reset namespaces should use LockOSThread 4 | // to make sure the namespace doesn't change due to a goroutine switch. 5 | // It is best to close NsHandles when you are done with them. This can be 6 | // accomplished via a `defer ns.Close()` on the handle. Changing namespaces 7 | // requires elevated privileges, so in most cases this code needs to be run 8 | // as root. 9 | package netns 10 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/vishvananda/netns 2 | 3 | go 1.23 4 | 5 | require golang.org/x/sys v0.4.0 6 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | golang.org/x/sys v0.4.0 h1:Zr2JFtRQNX3BCZ8YtxRE9hNJYC8J6I1MVbMg6owUp18= 2 | golang.org/x/sys v0.4.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 3 | -------------------------------------------------------------------------------- /netns_linux.go: -------------------------------------------------------------------------------- 1 | package netns 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | "path" 7 | "path/filepath" 8 | "strconv" 9 | "strings" 10 | 11 | "golang.org/x/sys/unix" 12 | ) 13 | 14 | // Deprecated: use golang.org/x/sys/unix pkg instead. 15 | const ( 16 | CLONE_NEWUTS = unix.CLONE_NEWUTS /* New utsname group? */ 17 | CLONE_NEWIPC = unix.CLONE_NEWIPC /* New ipcs */ 18 | CLONE_NEWUSER = unix.CLONE_NEWUSER /* New user namespace */ 19 | CLONE_NEWPID = unix.CLONE_NEWPID /* New pid namespace */ 20 | CLONE_NEWNET = unix.CLONE_NEWNET /* New network namespace */ 21 | CLONE_IO = unix.CLONE_IO /* Get io context */ 22 | ) 23 | 24 | const bindMountPath = "/run/netns" /* Bind mount path for named netns */ 25 | 26 | // Setns sets namespace using golang.org/x/sys/unix.Setns. 27 | // 28 | // Deprecated: Use golang.org/x/sys/unix.Setns instead. 29 | func Setns(ns NsHandle, nstype int) error { 30 | return unix.Setns(int(ns), nstype) 31 | } 32 | 33 | // Set sets the current network namespace to the namespace represented 34 | // by NsHandle. 35 | func Set(ns NsHandle) error { 36 | return unix.Setns(int(ns), unix.CLONE_NEWNET) 37 | } 38 | 39 | // New creates a new network namespace, sets it as current and returns 40 | // a handle to it. 41 | func New() (NsHandle, error) { 42 | if err := unix.Unshare(unix.CLONE_NEWNET); err != nil { 43 | return -1, err 44 | } 45 | return Get() 46 | } 47 | 48 | // NewNamed creates a new named network namespace, sets it as current, 49 | // and returns a handle to it 50 | func NewNamed(name string) (NsHandle, error) { 51 | if _, err := os.Stat(bindMountPath); os.IsNotExist(err) { 52 | err = os.MkdirAll(bindMountPath, 0o755) 53 | if err != nil { 54 | return None(), err 55 | } 56 | } 57 | 58 | newNs, err := New() 59 | if err != nil { 60 | return None(), err 61 | } 62 | 63 | namedPath := path.Join(bindMountPath, name) 64 | 65 | f, err := os.OpenFile(namedPath, os.O_CREATE|os.O_EXCL, 0o444) 66 | if err != nil { 67 | newNs.Close() 68 | return None(), err 69 | } 70 | f.Close() 71 | 72 | nsPath := fmt.Sprintf("/proc/%d/task/%d/ns/net", os.Getpid(), unix.Gettid()) 73 | err = unix.Mount(nsPath, namedPath, "bind", unix.MS_BIND, "") 74 | if err != nil { 75 | newNs.Close() 76 | return None(), err 77 | } 78 | 79 | return newNs, nil 80 | } 81 | 82 | // DeleteNamed deletes a named network namespace 83 | func DeleteNamed(name string) error { 84 | namedPath := path.Join(bindMountPath, name) 85 | 86 | err := unix.Unmount(namedPath, unix.MNT_DETACH) 87 | if err != nil { 88 | return err 89 | } 90 | 91 | return os.Remove(namedPath) 92 | } 93 | 94 | // Get gets a handle to the current threads network namespace. 95 | func Get() (NsHandle, error) { 96 | return GetFromThread(os.Getpid(), unix.Gettid()) 97 | } 98 | 99 | // GetFromPath gets a handle to a network namespace 100 | // identified by the path 101 | func GetFromPath(path string) (NsHandle, error) { 102 | fd, err := unix.Open(path, unix.O_RDONLY|unix.O_CLOEXEC, 0) 103 | if err != nil { 104 | return -1, err 105 | } 106 | return NsHandle(fd), nil 107 | } 108 | 109 | // GetFromName gets a handle to a named network namespace such as one 110 | // created by `ip netns add`. 111 | func GetFromName(name string) (NsHandle, error) { 112 | return GetFromPath(filepath.Join(bindMountPath, name)) 113 | } 114 | 115 | // GetFromPid gets a handle to the network namespace of a given pid. 116 | func GetFromPid(pid int) (NsHandle, error) { 117 | return GetFromPath(fmt.Sprintf("/proc/%d/ns/net", pid)) 118 | } 119 | 120 | // GetFromThread gets a handle to the network namespace of a given pid and tid. 121 | func GetFromThread(pid, tid int) (NsHandle, error) { 122 | return GetFromPath(fmt.Sprintf("/proc/%d/task/%d/ns/net", pid, tid)) 123 | } 124 | 125 | // GetFromDocker gets a handle to the network namespace of a docker container. 126 | // Id is prefixed matched against the running docker containers, so a short 127 | // identifier can be used as long as it isn't ambiguous. 128 | func GetFromDocker(id string) (NsHandle, error) { 129 | pid, err := getPidForContainer(id) 130 | if err != nil { 131 | return -1, err 132 | } 133 | return GetFromPid(pid) 134 | } 135 | 136 | // borrowed from docker/utils/utils.go 137 | func findCgroupMountpoint(cgroupType string) (int, string, error) { 138 | output, err := os.ReadFile("/proc/mounts") 139 | if err != nil { 140 | return -1, "", err 141 | } 142 | 143 | // /proc/mounts has 6 fields per line, one mount per line, e.g. 144 | // cgroup /sys/fs/cgroup/devices cgroup rw,relatime,devices 0 0 145 | for _, line := range strings.Split(string(output), "\n") { 146 | parts := strings.Split(line, " ") 147 | if len(parts) == 6 { 148 | switch parts[2] { 149 | case "cgroup2": 150 | return 2, parts[1], nil 151 | case "cgroup": 152 | for _, opt := range strings.Split(parts[3], ",") { 153 | if opt == cgroupType { 154 | return 1, parts[1], nil 155 | } 156 | } 157 | } 158 | } 159 | } 160 | 161 | return -1, "", fmt.Errorf("cgroup mountpoint not found for %s", cgroupType) 162 | } 163 | 164 | // Returns the relative path to the cgroup docker is running in. 165 | // borrowed from docker/utils/utils.go 166 | // modified to get the docker pid instead of using /proc/self 167 | func getDockerCgroup(cgroupVer int, cgroupType string) (string, error) { 168 | dockerpid, err := os.ReadFile("/var/run/docker.pid") 169 | if err != nil { 170 | return "", err 171 | } 172 | result := strings.Split(string(dockerpid), "\n") 173 | if len(result) == 0 || len(result[0]) == 0 { 174 | return "", fmt.Errorf("docker pid not found in /var/run/docker.pid") 175 | } 176 | pid, err := strconv.Atoi(result[0]) 177 | if err != nil { 178 | return "", err 179 | } 180 | output, err := os.ReadFile(fmt.Sprintf("/proc/%d/cgroup", pid)) 181 | if err != nil { 182 | return "", err 183 | } 184 | for _, line := range strings.Split(string(output), "\n") { 185 | parts := strings.Split(line, ":") 186 | // any type used by docker should work 187 | if (cgroupVer == 1 && parts[1] == cgroupType) || 188 | (cgroupVer == 2 && parts[1] == "") { 189 | return parts[2], nil 190 | } 191 | } 192 | return "", fmt.Errorf("cgroup '%s' not found in /proc/%d/cgroup", cgroupType, pid) 193 | } 194 | 195 | // Returns the first pid in a container. 196 | // borrowed from docker/utils/utils.go 197 | // modified to only return the first pid 198 | // modified to glob with id 199 | // modified to search for newer docker containers 200 | // modified to look for cgroups v2 201 | func getPidForContainer(id string) (int, error) { 202 | pid := 0 203 | 204 | // memory is chosen randomly, any cgroup used by docker works 205 | cgroupType := "memory" 206 | 207 | cgroupVer, cgroupRoot, err := findCgroupMountpoint(cgroupType) 208 | if err != nil { 209 | return pid, err 210 | } 211 | 212 | cgroupDocker, err := getDockerCgroup(cgroupVer, cgroupType) 213 | if err != nil { 214 | return pid, err 215 | } 216 | 217 | id += "*" 218 | 219 | var pidFile string 220 | switch cgroupVer { 221 | case 1: 222 | pidFile = "tasks" 223 | case 2: 224 | pidFile = "cgroup.procs" 225 | default: 226 | return -1, fmt.Errorf("invalid cgroup version '%d'", cgroupVer) 227 | } 228 | 229 | attempts := []string{ 230 | filepath.Join(cgroupRoot, cgroupDocker, id, pidFile), 231 | // With more recent lxc versions use, cgroup will be in lxc/ 232 | filepath.Join(cgroupRoot, cgroupDocker, "lxc", id, pidFile), 233 | // With more recent docker, cgroup will be in docker/ 234 | filepath.Join(cgroupRoot, cgroupDocker, "docker", id, pidFile), 235 | // Even more recent docker versions under systemd use docker-.scope/ 236 | filepath.Join(cgroupRoot, "system.slice", "docker-"+id+".scope", pidFile), 237 | // Even more recent docker versions under cgroup/systemd/docker// 238 | filepath.Join(cgroupRoot, "..", "systemd", "docker", id, pidFile), 239 | // Kubernetes with docker and CNI is even more different. Works for BestEffort and Burstable QoS 240 | filepath.Join(cgroupRoot, "..", "systemd", "kubepods", "*", "pod*", id, pidFile), 241 | // Same as above but for Guaranteed QoS 242 | filepath.Join(cgroupRoot, "..", "systemd", "kubepods", "pod*", id, pidFile), 243 | // Another flavor of containers location in recent kubernetes 1.11+. Works for BestEffort and Burstable QoS 244 | filepath.Join(cgroupRoot, cgroupDocker, "kubepods.slice", "*.slice", "*", "docker-"+id+".scope", pidFile), 245 | // Same as above but for Guaranteed QoS 246 | filepath.Join(cgroupRoot, cgroupDocker, "kubepods.slice", "*", "docker-"+id+".scope", pidFile), 247 | // When runs inside of a container with recent kubernetes 1.11+. Works for BestEffort and Burstable QoS 248 | filepath.Join(cgroupRoot, "kubepods.slice", "*.slice", "*", "docker-"+id+".scope", pidFile), 249 | // Same as above but for Guaranteed QoS 250 | filepath.Join(cgroupRoot, "kubepods.slice", "*", "docker-"+id+".scope", pidFile), 251 | // Support for nerdctl 252 | filepath.Join(cgroupRoot, "system.slice", "nerdctl-"+id+".scope", pidFile), 253 | // Support for finch 254 | filepath.Join(cgroupRoot, "..", "systemd", "finch", id, pidFile), 255 | } 256 | 257 | var filename string 258 | for _, attempt := range attempts { 259 | filenames, _ := filepath.Glob(attempt) 260 | if len(filenames) > 1 { 261 | return pid, fmt.Errorf("ambiguous id supplied: %v", filenames) 262 | } else if len(filenames) == 1 { 263 | filename = filenames[0] 264 | break 265 | } 266 | } 267 | 268 | if filename == "" { 269 | return pid, fmt.Errorf("unable to find container: %v", id[:len(id)-1]) 270 | } 271 | 272 | output, err := os.ReadFile(filename) 273 | if err != nil { 274 | return pid, err 275 | } 276 | 277 | result := strings.Split(string(output), "\n") 278 | if len(result) == 0 || len(result[0]) == 0 { 279 | return pid, fmt.Errorf("no pid found for container") 280 | } 281 | 282 | pid, err = strconv.Atoi(result[0]) 283 | if err != nil { 284 | return pid, fmt.Errorf("invalid pid '%s': %w", result[0], err) 285 | } 286 | 287 | return pid, nil 288 | } 289 | -------------------------------------------------------------------------------- /netns_linux_test.go: -------------------------------------------------------------------------------- 1 | package netns 2 | 3 | import ( 4 | "runtime" 5 | "sync" 6 | "testing" 7 | ) 8 | 9 | func TestGetNewSetDelete(t *testing.T) { 10 | runtime.LockOSThread() 11 | defer runtime.UnlockOSThread() 12 | 13 | origns, err := Get() 14 | if err != nil { 15 | t.Fatal(err) 16 | } 17 | newns, err := New() 18 | if err != nil { 19 | t.Fatal(err) 20 | } 21 | if origns.Equal(newns) { 22 | t.Fatal("New ns failed") 23 | } 24 | if err := Set(origns); err != nil { 25 | t.Fatal(err) 26 | } 27 | if err := newns.Close(); err != nil { 28 | t.Error("Failed to close ns", err) 29 | } 30 | if newns.IsOpen() { 31 | t.Fatal("newns still open after close", newns) 32 | } 33 | ns, err := Get() 34 | if err != nil { 35 | t.Fatal(err) 36 | } 37 | if !ns.Equal(origns) { 38 | t.Fatal("Reset ns failed", origns, newns, ns) 39 | } 40 | } 41 | 42 | func TestNone(t *testing.T) { 43 | ns := None() 44 | if ns.IsOpen() { 45 | t.Fatal("None ns is open", ns) 46 | } 47 | } 48 | 49 | func TestThreaded(t *testing.T) { 50 | ncpu := runtime.GOMAXPROCS(-1) 51 | if ncpu < 2 { 52 | t.Skip("-cpu=2 or larger required") 53 | } 54 | 55 | // Lock this thread simply to ensure other threads get used. 56 | runtime.LockOSThread() 57 | defer runtime.UnlockOSThread() 58 | 59 | wg := &sync.WaitGroup{} 60 | for i := 0; i < ncpu; i++ { 61 | wg.Add(1) 62 | go func() { 63 | defer wg.Done() 64 | TestGetNewSetDelete(t) 65 | }() 66 | } 67 | wg.Wait() 68 | } 69 | -------------------------------------------------------------------------------- /netns_others.go: -------------------------------------------------------------------------------- 1 | //go:build !linux 2 | // +build !linux 3 | 4 | package netns 5 | 6 | import "errors" 7 | 8 | var ErrNotImplemented = errors.New("not implemented") 9 | 10 | // Setns sets namespace using golang.org/x/sys/unix.Setns on Linux. It 11 | // is not implemented on other platforms. 12 | // 13 | // Deprecated: Use golang.org/x/sys/unix.Setns instead. 14 | func Setns(ns NsHandle, nstype int) error { 15 | return ErrNotImplemented 16 | } 17 | 18 | func Set(ns NsHandle) error { 19 | return ErrNotImplemented 20 | } 21 | 22 | func New() (NsHandle, error) { 23 | return -1, ErrNotImplemented 24 | } 25 | 26 | func NewNamed(name string) (NsHandle, error) { 27 | return -1, ErrNotImplemented 28 | } 29 | 30 | func DeleteNamed(name string) error { 31 | return ErrNotImplemented 32 | } 33 | 34 | func Get() (NsHandle, error) { 35 | return -1, ErrNotImplemented 36 | } 37 | 38 | func GetFromPath(path string) (NsHandle, error) { 39 | return -1, ErrNotImplemented 40 | } 41 | 42 | func GetFromName(name string) (NsHandle, error) { 43 | return -1, ErrNotImplemented 44 | } 45 | 46 | func GetFromPid(pid int) (NsHandle, error) { 47 | return -1, ErrNotImplemented 48 | } 49 | 50 | func GetFromThread(pid int, tid int) (NsHandle, error) { 51 | return -1, ErrNotImplemented 52 | } 53 | 54 | func GetFromDocker(id string) (NsHandle, error) { 55 | return -1, ErrNotImplemented 56 | } 57 | -------------------------------------------------------------------------------- /nshandle_linux.go: -------------------------------------------------------------------------------- 1 | package netns 2 | 3 | import ( 4 | "fmt" 5 | 6 | "golang.org/x/sys/unix" 7 | ) 8 | 9 | // NsHandle is a handle to a network namespace. It can be cast directly 10 | // to an int and used as a file descriptor. 11 | type NsHandle int 12 | 13 | // Equal determines if two network handles refer to the same network 14 | // namespace. This is done by comparing the device and inode that the 15 | // file descriptors point to. 16 | func (ns NsHandle) Equal(other NsHandle) bool { 17 | if ns == other { 18 | return true 19 | } 20 | var s1, s2 unix.Stat_t 21 | if err := unix.Fstat(int(ns), &s1); err != nil { 22 | return false 23 | } 24 | if err := unix.Fstat(int(other), &s2); err != nil { 25 | return false 26 | } 27 | return (s1.Dev == s2.Dev) && (s1.Ino == s2.Ino) 28 | } 29 | 30 | // String shows the file descriptor number and its dev and inode. 31 | func (ns NsHandle) String() string { 32 | if ns == -1 { 33 | return "NS(none)" 34 | } 35 | var s unix.Stat_t 36 | if err := unix.Fstat(int(ns), &s); err != nil { 37 | return fmt.Sprintf("NS(%d: unknown)", ns) 38 | } 39 | return fmt.Sprintf("NS(%d: %d, %d)", ns, s.Dev, s.Ino) 40 | } 41 | 42 | // UniqueId returns a string which uniquely identifies the namespace 43 | // associated with the network handle. 44 | func (ns NsHandle) UniqueId() string { 45 | if ns == -1 { 46 | return "NS(none)" 47 | } 48 | var s unix.Stat_t 49 | if err := unix.Fstat(int(ns), &s); err != nil { 50 | return "NS(unknown)" 51 | } 52 | return fmt.Sprintf("NS(%d:%d)", s.Dev, s.Ino) 53 | } 54 | 55 | // IsOpen returns true if Close() has not been called. 56 | func (ns NsHandle) IsOpen() bool { 57 | return ns != -1 58 | } 59 | 60 | // Close closes the NsHandle and resets its file descriptor to -1. 61 | // It is not safe to use an NsHandle after Close() is called. 62 | func (ns *NsHandle) Close() error { 63 | if err := unix.Close(int(*ns)); err != nil { 64 | return err 65 | } 66 | *ns = -1 67 | return nil 68 | } 69 | 70 | // None gets an empty (closed) NsHandle. 71 | func None() NsHandle { 72 | return NsHandle(-1) 73 | } 74 | -------------------------------------------------------------------------------- /nshandle_others.go: -------------------------------------------------------------------------------- 1 | //go:build !linux 2 | // +build !linux 3 | 4 | package netns 5 | 6 | // NsHandle is a handle to a network namespace. It can only be used on Linux, 7 | // but provides stub methods on other platforms. 8 | type NsHandle int 9 | 10 | // Equal determines if two network handles refer to the same network 11 | // namespace. It is only implemented on Linux. 12 | func (ns NsHandle) Equal(_ NsHandle) bool { 13 | return false 14 | } 15 | 16 | // String shows the file descriptor number and its dev and inode. 17 | // It is only implemented on Linux, and returns "NS(none)" on other 18 | // platforms. 19 | func (ns NsHandle) String() string { 20 | return "NS(none)" 21 | } 22 | 23 | // UniqueId returns a string which uniquely identifies the namespace 24 | // associated with the network handle. It is only implemented on Linux, 25 | // and returns "NS(none)" on other platforms. 26 | func (ns NsHandle) UniqueId() string { 27 | return "NS(none)" 28 | } 29 | 30 | // IsOpen returns true if Close() has not been called. It is only implemented 31 | // on Linux and always returns false on other platforms. 32 | func (ns NsHandle) IsOpen() bool { 33 | return false 34 | } 35 | 36 | // Close closes the NsHandle and resets its file descriptor to -1. 37 | // It is only implemented on Linux. 38 | func (ns *NsHandle) Close() error { 39 | return nil 40 | } 41 | 42 | // None gets an empty (closed) NsHandle. 43 | func None() NsHandle { 44 | return NsHandle(-1) 45 | } 46 | --------------------------------------------------------------------------------