#!/bin/sh
#
# External STONITH module for Xen Dom0 through ssh.
#
# Description:  Uses Xen Dom0 Domain as a STONITH device
#               to control DomUs.
#
#
# Author:       Serge Dubrouski (sergeyfd@gmail.com)
#               Inspired by Lars Marowsky-Bree's external/ssh agent.
#
# Copyright 2006 Serge Dubrouski <sergeyfd@gmail.com>
# License:      GNU General Public License (GPL)
#

SSH_COMMAND="/usr/bin/ssh -q -x -n -l root"
STOP_COMMAND="xm destroy"
START_COMMAND="xm create"

# Rewrite the hostlist to accept "," as a delimeter for hostnames too.
hostlist=`echo $hostlist | tr ',' ' '`

CheckIfDead() {
	for j in 1 2 3
        do
          if
            ping -w1 -c1 "$1" >/dev/null 2>&1
          then
            return 1
          fi
        done
        return 0
}

case $1 in
gethosts)
	for h in $hostlist ; do
          CIFS=$IFS
          IFS=:
          read node xen0 cfg << -!
$h
-!
          IFS=$CIFS

          echo $node
	done
	exit 0
	;;
on)
	# Can't really be implemented because ssh cannot power on a system
	# when it is powered off.
	exit 1
	;;
off)
	# Shouldn't really be implemented because if ssh cannot power on a 
	# system, it shouldn't be allowed to power it off.
	exit 1
	;;
reset)
        if
          [ -z "$hostlist" ]
        then
          exit 1
        fi

	for h in $hostlist
	do
          CIFS=$IFS
          IFS=:
          read node xen0 cfg << -!
$h
-!
          IFS=$CIFS

	  if
            [ "$node" != "$2" ]
          then
            continue
          fi
	  $SSH_COMMAND $xen0 "(sleep 2; $STOP_COMMAND $node) >/dev/null 2>&1 &"
          for j in 1 2 3 4 5
          do
            if
              CheckIfDead "$node"
            then
	      $SSH_COMMAND $xen0 "(sleep 2; $START_COMMAND $cfg) >/dev/null 2>&1 &"
              exit 0
            fi
            sleep 1
          done
	done
	exit 1
	;;
status)
	if
	  [ -z "$hostlist" ]
	then
	  exit 1
	fi

	for h in $hostlist
	do
          CIFS=$IFS
          IFS=:
          read node xen0 cfg << -!
$h
-!
          IFS=$CIFS

	  if
            ping -w1 -c1 "$node" 2>&1 | grep "unknown host"
          then
	    exit 1
	  fi
	done
	exit 0
	;;
getconfignames)
	echo "hostlist"
	exit 0
	;;
getinfo-devid)
	echo "xen0 STONITH device"
	exit 0
	;;
getinfo-devname)
	echo "xen0 STONITH external device"
	exit 0
	;;
getinfo-devdescr)
	echo "ssh-based Linux host reset for Xen DomU trough Dom0"
	echo "Fine for testing, but not really suitable for production!"
	exit 0
	;;
getinfo-devurl)
	echo "http://openssh.org http://www.xensource.com/"
	exit 0
	;;
getinfo-xml)
	cat << SSHXML
<parameters>
<parameter name="hostlist" unique="1" required="1">
<content type="string" />
<shortdesc lang="en">
Hostlist
</shortdesc>
<longdesc lang="en">
The list of controlled nodes in a format node:xen0:config_file.
For example: "node1:xen01:/opt/xen/node1.cfg node2:xen02:/opt/xen/node2.cfg"
</longdesc>
</parameter>
</parameters>
SSHXML
	exit 0
	;;
*)
	exit 1
	;;
esac
