Skip to content

Commit

Permalink
Use nsenter to associate pids and container ids
Browse files Browse the repository at this point in the history
Refs: #18
  • Loading branch information
praith-dsg committed May 27, 2022
1 parent 70355d6 commit 8f9050d
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
2 changes: 2 additions & 0 deletions internal/telemd/instrument.go
Original file line number Diff line number Diff line change
Expand Up @@ -499,6 +499,7 @@ func (c *DockerCgroupv1NetworkInstrument) MeasureAndReport(channel telem.Telemet
}

for _, containerId := range containerIds {
containerId = containerId[:12]
pid, ok := c.pids[containerId]

if !ok {
Expand Down Expand Up @@ -548,6 +549,7 @@ func (c *DockerCgroupv2NetworkInstrument) MeasureAndReport(channel telem.Telemet
stop := len(containerIdFolder) - len(".scope")
// 12 is the length of the short-form for container IDs
containerId := containerIdFolder[index:stop]
containerId = containerIdFolder[index : index+12]
pid, ok := c.pids[containerId]

if !ok {
Expand Down
34 changes: 34 additions & 0 deletions internal/telemd/sysparse.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ package telemd
import (
"bufio"
"errors"
"log"
"os"
"regexp"
"strconv"
"strings"
"time"
Expand Down Expand Up @@ -226,7 +228,39 @@ func readTotalProcessNetworkStats(pid string) (rx int64, tx int64, err error) {
return rx, tx, scanner.Err()
}

func allPids() ([]string, error) {
r, _ := regexp.Compile("^\\d*")
dirs, err := listFilterDir("/proc", func(info os.FileInfo) bool {
return info.IsDir() && r.MatchString(info.Name())
})

if err != nil {
log.Println("error fetching PIDs", err)
return nil, err
}
return dirs, nil
}

func containerProcessIds() (map[string]string, error) {
// get all PIDs from /proc
pids, err := allPids()
if err != nil {
return nil, err
}

pidMap := make(map[string]string, 0)
// execute for each PID 'nsenter -t $PID -u hostname'
for _, pid := range pids {
// check if result is equal to short containerId
command, err := execCommand("sudo nsenter -t " + pid + " -u hostname")
if err == nil {
pidMap[command] = pid
}
}
return pidMap, nil
}

func containerProcessIdsUsingDockerCli() (map[string]string, error) {
command, err := execCommand("docker ps -q | xargs docker inspect --format '{{ .Id }} {{ .State.Pid }}'")

if err != nil {
Expand Down

0 comments on commit 8f9050d

Please sign in to comment.