Exemple #1
0
    def relocate_vm(self, vm_name, host_dest, datastore_dest):
        self.logger.info('Perform relocate_vm')
        try:
            vm = self.get_obj([vim.VirtualMachine], vm_name)
            self.srchost = vm.runtime.host.name
            self.srcdatastore = vm.datastore[0].info.name
            # Create Relocate Spec
            spec = vim.VirtualMachineRelocateSpec()
            # Find destination host
            destination_host = self.get_obj([vim.HostSystem], host_dest)
            spec.host = destination_host

            # Find destination Resource pool
            resource_pool = destination_host.parent.resourcePool
            spec.pool = resource_pool

            # collect disks belong to the VM
            template_disks = self.collect_template_disks(vm)
            datastore_dest_id = self.get_obj([vim.Datastore], datastore_dest)
            spec.datastore = datastore_dest_id
            spec.disk = self.construct_locator(template_disks,
                                               datastore_dest_id)

            task = vm.RelocateVM_Task(spec)
            return (self.wait_for_task(task))
        except Exception as e:
            self.logger.error('Failed in relocate_vm: ' + str(e))
            self.logger.exception('')
            return False

        self.logger.info('Finished  relocate_vm')
Exemple #2
0
def relocate_vm(si, args):
    content = si.RetrieveContent()
    vm = get_vm(si, args.get('uuid'))

    priority = get_priority(args.get('priority'))
    spec = vim.VirtualMachineRelocateSpec()  # type: ignore
    spec.folder = search_for_obj(content, [vim.Folder], args.get('folder'))
    spec.host = search_for_obj(content, [vim.HostSystem], args.get('host'))
    spec.pool = search_for_obj(content, [vim.ResourcePool], args.get('pool'))  # type: ignore
    datastore = search_for_obj(content, [vim.Datastore], args.get('datastore'))

    if datastore:
        spec.datastore = datastore
        spec.disks = create_rellocation_locator_spec(vm, datastore)
    task = vm.RelocateVM_Task(spec, priority)
    wait_for_tasks(si, [task])

    if task.info.state == 'success':
        return {
            'ContentsFormat': formats['json'],
            'Type': entryTypes['note'],
            'Contents': {},
            'ReadableContentsFormat': formats['text'],
            'HumanReadable': 'Virtual Machine was relocated successfully.',
            'EntryContext': {}
        }
    elif task.info.state == 'error':
        raise Exception('Error occurred while trying to relocate VM.')
Exemple #3
0
def migrationVM(content, vminfo, vm, score, resourcepool):
    relocate_spec = vim.VirtualMachineRelocateSpec()
    relocate_spec.pool = resourcepool

    if score == 1:
        host = get_host_by_name(content, vminfo['targethost'])
        if not host:
            print "[ERROR] not found host"
            return
        relocate_spec.host = host
    elif score == 2:
        datastore = get_ds_by_name(content, vminfo['targetdatastore'])
        if not datastore:
            print "[ERROR] not found datastore"
            return
        relocate_spec.datastore = datastore
    elif score == 3:
        host = get_host_by_name(content, vminfo['targethost'])
        if not host:
            print "[ERROR] not found host"
            return
        relocate_spec.host = host
        datastore = get_ds_by_name(content, vminfo['targetdatastore'])
        if not datastore:
            print "[ERROR] not found datastore"
            return
        relocate_spec.datastore = datastore
    else:
        print "[ERROR] you must write target host or datastore"
        return

    # run migration
    task = vm.Relocate(relocate_spec)
    wait_for_task(task)
def cloneToTemplate(VM, dstFolder, dstDatastore):
    backup_snapshot = takeSnapshot(VM)
    if not (backup_snapshot):
        logging.warning("Error taking snapshot of virtual machine \"" +
                        VM.name + "\"")
        return None
    else:
        spec = vim.VirtualMachineCloneSpec()
        location = vim.VirtualMachineRelocateSpec()
        location.folder = dstFolder
        location.datastore = dstDatastore
        spec.location = location
        spec.snapshot = backup_snapshot
        spec.template = True
        spec.memory = False
        task = VM.CloneVM_Task(name=VM.name + "_Backup_" +
                               (datetime.today()).strftime("%Y-%m-%d_%H-%M"),
                               spec=spec,
                               folder=dstFolder)
        if trackTask(task):
            logging.info("Successfull backup of VM " + VM.name +
                         ", deleting Snapshot")
            deleteSnapshot(backup_snapshot)
            deleteOldBackups(VM, 2, dstFolder)
        else:
            logging.warning("Something gone wrong with coping VM \"" +
                            VM.name + "\". Deleting made snapshot.")
            deleteSnapshot(backup_snapshot)
