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 hotplug_nic(api): nic2_params = params.NIC( name='eth1', network=params.Network(name='ovirtmgmt', ), interface='virtio', ) api.vms.get(VM0_NAME).nics.add(nic2_params)
def add_nic(api): NIC_NAME = 'eth0' nic_params = params.NIC( name=NIC_NAME, interface='virtio', network=params.Network(name='ovirtmgmt', ), ) api.vms.get(VM0_NAME).nics.add(nic_params)
def hotplug_nic(prefix): api = prefix.virt_env.engine_vm().get_api() nic2_params = params.NIC( name='eth1', network=params.Network(name=VM_NETWORK, ), interface='virtio', ) api.vms.get(VM0_NAME).nics.add(nic2_params) assert_vm0_is_alive(prefix)
def execute(self, args): # Create NIC object c = self._api.clusters.get(args.cluster) cluster_net = c.networks.get(args.network) nic = params.NIC(name=args.iface, network=cluster_net) # Add network to VM vm = self._api.vms.get(args.name) result = vm.nics.add(nic)
def add(self, memory, disk_size, cluster_name, storage_name, nic_name='eth0', network_interface='virtio', network_name='ovirtmgmt', disk_interface='virtio', disk_format='raw', template_name='Blank'): """ Create VM with one NIC and one Disk. @memory: VM's memory size such as 1024*1024*1024=1GB. @disk_size: VM's disk size such as 512*1024=512MB. @nic_name: VM's NICs name such as 'eth0'. @network_interface: VM's network interface such as 'virtio'. @network_name: network such as ovirtmgmt for ovirt, rhevm for rhel. @disk_format: VM's disk format such as 'raw' or 'cow'. @disk_interface: VM's disk interface such as 'virtio'. @cluster_name: cluster name. @storage_name: storage domain name. @template_name: VM's template name, default is 'Blank'. """ # network name is ovirtmgmt for ovirt, rhevm for rhel. vm_params = param.VM(name=self.name, memory=memory, cluster=self.api.clusters.get(cluster_name), template=self.api.templates.get(template_name)) storage = self.api.storagedomains.get(storage_name) storage_params = param.StorageDomains(storage_domain=[storage]) nic_params = param.NIC(name=nic_name, network=param.Network(name=network_name), interface=network_interface) disk_params = param.Disk(storage_domains=storage_params, size=disk_size, type_='system', status=None, interface=disk_interface, format=disk_format, sparse=True, bootable=True) try: logging.info('Creating a VM %s' % self.name) self.api.vms.add(vm_params) logging.info('NIC is added to VM %s' % self.name) self.instance.nics.add(nic_params) logging.info('Disk is added to VM %s' % self.name) self.instance.disks.add(disk_params) logging.info('Waiting for VM to reach <Down> status ...') while self.state() != 'down': time.sleep(1) except Exception, e: logging.error('Failed to create VM with disk and NIC\n%s' % str(e))
def add_nic(api): NIC_NAME = 'eth0' nic_params = params.NIC( name=NIC_NAME, interface='virtio', network=params.Network(name='ovirtmgmt', ), ) api.vms.get(VM0_NAME).nics.add(nic_params) nic_params.mac = params.MAC(address=UNICAST_MAC_OUTSIDE_POOL) api.vms.get(VM2_NAME).nics.add(nic_params)
def add_profiles(vm, vmfex): for (profile_name, profile_id) in get_profiles(vmfex).items(): try: logging.info("Adding profile name: %s, id: %s", profile_name, profile_id) vm.nics.add( params.NIC(name=profile_name, description='', vnic_profile=params.VnicProfile(id=profile_id, ))) except Exception as e: # probably adding an existing vnic. Ignore this exception logging.exception(e)
def vm_run(prefix): api = prefix.virt_env.engine_vm().get_api() host_names = [h.name() for h in prefix.virt_env.host_vms()] start_params = params.Action( use_cloud_init=True, vm=params.VM( placement_policy=params.VmPlacementPolicy( host=params.Host( name=sorted(host_names)[0] ), ), initialization=params.Initialization( domain=params.Domain( name='lago.example.com' ), cloud_init=params.CloudInit( host=params.Host( address='VM0' ), users=params.Users( active=True, user=[params.User( user_name='root', password='******' )] ), network_configuration=params.NetworkConfiguration( nics=params.Nics( nic=[params.NIC( name='eth0', boot_protocol='STATIC', on_boot='True', network=params.Network( ip=params.IP( address='192.168.1.2.', netmask='255.255.255.0', gateway='192.168.1.1', ), ), )] ), ), ), ), ), ) api.vms.get(VM0_NAME).start(start_params) testlib.assert_true_within_short( lambda: api.vms.get(VM0_NAME).status.state == 'up', )
def run_vms(prefix): engine = prefix.virt_env.engine_vm() api = engine.get_api() vm_ip = '.'.join(engine.ip().split('.')[0:3] + ['199']) vm_gw = '.'.join(engine.ip().split('.')[0:3] + ['1']) host_names = [h.name() for h in prefix.virt_env.host_vms()] start_params = params.Action( use_cloud_init=True, vm=params.VM( placement_policy=params.VmPlacementPolicy( host=params.Host(name=sorted(host_names)[0]), ), initialization=params.Initialization( domain=params.Domain(name='lago.example.com'), cloud_init=params.CloudInit( host=params.Host(address='VM0'), users=params.Users(active=True, user=[ params.User(user_name='root', password='******') ]), network_configuration=params.NetworkConfiguration( nics=params.Nics(nic=[ params.NIC( name='eth0', boot_protocol='STATIC', on_boot=True, network=params.Network(ip=params.IP( address=vm_ip, netmask='255.255.255.0', gateway=vm_gw, ), ), ) ]), ), ), ), ), ) api.vms.get(VM0_NAME).start(start_params) api.vms.get(BACKUP_VM_NAME).start(start_params) start_params.vm.initialization.cloud_init = params.CloudInit( host=params.Host(address='VM2'), ) api.vms.get(VM2_NAME).start(start_params) testlib.assert_true_within_long( lambda: api.vms.get(VM0_NAME).status.state == 'up' and api.vms.get( BACKUP_VM_NAME).status.state == 'up', )
def __new_nic(self, name, network): vm = self.__entrypoint().vms.get(name=name) nic_name = 'eth1' nic_interface = 'virtio' nic_network = self.__entrypoint().networks.get(name=network) nic_params = params.NIC(name=nic_name, interface=nic_interface, network=nic_network) try: nic = vm.nics.add(nic_params) print('Network interface %s added to %s' % (nic.get_name(), vm.get_name())) except Exception as ex: print('Unexpected error: %s' % ex)
def vm_run_once(oe_api, vm_name, vm_password, vm_nic_info): """ vm run once with cloud-init """ try: if vm_name not in [vm_online.name for vm_online in oe_api.vms.list()]: print("[E] VM not found: {0}".format(vm_name)) return 1 elif vm_nic_info is None: print('[E] VM nic info is needed: "name_of_nic, ip_address, net_mask, gateway"') return 2 elif oe_api.vms.get(vm_name).status.state == 'down': print('[I] Starting VM with cloud-init.') p_host = params.Host(address="{0}".format(vm_name)) p_users = params.Users(user=[params.User(user_name="root", password=vm_password)]) vm_nic = [nic for nic in vm_nic_info.split(', ')] if len(vm_nic) != 4: print('[E] VM nic info need 4 args: "name_of_nic, ip_address, net_mask, gateway"') return 3 p_nic = params.Nics(nic=[params.NIC(name=vm_nic[0], boot_protocol="STATIC", on_boot=True, network=params.Network(ip=params.IP(address=vm_nic[1], netmask=vm_nic[2], gateway=vm_nic[3])))]) p_network = params.NetworkConfiguration(nics=p_nic) p_cloud_init = params.CloudInit(host=p_host, users=p_users, regenerate_ssh_keys=True, network_configuration=p_network) p_initialization = params.Initialization(cloud_init=p_cloud_init) vm_params = params.VM(initialization=p_initialization) vm_action = params.Action(vm=vm_params, use_cloud_init=True) oe_api.vms.get(vm_name).start(vm_action) print('[I] Waiting for VM to reach Up status... ', end='') while oe_api.vms.get(vm_name).status.state != 'up': print('.', end='') sleep(1) print('VM {0} is up!'.format(vm_name)) else: print('[E] VM already up.') except Exception as err: print('[E] Failed to Start VM with cloud-init: {0}'.format(str(err)))
def AddVmNic(vm_name, nic_name, nic_iface, nic_net, nic_mac): vm = api.vms.get(vm_name) nic_name = nic_name nic_interface = nic_iface nic_network = api.networks.get(name=nic_net) nic_params = params.NIC(name=nic_name, interface=nic_interface, network=nic_network) try: nic = vm.nics.add(nic_params) nic.mac.set_address(nic_mac) nic.update() print "Network interface '%s' added to '%s'." % (nic.get_name(), vm.get_name()) except Exception as ex: print "Adding network interface to '%s' failed: %s" % (vm.get_name(), ex)
def createNIC(self, vmname, nicname, vlan, interface): VM = self.get_VM(vmname) CLUSTER = self.get_cluster_byid(VM.cluster.id) DC = self.get_DC_byid(CLUSTER.data_center.id) newnic = params.NIC( name=nicname, network=DC.networks.get(name=vlan), interface=interface ) try: VM.nics.add(newnic) VM.update() setMsg("Successfully added iface " + nicname) setChanged() except Exception as e: setFailed() setMsg("Error attaching " + nicname + " iface, please recheck and remove any leftover configuration.") setMsg(str(e)) return False try: currentnic = VM.nics.get(name=nicname) attempt = 1 while currentnic.active is not True: currentnic = VM.nics.get(name=nicname) if attempt == 100: setMsg("Error, iface %s, state %s" % (nicname, str(currentnic.active))) raise Exception() else: attempt += 1 time.sleep(2) setMsg("The iface " + nicname + " is ready.") except Exception as e: setFailed() setMsg("Error getting the state of " + nicname + ".") setMsg(str(e)) return False return True
def createGuest(api,guest_cluster,guest_name,guest_description,guest_mem,guest_cpu,guest_disks_gb,guest_domain,guest_networks): cpu_params = params.CPU(topology=params.CpuTopology(cores=guest_cpu)) try: api.vms.add(params.VM(name=guest_name,memory=guest_mem*1024*1024,cluster=api.clusters.get(guest_cluster),template=api.templates.get('Blank'),cpu=cpu_params,type_="server",description=guest_description)) for ethnum in range(len(guest_networks)): api.vms.get(guest_name).nics.add(params.NIC(name='eth'+str(ethnum), network=params.Network(name=guest_networks[ethnum]), interface='virtio')) #create bootdisk. First disk is allways bootdisk createDisk(api, guest_name, guest_domain, guest_disks_gb[0], bootable=True, disk_name=guest_name+"_Disk1") #create remaining disks if len(guest_disks_gb) > 1: disk_num = 2 for guest_disk_gb in guest_disks_gb[1:]: createDisk(api, guest_name, guest_domain, guest_disk_gb, disk_name=guest_name+"_Disk"+str(disk_num)) disk_num += 1 while api.vms.get(guest_name).status.state != 'down': sleep(1) result = "Succesfully created guest: " + guest_name except Exception as e: result = 'Failed to create VM with disk and NIC: %s' % str(e) return result
def cloudinit(self, name, numinterfaces=None, ip1=None, subnet1=None, ip2=None, subnet2=None, ip3=None, subnet3=None, ip4=None, subnet4=None, gateway=None, rootpw=None, dns=None, dns1=None): api = self.api while api.vms.get(name).status.state == "image_locked": time.sleep(5) action = params.Action() hostname = params.Host(address=name) nic1, nic2, nic3, nic4 = None, None, None, None if ip1 and subnet1: ip = params.IP(address=ip1, netmask=subnet1, gateway=gateway) network = params.Network(ip=ip) nic1 = params.NIC(name='eth0', boot_protocol='STATIC', network=network, on_boot=True) else: nic1 = params.NIC(name='eth0', boot_protocol='DHCP', on_boot=True) if numinterfaces > 1: if ip2 and subnet2: ip = params.IP(address=ip2, netmask=subnet2) network = params.Network(ip=ip) nic2 = params.NIC(name='eth1', boot_protocol='STATIC', network=network, on_boot=True) else: nic2 = params.NIC(name='eth1', boot_protocol='DHCP', on_boot=True) if numinterfaces > 2: if ip3 and subnet3: ip = params.IP(address=ip3, netmask=subnet3) network = params.Network(ip=ip) nic3 = params.NIC(name='eth2', boot_protocol='STATIC', network=network, on_boot=True) else: nic3 = params.NIC(name='eth2', boot_protocol='DHCP', on_boot=True) if numinterfaces > 3: if ip4 and subnet4: ip = params.IP(address=ip4, netmask=subnet4) network = params.Network(ip=ip) nic4 = params.NIC(name='eth3', boot_protocol='STATIC', network=network, on_boot=True) else: nic4 = params.NIC(name='eth3', boot_protocol='DHCP', on_boot=True) nics = params.Nics() nics.add_nic(nic1) if numinterfaces > 1: nics.add_nic(nic2) if numinterfaces > 2: nics.add_nic(nic3) if numinterfaces > 3: nics.add_nic(nic4) networkconfiguration = params.NetworkConfiguration(nics=nics) users = None if rootpw: user = params.User(user_name='root', password=rootpw) users = params.Users() users.add_user(user) #buggy at the moment in ovirt # if dns: # domainhost = params.Host(address=dns) # domainhosts = params.Hosts() # domainhosts.add_host(domainhost) # dns = params.DNS(search_domains=domainhosts) # if dns1: # resolvhost = params.Host(address=dns1) # resolvhosts = params.Hosts() # resolvhosts.add_host(resolvhost) # dns.set_servers(resolvhosts) # networkconfiguration.set_dns(dns) files = None if dns1 and dns1: filepath, filecontent = '/etc/resolv.conf', "search %s\nnameserver %s" % ( dns, dns1) files = params.Files() cifile = params.File(name=filepath, content=filecontent, type_='PLAINTEXT') files = params.Files(file=[cifile]) cloudinit = params.CloudInit( host=hostname, network_configuration=networkconfiguration, regenerate_ssh_keys=True, users=users, files=files) initialization = params.Initialization(cloud_init=cloudinit) action.vm = params.VM(initialization=initialization) api.vms.get(name).start(action=action) return "%s started with cloudinit" % name
try: if (name == 'control'): vmachine.start( action=params.Action( vm=params.VM( initialization=params.Initialization( cloud_init=params.CloudInit( host=params.Host(address=name+str(num)+".onapp.labs"), network_configuration=params.NetworkConfiguration( nics=params.Nics( nic=[params.NIC( name="eth0", boot_protocol="static", on_boot=True, network=params.Network( ip=params.IP( address="192.168."+str(nic1)+".12", netmask="255.255.255.0", gateway="192.168."+str(nic1)+".1" ) ) ), params.NIC( name="eth1", boot_protocol="static", on_boot=True, network=params.Network( ip=params.IP( address="172.25."+str(nic2)+".12", netmask="255.255.255.0" ) )
number2 = raw_input("Second sequence classroom number: ") networks = ['ext', 'storage'] count = 0 inc = 0 number = 0 for network in networks: if count == 1: inc = 10 count = 1 for number in range(int(number1), int(number2) + 1): nic_name = "nic" + str(number + inc) nic_interface = "virtio" nic_network = vm_cluster.networks.get( name="class" + str(number) + "_" + network) nic_params = params.NIC(name=nic_name, interface=nic_interface, network=nic_network) vm.nics.add(nic_params) nic_name = "nic" + str(int(number2) * 2 + 1) nic_interface = "virtio" nic_network = vm_cluster.networks.get(name="external") nic_params = params.NIC(name=nic_name, interface=nic_interface, network=nic_network) vm.nics.add(nic_params) except Exception as ex: print "Adding network machine '%s' failed %s" % (vm_name, ex) try: vm.start(action=params.Action(vm=params.VM( initialization=params.Initialization(cloud_init=params.CloudInit( host=params.Host(address=vm_name),
def add(self, memory, disk_size, cluster_name, storage_name, nic_name='eth0', network_interface='virtio', network_name='ovirtmgmt', disk_interface='virtio', disk_format='raw', template_name='Blank', timeout=300): """ Create VM with one NIC and one Disk. :param memory: VM's memory size such as 1024*1024*1024=1GB. :param disk_size: VM's disk size such as 512*1024=512MB. :param nic_name: VM's NICs name such as 'eth0'. :param network_interface: VM's network interface such as 'virtio'. :param network_name: network such as ovirtmgmt for ovirt, rhevm for rhel. :param disk_format: VM's disk format such as 'raw' or 'cow'. :param disk_interface: VM's disk interface such as 'virtio'. :param cluster_name: cluster name. :param storage_name: storage domain name. :param template_name: VM's template name, default is 'Blank'. :param timeout: Time out """ end_time = time.time() + timeout # network name is ovirtmgmt for ovirt, rhevm for rhel. vm_params = param.VM(name=self.name, memory=memory, cluster=self.api.clusters.get(cluster_name), template=self.api.templates.get(template_name)) storage = self.api.storagedomains.get(storage_name) storage_params = param.StorageDomains(storage_domain=[storage]) nic_params = param.NIC(name=nic_name, network=param.Network(name=network_name), interface=network_interface) disk_params = param.Disk(storage_domains=storage_params, size=disk_size, type_='system', status=None, interface=disk_interface, format=disk_format, sparse=True, bootable=True) try: logging.info('Creating a VM %s' % self.name) self.api.vms.add(vm_params) logging.info('NIC is added to VM %s' % self.name) self.instance.nics.add(nic_params) logging.info('Disk is added to VM %s' % self.name) self.instance.disks.add(disk_params) logging.info('Waiting for VM to reach <Down> status') vm_down = False while time.time() < end_time: if self.is_dead(): vm_down = True break time.sleep(1) if not vm_down: raise WaitVMStateTimeoutError("DOWN", self.state()) except Exception as e: logging.error('Failed to create VM with disk and NIC\n%s' % str(e))
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
def trigger_add_vm(**kwargs): vm_params = params.VM(name=kwargs['vm_name'], template=kwargs['template_object'], disks=kwargs['template_disks'], cluster=kwargs['cluster_object'], host=kwargs['host_object'], cpu=kwargs['cpu_object'], memory=kwargs['appliance_memory'] * GB, placement_policy=kwargs['placement_object'], type_=kwargs['appliance_type']) try: cfme_appliance = api.vms.add(vm_params) except RequestError as E: print("Error while creating vm(s)") sys.exit(E) while cfme_appliance.status.state == 'image_locked': time.sleep(10) cfme_appliance = api.vms.get(name=kwargs['vm_name']) for disk in kwargs['disks']: disk_size = kwargs['disks'][disk]['size'] * GB interface_type = kwargs['disks'][disk]['interface'] disk_format = kwargs['disks'][disk]['format'] allocation = kwargs['disks'][disk]['allocation'] location = kwargs['disks'][disk]['location'] store = api.storagedomains.get(name=location) domain = params.StorageDomains(storage_domain=[store]) disk_param = params.Disk(description=disk, storage_domains=domain, size=disk_size, interface=interface_type, format=disk_format, type_=allocation) new_disk = cfme_appliance.disks.add(disk=disk_param) if len(kwargs['appliance_nics']) > 0: current_nics = cfme_appliance.get_nics().list() current_networks = [] for nic in current_nics: network_id = nic.get_network().id current_networks.append(api.networks.get(id=network_id).name) new_set = set(kwargs['appliance_nics']) current_set = set(current_networks) appliance_nics = list(new_set - current_set) for i in range(len(appliance_nics)): network_name = params.Network(name=appliance_nics[i]) nic_name = params.NIC(name='nic{}'.format(i + 1), network=network_name) cfme_appliance.nics.add(nic=nic_name) while locked_disks(cfme_appliance): time.sleep(10) cfme_appliance = api.vms.get(name=kwargs['vm_name']) dev = params.Boot(dev='network') cfme_appliance.os.boot.append(dev) # boot_params = { # # "ks": "http://<satellite-server>/ks", # # "ksdevice": boot_if, # # "dns": "1.2.3.4,1.2.3.5", # # "ip": "10.9.8.7", # # "netmask": "255.255.255.0", # # "gateway": "10.9.8.1", # "hostname": "{0}.my.domain".format(VM_NAME) # } # cmdline = " ".join(map("{0[0]}={0[1]}".format, boot_params.iteritems())) # cfme_appliance.set_os(params.OperatingSystem( # # kernel="iso://vmlinuz", # # initrd="iso://initrd.img", # cmdline=cmdline) # ) cfme_appliance.update() for disk in cfme_appliance.disks.list(): if disk.description in appliance['disks'] \ or already_moved(kwargs['domain_object'], disk): continue disk.move(action=kwargs['actions']) cfme_appliance = api.vms.get(name=kwargs['vm_name']) while locked_disks(cfme_appliance): time.sleep(10) cfme_appliance = api.vms.get(name=kwargs['vm_name']) cfme_appliance.start()
def trigger_add_vm(**kwargs): vm_params = params.VM(name=kwargs['vm_name'], template=kwargs['template_object'], disks=kwargs['template_disks'], cluster=kwargs['cluster_object'], host=kwargs['host_object'], cpu=kwargs['cpu_object'], memory=kwargs['appliance_memory'] * GB, placement_policy=kwargs['placement_object'], type_=kwargs['appliance_type']) try: cfme_appliance = api.vms.add(vm_params) except RequestError as E: print("Error while creating vm(s)") sys.exit(E) while cfme_appliance.status.state == 'image_locked': time.sleep(10) cfme_appliance = api.vms.get(name=kwargs['vm_name']) for disk in kwargs['disks']: disk_size = kwargs['disks'][disk]['size'] * GB interface_type = kwargs['disks'][disk]['interface'] disk_format = kwargs['disks'][disk]['format'] allocation = kwargs['disks'][disk]['allocation'] location = kwargs['disks'][disk]['location'] store = api.storagedomains.get(name=location) domain = params.StorageDomains(storage_domain=[store]) disk_param = params.Disk(description=disk, storage_domains=domain, size=disk_size, interface=interface_type, format=disk_format, type_=allocation) new_disk = cfme_appliance.disks.add(disk=disk_param) if len(kwargs['appliance_nics']) > 0: current_nics = cfme_appliance.get_nics().list() current_networks = [] for nic in current_nics: network_id = nic.get_network().id current_networks.append(api.networks.get(id=network_id).name) new_set = set(kwargs['appliance_nics']) current_set = set(current_networks) appliance_nics = list(new_set - current_set) for i in range(len(appliance_nics)): network_name = params.Network(name=appliance_nics[i]) nic_name = params.NIC(name='card{}'.format(i), network=network_name) cfme_appliance.nics.add(nic=nic_name) while locked_disks(cfme_appliance): time.sleep(10) cfme_appliance = api.vms.get(name=kwargs['vm_name']) dev = params.Boot(dev='network') cfme_appliance.os.boot.append(dev) cfme_appliance.update() for disk in cfme_appliance.disks.list(): if disk.description in appliance['disks'] \ or already_moved(kwargs['domain_object'], disk): continue disk.move(action=kwargs['actions']) cfme_appliance = api.vms.get(name=kwargs['vm_name']) while locked_disks(cfme_appliance): time.sleep(10) cfme_appliance = api.vms.get(name=kwargs['vm_name']) cfme_appliance.start()
def add_nic_to_vm(api, vm_id, network_name="rhevm"): vm = api.vms.get(id=vm_id) nic_params = params.NIC(name='eth0', network=params.Network(name=network_name), interface='virtio') return vm.nics.add(nic_params)
def spawn(self, context, instance, image_meta, network_info,block_device_info=None): """ Creates a VM instance in oVirt.""" try: try: for i in network_info: port_id = i['ovs_interfaceid'] mac = i['address'] except Exception as e: LOG.debug(_("network_info error %s" %str(e))) MB = 1024 * 1024 GB = 1024 * MB #name = instance['name'] name = instance['display_name'] cluster = self._session.clusters.get(instance['node']) memory = instance['memory_mb'] * MB template = self._session.templates.get('Blank') tdesc = image_meta['name'] + " ("+str(image_meta['id'])[0:7]+")" for t in self._session.templates.list(): if( tdesc == t.get_description()): template = t vmType = 'server' instance_vcpus = instance['vcpus'] template_cpus = template.cpu.topology.cores vm_cpu_cores = (instance_vcpus - template_cpus) + 1 LOG.info(_("*******rhevm -vmops ---- spawn--vm_cpu_cores-->>%s" %vm_cpu_cores)) cpuTopology = params.CpuTopology(cores=vm_cpu_cores, sockets=1) cpu = params.CPU(topology=cpuTopology) ovirtVMParam = params.VM(name=name, type_=vmType, memory=memory, cluster=cluster, cpu=cpu, template=template) newVm = self._session.vms.add(ovirtVMParam) #stackutils.delete_port(port_id) nicName = 'nic-1' macparam = params.MAC(address=mac) network = self._session.networks.get(name='ovirtmgmt') # ovirtmgmt, Net1 nicInterface = 'virtio' nic = params.NIC(name=nicName, interface=nicInterface, #mac=macparam, network=network) newNic = newVm.nics.add(nic) ''' instance_root_gb = instance['root_gb'] dl = template.disks.list() template_disksize = 0 for d in dl: template_disksize += d.get_size() template_diskGB = template_disksize / GB pending_diskGB = (instance_root_gb - template_diskGB) if pending_diskGB > 0: domain = self._engine.storagedomains.get('DataNFS') storageDomain = params.StorageDomains(storage_domain=[domain]) #volume_size = volume['size'] size = pending_diskGB * pow(2, 30) diskType = 'data' diskFormat = 'cow' diskInterface = 'virtio' sparse = True bootable = False vol_name = 'RootDisk' newVm.disks.add(params.Disk( name=vol_name, storage_domains=storageDomain, size=size, type_=diskType, interface=diskInterface, format=diskFormat, #sparse=FLAGS.ovirt_engine_sparse, sparse=sparse, bootable=bootable)) ''' while self._session.vms.get(name).status.state != 'down': time.sleep(3) try: newVm.start() except Exception as e: #print " ERROR....VM is not able to start : ", str(e) newVm.delete() raise Exception while self._session.vms.get(name).status.state != 'up': time.sleep(3) except Exception as e: raise Exception
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) if options.verbosity > 1: print "VM created successfuly"
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)
print "Virtual machine '%s' added." % vm_name except Exception as ex: print "Adding virtual machine '%s' failed %s" % (vm_name,ex) try: vm = api.vms.get(name=vm_name) if (name == "computea") or (name == "computeb"): nicnumber=0 networks = ['ext', 'mgmt', 'storage', 'prov', 'app'] for network in networks: nicnumber +=1 nic_name = "nic"+str(nicnumber) nic_interface = "virtio" nic_network = vm_cluster.networks.get(name="class"+str(num)+"_"+network) nic_params = params.NIC(name=nic_name, interface=nic_interface, network=nic_network) vm.nics.add(nic_params) for disk in vm.disks.list(): disk.set_alias(name+str(num)+".onapp.labs_Disk1") disk.update() elif name == "cboot": nicnumber=0 networks = ['ext', 'mgmt', 'storage', 'app'] for network in networks: nicnumber +=1 nic_name = "nic"+str(nicnumber) if nicnumber == 1: nic_interface = "virtio" else: nic_interface = "e1000" nic_network = vm_cluster.networks.get(name="class"+str(num)+"_"+network)
vm=params.VM( initialization=params.Initialization( cloud_init=params.CloudInit( host=params.Host(address=FQDN), authorized_keys=params.AuthorizedKeys( authorized_key=[params.AuthorizedKey(user=params.User(user_name="root"), key=SSHKEY)] ), regenerate_ssh_keys=True, users=params.Users( user=[params.User(user_name="root", password=SPASSWORD)] ), network_configuration=params.NetworkConfiguration( nics=params.Nics(nic=[params.NIC(name="eth0", boot_protocol="STATIC", on_boot=True, network=params.Network(ip=params.IP( address=IPADDR, netmask=NETMASK, gateway=GATEWAY)))]) ), files=params.Files( file=[params.File(name="/etc/motd", content=scontent, type_="PLAINTEXT")] ) ) ) ) ) logDebug( "Starting VM %s with cloud-init options" %(VMNAME) ) vm.start( action ) #vm started add sleeptime
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)