forked from genuinetools/netns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
list.go
84 lines (72 loc) · 1.81 KB
/
list.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
81
82
83
84
package main
import (
"fmt"
"net"
"os"
"path"
"strconv"
"text/tabwriter"
"github.com/boltdb/bolt"
"github.com/jfrazelle/netns/ipallocator"
"github.com/vishvananda/netlink"
"github.com/vishvananda/netns"
)
type network struct {
vethPair *netlink.Veth
ip net.IP
pid int
status string
fd netns.NsHandle
}
func listNetworks() error {
// open the database
dbpath := path.Join(stateDir, ipallocator.DBFile)
db, err := bolt.Open(dbpath, 0666, nil)
if err != nil {
return fmt.Errorf("Opening database at %s failed: %v", dbpath, err)
}
defer db.Close()
var networks []network
if err := db.View(func(tx *bolt.Tx) error {
// Retrieve the jobs bucket.
b := tx.Bucket(ipallocator.IPBucket)
return b.ForEach(func(k, v []byte) error {
n := network{
ip: net.ParseIP(string(k)),
}
// get the pid
n.pid, err = strconv.Atoi(string(v))
if err != nil {
return fmt.Errorf("parsing pid %s as int failed: %v", v, err)
}
// check the process
_, err := os.FindProcess(n.pid)
if err != nil {
n.status = "does not exist"
} else {
n.status = "running"
}
// get the veth pair from the pid
n.vethPair, err = vethPair(n.pid, bridgeName)
if err != nil {
return fmt.Errorf("Getting vethpair failed for pid %d: %v", n.pid, err)
}
// try to get the namespace handle
n.fd, _ = netns.GetFromPid(n.pid)
if n.fd <= 0 {
n.status = "destroyed"
}
networks = append(networks, n)
return nil
})
}); err != nil {
return fmt.Errorf("Getting networks from db failed: %v", err)
}
w := tabwriter.NewWriter(os.Stdout, 20, 1, 3, ' ', 0)
fmt.Fprint(w, "IP\tLOCAL VETH\tPID\tSTATUS\tNS FD\n")
for _, n := range networks {
fmt.Fprintf(w, "%s\t%s\t%d\t%s\t%d\n", n.ip.String(), n.vethPair.Attrs().Name, n.pid, n.status, n.fd)
}
w.Flush()
return nil
}