def clone_vm( content, template, vm_name, si, datastore_name, resource_pool):
    datacenter = get_obj( content, [vim.Datacenter], None)
    destfolder = datacenter.vmFolder
    if datastore_name:
        datastore = get_obj( content, [vim.Datastore], datastore_name)
    else:
        objview = content.viewManager.CreateContainerView( content.rootFolder, [vim.HostSystem], True)
        esxi_hosts = objview.view
        for esxi_host in esxi_hosts:
            if esxi_host.name == resource_pool:
                storage_system = esxi_host.configManager.storageSystem
                host_file_sys_vol_mount_info = storage_system.fileSystemVolumeInfo.mountInfo
                datastore = host_file_sys_vol_mount_info[0].volume.name
                datastore = get_obj( content, [vim.Datastore], datastore)               
                break
    cluster = get_obj(content, [vim.ClusterComputeResource], None)
    host_dest = resource_pool;
    if resource_pool:
        resource_pool = get_obj(content, [vim.ResourcePool], resource_pool)
    else:
        resource_pool = cluster.resourcePool
    vmconf = vim.vm.ConfigSpec()
    destination_host = get_obj(content, [vim.HostSystem], host_dest)
    relospec = vim.VirtualMachineRelocateSpec()
    relospec.pool = destination_host.parent.resourcePool
    relospec.datastore = datastore
    clonespec = vim.vm.CloneSpec()
    clonespec.location = relospec
    print("cloning VM...")
    task = template.Clone( folder = destfolder, name = vm_name, spec = clonespec)
    wait_for_task(task)
Exemple #6
0
def relocate_vm(vm_name, content, host_dest, datastore_dest=None):
    """
    This method relocates vm to the host_dest across
    datacenters, clusters, datastores managed by a Vcenter

    Args:
        vm_name:
        content:
        host_dest:
        datastore_dest:

    Returns:

    """
    relocation_status = False
    message = "relocate_vm passed"
    try:
        vm = get_object(content, [vim.VirtualMachine], vm_name)
        current_host = vm.runtime.host.name
        print("vmotion_vm current_host:" + current_host)

        # Create Relocate Spec
        spec = vim.VirtualMachineRelocateSpec()

        # Check whether compute vmotion required and construct spec accordingly
        if host_dest is not None:
            if current_host == host_dest:
                raise Exception("WARNING:: destination_host can not equal "
                                "current_host")

            # Find destination host
            destination_host = get_object(content, [vim.HostSystem], host_dest)
            print("vmotion_vm destination_host:" + str(destination_host))
            spec.host = destination_host

            # Find destination Resource pool
            resource_pool = destination_host.parent.resourcePool
            print("vmotion_vm resource_pool:" + str(resource_pool))
            spec.pool = resource_pool

        # Check whether storage vmotion required and construct spec accordingly
        if datastore_dest is not None:
            # collect disks belong to the VM
            template_disks = collect_template_disks(vm)
            datastore_dest_id = get_object(content, [vim.Datastore],
                                           datastore_dest)
            spec.datastore = datastore_dest_id
            spec.disk = construct_locator(template_disks, datastore_dest_id)

        print("relocate_vm spec:" + str(spec))
        task = vm.RelocateVM_Task(spec)
        while task.info.state == vim.TaskInfo.State.running:
            continue
        relocation_status = True
    except Exception as e:
        message = "relocate_vm failed for vm:" + vm_name \
                  + " with error:" + str(e)
    print(message)
    return relocation_status, message
