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