Sensorsd - UPS Shutdown

Page content

Shutdown Hosts on Power Outages

Everybody is talking about Power Outages. Let’s assume you have a Smart-UPS for your Playground and you’d like to shut some Infrastructure to avoid some troubles with corrupt filesystems, broken vm’s and things like that.

Connection UPS to APU via USB Cable

dmesg show the UPS connected

APU# dmesg
uhidev0 at uhub0 port 3 configuration 1 interface 0 "American Power Conversion Smart-UPS_1500 ...
uhidev0: iclass 3/0, 142 report ids
upd0 at uhidev0
uhid0 at uhidev0 reportid 1: input=0, output=0, feature=1
uhid1 at uhidev0 reportid 2: input=0, output=0, feature=1
...
uhid21 at uhidev0 reportid 142: input=0, output=0, feature=4

Check sysctl

what kind of information do we get from the hardware sensor ?

APU# sysctl hw.sensors
hw.sensors.upd0.indicator0=On (BatteryPresent), OK
hw.sensors.upd0.indicator1=On (Charging), OK
hw.sensors.upd0.indicator2=Off (Discharging), OK
hw.sensors.upd0.indicator3=Off (NeedReplacement), OK
hw.sensors.upd0.indicator4=Off (ShutdownImminent), OK
hw.sensors.upd0.indicator5=On (ACPresent), OK
hw.sensors.upd0.indicator6=Off (Overload), OK
hw.sensors.upd0.percent0=99.00% (RemainingCapacity), OK
hw.sensors.upd0.percent1=100.00% (FullChargeCapacity), OK
hw.sensors.upd0.timedelta0=86400.000000 secs (RunTimeToEmpty), OK

Sensorsd Config

append to sensorsd.conf file

cat << 'EOF' >> /etc/sensorsd.conf

# shutdown servers at 30% capacity
hw.sensors.upd0.percent0:low=30.00%:command=/root/shutdown-low-battery.sh %2 %l

EOF

Shutdown Script

cat << 'EOF' > /root/shutdown-low-battery.sh
#!/bin/sh

# wait seconds
limit=120

# get the charging state of the UPS
CHARGING=$(sysctl -n hw.sensors.upd0.indicator1)

# If the UPS is currently charging, do nothing.
if [[ "$CHARGING" = "On (Charging), OK" ]]; then
  logger "power is on, do nothing \($1, $2\)"
  return
fi

# If the UPS is on battery and the threshold is below the setting, shutdown in 2min
if [[ "$2" = "below" ]]; then
  logger "battery below $1, shutting down in ${limit} seconds."
  sleep ${limit}
  logger "battery at $1, shutting down now."

  # shutdown other boxes
  ssh root@host1 "halt -p"
  ssh root@host2 "halt -p"
  ssh root@host3 "halt -p"

  # shutdown myself
  halt -p
fi
EOF

chmod 700 shutdown-low-battery.sh

Enable and Start Service

rcctl enable sensorsd
rcctl restart sensorsd

now wait for the next power outage (just kidding) or better yet, simulate one and see if your script behaves as expected…

sha256: aeaab10338f9f01827baf134dec5c8b9511773f21bdc97a8a54737cc98dee16c