Skip to content

Commit

Permalink
Merge pull request #44 from cccfs/feat-dev
Browse files Browse the repository at this point in the history
feat: add pid2pod command
  • Loading branch information
g3rzi authored Dec 29, 2024
2 parents e7d4142 + 572120b commit 79a5d86
Show file tree
Hide file tree
Showing 5 changed files with 283 additions and 38 deletions.
92 changes: 92 additions & 0 deletions cmd/pid2pod/lookuppod.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
/*
Copyright (c) 2020 CyberArk Software Ltd. All rights reserved
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package pid2pod

import (
"bufio"
"fmt"
"github.com/jedib0t/go-pretty/table"
"os"
"regexp"
"strings"
)

// ID identifies a single container running in a Kubernetes Pod
type ID struct {
Namespace string
PodName string
//ContainerID string
ContainerName string
}

// LookupPod looks up a process ID from the host PID namespace, returning its Kubernetes identity.
func LookupPod(pid int, executable string, podInfo *podList, tw table.Writer) (*ID, error) {
cid, err := LookupContainerID(pid)
if err != nil {
return nil, err
}

var containerRuntime string
pidAndProcExecutable := fmt.Sprintf("%d (%s)", pid, executable)
for _, item := range podInfo.Items {
for _, status := range item.Status.ContainerStatuses {
if strings.Contains(status.ContainerID, "containerd") {
containerRuntime = "containerd"
}
if strings.Contains(status.ContainerID, "docker") {
containerRuntime = "docker"
}
containerID := fmt.Sprintf("%s://%s", containerRuntime, cid)
if status.ContainerID == containerID {
tw.AppendRow([]interface{}{pidAndProcExecutable, item.Metadata.Name, item.Metadata.Namespace, status.Name})
return &ID{
Namespace: item.Metadata.Namespace,
PodName: item.Metadata.Name,
//ContainerID: cid,
ContainerName: status.Name,
}, nil
}
}
}
return nil, nil
}

// LookupContainerID looks up a process ID from the host PID namespace,
// returning its Docker and Containerd container ID.
func LookupContainerID(pid int) (string, error) {
f, err := os.Open(fmt.Sprintf("/proc/%d/cgroup", pid))
if err != nil {
// this is normal, it just means the PID no longer exists
return "", nil
}
defer f.Close()

scanner := bufio.NewScanner(f)
for scanner.Scan() {
line := scanner.Text()
parts := kubePattern.FindStringSubmatch(line)
if parts != nil {
if len(parts) > 1 {
return parts[1], nil
}
}
}
return "", nil
}

var (
kubePattern = regexp.MustCompile(`(?:docker-|cri-containerd-)?([a-f0-9]{64})\.scope`)
)
146 changes: 146 additions & 0 deletions cmd/pid2pod/pid2pod.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
/*
Copyright (c) 2020 CyberArk Software Ltd. All rights reserved
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package pid2pod

import (
"bytes"
"encoding/json"
"fmt"
"github.com/jedib0t/go-pretty/table"
"github.com/jedib0t/go-pretty/text"
"github.com/mitchellh/go-ps"
"io"
"kubeletctl/cmd"
"kubeletctl/pkg/api"
"log"
"net/http/httputil"
"os"

"github.com/spf13/cobra"
)

type podList struct {
// We only care about namespace, serviceAccountName and containerID
Metadata struct {
} `json:"metadata"`
Items []struct {
Metadata struct {
Namespace string `json:"namespace"`
Name string `json:"name"`
UID string `json:"uid"`
Labels map[string]string `json:"labels"`
} `json:"metadata"`
Spec struct {
ServiceAccountName string `json:"serviceAccountName"`
} `json:"spec"`
Status struct {
ContainerStatuses []struct {
ContainerID string `json:"containerID"`
Name string `json:"name"`
} `json:"containerStatuses"`
} `json:"status"`
} `json:"items"`
}

// pid2podCmd represents the pid2pod command
var pid2podCmd = &cobra.Command{
Use: "pid2pod",
Short: "That shows how Linux process IDs (PIDs) can be mapped to Kubernetes pod metadata",
Long: `Description:
That shows how Linux process IDs (PIDs) can be mapped to Kubernetes pod metadata.
Example for usage:
kubeletctl pid2pod
`,
Run: func(cmd2 *cobra.Command, args []string) {
apiPathUrl := cmd.ServerFullAddressGlobal + api.PODS
resp, err := api.GetRequest(api.GlobalClient, apiPathUrl)
respDump, err := httputil.DumpResponse(resp, true)
if cmd.RawFlag {
fmt.Printf("RESPONSE:\n%s", string(respDump))
} else {
if err != nil {
fmt.Printf("[*] Failed to run HTTP request with error: %s\n", err)
os.Exit(1)
}

bodyBytes, err := io.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
resp.Body = io.NopCloser(bytes.NewBuffer(bodyBytes))
var podInfo *podList
err = json.Unmarshal(bodyBytes, &podInfo)

if err != nil {
// TODO: this function does some of the previous checks, consider modification
cmd.PrintPrettyHttpResponse(resp, err)
} else {
tw := table.NewWriter()
tw.AppendHeader(table.Row{"PID", "POD", "NAMESPACE", "CONTAINERS"})

// get system all processes
processes, err := ps.Processes()
if err != nil {
log.Fatalf("could not list processes: %v", err)
}
for _, proc := range processes {
if pidFlag != 0 {
if pidFlag == proc.Pid() {
pid = pidFlag
printPid2Pod(pid, proc.Executable(), podInfo, tw)
}
} else {
pid = proc.Pid()
printPid2Pod(pid, proc.Executable(), podInfo, tw)
}
}
tw.SetTitle("Pods from Pid")
tw.SetStyle(table.StyleLight)
tw.Style().Title.Align = text.AlignCenter
tw.SetAutoIndex(true)
tw.Style().Options.SeparateRows = true
if displayFlag == "table" {
fmt.Println(tw.Render())
}
}
}
},
}

func printPid2Pod(pid int, executable string, podInfo *podList, tw table.Writer) {
id, err := LookupPod(pid, executable, podInfo, tw)
if err != nil {
log.Fatalf("could not get ID of process %d: %v", pid, err)
}
if id != nil {
if displayFlag == "raw" {
fmt.Printf("PID %d (%s): %+#v\n", pid, executable, id)
}
}
}

var (
pidFlag int
pid int
displayFlag string
)

func init() {
cmd.RootCmd.AddCommand(pid2podCmd)
pid2podCmd.PersistentFlags().IntVarP(&pidFlag, "pid", "", 0, "Name of pid to look.")
pid2podCmd.PersistentFlags().StringVarP(&displayFlag, "display", "", "table", "Data display mode, [raw、table].")
}
80 changes: 42 additions & 38 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,42 +3,46 @@ module kubeletctl
go 1.19

require (
github.com/dgrijalva/jwt-go v3.2.0+incompatible
github.com/jedib0t/go-pretty v4.3.0+incompatible
github.com/spf13/cobra v0.0.7
github.com/tidwall/pretty v1.0.1
k8s.io/api v0.0.0-20200403220253-fa879b399cd0
k8s.io/client-go v0.0.0-20200404181738-fe32aa3b9449
github.com/asaskevich/govalidator v0.0.0-20190424111038-f61b66f89f4a // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/docker/spdystream v0.0.0-20160310174837-449fdfce4d96 // indirect
github.com/go-openapi/errors v0.19.2 // indirect
github.com/go-openapi/strfmt v0.19.5 // indirect
github.com/go-stack/stack v1.8.0 // indirect
github.com/gogo/protobuf v1.3.1 // indirect
github.com/golang/protobuf v1.3.3 // indirect
github.com/google/gofuzz v1.1.0 // indirect
github.com/imdario/mergo v0.3.5 // indirect
github.com/inconshreveable/mousetrap v1.0.0 // indirect
github.com/json-iterator/go v1.1.8 // indirect
github.com/mattn/go-runewidth v0.0.9 // indirect
github.com/mitchellh/mapstructure v1.1.2 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.1 // indirect
github.com/spf13/pflag v1.0.5 // indirect
go.mongodb.org/mongo-driver v1.0.3 // indirect
golang.org/x/crypto v0.0.0-20200220183623-bac4c82f6975 // indirect
golang.org/x/net v0.0.0-20200324143707-d3edc9973b7e // indirect
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45 // indirect
golang.org/x/sys v0.7.0 // indirect
golang.org/x/text v0.3.2 // indirect
golang.org/x/time v0.0.0-20191024005414-555d28b269f0 // indirect
google.golang.org/appengine v1.5.0 // indirect
gopkg.in/inf.v0 v0.9.1 // indirect
gopkg.in/yaml.v2 v2.2.8 // indirect
k8s.io/apimachinery v0.0.0-20200403220105-fa0d5bf06730 // indirect
k8s.io/klog v1.0.0 // indirect
k8s.io/utils v0.0.0-20200324210504-a9aa75ae1b89 // indirect
sigs.k8s.io/structured-merge-diff/v3 v3.0.0 // indirect
sigs.k8s.io/yaml v1.2.0 // indirect
github.com/dgrijalva/jwt-go v3.2.0+incompatible
github.com/jedib0t/go-pretty v4.3.0+incompatible
github.com/mitchellh/go-ps v1.0.0
github.com/spf13/cobra v0.0.7
github.com/tidwall/pretty v1.0.1
k8s.io/api v0.0.0-20200403220253-fa879b399cd0
k8s.io/client-go v0.0.0-20200404181738-fe32aa3b9449
)

require (
github.com/asaskevich/govalidator v0.0.0-20190424111038-f61b66f89f4a // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/docker/spdystream v0.0.0-20160310174837-449fdfce4d96 // indirect
github.com/go-openapi/errors v0.19.2 // indirect
github.com/go-openapi/strfmt v0.19.5 // indirect
github.com/go-stack/stack v1.8.0 // indirect
github.com/gogo/protobuf v1.3.1 // indirect
github.com/golang/protobuf v1.3.3 // indirect
github.com/google/gofuzz v1.1.0 // indirect
github.com/imdario/mergo v0.3.5 // indirect
github.com/inconshreveable/mousetrap v1.0.0 // indirect
github.com/json-iterator/go v1.1.8 // indirect
github.com/mattn/go-runewidth v0.0.9 // indirect
github.com/mitchellh/mapstructure v1.1.2 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.1 // indirect
github.com/spf13/pflag v1.0.5 // indirect
go.mongodb.org/mongo-driver v1.0.3 // indirect
golang.org/x/crypto v0.0.0-20200220183623-bac4c82f6975 // indirect
golang.org/x/net v0.0.0-20200324143707-d3edc9973b7e // indirect
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45 // indirect
golang.org/x/sys v0.7.0 // indirect
golang.org/x/text v0.3.2 // indirect
golang.org/x/time v0.0.0-20191024005414-555d28b269f0 // indirect
google.golang.org/appengine v1.5.0 // indirect
gopkg.in/inf.v0 v0.9.1 // indirect
gopkg.in/yaml.v2 v2.2.8 // indirect
k8s.io/apimachinery v0.0.0-20200403220105-fa0d5bf06730 // indirect
k8s.io/klog v1.0.0 // indirect
k8s.io/utils v0.0.0-20200324210504-a9aa75ae1b89 // indirect
sigs.k8s.io/structured-merge-diff/v3 v3.0.0 // indirect
sigs.k8s.io/yaml v1.2.0 // indirect
)
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,8 @@ github.com/mattn/go-runewidth v0.0.9 h1:Lm995f3rfxdpd6TSmuVCHVb/QhupuXlYr8sCI/Qd
github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
github.com/mitchellh/go-ps v1.0.0 h1:i6ampVEEF4wQFF+bkYfwYgY+F/uYJDktmvLPf7qIgjc=
github.com/mitchellh/go-ps v1.0.0/go.mod h1:J4lOc8z8yJs6vUwklHw2XEIiT4z4C40KtWVN3nvg8Pg=
github.com/mitchellh/mapstructure v1.1.2 h1:fmNYVwqnSfB9mZU6OS2O6GsXM+wcskZDuKQzvN1EDeE=
github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
Expand Down
1 change: 1 addition & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"kubeletctl/cmd"
_ "kubeletctl/cmd/log"
_ "kubeletctl/cmd/metrics"
_ "kubeletctl/cmd/pid2pod"
_ "kubeletctl/cmd/proxy"
_ "kubeletctl/cmd/proxy/debug"
_ "kubeletctl/cmd/proxy/healthz"
Expand Down

0 comments on commit 79a5d86

Please sign in to comment.