netns_linux.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. // +build linux
  2. package netns
  3. import (
  4. "fmt"
  5. "io/ioutil"
  6. "os"
  7. "path/filepath"
  8. "runtime"
  9. "strconv"
  10. "strings"
  11. "syscall"
  12. )
  13. // SYS_SETNS syscall allows changing the namespace of the current process.
  14. var SYS_SETNS = map[string]uintptr{
  15. "386": 346,
  16. "amd64": 308,
  17. "arm64": 268,
  18. "arm": 375,
  19. "ppc64": 350,
  20. "ppc64le": 350,
  21. "s390x": 339,
  22. }[runtime.GOARCH]
  23. // Deprecated: use syscall pkg instead (go >= 1.5 needed).
  24. const (
  25. CLONE_NEWUTS = 0x04000000 /* New utsname group? */
  26. CLONE_NEWIPC = 0x08000000 /* New ipcs */
  27. CLONE_NEWUSER = 0x10000000 /* New user namespace */
  28. CLONE_NEWPID = 0x20000000 /* New pid namespace */
  29. CLONE_NEWNET = 0x40000000 /* New network namespace */
  30. CLONE_IO = 0x80000000 /* Get io context */
  31. )
  32. // Setns sets namespace using syscall. Note that this should be a method
  33. // in syscall but it has not been added.
  34. func Setns(ns NsHandle, nstype int) (err error) {
  35. _, _, e1 := syscall.Syscall(SYS_SETNS, uintptr(ns), uintptr(nstype), 0)
  36. if e1 != 0 {
  37. err = e1
  38. }
  39. return
  40. }
  41. // Set sets the current network namespace to the namespace represented
  42. // by NsHandle.
  43. func Set(ns NsHandle) (err error) {
  44. return Setns(ns, CLONE_NEWNET)
  45. }
  46. // New creates a new network namespace and returns a handle to it.
  47. func New() (ns NsHandle, err error) {
  48. if err := syscall.Unshare(CLONE_NEWNET); err != nil {
  49. return -1, err
  50. }
  51. return Get()
  52. }
  53. // Get gets a handle to the current threads network namespace.
  54. func Get() (NsHandle, error) {
  55. return GetFromThread(os.Getpid(), syscall.Gettid())
  56. }
  57. // GetFromPath gets a handle to a network namespace
  58. // identified by the path
  59. func GetFromPath(path string) (NsHandle, error) {
  60. fd, err := syscall.Open(path, syscall.O_RDONLY, 0)
  61. if err != nil {
  62. return -1, err
  63. }
  64. return NsHandle(fd), nil
  65. }
  66. // GetFromName gets a handle to a named network namespace such as one
  67. // created by `ip netns add`.
  68. func GetFromName(name string) (NsHandle, error) {
  69. return GetFromPath(fmt.Sprintf("/var/run/netns/%s", name))
  70. }
  71. // GetFromPid gets a handle to the network namespace of a given pid.
  72. func GetFromPid(pid int) (NsHandle, error) {
  73. return GetFromPath(fmt.Sprintf("/proc/%d/ns/net", pid))
  74. }
  75. // GetFromThread gets a handle to the network namespace of a given pid and tid.
  76. func GetFromThread(pid, tid int) (NsHandle, error) {
  77. return GetFromPath(fmt.Sprintf("/proc/%d/task/%d/ns/net", pid, tid))
  78. }
  79. // GetFromDocker gets a handle to the network namespace of a docker container.
  80. // Id is prefixed matched against the running docker containers, so a short
  81. // identifier can be used as long as it isn't ambiguous.
  82. func GetFromDocker(id string) (NsHandle, error) {
  83. pid, err := getPidForContainer(id)
  84. if err != nil {
  85. return -1, err
  86. }
  87. return GetFromPid(pid)
  88. }
  89. // borrowed from docker/utils/utils.go
  90. func findCgroupMountpoint(cgroupType string) (string, error) {
  91. output, err := ioutil.ReadFile("/proc/mounts")
  92. if err != nil {
  93. return "", err
  94. }
  95. // /proc/mounts has 6 fields per line, one mount per line, e.g.
  96. // cgroup /sys/fs/cgroup/devices cgroup rw,relatime,devices 0 0
  97. for _, line := range strings.Split(string(output), "\n") {
  98. parts := strings.Split(line, " ")
  99. if len(parts) == 6 && parts[2] == "cgroup" {
  100. for _, opt := range strings.Split(parts[3], ",") {
  101. if opt == cgroupType {
  102. return parts[1], nil
  103. }
  104. }
  105. }
  106. }
  107. return "", fmt.Errorf("cgroup mountpoint not found for %s", cgroupType)
  108. }
  109. // Returns the relative path to the cgroup docker is running in.
  110. // borrowed from docker/utils/utils.go
  111. // modified to get the docker pid instead of using /proc/self
  112. func getThisCgroup(cgroupType string) (string, error) {
  113. dockerpid, err := ioutil.ReadFile("/var/run/docker.pid")
  114. if err != nil {
  115. return "", err
  116. }
  117. result := strings.Split(string(dockerpid), "\n")
  118. if len(result) == 0 || len(result[0]) == 0 {
  119. return "", fmt.Errorf("docker pid not found in /var/run/docker.pid")
  120. }
  121. pid, err := strconv.Atoi(result[0])
  122. output, err := ioutil.ReadFile(fmt.Sprintf("/proc/%d/cgroup", pid))
  123. if err != nil {
  124. return "", err
  125. }
  126. for _, line := range strings.Split(string(output), "\n") {
  127. parts := strings.Split(line, ":")
  128. // any type used by docker should work
  129. if parts[1] == cgroupType {
  130. return parts[2], nil
  131. }
  132. }
  133. return "", fmt.Errorf("cgroup '%s' not found in /proc/%d/cgroup", cgroupType, pid)
  134. }
  135. // Returns the first pid in a container.
  136. // borrowed from docker/utils/utils.go
  137. // modified to only return the first pid
  138. // modified to glob with id
  139. // modified to search for newer docker containers
  140. func getPidForContainer(id string) (int, error) {
  141. pid := 0
  142. // memory is chosen randomly, any cgroup used by docker works
  143. cgroupType := "memory"
  144. cgroupRoot, err := findCgroupMountpoint(cgroupType)
  145. if err != nil {
  146. return pid, err
  147. }
  148. cgroupThis, err := getThisCgroup(cgroupType)
  149. if err != nil {
  150. return pid, err
  151. }
  152. id += "*"
  153. attempts := []string{
  154. filepath.Join(cgroupRoot, cgroupThis, id, "tasks"),
  155. // With more recent lxc versions use, cgroup will be in lxc/
  156. filepath.Join(cgroupRoot, cgroupThis, "lxc", id, "tasks"),
  157. // With more recent docker, cgroup will be in docker/
  158. filepath.Join(cgroupRoot, cgroupThis, "docker", id, "tasks"),
  159. // Even more recent docker versions under systemd use docker-<id>.scope/
  160. filepath.Join(cgroupRoot, "system.slice", "docker-"+id+".scope", "tasks"),
  161. // Even more recent docker versions under cgroup/systemd/docker/<id>/
  162. filepath.Join(cgroupRoot, "..", "systemd", "docker", id, "tasks"),
  163. }
  164. var filename string
  165. for _, attempt := range attempts {
  166. filenames, _ := filepath.Glob(attempt)
  167. if len(filenames) > 1 {
  168. return pid, fmt.Errorf("Ambiguous id supplied: %v", filenames)
  169. } else if len(filenames) == 1 {
  170. filename = filenames[0]
  171. break
  172. }
  173. }
  174. if filename == "" {
  175. return pid, fmt.Errorf("Unable to find container: %v", id[:len(id)-1])
  176. }
  177. output, err := ioutil.ReadFile(filename)
  178. if err != nil {
  179. return pid, err
  180. }
  181. result := strings.Split(string(output), "\n")
  182. if len(result) == 0 || len(result[0]) == 0 {
  183. return pid, fmt.Errorf("No pid found for container")
  184. }
  185. pid, err = strconv.Atoi(result[0])
  186. if err != nil {
  187. return pid, fmt.Errorf("Invalid pid '%s': %s", result[0], err)
  188. }
  189. return pid, nil
  190. }