PipeBashOverSSH

24th October 2016 at 12:44pm
Bash

An evil example of nastiness. ;-)

#!/bin/bash

set -ueo pipefail

_vm_available () {
    (
    find /var/lib/images/ -maxdepth 1 -mindepth 1 \
        -name 'lost+found' -prune -o -type d -printf '%f\n' 2>/dev/null
    find /etc/xen/ -iname '*.pv' -printf '%f\n' 2>/dev/null
    ) | sort -u
}

_vm_running () {
    (
    for pid in $(pgrep '^qemu-system-[^[:space:]]+|kvm|kvm-[a-z0-9\._-]+$')
    do
        for fd in /proc/$pid/fd/* ; do
            readlink -f "$fd" | egrep -o '^/images/[^/]*/*' | cut -d'/' -f3
        done
    done
    xen list 2>&1 | tail -n+3 | awk '{print $1}'
    ) | sort -u
}

ssh () {
    command ssh \
      -o ConnectTimeout=7 -o LogLevel=QUIET -o BatchMode=yes \
      -t -l root "$@"
}

query_hypervisor () {
    declare -x vmhost="$1"
    while IFS=, read -r available running both ; do
        if [[ -n "$both" ]] ; then
            echo "$vmhost,$available,$both"
        else
            echo "$vmhost,$available,$running"
        fi
    done < <(
      {
          typeset -f _vm_available _vm_running
          echo 'comm --output-delimiter=, <(_vm_available) <(_vm_running)'
      } | ssh "$vmhost" bash --norc --noprofile
      )
}

main () {
    declare -x searchstr="${1:-.}"
    declare -arx vmhosts=(
    		hypervisor1 hypervisor2 hypervisor3 hypervisor4
            anotherhostA anotherhostB
            )
    echo "VMHOST,AVAILABLE,RUNNING" >&2
    {
        declare vmhost
        for vmhost in "${vmhosts[@]}" ; do
            query_hypervisor "$vmhost" &
        done
    } | grep -P "$searchstr"
}

main "$@"