The agent ran as (capability-less) root only so needrestart could read Ubuntu's root-only /boot images. Switch the unit to DynamicUser=yes and make needrestart optional. To cover the case needrestart was catching (running kernel's package upgraded in place, same uname -r), the agent now reports the installed package version of the running kernel and the server compares it with the build in uname -v: "Debian 6.12.57-1" vs 6.12.57-1 on Debian, "#85-Ubuntu" / "#33~24.04.1-Ubuntu" vs the upload part of 6.8.0-85.85 / 6.14.0-33.33~24.04.1 on Ubuntu. Unrecognised builds fall back to needrestart and the newest-installed comparison. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
268 lines
7.6 KiB
Bash
Executable File
268 lines
7.6 KiB
Bash
Executable File
#!/usr/bin/env bash
|
|
# kernelwatch-agent: collect kernel/update state on a Debian or Ubuntu host and
|
|
# report it to the kernelwatch server. Run by kernelwatch-agent.timer.
|
|
#
|
|
# The agent only gathers facts; the server decides what they mean, so status
|
|
# rules can change without redeploying agents.
|
|
set -euo pipefail
|
|
|
|
AGENT_VERSION=0.1.0
|
|
|
|
# Prefix for every file the agent reads. Only the test suite sets this.
|
|
ROOT=${KERNELWATCH_ROOT:-}
|
|
CONF=${KERNELWATCH_CONF:-$ROOT/etc/kernelwatch/agent.conf}
|
|
|
|
usage() {
|
|
cat <<EOF
|
|
Usage: kernelwatch-agent [--print] [--help]
|
|
|
|
Collects kernel and package update state and POSTs it to the kernelwatch server.
|
|
|
|
--print print the JSON report to stdout instead of sending it
|
|
--help show this help
|
|
|
|
Configuration is read from $CONF.
|
|
EOF
|
|
}
|
|
|
|
die() {
|
|
echo "kernelwatch-agent: $*" >&2
|
|
exit 1
|
|
}
|
|
|
|
# --- JSON helpers -----------------------------------------------------------
|
|
|
|
json_str() {
|
|
local s
|
|
s=$(printf '%s' "$1" | tr -d '\000-\037')
|
|
s=${s//\\/\\\\}
|
|
s=${s//\"/\\\"}
|
|
printf '"%s"' "$s"
|
|
}
|
|
|
|
# Integer or null.
|
|
json_int() {
|
|
if [[ $1 =~ ^-?[0-9]+$ ]]; then printf '%s' "$1"; else printf 'null'; fi
|
|
}
|
|
|
|
json_bool() {
|
|
if [[ $1 == 1 ]]; then printf 'true'; else printf 'false'; fi
|
|
}
|
|
|
|
# JSON array of strings from newline-separated input on stdin.
|
|
json_str_array() {
|
|
local line first=1
|
|
printf '['
|
|
while IFS= read -r line; do
|
|
[[ -z $line ]] && continue
|
|
((first)) || printf ','
|
|
first=0
|
|
json_str "$line"
|
|
done
|
|
printf ']'
|
|
}
|
|
|
|
# --- config -----------------------------------------------------------------
|
|
|
|
SERVER_URL=
|
|
TOKEN_FILE=$ROOT/etc/kernelwatch/agent.token
|
|
CA_FILE=
|
|
TIMEOUT=30
|
|
|
|
load_config() {
|
|
[[ -r $CONF ]] || return 0
|
|
local key value
|
|
while IFS='=' read -r key value; do
|
|
key=${key//[[:space:]]/}
|
|
[[ -z $key || $key == \#* ]] && continue
|
|
value=${value#"${value%%[![:space:]]*}"}
|
|
value=${value%"${value##*[![:space:]]}"}
|
|
value=${value#\"}
|
|
value=${value%\"}
|
|
case $key in
|
|
SERVER_URL) SERVER_URL=$value ;;
|
|
TOKEN_FILE) TOKEN_FILE=$value ;;
|
|
CA_FILE) CA_FILE=$value ;;
|
|
TIMEOUT) TIMEOUT=$value ;;
|
|
*) echo "kernelwatch-agent: ignoring unknown config key '$key'" >&2 ;;
|
|
esac
|
|
done <"$CONF"
|
|
}
|
|
|
|
# --- collectors -------------------------------------------------------------
|
|
|
|
os_release_field() {
|
|
local key=$1 k v
|
|
[[ -r $ROOT/etc/os-release ]] || return 0
|
|
while IFS='=' read -r k v; do
|
|
if [[ $k == "$key" ]]; then
|
|
v=${v#\"}
|
|
v=${v%\"}
|
|
printf '%s' "$v"
|
|
return 0
|
|
fi
|
|
done <"$ROOT/etc/os-release"
|
|
}
|
|
|
|
# Installed kernel image versions (e.g. 6.12.57+deb13-amd64), oldest first.
|
|
installed_kernels() {
|
|
dpkg-query -W -f='${db:Status-Abbrev} ${Package}\n' \
|
|
'linux-image-[0-9]*' 'linux-image-unsigned-[0-9]*' 2>/dev/null |
|
|
awk '$1 == "ii" { print $2 }' |
|
|
grep -v -- '-dbg$' |
|
|
sed -E 's/^linux-image-(unsigned-)?//' |
|
|
sort -uV || true
|
|
}
|
|
|
|
# Package version of the image for the running kernel (e.g. 6.12.57-1). The
|
|
# server compares it with the build in `uname -v` to spot in-place upgrades.
|
|
running_kernel_pkg_version() {
|
|
dpkg-query -W -f='${db:Status-Abbrev} ${Version}\n' \
|
|
"linux-image-$1" "linux-image-unsigned-$1" 2>/dev/null |
|
|
awk '$1 == "ii" { print $2; exit }' || true
|
|
}
|
|
|
|
# Sets NR_KSTA / NR_KEXP from `needrestart -b`. KSTA: 0 unknown, 1 current,
|
|
# 2 ABI-compatible upgrade pending, 3 version upgrade pending. Optional: as a
|
|
# normal user it can't read Ubuntu's root-only /boot images and reports 0.
|
|
NR_KSTA=
|
|
NR_KEXP=
|
|
read_needrestart() {
|
|
command -v needrestart >/dev/null 2>&1 || return 0
|
|
local line
|
|
while IFS= read -r line; do
|
|
case $line in
|
|
NEEDRESTART-KSTA:*) NR_KSTA=${line#*: } ;;
|
|
NEEDRESTART-KEXP:*) NR_KEXP=${line#*: } ;;
|
|
esac
|
|
done < <(needrestart -b -k -r l 2>/dev/null || true)
|
|
}
|
|
|
|
# Simulated dist-upgrade. Reads only: no locks, no cache files written.
|
|
# dist-upgrade (not upgrade) so new-ABI kernel packages pulled in by the
|
|
# meta-package show up.
|
|
apt_simulation() {
|
|
apt-get -s -q \
|
|
-o Debug::NoLocking=true \
|
|
-o Dir::Cache::pkgcache= \
|
|
-o Dir::Cache::srcpkgcache= \
|
|
dist-upgrade 2>/dev/null || true
|
|
}
|
|
|
|
# Seconds since apt last refreshed its package lists, or empty if unknown.
|
|
apt_lists_age() {
|
|
local newest=0 f m
|
|
for f in \
|
|
"$ROOT/var/lib/apt/periodic/update-success-stamp" \
|
|
"$ROOT/var/lib/apt/periodic/update-stamp" \
|
|
"$ROOT/var/lib/apt/lists/partial"; do
|
|
[[ -e $f ]] || continue
|
|
m=$(stat -c %Y "$f" 2>/dev/null) || continue
|
|
((m > newest)) && newest=$m
|
|
done
|
|
((newest > 0)) && printf '%s' $(($(date +%s) - newest))
|
|
return 0
|
|
}
|
|
|
|
uptime_seconds() {
|
|
local up _
|
|
[[ -r $ROOT/proc/uptime ]] || return 0
|
|
read -r up _ <"$ROOT/proc/uptime"
|
|
printf '%s' "${up%%.*}"
|
|
}
|
|
|
|
build_report() {
|
|
local running newest kernels sim inst reboot_file=0 reboot_pkgs=
|
|
|
|
running=$(uname -r)
|
|
kernels=$(installed_kernels)
|
|
newest=$(tail -n1 <<<"$kernels")
|
|
read_needrestart
|
|
|
|
sim=$(apt_simulation)
|
|
inst=$(grep '^Inst ' <<<"$sim" || true)
|
|
|
|
if [[ -e $ROOT/run/reboot-required ]]; then
|
|
reboot_file=1
|
|
[[ -r $ROOT/run/reboot-required.pkgs ]] && reboot_pkgs=$(sort -u "$ROOT/run/reboot-required.pkgs")
|
|
fi
|
|
|
|
printf '{'
|
|
printf '"agent_version":%s,' "$(json_str "$AGENT_VERSION")"
|
|
printf '"reported_hostname":%s,' "$(json_str "$(hostname -f 2>/dev/null || hostname)")"
|
|
printf '"os_id":%s,' "$(json_str "$(os_release_field ID)")"
|
|
printf '"os_version_id":%s,' "$(json_str "$(os_release_field VERSION_ID)")"
|
|
printf '"os_pretty_name":%s,' "$(json_str "$(os_release_field PRETTY_NAME)")"
|
|
printf '"kernel_running":%s,' "$(json_str "$running")"
|
|
printf '"kernel_build":%s,' "$(json_str "$(uname -v)")"
|
|
printf '"kernel_running_pkg_version":%s,' "$(json_str "$(running_kernel_pkg_version "$running")")"
|
|
printf '"kernels_installed":%s,' "$(json_str_array <<<"$kernels")"
|
|
printf '"kernel_newest_installed":%s,' "$(json_str "$newest")"
|
|
printf '"needrestart_ksta":%s,' "$(json_int "$NR_KSTA")"
|
|
printf '"needrestart_kexp":%s,' "$(json_str "$NR_KEXP")"
|
|
printf '"reboot_required":%s,' "$(json_bool "$reboot_file")"
|
|
printf '"reboot_required_pkgs":%s,' "$(json_str_array <<<"$reboot_pkgs")"
|
|
printf '"upgradable_count":%s,' "$(json_int "$(grep -c . <<<"$inst" || true)")"
|
|
printf '"security_count":%s,' "$(json_int "$(grep -ci 'security' <<<"$inst" || true)")"
|
|
printf '"kernel_upgradable":%s,' "$(awk '$2 ~ /^linux-image-/ { print $2 }' <<<"$inst" | json_str_array)"
|
|
printf '"apt_lists_age_seconds":%s,' "$(json_int "$(apt_lists_age)")"
|
|
printf '"uptime_seconds":%s' "$(json_int "$(uptime_seconds)")"
|
|
printf '}\n'
|
|
}
|
|
|
|
send_report() {
|
|
local payload=$1 token
|
|
[[ -n $SERVER_URL ]] || die "SERVER_URL is not set in $CONF"
|
|
|
|
# Prefer the systemd credential (LoadCredential=token:...).
|
|
if [[ -n ${CREDENTIALS_DIRECTORY:-} && -r $CREDENTIALS_DIRECTORY/token ]]; then
|
|
token=$(<"$CREDENTIALS_DIRECTORY/token")
|
|
elif [[ -r $TOKEN_FILE ]]; then
|
|
token=$(<"$TOKEN_FILE")
|
|
else
|
|
die "no token: neither \$CREDENTIALS_DIRECTORY/token nor $TOKEN_FILE is readable"
|
|
fi
|
|
token=${token//[[:space:]]/}
|
|
[[ -n $token ]] || die "token is empty"
|
|
|
|
local -a args=(--silent --show-error --fail-with-body
|
|
--max-time "$TIMEOUT" --retry 3 --retry-delay 10 --retry-connrefused
|
|
--header 'Content-Type: application/json'
|
|
--data-binary "$payload"
|
|
--config -)
|
|
[[ -n $CA_FILE ]] && args+=(--cacert "$CA_FILE")
|
|
|
|
# Token goes in via a curl config on stdin so it never appears in argv.
|
|
printf 'header = "Authorization: Bearer %s"\n' "$token" |
|
|
curl "${args[@]}" "${SERVER_URL%/}/api/v1/report" >/dev/null
|
|
}
|
|
|
|
main() {
|
|
local mode=send
|
|
case ${1:-} in
|
|
--print) mode=print ;;
|
|
--help | -h)
|
|
usage
|
|
return 0
|
|
;;
|
|
"") ;;
|
|
*)
|
|
usage >&2
|
|
return 2
|
|
;;
|
|
esac
|
|
|
|
load_config
|
|
local report
|
|
report=$(build_report)
|
|
|
|
if [[ $mode == print ]]; then
|
|
printf '%s\n' "$report"
|
|
else
|
|
send_report "$report"
|
|
echo "kernelwatch-agent: report sent to $SERVER_URL"
|
|
fi
|
|
}
|
|
|
|
main "$@"
|