def DeployVmFn(Properties):
    task = Properties['task']
    params = getParameters(task['Parameters'])
    opStatus = {}

    # ===========================================================================
    # Connect to Vcenter
    # ===========================================================================
    si = connectVcenter(Properties)

    obj = getObjRef(si.content, vim.VirtualMachine, params['Template'])

    destination_host = getObjRef(si.content, vim.HostSystem, params['Host'])
    dc = getObjRef(si.content, vim.Datacenter, params['Datacenter'])
    cluster = getObjRef(si.content, vim.ClusterComputeResource, params['Cluster'])

    if obj is None:
        msg = "A object named " + params['Template'] + " could not be found"
        updateFailedTaskList(task['TaskName'], params, msg, opStatus)

    elif destination_host is None:
        msg = "A object named " + params['Host'] + " could not be found"
        updateFailedTaskList(task['TaskName'], params, msg, opStatus)

    elif dc is None:
        msg = "A object named " + params['Datacenter'] + " could not be found"
        updateFailedTaskList(task['TaskName'], params, msg, opStatus)

    elif cluster is None:
        msg = "A object named " + params['Cluster'] + " could not be found"
        updateFailedTaskList(task['TaskName'], params, msg, opStatus)

    else:
        try:
            print(" Deploying the VM %s" % obj.name)
            rs = vim.VirtualMachineRelocateSpec()
            cs = vim.VirtualMachineCloneSpec()
            target_folder = dc.vmFolder
            rs.host = destination_host
            rs.pool = cluster.resourcePool
            cs.location = rs
            cs.powerOn = False
            print ("Deploy initiated...")
            WaitForTask(obj.CloneVM_Task(target_folder, params['VmName'], cs))
            print(" Virtual Machine %s has been Deployed successfully" % params['VmName'])

            opStatus['ObjectName'] = getObjName(obj)
            opStatus['Status'] = 'Passed'

        except Exception as e:
            updateFailedTaskList(task['TaskName'], params, e.msg, opStatus)
    # ===========================================================================
    # Disconnect Vcenter
    # ===========================================================================
    Disconnect(si)

    return opStatus
Exemple #8
0
 def buildVmotionSpec(self, vm, dest_host, dest_datastore):
     spec = vim.VirtualMachineRelocateSpec()
     destination_host = self.getHost(dest_host)
     destination_ds = self.getDatastore(dest_datastore)
     spec.host = destination_host
     spec.pool = destination_host.parent.resourcePool
     spec.datastore = destination_ds
     template_disks = self.collect_template_disks(vm)
     spec.disk = self.construct_locator(template_disks, destination_ds)
     return spec
    def vmotion_inside_bb(self, openstack_obj, big_vm_name_uuid,
                          free_node_name, data):

        # details about vm and  free node
        vm = self.find_server(big_vm_name_uuid)
        # if vm not found on vcenter return
        vhost = self.get_object_by_name(vim.HostSystem, free_node_name)
        log.info(
            "INFO:  vmotion of instance uuid %s started to target node %s",
            big_vm_name_uuid, free_node_name)

        # capture the status of server
        # check metadata and lock if exist
        loc_check = openstack_obj.api.compute.get_server(big_vm_name_uuid)
        # if vm not found on vcenter return
        log.info("INFO: instance uuid %s lock status %s", big_vm_name_uuid,
                 loc_check['is_locked'])

        # setting metadata and lock for nanny
        openstack_obj.api.compute.set_server_metadata(big_vm_name_uuid,
                                                      nanny_metadata=data)
        openstack_obj.api.compute.lock_server(big_vm_name_uuid)
        loc_check = openstack_obj.api.compute.get_server(big_vm_name_uuid)
        log.info("INFO: instance uuid %s lock status set by nanny %s",
                 big_vm_name_uuid, loc_check['is_locked'])

        # actual vmotion step
        spec = vim.VirtualMachineRelocateSpec()
        spec.host = vhost
        task = vm.RelocateVM_Task(spec)
        try:
            state = WaitForTask(task, si=self.api)
        except Exception as e:
            log.error(
                "ERROR: failed to relocate big vm %s to target node %s with error message =>%s",
                str(big_vm_name_uuid), str(free_node_name), str(e.msg))
            state = "Vmotion_failed"
        else:
            log.info(
                "INFO: vmotion done big vm %s to target node %s and state %s",
                str(big_vm_name_uuid), str(free_node_name), str(state))

        # if result failed through alert
        # unlock the server and unset nanny metadata
        openstack_obj.api.compute.unlock_server(big_vm_name_uuid)
        openstack_obj.api.compute.delete_server_metadata(
            big_vm_name_uuid, ['nanny_metadata'])

        # check unlock succesfully done
        unloc_check = openstack_obj.api.compute.get_server(big_vm_name_uuid)
        log.info("INFO: instance uuid %s unlock status %s done",
                 big_vm_name_uuid, unloc_check['is_locked'])

        return state
