forked from vishvananda/netns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
nshandle_linux.go
73 lines (64 loc) · 1.71 KB
/
nshandle_linux.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
package netns
import (
"fmt"
"golang.org/x/sys/unix"
)
// NsHandle is a handle to a network namespace. It can be cast directly
// to an int and used as a file descriptor.
type NsHandle int
// Equal determines if two network handles refer to the same network
// namespace. This is done by comparing the device and inode that the
// file descriptors point to.
func (ns NsHandle) Equal(other NsHandle) bool {
if ns == other {
return true
}
var s1, s2 unix.Stat_t
if err := unix.Fstat(int(ns), &s1); err != nil {
return false
}
if err := unix.Fstat(int(other), &s2); err != nil {
return false
}
return (s1.Dev == s2.Dev) && (s1.Ino == s2.Ino)
}
// String shows the file descriptor number and its dev and inode.
func (ns NsHandle) String() string {
if ns == -1 {
return "NS(none)"
}
var s unix.Stat_t
if err := unix.Fstat(int(ns), &s); err != nil {
return fmt.Sprintf("NS(%d: unknown)", ns)
}
return fmt.Sprintf("NS(%d: %d, %d)", ns, s.Dev, s.Ino)
}
// UniqueId returns a string which uniquely identifies the namespace
// associated with the network handle.
func (ns NsHandle) UniqueId() string {
if ns == -1 {
return "NS(none)"
}
var s unix.Stat_t
if err := unix.Fstat(int(ns), &s); err != nil {
return "NS(unknown)"
}
return fmt.Sprintf("NS(%d:%d)", s.Dev, s.Ino)
}
// IsOpen returns true if Close() has not been called.
func (ns NsHandle) IsOpen() bool {
return ns != -1
}
// Close closes the NsHandle and resets its file descriptor to -1.
// It is not safe to use an NsHandle after Close() is called.
func (ns *NsHandle) Close() error {
if err := unix.Close(int(*ns)); err != nil {
return err
}
*ns = -1
return nil
}
// None gets an empty (closed) NsHandle.
func None() NsHandle {
return NsHandle(-1)
}