[英]How to retrieve the pod/container in which run a given process
Using crictl an
containerd , is there an easy way to find to which pod/container belongs a given process, using it's
PID` on the host machine?使用crictl an
containerd , is there an easy way to find to which pod/container belongs a given process, using it's
?
For example, how can I retrieve the name of the pod which runs the process below ( 1747
):例如,如何检索运行以下进程的 pod 的名称( 1747
):
root@k8s-worker-node:/# ps -ef | grep mysql
1000 1747 1723 0 08:58 ? 00:00:01 mysqld
Assuming that you're looking at the primary process in a pod, you could do something like this:假设您正在查看 pod 中的主要进程,您可以执行以下操作:
crictl ps -q | while read cid; do
if crictl inspect -o go-template --template '{{ .info.pid }}' $cid | grep -q $target_pid; then
echo $cid
fi
done
This walks through all the crictl managed pods and checks the pod pid against the value of the $target_pid
value (which you have set beforehand to the host pid in which you are interested).这将遍历所有 crictl 托管的 pod,并根据$target_pid
值(您预先设置为您感兴趣的主机 pid)的值检查 pod pid。
Using @Iarsks answer, I propose a robust and tested solution, which display namespace, pod, container and container's primary PID.使用@Iarsks 的答案,我提出了一个强大且经过测试的解决方案,它显示命名空间、pod、容器和容器的主要 PID。 It is possible to copy paste the script below in a file named get_pid.sh
and then run ./get_pid.sh 2345
for example.例如,可以将下面的脚本复制粘贴到名为get_pid.sh
的文件中,然后运行./get_pid.sh 2345
。
#!/bin/bash
# Display pod information about a process, using its host PID as input
set -euo pipefail
usage() {
cat << EOD
Usage: `basename $0` PID
Available options:
-h this message
Display pod information about a process, using its host PID as input:
- display namespace, pod, container, and primary process pid for this container if the process is running in a pod
- else exit with code 1
EOD
}
if [ $# -ne 1 ] ; then
usage
exit 2
fi
pid=$1
is_running_in_pod=false
pod=$(nsenter -t $pid -u hostname 2>&1)
if [ $? -ne 0 ]
then
printf "%s %s:\n %s" "nsenter command failed for pid" "$pid" "$pod"
fi
cids=$(crictl ps -q)
for cid in $cids
do
current_pod=$(crictl inspect -o go-template --template '{{ index .info.config.labels "io.kubernetes.pod.name"}}' "$cid")
if [ "$pod" == "$current_pod" ]
then
tmpl='NS:{{ index .info.config.labels "io.kubernetes.pod.namespace"}} POD:{{ index .info.config.labels "io.kubernetes.pod.name"}} CONTAINER:{{ index .info.config.labels "io.kubernetes.container.name"}} PRIMARY PID:{{.info.pid}}'
crictl inspect --output go-template --template "$tmpl" "$cid"
is_running_in_pod=true
break
fi
done
if [ "$is_running_in_pod" = false ]
then
echo "Process $pid is not running in a pod."
exit 1
fi
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.