def create_vm(conn, vmtype, vmname, zone, vmdisk_size, vmcpus, vmnic, vmnetwork, vmmem, vmdisk_alloc, sdomain, vmcores, vmos, vmdisk_int):
    if vmdisk_alloc == 'thin':
        # define VM params
        vmparams = params.VM(name=vmname,cluster=conn.clusters.get(name=zone),os=params.OperatingSystem(type_=vmos),template=conn.templates.get(name="Blank"),memory=1024 * 1024 * int(vmmem),cpu=params.CPU(topology=params.CpuTopology(cores=int(vmcores))), type_=vmtype)
        # define disk params
        vmdisk= params.Disk(size=1024 * 1024 * 1024 * int(vmdisk_size), wipe_after_delete=True, sparse=True, interface=vmdisk_int, type_="System", format='cow',
        storage_domains=params.StorageDomains(storage_domain=[conn.storagedomains.get(name=sdomain)]))
        # define network parameters
        network_net = params.Network(name=vmnetwork)
        nic_net1 = params.NIC(name='nic1', network=network_net, interface='virtio')
    elif vmdisk_alloc == 'preallocated':
        # define VM params
        vmparams = params.VM(name=vmname,cluster=conn.clusters.get(name=zone),os=params.OperatingSystem(type_=vmos),template=conn.templates.get(name="Blank"),memory=1024 * 1024 * int(vmmem),cpu=params.CPU(topology=params.CpuTopology(cores=int(vmcores))) ,type_=vmtype)
        # define disk params
        vmdisk= params.Disk(size=1024 * 1024 * 1024 * int(vmdisk_size), wipe_after_delete=True, sparse=False, interface=vmdisk_int, type_="System", format='raw',
        storage_domains=params.StorageDomains(storage_domain=[conn.storagedomains.get(name=sdomain)]))
        # define network parameters
        network_net = params.Network(name=vmnetwork)
        nic_net1 = params.NIC(name=vmnic, network=network_net, interface='virtio')
        
    try:
        conn.vms.add(vmparams)
    except:
        print "Error creating VM with specified parameters"
        sys.exit(1)
    vm = conn.vms.get(name=vmname)
    try:
        vm.disks.add(vmdisk)
    except:
        print "Error attaching disk"
    try:
        vm.nics.add(nic_net1)
    except:
        print "Error adding nic"
def add_blank_vms(api):
    vm_memory = 256 * MB
    vm_params = params.VM(
        memory=vm_memory,
        os=params.OperatingSystem(type_='other_linux', ),
        type_='server',
        high_availability=params.HighAvailability(enabled=False, ),
        cluster=params.Cluster(name=TEST_CLUSTER, ),
        template=params.Template(name=TEMPLATE_BLANK, ),
        display=params.Display(
            smartcard_enabled=True,
            keyboard_layout='en-us',
            file_transfer_enabled=True,
            copy_paste_enabled=True,
        ),
        memory_policy=params.MemoryPolicy(guaranteed=vm_memory / 2, ),
        name=VM0_NAME)
    for vm in [VM0_NAME, VM2_NAME, BACKUP_VM_NAME]:
        vm_params.name = vm
        if vm == VM2_NAME:
            vm_params.high_availability.enabled = True
            vm_params.custom_emulated_machine = 'pc-i440fx-rhel7.4.0'

        api.vms.add(vm_params)
        testlib.assert_true_within_short(
            lambda: api.vms.get(vm).status.state == 'down', )
Exemple #3
0
def add_vm_blank(api):
    vm_memory = 256 * MB
    vm_params = params.VM(
        memory=vm_memory,
        os=params.OperatingSystem(type_='other_linux', ),
        type_='server',
        high_availability=params.HighAvailability(enabled=False, ),
        cluster=params.Cluster(name=TEST_CLUSTER, ),
        template=params.Template(name=TEMPLATE_BLANK, ),
        display=params.Display(
            smartcard_enabled=True,
            keyboard_layout='en-us',
            file_transfer_enabled=True,
            copy_paste_enabled=True,
        ),
        memory_policy=params.MemoryPolicy(guaranteed=vm_memory / 2, ),
        name=VM0_NAME)
    api.vms.add(vm_params)
    testlib.assert_true_within_short(
        lambda: api.vms.get(VM0_NAME).status.state == 'down', )
    vm_params.name = VM2_NAME
    vm_params.high_availability.enabled = True
    api.vms.add(vm_params)
    testlib.assert_true_within_short(
        lambda: api.vms.get(VM2_NAME).status.state == 'down', )
