From c9712d887660066e110fe1ffb4d9cfe7fac8e206 Mon Sep 17 00:00:00 2001 From: Paul-Christian Volkmer Date: Sun, 25 Dec 2022 11:29:19 +0100 Subject: [PATCH] Extract method to fetch container processes --- main.go | 67 +++++++++++++++++++++++++++++++++------------------------ 1 file changed, 39 insertions(+), 28 deletions(-) diff --git a/main.go b/main.go index 5788864..94f30ba 100644 --- a/main.go +++ b/main.go @@ -74,34 +74,8 @@ func getProcesses(dc *client.Client) ([]Process, error) { if containers, err := dc.ContainerList(context.Background(), types.ContainerListOptions{All: true}); err == nil { for _, container := range containers { - tops, err := dc.ContainerTop(context.Background(), container.ID, []string{}) - if err != nil { - continue - } - - uid := 0 - pid := 0 - cmd := 0 - for idx, title := range tops.Titles { - if title == "UID" { - uid = idx - } - if title == "PID" { - pid = idx - } - if title == "CMD" { - cmd = idx - } - } - - for _, process := range tops.Processes { - processes = append(processes, Process{ - ContainerID: container.ID, - Image: strings.Split(container.Image, "@sha256")[0], - PID: process[pid], - UID: process[uid], - Command: process[cmd], - }) + if containerProcesses, err := containerProcesses(dc, container); err == nil { + processes = append(processes, containerProcesses...) } } } else { @@ -111,6 +85,43 @@ func getProcesses(dc *client.Client) ([]Process, error) { return processes, nil } +// Get all processes running in current docker container +func containerProcesses(dc *client.Client, container types.Container) ([]Process, error) { + var processes []Process + + tops, err := dc.ContainerTop(context.Background(), container.ID, []string{}) + if err != nil { + return nil, err + } + + uid := 0 + pid := 0 + cmd := 0 + for idx, title := range tops.Titles { + if title == "UID" { + uid = idx + } + if title == "PID" { + pid = idx + } + if title == "CMD" { + cmd = idx + } + } + + for _, process := range tops.Processes { + processes = append(processes, Process{ + ContainerID: container.ID, + Image: strings.Split(container.Image, "@sha256")[0], + PID: process[pid], + UID: process[uid], + Command: process[cmd], + }) + } + + return processes, nil +} + // Print out table if processes, running within docker containers func printTable(processes []Process) { imageColumnLength := 5