def templatize_vm(api, template_name, cluster): """Templatizes temporary VM. Result is template with two disks. Args: api: API to chosen RHEVM provider. template_name: Name of the final template. cluster: Cluster to save the final template onto. """ if api.templates.get(template_name) is not None: print "RHEVM: Warning: found finished template with this name." print "RHEVM: Skipping this step, attempting to continue..." return temporary_vm = api.vms.get(TEMP_VM_NAME) actual_cluster = api.clusters.get(cluster) new_template = params.Template(name=template_name, vm=temporary_vm, cluster=actual_cluster) api.templates.add(new_template) wait_for(check_disks, [api], fail_condition=False, delay=5, num_sec=900) # check, if template is really there if not api.templates.get(template_name): print "RHEVM: VM failed to templatize" sys.exit(127)
def add_vm_template(api): #TODO: Fix the exported domain generation raise SkipTest('Exported domain generation not supported yet') vm_params = params.VM( name=VM1_NAME, memory=512 * MB, cluster=params.Cluster( name=TEST_CLUSTER, ), template=params.Template( name=TEMPLATE_CENTOS7, ), display=params.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 add_vm_blank(api): vm_memory = 512 * MB vm_params = params.VM( name=VM0_NAME, memory=vm_memory, cluster=params.Cluster( name=TEST_CLUSTER, ), template=params.Template( name=TEMPLATE_BLANK, ), display=params.Display( smartcard_enabled=True, keyboard_layout='en-us', file_transfer_enabled=True, copy_paste_enabled=True, ), memory_policy=params.MemoryPolicy( guaranteed=vm_memory / 2, ), ) api.vms.add(vm_params) testlib.assert_true_within_short( lambda: api.vms.get(VM0_NAME).status.state == 'down', )
def add_blank_vms(api): vm_memory = 256 * MB vm_params = params.VM( memory=vm_memory, os=params.OperatingSystem(type_='other_linux', ), type_='server', high_availability=params.HighAvailability(enabled=False, ), cluster=params.Cluster(name=TEST_CLUSTER, ), template=params.Template(name=TEMPLATE_BLANK, ), display=params.Display( smartcard_enabled=True, keyboard_layout='en-us', file_transfer_enabled=True, copy_paste_enabled=True, ), memory_policy=params.MemoryPolicy(guaranteed=vm_memory / 2, ), name=VM0_NAME) for vm in [VM0_NAME, VM2_NAME, BACKUP_VM_NAME]: vm_params.name = vm if vm == VM2_NAME: vm_params.high_availability.enabled = True vm_params.custom_emulated_machine = 'pc-i440fx-rhel7.4.0' api.vms.add(vm_params) testlib.assert_true_within_short( lambda: api.vms.get(vm).status.state == 'down', )
def templatize_vm(api, template_name, cluster, temp_vm_name, provider): """Templatizes temporary VM. Result is template with two disks. Args: api: API to chosen RHEVM provider. template_name: Name of the final template. cluster: Cluster to save the final template onto. """ try: if api.templates.get(template_name) is not None: logger.info("RHEVM:%r Warning: found finished template with this name (%r).", provider, template_name) logger.info("RHEVM:%r Skipping this step, attempting to continue", provider) return temporary_vm = api.vms.get(temp_vm_name) actual_cluster = api.clusters.get(cluster) new_template = params.Template(name=template_name, vm=temporary_vm, cluster=actual_cluster) api.templates.add(new_template) wait_for(check_disks, [api, temp_vm_name], fail_condition=False, delay=5, num_sec=900) # check, if template is really there if not api.templates.get(template_name): logger.error("RHEVM:%r templatizing temporary VM failed", provider) sys.exit(127) logger.info("RHEVM:%r successfully templatized the temporary VM", provider) except Exception: logger.exception("RHEVM:%r templatizing temporary VM failed", provider)
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.api.clusters.get(cluster_name) tmpl_params = param.Template(name=template_name, vm=self.instance, cluster=cluster) try: logging.info('Creating a template %s from VM %s' % (template_name, self.name)) self.api.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 add_vm_blank(api): vm_memory = 256 * MB vm_params = params.VM( memory=vm_memory, os=params.OperatingSystem(type_='other_linux', ), type_='server', high_availability=params.HighAvailability(enabled=False, ), cluster=params.Cluster(name=TEST_CLUSTER, ), template=params.Template(name=TEMPLATE_BLANK, ), display=params.Display( smartcard_enabled=True, keyboard_layout='en-us', file_transfer_enabled=True, copy_paste_enabled=True, ), memory_policy=params.MemoryPolicy(guaranteed=vm_memory / 2, ), name=VM0_NAME) api.vms.add(vm_params) testlib.assert_true_within_short( lambda: api.vms.get(VM0_NAME).status.state == 'down', ) vm_params.name = VM2_NAME vm_params.high_availability.enabled = True api.vms.add(vm_params) testlib.assert_true_within_short( lambda: api.vms.get(VM2_NAME).status.state == 'down', )
def generic_import_from_glance(api, image_name=CIRROS_IMAGE_NAME, as_template=False, image_ext='_glance_disk', template_ext='_glance_template', dest_storage_domain=MASTER_SD_TYPE, dest_cluster=CLUSTER_NAME): glance_provider = api.storagedomains.get(SD_GLANCE_NAME) target_image = glance_provider.images.get(name=image_name) disk_name = image_name.replace(" ", "_") + image_ext template_name = image_name.replace(" ", "_") + template_ext import_action = params.Action( storage_domain=params.StorageDomain( name=dest_storage_domain, ), cluster=params.Cluster( name=dest_cluster, ), import_as_template=as_template, disk=params.Disk( name=disk_name, ), template=params.Template( name=template_name, ), ) nt.assert_true( target_image.import_image(import_action) ) testlib.assert_true_within_long( lambda: api.disks.get(disk_name).status.state == 'ok', )
def import_template_from_glance(api, sdomain, cluster, temp_template_name, glance_server, provider, template_name): try: if api.templates.get(temp_template_name) is not None: logger.info( "RHEVM:%r Warning: found another template with this name.", provider) logger.info( "RHEVM:%r Skipping this step, attempting to continue...", provider) return # Find the storage domain: sd = api.storagedomains.get(name=glance_server) # Find the image: image = sd.images.get(name=template_name) # Import the image: image.import_image( params.Action(async=True, import_as_template=True, template=params.Template(name=temp_template_name), cluster=params.Cluster(name=cluster), storage_domain=params.StorageDomain(name=sdomain)))
def add_vm_blank(api): vm_params = params.VM( name=VM0_NAME, memory=1 * GB, cluster=params.Cluster(name=TEST_CLUSTER, ), template=params.Template(name=TEMPLATE_BLANK, ), display=params.Display(type_='spice', ), ) api.vms.add(vm_params) testlib.assert_true_within_short( lambda: api.vms.get(VM0_NAME).status.state == 'down', )
def mark_as_template(self, vm_name, delete=True, temporary_name=None, delete_on_error=True, **kwargs): """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. """ 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 = vm.get_cluster() new_template = params.Template(name=temp_template_name, vm=vm, cluster=actual_cluster) self.api.templates.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 deployFromTemplate(self, name, comments, templateId, clusterId, displayType, usbType, memoryMB, guaranteedMB): ''' Deploys a virtual machine on selected cluster from selected template Args: name: Name (sanitized) of the machine comments: Comments for machine templateId: Id of the template to deploy from clusterId: Id of the cluster to deploy to displayType: 'vnc' or 'spice'. Display to use ad oVirt admin interface memoryMB: Memory requested for machine, in MB guaranteedMB: Minimum memory guaranteed for this machine Returns: Id of the machine being created form template ''' logger.debug( 'Deploying machine with name "{0}" from template {1} at cluster {2} with display {3} and usb {4}, memory {5} and guaranteed {6}' .format(name, templateId, clusterId, displayType, usbType, memoryMB, guaranteedMB)) try: lock.acquire(True) api = self.__getApi() logger.debug('Deploying machine {0}'.format(name)) cluster = params.Cluster(id=clusterId) template = params.Template(id=templateId) display = params.Display(type_=displayType) if usbType in ('native', 'legacy'): usb = params.Usb(enabled=True, type_=usbType) else: usb = params.Usb(enabled=False) memoryPolicy = params.MemoryPolicy(guaranteed=guaranteedMB * 1024 * 1024) par = params.VM(name=name, cluster=cluster, template=template, description=comments, type_='desktop', memory=memoryMB * 1024 * 1024, memory_policy=memoryPolicy, usb=usb) # display=display, return api.vms.add(par).get_id() finally: lock.release()
def add_vm_template(api): #TODO: Fix the exported domain generation. #For the time being, add VM from Glance imported template. if api.templates.get(name=TEMPLATE_CIRROS) is None: raise SkipTest('%s: template %s not available.' % (add_vm_template.__name__, TEMPLATE_CIRROS)) vm_memory = 512 * MB vm_params = params.VM( name=VM1_NAME, description='CirrOS imported from Glance as Template', memory=vm_memory, cluster=params.Cluster( name=TEST_CLUSTER, ), template=params.Template( name=TEMPLATE_CIRROS, ), display=params.Display( type_='vnc', ), memory_policy=params.MemoryPolicy( guaranteed=vm_memory / 2, ballooning=False, ), os=params.OperatingSystem( type_='other_linux', ), timezone='Etc/GMT', type_='server', serial_number=params.SerialNumber( policy='custom', value='12345678', ), cpu=params.CPU( architecture='X86_64', topology=params.CpuTopology( cores=1, threads=2, sockets=1, ), ), ) 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 backup_to_template(api, config, vm_from_list): """ Create template from cloned vm :param api: ovirtsdk api :param config: Configuration :vm_name: Name of VM to backup """ vm_clone_name = vm_from_list + config.get_vm_middle() + config.get_vm_suffix() vm_clone = api.vms.get(vm_clone_name) logger.info("Creation of template from VM (%s) started ..." % vm_clone_name) if not config.get_dry_run(): api.templates.add(params.Template(name=vm_clone_name, vm=vm_clone)) VMTools.wait_for_vm_operation(api, config, "Creating template", vm_from_list) logger.info("Template creation finished")
def add_vm_template(api): vm_params = params.VM( name=VM1_NAME, memory=4 * GB, cluster=params.Cluster(name=TEST_CLUSTER, ), template=params.Template(name=TEMPLATE_CENTOS7, ), display=params.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 _create_from_vms( vms, delete_vms='no', show=None, headers='yes', ovirt=None ): """ Create an oVirt template from the given VMs (See create_from_vm for explanation about parameters) """ templates = [] for vm in vms: templ = ovirt.templates.add(oVirtParams.Template(vm=vm, name=vm.name)) templates.append(templ) if delete_vms == 'yes': _delete_vms(vms=vms, ovirt=ovirt) oVirtObjectType.all_types['template'].print_table( templates, show=show, headers=headers ) return templates
def generic_import_from_glance(glance_provider, image_name=CIRROS_IMAGE_NAME, as_template=False, image_ext='_glance_disk', template_ext='_glance_template', dest_storage_domain=MASTER_SD_TYPE, dest_cluster=CLUSTER_NAME): target_image = glance_provider.images.get(name=image_name) disk_name = image_name.replace(" ", "_") + image_ext template_name = image_name.replace(" ", "_") + template_ext import_action = params.Action( storage_domain=params.StorageDomain(name=dest_storage_domain, ), cluster=params.Cluster(name=dest_cluster, ), import_as_template=as_template, disk=params.Disk(name=disk_name, ), template=params.Template(name=template_name, ), ) nt.assert_true(target_image.import_image(import_action))
def create_template(self, cluster_name, template_name='my_template'): """ Create a template from VM. @cluster_name: cluster name. @template_name: 'my_template' is default template name. """ cluster = self.api.clusters.get(cluster_name) tmpl_params = param.Template(name=template_name, vm=self.instance, cluster=cluster) try: logging.info('Creating a template %s from VM %s' % (template_name, self.name)) self.api.templates.add(tmpl_params) logging.info('Waiting for VM to reach <Down> status ...') while self.state() != 'down': self.instance = self.api.vms.get(self.name) time.sleep(1) except Exception, e: logging.error('Failed to create a template from VM:\n%s' % str(e))
def create_rhevm_template(host, cluster, new_template, storage): """ Creates template from Virtual machines :param string host: The Virtual machine name of which, template is to be created. :param string cluster: The Cluster name of the RHEVM, in which the template is to be created. :param string new_template: The name of the template to be created. :param string storage: The name of the storage domain, which will be used to create template. """ get_client = get_rhevm_client() storage_domain = get_client.storagedomains.get(name=storage) size = storage_domain.get_available() / 1024 / 1024 / 1024 vm = get_client.vms.get(host) if size > 300 and vm: try: vm.stop() logger.info('Waiting for VM to reach Down status') wait_till_rhevm_instance_status(host, 'down') logger.info('Template creation in Progress') get_client.templates.add( params.Template(name=new_template, vm=get_client.vms.get(host), cluster=get_client.clusters.get(cluster))) wait_till_rhevm_instance_status(host, 'down', timeout=80) if get_client.templates.get(new_template): logger.info('{0} template is created successfully'.format( new_template)) get_client.disconnect() except Exception as ex: logger.error('Failed to Create Template from VM:\n%s' % str(ex)) get_client.disconnect() else: get_client.disconnect() logger.error('Low Storage cannot proceed or VM not found')
time.sleep(5) # ...then we wait until it is shut down. while state != 'down': time.sleep(5) vm = api.vms.get(id=uuid) if vm: vm.stop() state = vm.status.state logline = "vm2template waiting for %s uuid: %s to power off state: %s" % ( hostname, uuid, state) else: logline = "vm2template waiting for %s uuid: %s to power off state: unknown" % ( hostname, uuid) syslog.syslog(logline) # finally, we create the new template from this VM time.sleep(5) vm = api.vms.get(id=uuid) state = vm.status.state logline = "vm2template creating template from %s uuid: %s state: %s" % ( hostname, uuid, state) syslog.syslog(logline) dt = datetime.now() timestamp = dt.strftime("%y%m%d%H") name = "rhel7baseline%s" % (timestamp) vm = api.vms.get(id=uuid) template = params.Template(name=name, vm=vm) api.templates.add(template) exit(0)
def makeTemplate(self, name, comments, machineId, clusterId, storageId, displayType): ''' Publish the machine (makes a template from it so we can create COWs) and returns the template id of the creating machine Args: name: Name of the machine (care, only ascii characters and no spaces!!!) machineId: id of the machine to be published clusterId: id of the cluster that will hold the machine storageId: id of the storage tuat will contain the publication AND linked clones displayType: type of display (for oVirt admin interface only) Returns Raises an exception if operation could not be acomplished, or returns the id of the template being created. ''' logger.debug( "n: {0}, c: {1}, vm: {2}, cl: {3}, st: {4}, dt: {5}".format( name, comments, machineId, clusterId, storageId, displayType)) try: lock.acquire(True) api = self.__getApi() cluster = api.clusters.get(id=clusterId) vm = api.vms.get(id=machineId) if vm is None: raise Exception('Machine not found') if cluster is None: raise Exception('Cluster not found') if vm.get_status().get_state() != 'down': raise Exception('Machine must be in down state to publish it') print(vm.disks.list()) # Create disks description to be created in specified storage domain, one for each disk sd = params.StorageDomains( storage_domain=[params.StorageDomain(id=storageId)]) fix = not self._isFullyFunctionalVersion(api)[ 0] # If we need a fix for "publish" dsks = [] for dsk in vm.disks.list(): dsks.append( params.Disk(id=dsk.get_id(), storage_domains=sd, alias=dsk.get_alias())) # dsks.append(dsk) disks = params.Disks(disk=dsks) # Create display description # display = params.Display(type_=displayType) # TODO: Restore proper template creation mechanism if fix is True: vm = params.VM(id=vm.get_id()) else: vm = params.VM(id=vm.get_id(), disks=disks) template = params.Template( name=name, vm=vm, cluster=params.Cluster(id=cluster.get_id()), description=comments) # display=display) return api.templates.add(template).get_id() finally: lock.release()