def detachOrAttachIso(vmName, iso, isAttach):
        try:
            if vmName in OvmHost.getAllVms():
                scope = 'both'
                vmPath = OvmHost()._vmNameToPath(vmName)
            else:
                scope = 'cfg'
                vmPath = OvmHost()._getVmPathFromPrimaryStorage(vmName)

            vmType = OvmVm()._getVmTypeFromConfigFile(vmPath)
            if vmType != 'HVM':
                raise Exception("Only HVM supports attaching/detaching ISO")

            if not isAttach:
                iso = ''
            else:
                isoName = basename(iso)
                isoMountPoint = OvmVm()._getIsoMountPath(vmPath)
                isoOnSecStorage = dirname(iso)
                OvmStoragePool()._mount(isoOnSecStorage, isoMountPoint)
                iso = join(isoMountPoint, isoName)

            exceptionIfNoSuccess(xen_change_vm_cdrom(vmPath, iso, scope))
            return SUCC()
        except Exception, e:
            errmsg = fmt_err_msg(e)
            logger.error(OvmVm.detachOrAttachIso, errmsg)
            raise XmlRpcFault(toErrCode(OvmVm, OvmVm.detachOrAttachIso),
                              errmsg)
    def getDetails(vmName):
        try:
            vm = OvmVm()

            try:
                OvmHost()._getDomainIdByName(vmName)
                vmPath = OvmHost()._vmNameToPath(vmName)
                vifsFromConfig = False
            except NoVmFoundException, e:
                vmPath = OvmHost()._getVmPathFromPrimaryStorage(vmName)
                vifsFromConfig = True

            if not isdir(vmPath):
                # The case is, when vm starting was not completed at primaryStroageDownload or createVolume(e.g. mgmt server stop), the mgmt
                # server will keep vm state in staring, then a stop command will be sent. The stop command will delete bridges that vm attaches,
                # by retriving birdge info by OvmVm.getDetails(). In this case, the vm doesn't exists, so returns a fake object here.
                fakeDisk = OvmDisk()
                vm.rootDisk = fakeDisk
            else:
                if vifsFromConfig:
                    vm.vifs.extend(vm._getVifsFromConfig(vmPath))
                else:
                    vm.vifs.extend(vm._getVifs(vmName))

                safeSetAttr(vm, 'name', vmName)
                disks = successToMap(
                    xen_get_vdisks(vmPath))['vdisks'].split(',')
                rootDisk = None
                #BUG: there is no way to get type of disk, assume all are "w"
                for d in disks:
                    if vmName in d:
                        rootDisk = OvmDisk()
                        safeSetAttr(rootDisk, 'path', d)
                        safeSetAttr(rootDisk, 'type', "w")
                        continue
                    disk = OvmDisk()
                    safeSetAttr(disk, 'path', d)
                    safeSetAttr(disk, 'type', "w")
                    vm.disks.append(disk)
                if not rootDisk:
                    raise Exception("Cannot find root disk for vm %s" % vmName)
                safeSetAttr(vm, 'rootDisk', rootDisk)
                vcpus = int(successToMap(xen_get_vcpus(vmPath))['vcpus'])
                safeSetAttr(vm, 'cpuNum', vcpus)
                memory = MtoBytes(
                    int(successToMap(xen_get_memory(vmPath))['memory']))
                safeSetAttr(vm, 'memory', memory)
                vmStatus = db_get_vm(vmPath)
                safeSetAttr(vm, 'powerState', vmStatus['status'])
                vmType = successToMap(xen_get_vm_type(vmPath))['type'].replace(
                    'hvm', 'HVM').replace('para', 'PV')
                safeSetAttr(vm, 'type', vmType)

            rs = fromOvmVm(vm)
            logger.info(OvmVm.getDetails, rs)
            return rs
    def getVmStats(vmName):
        def getVcpuNumAndUtils():
            try:
                session = session_login()
                refs = session.xenapi.VM.get_by_name_label(vmName)
                if len(refs) == 0:
                    raise Exception("No ref for %s found in xenapi VM objects"%vmName)
                vm = XenAPIObject('VM', session, refs[0])
                VM_metrics = XenAPIObject("VM_metrics", session, vm.get_metrics())
                items = VM_metrics.get_VCPUs_utilisation().items()
                nvCpus = len(items)
                if nvCpus == 0:
                    raise Exception("vm %s has 0 vcpus !!!"%vmName)

                xmInfo = successToMap(xen_get_xm_info())
                nCpus = int(xmInfo['nr_cpus'])
                totalUtils = 0.0
                # CPU utlization of VM = (total cpu utilization of each vcpu) / number of physical cpu
                for num, util in items:
                    totalUtils += float(util)
                avgUtils = float(totalUtils/nCpus) * 100
                return (nvCpus, avgUtils)
            finally:
                session_logout()


        try:
            try:
                OvmHost()._getDomainIdByName(vmName)
                vmPath = OvmHost()._vmNameToPath(vmName)
                (nvcpus, avgUtils) = getVcpuNumAndUtils()
                vifs = successToMap(xen_get_vifs(vmPath))
                rxBytes = 0
                txBytes = 0
                vifs = OvmVm()._getVifs(vmName)
                for vif in vifs:
                    rxp = join('/sys/class/net', vif.name, 'statistics/rx_bytes')
                    txp = join("/sys/class/net/", vif.name, "statistics/tx_bytes")
                    if not exists(rxp): raise Exception('can not find %s'%rxp)
                    if not exists(txp): raise Exception('can not find %s'%txp)
                    rxBytes += long(doCmd(['cat', rxp])) / 1000
                    txBytes += long(doCmd(['cat', txp])) / 1000
            except NoVmFoundException, e:
                vmPath = OvmHost()._getVmPathFromPrimaryStorage(vmName)
                nvcpus = int(successToMap(xen_get_vcpus(vmPath))['vcpus'])
                avgUtils = 0
                rxBytes = 0
                txBytes = 0

            rs = toGson({"cpuNum":nvcpus, "cpuUtil":avgUtils, "rxBytes":rxBytes, "txBytes":txBytes})
            logger.debug(OvmVm.getVmStats, rs)
            return rs
    def stop(vmName):
        try:
            try:
                OvmHost()._getDomainIdByName(vmName)
            except NoVmFoundException, e:
                logger.info(OvmVm.stop, "vm %s is already stopped"%vmName)
                return SUCC()

            logger.info(OvmVm.stop, "Stop vm %s"%vmName)
            try:
                vmPath = OvmHost()._vmNameToPath(vmName)
            except Exception, e:
                errmsg = fmt_err_msg(e)
                logger.info(OvmVm.stop, "Cannot find link for vm %s on primary storage, treating it as stopped\n %s"%(vmName, errmsg))
                return SUCC()
