#!/bin/bash
# End every container's processes while the network and the NFS shares are still up.
#
# With live-restore dockerd does not stop containers at host shutdown, and systemd-shutdown then signals them only after the network is
# gone. A container that holds an NFS mount blocks in the kernel's final unmount of it (a request to a server it can no longer reach)
# until the SIGKILL timer, which makes the host take minutes to stop.
#
# Run by the unit's ExecStop, which systemd orders after docker.service has stopped (so no restart policy interferes) and before the
# network and remote-fs targets. SIGTERM to every process of every container, wait, then SIGKILL what is left. It never uses
# `docker stop` or `docker kill`: both set the manually-stopped marker, and a container with restart policy unless-stopped would then not
# start again at the next boot. With dockerd down the containers simply exit and their policy restarts them at boot.
# It reads the systemd cgroup driver's layout (cgroup v2, /sys/fs/cgroup/system.slice/docker-<id>.scope). On a host that lays containers out
# differently it finds nothing, says so in the journal and changes nothing.
set -u
shopt -s nullglob

timeout="${DOCKER_STOP_TIMEOUT:-30}"
scopes=(/sys/fs/cgroup/system.slice/docker-*.scope)

if [ "${#scopes[@]}" -eq 0 ]; then
  logger -t docker-stop-at-shutdown "no container scopes, nothing to do"
  exit 0
fi

# Every process of every scope, including those in child cgroups. Only real PIDs: a process this namespace cannot see is listed as 0,
# and `kill 0` would signal our own process group.
pids() { find "${scopes[@]}" -name cgroup.procs -exec cat {} + 2> /dev/null | grep -E '^[1-9][0-9]*$'; }

logger -t docker-stop-at-shutdown "SIGTERM to $(pids | wc -l) processes in ${#scopes[@]} container scopes (wait up to ${timeout}s)"
pids | xargs -r kill -TERM 2> /dev/null

deadline=$((SECONDS + timeout))
while [ "$SECONDS" -lt "$deadline" ] && [ -n "$(pids)" ]; do
  sleep 0.25
done

left=$(pids | wc -l)
if [ "$left" -gt 0 ]; then
  logger -t docker-stop-at-shutdown "$left processes still there after ${timeout}s: SIGKILL"
  pids | xargs -r kill -KILL 2> /dev/null
  sleep 1
fi
logger -t docker-stop-at-shutdown "done after ${SECONDS}s, processes left: $(pids | wc -l)"
exit 0
