def vm_run(prefix, api): host_names = [h.name() for h in prefix.virt_env.host_vms()] vms_service = api.system_service().vms_service() vm = vms_service.list(search='name=%s' % VM0_NAME)[0] gw_ip = test_utils.get_management_net(prefix).gw() vm_params = types.Vm( placement_policy=types.VmPlacementPolicy(hosts=[ types.Host(name="{}.{}".format(sorted(host_names)[0], DOMAIN_NAME)) ], ), initialization=types.Initialization(user_name=VM_USER_NAME, root_password=VM_PASSWORD)) vm_params.initialization.host_name = 'VM0' vm_params.initialization.dns_search = DOMAIN_NAME vm_params.initialization.domain = DOMAIN_NAME vm_params.initialization.dns_servers = gw_ip vm_params.initialization.nic_configurations = [ types.NicConfiguration( name='eth0', boot_protocol=types.BootProtocol.STATIC, on_boot=True, ip=types.Ip(address=test_utils.get_vm0_ip_address(prefix), netmask='255.255.255.0', gateway=gw_ip)) ] vm_service = vms_service.vm_service(vm.id) vm_service.start(use_cloud_init=True, vm=vm_params) testlib.assert_true_within_long( lambda: (vms_service.list(search='name=%s' % VM0_NAME)[0]).status == types.VmStatus.UP, )
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 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 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 vm_run(prefix): engine = prefix.virt_env.engine_vm() api = engine.get_api_v4() host_names = [h.name() for h in prefix.virt_env.host_vms()] vms_service = api.system_service().vms_service() vm = vms_service.list(search='name=%s' % VM0_NAME)[0] vm_service = vms_service.vm_service(vm.id) vm_service.start(use_cloud_init=True, vm=types.Vm(placement_policy=types.VmPlacementPolicy( hosts=[types.Host(name=sorted(host_names)[0])], ), initialization=types.Initialization( domain='lago.example.com', cloud_init=types.CloudInit( host=types.Host(address='VM0'), ), ))) testlib.assert_true_within_long( lambda: (vms_service.list(search='name=%s' % VM0_NAME)[0]).status == types.VmStatus.UP, )
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 main(): argument_spec = ovirt_full_argument_spec( state=dict( choices=['running', 'stopped', 'present', 'absent', 'suspended', 'next_run'], default='present', ), name=dict(default=None), id=dict(default=None), cluster=dict(default=None), template=dict(default=None), template_version=dict(default=None, type='int'), use_latest_template_version=dict(default=None, type='bool'), disks=dict(default=[], type='list'), memory=dict(default=None), memory_guaranteed=dict(default=None), cpu_sockets=dict(default=None, type='int'), cpu_cores=dict(default=None, type='int'), cpu_shares=dict(default=None, type='int'), type=dict(choices=['server', 'desktop']), operating_system=dict( default=None, choices=[ 'rhel_6_ppc64', 'other', 'freebsd', 'windows_2003x64', 'windows_10', 'rhel_6x64', 'rhel_4x64', 'windows_2008x64', 'windows_2008R2x64', 'debian_7', 'windows_2012x64', 'ubuntu_14_04', 'ubuntu_12_04', 'ubuntu_13_10', 'windows_8x64', 'other_linux_ppc64', 'windows_2003', 'other_linux', 'windows_10x64', 'windows_2008', 'rhel_3', 'rhel_5', 'rhel_4', 'other_ppc64', 'sles_11', 'rhel_6', 'windows_xp', 'rhel_7x64', 'freebsdx64', 'rhel_7_ppc64', 'windows_7', 'rhel_5x64', 'ubuntu_14_04_ppc64', 'sles_11_ppc64', 'windows_8', 'windows_2012R2x64', 'windows_2008r2x64', 'ubuntu_13_04', 'ubuntu_12_10', 'windows_7x64', ], ), cd_iso=dict(default=None), boot_devices=dict(default=None, type='list'), high_availability=dict(type='bool'), stateless=dict(type='bool'), delete_protected=dict(type='bool'), force=dict(type='bool', default=False), nics=dict(default=[], type='list'), cloud_init=dict(type='dict'), cloud_init_nics=dict(defaul=[], type='list'), sysprep=dict(type='dict'), host=dict(default=None), clone=dict(type='bool', default=False), clone_permissions=dict(type='bool', default=False), ) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, ) check_sdk(module) check_params(module) try: state = module.params['state'] connection = create_connection(module.params.pop('auth')) vms_service = connection.system_service().vms_service() vms_module = VmsModule( connection=connection, module=module, service=vms_service, ) vm = vms_module.search_entity() control_state(vm, vms_service, module) if state == 'present' or state == 'running' or state == 'next_run': sysprep = module.params['sysprep'] cloud_init = module.params['cloud_init'] cloud_init_nics = module.params['cloud_init_nics'] cloud_init_nics.append(cloud_init) # In case VM don't exist, wait for VM DOWN state, # otherwise don't wait for any state, just update VM: vms_module.create( entity=vm, result_state=otypes.VmStatus.DOWN if vm is None else None, clone=module.params['clone'], clone_permissions=module.params['clone_permissions'], ) ret = vms_module.action( action='start', post_action=vms_module._post_start_action, action_condition=lambda vm: ( vm.status not in [ otypes.VmStatus.MIGRATING, otypes.VmStatus.POWERING_UP, otypes.VmStatus.REBOOT_IN_PROGRESS, otypes.VmStatus.WAIT_FOR_LAUNCH, otypes.VmStatus.UP, otypes.VmStatus.RESTORING_STATE, ] ), wait_condition=lambda vm: vm.status == otypes.VmStatus.UP, # Start action kwargs: use_cloud_init=cloud_init is not None or len(cloud_init_nics) > 0, use_sysprep=sysprep is not None, vm=otypes.Vm( placement_policy=otypes.VmPlacementPolicy( hosts=[otypes.Host(name=module.params['host'])] ) if module.params['host'] else None, initialization=_get_initialization(sysprep, cloud_init, cloud_init_nics), ), ) if state == 'next_run': # Apply next run configuration, if needed: vm = vms_service.vm_service(ret['id']).get() if vm.next_run_configuration_exists: ret = vms_module.action( action='reboot', entity=vm, action_condition=lambda vm: vm.status == otypes.VmStatus.UP, wait_condition=lambda vm: vm.status == otypes.VmStatus.UP, ) elif state == 'stopped': vms_module.create( result_state=otypes.VmStatus.DOWN if vm is None else None, clone=module.params['clone'], clone_permissions=module.params['clone_permissions'], ) if module.params['force']: ret = vms_module.action( action='stop', post_action=vms_module._attach_cd, action_condition=lambda vm: vm.status != otypes.VmStatus.DOWN, wait_condition=lambda vm: vm.status == otypes.VmStatus.DOWN, ) else: ret = vms_module.action( action='shutdown', pre_action=vms_module._pre_shutdown_action, post_action=vms_module._attach_cd, action_condition=lambda vm: vm.status != otypes.VmStatus.DOWN, wait_condition=lambda vm: vm.status == otypes.VmStatus.DOWN, ) elif state == 'suspended': vms_module.create( result_state=otypes.VmStatus.DOWN if vm is None else None, clone=module.params['clone'], clone_permissions=module.params['clone_permissions'], ) ret = vms_module.action( action='suspend', pre_action=vms_module._pre_suspend_action, action_condition=lambda vm: vm.status != otypes.VmStatus.SUSPENDED, wait_condition=lambda vm: vm.status == otypes.VmStatus.SUSPENDED, ) elif state == 'absent': ret = vms_module.remove() module.exit_json(**ret) except Exception as e: module.fail_json(msg=str(e)) finally: connection.close(logout=False)
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
password='******', ca_file='ca.pem', debug=True, log=logging.getLogger(), ) # Get the reference to the root of the tree of services: system_service = connection.system_service() # Find the virtual machine: vms_service = system_service.vms_service() vm = vms_service.list(search='name=myvm')[0] # Update the placement policy of the virtual machine so that it is # pinned to the host. vm_service = vms_service.vm_service(vm.id) vm_service.update( vm=types.Vm( placement_policy=types.VmPlacementPolicy( hosts=[ types.Host( name='myhost' ) ] ) ) ) # Close the connection to the server: connection.close()