Exemple #10
0
def main():

    # connection for vm
    nanny_metadata_handle = "nanny_big_vm_handle"
    openstack_obj = OpenstackHelper(os.getenv('REGION'), os.getenv('OS_USER_DOMAIN_NAME'),
                                    os.getenv('OS_PROJECT_DOMAIN_NAME'),os.getenv('OS_PROJECT_NAME'),
                                    os.getenv('OS_USERNAME'), os.getenv('OS_PASSWORD'))

    vc = VCenterHelper(host=os.getenv('VM_BALANCE_VCHOST'),user=os.getenv('VM_BALANCE_VCUSER'),password=os.getenv('VM_BALANCE_VCPASSWORD'))

    big_vm_name_uuid = input("Enter BIG VM Instance UUID: ")
    # details about vm and  free node
    vm = vc.find_server(big_vm_name_uuid)
    free_node_name = input("Enter Free Node name like(node*-bb*.cc.*-*-*.cloud.sap):")
    vhost = vc.get_object_by_name(vim.HostSystem,free_node_name)
    log.info("INFO:  vmotion of instance uuid %s started to target node %s",big_vm_name_uuid,free_node_name)

    # capture the status of server
    # check metadata and lock if exist
    loc_check = openstack_obj.api.compute.get_server(big_vm_name_uuid)
    log.info("INFO: instance uuid %s lock status %s", big_vm_name_uuid, loc_check['is_locked'])

    # setting metadata and lock for nanny
    metadata_check = openstack_obj.api.compute.set_server_metadata(big_vm_name_uuid, nanny_metadata=nanny_metadata_handle)
    loc = openstack_obj.api.compute.lock_server(big_vm_name_uuid)
    loc_check = openstack_obj.api.compute.get_server(big_vm_name_uuid)
    log.info("INFO: instance uuid %s lock status set by nanny %s", big_vm_name_uuid, loc_check['is_locked'])

    # actual vmotion step
    spec = vim.VirtualMachineRelocateSpec()
    spec.host = vhost
    task = vm.RelocateVM_Task(spec)
    try:
        state = WaitForTask(task,si=vc.api)
    except Exception as e:
        logging.error("ERROR: failed to relocate big vm %s to target node %s with error message =>%s",
                      str(big_vm_name_uuid),str(free_node_name),str(e.msg))
        state = "VMotion_failed"
    else:
        log.info("INFO: vmotion done big vm %s to target node %s and state %s",str(big_vm_name_uuid),str(free_node_name),str(state))

    # if result failed through alert
    # unlock the server and unset nanny metadata
    unloc = openstack_obj.api.compute.unlock_server(big_vm_name_uuid)
    metadata_check = openstack_obj.api.compute.delete_server_metadata(big_vm_name_uuid,['nanny_metadata'])

    # check unlock succesfully done
    unloc_check = openstack_obj.api.compute.get_server(big_vm_name_uuid)
    log.info("INFO: instance uuid %s unlock status %s done", big_vm_name_uuid, unloc_check['is_locked'])
    return state
