-
Notifications
You must be signed in to change notification settings - Fork 0
/
netns.go
80 lines (68 loc) · 1.57 KB
/
netns.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package deploy
import (
"bytes"
"fmt"
"strings"
)
const (
// netnsPrefix is the prefix used to build namespace names
netnsPrefix = "netns-topo-"
)
var (
// networkNamespaces is the current list of active network namespaces
networkNamespaces []string
)
// Netns is a network namespace
type Netns struct {
Name string
}
// netnsName creates a network namespace name from topology and node name
func netnsName(topology, node string) string {
return fmt.Sprintf("%s%s-%s", netnsPrefix, topology, node)
}
// Start starts the network namespace
func (n *Netns) Start() {
runIP("netns", "add", n.Name)
}
// Stop stops the network namespace
func (n *Netns) Stop() {
runIP("netns", "delete", n.Name)
}
// listNetns returns the names of active network namespaces
func listNetns() []string {
// use buffered list of namespaces if present
if networkNamespaces != nil {
return networkNamespaces
}
// get list of namespaces
b := &bytes.Buffer{}
runIPStdout(b, "netns", "list")
nses := []string{}
for _, s := range strings.Split(b.String(), "\n") {
fields := strings.Fields(s)
if len(fields) == 0 {
continue
}
name := fields[0]
if strings.HasPrefix(name, "netns-topo-") {
nses = append(nses, name)
}
}
// buffer list of namespaces
networkNamespaces = nses
return nses
}
// Status returns the status of the network namespace
func (n *Netns) Status() Status {
nses := listNetns()
for _, ns := range nses {
if n.Name == ns {
return StatusActive
}
}
return StatusInactive
}
// NewNetns returns a new network namespace
func NewNetns() *Netns {
return &Netns{}
}