Make "shutdown time" configurable: SHUTDOWN_TIME
[trigger-rcmd.git] / scripts / trigger-rcmd
index 89f61f1b148d37a817106b3c0df3a50e9b371c6f..7d90e3bcc4bb750e2863e785bb51dc794bd53d5a 100755 (executable)
@@ -15,11 +15,19 @@ RCMD_D="/usr/local/etc/rcmd.d"
 
 PATH="$PATH:/usr/local/sbin:/usr/sbin"
 
+do_help() {
+       echo "Usage: $0 <rcmd> [<rcmd> [...]]" >&2
+       exit 2
+}
+
 do_rcmd() {
        SYSTEM="localhost"
        IFACE="eth0"
        CMD="uptime"
        TIMEOUT="180"
+       SSH_CHECKS="6"
+       WAKE_DELAY="10s"
+       SHUTDOWN_TIME="+10"
 
        . "$cnf"
 
@@ -33,6 +41,11 @@ do_rcmd() {
        echo "$NAME: checking system \"$SYSTEM\" ..."
        fping -c1 -q "$SYSTEM" 2>/dev/null
        if [ $? -ne 0 ]; then
+               if [ -n "$NO_WAKE" ]; then
+                       echo "$NAME: \"$SYSTEM\" seems to be down, skipping job."
+                       return 9
+               fi
+
                echo "$NAME: \"$SYSTEM\" seems to be down, wake it up ..."
                etherwake -b -i "$IFACE" `echo "$SYSTEM" | cut -d'.' -f1`
                if [ $? -ne 0 ]; then
@@ -50,13 +63,20 @@ do_rcmd() {
                        echo "$NAME: failed to wake \"$SYSTEM\"!" >&2
                        return 4
                fi
-               sleep 3
+               sleep "$WAKE_DELAY"
                rsys_was_running=0
        else
                echo "$NAME: \"$SYSTEM\" is already alive, ok."
                rsys_was_running=1
        fi
 
+       for i in `seq 1 $SSH_CHECKS`; do
+               echo "$NAME: checking SSH connection ($i/$SSH_CHECKS) ..."
+               ssh -q "$SYSTEM" true >/dev/null 2>&1 && break
+               echo "$NAME: SSH on \"$SYSTEM\" not ready. Waiting ..."
+               sleep 10s
+       done
+
        echo "$NAME: calling \"$CMD\" on \"$SYSTEM\" ..."
        echo
 
@@ -70,7 +90,7 @@ do_rcmd() {
                rsys_users=`ssh -q "$SYSTEM" w | tail -n +3 | wc -l`
                if [ "$rsys_users" = "0" ]; then
                        echo "$NAME: power off \"$SYSTEM\" again ..."
-                       ssh -q "$SYSTEM" "sync; shutdown -hP +1"
+                       ssh -q "$SYSTEM" "sync; shutdown -hP $SHUTDOWN_TIME" >/dev/null
                        if [ $? -ne 0 ]; then
                                echo "$NAME: failed to power off \"$SYSTEM\"!" >&2
                                return 5
@@ -87,10 +107,22 @@ do_rcmd() {
        [ $r -eq 0 ] && return 0 || return 1
 }
 
-if [ $# -lt 1 ]; then
-       echo "Usage: $0 <rcmd> [<rcms> [...]]" >&2
-       exit 2
-fi
+# Defaults
+NO_WAKE=
+
+while [ $# -gt 0 ]; do
+       case "$1" in
+         --no-wake|-n)
+               NO_WAKE=1; ;;
+         --help|-*)
+               do_help; ;;
+         *)
+               break
+       esac
+       shift
+done
+
+[ $# -gt 0 ] || do_help
 
 result=0
 while [ $# -gt 0 ]; do