Starting or stopping services when on AC or battery



I have been experimenting with Saltstack - more commonly known as just 'Salt' - and running the master on my laptop. Since it seems to be consuming CPU cycles all the time and I'd like to optimise my laptop's autonomy, I started looking into ways to disable it on battery, and enable it when on AC. My Dell's ACPI, however, is pretty wonky. I have been using TLP happily for a few years, but it does not support running extra commands when you plug in or unplug your charger. So my first try was acpid; but since acpi_listen does not see any difference between both events, that turned out useless. Next stop was pm-utils, but I was a bit wary that it might interfere with TLP's operations, so when that did not yield any results quickly, I decided to turn to udev once more. And luckily enough, all it takes is just an extra rules set to get things going. It can be a bit of a monster, but here's how it turned out:

cat /etc/udev/rules/100-salt.rules
# Enables Salt on AC, disables it on battery. Seems to be hogging a bit of power.
SUBSYSTEM=="power_supply", ENV{POWER_SUPPLY_ONLINE}=="1", RUN+="/bin/systemctl start salt-master.service"
SUBSYSTEM=="power_supply", ENV{POWER_SUPPLY_ONLINE}=="1", RUN+="/bin/systemctl start salt-minion.service"

SUBSYSTEM=="power_supply", ENV{POWER_SUPPLY_ONLINE}=="0", RUN+="/bin/systemctl stop salt-master.service"
SUBSYSTEM=="power_supply", ENV{POWER_SUPPLY_ONLINE}=="0", RUN+="/bin/systemctl stop salt-minion.service"

It looks like udev does not care (or know) about paths so using the full path is recommended. You can also tell udev to run commands depending on whether the battery's charging or discharging (e.g. some systems will not start charging if the battery charge's still above a certain treshold).