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 nullifyNic(hostNIC): ''' resets nic configuration to enable its reuse ''' hostNIC.network = params.Network() hostNIC.boot_protocol = 'none' hostNIC.ip = params.IP(address='', netmask='', gateway='') return hostNIC
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 create_network_params(network_name, dc_name, **net_params): return params.Network( name=network_name, data_center=params.DataCenter( name=dc_name, ), **net_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 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_vm_network(api): VLAN100 = params.Network( name=VLAN100_NET, data_center=params.DataCenter(name=DC_NAME, ), description='VM Network on VLAN 100', vlan=params.VLAN(id='100', ), ) nt.assert_true(api.networks.add(VLAN100)) nt.assert_true(api.clusters.get(CLUSTER_NAME).networks.add(VLAN100))
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 make_vm_from_template(api, cluster, temp_template_name, temp_vm_name, provider, mgmt_network=None): """Makes temporary VM from imported template. This template will be later deleted. It's used to add a new disk and to convert back to template. Args: api: API to chosen RHEVM provider. cluster: Cluster to save the temporary VM on. mgmt_network: management network on RHEVM box, its 'ovirtmgmt' by default on rhv4.0 and 'rhevm' on older RHEVM versions. temp_template_name: temporary template name created from ova temp_vm_name: temporary vm name to be created. provider: provider_key """ try: if api.vms.get(temp_vm_name) is not None: logger.info( "RHEVM:%r Warning: found another VM with this name (%r).", provider, temp_vm_name) logger.info( "RHEVM:%r Skipping this step, attempting to continue...", provider) return actual_template = api.templates.get(temp_template_name) actual_cluster = api.clusters.get(cluster) params_vm = params.VM(name=temp_vm_name, template=actual_template, cluster=actual_cluster) api.vms.add(params_vm) # we must wait for the vm do become available def check_status(): return api.vms.get(temp_vm_name).get_status().state == 'down' wait_for(check_status, fail_condition=False, delay=5, num_sec=240) if mgmt_network: vm = api.vms.get(temp_vm_name) nic = vm.nics.get('eth0') nic.network = params.Network(name=mgmt_network) nic.interface = 'virtio' nic.update() # check, if the vm is really there if not api.vms.get(temp_vm_name): logger.error("RHEVM:%r temp VM could not be provisioned", provider) sys.exit(127) logger.info("RHEVM:%r successfully provisioned temp vm", provider) except Exception: logger.exception("RHEVM:%r Make_temp_vm_from_template failed:", provider)
def add_non_vm_network(api): VLAN200 = params.Network( name=VLAN200_NET, data_center=params.DataCenter(name=DC_NAME, ), description='Non VM Network on VLAN 200, MTU 9000', vlan=params.VLAN(id='200', ), usages=params.Usages(), mtu=9000, ) nt.assert_true(api.networks.add(VLAN200)) nt.assert_true(api.clusters.get(CLUSTER_NAME).networks.add(VLAN200))
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 attach_network_to_host(api, host, nic_name, network_name, ip_configuration, bonds=[]): network_attachment = params.NetworkAttachment( network=params.Network(name=network_name), host_nic=params.HostNIC(name=nic_name), ip_address_assignments=ip_configuration) attachment_action = params.Action( modified_bonds=params.HostNics(host_nic=bonds), modified_network_attachments=params.NetworkAttachments( network_attachment=[network_attachment]), check_connectivity=True) return host.setupnetworks(attachment_action)
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 _attach_vlan_to_host(api, host, ip_configuration): mgmt_attachment = _get_mgmt_attachment(api, host) mgmt_nic_id = mgmt_attachment.get_host_nic().id mgmt_nic_name = host.nics.get(id=mgmt_nic_id).name vlan_network_attachment = params.NetworkAttachment( network=params.Network(name=VLAN100_NET), host_nic=params.HostNIC(name=mgmt_nic_name), ip_address_assignments=ip_configuration) attachment_action = params.Action( modified_network_attachments=params.NetworkAttachments( network_attachment=[vlan_network_attachment]), check_connectivity=True) host.setupnetworks(attachment_action)
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 add_labeled_network(api): """ Creates a labeled network """ # create network labeled_net = params.Network( name=LABELED_NET_NAME, data_center=params.DataCenter(name=DC_NAME, ), description='Labeled network on VLAN {}'.format(LABELED_NET_VLAN_ID), usages=params.Usages(), # because only one non-VLAN network, here 'ovirtmgmt', can be assigned to each nic, # this additional network has to be a VLAN network vlan=params.VLAN(id=LABELED_NET_VLAN_ID, ), ) net = api.networks.add(labeled_net) nt.assert_true(net) # assign label to the network nt.assert_true(net.labels.add(params.Label(id=NETWORK_LABEL))) nt.assert_equal(len(net.labels.list(id=NETWORK_LABEL)), 1)
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 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 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)
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
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)
password=options.password, insecure=True) if __name__ == "__main__": dc = options.datacenter vlan = options.vlan if not options.vlanname: vlanname = "VLAN_%s" % vlan else: vlanname = options.vlanname datacenter = api.datacenters.get(name=dc) description = "Network for %s %s" % (vlanname, vlan) nueva = params.Network(name=vlanname, data_center=datacenter, vlan=params.VLAN(id=vlan), description=description) nueva.vlan_id = int(vlan) try: red = api.networks.add(nueva) except: print "ERROR creating VLAN %s with ID %s" % (vlanname, vlan) red = api.networks.get(name=vlanname) if not red: print "Network %s was not found, exitting" % vlanname sys.exit(1) if red.name != vlanname:
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()
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" if options.verbosity > 1:
except Exception as e: print 'Failed to install Host:\n%s' % str(e) # Add ovirtmgmt to host try: #data_center=api.datacenters.get(DC_NAME), #host = api.hosts.get(HOST_NAME), #ovirtmgmt = data_center.networks.get(name='ovirtmgmt') #eth = host.nics.get(name=ETH) print 'Adding ovirtmgmt to host' hostNics = api.hosts.get(HOST_NAME).nics # sync hostNicsParam = hostNics.list() for nic in hostNicsParam: nic.set_override_configuration(True) attachnic = params.HostNIC(network=params.Network(name='ovirtmgmt'), name='eth0', boot_protocol='static', ip=params.IP(address=IP_ADDRESS, netmask=IP_NETMASK, gateway=IP_GATEWAY), override_configuration=1) hostNics.setupnetworks( params.Action(force=0, check_connectivity=1, host_nics=params.HostNics(host_nic=[attachnic]))) # Active host host = api.hosts.get(HOST_NAME) host.activate() print 'Waiting for host to reach the Up status' while api.hosts.get(HOST_NAME).status.state != 'up':
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" ) ) )
def set_Host(self, host_name, cluster, ifaces): HOST = self.get_Host(host_name) CLUSTER = self.get_cluster(cluster) if HOST is None: setMsg("Host does not exist.") ifacelist = dict() networklist = [] manageip = '' try: for iface in ifaces: try: setMsg('creating host interface ' + iface['name']) if 'management' in iface: manageip = iface['ip'] if 'boot_protocol' not in iface: if 'ip' in iface: iface['boot_protocol'] = 'static' else: iface['boot_protocol'] = 'none' if 'ip' not in iface: iface['ip'] = '' if 'netmask' not in iface: iface['netmask'] = '' if 'gateway' not in iface: iface['gateway'] = '' if 'network' in iface: if 'bond' in iface: bond = [] for slave in iface['bond']: bond.append(ifacelist[slave]) try: tmpiface = params.Bonding( slaves=params.Slaves(host_nic=bond), options=params.Options( option=[ params.Option(name='miimon', value='100'), params.Option(name='mode', value='4') ] ) ) except Exception as e: setMsg('Failed to create the bond for ' + iface['name']) setFailed() setMsg(str(e)) return False try: tmpnetwork = params.HostNIC( network=params.Network(name=iface['network']), name=iface['name'], boot_protocol=iface['boot_protocol'], ip=params.IP( address=iface['ip'], netmask=iface['netmask'], gateway=iface['gateway'] ), override_configuration=True, bonding=tmpiface) networklist.append(tmpnetwork) setMsg('Applying network ' + iface['name']) except Exception as e: setMsg('Failed to set' + iface['name'] + ' as network interface') setFailed() setMsg(str(e)) return False else: tmpnetwork = params.HostNIC( network=params.Network(name=iface['network']), name=iface['name'], boot_protocol=iface['boot_protocol'], ip=params.IP( address=iface['ip'], netmask=iface['netmask'], gateway=iface['gateway'] )) networklist.append(tmpnetwork) setMsg('Applying network ' + iface['name']) else: tmpiface = params.HostNIC( name=iface['name'], network=params.Network(), boot_protocol=iface['boot_protocol'], ip=params.IP( address=iface['ip'], netmask=iface['netmask'], gateway=iface['gateway'] )) ifacelist[iface['name']] = tmpiface except Exception as e: setMsg('Failed to set ' + iface['name']) setFailed() setMsg(str(e)) return False except Exception as e: setMsg('Failed to set networks') setMsg(str(e)) setFailed() return False if manageip == '': setMsg('No management network is defined') setFailed() return False try: HOST = params.Host(name=host_name, address=manageip, cluster=CLUSTER, ssh=params.SSH(authentication_method='publickey')) if self.conn.hosts.add(HOST): setChanged() HOST = self.get_Host(host_name) state = HOST.status.state while (state != 'non_operational' and state != 'up'): HOST = self.get_Host(host_name) state = HOST.status.state time.sleep(1) if state == 'non_responsive': setMsg('Failed to add host to RHEVM') setFailed() return False setMsg('status host: up') time.sleep(5) HOST = self.get_Host(host_name) state = HOST.status.state setMsg('State before setting to maintenance: ' + str(state)) HOST.deactivate() while state != 'maintenance': HOST = self.get_Host(host_name) state = HOST.status.state time.sleep(1) setMsg('status host: maintenance') try: HOST.nics.setupnetworks(params.Action( force=True, check_connectivity=False, host_nics=params.HostNics(host_nic=networklist) )) setMsg('nics are set') except Exception as e: setMsg('Failed to apply networkconfig') setFailed() setMsg(str(e)) return False try: HOST.commitnetconfig() setMsg('Network config is saved') except Exception as e: setMsg('Failed to save networkconfig') setFailed() setMsg(str(e)) return False except Exception as e: if 'The Host name is already in use' in str(e): setMsg("Host already exists") else: setMsg("Failed to add host") setFailed() setMsg(str(e)) return False HOST.activate() while state != 'up': HOST = self.get_Host(host_name) state = HOST.status.state time.sleep(1) if state == 'non_responsive': setMsg('Failed to apply networkconfig.') setFailed() return False setMsg('status host: up') else: setMsg("Host exists.") return True
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()
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), 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.1", netmask="255.255.255.0", gateway="192.168.0.1"))), params.NIC(name="eth1", boot_protocol="static", on_boot=True, network=params.Network( ip=params.IP(address="192.168.2.1", netmask="255.255.255.0", gateway="192.168.0.1"))), params.NIC(name="eth2", boot_protocol="static", on_boot=True, network=params.Network( ip=params.IP(address="192.168.3.1", netmask="255.255.255.0", gateway="192.168.0.1"))),