Beispiel #5
0
 def detachOrAttachIso(vmName, iso, isAttach):
     try:
         if vmName in OvmHost.getAllVms():
             scope = 'both'
             vmPath = OvmHost()._vmNameToPath(vmName)
         else:
             scope = 'cfg'
             vmPath = OvmHost()._getVmPathFromPrimaryStorage(vmName)
         
         vmType = OvmVm()._getVmTypeFromConfigFile(vmPath)
         if vmType != 'HVM':
             raise Exception("Only HVM supports attaching/detaching ISO")
         
         if not isAttach:
             iso = ''
         else:
             isoName = basename(iso)
             isoMountPoint = OvmVm()._getIsoMountPath(vmPath)
             isoOnSecStorage = dirname(iso)
             OvmStoragePool()._mount(isoOnSecStorage, isoMountPoint)
             iso = join(isoMountPoint, isoName)
                    
         exceptionIfNoSuccess(xen_change_vm_cdrom(vmPath, iso, scope))
         return SUCC()
     except Exception, e:
         errmsg = fmt_err_msg(e)
         logger.error(OvmVm.detachOrAttachIso, errmsg)
         raise XmlRpcFault(toErrCode(OvmVm, OvmVm.detachOrAttachIso), errmsg)
    def _getVifs(self, vmName):
        vmPath = OvmHost()._vmNameToPath(vmName)
        domId = OvmHost()._getDomainIdByName(vmName)
        vifs = successToMap(xen_get_vifs(vmPath))
        lst = []
        for k in vifs:
            v = vifs[k]
            vifName = 'vif' + domId + '.' + k[len('vif'):]
            vif = OvmVif()
            (mac, bridge, type) = v.split(',')
            safeSetAttr(vif, 'name', vifName)
            safeSetAttr(vif, 'mac', mac)
            safeSetAttr(vif, 'bridge', bridge)
            safeSetAttr(vif, 'type', type)
            lst.append(vif)

        return lst
 def migrate(vmName, targetHost):
     try:
         vmPath = OvmHost()._vmNameToPath(vmName)
         raiseExceptionIfFail(xen_migrate_vm(vmPath, targetHost))
         unregister_vm(vmPath)
         OvmVm()._cleanUpOwnerFile(vmPath)
         return SUCC()
     except Exception, e:
         errmsg = fmt_err_msg(e)
         logger.error(OvmVm.migrate, errmsg)
         raise XmlRpcFault(toErrCode(OvmVm, OvmVm.migrate), errmsg)
 def register(vmName):
     try:
         vmPath = OvmHost()._vmNameToPath(vmName)
         raiseExceptionIfFail(register_vm(vmPath))
         OvmVm()._tapAOwnerFile(vmPath)
         vncPort = successToMap(xen_get_vnc_port(vmName))['vnc_port']
         rs = toGson({"vncPort": str(vncPort)})
         logger.debug(OvmVm.register, rs)
         return rs
     except Exception, e:
         errmsg = fmt_err_msg(e)
         logger.error(OvmVm.register, errmsg)
         raise XmlRpcFault(toErrCode(OvmVm, OvmVm.register), errmsg)
 def reboot(vmName):
     try:
         #===================================================================
         # Xend has a bug of reboot. If reboot vm too quick, xend return success
         # but actually it refused reboot (seen from log)
         # vmPath = successToMap(xen_get_vm_path(vmName))['path']
         # raiseExceptionIfFail(reset_vm(vmPath))
         #===================================================================
         vmPath = OvmHost()._vmNameToPath(vmName)
         OvmVm.stop(vmName)
         raiseExceptionIfFail(start_vm(vmPath))
         vncPort= successToMap(xen_get_vnc_port(vmName))['vnc_port']
         logger.info(OvmVm.stop, "reboot vm %s, new vncPort is %s"%(vmName, vncPort))
         return toGson({"vncPort":str(vncPort)})
     except Exception, e:
         errmsg = fmt_err_msg(e)
         logger.error(OvmVm.reboot, errmsg)
         raise XmlRpcFault(toErrCode(OvmVm, OvmVm.reboot), errmsg)