def do_a_vmotion(vm_obj, host, pingaddr, verbose=False):
    """
    do one repetition of a vmotion.

    Ping the pingaddr,
    migrate the vm
    Ping the pingaddr
    raising exceptions on any failure

    vm_obj - vm object
    host - host object
    pingaddr - the dns or ip to ping.
    """

    spec = vim.VirtualMachineRelocateSpec()
    spec.host = host

    if verbose:
        print('*** Preparing to move VM: ' + vm_obj.name +
              ' to host: %s' % host.name)

    if ping(pingaddr):
        if verbose:
            print('*** We have initial pings - moving to host: %s' % host.name)
            print('*** VMotion to host %s now' % host.name)
        task = vm_obj.RelocateVM_Task(spec)
    else:
        raise Exception('Pre-VMotion Ping Failed')

    if wait_for_task(task, verbose):
        if verbose:
            print("*** VMotion succeeded")
    else:
        raise Exception("VMotion task failed")

    if verbose:
        print("*** Sleeping 5 seconds to let things settle.")
    time.sleep(5)

    if ping(pingaddr):
        if verbose:
            print('*** Success, we have ping post VMotion to %s' % host.name)
    else:
        raise Exception('Post-VMotion Ping Failed')
def relocate_vm(vm_name, content, host_dest, datastore_dest=None):
    relocation_status = False
    try:
        vm = get_object(content, [vim.VirtualMachine], vm_name)
        current_host = vm.runtime.host.name
        spec = vim.VirtualMachineRelocateSpec()
        if host_dest is not None:
            if current_host == host_dest:
                raise Exception("WARNING:: destination_host can not equal "
                                "current_host")
            destination_host = get_object(content, [vim.HostSystem], host_dest)
            spec.host = destination_host
            target_esx_host = destination_host.parent.resourcePool
            spec.pool = target_esx_host
        if datastore_dest is not None:
            template_disks = collect_template_disks(vm)
            datastore_dest_id = get_object(content, [vim.Datastore],
                                           datastore_dest)
            spec.datastore = datastore_dest_id
            spec.disk = construct_locator(template_disks, datastore_dest_id)
        else:
            objview = content.viewManager.CreateContainerView(
                content.rootFolder, [vim.HostSystem], True)
            esxi_hosts = objview.view
            objview.Destroy()
            for esxi_host in esxi_hosts:
                if esxi_host.name == host_dest:
                    storage_system = esxi_host.configManager.storageSystem
                    host_file_sys_vol_mount_info = storage_system.fileSystemVolumeInfo.mountInfo
                    datastore = host_file_sys_vol_mount_info[0].volume.name
                    datastore = get_object(content, [vim.Datastore], datastore)
                    template_disks = collect_template_disks(vm)
                    spec.datastore = datastore
                    spec.disk = construct_locator(template_disks, datastore)
                    break
        task = vm.RelocateVM_Task(spec)
        wait_for_task(task)
    except Exception as e:
        print(
            "Relocation failed for vm:", vm_name, " with error:", str(e),
            ".\nHost or VM doesn't exist or Vm is already in the mentioned host."
        )
        return -1
Exemple #13
0
def clone(
    content,
    template,
    name,
    pool,
    folder,
    datastore,
):

    vm_mor = get_object(content, vim.VirtualMachine, template)
    if vm_mor is None:
        logger.error(u'VirtualMachine %s not found' % template)
        return None

    pool_mor = get_object(content, vim.ResourcePool, pool)
    if pool_mor is None:
        logger.error(u'ResourcePoll %s not found' % pool)
        return None

    folder_mor = get_object(content, vim.Folder, folder)
    if folder_mor is None:
        loggeer.error(u'Folder %s not found' % folder)
        return None

    datastore_mor = get_object(content, vim.Datastore, datastore)
    if datastore_mor is None:
        logger.error(u'Datastore %s not found' % datastore)
        return None

    r_spec = vim.VirtualMachineRelocateSpec()
    c_spec = vim.VirtualMachineCloneSpec()

    r_spec.pool = pool_mor
    r_spec.datastore = datastore_mor

    c_spec.location = r_spec
    c_spec.powerOn = True

    # TODO: zvazit alternativne riesenie cez metodu vm_mor.Clone
    return vm_mor.CloneVM_Task(name=name, folder=folder_mor, spec=c_spec)
