-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathns.go
73 lines (65 loc) · 1.5 KB
/
ns.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 common
import (
"fmt"
"github.com/prometheus/procfs"
)
const (
DockerdProcess = "dockerd"
ContainerdProcess = "containerd"
ContainerdProcessShim = "containerd-shim"
)
func getPidProc(hostProcPath string, pid int) (*procfs.Proc, error) {
fs, err := procfs.NewFS(hostProcPath)
if err != nil {
return nil, err
}
proc, err := fs.Proc(pid)
if err != nil {
return nil, err
}
return &proc, nil
}
func getSelfProc(hostProcPath string) (*procfs.Proc, error) {
fs, err := procfs.NewFS(hostProcPath)
if err != nil {
return nil, err
}
proc, err := fs.Self()
if err != nil {
return nil, err
}
return &proc, nil
}
func findAncestorByName(hostProcPath string, ancestorProcess string) (*procfs.Proc, error) {
proc, err := getSelfProc(hostProcPath)
if err != nil {
return nil, err
}
for {
st, err := proc.Stat()
if err != nil {
return nil, err
}
if st.Comm == ancestorProcess {
return proc, nil
}
if st.PPID == 0 {
break
}
proc, err = getPidProc(hostProcPath, st.PPID)
if err != nil {
return nil, err
}
}
return nil, fmt.Errorf("failed to find the ancestor process: %s", ancestorProcess)
}
func GetHostNamespacePath(hostProcPath string) string {
containerNames := []string{DockerdProcess, ContainerdProcess, ContainerdProcessShim}
for _, name := range containerNames {
proc, err := findAncestorByName(hostProcPath, name)
if err == nil {
return fmt.Sprintf("%s/%d/ns/", hostProcPath, proc.PID)
}
}
return fmt.Sprintf("%s/%d/ns/", hostProcPath, 1)
}