#!/bin/sh

#  Copyright (c) 2013 Intel Corporation, All rights reserved. 
#  Copyright (C) 2006-2012 QLogic Corporation, All rights reserved.
#  Copyright (c) 2004, 2005, 2006 PathScale, Inc. All rights reserved.
#
#  Permission is granted to Intel customers to use this software in 
#  source and binary forms, with or without modification, provided that 
#  the following conditions are met: 
#  
#  + All copies of source code must retain the above copyright notice, 
#    this list of conditions and the following disclaimer. 
#  
#  + Customer has a valid license agreement from Intel Corporation. for the 
#    software product with which this software is originally distributed. 
#  
#  + Redistribution of original or modified versions to third parties is 
#    prohibited without specific prior written permission of Intel
#    Corporation. 
#  
#  + If customer makes modifications to this software, and provides those 
#    modifications to Intel, customer assigns to Intel Corporation. 
#    ownership of the provided modifications and all intellectual property 
#    rights embodied in those modifications. 
#  
#  + The name of Intel Corporation. may not be used to endorse or promote 
#    products derived from this software without specific prior written 
#    permission. 
#  
#  THIS SOFTWARE IS PROVIDED BY INTEL CORPORATION. AND ITS LICENSORS "AS IS" 
#  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, 
#  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 
#  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL INTEL CORPORATION. OR ITS 
#  LICENSORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 
#  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 
#  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 
#  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 
#  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 
#  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
#  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 

declare    cont=false
declare -i failures=0
declare -a good_nodes
declare    keep=false
declare -r launch_dir="${PWD}"
declare    machine_file=
declare -a nodes
declare -i num_nodes=0
declare    skip_list=
declare    run_list="1234567"
declare    work_dir=
declare    verbose=false
declare    vverbose=false
declare    vvverbose=false
declare    sshopt=-ax
declare    sshpath=PATH=/bin:/usr/bin:/sbin:/usr/bin
declare    sshshell='/bin/sh -f'
declare    sshshellg='/bin/sh'
declare    watchdog_file=/tmp/.watchdog.$$

# mpi_dir is determined in get_mpi_info. The mpirun options are  parameterized 
# here to make it easier to use a different MPI if required.
declare    mpi_dir=
declare    mpirun=mpirun
declare    mpi_nxnlatbw=mpi_nxnlatbw
declare    mpirun_m="--machinefile"
declare    mpirun_n="-n"
declare    mpirun_version="--version"
declare    mpirun_options="--mca mtl psm"

unset IPATH_CHECKOUT_VERBOSE
unset IPATH_CHECKOUT_VVERBOSE
unset IPATH_CHECKOUT_VVVERBOSE

export PATH=/bin:/usr/bin:/sbin:/usr/bin:$PATH # Set a sane search path

usage()
{
    echo 'Usage:'
    echo '    ipath_checkout [-h|--help] [-v|-vv|-vvv] [-c|--continue] [-k|--keep]'
    echo '        [--workdir=DIR] [--run=LIST] [--skip=LIST] [-d|--debug] [--] nodefile'
    echo ''
    echo '    -h, --help'
    echo '        Display this usage message and exit.'
    echo ''
    echo '    -v, --verbose'
    echo '    -vv, --vverbose'
    echo '    -vvv, --vvverbose'
    echo '        Print increasingly more detailed reports of what is being tested'
    echo '        and the results of those tests.'
    echo ''
    echo '    -c, --continue'
    echo '        Continue on to subsequent tests rather than halting when some nodes'
    echo '        fail.  Failing nodes are excluded from subsequent tests.'
    echo ''
    echo '    -k, --keep'
    echo '        Keep intermediate files that were created while performing tests'
    echo '        and compiling reports.  Results will be saved in a directory named'
    echo '        ipath_checkout_?????? or the directory name given to --workdir.'
    echo ''
    echo '    --workdir=DIR'
    echo '        Use DIR to hold intermediate files created while running tests.'
    echo '        DIR must not already exist.'
    echo ''
    echo '    --run=LIST'
    echo '        Run only the tests in LIST (e.g. --run=123 will run only tests 1, 2,'
    echo '        and 3).  The test phases are:'
    echo ''
    echo '        1. ping all nodes to verify network connectivity'
    echo '        2. ssh to each node'
    echo '        3. gather and analyze system configuration from nodes'
    echo '        4. gather and analyze RPMs installed on nodes'
    echo '        5. verify InfiniPath hw and software status and configuration'
    echo '        6. verify ability to mpirun jobs on nodes'
    echo '        7. run NxN bandwith/latency MPI program and analyze results'
    echo ''
    echo '    --skip=LIST'
    echo '        Skip the tests in LIST (e.g. --skip=2457 will skip tests 2, 4, 5,'
    echo '        and 7).  The test phases are the same as with the --run option.'
    echo '        If both --run and --skip options are specified, test given by the'
    echo '        --skip option will be removed from the list of tests given by the'
    echo '        --run option.'
    echo ''
    echo '    --'
    echo '        Indicates the end of supplied flags.'
    echo ''
    echo '    nodefile'
    echo '        A list of hostnames that constitute the nodes of the cluster'
    echo '        to be tested, one per line.'
}

abend()
{
    cleanup
    echo "$0: Test aborted"
    exit 1
}

cleanup()
{
    cd "${launch_dir}"
    exec 3< /dev/null # don't want to still have a file open in work_dir
    if [ ${keep} = "false" ]; then
        rm -rf "${work_dir}"
    fi
}

error()
{
    echo "$0: Error -- $1"
    exit 1
}

failure()
{
    (( failures++ ))
    if [ ${cont} = "false" ]; then
        abend
    fi
}

cmp_kernrels()
{
    # return true if kernel maj.min.sub rev number in $4-6 < one in $1-3
    if [ $4 -lt $1 ] ; then
        return 0
    elif [ $4 -gt $1 ] ; then
        return 1
    fi
    if [ $5 -lt $2 ] ; then
        return 0
    elif [ $5 -gt $2 ] ; then
        return 1
    fi
    if [ $6 -lt $3 ] ; then
        return 0
    elif [ $6 -gt $3 ] ; then
        return 1
    fi
    return 1
}


get_nodes()
{
    # read in machine file

    if [ "${vverbose}" = "true" ]; then
        echo "Reading node list..."
    fi

    exec 3< ./NODELIST
    while IFS="${IFS}:" read -u 3 node junk; do
        case "${node}" in
            \#*)
                if [ "${verbose}" = "true" ]; then
                    echo "Skipping commented out node: ${node} ${junk}"
                fi
                continue
                ;;
        esac
        nodes[${num_nodes}]="${node}"
        good_nodes[${num_nodes}]="${node}"
        (( num_nodes++ ))
        if [ "${vverbose}" = "true" ]; then
            echo -e "\t${node}"
        fi
    done
    if [ ${num_nodes} -eq 0 ]; then
        error "no hosts listed in machine file"
    fi
    exec 3<&-

    for (( i=0; i<num_nodes; i++ )); do
        mkdir "${nodes[${i}]}" || error "couldn't mkdir ${PWD}/${nodes[${i}]}"
        echo "${nodes[${i}]}" > "${nodes[${i}]}/hostname"
    done

    if [ "${vverbose}" = "true" ]; then
        echo
    fi
}

mk_workdir()
{
    # create work dir
    if [ ! "${work_dir}" ]; then
        work_dir=${launch_dir}/`mktemp -d infinipath_XXXXXX`
        if [ $? -ne 0 ]; then
            error "mktemp of work directory failed"
        fi
    elif [ ! -e "${work_dir}" ]; then
        mkdir -m 700 -p "${work_dir}"
        if [ $? -ne 0 ]; then
            error "could not create work directory ${work_dir}"
        fi
    else
        error "work directory ${work_dir} exists"
    fi

    # copy machine file
    sort -u "${machine_file}" | sed '/^[ 	]*$/d' > "${work_dir}/NODELIST"
}

get_mpi_info()
{
    info=`rpm -qi openmpi_gcc_qlc 2> /dev/null`
    if [ "$?" == "0" ] ; then
        dir=`echo "$info" | gawk '/Relocations[:| :]/ { print $NF }'`
        if [ -d "$dir" ] ; then
            mpi_dir="$dir"
            mpirun="$mpi_dir/bin/mpirun"
            mpi_nxnlatbw="$mpi_dir/tests/intel/mpi_nxnlatbw"
            mpi_allow_root="--allow-run-as-root"
        fi
    fi
    if [ "${vverbose}" = "true" ]; then
        if [ "$mpi_dir" = "" ] ; then 
            echo "Did not find OpenMPI installation"
        else
            echo "Found OpenMPI installation at $mpi_dir"
        fi
    fi
}

function handle_interupt() {
    if [ -e ${watchdog_file} ]; then
	fuser -sk ${watchdog_file}
	rm -rf ${watchdog_file}
    fi
    exit 1
}