Exemple #14
0
def v_motion_handler(logger, si, template_vm, host_mor, ds_mor):
    """
    Will handle the thread handling migration of virtual machine and run post processing
    """

    #time.sleep(10) # Sleep Introduced to trigger Host Collection Stats

    if ds_mor is None:
        logger.info("No Datastore specified. Doing only Compute vMotion")

    try:

        vm_name = template_vm.name

        vm_relocate_spec = vim.VirtualMachineRelocateSpec()
        vm_relocate_spec.host = host_mor

        resource_pool = host_mor.parent.resourcePool

        vm_relocate_spec.pool = resource_pool

        if ds_mor:
            template_disks = Propertycollector.collect_template_disks(
                template_vm)
            vm_relocate_spec.datastore = ds_mor
            vm_relocate_spec.disk = Propertycollector.construct_locator(
                template_disks, ds_mor)
            print("VM %s Host %s DS %s" % (template_vm, host_mor, ds_mor))

        logger.info("Initiating Migration of %s" % vm_name)

        task = template_vm.RelocateVM_Task(vm_relocate_spec)

        #task_results.append(task_pool.apply_async(TaskAnalyzer.Analyze,(logger,si,vm_name,task)))
        TaskAnalyzer.Analyze(logger, si, vm_name, task)

    except vmodl.MethodFault, e:
        logger.error("Caught vmodl fault: %s" % e.msg)
Exemple #15
0
def main():
    global dc_to_check, dc_limit, dc_target, bad_stor_exist, dc_dest, vm_to

    if args.verbose:
        sys.stdout.write("Connect to VMWare ... ")
        sys.stdout.flush()

    context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
    if args.disable_ssl_verification:
        context.verify_mode = ssl.CERT_NONE

    si = SmartConnect(host=args.host,
                      user=args.user,
                      pwd=args.password,
                      port=args.port,
                      sslContext=context)
    # disconnect vc
    atexit.register(Disconnect, si)
    if args.verbose:
        print "Connected!"
    content = si.RetrieveContent()

    datacenter = content.rootFolder.childEntity[0]
    datastores = datacenter.datastore

    if args.name:
        dc_to_check = args.name

    if args.target:
        dc_target = args.target

    if args.destination:
        dc_dest = args.destination

    if args.limit:
        dc_limit = int(args.limit)

    #ds_collect(datastores)

    ds_list = []

    need_free = 0

    for ds in datastores:
        if dc_to_check in ds.summary.name:
            ds_list.append(ds)
            if args.verbose:
                print "Found %s" % ds.summary.name

    for i, ds in enumerate(ds_list):
        need_perc = dc_limit - (
            (ds.summary.freeSpace * 100) / ds.summary.capacity) + 1
        need_free = (ds.summary.capacity / 100) * need_perc
        if (need_perc > 0):
            print "%s need to free %s" % (ds.summary.name,
                                          sizeof_fmt(need_free))
            bad_stor_exist = True
            # now try to find stor with free space
            for n, vl in enumerate(ds_list):
                # calculate, how many space left if we push
                c = vl.summary.freeSpace - need_free
                p = (c * 100) / vl.summary.capacity
                if (p > dc_limit):
                    if args.verbose:
                        print "%s will have %s%% free. good" % (
                            vl.summary.name, p)
                    if dc_dest in vl.summary.name:
                        ds_from.append(ds)
                        ds_to.append(vl)
                        ds_to_free.append(p)
                        if args.verbose:
                            print "Can move %s -> %s" % (ds.summary.name,
                                                         vl.summary.name)
                    else:
                        if args.verbose:
                            print "Cannot %s /> %s (banned by destination)" % (
                                ds.summary.name, vl.summary.name)
                else:
                    if args.verbose:
                        print "%s not suitable %s%%<%s%% bad" % (
                            vl.summary.name, p, dc_limit)
                # ok, now we need to collect VM files

    if bad_stor_exist == True:
        print "Found %s possible relocations" % len(ds_from)
        if len(ds_from) == 0:
            print "ALERT! Lack of space. Do handjob quickly ..."
            return  # noting to do
        # ok, lets choice which stor
        ch_n = 0
        ch_p = 0
        for i, fr in enumerate(ds_from):
            print "Can migrate %s -> %s" % (fr.summary.name,
                                            ds_to[i].summary.name)
            if ds_to_free[i] > ch_p:
                ch_n = i
                ch_p = ds_to_free[i]
        print "OK, lets move from %s to %s (%s%% free will be after move)" % (
            ds_from[ch_n].summary.name, ds_to[ch_n].summary.name, ch_p)
        # now select VM to move.
        print "Try to find possible VM to move"

        np = dc_limit - ((ds_from[ch_n].summary.freeSpace * 100) /
                         ds_from[ch_n].summary.capacity) + 1
        nf = (ds_from[ch_n].summary.capacity / 100) * np

        for i, vm in enumerate(ds_from[ch_n].vm):
            s = 0
            for t in vm.layoutEx.file:
                s = s + t.size

            if dc_target in vm.summary.config.name:
                if args.verbose:
                    print "Can take %s (%s)" % (vm.summary.config.name,
                                                sizeof_fmt(s))
                # collect enougth VM to move
                if nf > 0:
                    vm_to.append(vm)
                    nf = nf - s
            else:
                if args.verbose:
                    print "Cannot take %s (banned by target) %s " % (
                        vm.summary.config.name, sizeof_fmt(s))
        if len(vm_to) == 0:
            print "ALERT! Ooops, cannot find VM to move. Abort"
            return

        for i, vm in enumerate(vm_to):
            print "Ok, Final. Move %s from %s to %s " % (
                vm.summary.config.name, ds_from[ch_n].summary.name,
                ds_to[ch_n].summary.name)
            # https://gist.github.com/rgerganov/12fdd2ded8d80f36230f
            # vm = vim.VirtualMachine(vm.summary.config.name, si._stub)

            disk_key = []
            disk_filekey = []
            # collect info about key - filekey and grab only one part or pair (vmdk, -flat.vmdk)
            for t in vm.layoutEx.disk:
                disk_key.append(t.key)
                disk_filekey.append(t.chain[0].fileKey[0])
                #print "DISK ", t.key, t.chain[0].fileKey[0]
            # check disk for moving
            for t in vm.layoutEx.file:
                #print "Check %s " % t.name
                if ds_from[
                        ch_n].summary.name in t.name:  # ok this file on bad store, move
                    for i, j in enumerate(disk_filekey):
                        # print "compare %s %s" % (j,t.key)
                        if j == t.key:
                            spec = vim.VirtualMachineRelocateSpec()

                            dsk = vim.VirtualMachineRelocateSpecDiskLocator()

                            print "Move %s queue" % t.name
                            dsk.datastore = ds_to[ch_n]
                            dsk.diskId = disk_key[i]
                            spec.disk.append(dsk)
                            task = vm.RelocateVM_Task(spec)
                            wait_for_task(task)

                else:
                    print "%s already moved" % t.name

    else:
        print "All look seems to be in order. Have a nice day!"
