Skip to content

Commit

Permalink
change:getNsInumByPid readlink /proc/{{pid}}/ns/net directly
Browse files Browse the repository at this point in the history
  • Loading branch information
RichardoMrMu authored and Mu Huai committed May 15, 2024
1 parent 41254c9 commit 7fd6436
Showing 1 changed file with 11 additions and 18 deletions.
29 changes: 11 additions & 18 deletions pkg/exporter/nettop/netns.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,31 +14,24 @@ func getNsInumByPid(pid int) (int, error) {
}
defer d.Close()

names, err := d.Readdirnames(-1)
target, err := os.Readlink(fmt.Sprintf("/proc/%d/ns/net", pid))
if err != nil {
return 0, fmt.Errorf("failed to read contents of ns dir: %w", err)
return 0, err
}

for _, name := range names {
target, err := os.Readlink(fmt.Sprintf("/proc/%d/ns/%s", pid, name))
if err != nil {
return 0, err
}
fields := strings.SplitN(target, ":", 2)

fields := strings.SplitN(target, ":", 2)
if len(fields) != 2 {
return 0, fmt.Errorf("failed to parse namespace type and inode from %q", target)
}

if fields[0] == "net" {
inode, err := strconv.ParseUint(strings.Trim(fields[1], "[]"), 10, 32)
if err != nil {
return 0, fmt.Errorf("failed to parse inode from %q: %w", fields[1], err)
}
if len(fields) != 2 {
return 0, fmt.Errorf("failed to parse namespace type and inode from %q", target)
}

return int(inode), nil
if fields[0] == "net" {
inode, err := strconv.ParseUint(strings.Trim(fields[1], "[]"), 10, 32)
if err != nil {
return 0, fmt.Errorf("failed to parse inode from %q: %w", fields[1], err)
}

return int(inode), nil
}

return 0, fmt.Errorf("net namespace of %d not found", pid)
Expand Down

0 comments on commit 7fd6436

Please sign in to comment.