Exemple #4
0
def add_vm_template(api):
    #TODO: Fix the exported domain generation.
    #For the time being, add VM from Glance imported template.
    if api.templates.get(name=TEMPLATE_CIRROS) is None:
        raise SkipTest('%s: template %s not available.' % (add_vm_template.__name__, TEMPLATE_CIRROS))

    vm_memory = 512 * MB
    vm_params = params.VM(
        name=VM1_NAME,
        description='CirrOS imported from Glance as Template',
        memory=vm_memory,
        cluster=params.Cluster(
            name=TEST_CLUSTER,
        ),
        template=params.Template(
            name=TEMPLATE_CIRROS,
        ),
        display=params.Display(
            type_='vnc',
        ),
        memory_policy=params.MemoryPolicy(
            guaranteed=vm_memory / 2,
            ballooning=False,
        ),
        os=params.OperatingSystem(
            type_='other_linux',
        ),
        timezone='Etc/GMT',
        type_='server',
        serial_number=params.SerialNumber(
            policy='custom',
            value='12345678',
        ),
        cpu=params.CPU(
            architecture='X86_64',
            topology=params.CpuTopology(
                cores=1,
                threads=2,
                sockets=1,
            ),
        ),
    )
    api.vms.add(vm_params)
    testlib.assert_true_within_long(
        lambda: api.vms.get(VM1_NAME).status.state == 'down',
    )
    disk_name = api.vms.get(VM1_NAME).disks.list()[0].name
    testlib.assert_true_within_long(
        lambda:
        api.vms.get(VM1_NAME).disks.get(disk_name).status.state == 'ok'
    )
Exemple #5
0
def CreateVm(vm_name, vm_type, vm_mem, vm_cluster, vm_template):
    vm_params = params.VM(
        name=vm_name,
        memory=vm_mem * MB,
        cluster=api.clusters.get(name=vm_cluster),
        template=api.templates.get(name=vm_template),
        os=params.OperatingSystem(boot=[params.Boot(dev="hd")]))
    vm_params.set_type(vm_type)

    try:
        api.vms.add(vm=vm_params)
        print "Virtual machine '%s' added." % vm_name
    except Exception as ex:
        print "Adding virtual machine '%s' failed: %s" % (vm_name, ex)
Exemple #6
0
 def createVM(self, name, cluster, os, actiontype):
     try:
         vmparams = params.VM(
             name=name,
             cluster=self.conn.clusters.get(name=cluster),
             os=params.OperatingSystem(type_=os),
             template=self.conn.templates.get(name="Blank"),
             type_=actiontype
         )
         self.conn.vms.add(vmparams)
         setMsg("VM is created")
         setChanged()
         return True
     except Exception as e:
         setMsg("Failed to create VM")
         setMsg(str(e))
         setFailed()
         return False
Exemple #7
0
    def __new_vm_base(self, name, template, ram):
        memory = 1024**3 * ram  # convert from bytes to GB
        cluster = self.__entrypoint().clusters.get(name='Default')
        template = self.__entrypoint().templates.get(name=template)
        os = params.OperatingSystem(boot=[params.Boot(dev='hd')])

        vm_params = params.VM(name=name,
                              memory=memory,
                              cluster=cluster,
                              template=template,
                              os=os,
                              type_='Server')

        try:
            self.__entrypoint().vms.add(vm=vm_params)
            print('added vm %s' % name)

        except Exception as ex:
            print('Unexpected error: %s' % ex)
Exemple #8
0
from ovirtsdk.api import API
from ovirtsdk.xml import params

try:
    api = API (url="https://_HOST_",
               username="******",
               password="******",
               ca_file="_ca.crt_")

    vm_name = "vm1"
    vm_memory = 512 * 1024 * 1024
    vm_cluster = api.clusters.get(name="Default")
    vm_template = api.templates.get(name="Blank")
    vm_os = params.OperatingSystem(boot=[params.Boot(dev="hd")])

    vm_params = params.VM(name=vm_name,
                         memory=vm_memory,
                         cluster=vm_cluster,
                         template=vm_template,
                         os=vm_os)

    try:
        api.vms.add(vm=vm_params)
        print "Virtual machine '%s' added." % vm_name
    except Exception as ex:
        print "Adding virtual machine '%s' failed: %s" % (vm_name, ex)

    api.disconnect()

