0

Occasionally my laptop doesn't go to sleep when the lid is shut. The reasons for this vary, but it's often due to a driver that is in a bad state. I currently have no way of knowing there's a problem until hours later when I open the laptop and it's either fully drained the battery and hard powered off or the battery is severely depleted.

I'd like to create a rule such that for some predetermined log line or pattern an action is taken, such as running a script to generate an audible alert. Ideally this should be event based rather than polling, and if possible it would be good to avoid setting up a syslog configuration to achieve this.

Sample log lines for this include:

can't change power state from D3cold to D0
can't change power state from D3hot to D0
0

I've found a way to make this work, and without having to use the journal to do any log parsing, which really is not a great idea.

Instead I tapped into the systemd-sleep hooks and used that to check the logs for a failed sleep within the last couple of minutes, on wake. In that event an audio file would be played.

My tooling is available at https://gitlab.com/jinnko/failed-sleep-alarm.

The key to this is having a script in /lib/systemd/system-sleep/ that will be triggered both before and after any of sleep, suspend or hibernate. That script can then check the logs and take action. In my case the script looks like this (check the repo for the latest version):

#!/usr/bin/env bash

set -euo pipefail

logger -s -p kern.debug "Invoked $(realpath "$0") $*"

case $1/$2 in
  post/*)
    if /usr/bin/journalctl --since "2m ago" | grep -E "Failed to start (Hibernate|Sleep|Suspend)"; then
      amixer -q sset Master unmute
      amixer sset Master '35%'
      for i in {1..3}; do
        mpg123 -q /usr/share/failed-sleep-alarm/pig.mp3
      done
    fi
    ;;
esac
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.