-
Notifications
You must be signed in to change notification settings - Fork 0
/
namespace.go
86 lines (72 loc) · 1.76 KB
/
namespace.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
85
86
package namespace
import (
"errors"
"fmt"
"os"
"path/filepath"
"strconv"
"syscall"
)
var (
ErrNotImplemented = errors.New("not implemented")
)
type nstype int
type Namespace struct {
proc string
pid int
types []nstype
flags int64
prefix string
currents []*namespace
targets []*namespace
}
// New creates a new Namespace instance
func New(options ...Option) (*Namespace, error) {
ns := &Namespace{proc: "/proc", pid: -1}
for _, option := range options {
option(ns)
}
if ns.pid <= 0 {
return nil, errors.New("namespace id is not specified")
}
for _, t := range ns.types {
if t == MNT {
return nil, fmt.Errorf("mnt namespace is not supported, using ReadFile/Stat instead")
}
}
var (
cns string
tns string
err error
)
currentNSPath := filepath.Join("/proc", strconv.Itoa(os.Getpid()), "task", strconv.Itoa(syscall.Gettid()), "ns")
targetNSPath := filepath.Join(ns.proc, strconv.Itoa(ns.pid), "ns")
ns.prefix = targetNSPath
if len(ns.types) > 0 {
ns.currents = make([]*namespace, 0, len(ns.types))
ns.targets = make([]*namespace, 0, len(ns.types))
for _, nst := range ns.types {
cpath := filepath.Join(currentNSPath, nst.String())
if cns, err = os.Readlink(cpath); err != nil {
return nil, err
}
tpath := filepath.Join(targetNSPath, nst.String())
if tns, err = os.Readlink(tpath); err != nil {
return nil, err
}
// skip namespace same with current task
if cns != tns {
ns.currents = append(ns.currents, &namespace{path: cpath, nst: nst, fd: -1})
ns.targets = append(ns.targets, &namespace{path: tpath, nst: nst, fd: -1})
ns.flags |= int64(nst)
}
}
}
return ns, nil
}
// namespace represents a system namespace
type namespace struct {
path string
nst nstype
fd int
}