except Exception as ex:
print "Unexpected error: %s" % ex
    def create(self,
               name,
               clu,
               numcpu,
               numinterfaces,
               netinterface,
               diskthin1,
               disksize1,
               diskinterface,
               memory,
               storagedomain,
               guestid,
               net1,
               net2=None,
               net3=None,
               net4=None,
               mac1=None,
               mac2=None,
               launched=True,
               iso=None,
               diskthin2=None,
               disksize2=None,
               vnc=False):
        boot1, boot2 = 'hd', 'network'
        if iso in ["", "xx", "yy"]:
            iso = None
        if iso:
            boot2 = 'cdrom'
        api = self.api
        memory = memory * MB
        disksize1 = disksize1 * GB
        if disksize2:
            disksize2 = disksize2 * GB
        #VM CREATION IN OVIRT
        #TODO check that clu and storagedomain exist and that there is space there
        diskformat1, diskformat2 = 'raw', 'raw'
        sparse1, sparse2 = False, False
        if diskthin1:
            diskformat1 = 'cow'
            sparse1 = True
        if disksize2 and diskthin2:
            diskformat2 = 'cow'
            sparse2 = True
        vm = api.vms.get(name=name)
        if vm:
            return "VM %s allready existing.Leaving...\n" % name
        clu = api.clusters.get(name=clu)
        storagedomain = api.storagedomains.get(name=storagedomain)
        try:
            disk1 = params.Disk(storage_domains=params.StorageDomains(
                storage_domain=[storagedomain]),
                                name="%s_Disk1" % (name),
                                size=disksize1,
                                type_='system',
                                status=None,
                                interface=diskinterface,
                                format=diskformat1,
                                sparse=sparse1,
                                bootable=True)
            disk1 = api.disks.add(disk1)
            disk1id = disk1.get_id()
        except:
            return "Insufficient space in storage domain for disk1.Leaving...\n"
        if disksize2:
            try:
                disk2 = params.Disk(storage_domains=params.StorageDomains(
                    storage_domain=[storagedomain]),
                                    name="%s_Disk2" % (name),
                                    size=disksize2,
                                    type_='system',
                                    status=None,
                                    interface=diskinterface,
                                    format=diskformat2,
                                    sparse=sparse2,
                                    bootable=False)
                disk2 = api.disks.add(disk2)
                disk2id = disk2.get_id()
            except:
                return "Insufficient space in storage domain for disk2.Leaving...\n"

        #boot order
        boot = [params.Boot(dev=boot1), params.Boot(dev=boot2)]
        #vm creation
        kernel, initrd, cmdline = None, None, None
        if vnc:
            display = params.Display(type_='vnc')
        else:
            display = params.Display(type_='spice')
        api.vms.add(
            params.VM(
                name=name,
                memory=memory,
                cluster=clu,
                display=display,
                template=api.templates.get('Blank'),
                os=params.OperatingSystem(type_=guestid,
                                          boot=boot,
                                          kernel=kernel,
                                          initrd=initrd,
                                          cmdline=cmdline),
                cpu=params.CPU(topology=params.CpuTopology(cores=numcpu)),
                type_="server"))
        #add nics
        api.vms.get(name).nics.add(
            params.NIC(name='eth0',
                       network=params.Network(name=net1),
                       interface=netinterface))

        if numinterfaces >= 2:
            api.vms.get(name).nics.add(
                params.NIC(name='eth1',
                           network=params.Network(name=net2),
                           interface=netinterface))
            #compare eth0 and eth1 to get sure eth0 has a lower mac
            eth0ok = True
            maceth0 = api.vms.get(name).nics.get(name="eth0").mac.address
            maceth1 = api.vms.get(name).nics.get(name="eth1").mac.address
            eth0 = maceth0.split(":")
            eth1 = maceth1.split(":")
            for i in range(len(eth0)):
                el0 = int(eth0[i], 16)
                el1 = int(eth1[i], 16)
                if el0 == el1:
                    pass
                elif el0 > el1:
                    eth0ok = False

            if not eth0ok:
                tempnic = "00:11:11:11:11:11"
                nic = api.vms.get(name).nics.get(name="eth0")
                nic.mac.address = tempnic
                nic.update()
                nic = api.vms.get(name).nics.get(name="eth1")
                nic.mac.address = maceth0
                nic.update()
                nic = api.vms.get(name).nics.get(name="eth0")
                nic.mac.address = maceth1
                nic.update()

        if mac1:
            nic = api.vms.get(name).nics.get(name="eth0")
            if not ":" in mac1:
                mac1 = "%s%s" % (nic.mac.address[:-2], mac1)
            nic.mac.address = mac1
            nic.update()

        if mac2:
            nic = api.vms.get(name).nics.get(name="eth1")
            if not ":" in mac2:
                mac2 = "%s%s" % (nic.mac.address[:-2], mac2)
            nic.mac.address = mac2
            nic.update()

        if numinterfaces >= 3:
            api.vms.get(name).nics.add(
                params.NIC(name='eth2',
                           network=params.Network(name=net3),
                           interface=netinterface))
        if numinterfaces >= 4:
            api.vms.get(name).nics.add(
                params.NIC(name='eth3',
                           network=params.Network(name=net4),
                           interface=netinterface))
        api.vms.get(name).update()
        if iso:
            iso = checkiso(api, iso)
            cdrom = params.CdRom(file=iso)
            api.vms.get(name).cdroms.add(cdrom)
        while api.disks.get(id=disk1id).get_status().get_state() != "ok":
            time.sleep(5)
        api.vms.get(name).disks.add(disk1)
        while not api.vms.get(name).disks.get(id=disk1id):
            time.sleep(2)
        api.vms.get(name).disks.get(id=disk1id).activate()
        if disksize2:
            while api.disks.get(id=disk2id).get_status().get_state() != "ok":
                time.sleep(5)
            api.vms.get(name).disks.add(disk2)
            while not api.vms.get(name).disks.get(id=disk2id):
                time.sleep(2)
            api.vms.get(name).disks.get(id=disk2id).activate()
        #retrieve MACS for cobbler
        vm = api.vms.get(name=name)
        for nic in vm.nics.list():
            self.macaddr.append(nic.mac.address)
