def build_entity(self): return otypes.Nic( id=self._module.params.get('id'), name=self._module.params.get('name'), interface=otypes.NicInterface( self._module.params.get('interface') ) if self._module.params.get('interface') else None, vnic_profile=otypes.VnicProfile( id=self.vnic_id, ) if self.vnic_id else None, mac=otypes.Mac( address=self._module.params.get('mac_address') ) if self._module.params.get('mac_address') else None, linked=self.param('linked') if self.param('linked') is not None else None, )
def _get_vnic_profile_mappings(module): vnicProfileMappings = list() for vnicProfileMapping in module.params['vnic_profile_mappings']: vnicProfileMappings.append( otypes.VnicProfileMapping( source_network_name=vnicProfileMapping['source_network_name'], source_network_profile_name=vnicProfileMapping[ 'source_profile_name'], target_vnic_profile=otypes.VnicProfile( id=vnicProfileMapping['target_profile_id'], ) if vnicProfileMapping['target_profile_id'] else None, )) return vnicProfileMappings
def _hotplug_network_to_vm(api, vm_name, network_name, iface_name): engine = api.system_service() profiles_service = engine.vnic_profiles_service() profile = next(profile for profile in profiles_service.list() if profile.name == network_name) nics_service = test_utils.get_nics_service(engine, vm_name) nics_service.add( types.Nic( name=iface_name, vnic_profile=types.VnicProfile( id=profile.id, ), ), )
def add_nic_to_instance(api, vm_id, vnic_id, nic_name='nic1'): """Add nic to vm.""" vms_service = api.system_service().vms_service() """Get id of network.""" nics_service = vms_service.vm_service(vm_id).nics_service() try: nics_service.add( types.Nic( name=nic_name, description='My network interface card', vnic_profile=types.VnicProfile(id=vnic_id, ), ), ) except Exception as e: print "Can't add NIC: %s" % str(e) api.close() sys.exit(1)
def add_filter(ovirt_api4): engine = ovirt_api4.system_service() nics_service = test_utils.get_nics_service(engine, VM0_NAME) nic = nics_service.list()[0] network = ovirt_api4.follow_link(nic.vnic_profile).network network_filters_service = engine.network_filters_service() network_filter = next(network_filter for network_filter in network_filters_service.list() if network_filter.name == NETWORK_FILTER_NAME) vnic_profiles_service = engine.vnic_profiles_service() vnic_profile = vnic_profiles_service.add( types.VnicProfile(name='{}_profile'.format(network_filter.name), network=network, network_filter=network_filter)) nic.vnic_profile = vnic_profile nt.assert_true(nics_service.nic_service(nic.id).update(nic))
def build_entity(self): return otypes.VnicProfile( name=self.param('name'), network=otypes.Network(id=self._get_network_id()), description=self.param('description') if self.param('description') is not None else None, pass_through=otypes.VnicPassThrough(mode=otypes.VnicPassThroughMode(self.param('pass_through'))) if self.param('pass_through') else None, custom_properties=[ otypes.CustomProperty( name=cp.get('name'), regexp=cp.get('regexp'), value=str(cp.get('value')), ) for cp in self.param('custom_properties') if cp ] if self.param('custom_properties') else None, migratable=self._get_migratable(), qos=self._get_qos(), port_mirroring=self._get_port_mirroring(), network_filter=self._get_network_filter() )
def __attach_nics(self, entity): # Attach NICs to VM, if specified: nics_service = self._service.service(entity.id).nics_service() for nic in self.param('nics'): if search_by_name(nics_service, nic.get('name')) is None: if not self._module.check_mode: nics_service.add( otypes.Nic( name=nic.get('name'), interface=otypes.NicInterface( nic.get('interface', 'virtio')), vnic_profile=otypes.VnicProfile( id=self.__get_vnic_profile_id(nic), ) if nic.get('profile_name') else None, mac=otypes.Mac(address=nic.get('mac_address')) if nic.get('mac_address') else None, )) self.changed = True
def create_vm_nic(self, vlan, logger): try: network = next((i for i in self.networks_service.list() if i.vlan is not None and i.vlan.id == vlan), None) if network is None: raise Exception( 'Can not find network with vlan{}'.format(vlan)) profile = next((i for i in self.profiles_service.list() if i.name == network.name), None) if profile is None: raise Exception('Can not find profiles name {}'.format( network.name)) # create nic template return types.Nic(name='nic', interface=types.NicInterface.VIRTIO, vnic_profile=types.VnicProfile(id=profile.id)) except Exception as e: raise Exception(e)
def add_vm_network( self, vm: types.Vm, name: str, profile_name: str, mac: str, interface_type: types.NicInterface = types.NicInterface.VIRTIO ) -> types.Nic: profiles_service = self._connection.system_service( ).vnic_profiles_service() profile = find_one_in_list_by_name(profiles_service.list(), profile_name) nics_service = self._connection.system_service().vms_service( ).vm_service(vm.id).nics_service() return nics_service.add( types.Nic( name=name, mac=types.Mac(address=mac), interface=interface_type, vnic_profile=types.VnicProfile(id=profile.id, ), ))
def addNICs(session): """ Adds NICs to an existing VM """ print "\n\n=================[ ADDING NICS ]=================" for vm in configFile['vms']: hostname = vm['hostname'] cluster = vm['cluster'] for nic in vm['interfaces']: network = vm['interfaces'][nic] profileId = None profileName = None systemService = session.system_service() vmService = systemService.vms_service() machine = vmService.list(search='name=%s' % str(hostname))[0] dcService = session.system_service().data_centers_service() dc = dcService.list(search='Clusters.name=%s' % str(cluster))[0] networkService = dcService.service(dc.id).networks_service() # logical networks in respective cluster for net in networkService.list(): if net.name == str(network): # logical network if of specified nic network in configfile profileService = session.system_service().vnic_profiles_service() for profile in profileService.list(): if profile.name == str(network): try: nicService = vmService.vm_service(machine.id).nics_service() nicService.add( types.Nic( name=nic, vnic_profile=types.VnicProfile( id=profile.id), ), ) print "Adding logical network \"%s\" to \"%s\" as NIC \"%s\"." % (str(network), hostname, nic) except Exception as e: pass
def add_nic_to_vm(api, options): """Add nic to vm.""" search_name = "name=" + options['vm_name'] vms_service = api.system_service().vms_service() vm = vms_service.list(search=search_name)[0] """Get id of network.""" profiles_service = api.system_service().vnic_profiles_service() profile_id = None for profile in profiles_service.list(): if profile.name == options['network_name']: profile_id = profile.id break nics_service = vms_service.vm_service(vm.id).nics_service() try: nics_service.add( types.Nic( name='nic1', description='My network interface card', vnic_profile=types.VnicProfile(id=profile_id, ), ), ) except Exception as e: print "Can't add NIC: %s" % str(e) api.close() sys.exit(1)
def add_nic(api): NIC_NAME = 'eth0' # Locate the vnic profiles service and use it to find the ovirmgmt # network's profile id: profiles_service = api.system_service().vnic_profiles_service() profile_id = next( ( profile.id for profile in profiles_service.list() if profile.name == MANAGEMENT_NETWORK ), None ) # Empty profile id would cause fail in later tests (e.g. add_filter): nt.assert_is_not_none(profile_id) # Locate the virtual machines service and use it to find the virtual # machine: vms_service = api.system_service().vms_service() vm = vms_service.list(search='name=%s' % VM0_NAME)[0] # Locate the service that manages the network interface cards of the # virtual machine: nics_service = vms_service.vm_service(vm.id).nics_service() # Use the "add" method of the network interface cards service to add the # new network interface card: nics_service.add( types.Nic( name=NIC_NAME, interface=types.NicInterface.VIRTIO, vnic_profile=types.VnicProfile( id=profile_id ), ), )
def addVMNIC(self, vmname, network, nicname): vms_service = self.connection.system_service().vms_service() vm = vms_service.list(search='name=%s' % vmname)[0] profiles_service = self.connection.system_service( ).vnic_profiles_service() profile_id = None # network的网卡编号UUID network_list = profiles_service.list() for profile in network_list: if profile.name == network: # 判断网卡名是否是network传来的名称 profile_id = profile.id # 获取network对应网卡名的UUID try: nics_service = vms_service.vm_service(vm.id).nics_service() nics_service.add( types.Nic( name=nicname, # 虚拟机新增网卡 description='My network interface', # 描述 vnic_profile=types.VnicProfile( id= profile_id, # 选择添加网卡关联的nic,这个与ovirt的网络关联,网络关联的是vlanid ), ), ) break # 停止查找 except: pass
def get_sdk_type(self): return types.VnicProfile()
disk_attachment = disk_attachments_service.add( types.DiskAttachment( disk=types.Disk( format=types.DiskFormat.COW, provisioned_size=VMCapacity, storage_domains=[ types.StorageDomain(name=VMDomain, ), ], ), interface=types.DiskInterface.VIRTIO_SCSI, bootable=True, active=True, ), ) ################################### netlist = connection.system_service().vnic_profiles_service().list( search=VMNetwork)[0] nics_service = vms_service.vm_service(vm.id).nics_service() nics_service.add( types.Nic( name='nic1', interface=types.NicInterface.VIRTIO, # network=types.Network(name='ovirtmgmt'), vnic_profile=types.VnicProfile(id=netlist.id), ), ) ################################# print("Virtual machine '%s' added." % vm.name) print("myinfo: '%s' " % vm.id) connection.close()
def create(self, name, virttype='kvm', profile='', flavor=None, plan='kvirt', cpumodel='Westmere', cpuflags=[], numcpus=2, memory=512, guestid='guestrhel764', pool='default', template=None, disks=[{ 'size': 10 }], disksize=10, diskthin=True, diskinterface='virtio', nets=['default'], iso=None, vnc=False, cloudinit=True, reserveip=False, reservedns=False, reservehost=False, start=True, keys=None, cmds=[], ips=None, netmasks=None, gateway=None, nested=True, dns=None, domain=None, tunnel=False, files=[], enableroot=True, alias=[], overrides={}, tags=None): """ :param name: :param virttype: :param profile: :param flavor: :param plan: :param cpumodel: :param cpuflags: :param numcpus: :param memory: :param guestid: :param pool: :param template: :param disks: :param disksize: :param diskthin: :param diskinterface: :param nets: :param iso: :param vnc: :param cloudinit: :param reserveip: :param reservedns: :param reservehost: :param start: :param keys: :param cmds: :param ips: :param netmasks: :param gateway: :param nested: :param dns: :param domain: :param tunnel: :param files: :param enableroot: :param alias: :param overrides: :param tags: :return: """ clone = not diskthin templateobject = types.Template(name=template) if template else None console = types.Console(enabled=True) try: vm = self.vms_service.add(types.Vm( name=name, cluster=types.Cluster(name=self.cluster), template=templateobject, console=console), clone=clone) vm_service = self.vms_service.vm_service(vm.id) except Exception as e: if self.debug: print(e) return {'result': 'failure', 'reason': e} timeout = 0 while True: vm = vm_service.get() if vm.status == types.VmStatus.DOWN: break else: timeout += 5 sleep(5) common.pprint("Waiting for vm to be ready", color='green') if timeout > 60: return { 'result': 'failure', 'reason': 'timeout waiting for vm to be ready' } profiles_service = self.conn.system_service().vnic_profiles_service() netprofiles = {} for prof in profiles_service.list(): netprofiles[prof.name] = prof.id if 'default' not in netprofiles and 'ovirtmgmt' in netprofiles: netprofiles['default'] = netprofiles['ovirtmgmt'] nics_service = self.vms_service.vm_service(vm.id).nics_service() nic_configurations = [] for index, net in enumerate(nets): netname = None netmask = None mac = None if isinstance(net, str): netname = net elif isinstance(net, dict) and 'name' in net: netname = net['name'] ip = None mac = net.get('mac') netmask = next( (e for e in [net.get('mask'), net.get('netmask')] if e is not None), None) gateway = net.get('gateway') noconf = net.get('noconf') if noconf is not None: continue if 'ip' in net: ip = net['ip'] # if 'alias' in net: # alias = net['alias'] if ips and len(ips) > index and ips[index] is not None: ip = ips[index] if ip is not None and netmask is not None and gateway is not None: nic_configuration = types.NicConfiguration( name='eth%s' % index, on_boot=True, boot_protocol=types.BootProtocol.STATIC, ip=types.Ip(version=types.IpVersion.V4, address=ip, netmask=netmask, gateway=gateway)) nic_configurations.append(nic_configuration) if netname is not None and netname in netprofiles: profile_id = netprofiles[netname] nics_service.add( types.Nic(name='eth%s' % index, mac=mac, vnic_profile=types.VnicProfile(id=profile_id))) for index, disk in enumerate(disks): diskpool = pool diskthin = True disksize = '10' if index == 0 and template is not None: continue if isinstance(disk, int): disksize = disk elif isinstance(disk, str) and disk.isdigit(): disksize = int(disk) elif isinstance(disk, dict): disksize = disk.get('size', disksize) diskpool = disk.get('pool', pool) diskthin = disk.get('thin', diskthin) self.add_disk(name, disksize, pool=diskpool, thin=diskthin) initialization = None if cloudinit: custom_script = '' if files: data = common.process_files(files=files, overrides=overrides) if data != '': custom_script += "write_files:\n" custom_script += data cmds.append('sleep 60') if template.lower().startswith('centos'): cmds.append('yum -y install centos-release-ovirt42') if template.lower().startswith('centos') or template.lower().startswith('fedora')\ or template.lower().startswith('rhel'): cmds.append('yum -y install ovirt-guest-agent-common') cmds.append('systemctl enable ovirt-guest-agent') cmds.append('systemctl start ovirt-guest-agent') if template.lower().startswith('debian'): cmds.append( 'echo "deb http://download.opensuse.org/repositories/home:/evilissimo:/deb/Debian_7.0/ ./" ' '>> /etc/apt/sources.list') cmds.append( 'gpg -v -a --keyserver http://download.opensuse.org/repositories/home:/evilissimo:/deb/' 'Debian_7.0/Release.key --recv-keys D5C7F7C373A1A299') cmds.append('gpg --export --armor 73A1A299 | apt-key add -') cmds.append('apt-get update') cmds.append('apt-get -Y install ovirt-guest-agent') cmds.append('service ovirt-guest-agent enable') cmds.append('service ovirt-guest-agent start') if [x for x in common.ubuntus if x in template.lower()]: cmds.append( 'echo deb http://download.opensuse.org/repositories/home:/evilissimo:/ubuntu:/16.04/' 'xUbuntu_16.04/ /') cmds.append( 'wget http://download.opensuse.org/repositories/home:/evilissimo:/ubuntu:/16.04/' 'xUbuntu_16.04//Release.key') cmds.append('apt-key add - < Release.key') cmds.append('apt-get update') cmds.append('apt-get -Y install ovirt-guest-agent') data = common.process_cmds(cmds=cmds, overrides=overrides) custom_script += "runcmd:\n" custom_script += data custom_script = None if custom_script == '' else custom_script user_name = common.get_user(template) root_password = None dns_servers = '8.8.8.8 1.1.1.1' key = get_home_ssh_key() initialization = types.Initialization( user_name=user_name, root_password=root_password, regenerate_ssh_keys=True, authorized_ssh_keys=key, host_name=name, nic_configurations=nic_configurations, dns_servers=dns_servers, dns_search=domain, custom_script=custom_script) tags_service = self.conn.system_service().tags_service() existing_tags = [tag.name for tag in tags_service.list()] if "profile_%s" % profile not in existing_tags: tags_service.add(types.Tag(name="profile_%s" % profile)) if "plan_%s" % plan not in existing_tags: tags_service.add(types.Tag(name="plan_%s" % plan)) tags_service = vm_service.tags_service() tags_service.add(tag=types.Tag(name="profile_%s" % profile)) tags_service.add(tag=types.Tag(name="plan_%s" % plan)) vm_service.start(use_cloud_init=cloudinit, vm=types.Vm(initialization=initialization)) return {'result': 'success'}
def main(): parser = option_parser() args = parser.parse_args() if not early_option_check(args): sys.exit(-1) # Create the connection to the server: connection = sdk.Connection( url='https://@ENGINE_FQDN@/ovirt-engine/api', username='******', password=base64.b64decode('@ENGINEPASS_BASE64@'), ca_file='@CA_PEM@', debug=False, ) vms_service = connection.system_service().vms_service() cluster = connection.system_service().clusters_service().list()[0] clustername = cluster.name dcs_service = connection.system_service().data_centers_service() dc = dcs_service.list(search='Clusters.name=%s' % cluster.name)[0] networks_service = dcs_service.service(dc.id).networks_service() profiles_service = connection.system_service().vnic_profiles_service() if not later_option_check(args, connection): connection.close() sys.exit(-1) shorthand = { 'rhel6': 'rhel_6x64', 'rhel7': 'rhel_7x64', 'rhel8': 'rhel_8x64', 'ubuntu': 'ubuntu_14_04', 'debian': 'debian_7', } vmtype = { 'server': types.VmType.SERVER, 'desktop': types.VmType.DESKTOP, 'high_performance': types.VmType.HIGH_PERFORMANCE } # Creating new virtual machine vm = types.Vm() vm.name = args.name vm.cluster = types.Cluster(name=clustername) vm.template = types.Template(name=args.template) if args.os in shorthand.keys(): vm.os = types.OperatingSystem(type=shorthand[args.os]) else: vm.os = types.OperatingSystem(type=args.os) vm.memory = args.memory * 1024 * 1024 if args.balloon == 0: vm.memory_policy = types.MemoryPolicy( max=args.max_memory * 1024 * 1024, guaranteed=args.guaranteed_memory * 1024 * 1024) else: vm.memory_policy = types.MemoryPolicy( max=args.max_memory * 1024 * 1024, guaranteed=args.guaranteed_memory * 1024 * 1024, ballooning=True if args.balloon == 1 else False) vm.cpu = types.Cpu() vm.cpu.architecture = types.Architecture.X86_64 vm.cpu.topology = types.CpuTopology(cores=1, sockets=args.cpu, threads=1) if args.sound != 0: vm.soundcard_enabled = True if args.sound == 1 else False vm.type = vmtype[args.type] print("Creating New Virtual Machine:{0}".format(args.name)) vm = vms_service.add(vm) while vms_service.list(search=args.name)[0].status != types.VmStatus.DOWN: time.sleep(1) # Attach network interface(s) nics_service = vms_service.vm_service(vm.id).nics_service() nicnum = 0 for netname in args.vmnet: network = next( (n for n in networks_service.list() if n.name == netname), None) profile_id = None for profile in profiles_service.list(): if profile.name == netname: profile_id = profile.id break if profile_id != None: nicnum = nicnum + 1 print("Attaching nic{0}(Network:{1})".format(nicnum, netname)) nics_service.add( types.Nic( name="nic{0}".format(nicnum), vnic_profile=types.VnicProfile(id=profile_id, ), ), ) # Create and attach disk(s) disk_attachments_service = vms_service.vm_service( vm.id).disk_attachments_service() disks_service = connection.system_service().disks_service() disknum = 0 for d in args.vmdisk: disknum += 1 new_disk = types.DiskAttachment() new_disk.disk = types.Disk() new_disk.disk.name = "{0}_Disk{1}".format(args.name, disknum) new_disk.disk.provisioned_size = int(d.split(':')[1]) * 2**30 new_disk.disk.storage_domains = [ types.StorageDomain(name=d.split(':')[0]) ] if d.split(':')[2] == "RAW": new_disk.disk.format = types.DiskFormat.RAW else: new_disk.disk.format = types.DiskFormat.COW new_disk.interface = types.DiskInterface.VIRTIO_SCSI new_disk.active = True if disknum == 1: new_disk.bootable = True print( "Attaching Disk{0}(Domain:{1}, Size:{2}GB, DiskFormat:{3})".format( disknum, d.split(':')[0], d.split(':')[1], d.split(':')[2])) disk_attachment = disk_attachments_service.add(new_disk) disk_service = disks_service.disk_service(disk_attachment.disk.id) # wait disk attach finish time.sleep(5) while disk_service.get().status != types.DiskStatus.OK: print("Waiting disk attach complete") time.sleep(5) if args.ks != None or args.ps != None or args.ai != None: # one-shot VM configuration for Kickstart/preseed one_vm = types.Vm() one_vm.os = types.OperatingSystem() one_vm.os.kernel = 'iso://' + args.kernel one_vm.os.initrd = 'iso://' + args.initrd one_vm.run_once = True one_vm.cdroms = list() one_vm.cdroms.append(types.Cdrom()) one_vm.cdroms[0].file = types.File() one_vm.cdroms[0].file.id = args.iso if args.dns == None: args.dns = "" elif args.os == 'rhel6': args.dns = 'dns=' + args.dns else: args.dns = 'nameserver=' + args.dns if args.os == 'rhel6': ksdev = args.network.split(':')[5] ksip = args.network.split(':')[0] ksnm = calc_netmask(int(args.network.split(':')[3])) ksgw = args.network.split(':')[2] args.network = "ksdevice={0} ip={1} netmask={2} gateway={3}".format( ksdev, ksip, ksnm, ksgw) if args.ks != None: if args.os == 'rhel6': one_vm.os.cmdline = args.network + " " + args.dns + " ks=" + args.ks else: one_vm.os.cmdline = args.network + " " + args.dns + " inst.ks=" + args.ks if args.ps != None: one_vm.os.cmdline = "auto=true url=" + args.ps if args.ai != None: one_vm.os.cmdline = "autoinstall ds=nocloud-net;s=" + args.ai vm_service = vms_service.vm_service(vm.id) print("Starting automatic OS installation on {0}".format(args.name)) vm_service.start(vm=one_vm, volatile=True) # Close the connection to the server: connection.close()
def create(self, name, network, qos=None): qos_type = None if qos is None else qos.get_sdk_type() sdk_type = types.VnicProfile(name=name, network=network.get_sdk_type(), qos=qos_type) self._create_sdk_entity(sdk_type)
def create(self, name, network): sdk_type = types.VnicProfile(name=name, network=network) self._create_sdk_entity(sdk_type)
# network by datacenter and cluster: cluster = system_service.clusters_service().cluster_service( vm.cluster.id).get() dcs_service = connection.system_service().data_centers_service() dc = dcs_service.list(search='Clusters.name=%s' % cluster.name)[0] networks_service = dcs_service.service(dc.id).networks_service() network = next((n for n in networks_service.list() if n.name == 'mynetwork'), None) profiles_service = connection.system_service().vnic_profiles_service() profile_id = None for profile in profiles_service.list(): if profile.name == 'mynetwork': profile_id = profile.id break # Locate the service that manages the network interface cards of the # virtual machine: nics_service = vms_service.vm_service(vm.id).nics_service() # Use the "add" method of the network interface cards service to add the # new network interface card: nics_service.add( types.Nic( name='mynic', description='My network interface card', vnic_profile=types.VnicProfile(id=profile_id, ), ), ) # Close the connection to the server: connection.close()
# the action methods are defined: storage_domain_service = storage_domains_service.storage_domain_service(sd.id) # Locate the service that manages the VMs in storage domain: vms_service = storage_domain_service.vms_service() # Find the the unregistered VM we want to register: vms = vms_service.list(unregistered=True) vm = next((v for v in vms if v.name == 'myvm'), None) # Locate the service that manages virtual machine in the storage domain, # as that is where the action methods are defined: vm_service = vms_service.vm_service(vm.id) # Register the VM into the system: vm = vm_service.register( cluster=types.Cluster(name='mycluster', ), vm=types.Vm(name='exported_myvm', ), vnic_profile_mappings=[ types.VnicProfileMapping( source_network_name='mynetwork', source_network_profile_name='mynetwork', target_vnic_profile=types.VnicProfile(name='mynetwork', ), ), ], reassign_bad_macs=True, ) # Close the connection to the server: connection.close()