my-homelab-configs/scripts/k3s-stop.sh

90 lines
3.0 KiB
Bash

#!/usr/bin/env bash
# Stop only K3s and its private CRI workloads. Keep Docker, Pimox and data intact.
set -euo pipefail
if [[ "${1:-}" == --disable ]]; then
sudo -n systemctl disable --now k3s
elif [[ $# == 0 ]]; then
sudo -n systemctl stop k3s
else
echo "Usage: k3s-stop.sh [--disable]" >&2
exit 2
fi
# The service can terminate containerd while its shims keep containers alive.
# Stop only shim trees using K3s' private socket. Avoid killall's interface and
# iptables cleanup, which can affect other host services.
sudo -n python3 - <<'K3S_TASKS_PY'
import os
from pathlib import Path
import signal
import time
def identity(pid):
try:
fields = Path(f"/proc/{pid}/stat").read_text().rsplit(")", 1)[1].split()
return (int(fields[1]), fields[19], fields[0]) # parent, start time, state
except (FileNotFoundError, ProcessLookupError):
return None
snapshot = {}
roots = []
for entry in Path("/proc").iterdir():
if not entry.name.isdigit():
continue
pid = int(entry.name)
info = identity(pid)
if info is None:
continue
snapshot[pid] = info
try:
arguments = (entry / "cmdline").read_bytes().split(b"\0")
except (FileNotFoundError, ProcessLookupError):
continue
private_shim = (arguments and b"containerd-shim" in os.path.basename(arguments[0])
and b"/run/k3s/containerd/containerd.sock" in arguments)
private_daemon = (arguments and os.path.basename(arguments[0]) == b"containerd"
and b"/var/lib/rancher/k3s/agent/etc/containerd/config.toml" in arguments)
if private_shim or private_daemon:
roots.append(pid)
wanted = set(roots)
while True:
children = {pid for pid, info in snapshot.items() if info[0] in wanted}
if children.issubset(wanted):
break
wanted.update(children)
def alive(pid):
current = identity(pid)
return current is not None and current[1] == snapshot[pid][1] and current[2] != "Z"
def send(sig):
for pid in wanted:
if alive(pid):
try:
os.kill(pid, sig)
except ProcessLookupError:
pass
send(signal.SIGTERM)
deadline = time.monotonic() + 10
while any(alive(pid) for pid in wanted) and time.monotonic() < deadline:
time.sleep(0.2)
send(signal.SIGKILL)
deadline = time.monotonic() + 5
while any(alive(pid) for pid in wanted) and time.monotonic() < deadline:
time.sleep(0.2)
if any(alive(pid) for pid in wanted):
raise SystemExit("K3s workload processes remain; runtime is not stopped")
K3S_TASKS_PY
for attempt in {1..10}; do
if sudo -n pgrep -f '[c]ontainerd-shim.*[/]run/k3s|[c]ontainerd .*[/]var/lib/rancher/k3s/agent/etc/containerd/config.toml' >/dev/null; then
sleep 1
else
status=$?
[[ "$status" == 1 ]] || exit "$status"
echo "K3s service and private runtime workloads stopped; data retained."
exit 0
fi
done
echo "K3s workload processes remain; refusing to declare this runtime stopped." >&2
exit 1