namespaces_unix.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. // +build linux freebsd
  2. package configs
  3. import "fmt"
  4. const (
  5. NEWNET NamespaceType = "NEWNET"
  6. NEWPID NamespaceType = "NEWPID"
  7. NEWNS NamespaceType = "NEWNS"
  8. NEWUTS NamespaceType = "NEWUTS"
  9. NEWIPC NamespaceType = "NEWIPC"
  10. NEWUSER NamespaceType = "NEWUSER"
  11. )
  12. func NamespaceTypes() []NamespaceType {
  13. return []NamespaceType{
  14. NEWNET,
  15. NEWPID,
  16. NEWNS,
  17. NEWUTS,
  18. NEWIPC,
  19. NEWUSER,
  20. }
  21. }
  22. // Namespace defines configuration for each namespace. It specifies an
  23. // alternate path that is able to be joined via setns.
  24. type Namespace struct {
  25. Type NamespaceType `json:"type"`
  26. Path string `json:"path"`
  27. }
  28. func (n *Namespace) GetPath(pid int) string {
  29. if n.Path != "" {
  30. return n.Path
  31. }
  32. return fmt.Sprintf("/proc/%d/ns/%s", pid, n.file())
  33. }
  34. func (n *Namespace) file() string {
  35. file := ""
  36. switch n.Type {
  37. case NEWNET:
  38. file = "net"
  39. case NEWNS:
  40. file = "mnt"
  41. case NEWPID:
  42. file = "pid"
  43. case NEWIPC:
  44. file = "ipc"
  45. case NEWUSER:
  46. file = "user"
  47. case NEWUTS:
  48. file = "uts"
  49. }
  50. return file
  51. }
  52. func (n *Namespaces) Remove(t NamespaceType) bool {
  53. i := n.index(t)
  54. if i == -1 {
  55. return false
  56. }
  57. *n = append((*n)[:i], (*n)[i+1:]...)
  58. return true
  59. }
  60. func (n *Namespaces) Add(t NamespaceType, path string) {
  61. i := n.index(t)
  62. if i == -1 {
  63. *n = append(*n, Namespace{Type: t, Path: path})
  64. return
  65. }
  66. (*n)[i].Path = path
  67. }
  68. func (n *Namespaces) index(t NamespaceType) int {
  69. for i, ns := range *n {
  70. if ns.Type == t {
  71. return i
  72. }
  73. }
  74. return -1
  75. }
  76. func (n *Namespaces) Contains(t NamespaceType) bool {
  77. return n.index(t) != -1
  78. }