Skip to content
Open
Show file tree
Hide file tree
Changes from 10 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
224 changes: 139 additions & 85 deletions bin/omarchy-crash-watch
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@
# omarchy:summary=Watch for process crashes and OOM kills and notify the user
# omarchy:hidden=true

# systemd-coredump journals every core dump under COREDUMP_MESSAGE_ID with
# structured COREDUMP_* fields. systemd journals systemd-oomd kills under
# OOMD_KILL_MESSAGE_ID and kernel cgroup OOM kills under OOM_KILL_MESSAGE_ID
# with USER_UNIT.
# systemd-coredump's ExecStopPost emits its InvocationID, even when no core
# file is saved, so crashes arrive as markers in /run/omarchy-crash-events and
# cost one short-lived journal lookup each. systemd journals systemd-oomd kills
# under OOMD_KILL_MESSAGE_ID and kernel cgroup OOM kills under
# OOM_KILL_MESSAGE_ID with USER_UNIT, and those still come from one journal
# stream.

set -uo pipefail

Expand All @@ -15,6 +17,10 @@ readonly COREDUMP_MESSAGE_ID=fc2e22bc6ee647b6b90729ab34a250b1
readonly OOMD_KILL_MESSAGE_ID=d989611b15e44c9dbf31e3c81256e4ed
readonly OOM_KILL_MESSAGE_ID=fe6faa94e7774663a0da52717891d8ef

# The crash-events drop-in writes one ephemeral, root-owned marker here per
# finished coredump, named after its InvocationID.
readonly crash_event_dir=/run/omarchy-crash-events

# nf-md-robot_dead and nf-md-memory, escaped so this file reads without a Nerd Font.
readonly CRASH_GLYPH=$'\U000f16a1'
readonly OOM_GLYPH=$'\U000f035b'
Expand Down Expand Up @@ -122,38 +128,46 @@ announce_oom() {
"$body"
}

# -n 0 so a restart does not re-announce events already dealt with. Passing
# multiple MESSAGE_ID= matches tells journalctl to OR them into one stream.
journalctl -f -n 0 -o json \
"MESSAGE_ID=$COREDUMP_MESSAGE_ID" \
"MESSAGE_ID=$OOMD_KILL_MESSAGE_ID" \
"MESSAGE_ID=$OOM_KILL_MESSAGE_ID" 2>/dev/null |
while IFS= read -r entry; do
# A dash for a field that is empty, missing, or non-string (journalctl
# emits non-UTF-8 values as byte arrays): tab is IFS whitespace, so an
# empty field collapses into the next delimiter and shifts fields along.
IFS=$'\t' read -r msg_id uid comm pid exe signal user_unit rt_us cd_us < <(
jq -r 'def field:
if type == "string" and . != "" then
gsub("[\t\r\n]"; "") | if . == "" then "-" else . end
else "-"
end;
[(.MESSAGE_ID | field),
(._UID | field),
(.COREDUMP_COMM | field),
(.COREDUMP_PID | field),
(.COREDUMP_EXE | field),
(.COREDUMP_SIGNAL_NAME | field),
(.USER_UNIT | field),
(.__REALTIME_TIMESTAMP | field),
(.COREDUMP_TIMESTAMP | field)] | join("\t")' <<<"$entry" 2>/dev/null
)

# Only this user's events; a daemon dying is a sysadmin's problem.
[[ $uid =~ ^[0-9]+$ ]] || continue
((uid == UID)) || continue

