source: misc/power-saver@ 362

Last change on this file since 362 was 362, checked in by Rick van der Zwet, 13 years ago

Allow hacking on CLI by introducing some variables.

Load off-course needs to be less not more.

  • Property svn:executable set to *
File size: 1.9 KB
RevLine 
[361]1#!/bin/sh
2#
3# Shutdown system if it has been idle for 1 hour and no active users are logged
4# in.
5#
6# Usage: This script is mainly used on a home server used for building FreeBSD
7# World and kernels. As soon it is done it can shutdown if not being used
8# anymore. The system has Wake-On-Lan support and can thus be activated again
9# from remote.
10#
11# Please run from cron every CRON_INTERVAL minutes:
12# */5 * * * * * /usr/local/bin/power-saver
13#
14# Rick van der Zwet <info@rickvanderzwet.nl>
15#
16
17CRON_INTERVAL=5
18MAX_LOAD=0.10
19MAX_IDLE=60
20
[362]21# Abuse this trick to force a quicker shutdown by ignoring some users
22IDLE_USER=${1:-1}
23SHUTDOWN_DELAY=${2:-15}
24
[361]25# Stored as <epoch> <load>
26DAT_FILE='/tmp/power-saver.dat'
27
28# Current values
29EPOCH=`date "+%s"`
30LOAD_15=`sysctl vm.loadavg | awk '{print $5}'`
31
32# Empty file needs to be created and filled
33echo "$EPOCH $LOAD_15" >> $DAT_FILE || exit 1
34
35# Check if countdown has already been started
36ps -x | grep -q '[0-9] shutdown' && exit 0
37
38# Check if all users are no longer active
[362]39SHORTEST_IDLE=`w -ih | awk -vIDLE_USER=$IDLE_USER '{if (NR == IDLE_USER) print $5}'`
[361]40# Hack to make sure time is always in minutes
41SHORTEST_IDLE_IN_MIN=`echo $SHORTEST_IDLE | awk -F: '{if (NF > 1){print $1 * 60 + $2}else{print $1}}'`
42if [ -z "$SHORTEST_IDLE_IN_MIN" ]; then
43 # No users are currently logged in
44 continue
45elif [ "$SHORTEST_IDLE_IN_MIN" = "-" ]; then
46 # User is still active an minute ago
47 exit 0
48elif [ $SHORTEST_IDLE_IN_MIN -le $MAX_IDLE ]; then
49 # User is still active less than MAX_IDLE ago
50 exit 0
51fi
52
53# Count the amount entries we are current on our way
54IDLE_COUNTS=`awk -vMAX_LOAD=$MAX_LOAD -vMAX_IDLE=$MAX_IDLE -vEPOCH=$EPOCH \
[362]55 'BEGIN{MIN_TIME=EPOCH-MAX_IDLE;s=0}{if ($1 > MIN_TIME && $2 < MAX_LOAD){s += 1}}END{print s}' $DAT_FILE`
[361]56
57# We are idle for over $MAX_IDLE time, starting shutdown
58if [ $IDLE_COUNTS -gt `expr $MAX_IDLE / $CRON_INTERVAL` ]; then
[362]59 echo shutdown -p "+$SHUTDOWN_DELAY" "Cancel: sudo killall -SIGTERM shutdown"
[361]60fi
Note: See TracBrowser for help on using the repository browser.