def create_vm(self, name: str, host: types.Host, memory: int, cpu_sockets: int, template=None) -> types.Vm: """ Создание виртуальной машины :param name: Название ВМ :param host: Хост ВМ :param memory: Объем памяти ВМ в байтах :param cpu_sockets: Количество ядер для ВМ :param template: Шаблон ВМ :return: Созданная ВМ """ vms_service = self._connection.system_service().vms_service() free_memory = self.get_host_free_memory(host) if free_memory < memory: raise NotEnoughMemoryException(free_memory, memory) return vms_service.add(vm=types.Vm( name=name, cluster=host.cluster, template=template or types.Template(name='Blank'), cpu=types.Cpu(topology=types.CpuTopology(sockets=cpu_sockets)), memory=memory, memory_policy=types.MemoryPolicy(guaranteed=memory, max=memory), placement_policy=types.VmPlacementPolicy( affinity=types.VmAffinity.USER_MIGRATABLE, hosts=[host], )))
def build_entity(self): return otypes.Vm( name=self._module.params['name'], cluster=otypes.Cluster(name=self._module.params['cluster']) if self._module.params['cluster'] else None, template=otypes.Template(name=self._module.params['template']) if self._module.params['template'] else None, stateless=self._module.params['stateless'], delete_protected=self._module.params['delete_protected'], high_availability=otypes.HighAvailability( enabled=self._module.params['high_availability']) if self._module.params['high_availability'] is not None else None, cpu=otypes.Cpu(topology=otypes.CpuTopology( cores=self._module.params['cpu_cores'], sockets=self._module.params['cpu_sockets'], )) if (self._module.params['cpu_cores'] or self._module.params['cpu_sockets']) else None, cpu_shares=self._module.params['cpu_shares'], os=otypes.OperatingSystem( type=self._module.params['operating_system'], boot=otypes.Boot(devices=[ otypes.BootDevice(dev) for dev in self._module.params['boot_devices'] ], ) if self._module.params['boot_devices'] else None, ) if (self._module.params['operating_system'] or self._module.params['boot_devices']) else None, type=otypes.VmType(self._module.params['type']) if self._module.params['type'] else None, memory=convert_to_bytes(self._module.params['memory']) if self._module.params['memory'] else None, memory_policy=otypes.MemoryPolicy(guaranteed=convert_to_bytes( self._module.params['memory_guaranteed']), ) if self._module.params['memory_guaranteed'] else None, )
def update_clusters_cpu(self, timeout=2 * 60): cpu_family = self.get_ovirt_cpu_family() api = self.engine_vm().get_api_v4(check=True) clusters_service = api.system_service().clusters_service() clusters = clusters_service.list() if clusters is None: LOGGER.debug('no clusters found: skipping') return for cluster in clusters: if cluster.cpu.type == cpu_family: continue LOGGER.debug( ('found CPU cluster mismatch, current: {0}, required: ' '{1}').format(cluster.cpu.type, cpu_family)) cluster_service = clusters_service.cluster_service(cluster.id) cluster_service.update( otypes.Cluster(cpu=otypes.Cpu(type=cpu_family))) def _assert_cluster_cpu(cluster): cluster = clusters_service.cluster_service(cluster.id).get() return cluster.cpu.type == cpu_family testlib.assert_true_within(partial(_assert_cluster_cpu, cluster), timeout=timeout) LOGGER.debug(('successfuly changed cluster id {0} to cpu family: ' '{1}').format(cluster.id, cpu_family))
def deploy_template(self, template, *args, **kwargs): self.logger.debug(' Deploying RHEV template %s to VM %s' % (template, kwargs["vm_name"])) timeout = kwargs.pop('timeout', 900) power_on = kwargs.pop('power_on', True) vm_kwargs = { 'name': kwargs['vm_name'], 'cluster': self._get_cluster(kwargs['cluster']), 'template': self._get_template(template) } if 'placement_policy_host' in kwargs and 'placement_policy_affinity' in kwargs: host = types.Host(name=kwargs['placement_policy_host']) policy = types.VmPlacementPolicy( hosts=[host], affinity=kwargs['placement_policy_affinity']) vm_kwargs['placement_policy'] = policy if 'cpu' in kwargs: vm_kwargs['cpu'] = types.Cpu(topology=types.CpuTopology( cores=kwargs['cpu'], sockets=kwargs.pop('sockets'))) if 'ram' in kwargs: vm_kwargs['memory'] = int(kwargs['ram']) * 1024 * 1024 # MB self._vms_service.add(types.Vm(**vm_kwargs)) self.wait_vm_stopped(kwargs['vm_name'], num_sec=timeout) if power_on: self.start_vm(kwargs['vm_name']) return kwargs['vm_name']
def create_vm_template(self, vm, logger): try: # hosts specified placement_policy = types.VmPlacementPolicy( hosts=[types.Host(name=vm.host)]) # cpu number cpu = types.CpuTopology(cores=vm.vcpu) # template template = types.Vm( name=vm.name, memory=vm.ram * 1024 * 1024, #MB cpu=types.Cpu(topology=cpu), cluster=types.Cluster(id=vm.cluster, ), template=types.Template(name='Blank', ), placement_policy=placement_policy) logger.info('Successfully created vm template') logger.info( 'Instance properties: name:{}, host:{}, cluster:{}, vcpu:{}, ram:{}' .format(vm.name, vm.host, vm.cluster, vm.vcpu, vm.ram)) return template except Exception as e: logger.error('Can not add vm template') logger.error(e) return {"name": vm.name, "status": 'fail,template'}
def add_cluster(pname, pdescription, ptype, pdc): print('Adding Cluster : ' + pname + '...') clusters_service.add( types.Cluster( name=pname, description=pdescription, cpu=types.Cpu( architecture=types.Architecture.X86_64, type=ptype, ), data_center=types.DataCenter(name=pdc, ), ), )
def set_vm_cpu_shares(self, vm: types.Vm, cpu_sockets: int): """ Установить количество ядер у ВМ :param vm: ВМ :param cpu_sockets: Количество ядер """ vm_service = self._connection.system_service().vms_service( ).vm_service(vm.id) vm_service.update( types.Vm(cpu=types.Cpu(topology=types.CpuTopology( sockets=cpu_sockets))))
def editVMCPU(self, vmname, core=2, socket=1): # 虚拟机的CPU在虚拟机看到的数量lscpu由 core 和 socket 组成 vms_service = self.connection.system_service().vms_service() vm = vms_service.list(search='name=%s' % vmname)[0] vm_service = vms_service.vm_service(vm.id) vm_service.update( types.Vm(cpu=types.Cpu( topology=types.CpuTopology( cores=core, # 更新 虚拟机的 cpu core sockets=socket, ), # 更新 虚拟机的cpu socket )))
def build_entity(self): template = self.__get_template_with_version() return otypes.Vm( name=self.param('name'), cluster=otypes.Cluster( name=self.param('cluster')) if self.param('cluster') else None, template=otypes.Template(id=template.id, ) if template else None, use_latest_template_version=self.param( 'use_latest_template_version'), stateless=self.param('stateless') or self.param('use_latest_template_version'), delete_protected=self.param('delete_protected'), high_availability=otypes.HighAvailability( enabled=self.param('high_availability')) if self.param('high_availability') is not None else None, cpu=otypes.Cpu(topology=otypes.CpuTopology( cores=self.param('cpu_cores'), sockets=self.param('cpu_sockets'), )) if (self.param('cpu_cores') or self.param('cpu_sockets')) else None, cpu_shares=self.param('cpu_shares'), os=otypes.OperatingSystem( type=self.param('operating_system'), boot=otypes.Boot(devices=[ otypes.BootDevice(dev) for dev in self.param('boot_devices') ], ) if self.param('boot_devices') else None, ) if (self.param('operating_system') or self.param('boot_devices')) else None, type=otypes.VmType(self.param('type')) if self.param('type') else None, memory=convert_to_bytes(self.param('memory')) if self.param('memory') else None, memory_policy=otypes.MemoryPolicy(guaranteed=convert_to_bytes( self.param('memory_guaranteed')), ) if self.param('memory_guaranteed') else None, instance_type=otypes.InstanceType(id=get_id_by_name( self._connection.system_service().instance_types_service(), self.param('instance_type'), ), ) if self.param('instance_type') else None, description=self.param('description'), comment=self.param('comment'), time_zone=otypes.TimeZone(name=self.param('timezone'), ) if self.param('timezone') else None, serial_number=otypes.SerialNumber( policy=otypes.SerialNumberPolicy(self.param('serial_policy')), value=self.param('serial_policy_value'), ) if (self.param('serial_policy') is not None or self.param('serial_policy_value') is not None) else None, )
def add_instance_type(api): instance_types_service = api.system_service().instance_types_service() nt.assert_true( instance_types_service.add( types.InstanceType( name='myinstancetype', description='My instance type', memory=1 * 2**30, memory_policy=types.MemoryPolicy(max=1 * 2**30, ), high_availability=types.HighAvailability(enabled=True, ), cpu=types.Cpu(topology=types.CpuTopology( cores=2, sockets=2, ), ), ), ))
def deploy(self, vm_name, **kwargs): """ Deploy a VM using this template Args: vm_name -- name of VM to create cluster -- cluster to which VM should be deployed timeout (optional) -- default 900 power_on (optional) -- default True placement_policy_host (optional) placement_policy_affinity (optional) cpu (optional) -- number of cpu cores sockets (optional) -- numbner of cpu sockets ram (optional) -- memory in GB Returns: wrapanapi.systems.rhevm.RHEVMVirtualMachine """ self.logger.debug(' Deploying RHEV template %s to VM %s', self.name, vm_name) timeout = kwargs.pop('timeout', 900) power_on = kwargs.pop('power_on', True) vm_kwargs = { 'name': vm_name, 'cluster': self.system.get_cluster(kwargs['cluster']), 'template': self.raw, } if 'placement_policy_host' in kwargs and 'placement_policy_affinity' in kwargs: host = types.Host(name=kwargs['placement_policy_host']) policy = types.VmPlacementPolicy( hosts=[host], affinity=kwargs['placement_policy_affinity']) vm_kwargs['placement_policy'] = policy if 'cpu' in kwargs: vm_kwargs['cpu'] = types.Cpu( topology=types.CpuTopology( cores=kwargs['cpu'], sockets=kwargs.pop('sockets') ) ) if 'ram' in kwargs: vm_kwargs['memory'] = int(kwargs['ram']) # in Bytes vms_service = self.system.api.system_service().vms_service() vms_service.add(types.Vm(**vm_kwargs)) vm = self.system.get_vm(vm_name) vm.wait_for_state(VmState.STOPPED, timeout=timeout) if power_on: vm.start() return vm
def test_add_vm1_from_template(engine_api, cirros_image_glance_template_name): engine = engine_api.system_service() templates_service = engine.templates_service() glance_template = templates_service.list( search='name=%s' % cirros_image_glance_template_name)[0] if glance_template is None: pytest.skip('%s: template %s not available.' % (add_vm1_from_template.__name__, cirros_image_glance_template_name)) vm_memory = 128 * MB # runs with 64 ok, but we need to do a hotplug later (64+256 is too much difference) vms_service = engine.vms_service() vms_service.add( types.Vm( name=VM1_NAME, description='CirrOS imported from Glance as Template', memory=vm_memory, cluster=types.Cluster(name=TEST_CLUSTER, ), template=types.Template(name=cirros_image_glance_template_name, ), use_latest_template_version=True, stateless=True, display=types.Display(type=types.DisplayType.VNC, ), memory_policy=types.MemoryPolicy( guaranteed= vm_memory, # with so little memory we don't want guaranteed to be any lower ballooning=False, ), os=types.OperatingSystem( type= 'rhel_7x64', # even though it's CirrOS we want to check a non-default OS type ), time_zone=types.TimeZone(name='Etc/GMT', ), type=types.VmType.SERVER, serial_number=types.SerialNumber( policy=types.SerialNumberPolicy.CUSTOM, value='12345678', ), cpu=types.Cpu( architecture=types.Architecture.X86_64, topology=types.CpuTopology( sockets=1, cores=1, threads=2, ), ), ))
def add_vm(api, options): """Adding a VM.""" vms_service = api.system_service().vms_service() try: vms_service.add( types.Vm( name=options['vm_name'], memory=options['vmem'], cpu=types.Cpu(topology=options['vcpus']), type=types.VmType('server'), os=types.OperatingSystem(type=options['os_type']), cluster=types.Cluster(name=options['vm_dc'], ), template=types.Template(name='Blank', ), ), ) except Exception as e: print "Can't add VM: %s" % str(e) api.close() sys.exit(1)
def add_vm1_from_template(api): engine = api.system_service() templates_service = engine.templates_service() glance_template = templates_service.list(search='name=%s' % TEMPLATE_CIRROS)[0] if glance_template is None: raise SkipTest('%s: template %s not available.' % ( add_vm1_from_template.__name__, TEMPLATE_CIRROS, )) vm_memory = 512 * MB vms_service = engine.vms_service() vms_service.add( types.Vm( name=VM1_NAME, description='CirrOS imported from Glance as Template', memory=512 * MB, cluster=types.Cluster(name=TEST_CLUSTER, ), template=types.Template(name=TEMPLATE_CIRROS, ), use_latest_template_version=True, stateless=True, display=types.Display(type=types.DisplayType.VNC, ), memory_policy=types.MemoryPolicy( guaranteed=vm_memory / 2, ballooning=False, ), os=types.OperatingSystem(type='other_lnux', ), time_zone=types.TimeZone(name='Etc/GMT', ), type=types.VmType.SERVER, serial_number=types.SerialNumber( policy=types.SerialNumberPolicy.CUSTOM, value='12345678', ), cpu=types.Cpu( architecture=types.Architecture.X86_64, topology=types.CpuTopology( sockets=1, cores=1, threads=2, ), ), ))
def build_entity(self): sched_policy = self._get_sched_policy() return otypes.Cluster( id=self.param('id'), name=self.param('name'), comment=self.param('comment'), description=self.param('description'), ballooning_enabled=self.param('ballooning'), gluster_service=self.param('gluster'), virt_service=self.param('virt'), threads_as_cores=self.param('threads_as_cores'), ha_reservation=self.param('ha_reservation'), trusted_service=self.param('trusted_service'), optional_reason=self.param('vm_reason'), maintenance_reason_required=self.param('host_reason'), scheduling_policy=otypes.SchedulingPolicy(id=sched_policy.id, ) if sched_policy else None, serial_number=otypes.SerialNumber( policy=otypes.SerialNumberPolicy(self.param('serial_policy')), value=self.param('serial_policy_value'), ) if (self.param('serial_policy') is not None or self.param('serial_policy_value') is not None) else None, migration=otypes.MigrationOptions( auto_converge=otypes.InheritableBoolean( self.param('migration_auto_converge'), ) if self.param('migration_auto_converge') else None, bandwidth=otypes.MigrationBandwidth( assignment_method=otypes. MigrationBandwidthAssignmentMethod( self.param('migration_bandwidth'), ) if self.param('migration_bandwidth') else None, custom_value=self.param('migration_bandwidth_limit'), ) if (self.param('migration_bandwidth') or self.param('migration_bandwidth_limit')) else None, compressed=otypes.InheritableBoolean( self.param('migration_compressed'), ) if self.param('migration_compressed') else None, policy=otypes.MigrationPolicy(id=self._get_policy_id()) if self.param('migration_policy') else None, ) if (self.param('migration_bandwidth') is not None or self.param('migration_bandwidth_limit') is not None or self.param('migration_auto_converge') is not None or self.param('migration_compressed') is not None or self.param('migration_policy') is not None) else None, error_handling=otypes.ErrorHandling(on_error=otypes.MigrateOnError( self.param('resilience_policy')), ) if self.param('resilience_policy') else None, fencing_policy=otypes.FencingPolicy( enabled=self.param('fence_enabled'), skip_if_gluster_bricks_up=self.param( 'fence_skip_if_gluster_bricks_up'), skip_if_gluster_quorum_not_met=self.param( 'fence_skip_if_gluster_quorum_not_met'), skip_if_connectivity_broken=otypes.SkipIfConnectivityBroken( enabled=self.param('fence_skip_if_connectivity_broken'), threshold=self.param('fence_connectivity_threshold'), ) if (self.param('fence_skip_if_connectivity_broken') is not None or self.param('fence_connectivity_threshold') is not None) else None, skip_if_sd_active=otypes.SkipIfSdActive( enabled=self.param('fence_skip_if_sd_active'), ) if self.param('fence_skip_if_sd_active') is not None else None, ) if (self.param('fence_enabled') is not None or self.param('fence_skip_if_sd_active') is not None or self.param('fence_skip_if_connectivity_broken') is not None or self.param('fence_skip_if_gluster_bricks_up') is not None or self.param('fence_skip_if_gluster_quorum_not_met') is not None or self.param('fence_connectivity_threshold') is not None) else None, display=otypes.Display(proxy=self.param('spice_proxy'), ) if self.param('spice_proxy') else None, required_rng_sources=[ otypes.RngSource(rng) for rng in self.param('rng_sources') ] if self.param('rng_sources') else None, memory_policy=otypes.MemoryPolicy( over_commit=otypes.MemoryOverCommit( percent=self._get_memory_policy(), ), ) if self.param('memory_policy') else None, ksm=otypes.Ksm( enabled=self.param('ksm'), merge_across_nodes=not self.param('ksm_numa'), ) if (self.param('ksm_numa') is not None or self.param('ksm') is not None) else None, data_center=otypes.DataCenter(name=self.param('data_center'), ) if self.param('data_center') else None, management_network=otypes.Network(name=self.param('network'), ) if self.param('network') else None, cpu=otypes.Cpu( architecture=otypes.Architecture(self.param('cpu_arch')) if self.param('cpu_arch') else None, type=self.param('cpu_type'), ) if (self.param('cpu_arch') or self.param('cpu_type')) else None, version=otypes.Version( major=self.__get_major(self.param('compatibility_version')), minor=self.__get_minor(self.param('compatibility_version')), ) if self.param('compatibility_version') else None, switch_type=otypes.SwitchType(self.param('switch_type')) if self.param('switch_type') else None, mac_pool=otypes.MacPool(id=get_id_by_name( self._connection.system_service().mac_pools_service(), self.param('mac_pool'))) if self.param('mac_pool') else None, external_network_providers=self. _get_external_network_providers_entity(), custom_scheduling_policy_properties=[ otypes.Property( name=sp.get('name'), value=str(sp.get('value')), ) for sp in self.param('scheduling_policy_properties') if sp ] if self.param('scheduling_policy_properties') is not None else None, firewall_type=otypes.FirewallType(self.param('firewall_type')) if self.param('firewall_type') else None, gluster_tuned_profile=self.param('gluster_tuned_profile'), )
def create_vm(kwargs, call=None): ''' Create VM based on YAML file (must include parameter @ filename = "path/to/file" @ ) - If C(cow) format is used, disk will by created as sparse, so space will be allocated for the volume as needed, also known as I(thin provision). - If C(raw) format is used, disk storage will be allocated right away, also known as I(preallocated). ''' assert "filename" in kwargs, "Can't find filename parameter in function call" vm_info = parse_yaml(kwargs["filename"]) boot_devices = [] if "boot_first_device" in vm_info["common"]: if vm_info["common"]["boot_first_device"].lower() in [ "hd", "network", "cdrom" ]: if vm_info["common"]["boot_first_device"].lower() == "hd": boot_devices.append(types.BootDevice.HD) elif vm_info["common"]["boot_first_device"].lower() == "cdrom": boot_devices.append(types.BootDevice.CDROM) elif vm_info["common"]["boot_first_device"].lower() == "network": boot_devices.append(types.BootDevice.NETWORK) else: boot_devices.append(None) if "boot_second_device" in vm_info["common"]: if vm_info["common"]["boot_second_device"].lower() in [ "hd", "network", "cdrom" ]: if vm_info["common"]["boot_second_device"].lower() == "hd": boot_devices.append(types.BootDevice.HD) elif vm_info["common"]["boot_second_device"].lower() == "cdrom": boot_devices.append(types.BootDevice.CDROM) elif vm_info["common"]["boot_second_device"].lower() == "network": boot_devices.append(types.BootDevice.NETWORK) else: boot_devices.append(None) connection() vms_service = connection.system_service().vms_service() vms_service.add( types.Vm( name=vm_info["name"], os=types.OperatingSystem( type=vm_info["os_type"] if "os_type" in vm_info else "Other", boot=types.Boot(devices=boot_devices)), # type=vm_info["common"]["type"], placement_policy=types.VmPlacementPolicy( hosts=[types.Host(name=vm_info["common"]["host"])]), cpu=types.Cpu(topology=types.CpuTopology( cores=vm_info["CPU"]["cores"] if "cores" in vm_info["CPU"] else 1, sockets=vm_info["CPU"]["sockets"] if "sockets" in vm_info["CPU"] else 1, threads=vm_info["CPU"]["threads"] if "threads" in vm_info["CPU"] else 1, ), ), memory=1024 * 1024 * 1024 * int(vm_info["memory"]["memory"]), memory_policy=types.MemoryPolicy( guaranteed=1024 * 1024 * 1024 * vm_info["memory"]["guaranteed"] if "guaranteed" in vm_info["memory"] else 512 * 1024 * 1024 * int(vm_info["memory"]["memory"]), ballooning=vm_info["memory"]["ballooning"] if "ballooning" in vm_info["memory"] else True, max=1024 * 1024 * 1024 * vm_info["memory"]["maximum"] if "maximum" in vm_info["memory"] else 2048 * 1024 * 1024 * int(vm_info["memory"]["memory"]), ), cluster=types.Cluster(name=vm_info["common"]["cluster"], ), template=types.Template( name=vm_info["common"]["template"] if "template" in vm_info["common"] else "Blank", ), description=vm_info["common"]["description"] if "description" in vm_info["common"] else "Not provided", comment=vm_info["common"]["comment"] if "comment" in vm_info["common"] else "Not provided", soundcard_enabled=vm_info["common"]["soundcard_enabled"] if "soundcard_enabled" in vm_info["common"] else False, ), ) if "disks" in vm_info: for disk in vm_info["disks"]: attach_disk(disk, vm_info["name"]) if "networks" in vm_info: for network in vm_info["networks"]: attach_network(network, vm_info["name"]) # Check according to salt: if call != 'function': raise SaltCloudSystemExit( 'The show_instance action must be called with -f or --function.') connection.close() return {'Created': '{0} was created.'.format(vm_info["name"])}
def build_entity(self): return otypes.InstanceType( id=self.param('id'), name=self.param('name'), console=( otypes.Console(enabled=self.param('serial_console')) ) if self.param('serial_console') is not None else None, usb=( otypes.Usb(enabled=self.param('usb_support')) ) if self.param('usb_support') is not None else None, high_availability=otypes.HighAvailability( enabled=self.param('high_availability'), priority=self.param('high_availability_priority'), ) if self.param('high_availability') is not None or self.param('high_availability_priority') else None, cpu=otypes.Cpu( topology=otypes.CpuTopology( cores=self.param('cpu_cores'), sockets=self.param('cpu_sockets'), threads=self.param('cpu_threads'), ) if any(( self.param('cpu_cores'), self.param('cpu_sockets'), self.param('cpu_threads') )) else None, cpu_tune=otypes.CpuTune( vcpu_pins=[ otypes.VcpuPin(vcpu=int(pin['vcpu']), cpu_set=str(pin['cpu'])) for pin in self.param('cpu_pinning') ], ) if self.param('cpu_pinning') else None, mode=otypes.CpuMode(self.param('cpu_mode')) if self.param( 'cpu_mode') else None, ) if any(( self.param('cpu_cores'), self.param('cpu_sockets'), self.param('cpu_threads'), self.param('cpu_mode'), self.param('cpu_pinning') )) else None, os=otypes.OperatingSystem( type=self.param('operating_system'), boot=otypes.Boot( devices=[ otypes.BootDevice(dev) for dev in self.param('boot_devices') ], ) if self.param('boot_devices') else None ), rng_device=otypes.RngDevice( source=otypes.RngSource(self.param('rng_device')), rate=otypes.Rate( bytes=self.param('rng_bytes'), period=self.param('rng_period') ) ) if self.param('rng_device') else None, memory=convert_to_bytes( self.param('memory') ) if self.param('memory') else None, virtio_scsi=otypes.VirtioScsi( enabled=self.param('virtio_scsi') ) if self.param('virtio_scsi') else None, memory_policy=otypes.MemoryPolicy( guaranteed=convert_to_bytes(self.param('memory_guaranteed')), ballooning=self.param('ballooning_enabled'), max=convert_to_bytes(self.param('memory_max')), ) if any(( self.param('memory_guaranteed'), self.param('ballooning_enabled') is not None, self.param('memory_max') )) else None, description=self.param('description'), placement_policy=otypes.VmPlacementPolicy( affinity=otypes.VmAffinity(self.param('placement_policy')), hosts=[ otypes.Host(name=self.param('host')), ] if self.param('host') else None, ) if self.param('placement_policy') else None, soundcard_enabled=self.param('soundcard_enabled'), display=otypes.Display( smartcard_enabled=self.param('smartcard_enabled') ) if self.param('smartcard_enabled') is not None else None, io=otypes.Io( threads=self.param('io_threads'), ) if self.param('io_threads') is not None else None, )
def deploy(self, vm_name, cluster, timeout=900, power_on=True, **kwargs): """ Deploy a VM using this template Args: vm_name -- name of VM to create cluster -- cluster name to which VM should be deployed timeout (optional) -- default 900 power_on (optional) -- default True placement_policy_host (optional) placement_policy_affinity (optional) cpu (optional) -- number of cpu cores sockets (optional) -- numbner of cpu sockets ram (optional) -- memory in GB storage_domain (optional) -- storage domain name to which VM should be deployed Returns: wrapanapi.systems.rhevm.RHEVMVirtualMachine """ self.logger.debug(' Deploying RHEV template %s to VM %s', self.name, vm_name) vm_kwargs = { 'name': vm_name, 'cluster': self.system.get_cluster(cluster), 'template': self.raw, } clone = None domain_name = kwargs.get('storage_domain') if domain_name: # need to specify storage domain, if its different than the template's disks location # then additional options required. disk allocation mode in UI required to be clone clone = True target_storage_domain = self.system.get_storage_domain(domain_name) disk_attachments = [] for template_attachment in self.api.disk_attachments_service( ).list(): new_attachment = types.DiskAttachment( disk=types.Disk(id=template_attachment.id, format=types.DiskFormat.COW, storage_domains=[target_storage_domain])) disk_attachments.append(new_attachment) vm_kwargs['disk_attachments'] = disk_attachments # Placement requires two args if 'placement_policy_host' in kwargs and 'placement_policy_affinity' in kwargs: host = types.Host(name=kwargs['placement_policy_host']) policy = types.VmPlacementPolicy( hosts=[host], affinity=kwargs['placement_policy_affinity']) vm_kwargs['placement_policy'] = policy # if cpu is passed, also default a sockets # unless its passed cpu = kwargs.get('cpu', None) # don't set default if its not passed if cpu: vm_kwargs['cpu'] = types.Cpu(topology=types.CpuTopology( cores=cpu, sockets=kwargs.get('sockets', 1))) if 'ram' in kwargs: vm_kwargs['memory'] = int(kwargs['ram']) # in Bytes vms_service = self.system.api.system_service().vms_service() vms_service.add(types.Vm(**vm_kwargs), clone=clone) vm = self.system.get_vm(vm_name) vm.wait_for_state(VmState.STOPPED, timeout=timeout) if power_on: vm.start() return vm
connection = sdk.Connection( url='https://' + RHVMURL + '/ovirt-engine/api', username=RHVMUser, password=RHVMPass, ca_file='/etc/pki/vdsm/certs/cacert.pem', ) # Get the reference to the "vms" service: vms_service = connection.system_service().vms_service() vm = types.Vm() vm.name = VMName vm.comment = VMComment vm.description = VMDescription cpu = types.CpuTopology(cores=VMCores, sockets=VMSockets) vm.cpu = types.Cpu(topology=cpu) vm.cluster = types.Cluster(name=VMCluster) vm.template = types.Template(name=VMTemplate) vm.os = types.OperatingSystem(boot=types.Boot(devices=[types.BootDevice.HD]), type='rhel_8x64') #vm.instance_type = types.InstanceType(id="00000003-0003-0003-0003-0000000000be") vm.memory = VMMemory vm.time_zone = types.TimeZone(name='Asia/Tehran') netlist = connection.system_service().operating_systems_service().list() for host in netlist: if host.name == 'rhel_8x64': myos = host print("%s (%s)" % (host.name, host.id)) vm.type = types.VmType.SERVER vm.soundcard_enabled = False provider = connection.system_service().external_host_providers_service().list(
# Create the connection to the server: connection = sdk.Connection( url='https://engine40.example.com/ovirt-engine/api', username='******', password='******', ca_file='ca.pem', debug=True, log=logging.getLogger(), ) # Get the reference to the instance types service: instance_types_service = connection.system_service().instance_types_service() # Add the instance type. Note that the size of the memory, the `memory` # attribute, is specified in bytes, so to create a instance type with # 2 GiB of memory the value should be 2 * 2^30. instance_types_service.add( types.InstanceType( name='myinstancetype', description='My instance type', memory=2 * 2**30, high_availability=types.HighAvailability(enabled=True, ), cpu=types.Cpu(topology=types.CpuTopology( cores=2, sockets=2, ), ), ), ) # Close the connection to the server: connection.close()
# This example will connect to the server and create a new cluster: # Create the connection to the server: connection = sdk.Connection( url='https://engine40.example.com/ovirt-engine/api', username='******', password='******', ca_file='ca.pem', debug=True, log=logging.getLogger(), ) # Get the reference to the clusters service: clusters_service = connection.system_service().clusters_service() # Use the "add" method to create a cluster: clusters_service.add( types.Cluster( name='mycluster', description='My cluster', cpu=types.Cpu( architecture=types.Architecture.X86_64, type='Intel Conroe Family', ), data_center=types.DataCenter(name='mydc', ), ), ) # Close the connection to the server: connection.close()
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()