if [[ $msg_id == $OOMD_KILL_MESSAGE_ID || $msg_id == $OOM_KILL_MESSAGE_ID ]]; then
# Two producers, one reader: a coredump completion marker means a crash, while
# OOM kills still arrive on the journal stream (-n 0 so a restart does not
# re-announce events already dealt with). Both run at once and share one reader,
# so the OOM grace window and the dedupe state stay in a single process.
{
journalctl -f -n 0 -o json \
"MESSAGE_ID=$OOMD_KILL_MESSAGE_ID" \
"MESSAGE_ID=$OOM_KILL_MESSAGE_ID" 2>/dev/null |
jq -r 'def field:
Comment thread
felixzsh marked this conversation as resolved.
Resolved
if type == "string" and . != "" then
gsub("[\t\r\n]"; "") | if . == "" then "-" else . end
else "-"
end;
["oom",
(._UID | field),
(.USER_UNIT | field),
(.__REALTIME_TIMESTAMP | field)] | join("\t")' &

# inotify queues a marker's name even if it is removed before we read it, and
# a restart does not replay events that arrived while the watcher was down.
# A missing event directory makes inotifywait exit at once, so retry: the
# directory only appears when tmpfiles or the drop-in first runs, and losing
# every later crash for the rest of the session would be worse than a wait.
until inotifywait -m -e create --format '%f' "$crash_event_dir" 2>/dev/null |
while IFS= read -r invocation_id; do printf 'crash\t%s\n' "$invocation_id"; done; do
sleep 5
done &

wait
} | while IFS=$'\t' read -r kind payload; do
case $kind in
oom)
# A dash for a field that is empty, missing, or non-string (journalctl
# emits non-UTF-8 values as byte arrays).
IFS=$'\t' read -r uid user_unit rt_us <<<"$payload"

# Only this user's events; a daemon dying is a sysadmin's problem.
[[ $uid =~ ^[0-9]+$ ]] || continue
((uid == UID)) || continue

# Kernel OOM events can propagate to parent slices; notify only for the
# killed unit itself.
[[ $user_unit == *.slice ]] && continue
Expand All @@ -168,52 +182,92 @@ journalctl -f -n 0 -o json \

(((now - ${last_oom_notified[$oom_key]:-0}) < dedupe_seconds)) && continue
announce_oom "$oom_app" && last_oom_notified[$oom_key]=$now
continue
fi

[[ $pid =~ ^[0-9]+$ ]] || continue

# The toast only offers a diagnosis, so it has nothing to offer until an
# agent is chosen. Checked per crash, not at startup, so picking one takes
# effect without restarting this service.
[[ -n $(omarchy-default-agent) ]] || continue

now=$EPOCHSECONDS
crash_at=$now
[[ $cd_us =~ ^[0-9]{7,}$ ]] && crash_at=$(( cd_us / 1000000 ))
recent_oom "$crash_at" && continue

