Skip to content

Commit be8852b

Browse files
author
Eugene Yakubovich
committed
Add GetFromPath to construct NsHandle from any path
Also makes other Get functions utilize GetFromPath to avoid duplication.
1 parent 5478c06 commit be8852b

File tree

1 file changed

+12
-15
lines changed

1 file changed

+12
-15
lines changed

netns_linux.go

Lines changed: 12 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -52,33 +52,30 @@ func Get() (NsHandle, error) {
5252
return GetFromThread(os.Getpid(), syscall.Gettid())
5353
}
5454

55-
// GetFromName gets a handle to a named network namespace such as one
56-
// created by `ip netns add`.
57-
func GetFromName(name string) (NsHandle, error) {
58-
fd, err := syscall.Open(fmt.Sprintf("/var/run/netns/%s", name), syscall.O_RDONLY, 0)
55+
// GetFromPath gets a handle to a network namespace
56+
// identified by the path
57+
func GetFromPath(path string) (NsHandle, error) {
58+
fd, err := syscall.Open(path, syscall.O_RDONLY, 0)
5959
if err != nil {
6060
return -1, err
6161
}
6262
return NsHandle(fd), nil
6363
}
6464

65+
// GetFromName gets a handle to a named network namespace such as one
66+
// created by `ip netns add`.
67+
func GetFromName(name string) (NsHandle, error) {
68+
return GetFromPath(fmt.Sprintf("/var/run/netns/%s", name))
69+
}
70+
6571
// GetFromPid gets a handle to the network namespace of a given pid.
6672
func GetFromPid(pid int) (NsHandle, error) {
67-
fd, err := syscall.Open(fmt.Sprintf("/proc/%d/ns/net", pid), syscall.O_RDONLY, 0)
68-
if err != nil {
69-
return -1, err
70-
}
71-
return NsHandle(fd), nil
73+
return GetFromPath(fmt.Sprintf("/proc/%d/ns/net", pid))
7274
}
7375

7476
// GetFromThread gets a handle to the network namespace of a given pid and tid.
7577
func GetFromThread(pid, tid int) (NsHandle, error) {
76-
name := fmt.Sprintf("/proc/%d/task/%d/ns/net", pid, tid)
77-
fd, err := syscall.Open(name, syscall.O_RDONLY, 0)
78-
if err != nil {
79-
return -1, err
80-
}
81-
return NsHandle(fd), nil
78+
return GetFromPath(fmt.Sprintf("/proc/%d/task/%d/ns/net", pid, tid))
8279
}
8380

8481
// GetFromDocker gets a handle to the network namespace of a docker container.

0 commit comments

Comments
 (0)