Exemple #10
0
def create_vm(vmprefix,disksize, storagedomain,network, vmcores,vmsockets,addstorage):
    print ("------------------------------------------------------")
    print ("Creating", num, "RHEV based virtual machines")
    print ("-------------------------------------------------------")
    for machine in range(0,int(num)):
        try:
            vm_name = str(vmprefix) + "_" + str(machine) + "_sockets_" + str(vmsockets)
            vm_memory = int(memory)*1024*1024*1024
            vm_cluster = api.clusters.get(name=cluster)
            vm_template = api.templates.get(name=vmtemplate)
            vm_os = params.OperatingSystem(boot=[params.Boot(dev="hd")])
            cpu_params = params.CPU(topology=params.CpuTopology(sockets=vmsockets,cores=vmcores))
            # set proper VM parameters - based on will VM be on "thin" disk or "preallocated" disk
            if vmdiskpreallocated == "yes":
                vm_params = params.VM(name=vm_name,memory=vm_memory,cluster=vm_cluster,template=vm_template,os=vm_os,cpu=cpu_params, disks=params.Disks(clone=True))
            elif vmdiskpreallocated == "no":
                vm_params = params.VM(name=vm_name,memory=vm_memory,cluster=vm_cluster, template=vm_template, os=vm_os,cpu=cpu_params)

            print ("creating virtual machine", vm_name)
            api.vms.add(vm=vm_params)
            api.vms.get(vm_name).nics.add(params.NIC(name=nicname, network=params.Network(name=network), interface='virtio'))
            # update vm and add disk to it
            wait_vm_state(vm_name,"down")
            print ("Virtual machine created: ", vm_name, "and it has parameters"," memory:", memory,"[GB]",
                   " cores:", vmcores,
                   " sockets", vmsockets,
                   " waiting on machine to unlock so we proceed with configuration")
            wait_vm_state(vm_name, "down")
            diskname = "disk_" + str(vmprefix) + str(machine)

            # if there is necessary to add additional disk to VM - can be preallocated or thin

            if addstorage == "yes" and diskpreallocated == "no":

                for disk in range(0,int(numdisks)):
                    # add one disk at time - one will be added by default - only add thin disks
                    api.vms.get(vm_name).disks.add(params.Disk(name=diskname + "_" + str(disk), storage_domains=params.StorageDomains(storage_domain=[api.storagedomains.get(name=storagedomain)]),
                                                           size=int(disksize)*1024*1024*1024,
                                                           status=None,
                                                           interface='virtio',
                                                           format='cow',
                                                           sparse=True,
                                                           bootable=False))
                    print ("Disk of size:",disksize,"GB originating from", storagedomain, "storage domain is attached to VM - but we cannot start machine before disk is in OK state"
                                                                                      " starting machine with disk attached to VM and same time having disk in Locked state will result in machine start failure")
                    wait_disk_state(diskname + "_" + str(disk) ,"ok")

                print ("Machine", vm_name, "is ready to be started")
                api.vms.get(vm_name).start()
                print ("Machine", vm_name, "started successfully, machine parameters are memory:",memory,"[GB]",
                       "cores:", vmcores,
                       " sockets", vmsockets,
                       " storage disk", disksize, "[GB]")


            elif addstorage == "yes" and diskpreallocated == "yes":

                for disk in range(0, int(numdisks)):
                    api.vms.get(vm_name).disks.add(params.Disk(name=diskname + "_" + str(disk) , storage_domains=params.StorageDomains(storage_domain=[api.storagedomains.get(name=storagedomain)]),
                                                           size=int(disksize)*1024*1024*1024,
                                                           status=None,
                                                           interface='virtio',
                                                           format='raw',
                                                           sparse=False,
                                                           bootable=False
                                                           ))
                    # if disk is not in "OK" state ... wait here - we cannot start machine if this is not the case
                    print ("Disk of size:",disksize,"GB originating from", storagedomain, "storage domain is attached to VM - but we cannot start machine before disk is in OK state"
                   " starting machine with disk attached to VM and same time having disk in Locked state will result in machine start failure")
                    wait_disk_state(diskname + "_" + str(disk) ,"ok")

                print ("Machine", vm_name, "is ready to be started")
                api.vms.get(vm_name).start()
                print ("Machine", vm_name, "started successfully, machine parameters are memory:",memory,"[GB]"
                   " cores:", vmcores,
                   " sockets", vmsockets,
                   " storage disk", disksize, "[GB]"
                       )

            elif addstorage == "no":
                print ("addstorage=no was specified for", vm_name,"no additional disk will be added, starting VM:", vm_name)
                api.vms.get(vm_name).start()

            print ("Machine", vm_name, "started successfully, machine parameters are memory:",memory,"[GB]"
                       "cores:", vmcores,
                       "sockets:", vmsockets,
                       "storage_disk", disksize, "[GB]"
                       )
        except Exception as e:
            print ("Adding virtual machine '%s' failed: %s", vm_name, e)