# comm is truncated to 15 characters, so prefer the executable's basename.
name=$comm
[[ $exe == /* ]] && name=${exe##*/}

# A process can set its own comm to anything prctl takes, slashes included,
# and a crash with no recorded executable falls back to it. The mute below
# turns this name into a path, so keep it one component: a crash must not
# reach a flag outside crash-ignore/, nor have a diagnosis write one there.
name=${name##*/}

# What that leaves is not always a name. "/" leaves nothing, which is no
# kind of array subscript and no kind of toast; a dot component names a
# directory rather than a flag, so a mute on it would touch that directory
# and then never match; and a dash is what the read above puts there when
# the crash recorded no name at all.
[[ -n $name && $name != "-" && $name != "." && $name != ".." ]] || name=unknown

[[ -n $ignore_pattern && $name =~ $ignore_pattern ]] && continue

# Never announce our own machinery, or it notifies about itself.
[[ $name == omarchy-crash-* || $name == omarchy-agent-* ]] && continue

# Muted at the end of a diagnosis, when the user was offered it and said
# yes. A flag per program rather than one list, so omarchy-crash-mute can
# lift one without reading, rewriting and re-parsing the rest.
omarchy-toggle-enabled "crash-ignore/$name" && continue

(((now - ${last_notified[$name]:-0}) < dedupe_seconds)) && continue

# Only a delivered toast starts the dedupe window. A failed send that
# counted would suppress the rest of a crash loop for a minute, and
# `journalctl -n 0` never replays what was missed.
announce_crash "$name" "$pid" "$exe" "$signal" && last_notified[$name]=$now
done
;;
crash)
invocation_id=$payload

# The event directory is world-readable, so a marker name that is not an
# InvocationID is not one of ours and is not a journal lookup.
[[ $invocation_id =~ ^[0-9a-f]{32}$ ]] || continue

# The toast only offers a diagnosis, so it has nothing to offer until an
# agent is chosen. Checked per crash, not at startup, so picking one takes
# effect without restarting this service.
[[ -n $(omarchy-default-agent) ]] || continue

# journald may still be accepting the entry when ExecStopPost runs. Match
# the handler's invocation, not a PID that can be reused within one boot.
# JSON preserves the original name and SIG-prefixed signal without parsing
# coredumpctl's human-readable output or systemd's escaped core filenames.
attempts=0
while (( attempts < 20 )); do
entry=$(journalctl --no-pager -n 1 -o json \
--output-fields=COREDUMP_UID,COREDUMP_COMM,COREDUMP_PID,COREDUMP_EXE,COREDUMP_SIGNAL_NAME,COREDUMP_TIMESTAMP \
"MESSAGE_ID=$COREDUMP_MESSAGE_ID" "_SYSTEMD_INVOCATION_ID=$invocation_id" 2>/dev/null
)
[[ -n $entry ]] && break
((attempts++))
(( attempts < 20 )) && sleep 0.1
done
if [[ -z $entry ]]; then
echo "No crash details for coredump invocation $invocation_id" >&2
continue
fi

# NUL separates even empty fields and names containing tabs or newlines.
mapfile -d '' -t fields < <(
jq -j '[(.COREDUMP_UID // ""), (.COREDUMP_COMM // ""), (.COREDUMP_PID // ""),
(.COREDUMP_EXE // "unknown"), (.COREDUMP_SIGNAL_NAME // "unknown"),
(.COREDUMP_TIMESTAMP // "")]
| .[] | ., "\u0000"' <<<"$entry" 2>/dev/null
)
(( ${#fields[@]} == 6 )) || continue
uid=${fields[0]} comm=${fields[1]} pid=${fields[2]} exe=${fields[3]} signal=${fields[4]} cd_us=${fields[5]}
[[ $uid =~ ^[0-9]+$ && $pid =~ ^[0-9]+$ ]] || continue

# Only this user's crashes; a daemon dumping core is a sysadmin's problem.
((uid == UID)) || continue

# A core dump right after an OOM kill is usually a process that kill took
# down, and the OOM toast already told the story.
now=$EPOCHSECONDS
crash_at=$now
[[ $cd_us =~ ^[0-9]{7,}$ ]] && crash_at=$(( cd_us / 1000000 ))
recent_oom "$crash_at" && continue

name=$comm
[[ $exe == /* ]] && name=${exe##*/}
[[ -n $exe ]] || exe=unknown
[[ -n $signal ]] || signal=unknown

# A process can set its own comm to anything prctl takes, slashes included,
# and a crash with no recorded executable falls back to it. The mute below
# turns this name into a path, so keep it one component: a crash must not
# reach a flag outside crash-ignore/, nor have a diagnosis write one there.
name=${name##*/}

# What that leaves is not always a name. "/" leaves nothing, which is no
# kind of array subscript and no kind of toast; a dot component names a
# directory rather than a flag, so a mute on it would touch that directory
# and then never match. Treat a dash placeholder as unknown too.
[[ -n $name && $name != "-" && $name != "." && $name != ".." ]] || name=unknown

[[ -n $ignore_pattern && $name =~ $ignore_pattern ]] && continue

# Never announce our own machinery, or it notifies about itself.
[[ $name == omarchy-crash-* || $name == omarchy-agent-* ]] && continue

# Muted at the end of a diagnosis, when the user was offered it and said
# yes. A flag per program rather than one list, so omarchy-crash-mute can
# lift one without reading, rewriting and re-parsing the rest.
omarchy-toggle-enabled "crash-ignore/$name" && continue

(((now - ${last_notified[$name]:-0}) < dedupe_seconds)) && continue

# Only a delivered toast starts the dedupe window. A failed send that
# counted would suppress the rest of a crash loop for a minute, and there
# is no replay of earlier events to make up for a missed toast.
announce_crash "$name" "$pid" "$exe" "$signal" && last_notified[$name]=$now
;;
esac
done
13 changes: 7 additions & 6 deletions docs/notifications.md
Original file line number Diff line number Diff line change
Expand Up @@ -207,12 +207,13 @@ The `notifications` IPC target also answers `ping` (used by `omarchy-notificatio
Everything goes through the same sender contract, so the pieces are small:

- **Low battery** — `omarchy-battery-low` sends a normal toast that expires after 30 seconds (paused, like any card, while the deck is open) and runs the `battery-low` hook. Not critical: a critical toast never expires and comes back on every shell start, so the warning would outlive the charger going in. As an `omarchy-action` toast it still gets through Do Not Disturb.
- **Crash capture** — `omarchy-crash-watch` follows the systemd-coredump
journal stream and announces each crashed program (deduped per minute) as a
critical toast whose click runs `omarchy-agent-crash` (via `--exec`, so a
hostile process name stays a discrete argument). It waits for the
server first: a shell crash takes the notification server down with it, and
that crash is the one most worth reporting.
- **Crash capture** — `omarchy-crash-watch` watches `/run/omarchy-crash-events` with inotify for coredump completion events and announces each crashed program (deduped per minute) as a critical toast whose click runs `omarchy-agent-crash` (via `--exec`, so a hostile process name stays a discrete argument). It waits for the server first: a shell crash takes the notification server down with it, and that crash is the one most worth reporting.

The package-owned `systemd-coredump@.service` drop-in emits its unique `InvocationID` through an ephemeral, root-owned marker in `ExecStopPost`. Tmpfiles creates the directory before user sessions start; only root can write it. The marker is immediately removed, but inotify retains its name. This does not depend on retaining a core file, so the event also arrives with `Storage=journal`, `Storage=none` (including `ProcessSizeMax=0`), or when a core exceeds `ExternalSizeMax`.

Each event triggers a short-lived JSON journal query matching the coredump `MESSAGE_ID` and `_SYSTEMD_INVOCATION_ID`, with brief retries for journal delivery. Only the current user's crashes are announced. The invocation match cannot select an older crash after PID reuse, and the original journal fields preserve empty names, spaces, leading dots and `SIG`-prefixed signals. Missing journal metadata is logged and the event skipped, since an invocation alone cannot safely identify a program. Events missed while the watcher is stopped are not replayed.

Out-of-memory kills are read from the journal instead, under their own `MESSAGE_ID`s and with `-n 0` so a restart does not replay them. A crash that lands within a few seconds of one is suppressed, because a process trapped by a kill it just survived is usually the story the OOM toast already told.
- **Pending migrations** — `omarchy-migrate-notify` (from its user service
after `graphical-session.target`) waits for the server, then sends a
critical toast whose click opens a terminal running `omarchy-migrate`,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
[Service]
# Only the handler writes here; user watchers need names, not file contents.
RuntimeDirectory=omarchy-crash-events
RuntimeDirectoryMode=0755
RuntimeDirectoryPreserve=yes
# Emitted after processing, independent of Storage= and core size limits.
# Each invocation is unique; deleting the marker does not erase its inotify event.
# Notification plumbing must never make coredump processing fail.
ExecStopPost=-/usr/bin/touch -- /run/omarchy-crash-events/${INVOCATION_ID}
ExecStopPost=-/usr/bin/rm -f -- /run/omarchy-crash-events/${INVOCATION_ID}
2 changes: 2 additions & 0 deletions etc/tmpfiles.d/omarchy-crash-events.conf
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# Create before user watchers start, not only when the first crash happens.
d /run/omarchy-crash-events 0755 root root -
18 changes: 18 additions & 0 deletions migrations/1786894219.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
echo "Enable coredump completion events and restart the crash watcher"

# Package-owned drop-ins are already installed. Create the event directory
# without waiting for reboot and load ExecStopPost for future coredumps.
sudo systemd-tmpfiles --create /etc/tmpfiles.d/omarchy-crash-events.conf
Comment thread
felixzsh marked this conversation as resolved.
Resolved
sudo systemctl daemon-reload

# The unit's ConditionPathExists re-checks the same toggle flag at every
# start, so a watcher the user disabled stays off: honoring the flag here
# makes this migration a no-op for them. Only nudge a watcher that is
# actually running; a stopped one stays stopped. A requested restart is left
# to fail loudly: the migration stays unmarked so omarchy-migrate retries it,
# instead of recording a success the watcher did not get.
[[ -f "$HOME/.local/state/omarchy/toggles/crash-capture-off" ]] && exit 0

if systemctl --user is-active --quiet omarchy-crash-watch.service; then
systemctl --user restart omarchy-crash-watch.service
fi
Loading