|
| 1 | +// clear-refs-exec.go |
| 2 | +// |
| 3 | +// A utility to clear soft-dirty bits for a containerized process by executing |
| 4 | +// clear_refs inside the container via crictl exec. |
| 5 | +// |
| 6 | +// Build: CGO_ENABLED=0 go build -ldflags="-s -w" -o clear-refs-exec clear-refs-exec.go |
| 7 | + |
| 8 | +package main |
| 9 | + |
| 10 | +import ( |
| 11 | + "bufio" |
| 12 | + "flag" |
| 13 | + "fmt" |
| 14 | + "os" |
| 15 | + "os/exec" |
| 16 | + "path/filepath" |
| 17 | + "strconv" |
| 18 | + "strings" |
| 19 | +) |
| 20 | + |
| 21 | +func main() { |
| 22 | + // Parse command-line flags |
| 23 | + clearRefsBin := flag.String("clear-refs-bin", "/bin/clear_refs", "path to clear_refs binary inside container") |
| 24 | + flag.Usage = func() { |
| 25 | + fmt.Fprintf(os.Stderr, "Usage: %s [options] <root-ns-pid>\n\n", os.Args[0]) |
| 26 | + fmt.Fprintf(os.Stderr, "Clears soft-dirty bits for a container process via crictl exec.\n\n") |
| 27 | + fmt.Fprintf(os.Stderr, "Options:\n") |
| 28 | + flag.PrintDefaults() |
| 29 | + } |
| 30 | + flag.Parse() |
| 31 | + |
| 32 | + if flag.NArg() != 1 { |
| 33 | + flag.Usage() |
| 34 | + os.Exit(1) |
| 35 | + } |
| 36 | + |
| 37 | + pid := flag.Arg(0) |
| 38 | + |
| 39 | + // Validate PID is a number |
| 40 | + if _, err := strconv.Atoi(pid); err != nil { |
| 41 | + fmt.Fprintf(os.Stderr, "error: invalid PID %q: %v\n", pid, err) |
| 42 | + os.Exit(1) |
| 43 | + } |
| 44 | + |
| 45 | + // Extract container ID from cgroup |
| 46 | + containerID, err := getContainerID(pid) |
| 47 | + if err != nil { |
| 48 | + fmt.Fprintf(os.Stderr, "error: failed to get container ID: %v\n", err) |
| 49 | + os.Exit(1) |
| 50 | + } |
| 51 | + |
| 52 | + // Get the NSpid (PID in container namespace) |
| 53 | + nspid, err := getNsPid(pid) |
| 54 | + if err != nil { |
| 55 | + fmt.Fprintf(os.Stderr, "error: failed to get NSpid: %v\n", err) |
| 56 | + os.Exit(1) |
| 57 | + } |
| 58 | + |
| 59 | + fmt.Printf("Container ID: %s\n", containerID) |
| 60 | + fmt.Printf("NSpid: %s\n", nspid) |
| 61 | + |
| 62 | + // Execute clear_refs inside the container via crictl exec |
| 63 | + if err := execClearRefs(containerID, *clearRefsBin, nspid); err != nil { |
| 64 | + fmt.Fprintf(os.Stderr, "error: failed to execute clear_refs: %v\n", err) |
| 65 | + os.Exit(1) |
| 66 | + } |
| 67 | + |
| 68 | + fmt.Println("Successfully cleared soft-dirty bits") |
| 69 | +} |
| 70 | + |
| 71 | +// getContainerID reads /proc/<pid>/cgroup and extracts the container ID. |
| 72 | +// Handles both standard kubepods format and cri-containerd scope format. |
| 73 | +func getContainerID(pid string) (string, error) { |
| 74 | + cgroupPath := filepath.Join("/proc", pid, "cgroup") |
| 75 | + file, err := os.Open(cgroupPath) |
| 76 | + if err != nil { |
| 77 | + return "", fmt.Errorf("failed to open %s: %w", cgroupPath, err) |
| 78 | + } |
| 79 | + defer file.Close() |
| 80 | + |
| 81 | + scanner := bufio.NewScanner(file) |
| 82 | + for scanner.Scan() { |
| 83 | + line := scanner.Text() |
| 84 | + // cgroup line format: hierarchy-ID:controller-list:cgroup-path |
| 85 | + // Example: 0::/kubepods/besteffort/pod<uuid>/<container_id> |
| 86 | + parts := strings.SplitN(line, ":", 3) |
| 87 | + if len(parts) < 3 { |
| 88 | + continue |
| 89 | + } |
| 90 | + |
| 91 | + cgroupPathPart := parts[2] |
| 92 | + if cgroupPathPart == "" || cgroupPathPart == "/" { |
| 93 | + continue |
| 94 | + } |
| 95 | + |
| 96 | + // Try to extract container ID from the cgroup path |
| 97 | + containerID := extractContainerID(cgroupPathPart) |
| 98 | + if containerID != "" { |
| 99 | + return containerID, nil |
| 100 | + } |
| 101 | + } |
| 102 | + |
| 103 | + if err := scanner.Err(); err != nil { |
| 104 | + return "", fmt.Errorf("failed to read %s: %w", cgroupPath, err) |
| 105 | + } |
| 106 | + |
| 107 | + return "", fmt.Errorf("could not find container ID in %s", cgroupPath) |
| 108 | +} |
| 109 | + |
| 110 | +// extractContainerID extracts the container ID from a cgroup path. |
| 111 | +// Handles formats like: |
| 112 | +// - /kubepods/besteffort/pod<uuid>/<container_id> |
| 113 | +// - /kubepods.slice/kubepods-besteffort.slice/kubepods-besteffort-pod<uuid>.slice/cri-containerd-<container_id>.scope |
| 114 | +func extractContainerID(cgroupPath string) string { |
| 115 | + // Get the last component of the path |
| 116 | + lastComponent := filepath.Base(cgroupPath) |
| 117 | + |
| 118 | + // Handle cri-containerd scope format: cri-containerd-<container_id>.scope |
| 119 | + if strings.HasPrefix(lastComponent, "cri-containerd-") && strings.HasSuffix(lastComponent, ".scope") { |
| 120 | + // Remove "cri-containerd-" prefix and ".scope" suffix |
| 121 | + id := strings.TrimPrefix(lastComponent, "cri-containerd-") |
| 122 | + id = strings.TrimSuffix(id, ".scope") |
| 123 | + if isValidContainerID(id) { |
| 124 | + return id |
| 125 | + } |
| 126 | + } |
| 127 | + |
| 128 | + // Handle docker format: docker-<container_id>.scope |
| 129 | + if strings.HasPrefix(lastComponent, "docker-") && strings.HasSuffix(lastComponent, ".scope") { |
| 130 | + id := strings.TrimPrefix(lastComponent, "docker-") |
| 131 | + id = strings.TrimSuffix(id, ".scope") |
| 132 | + if isValidContainerID(id) { |
| 133 | + return id |
| 134 | + } |
| 135 | + } |
| 136 | + |
| 137 | + // Handle plain container ID format (last path component is the container ID) |
| 138 | + // Example: /kubepods/besteffort/pod<uuid>/<container_id> |
| 139 | + if isValidContainerID(lastComponent) { |
| 140 | + return lastComponent |
| 141 | + } |
| 142 | + |
| 143 | + return "" |
| 144 | +} |
| 145 | + |
| 146 | +// isValidContainerID checks if a string looks like a valid container ID. |
| 147 | +// Container IDs are typically 64 hex characters. |
| 148 | +func isValidContainerID(id string) bool { |
| 149 | + if len(id) != 64 { |
| 150 | + return false |
| 151 | + } |
| 152 | + for _, c := range id { |
| 153 | + if !((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')) { |
| 154 | + return false |
| 155 | + } |
| 156 | + } |
| 157 | + return true |
| 158 | +} |
| 159 | + |
| 160 | +// getNsPid reads /proc/<pid>/status and extracts the NSpid (PID in container namespace). |
| 161 | +// The NSpid line contains space-separated PIDs for each namespace level. |
| 162 | +// Example: "NSpid: 12345 1" where 12345 is root ns PID and 1 is container ns PID. |
| 163 | +func getNsPid(pid string) (string, error) { |
| 164 | + statusPath := filepath.Join("/proc", pid, "status") |
| 165 | + file, err := os.Open(statusPath) |
| 166 | + if err != nil { |
| 167 | + return "", fmt.Errorf("failed to open %s: %w", statusPath, err) |
| 168 | + } |
| 169 | + defer file.Close() |
| 170 | + |
| 171 | + scanner := bufio.NewScanner(file) |
| 172 | + for scanner.Scan() { |
| 173 | + line := scanner.Text() |
| 174 | + if strings.HasPrefix(line, "NSpid:") { |
| 175 | + // Remove "NSpid:" prefix and split by whitespace |
| 176 | + nspidPart := strings.TrimPrefix(line, "NSpid:") |
| 177 | + pids := strings.Fields(nspidPart) |
| 178 | + if len(pids) == 0 { |
| 179 | + return "", fmt.Errorf("NSpid line is empty in %s", statusPath) |
| 180 | + } |
| 181 | + // Return the last PID (innermost namespace) |
| 182 | + return pids[len(pids)-1], nil |
| 183 | + } |
| 184 | + } |
| 185 | + |
| 186 | + if err := scanner.Err(); err != nil { |
| 187 | + return "", fmt.Errorf("failed to read %s: %w", statusPath, err) |
| 188 | + } |
| 189 | + |
| 190 | + return "", fmt.Errorf("NSpid not found in %s", statusPath) |
| 191 | +} |
| 192 | + |
| 193 | +// execClearRefs runs clear_refs inside the container via crictl exec. |
| 194 | +func execClearRefs(containerID, clearRefsBin, nspid string) error { |
| 195 | + // Build the crictl exec command |
| 196 | + cmd := exec.Command("crictl", "exec", containerID, clearRefsBin, nspid) |
| 197 | + |
| 198 | + // Capture combined output for error reporting |
| 199 | + output, err := cmd.CombinedOutput() |
| 200 | + if err != nil { |
| 201 | + return fmt.Errorf("crictl exec failed: %w\nOutput: %s", err, string(output)) |
| 202 | + } |
| 203 | + |
| 204 | + if len(output) > 0 { |
| 205 | + fmt.Printf("crictl exec output: %s\n", string(output)) |
| 206 | + } |
| 207 | + |
| 208 | + return nil |
| 209 | +} |
0 commit comments