function pssh() {
    cmd="$1"
    output="$2"
    
    trap 'handle_interupt; trap 0 1 2 15' 0 1 2 15
    
    cmd_p="$(echo $cmd | sed -e 's/\$/\\\$/g' -e 's/"/\\"/g')"
    for (( i=0; i<num_nodes; i++ )); do
	if [ "${failed_nodes[${i}]}" != "" ]; then
	    sshcmdfile="${nodes[${i}]}/sshcmdfile-$output"
	    (echo "[ \"${vverbose}\" = \"true\" ] && echo -n \"\$(hostname): $cmd_p: \" 1>&2
	    [ -z \"\$TMPDIR\" ] && TMPDIR=/tmp
	    ($sshpath; $cmd) && echo 1 > \${TMPDIR}/done$$
	    if [ -s \"\${TMPDIR}/done$$\" ]; then
                if [ \"${vverbose}\" = \"true\" ]; then
                    echo \"success\" 1>&2
                elif [ \"${verbose}\" = \"true\" ]; then
                    echo -n \".\" 1>&2
                fi
            else
                if [ \"${vverbose}\" = \"true\" ]; then
                    echo \"failed\" 1>&2
                elif [ \"${verbose}\" = \"true\" ]; then
                    echo -n \"?\" 1>&2
                fi
            fi
            rm -f \${TMPDIR}/done$$" \
	    | ssh ${sshopt} "${nodes[${i}]}" ${sshshellg} > ${PWD}/${nodes[${i}]}/$2) 10>${watchdog_file} &
	fi
    done
    wait
    trap 0 1 2 15
}

test1_ping_nodes()
{
    # ping the hosts
    echo -n "Test 1. Pinging each node... "

    if [ "${vverbose}" = "true" ]; then
        echo
    fi

    declare -a failed_nodes
    declare -i num_failed=0
    declare -i num_pings=5

    for (( i=0; i<num_nodes; i++ )); do
        if [ "${good_nodes[${i}]}" != "" ]; then
            failed_nodes[${i}]=${good_nodes[${i}]}
            (( num_failed++ ))
        fi
    done

    for (( j=0; j<${num_pings}; j++ )); do
        for (( i=0; i<num_nodes; i++ )); do
            if [ "${failed_nodes[${i}]}" != "" ]; then
                if [ "${vverbose}" = "true" ]; then
                    if [ ${j} -gt 0 ]; then
                        echo -ne "\tRetrying ${nodes[${i}]}..."
                    else
                        echo -ne "\tPinging ${nodes[${i}]}..."
                    fi
                fi
                ping -q -c 1 -w 1 "${nodes[${i}]}" 2>&1 >/dev/null
                if [ $? -eq 0 ]; then
                    failed_nodes[${i}]=
                    (( num_failed-- ))
                    if [ "${vverbose}" = "true" ]; then
                        echo "success"
                    elif [ "${verbose}" = "true" ]; then
                        echo -n "."
                    fi
                else
                    if [ "${vverbose}" = "true" ]; then
                        echo "failed"
                    elif [ "${verbose}" = "true" ]; then
                        echo -n "?"
                    fi
                fi
            fi
        done
    done

    if [ "${verbose}" = "true" -a "${vverbose}" = "false" ]; then
        echo -n " "
    fi
    if [ ${num_failed} -gt 0 ]; then
        echo "FAILED"
        echo
        if [ ${num_failed} -eq 1 ]; then
            echo "The following ${num_failed} node could not be pinged after ${num_pings} tries:"
        else
            echo "The following ${num_failed} nodes could not be pinged after ${num_pings} tries:"
        fi
        for (( i=0; i<num_nodes; i++ )); do
            if [ "${failed_nodes[${i}]}" != "" ]; then
                echo -e "\t${nodes[${i}]}"
            fi
        done
        failure
        for (( i=0; i<num_nodes; i++ )); do
            if [ "${failed_nodes[${i}]}" != "" ]; then
                good_nodes[${i}]=
            fi
        done
    else
        echo "OK"
    fi
    echo
}

test2_ssh_nodes()
{
    # ssh to the hosts
    echo -n "Test 2. Attempting to ssh to each node... "

    if [ "${vverbose}" = "true" ]; then
        echo
    fi

    declare -a failed_nodes
    declare -i num_failed=0

    for (( i=0; i<num_nodes; i++ )); do
        if [ "${good_nodes[${i}]}" != "" ]; then
            failed_nodes[${i}]=${good_nodes[${i}]}
            (( num_failed++ ))
        fi
    done

    for (( i=0; i<num_nodes; i++ )); do
        if [ "${failed_nodes[${i}]}" != "" ]; then
            if [ "${vverbose}" = "true" ]; then
                echo -ne "\tssh'ing to ${nodes[${i}]}..."
            fi
            ssh ${sshopt} "${nodes[${i}]}" true
            if [ $? -eq 0 ]; then
                failed_nodes[${i}]=
                (( num_failed-- ))
                if [ "${vverbose}" = "true" ]; then
                    echo "success"
                elif [ "${verbose}" = "true" ]; then
                    echo -n "."
                fi
            else
                if [ "${vverbose}" = "true" ]; then
                    echo "failed"
                elif [ "${verbose}" = "true" ]; then
                    echo -n "?"
                fi
            fi
        else
            if [ "${vverbose}" = "true" ]; then
                echo -e "\tSkipping node ${nodes[${i}]} due to earlier failures..."
            elif [ "${verbose}" = "true" ]; then
                echo -n "x"
            fi
        fi
    done

    if [ "${verbose}" = "true" -a "${vverbose}" = "false" ]; then
        echo -n " "
    fi
    if [ ${num_failed} -gt 0 ]; then
        echo "FAILED"
        echo
        if [ ${num_failed} -eq 1 ]; then
            echo "The following ${num_failed} node could not be ssh'd to:"
        else
            echo "The following ${num_failed} nodes could not be ssh'd to:"
        fi
        for (( i=0; i<num_nodes; i++ )); do
            if [ "${failed_nodes[${i}]}" != "" ]; then
                echo -e "\t${nodes[${i}]}"
            fi
        done
        failure
        for (( i=0; i<num_nodes; i++ )); do
            if [ "${failed_nodes[${i}]}" != "" ]; then
                good_nodes[${i}]=
            fi
        done
    else
        echo "OK"
    fi
    echo
}

chkmodparam()
{
    parm=$1
    if [ "${vverbose}" = "true" ]; then
        echo
        echo -e "\tChecking for consistent infinipath ${parm} module parameters..."
    fi

    declare -a modparms
    declare -a modparm_cnts
    declare -a modparm_by_nodenum
    declare -i num_modparms=0
    for (( i=0; i<num_nodes; i++ )); do
        unset found
        if [ "${good_nodes[${i}]}" != "" ]; then
            modparm=`cat "${nodes[${i}]}/${parm}"`
            modparm_by_nodenum[${i}]="${modparm}"
            for (( j=0; j<num_modparms; j++ )); do
                if [ "${modparm}" = "${modparms[${j}]}" ]; then
                    (( modparm_cnts[${j}]++ ))
                    found=true
                    break
                fi
            done
            if [ ! ${found} ]; then
                modparms[${num_modparms}]=${modparm}
                modparm_cnts[${num_modparms}]=1
                (( num_modparms++ ))
            fi
        fi
    done

    if [ ${num_modparms} -gt 1 ]; then
        echo
        echo -e "\t!!!WARNING!!! Different infinipath ${parm} parameters on nodes."
        echo
        echo -e "\t\tThese ${num_modparms} different infinipath ${parm} settings were found:"
        for (( j=0; j<${num_modparms}; j++ )); do
            echo -e "\t\t\t${modparms[${j}]} used\t${modparm_cnts[${j}]} times"
        done
        echo
        if [ ${verbose} = "true" ]; then
            for (( j=0; j<${num_modparms}; j++ )); do
                echo -e "\t\tUsing ${modparms[${j}]} are:"
                for (( i=0; i<num_nodes; i++ )); do
                    if [ \
                        "${good_nodes[${i}]}" != "" \
                        -a "${modparms[${j}]}" = "${modparm_by_nodenum[${i}]}" \
                    ]; then
                        echo -e "\t\t\t${nodes[${i}]}"
                    fi
                done
                echo
            done
        fi
        echo -e "\t\tHaving different infinipath ${parm} settings on nodes may lead"
        echo -e "\t\tto asymmetric performance and/or InfiniPath utilization"
        echo -e "\t\twhich could result in increased latency and poor scaling."
    elif [ ${verbose} = "true" ]; then
        echo -e "\t\tPASSED.  All nodes using ${parm}=${modparms[0]}."
    fi
}

test3_sysconfig()
{
    unset test_failed
    parms_checked='debug cfg{ports,ctxts}'
    
    # ssh to the hosts
    echo -n "Test 3. Retrieving system configuration information... "

    if [ "${vverbose}" = "true" ]; then
        echo
    fi

    declare -a failed_nodes
    declare -i num_failed=0

    for (( i=0; i<num_nodes; i++ )); do
        if [ "${good_nodes[${i}]}" != "" ]; then
            failed_nodes[${i}]=${good_nodes[${i}]}
            (( num_failed++ ))
        fi
    done

    pssh "ulimit -l" ulimit-l
    pssh "uname -r" uname-r
    pssh "uname -m" uname-m
    pssh "cat /proc/cpuinfo" cpuinfo
    pssh "cat /proc/meminfo" meminfo
    pssh "cat /proc/devices" devices
    pssh "cat /proc/modules" modules
    pssh "test -e /proc/mtrr && cat /proc/mtrr || echo 0" mtrr
    pssh "cat /proc/interrupts" interrupts
    pssh "chkconfig --list" chkconfig
    pssh "cat /proc/bus/pci/devices" pci-devices
    pssh "sysctl -a 2>/dev/null" sysctl
    for p in $parms_checked; do
	pssh "if [ -d /sys/module ]; then cat /sys/module/ib_{ipath,qib}/{parameters,}/{infinipath_,}$p ; else echo no /sys/module support; fi 2>/dev/null" $p
       if [ "$p" != "0" ]; then
          test_failed=true
       fi
    done
    pssh "test -f /etc/redhat-release && cat /etc/redhat-release ; \
	  test -f /etc/SuSE-release && cat /etc/SuSE-release" distro-release
    for (( i=0; i<num_nodes; i++ )); do
        if [ "${failed_nodes[${i}]}" != "" ]; then
            unset failed
	    
	    if ! [ -s "${nodes[${i}]}/ulimit-l" ] ; then
		failed="ulimit -l; $failed"
	    fi
	    if ! [ -s "${nodes[${i}]}/uname-r" ] ; then
		failed="uname -r; $failed"
	    fi
	    if ! [ -s "${nodes[${i}]}/uname-m" ] ; then
		failed="uname -m; $failed"
	    fi
	    if ! [ -s "${nodes[${i}]}/cpuinfo" ] ; then
		failed="cat /proc/cpuinfo; $failed"
	    fi
	    if ! [ -s "${nodes[${i}]}/meminfo" ] ; then
		failed="cat /proc/meminfo; $failed"
	    fi
	    if ! [ -s "${nodes[${i}]}/devices" ] ; then
		failed="cat /proc/devices; $failed"
	    fi
	    if ! [ -s "${nodes[${i}]}/modules" ] ; then
		failed="cat /proc/modules; $failed"
	    fi
	    if ! [ -s "${nodes[${i}]}/mtrr" ] ; then
		failed="cat /proc/mtrr; $failed"
	    fi
	    if ! [ -s "${nodes[${i}]}/interrupts" ] ; then
		failed="cat /proc/interrupts; $failed"
	    fi
	    if ! [ -s "${nodes[${i}]}/chkconfig" ] ; then
		failed="chkconfig --list; $failed"
	    fi
	    if ! [ -s "${nodes[${i}]}/pci-devices" ] ; then
		failed="cat /proc/bus/pci/devices; $failed"
	    fi
	    if ! [ -s "${nodes[${i}]}/sysctl" ] ; then
		failed="sysctl -a; $failed"
	    fi
            
            valid_param_list=""
	    for p in $parms_checked; do
		if ! [ -s "${nodes[${i}]}/$p" ] ; then
                   #don't fail if module parameter is not defined.
                   #as this causes good_nodes to be marked as empty and all
                   #other tests suffers
                   #report failure here itself 
                   param_failed="cat /sys/module/ib_{ipath,qib}/{parameters,}/{infinipath_,}$p $param_failed" 2>/dev/null
                   if [ "${param_failed}" ]; then
                      echo ""
                      echo -e "\t\tFAILED. Module paramter \"$p\" not found"
		    fi
		else
                   #This ensures keep only available module parameters
                   valid_param_list="$valid_param_list $p"
		fi
	    done
            parms_checked=$valid_param_list
	
	    if ! [ -s "${nodes[${i}]}/distro-release" ] ; then
		failed="cat /etc/{redhat,SuSE}-release; $failed" 2>/dev/null
	    fi
	    
            if [ "${failed}" ]; then
                if [ "${vverbose}" = "true" ]; then
                    echo "failed in ${failed}"
                elif [ "${verbose}" = "true" ]; then
                    echo -n "?"
                fi
            else
                failed_nodes[${i}]=
                (( num_failed-- ))
                if [ "${vverbose}" = "true" ]; then
                    echo "success"
                elif [ "${verbose}" = "true" ]; then
                    echo -n "."
                fi
            fi
        else
            if [ "${vverbose}" = "true" ]; then
                echo -e "\tSkipping node ${nodes[${i}]} due to earlier failures..."
            elif [ "${verbose}" = "true" ]; then
                echo -n "x"
            fi
        fi
    done

    if [ "${verbose}" = "true" -a "${vverbose}" = "false" ]; then
        echo -n " "
    fi
    if [ ${num_failed} -gt 0 ]; then
        echo "FAILED"
        echo
        if [ ${num_failed} -eq 1 ]; then
            echo "Unable to get system info for ${num_failed} node:"
        else
            echo "Unable to get system info for ${num_failed} nodes:"
        fi
        for (( i=0; i<num_nodes; i++ )); do
            if [ "${failed_nodes[${i}]}" != "" ]; then
                echo -e "\t${nodes[${i}]}"
            fi
        done
        failure
        for (( i=0; i<num_nodes; i++ )); do
            if [ "${failed_nodes[${i}]}" != "" ]; then
                good_nodes[${i}]=
            fi
        done
    else
        echo ""
    fi

    echo -e "\tAnalyzing results..."

    # check for kernel at least 2.6.11 (2.6.9 for RHEL 4)

    if [ "${vverbose}" = "true" ]; then
        echo
        echo -e "\tChecking for unsupported kernel releases..."
    fi

    declare -a kernrels
    declare -a kernrel_cnts
    declare -a node_kernrel
    declare -a kernrel_majors
    declare -a kernrel_minors
    declare -a kernrel_subminors
    declare -a node_distro
    declare -i num_kernrels=0
    unset foundbad
    for (( i=0; i<num_nodes; i++ )); do
        unset found
        if [ "${good_nodes[${i}]}" != "" ]; then
            if [ -f "${nodes[${i}]}/distro-release" ] ; then
                if grep -q "Red Hat Enterprise Linux .* release 4" "${nodes[${i}]}/distro-release"
                then
                    node_distro[${i}]=rhel4
                elif grep -q "CentOS release 4" "${nodes[${i}]}/distro-release" ; then
                    node_distro[${i}]=rocks4
                fi
            fi
            kernrel=`cat "${nodes[${i}]}/uname-r"`
            node_kernrel[${i}]=${kernrel}
            for (( j=0; j<num_kernrels; j++ )); do
                if [ "${kernrel}" = "${kernrels[${j}]}" ]; then
                    (( kernrel_cnts[${j}]++ ))
                    found=true
                    break
                fi
            done
            if [ ${j} -eq ${num_kernrels} ]; then
                kernrel_cnts[${j}]=1
                kernrels[${j}]=${kernrel}
                # lop off everything after the first '.' to get major num
                kernrel_majors[${j}]=${kernrel%%.*}
                # lop off leading 'x.' to get y.z-*
                # then lop off trailing '.z-*A to get y'
                scratch=${kernrel#*.}
                kernrel_minors[${j}]=${scratch%%.*}
                # lop off leading 'x.y.' to get z-*
                # then lop off trailing '[-.]*' to get z
                scratch=${kernrel#*.*.}
                kernrel_subminors[${j}]=${scratch%%[-.]*}
                (( num_kernrels++ ))
            fi
            case "${node_distro[${i}]}" in
                rhel4|rocks4)
                    if cmp_kernrels 2 6 9 \
                        ${kernrel_majors[${j}]} ${kernrel_minors[${j}]} ${kernrel_subminors[${j}]}
                    then
                        if [ ! ${foundbad} ]; then
                            echo
                            echo -e "\t!!!WARNING!!! Found unsupported kernel releases:"
                            foundbad=true
                        fi
                        echo -e "\t\t${kernrels[${j}]} on ${nodes[${i}]}"
                    fi
                    ;;
                *)
                    if cmp_kernrels 2 6 11 \
                        ${kernrel_majors[${j}]} ${kernrel_minors[${j}]} ${kernrel_subminors[${j}]}
                    then
                        if [ ! ${foundbad} ]; then
                            echo
                            echo -e "\t!!!WARNING!!! Found unsupported kernel releases:"
                            foundbad=true
                        fi
                        echo -e "\t\t${kernrels[${j}]} on ${nodes[${i}]}"
                    fi
                    ;;
            esac
        fi
    done

    if [ ${foundbad} ]; then
        echo -e "\t\tCurrently, only 2.6.17 and later kernels (2.6.9 for RHEL 4"
        echo -e "\t\tand ROCKS 4 are supported by Intel.  Using older kernel"
	echo -e "\t\treleases may lead to undefined behavior."
    elif [ ${verbose} = "true" ]; then
        echo -e "\t\tPASSED.  All nodes are running supported kernel releases."
    fi

    # check for consistent kernel releases across nodes

    if [ "${vverbose}" = "true" ]; then
        echo
        echo -e "\tChecking for consistent kernel releases across nodes..."
    fi

    if [ ${num_kernrels} -gt 1 ]; then
        echo
        echo -e "\t!!!WARNING!!! Multiple kernel releases found."
        echo
        echo -e "\t\tThese ${num_kernrels} different releases were found:"
        for (( j=0; j<${num_kernrels}; j++ )); do
            echo -e "\t\t\t${kernrels[${j}]}"
        done
        echo
        if [ ${verbose} = "true" ]; then
            for (( j=0; j<${num_kernrels}; j++ )); do
                echo -e "\t\tUsing release ${kernrels[${j}]} are:"
                for (( i=0; i<num_nodes; i++ )); do
                    if [ \
                        "${good_nodes[${i}]}" != "" \
                        -a "${kernrels[${j}]}" = "${node_kernrel[${i}]}" \
                    ]; then
                        echo -e "\t\t\t${nodes[${i}]}"
                    fi
                done
                echo
            done
        fi
        echo -e "\t\tHaving different kernel releases on different nodes may"
        echo -e "\t\tlead to asymmetric performance which could result in"
        echo -e "\t\tincreased latency and poor scaling."
    elif [ ${verbose} = "true" ]; then
        echo -e "\t\tPASSED.  All nodes are running the same kernel release."
    fi

    # check for similar memory

    if [ "${vverbose}" = "true" ]; then
        echo
        echo -e "\tChecking for consistent memory installed in nodes..."
    fi

    declare -a mems
    declare -a mem_cnts
    declare -a node_mem
    declare -i mem_cnt=0
    declare -i num_mems=0
    declare -i max_max
    declare -i min_mem
    declare -i sum_mem=0
    declare -i delta_mem
    declare -i avg_mem
    declare -i mem_spread
    for (( i=0; i<num_nodes; i++ )); do
        unset found

        if [ "${good_nodes[${i}]}" != "" ]; then
            mem=`cat "${nodes[${i}]}/meminfo" | gawk '/^MemTotal/{print $2}'`
            node_mem[${i}]=${mem}
            if [ ! ${min_mem} ]; then min_mem=${mem}; fi
            if [ ! ${max_mem} ]; then max_mem=${mem}; fi
            if [ ${mem} -lt ${min_mem} ]; then min_mem=${mem}; fi
            if [ ${mem} -gt ${max_mem} ]; then max_mem=${mem}; fi
            (( sum_mem += mem ))
            for (( j=0; j<num_mems; j++ )); do
                if [ "${mem}" = "${mems[${j}]}" ]; then
                    (( mem_cnts[${j}]++ ))
                    found=true
                    break
                fi
            done
            if [ ! ${found} ]; then
                mems[${num_mems}]=${mem}
                mem_cnts[${num_mems}]=1
                (( num_mems++ ))
            fi
            (( mem_cnt++ ))
        fi
    done
    (( delta_mem = max_mem - min_mem ))
    (( avg_mem = sum_mem / mem_cnt ))
    (( mem_spread = (100 * delta_mem) / avg_mem ))
    if [ "${vverbose}" = "true" ]; then
        echo
        echo -e "\t\tMinimum memory is ${min_mem} kB"
        echo -e "\t\tMaximum memory is ${max_mem} kB"
        echo -e "\t\tDelta between min and max is ${delta_mem} kB"
        echo -e "\t\tAverage memory is ${avg_mem} kB"
        echo -e "\t\tSpread between systems is ${mem_spread}%"
    fi
    if [ ${mem_spread} -gt 2 ]; then
        echo
        echo -e "\t!!!WARNING!!! Systems have different amounts of memory."
        if [ "${verbose}" = "true" ]; then
            echo
            echo -e "\t\tThe following systems deviate more than 2% from the"
            echo -e "\t\taverage memory of ${avg_mem} kB:"
            for (( i=0; i<num_nodes; i++ )); do
                if [ "${good_nodes[${i}]}" != "" ]; then
                    (( spread = (100 * (node_mem[i] - avg_mem))/avg_mem ))
                    if [ ${spread} -gt 2 -o ${spread} -lt -2 ]; then
                        echo -e "\t\t\t${nodes[${i}]}\t${node_mem[${i}]} kB\t${spread}%"
                    fi
                fi
            done
        fi
        echo
        echo -e "\t\tThe spread between systems is ${mem_spread}% which may be enough"
        echo -e "\t\tto lead to asymmetric performance which could result in"
        echo -e "\t\tincreased latency and poor scaling."
    elif [ ${verbose} = "true" ]; then
        if [ "${vverbose}" = "true" ]; then
            echo
        fi
        echo -e "\t\tPASSED.  All nodes' memories are within ${mem_spread}% of each other."
    fi

    # do some setup for following tests

    declare -a cpucount_by_nodenum
    declare -a cpunum_by_nodenum
    declare -a node_by_cpunum
    declare -a cpufamily_by_cpunum
    declare -a cpumodel_by_cpunum
    declare -a cpuname_by_cpunum
    declare -a cpuspeed_by_cpunum
    declare -i nodenum=0
    declare -i cpunum=0

    for (( nodenum=0; nodenum<num_nodes; nodenum++ )); do
        if [ "${good_nodes[${nodenum}]}" != "" ]; then
            cpucount=`grep "^processor" "${nodes[${nodenum}]}/cpuinfo" | wc -l`
            cpucount_by_nodenum[${nodenum}]=${cpucount}
            cpunum_by_nodenum[${nodenum}]=${cpunum}
            for (( i=1; i<=cpucount; i++ )); do
                node_by_cpunum[${cpunum}]="${nodes[${nodenum}]}"
                cpufamily_by_cpunum[${cpunum}]=`\
                    gawk '/^cpu family\t*:/{print $4}' "${nodes[${nodenum}]}/cpuinfo" | \
                    tail -n ${i} | head -n 1`
                cpumodel_by_cpunum[${cpunum}]=`\
                    gawk '/^model\t*:/{print $3}' "${nodes[${nodenum}]}/cpuinfo" | \
                    tail -n ${i} | head -n 1`
                cpuname_by_cpunum[${cpunum}]=`\
                    gawk '/^model name\t*:/{$1="";$2="";$3="";print $0}' "${nodes[${nodenum}]}/cpuinfo" | \
                    tail -n ${i} | head -n 1 | sed -e 's/^ *//'`
                cpuspeed_by_cpunum[${cpunum}]=`\
                    gawk '/^cpu MHz\t*:/{print $4}' "${nodes[${nodenum}]}/cpuinfo" | \
                    tail -n ${i} | head -n 1`
                (( cpunum++ ))
            done
        fi
    done

    # check for same processor count

    if [ "${vverbose}" = "true" ]; then
        echo
        echo -e "\tChecking for consistent number of processors..."
    fi

    declare -a cpucounts
    declare -a cpucount_cnts
    declare -i num_cpucounts=0
    for (( i=0; i<num_nodes; i++ )); do
        unset found
        if [ "${good_nodes[${i}]}" != "" ]; then
            cpucount=${cpucount_by_nodenum[${i}]}
            for (( j=0; j<num_cpucounts; j++ )); do
                if [ "${cpucount}" = "${cpucounts[${j}]}" ]; then
                    (( cpucount_cnts[${j}]++ ))
                    found=true
                    break
                fi
            done
            if [ ! ${found} ]; then
                cpucounts[${num_cpucounts}]=${cpucount}
                cpucount_cnts[${num_cpucounts}]=1
                (( num_cpucounts++ ))
            fi
        fi
    done

    if [ ${num_cpucounts} -gt 1 ]; then
        echo
        echo -e "\t!!!WARNING!!! Different number of processors in hosts."
        echo
        echo -e "\t\tThese ${num_cpucounts} different processor counts were found:"
        for (( j=0; j<${num_cpucounts}; j++ )); do
            echo -e "\t\t\t${cpucounts[${j}]} processors\t${cpucount_cnts[${j}]} times"
        done
        echo
        if [ ${verbose} = "true" ]; then
            for (( j=0; j<${num_cpucounts}; j++ )); do
                echo -e "\t\tUsing ${cpucounts[${j}]} processors are:"
                for (( i=0; i<num_nodes; i++ )); do
                    if [ \
                        "${good_nodes[${i}]}" != "" \
                        -a "${cpucounts[${j}]}" = "${cpucount_by_nodenum[${i}]}" \
                    ]; then
                        echo -e "\t\t\t${nodes[${i}]}"
                    fi
                done
                echo
            done
        fi
        echo -e "\t\tHaving different numbers of processors in nodes may lead"
        echo -e "\t\tto asymmetric performance and/or InfiniPath utilization"
        echo -e "\t\twhich could result in increased latency and poor scaling."
    elif [ ${verbose} = "true" ]; then
        echo -e "\t\tPASSED.  All nodes have ${cpucounts[0]} processors."
    fi

    # check for same processor cpu family

    if [ "${vverbose}" = "true" ]; then
        echo
        echo -e "\tChecking for consistent processor family..."
    fi

    declare -a cpufamilies
    declare -a cpufamily_cnts
    declare -i num_cpufamilies=0
    for (( i=0; i<cpunum; i++ )); do
        unset found
        node=${node_by_cpunum[${i}]}
        cpufamily=${cpufamily_by_cpunum[${i}]}
        for (( j=0; j<num_cpufamilies; j++ )); do
            if [ "${cpufamily}" = "${cpufamilies[${j}]}" ]; then
                (( cpufamily_cnts[${j}]++ ))
                found=true
                break
            fi
        done
        if [ ! ${found} ]; then
            cpufamilies[${num_cpufamilies}]=${cpufamily}
            cpufamily_cnts[${num_cpufamilies}]=1
            (( num_cpufamilies++ ))
        fi
    done

    if [ ${num_cpufamilies} -gt 1 ]; then
        echo
        echo -e "\t!!!WARNING!!! Different CPU families used in nodes."
        echo
        echo -e "\t\tThese ${num_cpufamilies} different processor families were found:"
        for (( j=0; j<${num_cpufamilies}; j++ )); do
            echo -e "\t\t\tCPU family ${cpufamilies[${j}]}\tin ${cpufamily_cnts[${j}]} nodes"
        done
        echo
        if [ ${verbose} = "true" ]; then
            for (( j=0; j<${num_cpufamilies}; j++ )); do
                echo -e "\t\tUsing CPU family ${cpufamilies[${j}]} are:"
                for (( i=0; i<num_nodes; i++ )); do
                    if [ \
                        "${good_nodes[${i}]}" != "" \
                        -a "${cpufamilies[${j}]}" = "${cpufamily_by_cpunum[${i}]}" \
                    ]; then
                        echo -e "\t\t\t${nodes[${i}]}"
                    fi
                done
                echo
            done
        fi
        echo -e "\t\tHaving different CPU families in nodes may lead to"
        echo -e "\t\tasymmetric performance twhich could result in increased"
        echo -e "\t\tlatency and poor scaling."
    elif [ ${verbose} = "true" ]; then
        echo -e "\t\tPASSED.  All nodes have CPU family ${cpufamilies[0]}."
    fi

    # check for same processor model name

    # check for same processor stepping

    # check for similar processor speeds

    # check for same sysconfig settings

    # check for InfiniPath device

    if [ "${vverbose}" = "true" ]; then
        echo
        echo -e "\tChecking for InfiniPath device..."
    fi

    unset notfound
    for (( i=0; i<num_nodes; i++ )); do
        if [ "${good_nodes[${i}]}" != "" ]; then
            devline_pre11=`grep "infinipath" "${nodes[${i}]}/pci-devices"`
            devline=`egrep 'ib_(ipath|qib)' "${nodes[${i}]}/pci-devices"`
            if [ ! "${devline}" -a ! "${devline_pre11}" ]; then
                if [ ! ${notfound} ]; then
                    echo
                    test_failed=true
                    notfound=true
                fi
                echo -e "\t!!!ERROR!!! ${nodes[${i}]} does not have an InfiniPath device"
            fi
        fi
    done
    if [ ${notfound} ]; then
        echo
        echo -e "\t\tThis could be due to one of the following problems:"
        echo -e "\t\t\tThe system does not have an InfiniPath device installed"
        echo -e "\t\t\tThe system's BIOS failed to recognize the InfiniPath device"
        echo -e "\t\t\tThe InfiniPath device or the riser may have become unseated"
        echo
        echo -e "\t\tIf there is an InfiniPath device installed in the system,"
        echo -e "\t\tit is recommended to try:"
        echo -e "\t\t\trebooting the system"
        echo -e "\t\t\treseating the InfiniPath device and riser"
        echo -e "\t\t\tconsult the release notes for supported BIOSes"
        echo -e "\t\t\tcontact Intel support"
    elif [ ${verbose} = "true" ]; then
        echo -e "\t\tPASSED.  All devices found."
    fi

    # check for InfiniPath device driver

    if [ "${vverbose}" = "true" ]; then
        echo
        echo -e "\tChecking for InfiniPath device driver..."
    fi

    unset notfound
    for (( i=0; i<num_nodes; i++ )); do
        if [ "${good_nodes[${i}]}" != "" ]; then
            devid_pre11=`cat "${nodes[${i}]}/devices" | gawk '/ infinipath$/{print $1}'`
            devid=`cat "${nodes[${i}]}/devices" | gawk '/ ib_ipath$/{print $1} / ib_qib$/{print $1}'`
            if [ ! "${devid}" -a ! "${devid_pre11}" ]; then
                if [ ! ${notfound} ]; then
                    echo
                    test_failed=true
                    notfound=true
                fi
                echo -e "\t!!!ERROR!!! ${nodes[${i}]} does not have the ib_ipath nor ib_qib module loaded"
            fi
            modline_pre11=`cat "${nodes[${i}]}/modules" | grep '^infinipath ' `
            modline=`cat "${nodes[${i}]}/modules" | egrep '^ib_(ipath|qib) ' `
            if [ -n "${modline_pre11}" -a -n "${modline}" ] ; then
                echo -e "\t!!!WARNING!!! ${nodes[${i}]} has both new and old modules"
            fi
        fi
    done
    if [ ${notfound} ]; then
        echo
        echo -e "\t\tThis could be due to either of the following problems:"
        echo -e "\t\t\tThe InfiniPath driver is not loaded"
        echo -e "\t\t\tThe InfiniPath RPMs are not installed"
    elif [ ${verbose} = "true" ]; then
        echo -e "\t\tPASSED.  All device drivers found."
    fi

    # check for powersaved or cpuspeed being enabled in chkconfig
    # We don't bother to check for them actually running, since MHz
    # check will usually catch that

    if [ "${vverbose}" = "true" ]; then
        echo
        echo -e "\tChecking for power save enabled in chkconfig..."
    fi

    declare -a powersaves
    declare -i num_powersaves=0
    for (( i=0; i<num_nodes; i++ )); do
        if [ "${good_nodes[${i}]}" != "" ]; then
            powersave="`egrep '(powersaved|cpuspeed).*on' ${nodes[${i}]}/chkconfig`"
	    if [ "${powersave}" ]; then
		powersaves[${i}]="${powersave}"
		(( num_powersaves++ ))
            fi
        fi
    done
    if [ ${num_powersaves} -gt 0 ]; then
        echo
        echo -e "\t!!!WARNING!!! powersave (reduced cpu speed) set on ${num_powersaves} nodes."
        echo
        if [ ${verbose} = "true" ]; then
	    for (( i=0; i<num_nodes; i++ )); do
		if [ "${good_nodes[${i}]}" != "" \
		    -a "${powersaves[${i}]}" ] ; then
		    echo -e "\t\t\t${nodes[${i}]}: ${powersaves[${i}]}"
		fi
	    done
        fi
        echo -e "\t\tHaving powersave enabled can cause performance problems"
        echo -e "\t\twhich could result in increased latency and poor scaling."
    elif [ ${verbose} = "true" ]; then
        echo -e "\t\tPASSED.  All nodes have powersave disabled"
    fi

    # check for iptables being enabled, since if configured on and
    # at default settings, it may prevent node programs from connecting
    # back to mpirun.  Can't check actual iptables config without root
    if [ "${vverbose}" = "true" ]; then
        echo
        echo -e "\tChecking for iptables enabled in chkconfig..."
    fi

    declare -a iptables
    declare -i num_iptables=0
    for (( i=0; i<num_nodes; i++ )); do
        if [ "${good_nodes[${i}]}" != "" ]; then
            iptables="`egrep 'iptables.*on' ${nodes[${i}]}/chkconfig`"
	    if [ "${iptables}" ]; then
		iptables[${i}]="${iptables}"
		(( num_iptables++ ))
            fi
        fi
    done
    if [ ${num_iptables} -gt 0 ]; then
        echo
	echo -e "\t!!!WARNING!!! iptables (firewall) enabled on ${num_iptables} nodes."
        echo
        if [ ${verbose} = "true" ]; then
	    for (( i=0; i<num_nodes; i++ )); do
		if [ "${good_nodes[${i}]}" != "" \
		    -a "${iptables[${i}]}" ] ; then
		    echo -e "\t\t\t${nodes[${i}]}: ${iptables[${i}]}"
		fi
	    done
        fi
        echo -e "\t\tHaving iptables enabled may disable MPI network connections"
    elif [ ${verbose} = "true" ]; then
        echo -e "\t\tPASSED.  All nodes have iptables disabled"
    fi

    # check for consistent infinipath module parameters that affect 
    # performance or functionality.
    for p in $parms_checked; do
	    chkmodparam $p
    done

    # check for different ulimits, and ulimit being "too small"
    if [ "${vverbose}" = "true" ]; then
        echo
        echo -e "\tChecking for lockable memory limit..."
    fi

    declare -a limitl
    declare -i num_limitl=0 lim badlim=0 minlock=4096 anysame=0
    for (( i=0; i<num_nodes; i++ )); do
        if [ "${good_nodes[${i}]}" != "" ]; then
            thislim=`cat "${nodes[${i}]}/ulimit-l"`
            lim=${thislim}
            limitl[${i}]=${thislim}
	    if [ ${thislim} != "unlimited" -a ${lim} -lt ${minlock} ]; then
		    (( badlim++ ))
	    fi
	    anysame=0
            for (( j=0; j<${i}; j++ )); do
                if [ "${thislim}" = "${limitl[${j}]}" ]; then
                    (( anysame++ ))
                    break
                fi
            done
	    if [ ${anysame} -eq 0 ]; then
		    (( num_limitl++ ))
	    fi
        fi
    done
    if [ ${badlim} -gt 0 ]; then
        echo
        echo -e "\t!!!ERROR!!! Lockable memory less than ${minlock}KB on ${badlim} nodes."
        test_failed=true
        if [ ${verbose} = "true" ]; then
	    for (( i=0; i<num_nodes; i++ )); do
		if [ "${good_nodes[${i}]}" != "" \
		    -a "${limitl[${i}]}" -lt ${minlock} ] ; then
		    echo -e "\t\t\t${nodes[${i}]}: ${limitl[${i}]}KB"
		fi
	    done
	fi
    fi
    if [ ${num_limitl} -gt 1 ]; then
        echo
        echo -e "\t!!!WARNING!!! ${num_limitl} different lockable memory values."
        if [ ${verbose} = "true" ]; then
	    for (( i=0; i<num_nodes; i++ )); do
		if [ ${limitl[${i}]} != unlimited ]; then kb=KB; else kb=; fi
		if [ "${good_nodes[${i}]}" != "" ] ; then
		    echo -e "\t\t\t${nodes[${i}]}: ${limitl[${i}]}${kb}"
		fi
	    done
	fi
    fi
    if [ ${verbose} = "true" -a ${num_limitl} -eq 1 -a ${badlim} -eq 0 ]; then
        echo -e "\t\tPASSED.  All nodes have lockable memory set to ${limitl[0]}KB."
    fi

    echo

    if [ ${test_failed} ]; then
        failure
        echo -e "\tFAILED.  Some tests were unsuccessful."
    else
        echo -e "\tPASSED.  All tests were successful."
        echo
    fi
}

test4_rpms()
{
    unset test_failed
    echo -n "Test 4. Retrieving installed RPMs... "

    if [ "${vverbose}" = "true" ]; then
        echo
    fi

    declare -a failed_nodes
    declare -i num_failed=0

    for (( i=0; i<num_nodes; i++ )); do
        if [ "${good_nodes[${i}]}" != "" ]; then
            failed_nodes[${i}]=${good_nodes[${i}]}
            (( num_failed++ ))
        fi
    done

    pssh "rpm -qa --qf '%{NAME} %{VERSION} %{RELEASE} %{ARCH}\n'" rpms

    for (( i=0; i<num_nodes; i++ )); do
	if [ -s "${nodes[${i}]}/rpms" ]; then
	    failed_nodes[${i}]=
	    (( num_failed-- ))
	fi
    done
    
    if [ "${verbose}" = "true" -a "${vverbose}" = "false" ]; then
        echo -n " "
    fi
    if [ ${num_failed} -gt 0 ]; then
        echo "FAILED"
        echo
        if [ ${num_failed} -eq 1 ]; then
            echo "Unable to list installed RPMs for ${num_failed} node:"
        else
            echo "Unable to list installed RPMs for ${num_failed} nodes:"
        fi
        for (( i=0; i<num_nodes; i++ )); do
            if [ "${failed_nodes[${i}]}" != "" ]; then
                echo -e "\t${nodes[${i}]}"
            fi
        done
        failure
        for (( i=0; i<num_nodes; i++ )); do
            if [ "${failed_nodes[${i}]}" != "" ]; then
                good_nodes[${i}]=
            fi
        done
    else
        echo "OK"
    fi

    echo -e "\tAnalyzing results..."

    # check for consistent install of most critical RPMs...

    if [ "${vverbose}" = "true" ]; then
        echo
        echo -e "\tChecking for consistent critical RPMs across nodes..."
    fi

    gawk '
        BEGIN {
          critrpmnames["infinipath"]=""
          critrpmnames["infinipath-kernel"]=""
          critrpmnames["infinipath-libs"]=""
          critrpmnames["openmpi_gcc_qlc"]=""
          critrpmnames["glibc"]=""
          critrpmnames["libipathverbs"]=""
          critrpmnames["libibverbs"]=""
          critrpmnames["libibmad"]=""
          critrpmnames["libibcommon"]=""
        }
        FNR == 1 {
          match(FILENAME, /^[^/]+/);
          node = substr(FILENAME, RSTART, RLENGTH)
          node_nodes[node] = node
        }
        {
          name = $1
          version = $2
          release = $3
          arch = $4
          rpm = name SUBSEP version SUBSEP release SUBSEP arch
          noderpm_[node,rpm]=""
          rpm_nodecount[rpm]++
        }
        END {
          failed=0
          num__nodes = asort(node_nodes, _nodes)
          i=1
          for ( rpm in rpm_nodecount ) {
            _rpms[i] = rpm
            i++
          }
	  
          num__rpms = asort(_rpms)
          for ( reportnodes=1; reportnodes<num__nodes; reportnodes++ ) {
            headerprinted=0
            for ( rpm=1; rpm<=num__rpms; rpm++ ) {
              nodecount = rpm_nodecount[_rpms[rpm]]
              split(_rpms[rpm], tuple, SUBSEP)
              rpm_name = tuple[1]
              rpm_version = tuple[2]
              rpm_release = tuple[3]
              rpm_arch = tuple[4]
              if ( (nodecount == reportnodes) && ( rpm_name in critrpmnames ) ) {
                failed=1
                rpmname = rpm_name "-" rpm_version "-" rpm_release "." rpm_arch ".rpm"
                if ( ! headerprinted ) {
                  print ""
                  print "\t!!!ERROR!!! The following critical RPMs were found on only", nodecount, "nodes:"
                  print ""
                  headerprinted=1
                }
                print "\t\t" rpmname
                if ( "IPATH_CHECKOUT_VERBOSE" in ENVIRON ) {
                  for ( j=1; j<=num__nodes; j++ ) {
                    if ( (_nodes[j],_rpms[rpm]) in noderpm_ ) {
                      print "\t\t\t" _nodes[j]
                    }
                  }
                  print ""
                }
              }
            }
          }
          exit failed
        }
    ' */rpms
    if [ $? -ne 0 ]; then
        echo
        echo -e "\t!!!WARNING!!!  Nodes have different InfiniPath RPMs installed."
        echo
        echo -e "\t\tIt is important that the infinipath-*, pathscale-*,"
        echo -e "\t\topenmpi_gcc_qlc-* and glibc-* RPMs are the same version across all"
        echo -e "\t\tof the nodes of the cluster (and OpenFabrics rpms as well,"
		echo -e "\t\tif they are in use).  If these RPMs differ then it"
        echo -e "\t\tis possible that the cluster will experience difficult"
        echo -e "\t\tto debug failures and performance variations."
        if [ "${verbose}" = "false" ]; then
            echo
            echo -e "\t\tA more detailed report is available with the -v flag"
        fi
    elif [ ${verbose} = "true" ]; then
        echo -e "\tPASSED.  All nodes have the same critical RPM versions installed."
    fi

    echo

    # check for consistent install of all RPMs...

    if [ "${vverbose}" = "true" ]; then
        echo
        echo -e "\tChecking for consistent RPMs across nodes..."
    fi

    gawk '
        BEGIN {
        }
        FNR == 1 {
          match(FILENAME, /^[^/]+/);
          node = substr(FILENAME, RSTART, RLENGTH)
          node_nodes[node] = node
        }
        {
          name = $1
          version = $2
          release = $3
          arch = $4
          rpm = name SUBSEP version SUBSEP release SUBSEP arch
          noderpm_[node,rpm]=""
          rpm_nodecount[rpm]++
        }
        END {
          failed=0
          num__nodes = asort(node_nodes, _nodes)
          i=1
          for ( rpm in rpm_nodecount ) {
            _rpms[i] = rpm
            i++
          }
          num__rpms = asort(_rpms)
          for ( reportnodes=1; reportnodes<num__nodes; reportnodes++ ) {
            headerprinted=0
            for ( rpm=1; rpm<=num__rpms; rpm++ ) {
              nodecount = rpm_nodecount[_rpms[rpm]]
              if ( nodecount == reportnodes ) {
                failed=1
                split(_rpms[rpm], tuple, SUBSEP)
                rpm_name = tuple[1]
                rpm_version = tuple[2]
                rpm_release = tuple[3]
                rpm_arch = tuple[4]
                rpmname = rpm_name "-" rpm_version "-" rpm_release "." rpm_arch ".rpm"
                if ( "IPATH_CHECKOUT_VVERBOSE" in ENVIRON ) {
                  if ( ! headerprinted ) {
                    print ""
                    print "\t!!!WARNING!!! The following RPMs were found on only", nodecount, "nodes:"
                    print ""
                    headerprinted=1
                  }
                  print "\t\t" rpmname
                  if ( "IPATH_CHECKOUT_VVVERBOSE" in ENVIRON ) {
                    for ( j=1; j<=num__nodes; j++ ) {
                      if ( (_nodes[j],_rpms[rpm]) in noderpm_ ) {
                        print "\t\t\t" _nodes[j]
                      }
                    }
                    print ""
                  }
                }
              }
            }
          }
          exit failed
        }
    ' */rpms
    if [ $? -ne 0 ]; then
        test_failed=true
        echo
        echo -e "\t!!!WARNING!!!  Nodes have different RPMs installed."
        echo
        echo -e "\t\tIt is recommended that all nodes of a cluster"
        echo -e "\t\thave the same RPMs installed and that those RPMs be the"
        echo -e "\t\tsame version and release.  Having different RPMs on the"
        echo -e "\t\tnodes may lead to hard to debug errors and performance"
        echo -e "\t\tvariations that may limit performance and scaling."
        if [ "${vverbose}" = "false" ]; then
            echo
            echo -e "\t\tMore detailed reports are available with the -vv or"
            echo -e "\t\t-vvv flags."
        elif [ "${vvverbose}" = "false" ]; then
            echo
            echo -e "\t\tA more detailed report is available with the -vvv flag."
        fi
    elif [ ${verbose} = "true" ]; then
        echo
        echo -e "\t\tPASSED.  All nodes have the same RPMs installed."
    fi

    echo

    if [ ${test_failed} ]; then
        echo "FAILED"
        echo
        failure
    else
        echo
        echo -e "\tPASSED.  All tests were successful."
        echo
    fi
}

test5_infinipath()
{
    unset test_failed
    echo -n "Test 5. Checking InfiniPath driver version and status... "

    if [ "${vverbose}" = "true" ]; then
        echo
    fi

    declare -a failed_nodes
    declare -i num_failed=0

    for (( i=0; i<num_nodes; i++ )); do
        if [ "${good_nodes[${i}]}" != "" ]; then
            failed_nodes[${i}]=${good_nodes[${i}]}
            (( num_failed++ ))
        fi
    done

    # -follow is needed because SuSE has updates dir as a symlink.
    # check for both new and old names, because if both present, modprobe
    # may load wrong one
    pssh ' find /lib/modules/$(uname -r) -follow -name ipath_core.ko -o -name ib_ipath.ko -o -name ib_qib.ko 2>/dev/null' infinipath-kmodules
    pssh "cat /proc/driver/infinipath/status 2>/dev/null;
		if [ -d /sys/class/infiniband/qib0 ]; then
		 for d in /sys/class/infiniband/qib*; do
		 u=\${d#*qib};
		 for p in \$d/ports/*; do
		  eval read status_str < \$p/linkcontrol/status_str;
		  eval read status < \$p/linkcontrol/status;
		  echo Unit\$u,\${p##*/}: Status: \${status} \${status_str};
		 done;
		done
		else
		cd /sys/bus/pci/drivers/ib_ipath 2>/dev/null \
		  && for unit in 0?; do (
		   eval read status_str < \${unit}/status_str;
		   eval read status < \${unit}/status;
		   echo Status: \${status} \${status_str} ) | sed s/^/Unit\${unit#0},1\\ /;
		  done ; fi" infinipath-status
    pssh "cd /sys/bus/pci/drivers/ib_ipath 2>/dev/null \
	  && for unit in 0?; do
		eval 2>/dev/null read boardver < \${unit}/boardversion;
		if [ \"\${boardver}\" ]; then
			echo Unit\${unit#0}: \${boardver//PCI [0-9]*,}; fi; done;
	  boardver= ;
	  cd /sys/class/infiniband 2>/dev/null && for unit in qib*; do
	    eval 2>/dev/null read boardver < \${unit}/boardversion;
	    if [ \"\${boardver}\" ]; then echo Unit\${unit##qib}: \${boardver}; fi; done;
	    true" infinipath-hwversion
    pssh "cat /proc/driver/infinipath/version /sys/bus/pci/drivers/ib_ipath/version \
    	/sys/class/infiniband/qib0/version 2>/dev/null; exit 0" infinipath-version
    pssh 'stat  -c %t,%T_%a_%U_%n /dev/ipath /dev/ipath[0-9]* 2>/dev/null | tr -s "[:space:]" "\t" ' infinipath-device
    pssh "cd /sys/bus/pci/drivers/ib_ipath 2>/dev/null \
	  && for unit in 0?; do
	    eval 2>/dev/null read localbus < \${unit}/localbus_info;
	    if [ \"\${localbus}\" ]; then echo Unit\${unit#0}: \${localbus}; fi; done;
	  localbus= ;
	  cd /sys/class/infiniband 2>/dev/null && for unit in qib*; do
	    eval 2>/dev/null read localbus < \${unit}/localbus_info;
	    if [ \"\${localbus}\" ]; then echo Unit\${unit##qib}: \${localbus}; fi; done;
          true" infinipath-localbus
    pssh "for d in /sys/class/infiniband/*; do u=\${d//*[a-z]} ;
	    for port in \$d/ports/*; do read speed < \$port/rate; p=\${port##*/} ; 
	    echo \$u,\$p: SPEED=\${speed}; done; done " infinipath-linkstate
    pssh "ipath_pkt_test -B 2>/dev/null" infinipath-mtrr
    for (( i=0; i<num_nodes; i++ )); do
	if [ -s "${nodes[${i}]}/infinipath-status" -a -s "${nodes[${i}]}/infinipath-version" ]
            then
                failed_nodes[${i}]=
                (( num_failed-- ))
	fi
    done

    if [ "${verbose}" = "true" -a "${vverbose}" = "false" ]; then
        echo -n " "
    fi
    if [ ${num_failed} -gt 0 ]; then
        echo "FAILED"
        echo
        if [ ${num_failed} -eq 1 ]; then
            echo "Unable to get InfiniPath status for ${num_failed} node:"
        else
            echo "Unable to get InfiniPath status for ${num_failed} nodes:"
        fi
        for (( i=0; i<num_nodes; i++ )); do
            if [ "${failed_nodes[${i}]}" != "" ]; then
                echo -e "\t${nodes[${i}]}"
            fi
        done
        failure
        for (( i=0; i<num_nodes; i++ )); do
            if [ "${failed_nodes[${i}]}" != "" ]; then
                good_nodes[${i}]=
            fi
        done
    else
        echo "OK"
    fi

    echo -e "\tAnalyzing results..."

    declare thisvers= firstvers= thisdev= firstdev= firstspeed=
    declare -i numvers=1 numrel=1 notup=${num_failed} numdevs=1 numbus=1 numspeed=1 badmtrr=0
    declare -a foundvers foundrels foundbus foundspeed

    # check for stuff here
    for (( i=0; i<num_nodes; i++ )); do
        if [ "${good_nodes[${i}]}" != "" ]; then
	    # don't worry if both normal kernel and our updates there, but
	    # if old (ipath_core) and new (ib_{ipath,qib}) are present, complain
            nkmods=$(sed 's,.*/,,' "${nodes[${i}]}/infinipath-kmodules" | sort -u | wc -l)
	    if [ ! "${nkmods}" ]; then nkmods=0; fi
	    if [ "${nkmods}" -ne 1 ]; then
                echo -e "\tWARNING: ${nodes[${i}]} found ${nkmods} versions of InfiniPath driver"
                if [ "${verbose}" = "true" ]; then
		    pr -t -o 16 ${nodes[${i}]}/infinipath-kmodules
                fi
	    fi
	    if [ -s "${nodes[${i}]}/infinipath-localbus" ]; then
		businfo="$(cat ${nodes[${i}]}/infinipath-localbus)"
		if [ ! "${foundbus}" ]; then
		    foundbus[0]="${businfo}"
		    firstbus="${businfo}"
		fi
		if [ "${vvverbose}" = "true" ]; then
		    echo -e "\t${nodes[${i}]} Local Bus is:"
		    bus="$(echo $businfo)"
		    bmulti="${bus// Unit/\n\t\tUnit}"
		    echo -e "\t\t${bmulti}"
		fi

		if [ "${businfo}" != "${firstbus}" ]; then
		    found_this_bus=0
		    for (( j=0; j<${#foundbus[*]}; j++)); do
			if [ "${businfo}" == "${foundbus[${j}]}" ]; then
			    found_this_bus=1
			fi
		    done
		    if [ $found_this_bus -eq 0 ]; then
			foundbus[${#foundbus[*]}]="${businfo}"
			(( numbus++ ))
		    fi
		    if [ "${verbose}" = "true" ]; then
			echo -e "\t${nodes[${i}]} Local Bus Info is different:"
			bus="$(echo $businfo)"
			bmulti="${bus// Unit/\n\t\tUnit}"
			echo -e "\t\t${bmulti}"
		    fi
		fi
	    fi
	    if [ -s "${nodes[${i}]}/infinipath-linkstate" ]; then
		speedinfo="$(cat ${nodes[${i}]}/infinipath-linkstate | grep SPEED)"
		if [ ! "${foundspeed}" ]; then
		    foundspeed[0]="${speedinfo}"
		    firstspeed="${speedinfo}"
		fi
		if [ "${vvverbose}" = "true" ]; then
		    echo -e "\t${nodes[${i}]} link speed is:"
		    speed="$(echo $speedinfo)"
		    smulti="${speed// Unit/\n\t\tUnit}"
		    echo -e "\t\t${smulti}"
		fi
		if [ "${speedinfo}" != "${firstspeed}" ]; then
		    found_this_speed=0
		    for (( j=0; j<${#foundspeed[*]}; j++ )); do
			if [ "${speedinfo}" == "${foundspeed[${j}]}" ]; then
			    found_this_speed=1
			fi
		    done
		    if [ $found_this_speed -eq 0 ]; then
			foundspeed[${#foundspped[*]}]="${speedinfo}"
			(( numspeed++ ))
		    fi
		    if [ "${verbose}" = "true" ]; then
			echo -e "\t${nodes[${i}]} link speed is different:"
			speed="$(echo $speedinfo)"
			smulti="${speed// Unit/\n\t\tUnit}"
			echo -e "\t\t${smulti}"
		    fi
		fi
	    fi
            if [ ! -s "${nodes[${i}]}/infinipath-status" ] ||
                ! grep -q IB_configured "${nodes[${i}]}/infinipath-status" ||
                grep -q Disabled "${nodes[${i}]}/infinipath-status" ||
                ! grep -q IB_link_up "${nodes[${i}]}/infinipath-status" ; then
                test_failed=1
                (( notup++ ))
                good_nodes[${i}]=
                echo -e "\t${nodes[${i}]} InfiniPath link is not up"
                if [ "${vverbose}" = "true" ]; then
                    pr -t -o 16 "${nodes[${i}]}/infinipath-status"
                fi
            fi
            if [ -s "${nodes[${i}]}/infinipath-version" ]; then
		if [ -s "${nodes[${i}]}/infinipath-hwversion" ]; then
			fullvers="$(cat ${nodes[${i}]}/infinipath-hwversion)" 
		else
			fullvers="$(grep '^Driver ' ${nodes[${i}]}/infinipath-version)" 
		fi
		# we don't want to consider chip minor versions as different hardware
		thisvers="${fullvers%.[0-9]*, PCI [0-9]*, SW Compat [0-9]*}"
		# don't consider build hour to be different, just date
		fullrel="$(grep Release ${nodes[${i}]}/infinipath-version)" 
		thisrel="${fullrel%-[0-2][0-9]:[0-5][0-9] *}"
                if [ ! "${firstvers}" ]; then
		    foundvers[0]="${thisvers}"
		    firstvers="${thisvers}"
		    firstrel="${thisrel}"
		fi
		if [ "${vvverbose}" = "true" ]; then
		    echo -e "\t${nodes[${i}]} HWversion is:"
		    # handle multiple units as multi-line out
		    hvers="$(echo $fullvers)"
		    hmulti="${hvers// Unit/\n\t\tUnit}"
		    echo -e "\t\t${hmulti}"
		    echo -e "\t${nodes[${i}]} SWversion is:"
		    echo -e "\t\t${fullrel}"
		fi
		# should do full associative check; later
		if [ "${thisvers}" != "${firstvers}" ]; then
		    found_this_ver=0
		    for (( j=0; j<${#foundvers[*]}; j++)); do
			if [ "${thisvers}" == "${foundvers[${j}]}" ]; then
			    found_this_ver=1
			fi
		    done
		    if [ $found_this_ver -eq 0 ]; then
			foundvers[${#foundvers[*]}]="${thisvers}"
			(( numvers++ ))
		    fi
		    if [ "${verbose}" = "true" ]; then
			# with verbose, report full hardware string
			echo -e "\t${nodes[${i}]} HWversion is different:"
						    # handle multiple units as multi-line out
						    hvers="$(echo $fullvers)"
						    hmulti="${hvers// Unit/\n\t\tUnit}"
						    echo -e "\t\t${hmulti}"
		    fi
		fi
		if [ "${thisrel}" != "${firstrel}" ]; then
		    found_this_rel=0
		    for (( j=0; j<${#foundrels[*]}; j++ )); do
			if [ "${thisrel}" == "${foundrels[${j}]}" ]; then
			    found_this_rel=1
			fi
		    done
		    if [ $found_this_rel -eq 0 ]; then
		        foundrels[${#foundrels[*]}]="${thisrel}"
			(( numrel++ ))
		    fi
		    if [ "${verbose}" = "true" ]; then
			# with verbose, report full release string
			echo -e "\t${nodes[${i}]} SWversion is different:"
			echo -e "\t\t${fullrel}"
		    fi
                fi
            fi

            if [ -s "${nodes[${i}]}/infinipath-device" ]; then
                if [ ! "${firstdev}" ]; then
					firstdev="$(cat ${nodes[${i}]}/infinipath-device)" 
					thisdev="${firstdev}"
                    if [ "${vvverbose}" = "true" ]; then
                        echo -e "\t${nodes[${i}]} 1st devices: ${thisdev}"
                    fi
                else
					thisdev="$(cat ${nodes[${i}]}/infinipath-device)" 
                    if [ "${verbose}" = "true" ]; then
                        echo -e "\t${nodes[${i}]} later devices: ${thisdev}"
                    fi
                    if [ "${thisdev}" != "${firstdev}" ]; then
                        (( numdevs++ ))
                        if [ "${verbose}" = "true" ]; then
                            echo -e "\t${nodes[${i}]} devices are different: ${thisdev}"
                        fi
                    fi
                fi
			else
				echo "!!!WARNING!!! ${nodes[${i}]}: no ipath devices found in /dev"
                if [ "${firstdev}" ]; then
                        (( numdevs++ ))
				fi
            fi
	    if [ -s "${nodes[${i}]}/infinipath-mtrr" ]; then
		mtrr="$(cat ${nodes[${i}]}/infinipath-mtrr)"
		mtrr=${mtrr//Buffer Copy test:  /}
		poi_bw=0
		
		if [ "${vvverbose}" = "true" ]; then
		    echo -e "\t${nodes[${i}]} PIO bandwidth is: "
		    echo -e "\t\t${mtrr}"
		fi

		pio_bw="$(echo ${mtrr} | sed -r -e 's/([0-9]*).*/\1/g')"
		# According to the driver code, PIO BW of less then 1GiB/sec
		# is considered bad
		if [ $pio_bw -lt 1024 ]; then
		    (( badmtrr++ ))
		    if [ "${verbose}" = "true" ]; then
			echo -e "\t${nodes[${i}]} may have incorrect MTRR settings"
		    fi
		fi
	    fi
        fi
    done

    if [ ${notup} -gt 0 ]; then
        echo "!!!ERROR!!! InfiniPath not configured up and working on ${notup} systems"
    fi

    if [ ${numbus} -gt 1 ]; then
	echo "!!!WARNING!!! Multiple (${numbus}) Local Bus Types found"
    fi
    
    if [ ${badmtrr} -ne 0 ]; then
	echo "!!!WARNING!!! Bad MTRR settings on $badmtrr nodes"
    fi
    if [ ${numspeed} -gt 1 ]; then
	echo "!!!WARNING!!! Multiple (${numspeed}) IB Link speeds found"
    fi
    if [ ${numvers} -gt 1 ]; then
        echo "!!!WARNING!!! Multiple (${numvers}) InfiniPath hardware versions found"
    fi
    if [ ${numrel} -gt 1 ]; then
        echo "!!!WARNING!!! Multiple (${numrel}) InfiniPath software versions found"
    fi
    if [ ${numdevs} -gt 1 ]; then
        echo "!!!WARNING!!! Multiple (${numdevs}) sets of /dev devices found"
    fi

    if [ ${test_failed} ]; then
        failure
    elif [ ${num_failed} -gt 0 ]; then
        echo -e "\tFAILED"
    else
        echo -e "\tPASSED.  All tests were sucessful."
    fi
    echo
}

test6_mpi()
{
    echo -n "Test 6. Checking MPI capability... "

    if [ "$mpi_dir" = "" ] ; then
        echo -e "\n\n\tSKIPPING because OpenMPI is unavailable, install openmpi_gcc_qlc RPM\n"
        return
    fi

    if [ "${vverbose}" = "true" ]; then
        echo
    fi

    declare -a failed_nodes
    declare -i num_failed=0

    for (( i=0; i<num_nodes; i++ )); do
        if [ "${good_nodes[${i}]}" != "" ]; then
            failed_nodes[${i}]=${good_nodes[${i}]}
            (( num_failed++ ))
        fi
    done

    nonmpi_msg='\tIf you are not using OpenMPI with InfiniPath, you should
\ttry running a simple MPI job at this point, using the appropriate
\tMPI launch command and test program(s)'

	$mpirun $mpi_allow_root $mpirun_version > ${work_dir}/mpirun-vers 2>${work_dir}/mpirun-err
	case "$(grep -i 'Open MPI' ${work_dir}/mpirun-vers| tr '[A-Z]' '[a-z]')" in
	*open\ mpi*) ;;
	*) if grep -qi 'command not found' "${work_dir}/mpirun-err" ||
              grep -qi 'no such file or directory' "${work_dir}/mpirun-err" ; then
	       echo "FAILED: cannot find mpirun for OpenMPI"
	       echo -e "\tIs the openmpi_gcc_qlc RPM installed?"
	       echo -e "$nonmpi_msg"
           else
	       echo "FAILED: mpirun command is not the OpenMPI version"
	       echo -e "$nonmpi_msg"
           fi
           if [ "${verbose}" = "true" ]; then
		  echo -e "\tmpirun version appears to be: "
		  head -q -n3 ${work_dir}/mpirun-vers ${work_dir}/mpirun-err
		  echo ""
	   fi
	   failure
	   return
	esac
    
    for (( i=0; i<num_nodes; i++ )); do
        if [ "${failed_nodes[${i}]}" != "" ]; then
            if [ "${vverbose}" = "true" ]; then
                echo -ne "\tlaunching MPI job on ${nodes[${i}]}..."
            fi
            (cd ${launch_dir} && 
		    $mpirun $mpi_allow_root $mpirun_m ${work_dir}/"${nodes[${i}]}/hostname" $mpirun_n 1 \
		    	true; exit $?) > mpirun.out
	    rc=$?
	    if [ $rc -ne 0 ]; then
		if [ -f ${work_dir}/mpirun.out ]; then
		    cat ${work_dir}/mpirun.out
		    rm -rf ${work_dir}/mpirun.out
		fi
	    fi
	    
            if [ $rc -eq 0 ]; then
                failed_nodes[${i}]=
                (( num_failed-- ))
                if [ "${vverbose}" = "true" ]; then
                    echo "success"
                elif [ "${verbose}" = "true" ]; then
                    echo -n "."
                fi
            else
                if [ "${vverbose}" = "true" ]; then
                    echo "failed"
                elif [ "${verbose}" = "true" ]; then
                    echo -n "?"
                fi
            fi
        else
            if [ "${vverbose}" = "true" ]; then
                echo -e "\tSkipping node ${nodes[${i}]} due to earlier failures..."
            elif [ "${verbose}" = "true" ]; then
                echo -n "x"
            fi
        fi
    done

    if [ "${verbose}" = "true" -a "${vverbose}" = "false" ]; then
        echo -n " "
    fi
    if [ ${num_failed} -gt 0 ]; then
        echo "FAILED"
        echo
        if [ ${num_failed} -eq 1 ]; then
            echo "Unable to launch MPI job on ${num_failed} node:"
        else
            echo "Unable to launch MPI job on ${num_failed} nodes:"
        fi
        for (( i=0; i<num_nodes; i++ )); do
            if [ "${failed_nodes[${i}]}" != "" ]; then
                echo -e "\t${nodes[${i}]}"
            fi
        done
        failure
        for (( i=0; i<num_nodes; i++ )); do
            if [ "${failed_nodes[${i}]}" != "" ]; then
                good_nodes[${i}]=
            fi
        done
    else
        echo "OK"
    fi
    echo
}

test7_nxnlatbw()
{
    unset test_failed
    echo -n "Test 7. Running MPI program mpi_nxnlatbw on all nodes... "

    declare -i num_to_run=0 bw_low=0 bw_high=0
    
    for (( i=0; i<num_nodes; i++ )); do
        if [ "${good_nodes[${i}]}" != "" ]; then
            echo "${nodes[${i}]}" >> nodes.nxnlatbw
            (( num_to_run++ ))
        fi
    done

    if [ "${vverbose}" = "true" ]; then
        echo -e "Running latency and bandwidth test against hosts:\n\t$(fmt nodes.nxnlatbw)"
    fi

    if [ ${num_to_run} -lt 2 ]; then
        echo -e "\n\n\tSKIPPING because fewer than two nodes passed earlier tests\n"
        return
    fi

    if [ "$mpi_dir" = "" ] ; then
        echo -e "\n\n\tSKIPPING because OpenMPI is unavailable, install openmpi_gcc_qlc RPM\n"
        return
    fi

    if [ ! -x $mpi_nxnlatbw ] ; then
        echo -e "\n\n\tSKIPPING because mpi_nxnlatbw executable is unavailable\n"
        return
    fi

    if [ "${vverbose}" == "true" ]; then
	(cd ${launch_dir} && 
	    $mpirun $mpi_allow_root $mpirun_m ${work_dir}/nodes.nxnlatbw $mpirun_n ${num_to_run} $mpirun_options \
		$mpi_nxnlatbw ; exit $?) 2>${work_dir}/err.nxnlatbw | tee ${work_dir}/out.nxnlatbw
    elif [ "${verbose}" == "true" ]; then
	stop=0
	(cd ${launch_dir} && 
	    $mpirun $mpi_allow_root $mpirun_m ${work_dir}/nodes.nxnlatbw $mpirun_n ${num_to_run} $mpirun_options \
		$mpi_nxnlatbw -q ; exit $?) 2>${work_dir}/err.nxnlatbw | \
		(IFS=''; (while read -d '\200' -r -n 1 c; do \
		if [ $stop -ne 1 -a "X$c" = "X." ]; then
		    echo -n $c
		else
		    exit
		fi; done); while read x; do \
		    echo $x >> ${work_dir}/out.nxnlatbw
	    done ; sed -i -e '/^$/d' ${work_dir}/out.nxnlatbw)
		
    else
	(cd ${launch_dir} &&
	    $mpirun $mpi_allow_root $mpirun_m ${work_dir}/nodes.nxnlatbw $mpirun_n ${num_to_run} $mpirun_options \
		$mpi_nxnlatbw ; exit $?) > ${work_dir}/out.nxnlatbw 2>${work_dir}/err.nxnlatbw
    fi

    if [ $? -eq 0 ]; then
        echo "OK"
        if [ -s ${work_dir}/err.nxnlatbw ]; then
            echo -e "!!!WARNING!!! there was some error output, however:\n\t$(cat err.nxnlatbw)"
        fi
    else
        test_failed=true
        echo "FAILED, error output: $(cat err.nxnlatbw)"
        if [ "${verbose}" = "true" -a -s ${work_dir}/out.nxnlatbw ]; then
            echo Output from latency and bandwidth check:
            cat ${work_dir}/out.nxnlatbw
        fi
        # return early to avoid the results parsing
	failure
	return
    fi

    # Declare the acceptable bandwidth ranges per card type
    bw_low_QLE7240=1150
    bw_high_QLE7240=1500
    bw_low_QLE7280=1700
    bw_high_QLE7280=2000
    bw_low_QLE7340=2000
    bw_high_QLE7340=3600
    bw_low_QLE7342=2000
    bw_high_QLE7342=3600
    bw_low_QMH7340=2000
    bw_high_QMH7340=3600
    bw_low_QMH7342=2000
    bw_high_QMH7342=3600
    bw_low_QME7342=2000
    bw_high_QME7342=3600
    bw_low_QME7362=2000
    bw_high_QME7362=3600

    # Determine the card type for the bandwidth analysis
    (cd ${launch_dir} &&
	$mpirun $mpi_allow_root $mpirun_n 1 $mpirun_m ${work_dir}/nodes.nxnlatbw \
	ipath_control -i; exit $?) > ${work_dir}/ipath_control
    card=$(cat ${work_dir}/ipath_control | grep 'InfiniPath' | sed -r -e 's/.*InfiniPath_([A-Z0-9]*),.*/\1/g')
    #Just use first card, in case of multiple cards (multiple HCAs)
    card=`echo $card | sed -r 's/(.*) .*/\1/'`

    eval bw_low=\$bw_low_$card
    eval bw_high=\$bw_high_$card

    # If we don't have a bandwidth range for this card use
    # the default values (should cover all non-QLE72*0 cards)
    [ $bw_low -eq 0 ] && bw_low=800
    [ $bw_high -eq 0 ] && bw_high=1000
    
    echo -e "\tAnalyzing results..."

    # check for stuff here
    declare _hosts _n1 _n2 _lat _bw avglatus
    declare -a hosts n1 n2 lat bw
    declare -i rescnt=0 hostcnt=0 totlat=0 totbw=0 avglat totlat
    declare -i bwlow=0 bwhi=0 latlow=0 lathi=0 

    exec 3< ./nodes.nxnlatbw
    while read -u 3 _hosts; do
        hosts[${hostcnt}]="${_hosts}"
        (( hostcnt++ ))
    done

    # This is the expected format
    # [0<->1]         1.41us          947.395446 (MillionBytes/sec)
    sed -e '/\.[0-9][0-9]*us/s/\.//' -e 's/us//' -e 's/[]\[<>.-]/ /g' ${work_dir}/out.nxnlatbw > out.cleaned
    exec 3< ./out.cleaned
    while read -u 3 _n1 _n2 _lat _bw junk; do
        n1[${rescnt}]="${_n1}"
        n2[${rescnt}]="${_n2}"
        #remove 0 from beginning if any
        _lat=`echo $_lat | sed 's/^0*//'`
        _bw=`echo $_bw | sed 's/^0*//'`
        lat[${rescnt}]="${_lat}" #multiplied by 100!
        bw[${rescnt}]="${_bw}"
        totbw=$(( $totbw + ${_bw} ))
        totlat=$(( $totlat + ${_lat} ))
        (( rescnt++ ))
    done

    if [ $rescnt -lt 1 ] ; then
        echo "!!!WARNING!!! No valid output from latency and bandwidth analysis"
        test_failed=1
    elif [ $totbw -lt 1 -o $totlat -lt 100 ] ; then
        echo "!!!WARNING!!! Incorrect totals ($totlat, $totbw) from latency and bandwidth analysis"
        test_failed=1
    else
        avgbw=$(( ${totbw} / ${rescnt} ))
        avglat=$(( ${totlat} / ${rescnt} ))
	avglatus=$(printf "%d.%02d" $(( ${avglat} / 100 )) $(( ${avglat} % 100 )))
        if [ ${avgbw} -lt ${bw_low} -o ${avgbw} -gt ${bw_high} ]; then
            echo "!!!WARNING!!! Average bandwidth ${avgbw} MBytes/sec is out of expected range"
        else
            echo "Average bandwidth: ${avgbw} MBytes/sec"
        fi
        if [ ${avglat} -lt 90 -o ${avglat} -ge 300 ]; then
            echo "!!!WARNING!!! Average latency ${avglatus} usec is out of expected range"
        else
            echo "Average latency: ${avglatus} usec"
        fi
# max bandwidth isn't affected much by switch configuration, so it is fairly
# tightly bounded for this test.  small packet latency is greatly affected by
# switch configuration (about 200nsec per switch hop), so we use a much broader
# range allowance for latency.
        bwlow=$(( (${avgbw} * 90) / 100 ))
        bwhi=$(( ${avgbw} * 110 ))
        latlow=$(( (${avglat} * 75) / 100 ))
        lathi=$(( ${avglat} * 125 ))

        # Now check for abnormally high or low
        for (( i=0; i<rescnt; i++ )); do
            latus=$(printf "%d.%02dus" $(( ${lat[${i}]} / 100 )) $(( ${lat[${i}]} % 100 )))
            if [ ${lat[${i}]} -lt ${latlow} ]; then
                echo "Host pair ${hosts[${n1[${i}]}]},${hosts[${n2[${i}]}]} latency ${latus} is lower than expected" 
            elif [ ${lat[${i}]} -gt ${lathi} ]; then
                echo "Host pair ${hosts[${n1[${i}]}]},${hosts[${n2[${i}]}]} latency ${latus} is higher than expected" 
            fi
            if [ ${bw[${i}]} -lt ${bwlow} ]; then
                echo "Host pair ${hosts[${n1[${i}]}]},${hosts[${n2[${i}]}]} bandwidth ${bw[${i}]}MB/s is lower than expected" 
            elif [ ${bw[${i}]} -gt ${bwhi} ]; then
                echo "Host pair ${hosts[${n1[${i}]}]},${hosts[${n2[${i}]}]} bandwidth ${bw[${i}]}MB/s is higher than expected" 
            fi
        done
    fi
    echo

    if [ ${test_failed} ]; then
        failure
    else
        echo -e "\tPASSED.  All tests were sucessful."
    fi
}

### begin

# parse args
while [ $# -gt 0 ]; do
    
    case "$1" in
        -*=*)
            optarg=`echo "$1" | sed 's/[-_a-zA-Z0-9]*=//'`
            ;;
        *)
            optarg=
            ;;
    esac

    case "$1" in
        -c|--continue)
            cont=true
            ;;
        -d|--debug)
            set -xv
            ;;
        -h|--help)
            usage
            exit 0
            ;;
        -k|--keep)
            keep=true
            ;;
        --skip=*)
            skip_list="${optarg}"
            ;;
	--run=*)
	    run_list="${optarg}"
	    ;;
        --workdir=*)
            work_dir=`eval echo ${optarg}`
            ;;
        -v|--verbose)
            verbose=true
            export IPATH_CHECKOUT_VERBOSE=1
            ;;
        -vv|--vv|--vverbose) # be *very* verbose
            verbose=true
            vverbose=true
            export IPATH_CHECKOUT_VERBOSE=1
            export IPATH_CHECKOUT_VVERBOSE=1
            ;;
        -vvv|--vvv|--vvverbose) # be *very* *VERY* verbose
            verbose=true
            vverbose=true
            vvverbose=true
            export IPATH_CHECKOUT_VERBOSE=1
            export IPATH_CHECKOUT_VVERBOSE=1
            export IPATH_CHECKOUT_VVVERBOSE=1
            ;;
        --) # use ' -- ' to indicate we're done with args
            shift
            break
            ;;
        -*)
            usage
            error "unknown flag $1"
            ;;
        *)
            break
            ;;
    esac
    shift
done

# sanity checks
if [ $# -lt 1 ]; then
    error "machines file argument required, use -h option for help"
elif [ $# -eq 1 ]; then
    machine_file=$1
else
    shift
    error "extra arguments after machines file: ($*)"
fi

if [ ! -e "${machine_file}" ]; then
    error "\"${machine_file}\" no such file or directory"
elif [ ! -r "${machine_file}" ]; then
    error "\"${machine_file}\" cannot read file"
fi

mk_workdir
get_mpi_info

cd "${work_dir}"

get_nodes

# make sure that commas are not in any of the lists
run_list=${run_list//,}
skip_list=${skip_list//,}

# filter the tests to run
for x in $(echo $skip_list | sed -e 's/\(.\)/\1 /g'); do
    run_list=${run_list//$x}
done

[[ $run_list = *1* ]] && test1_ping_nodes
[[ $run_list = *2* ]] && test2_ssh_nodes
[[ $run_list = *3* ]] && test3_sysconfig
[[ $run_list = *4* ]] && test4_rpms
[[ $run_list = *5* ]] && test5_infinipath
[[ $run_list = *6* ]] && test6_mpi
[[ $run_list = *7* ]] && test7_nxnlatbw

# done

cleanup

exit 0