Exemple #11
0
def set_boot_order(vm):
    vm.set_os(params.OperatingSystem(boot=[params.Boot(dev='hd')]))
    vm.update()
Exemple #12
0
from ovirtsdk.xml import params
from rhev_functions import *

baseurl = "https://%s:%s" % (options.server, options.port)

api = API(url=baseurl, username=options.username, password=options.password, insecure=True)

try:
    value = api.hosts.list()
except:
    print "Error accessing RHEV-M api, please check data and connection and retry"
    sys.exit(1)

# Define VM based on parameters
if __name__ == "__main__":
    vmparams = params.VM(os=params.OperatingSystem(type_=options.osver), cpu=params.CPU(topology=params.CpuTopology(cores=int(options.vmcpu))), name=options.name, memory=1024 * 1024 * 1024 * int(options.vmmem), cluster=api.clusters.get(name=options.cluster), template=api.templates.get(name="Blank"), type_="server")
    vmdisk = params.Disk(size=1024 * 1024 * 1024 * int(options.sdsize), wipe_after_delete=True, sparse=True, interface="virtio", type_="System", format="cow", storage_domains=params.StorageDomains(storage_domain=[api.storagedomains.get(name="data_domain")]))
    vmnet = params.NIC()

    network_gest = params.Network(name=options.vmgest)
    network_serv = params.Network(name=options.vmserv)

    nic_gest = params.NIC(name='eth0', network=network_gest, interface='virtio')
    nic_serv = params.NIC(name='eth1', network=network_serv, interface='virtio')

    try:
        api.vms.add(vmparams)
    except:
        print "Error creating VM with specified parameters, recheck"
        sys.exit(1)