Exemple #16
0
    def _clone(self, destination, resourcepool=None, datastore=None, power_on=True,
               sparse=False, template=False, provision_timeout=1800, progress_callback=None,
               allowed_datastores=None, cpu=None, ram=None, **kwargs):
        """
        Clone this template to a VM

        Returns a VMWareVirtualMachine object
        """
        try:
            vm = self.system.get_vm(destination)
        except VMInstanceNotFound:
            vm = None
        if vm:
            raise Exception("VM/template of the name {} already present!".format(destination))

        if progress_callback is None:
            progress_callback = partial(
                self._progress_log_callback, self.logger, self.name, destination)

        source_template = self.raw

        vm_clone_spec = vim.VirtualMachineCloneSpec()
        vm_reloc_spec = vim.VirtualMachineRelocateSpec()
        # DATASTORE
        if isinstance(datastore, six.string_types):
            vm_reloc_spec.datastore = self.system.get_obj(vim.Datastore, name=datastore)
        elif isinstance(datastore, vim.Datastore):
            vm_reloc_spec.datastore = datastore
        elif datastore is None:
            if allowed_datastores is not None:
                # Pick a datastore by space
                vm_reloc_spec.datastore = self._pick_datastore(allowed_datastores)
            else:
                # Use the same datastore
                datastores = source_template.datastore
                if isinstance(datastores, (list, tuple)):
                    vm_reloc_spec.datastore = datastores[0]
                else:
                    vm_reloc_spec.datastore = datastores
        else:
            raise NotImplementedError("{} not supported for datastore".format(datastore))
        progress_callback("Picked datastore `{}`".format(vm_reloc_spec.datastore.name))

        # RESOURCE POOL
        if isinstance(resourcepool, vim.ResourcePool):
            vm_reloc_spec.pool = resourcepool
        else:
            vm_reloc_spec.pool = self._get_resource_pool(resourcepool)
        progress_callback("Picked resource pool `{}`".format(vm_reloc_spec.pool.name))

        vm_reloc_spec.host = None
        if sparse:
            vm_reloc_spec.transform = vim.VirtualMachineRelocateTransformation().sparse
        else:
            vm_reloc_spec.transform = vim.VirtualMachineRelocateTransformation().flat

        vm_clone_spec.powerOn = power_on
        vm_clone_spec.template = template
        vm_clone_spec.location = vm_reloc_spec
        vm_clone_spec.snapshot = None

        if cpu is not None:
            vm_clone_spec.config.numCPUs = int(cpu)
        if ram is not None:
            vm_clone_spec.config.memoryMB = int(ram)

        try:
            folder = source_template.parent.parent.vmParent
        except AttributeError:
            folder = source_template.parent
        progress_callback("Picked folder `{}`".format(folder.name))

        task = source_template.CloneVM_Task(folder=folder, name=destination, spec=vm_clone_spec)

        def _check(store=[task]):
            try:
                if hasattr(store[0].info, 'progress') and store[0].info.progress is not None:
                    progress_callback("{}/{}%".format(store[0].info.state, store[0].info.progress))
                else:
                    progress_callback("{}".format(store[0].info.state))
            except AttributeError:
                pass
            if store[0].info.state not in {"queued", "running"}:
                return True
            store[0] = self.system.get_updated_obj(store[0])
            return False

        wait_for(_check, num_sec=provision_timeout, delay=4)

        if task.info.state != 'success':
            self.logger.error(
                "Clone VM from VM/template '%s' failed: %s",
                self.name, get_task_error_message(task)
            )
            raise VMInstanceNotCloned(destination)
        if template:
            entity_cls = VMWareTemplate
        else:
            entity_cls = VMWareVirtualMachine
        return entity_cls(system=self.system, name=destination)
