Skip to content

Commit

Permalink
Add findpid subcommand
Browse files Browse the repository at this point in the history
  • Loading branch information
iBug committed Jan 17, 2024
1 parent 2f1823a commit f98735e
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 0 deletions.
55 changes: 55 additions & 0 deletions cmd/findpid/findpid.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package findpid

import (
"bufio"
"fmt"
"os"
"strings"

"github.com/spf13/cobra"
)

func findLXCForPid(pid string) (string, error) {
filename := fmt.Sprintf("/proc/%s/cgroup", pid)
f, err := os.Open(filename)
if err != nil {
return "", err
}
defer f.Close()
s := bufio.NewScanner(f)
if !s.Scan() {
return "", fmt.Errorf("empty cgroup file %s", filename)
}
line := s.Text()
remainder, ok := strings.CutPrefix(line, "0::/lxc/")
if !ok {
return "", fmt.Errorf("invalid cgroup file %s (read %q)", filename, line)
}
parts := strings.SplitN(remainder, "/", 2)
if len(parts) != 2 {
return "", fmt.Errorf("invalid cgroup file %s (read %q)", filename, line)
}
return parts[0], nil
}

func runE(cmd *cobra.Command, args []string) error {
w := cmd.OutOrStdout()
for _, pid := range args {
id, err := findLXCForPid(pid)
if err != nil {
return err
}
fmt.Fprintf(w, "%s: %s\n", pid, id)
}
return nil
}

func MakeCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "findpid PID...",
Short: "Find container ID by PID",
Args: cobra.MinimumNArgs(1),
RunE: runE,
}
return cmd
}
2 changes: 2 additions & 0 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package cmd

import (
"github.com/USTC-vlab/vct/cmd/df"
"github.com/USTC-vlab/vct/cmd/findpid"
"github.com/USTC-vlab/vct/cmd/iostat"
"github.com/USTC-vlab/vct/cmd/pressure"
"github.com/spf13/cobra"
Expand All @@ -21,6 +22,7 @@ func MakeCmd() *cobra.Command {
}
cmd.CompletionOptions.HiddenDefaultCmd = true
cmd.AddCommand(df.MakeCmd())
cmd.AddCommand(findpid.MakeCmd())
cmd.AddCommand(iostat.MakeCmd())
cmd.AddCommand(pressure.MakeCmd())
return cmd
Expand Down

0 comments on commit f98735e

Please sign in to comment.