|
| 1 | +# `pod_by_pid_4microk8s` |
| 2 | + |
| 3 | +### A Script to Find the Kubernetes Pod Associated with a Process (PID) on MicroK8s |
| 4 | + |
| 5 | +`pod_by_pid.sh` is a Bash script designed specifically for environments running MicroK8s. It helps you determine which Kubernetes pod a specific process (identified by its PID) belongs to. This script extracts the container ID from the Linux process cgroup file and maps it to the corresponding pod using the `kubectl` command. |
| 6 | + |
| 7 | +--- |
| 8 | + |
| 9 | +## ✨ Features |
| 10 | + |
| 11 | +- **Works exclusively with MicroK8s**: |
| 12 | + - The script is tailored for MicroK8s, a lightweight Kubernetes distribution. |
| 13 | +- **Maps processes to pods**: |
| 14 | + - Given a Linux process ID (PID), this script efficiently locates the associated pod's name and namespace. |
| 15 | +- **Handles Edge Cases**: |
| 16 | + - Includes robust handling for processes without container IDs or when certain fields are null or incomplete. |
| 17 | +- **Error Handling**: |
| 18 | + - Clearly notifies users of invalid PIDs, missing container IDs, or unmatched pods. |
| 19 | + |
| 20 | +--- |
| 21 | + |
| 22 | +## ⚙️ How It Works |
| 23 | + |
| 24 | +1. **Provide a Process ID (PID)** as input to the script. |
| 25 | +2. The script inspects the process’s `/proc/<PID>/cgroup` file to extract the Kubernetes container ID. |
| 26 | +3. It uses the container ID to query all running Kubernetes pods via the MicroK8s `kubectl` tool. |
| 27 | +4. If a match is found, it outputs the namespace and name of the pod associated with the process. |
| 28 | + |
| 29 | +This script relies on the fact that MicroK8s organizes containers via `containerd` or similar runtime, and the cgroup paths include critical container metadata. |
| 30 | + |
| 31 | +--- |
| 32 | + |
| 33 | +## 📜 Prerequisites |
| 34 | + |
| 35 | +1. **MicroK8s**: |
| 36 | + - Ensure MicroK8s is installed and running on your system. |
| 37 | + - The script assumes the `kubectl` command provided by MicroK8s is installed and available or properly aliased (e.g., `microk8s kubectl` may be aliased to `kubectl`). |
| 38 | + |
| 39 | +2. **jq**: |
| 40 | + - The script requires `jq` to parse JSON output from Kubernetes API queries. |
| 41 | + - Install it using: |
| 42 | + ```bash |
| 43 | + # On Debian/Ubuntu |
| 44 | + sudo apt-get install jq |
| 45 | + |
| 46 | + # On RHEL/CentOS |
| 47 | + sudo yum install jq |
| 48 | + |
| 49 | + # On macOS |
| 50 | + brew install jq |
| 51 | + ``` |
| 52 | + |
| 53 | +3. **Run the Script with Sufficient Permissions**: |
| 54 | + - Run the script as a user with access to the `/proc` filesystem and Kubernetes cluster configurations in MicroK8s (requires access to `kubectl`). |
| 55 | + |
| 56 | +--- |
| 57 | + |
| 58 | +## 🔧 Installation |
| 59 | + |
| 60 | +1. Save the script to a file: |
| 61 | + ```bash |
| 62 | + nano pod_by_pid.sh |
0 commit comments