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 create_template(self, template_name, vm_name, cluster_name=None): """ Create a template based on a VM. Creates on the same cluster as the VM unless 'cluster_name' is specified """ vm = self.get_vm(vm_name) if cluster_name: cluster = self.get_cluster(cluster_name) else: cluster = vm.cluster new_template = types.Template(name=template_name, vm=vm.id, cluster=cluster.id) self.api.system_service().templates_service().add(new_template) # First it has to appear wait_for(lambda: self.does_template_exist(template_name), num_sec=30 * 60, message="template exists", delay=45) # Then the process has to finish template = self.get_template(template_name) template.wait_for_ok_status() return template
def create_template(self, cluster_name, template_name='my_template', timeout=300): """ Create a template from VM. :param cluster_name: cluster name. :param template_name: 'my_template' is default template name. :param timeout: Time out """ end_time = time.time() + timeout cluster = self.connection.clusters.get(cluster_name) tmpl_params = types.Template(name=template_name, vm=self.instance, cluster=cluster) try: logging.info('Creating a template %s from VM %s' % (template_name, self.name)) self.connection.templates.add(tmpl_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 a template from VM:\n%s' % str(e))
def export(self, name, template=None): """ :param name: :param template: :return: """ vmsearch = self.vms_service.list(search='name=%s' % name) if not vmsearch: common.pprint("VM %s not found" % name, color='red') return {'result': 'failure', 'reason': "VM %s not found" % name} vminfo = vmsearch[0] vm = self.vms_service.vm_service(vminfo.id) if str(vminfo.status) == 'up': vm.stop() attachments = self.conn.follow_link(vm.disk_attachments) disk_ids = [attachment.disk.id for attachment in attachments] _format = types.DiskFormat.COW attachments = [ types.DiskAttachment(disk=types.Disk(id=disk_id, format=_format)) for disk_id in disk_ids ] newvm = types.Vm(id=vm.id, disk_attachments=attachments) newname = template if template is not None else name template = types.Template(name=newname, vm=newvm) template = self.templates_service.add(template=template) template_service = self.templates_service.template_service(template.id) while True: sleep(5) template = template_service.get() if template.status == types.TemplateStatus.OK: break return {'result': 'success'}
def import_image(system_service, image_name, template_name, disk_name, dest_storage_domain, dest_cluster, sd_name, as_template=False): storage_domains_service = system_service.storage_domains_service() glance_storage_domain = storage_domains_service.list( search='name={}'.format(sd_name))[0] images = storage_domains_service.storage_domain_service( glance_storage_domain.id).images_service().list() image = [x for x in images if x.name == image_name][0] image_service = storage_domains_service.storage_domain_service( glance_storage_domain.id).images_service().image_service(image.id) result = image_service.import_( storage_domain=types.StorageDomain(name=dest_storage_domain, ), template=types.Template(name=template_name, ), cluster=types.Cluster(name=dest_cluster, ), import_as_template=as_template, disk=types.Disk(name=disk_name), ) disk = system_service.disks_service().list( search='name={}'.format(disk_name))[0] assert disk
def _get_base_template(self): templates = self._connection.system_service().templates_service().list() for template in templates: if template.version.version_number == 1 and template.name == self.param('name'): return otypes.Template( id=template.id )
def build_entity(self): return otypes.Template( id=self._module.params['id'], name=self._module.params['name'], cluster=otypes.Cluster(name=self._module.params['cluster']) if self._module.params['cluster'] else None, vm=otypes.Vm(name=self._module.params['vm']) if self._module.params['vm'] else None, description=self._module.params['description'], cpu_profile=otypes.CpuProfile(id=search_by_name( self._connection.system_service().cpu_profiles_service(), self._module.params['cpu_profile'], ).id) if self._module.params['cpu_profile'] else None, os=otypes.OperatingSystem(type=self.param('operating_system'), ) if self.param('operating_system') else None, memory=convert_to_bytes(self.param('memory')) if self.param('memory') else None, version=otypes.TemplateVersion( base_template=self._get_base_template(), version_name=self.param('version').get('name'), ) if self.param('version') else None, memory_policy=otypes.MemoryPolicy( guaranteed=convert_to_bytes(self.param('memory_guaranteed')), max=convert_to_bytes(self.param('memory_max')), ) if any((self.param('memory_guaranteed'), self.param('memory_max'))) else None, io=otypes.Io(threads=self.param('io_threads'), ) if self.param('io_threads') is not None else None, )
def build_entity(self): return otypes.Event( description=self._module.params['description'], severity=otypes.LogSeverity(self._module.params['severity']), origin=self._module.params['origin'], custom_id=self._module.params['custom_id'], id=self._module.params['id'], cluster=otypes.Cluster( id=self._module.params['cluster'] ) if self._module.params['cluster'] is not None else None, data_center=otypes.DataCenter( id=self._module.params['data_center'] ) if self._module.params['data_center'] is not None else None, host=otypes.Host( id=self._module.params['host'] ) if self._module.params['host'] is not None else None, storage_domain=otypes.StorageDomain( id=self._module.params['storage_domain'] ) if self._module.params['storage_domain'] is not None else None, template=otypes.Template( id=self._module.params['template'] ) if self._module.params['template'] is not None else None, user=otypes.User( id=self._module.params['user'] ) if self._module.params['user'] is not None else None, vm=otypes.Vm( id=self._module.params['vm'] ) if self._module.params['vm'] is not None else None, )
def createVM(self, vmname, cluster, template, group, memory=10, description=None): vms_service = self.connection.system_service().vms_service() vms = vms_service.list(search='name=%s' % vmname) if vms: # 根据 虚拟机名称区分 虚拟机是否存在 return ("%s虚拟机已存在" % vmname) vms_service.add( types.Vm( name=vmname, # 虚拟机名称 comment=group, # 注释,这里用于分组 description=description, # 虚拟机的描述 cluster=types.Cluster( name=cluster, # 虚拟机的集群环境 ), template=types.Template( name=template, # 虚拟机集群环境的模板 ), memory=memory * 2**30, # 内存 memory 单位GB,默认字节算 )) self.checkVM(vmname, "down") # 创建虚拟机,如果状态是down表示虚拟机已经创建好了
def createVM(session): """ Creates a virtual maschine """ print "\n\n=================[ CREATING VMS ]=================" try: for vm in configFile['vms']: hostname = vm['hostname'] cluster = vm['cluster'] template = vm['template'] memory = vm['memory'] vmService = session.system_service().vms_service() vm = vmService.add( types.Vm( name=hostname, memory = memory * 2**30, cluster=types.Cluster( name=cluster), template=types.Template( name=template), os=types.OperatingSystem( boot=types.Boot( devices=[types.BootDevice.HD])), ) ) print ("Created VM \"%s\" on cluster \"%s\" with template \"%s\"." % (hostname, cluster, template)) except Exception as e: print str(e) sys.exit(1)
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 add_vm(pname, pcluster, ptemplate): print('Adding VM : ' + pname + '...') vms_service.add( types.Vm( name=pname, cluster=types.Cluster(name=pcluster, ), template=types.Template(name=ptemplate, ), ), )
def add_vm_blank(api): # Get the vms service vms_service=api.system_service().vms_service() #Create VM from blank template vm_memory=256*MB vm=types.Vm( name=VM0_NAME, memory=vm_memory, type=types.VmType.SERVER, os=types.OperatingSystem( type='other_linux', boot=types.Boot( devices=[types.BootDevice.HD, types.BootDevice.NETWORK] ), ), high_availability=types.HighAvailability( enabled=False ), cluster=types.Cluster( name=TEST_CLUSTER ), template=types.Template( name=TEMPLATE_BLANK ), display=types.Display( smartcard_enabled=True, keyboard_layout='en-us', file_transfer_enabled=True, copy_paste_enabled=True ), memory_policy=types.MemoryPolicy( guaranteed=vm_memory//2 ) ) #Add this VM vm=vms_service.add(vm) #Check that VM was added vm_service=vms_service.vm_service(vm.id) testlib.assert_true_within_short( lambda: vm_service.get().status == types.VmStatus.DOWN ) #Add another VM vm.id=None vm.name=VM1_NAME vm.initialization=None vm=vms_service.add(vm) #Check that the second VM was added vm_service=vms_service.vm_service(vm.id) testlib.assert_true_within_short( lambda: vm_service.get().status == types.VmStatus.DOWN )
def mark_as_template(self, vm_name, delete=True, temporary_name=None, cluster=None, delete_on_error=True): """Turns the VM off, creates template from it and deletes the original VM. Mimics VMware behaviour here. Args: vm_name: Name of the VM to be turned to template delete: Whether to delete the VM (default: True) temporary_name: If you want, you can specific an exact temporary name for renaming. delete_on_error: delete on timeout as well. """ temp_template_name = temporary_name or "templatize_{}".format( fauxfactory.gen_alphanumeric(8)) try: with self.steady_wait(30): create_new_template = True if self.does_template_exist(temp_template_name): try: self._wait_template_ok(temp_template_name) except VMInstanceNotFound: pass # It got deleted. else: create_new_template = False if self.does_vm_exist(vm_name) and delete: self.delete_vm(vm_name, ) if delete: # We can only rename to the original name if we delete the vm self._rename_template(temp_template_name, vm_name) if create_new_template: self.stop_vm(vm_name) vm = self._get_vm(vm_name) actual_cluster = self._get_cluster( cluster) if cluster else vm.cluster new_template = types.Template(name=temp_template_name, vm=vm, cluster=actual_cluster) self.api.system_service().templates_service().add( new_template) # First it has to appear self._wait_template_exists(temp_template_name) # Then the process has to finish self._wait_template_ok(temp_template_name) # Delete the original VM if self.does_vm_exist(vm_name) and delete: self.delete_vm(vm_name, ) if delete: # We can only rename to the original name if we delete the vm self._rename_template(temp_template_name, vm_name) except TimedOutError: if delete_on_error: self.delete_template(temp_template_name) raise
def build_entity(self): return otypes.Template( id=self._module.params['id'], name=self._module.params['name'], cluster=otypes.Cluster( name=self._module.params['cluster'] ) if self._module.params['cluster'] else None, vm=otypes.Vm( name=self._module.params['vm'] ) if self._module.params['vm'] else None, description=self._module.params['description'], cpu_profile=otypes.CpuProfile( id=search_by_name( self._connection.system_service().cpu_profiles_service(), self._module.params['cpu_profile'], ).id ) if self._module.params['cpu_profile'] else None, display=otypes.Display( smartcard_enabled=self.param('smartcard_enabled') ) if self.param('smartcard_enabled') is not None else None, os=otypes.OperatingSystem( type=self.param('operating_system'), ) if self.param('operating_system') else None, memory=convert_to_bytes( self.param('memory') ) if self.param('memory') else None, soundcard_enabled=self.param('soundcard_enabled'), usb=( otypes.Usb(enabled=self.param('usb_support')) ) if self.param('usb_support') is not None else None, sso=( otypes.Sso( methods=[otypes.Method(id=otypes.SsoMethod.GUEST_AGENT)] if self.param('sso') else [] ) ) if self.param('sso') is not None else None, time_zone=otypes.TimeZone( name=self.param('timezone'), ) if self.param('timezone') else None, version=otypes.TemplateVersion( base_template=self._get_base_template(), version_name=self.param('version').get('name'), ) if self.param('version') 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'), self.param('memory_max') )) else None, io=otypes.Io( threads=self.param('io_threads'), ) if self.param('io_threads') is not None else None, initialization=self.get_initialization(), )
def rename(self, new_name): try: result = self.api.update(types.Template(name=new_name)) if not result: raise Exception("Update API call returned 'false'") except Exception: self.logger.exception("Failed to rename template %s to %s", self.name, new_name) return False else: # Update raw so we pick up the new name self.refresh() return True
def test_template_update(api_v4): template_guest = test_utils.get_template_service(api_v4.system_service(), TEMPLATE_GUEST) if template_guest is None: pytest.skip('{0}: template {1} is missing'.format( template_update.__name__, TEMPLATE_GUEST)) new_comment = "comment by ovirt-system-tests" template_guest.update(template=types.Template(comment=new_comment)) testlib.assert_true_within_short( lambda: template_guest.get().status == types.TemplateStatus.OK) assert template_guest.get().comment == new_comment
def template_update(api): template_cirros = test_utils.get_template_service(api.system_service(), TEMPLATE_CIRROS) if template_cirros is None: raise SkipTest('{0}: template {1} is missing'.format( template_update.__name__, TEMPLATE_CIRROS)) new_comment = "comment by ovirt-system-tests" template_cirros.update(template=types.Template(comment=new_comment)) testlib.assert_true_within_short( lambda: template_cirros.get().status == types.TemplateStatus.OK) nt.assert_true(template_cirros.get().comment == new_comment)
def test_template_update(engine_api, cirros_image_glance_template_name): template_guest = test_utils.get_template_service( engine_api.system_service(), cirros_image_glance_template_name) if template_guest is None: pytest.skip('{0}: template {1} is missing'.format( template_update.__name__, cirros_image_glance_template_name)) new_comment = "comment by ovirt-system-tests" template_guest.update(template=types.Template(comment=new_comment)) assertions.assert_true_within_short( lambda: template_guest.get().status == types.TemplateStatus.OK) assert template_guest.get().comment == new_comment
def import_template(self, edomain, sdomain, cluster, temp_template): export_sd_service = self._get_storage_domain_service(edomain) export_template = self.get_template_from_storage_domain( temp_template, edomain) target_storage_domain = self._get_storage_domain(sdomain) cluster_id = self._get_cluster(cluster).id sd_template_service = export_sd_service.templates_service( ).template_service(export_template.id) sd_template_service.import_( storage_domain=types.StorageDomain(id=target_storage_domain.id), cluster=types.Cluster(id=cluster_id), template=types.Template(id=export_template.id))
def create_template_and_subversion(api): engine = api.system_service() templates = engine.templates_service() template = types.Template( name=TEMPLATE_NAME, vm=types.Vm(name=VM_NAME) ) created_template = templates.add(template=template) _wait_template_status_ok(templates, created_template.id) template.version = types.TemplateVersion( version_name=TEMPLATE_SUBVERSION_NAME, base_template=types.Template( id=created_template.id ) ) created_template = templates.add(template) _wait_template_status_ok(templates, created_template.id)
def create(self, vm_name, cluster, template, stateless=False): """ :type vm_name: string :type cluster: clusterlib.Cluster :type template: string :type stateless: boolean """ sdk_type = types.Vm(name=vm_name, cluster=cluster.get_sdk_type(), template=types.Template(name=template), stateless=stateless) self._create_sdk_entity(sdk_type)
def build_entity(self): return otypes.Template( name=self._module.params['name'], cluster=otypes.Cluster(name=self._module.params['cluster']) if self._module.params['cluster'] else None, vm=otypes.Vm(name=self._module.params['vm']) if self._module.params['vm'] else None, description=self._module.params['description'], cpu_profile=otypes.CpuProfile(id=search_by_name( self._connection.system_service().cpu_profiles_service(), self._module.params['cpu_profile'], ).id) if self._module.params['cpu_profile'] else None, )
def add_image(self, image, pool, short=None, cmd=None, name=None, size=1): """ :param image: :param pool: :param short: :param cmd: :param name: :param size: :return: """ image = os.path.basename(image) if image not in otemplates: return {'result': 'failure', 'reason': "Image not supported"} if image in self.volumes(): common.pprint("Image %s already there" % image) return {'result': 'success'} system_service = self.conn.system_service() sds_service = system_service.storage_domains_service() poolcheck = sds_service.list(search='name=%s' % pool) if not poolcheck: return {'result': 'failure', 'reason': "Pool %s not found" % pool} sd = sds_service.list(search='name=%s' % self.imagerepository) common.pprint("Using %s glance repository" % self.imagerepository, color='green') if not sd: common.confirm( "No glance repo found. Do you want public glance repo to be installed?" ) providers_service = system_service.openstack_image_providers_service( ) sd_service = providers_service.add( provider=types.OpenStackImageProvider( name='ovirt-image-repository', url='http://glance.ovirt.org:9292', requires_authentication=False)) common.pprint("Relaunch kcli download now", color='green') return {'result': 'success'} else: sd_service = sds_service.storage_domain_service(sd[0].id) images_service = sd_service.images_service() images = images_service.list() imageobject = next((i for i in images if i.name == otemplates[image]), None) image_service = images_service.image_service(imageobject.id) image_service.import_(import_as_template=True, template=types.Template(name=image), cluster=types.Cluster(name=self.cluster), storage_domain=types.StorageDomain(name=pool)) return {'result': 'success'}
def _get_base_template(self): # The base template is the template with the lowest version_number. # Not necessarily version 1 templates = self._connection.system_service().templates_service().list() if not templates: return None template_name = self.param('name') named_templates = [t for t in templates if t.name == template_name] if not named_templates: return None base_template = min(named_templates, key=lambda x: x.version.version_number) return otypes.Template( id=base_template.id )
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 build_entity(self): return otypes.VmPool( name=self._module.params['name'], description=self._module.params['description'], comment=self._module.params['comment'], 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, max_user_vms=self._module.params['vm_per_user'], prestarted_vms=self._module.params['prestarted'], size=self._module.params['vm_count'], type=otypes.VmPoolType(self._module.params['type']) if self._module.params['type'] else None, )
def add_vm_template(api): #TODO: Fix the exported domain generation raise SkipTest('Exported domain generation not supported yet') vm_params = types.VM( name=VM1_NAME, memory=512 * MB, cluster=types.Cluster(name=TEST_CLUSTER, ), template=types.Template(name=TEMPLATE_CENTOS7, ), display=types.Display(type_='spice', ), ) api.vms.add(vm_params) testlib.assert_true_within_long( lambda: api.vms.get(VM1_NAME).status.state == 'down', ) disk_name = api.vms.get(VM1_NAME).disks.list()[0].name testlib.assert_true_within_long(lambda: api.vms.get(VM1_NAME).disks.get( disk_name).status.state == 'ok')
def bucle(): try: return vms_service.add( types.Vm( name=sys.argv[1], cluster=types.Cluster( name='Cluster-Rojo' ), template=types.Template( id=template_id ), ) ) except: time.sleep(100) bucle()