Exemple #17
0
def main():
    parser = argparse.ArgumentParser(description='vCenter login')
    parser.add_argument('-s',
                        '--host',
                        required=True,
                        action='store',
                        help='vSphere IP')
    parser.add_argument('-o',
                        '--port',
                        type=int,
                        default=443,
                        action='store',
                        help='vSphere Port')
    parser.add_argument('-u',
                        '--user',
                        required=True,
                        action='store',
                        help='User name')
    parser.add_argument('-p',
                        '--password',
                        required=True,
                        action='store',
                        help='Password')
    parser.add_argument('-n',
                        '--name',
                        required=True,
                        action='store',
                        help='VM name')
    parser.add_argument('-q',
                        '--resourcepool',
                        required=True,
                        action='store',
                        help='ResourcePool name')
    parser.add_argument('-d',
                        '--datastore',
                        required=False,
                        action='store',
                        help='Datastore name')
    args = parser.parse_args()

    try:
        service_instance = connect.SmartConnect(host=args.host,
                                                user=args.user,
                                                pwd=args.password,
                                                port=int(args.port))
        atexit.register(connect.Disconnect, service_instance)

        content = service_instance.content
        objView = content.viewManager.CreateContainerView(
            content.rootFolder, [vim.VirtualMachine], True)
        vmlist = objView.view
        objView.Destroy()

        for vm in vmlist:
            if vm.name == args.name:
                #print vm.name
                spec = vim.VirtualMachineRelocateSpec()

                for respool in libvmtask.get_vim_objects(
                        content, vim.ResourcePool):
                    if respool.name == args.resourcepool:
                        resourcepool = respool

                if not resourcepool:
                    sys.exit(0)
                spec.pool = resourcepool

                if args.datastore:
                    for ds in libvmtask.get_vim_objects(
                            content, vim.Datastore):
                        if ds.name == args.datastore:
                            spec.datastore = ds

                #print spec
                task = vm.RelocateVM_Task(spec)
                libvmtask.WaitForTasks([task], service_instance)

        return 0

    except vmodl.MethodFault as error:
        print("ERROR: " + error.msg)
        sys.exit(1)