import subprocess
import os
import sys
from baseCheck import baseCheck

class checkHostNodes(baseCheck):

    if sys.platform == "win32":
        countFlag='-n'
    else:
        countFlag='-c'

    def getHumanName(self):
        return "Check connection to KVM Hosts"

    def runCheck(self,config, debug):
        # confirm I can talk to all the hostnodees...
        returnCode=0
        for server in config["environment"]["servers"]:
            retval=0
            # make sure can talk to virsh on this node
            fnull=open(os.devnull,'w')
            with open('./.pr.tmp','w') as f:
                retval=subprocess.call(['ping',self.countFlag,'2',server["accessIP"]],stdout=fnull,stderr=fnull)
            fnull.close()

            if retval != 0:
                # thats a failure.
                rawResult = ''
                with open('./.pr.tmp','r') as f:
                    rawResult = "Ping failed (Error %s)" % f.read()
                self.addFailure(rawResult, "Unable to ping host %s.  Please verify the IP address." % server["accessIP"])
            else:

                # if a ping worked - how about a virsh?
                with open('./.v.tmp','w') as f:
                    try:
                        retval=subprocess.call(['virsh','-c',
                            'qemu+ssh://'+server["accessIP"]+'/system?no_verify=1',
                            'list'],stdout=f,stderr=f)
                    except:
                        retval=-1

                if retval != 0:
                    # failed.
                    rawResult = ''
                    with open('./.v.tmp','r') as f:
                        rawResult = "CheckHostNode failed to contact virsh agent on %s (Error: %s)" % (server["accessIP"],f.read())
                    self.addFailure(rawResult, 'Unable to contact KVM host VIRSH agent at '+server["accessIP"]+'. Please check the configured IP address.')
                
        return returnCode