Exemple #13
0
def create(name,
           cluster_query=None,
           template_query='name=Blank',
           memory=2 * GiB,
           vcpus=2,
           disk_query=None,
           ostype='rhel_7x64',
           networks=None,
           show=None,
           headers='yes',
           ovirt=None):
    """
    Create a new oVirt VM

    :param str name:           The name of the VM to create
    :param str cluster_query:  A query to find the cluster to place the VM in,
                               if more then one cluster is found, the first one
                               is used
    :param str template_query: A query to find the template to use to create
                               the VM, if more then one template is found the
                               first one is used
    :param int memory:         The VM memory size (in bytes)
    :param ind vcpus:          The amount of vCPUs to assign to the VM
    :param str disk_query:     A query for disks to attach to the VM
    :param str ostype:         The OS type of the VM
    :param str networks:       A pipe (|) separated list of networks to attach
                               to the VM in the order they should be added, a
                               network can appear more then once. Only networks
                               that are attached to the VM`s cluster will be
                               added
    :param ovirtsdk.api.API ovirt: An open oVirt API connection

    The 'show' and 'headers' parameters are the same as for the 'query' task

    :returns: The VM that was created
    :rtype: ovirtsdk.infrastructure.brokers.VM
    """
    if cluster_query is None:
        # get the 2 top clusters so we'll issue a warning if there is more then
        # one and the user didn't specify an explicit selection query
        clusters = ovirt.clusters.list(max=2)
    else:
        clusters = ovirt.clusters.list(query=cluster_query)
    if not clusters:
        abort("No cluster found by given query")
    if len(clusters) > 1:
        warn("More then one cluster found, will use the first")
    cluster = clusters[0]
    templates = ovirt.templates.list(query=template_query)
    if not templates:
        abort("No template found by given query")
    if len(templates) > 1:
        warn("More then one tempalte found, will use the first")
    template = templates[0]
    vm = ovirt.vms.add(
        oVirtParams.VM(
            name=name,
            template=template,
            cluster=cluster,
            memory=int(memory),
            cpu=oVirtParams.CPU(topology=oVirtParams.CpuTopology(
                sockets=int(vcpus))),
            os=oVirtParams.OperatingSystem(type_=ostype),
        ))
    if disk_query is not None:
        disks = ovirt.disks.list(query=disk_query)
        for disk in disks:
            vm.disks.add(disk)
    if networks is not None:
        nic_name = ('nic{0}'.format(i) for i in count())
        for network_name in networks.split('|'):
            network = cluster.networks.get(name=network_name)
            if network is None:
                continue
            vm.nics.add(nic=oVirtParams.NIC(
                name=next(nic_name),
                network=network,
                linked=True,
            ))
    oVirtObjectType.all_types['vm'].print_table((vm, ),
                                                show=show,
                                                headers=headers)
    return vm
Exemple #14
0
baseurl = "https://%s:%s" % (options.server, options.port)

api = apilogin(url=baseurl,
               username=options.username,
               password=options.password)

try:
    value = api.hosts.list()
except:
    print "Error accessing RHEV-M api, please check data and connection and retry"
    sys.exit(1)

# Define VM based on parameters
if __name__ == "__main__":
    vmparams = params.VM(
        os=params.OperatingSystem(type_=options.osver),
        cpu=params.CPU(topology=params.CpuTopology(cores=int(options.vmcpu))),
        name=options.name,
        memory=1024 * 1024 * 1024 * int(options.vmmem),
        cluster=api.clusters.get(name=options.cluster),
        template=api.templates.get(name="Blank"),
        type_="server")
    vmdisk = params.Disk(
        size=1024 * 1024 * 1024 * int(options.sdsize),
        wipe_after_delete=True,
        sparse=True,
        interface="virtio",
        type_="System",
        format="cow",
        storage_domains=params.StorageDomains(
            storage_domain=[api.storagedomains.get(name="data_domain")]))