def wait_for_task(vca_client, task): """ check status of current task and make request for recheck task status in case when we have not well defined state (not error and not success or by timeout) """ WAIT_TIME_MAX_MINUTES = 30 TASK_RECHECK_TIMEOUT = 5 TASK_STATUS_SUCCESS = 'success' TASK_STATUS_ERROR = 'error' MAX_ATTEMPTS = WAIT_TIME_MAX_MINUTES * 60 / TASK_RECHECK_TIMEOUT print('Maximun task wait time {0} minutes.'.format(WAIT_TIME_MAX_MINUTES)) print('Task recheck after {0} seconds.'.format(TASK_RECHECK_TIMEOUT)) status = task.get_status() for attempt in range(MAX_ATTEMPTS): print('Attempt: {0}/{1}.'.format(attempt + 1, MAX_ATTEMPTS)) if status == TASK_STATUS_SUCCESS: print('Task completed in {0} seconds'.format(attempt * TASK_RECHECK_TIMEOUT)) return if status == TASK_STATUS_ERROR: error = task.get_Error() raise cfy_exc.NonRecoverableError( "Error during task execution: {0}".format(error.get_message())) time.sleep(TASK_RECHECK_TIMEOUT) response = requests.get( task.get_href(), headers=vca_client.vcloud_session.get_vcloud_headers()) task = taskType.parseString(response.content, True) status = task.get_status() raise cfy_exc.NonRecoverableError("Wait for task timeout.")
def block_until_completed(self, task): progress = task.get_Progress() status = task.get_status() rnd = 0 while status != "success": if status == "error": error = task.get_Error() Log.error(self.logger, "task error, major=%s, minor=%s, message=%s" % (error.get_majorErrorCode(), error.get_minorErrorCode(), error.get_message())) return False else: # some task doesn't not report progress if progress: pass else: rnd += 1 time.sleep(1) self.response = Http.get(task.get_href(), headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify, logger=self.logger) if self.response.status_code == requests.codes.ok: task = taskType.parseString(self.response.content, True) progress = task.get_Progress() status = task.get_status() else: Log.error(self.logger, "can't get task") return False return True
def delete_disk(self, vdc_name, name, id=None): vdc = self.get_vdc(vdc_name) refs = self.get_diskRefs(vdc) link = [] if id is not None: link = filter(lambda link: link.get_href().endswith('/' + id), refs) elif name is not None: link = filter(lambda link: link.get_name() == name, refs) if len(link) == 1: self.response = requests.delete( link[0].get_href(), headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify) if self.response.status_code == requests.codes.accepted: task = taskType.parseString(self.response.content, True) return (True, task) else: return (False, self.response.content) elif len(link) == 0: return (False, 'disk not found') elif len(link) > 1: return ( False, 'more than one disks found with that name, use the disk id')
def update_vms_connections(self, network_connections): children = self.me.get_Children() if children: vms = children.get_Vm() for vm in vms: network_connection = self._create_network_connection(network_connections) output = StringIO() network_connection.export(output, 0, name_ = 'NetworkConnectionSection', namespacedef_ = 'xmlns="http://www.vmware.com/vcloud/v1.5" xmlns:vmw="http://www.vmware.com/vcloud/v1.5" xmlns:ovf="http://schemas.dmtf.org/ovf/envelope/1"', pretty_print = True) body=output.getvalue().replace("vmw:Info", "ovf:Info")\ .replace("<PrimaryNetworkConnectionIndex>", "<ovf:Info>Change network.</ovf:Info><PrimaryNetworkConnectionIndex>") response = self._invoke_api(requests, 'put', vm.get_href() + "/networkConnectionSection/", headers=self.headers, data=body, verify=self.verify) if response.status_code == requests.codes.forbidden: raise exceptions.ForbiddenException("Update_vms_connections error") if response.status_code == requests.codes.accepted: task = taskType.parseString(response.content, True) return (True, task) else: return (False, response.content)
def wait_for_task(vca_client, task): """ check status of current task and make request for recheck task status in case when we have not well defined state (not error and not success or by timeout) """ WAIT_TIME_MAX_MINUTES = 30 MAX_ATTEMPTS = WAIT_TIME_MAX_MINUTES * 60 / TASK_RECHECK_TIMEOUT ctx.logger.debug('Maximun task wait time {0} minutes.' .format(WAIT_TIME_MAX_MINUTES)) ctx.logger.debug('Task recheck after {0} seconds.' .format(TASK_RECHECK_TIMEOUT)) status = task.get_status() config = get_vcloud_config() for attempt in xrange(MAX_ATTEMPTS): ctx.logger.debug('Attempt: {0}/{1}.'.format(attempt + 1, MAX_ATTEMPTS)) if status == TASK_STATUS_SUCCESS: ctx.logger.debug('Task completed in {0} seconds' .format(attempt * TASK_RECHECK_TIMEOUT)) return if status == TASK_STATUS_ERROR: error = task.get_Error() raise cfy_exc.NonRecoverableError( "Error during task execution: {0}".format(error.get_message())) time.sleep(TASK_RECHECK_TIMEOUT) response = requests.get( task.get_href(), headers=vca_client.vcloud_session.get_vcloud_headers(), verify=config.get('ssl_verify', True)) task = taskType.parseString(response.content, True) status = task.get_status() raise cfy_exc.NonRecoverableError("Wait for task timeout.")
def block_until_completed(self, task): progress = task.get_Progress() status = task.get_status() rnd = 0 while status != "success": if status == "error": error = task.get_Error() return False else: # some task doesn't not report progress if progress: pass else: rnd += 1 time.sleep(1) self.response = requests.get( task.get_href(), headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify) if self.response.status_code == requests.codes.ok: task = taskType.parseString(self.response.content, True) progress = task.get_Progress() status = task.get_status() else: return False return True
def enableDownload(self): headers = self.headers url = '%s/action/enableDownload' % self.me.get_href() self.response = requests.post(url,data = {}, headers=headers, verify=self.verify) if self.response.status_code == requests.codes.accepted: return taskType.parseString(self.response.content, True) else: return False
def _put(self, href, body): response = Http.put( href, data=body, headers=self._session.vca.vcloud_session.get_vcloud_headers(), verify=CONF.vcloud.verify) if response.status_code == requests.codes.accepted: return taskType.parseString(response.content, True) return None
def delete_vdc_network(self, vdc_name, network_name): netref = self.get_admin_network_href(vdc_name, network_name) if netref is None: return (False, 'network not found') self.response = requests.delete(netref, headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify) if self.response.status_code == requests.codes.accepted: task = taskType.parseString(self.response.content, True) return (True, task) else: return (False, self.response.content)
def enableDownload(self): headers = self.headers url = '%s/action/enableDownload' % self.me.get_href() self.response = requests.post(url, data={}, headers=headers, verify=self.verify) if self.response.status_code == requests.codes.accepted: return taskType.parseString(self.response.content, True) else: return False
def save_gateway_configuration(gateway, vca_client): task = gateway.save_services_configuration() if task: wait_for_task(vca_client, task) return True else: error = taskType.parseString(gateway.response.content, True) if BUSY_MESSAGE in error.message: return False else: raise cfy_exc.NonRecoverableError(error.message)
def enableDownload(self): headers = self.headers url = "%s/action/enableDownload" % self.me.get_href() self.response = requests.post(url, data={}, headers=headers, verify=self.verify) if self.response.status_code == requests.codes.accepted: return taskType.parseString(self.response.content, True) elif self.response.status_code == requests.codes.forbidden: LOG.error("enableDownloadfailed: forbidden vapp %s" % self.name) raise exceptions.ForbiddenException("enableDownloadfailed: forbidden vapp %s" % self.name) else: return False
def _post(self, href, body, content_type): headers = self._session.vca.vcloud_session.get_vcloud_headers() headers['Content-type'] = content_type response = Http.post( href, data=body, headers=headers, verify=CONF.vcloud.verify) print response.content if response.status_code == requests.codes.accepted: return taskType.parseString(response.content, True) return None
def get_task(self, task_id): if self.vcloud_session: o = urlparse(self.vcloud_session.url) link = '%s://%s%s/%s' % (o.scheme, o.netloc, '/api/task', task_id) self.response = Http.get( link, headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify, logger=self.logger) if self.response.status_code == requests.codes.ok: return taskType.parseString(self.response.content, True) else: raise Exception(self.response.status_code) return None
def wait_for_task(vca_client, task): status = task.get_status() while status != TASK_STATUS_SUCCESS: if status == TASK_STATUS_ERROR: error = task.get_Error() raise cfy_exc.NonRecoverableError( "Error during task execution: {0}".format(error.get_message())) else: time.sleep(TASK_RECHECK_TIMEOUT) response = requests.get( task.get_href(), headers=vca_client.vcloud_session.get_vcloud_headers()) task = taskType.parseString(response.content, True) status = task.get_status()
def enableDownload(self): headers = self.headers url = '%s/action/enableDownload' % self.me.get_href() self.response = requests.post(url, data={}, headers=headers, verify=self.verify) if self.response.status_code == requests.codes.accepted: return taskType.parseString(self.response.content, True) elif self.response.status_code == requests.codes.forbidden: LOG.error("enableDownloadfailed: forbidden vapp %s" % self.name) raise exceptions.ForbiddenException( "enableDownloadfailed: forbidden vapp %s" % self.name) else: return False
def save_gateway_configuration(gateway, vca_client): """ save gateway configuration, return everything successfully finished raise NonRecoverableError - can't get task description """ task = gateway.save_services_configuration() if task: wait_for_task(vca_client, task) return True else: error = taskType.parseString(gateway.response.content, True) if BUSY_MESSAGE in error.message: return False else: raise cfy_exc.NonRecoverableError(error.message)
def delete_isolated_vdc_network(self, vdc_name, network_name): netref = self.get_isolated_network_href(vdc_name, network_name) if netref is None: return (True, None) response = requests.delete( netref, headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify) if response.status_code == requests.codes.forbidden: raise exception.Forbidden("Delete_isolated_vdc_network error, " + "network_name:" + network_name) if response.status_code == requests.codes.accepted: task = taskType.parseString(response.content, True) return (True, task) else: return (False, response.content)
def delete_isolated_vdc_network(self, vdc_name, network_name): netref = self.get_isolated_network_href(vdc_name, network_name) if netref is None: return (True, None) vcloud_headers = self.vcloud_session.get_vcloud_headers() response = self._invoke_api(requests, "delete", netref, headers=vcloud_headers, verify=self.verify) if response.status_code == requests.codes.forbidden: excep_msg = "Delete_isolated_vdc_network error, network_name:%s" % (network_name) raise exceptions.ForbiddenException(excep_msg) if response.status_code == requests.codes.bad_request: excep_msg = "Delete_isolated_vdc_network bad request, network_name:%s" % (network_name) raise exceptions.DeleteException(excep_msg) if response.status_code == requests.codes.accepted: task = taskType.parseString(response.content, True) return (True, task) else: return (False, response.content)
def delete_disk(self, vdc_name, name, id=None): vdc = self.get_vdc(vdc_name) refs = self.get_diskRefs(vdc) link = [] if id is not None: link = filter(lambda link: link.get_href().endswith('/'+id), refs) elif name is not None: link = filter(lambda link: link.get_name() == name, refs) if len(link) == 1: self.response = requests.delete(link[0].get_href(), headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify) if self.response.status_code == requests.codes.accepted: task = taskType.parseString(self.response.content, True) return (True, task) else: return(False, self.response.content) elif len(link) == 0: return(False, 'disk not found') elif len(link) > 1: return(False, 'more than one disks found with that name, use the disk id')
def wait_for_task(vca_client, task): """ check status of current task and make request for recheck task status in case when we have not well defined state (not error and not success) """ status = task.get_status() while status != TASK_STATUS_SUCCESS: if status == TASK_STATUS_ERROR: error = task.get_Error() raise cfy_exc.NonRecoverableError( "Error during task execution: {0}".format(error.get_message())) else: time.sleep(TASK_RECHECK_TIMEOUT) response = requests.get( task.get_href(), headers=vca_client.vcloud_session.get_vcloud_headers()) task = taskType.parseString(response.content, True) status = task.get_status()
def test_action_vminstance(self, get_vdc_details, get_namebyvappid, connect, get_vapp, block): task_resp = xml_resp.task_xml vm_id = '05e6047b-6938-4275-8940-22d1ea7245b8' # created vdc object vdc_xml_resp = xml_resp.vdc_xml_response vdc = vdcType.parseString(vdc_xml_resp, True) # assumed return value from VIM connector get_vdc_details.return_value = vdc get_namebyvappid.return_value = 'Test1_vm-69a18104-8413-4cb8-bad7-b5afaec6f9fa' connect.return_value = self.vca self.vim.vca = self.vim.connect() get_vapp.return_value.undeploy.return_value = taskType.parseString( task_resp, True) block.return_value = True # call to VIM connector method result = self.vim.action_vminstance(vm_id, {'shutdown': None}) # assert verified expected and return result from VIM connector self.assertEqual(result, None)
def modify_vm_memory(self, new_size): children = self.me.get_Children() if children: vms = children.get_Vm() for vm in vms: sections = vm.get_Section() virtualHardwareSection = filter(lambda section: section.__class__.__name__== "VirtualHardwareSection_Type", sections)[0] items = virtualHardwareSection.get_Item() memory = filter(lambda item: item.get_Description().get_valueOf_() == "Memory Size", items)[0] href = memory.get_anyAttributes_().get('{http://www.vmware.com/vcloud/v1.5}href') en = memory.get_ElementName() en.set_valueOf_('%s MB of memory' % new_size) memory.set_ElementName(en) vq = memory.get_VirtualQuantity() vq.set_valueOf_(new_size) memory.set_VirtualQuantity(vq) weight = memory.get_Weight() weight.set_valueOf_(str(int(new_size)*10)) memory.set_Weight(weight) memory_string = CommonUtils.convertPythonObjToStr(memory, 'Memory') output = StringIO() memory.export(output, 0, name_ = 'Item', namespacedef_ = 'xmlns="http://www.vmware.com/vcloud/v1.5" xmlns:ovf="http://schemas.dmtf.org/ovf/envelope/1" xmlns:rasd="http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData"', pretty_print = True) body = output.getvalue().\ replace('Info msgid=""', "ovf:Info").replace("/Info", "/ovf:Info").\ replace("vmw:", "").replace("class:", "rasd:").replace("ResourceType", "rasd:ResourceType") response = self._invoke_api(requests, 'put', href, headers=self.headers, data=body, verify=self.verify) if response.status_code == requests.codes.accepted: task = taskType.parseString(response.content, True) return (True, task) else: return (False, response.content) raise Exception('can\'t find vm')
def wait_for_task(vca_client, task): TASK_RECHECK_TIMEOUT = 5 TASK_STATUS_SUCCESS = 'success' TASK_STATUS_ERROR = 'error' WAIT_TIME_MAX_MINUTES = 30 MAX_ATTEMPTS = WAIT_TIME_MAX_MINUTES * 60 / TASK_RECHECK_TIMEOUT status = task.get_status() for attempt in xrange(MAX_ATTEMPTS): if status == TASK_STATUS_SUCCESS: return if status == TASK_STATUS_ERROR: error = task.get_Error() raise RuntimeError("Error during task execution: {0}".format( error.get_message())) time.sleep(TASK_RECHECK_TIMEOUT) response = requests.get( task.get_href(), headers=vca_client.vcloud_session.get_vcloud_headers(), verify=False) task = taskType.parseString(response.content, True) status = task.get_status() raise RuntimeError("Wait for task timeout.")
def block_until_completed(self, task): progress = task.get_Progress() status = task.get_status() rnd = 0 while status != "success": if status == "error": error = task.get_Error() return False else: # some task doesn't not report progress if progress: pass else: rnd += 1 time.sleep(1) self.response = requests.get(task.get_href(), headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify) if self.response.status_code == requests.codes.ok: task = taskType.parseString(self.response.content, True) progress = task.get_Progress() status = task.get_status() else: return False return True
def wait_for_task(vca_client, task): TASK_RECHECK_TIMEOUT = 5 TASK_STATUS_SUCCESS = 'success' TASK_STATUS_ERROR = 'error' WAIT_TIME_MAX_MINUTES = 30 MAX_ATTEMPTS = WAIT_TIME_MAX_MINUTES * 60 / TASK_RECHECK_TIMEOUT status = task.get_status() for attempt in xrange(MAX_ATTEMPTS): if status == TASK_STATUS_SUCCESS: return if status == TASK_STATUS_ERROR: error = task.get_Error() raise RuntimeError( "Error during task execution: {0}".format(error.get_message())) time.sleep(TASK_RECHECK_TIMEOUT) response = requests.get( task.get_href(), headers=vca_client.vcloud_session.get_vcloud_headers(), verify=False) task = taskType.parseString(response.content, True) status = task.get_status() raise RuntimeError("Wait for task timeout.")
def delete_isolated_vdc_network(self, vdc_name, network_name): netref = self.get_isolated_network_href(vdc_name, network_name) if netref is None: return (True, None) vcloud_headers = self.vcloud_session.get_vcloud_headers() response = self._invoke_api(requests, 'delete', netref, headers=vcloud_headers, verify=self.verify) if response.status_code == requests.codes.forbidden: excep_msg = "Delete_isolated_vdc_network error, network_name:%s"\ % (network_name) raise exceptions.ForbiddenException(excep_msg) if response.status_code == requests.codes.bad_request: excep_msg = "Delete_isolated_vdc_network bad request, network_name:%s"\ % (network_name) raise exceptions.DeleteException(excep_msg) if response.status_code == requests.codes.accepted: task = taskType.parseString(response.content, True) return (True, task) else: return (False, response.content)
def modify_vm_cpu(self, cpus): children = self.me.get_Children() if children: vms = children.get_Vm() for vm in vms: sections = vm.get_Section() virtualHardwareSection = filter(lambda section: section.__class__.__name__== "VirtualHardwareSection_Type", sections)[0] items = virtualHardwareSection.get_Item() cpu = filter(lambda item: (item.get_anyAttributes_().get('{http://www.vmware.com/vcloud/v1.5}href') != None and item.get_anyAttributes_().get('{http://www.vmware.com/vcloud/v1.5}href').endswith('/virtualHardwareSection/cpu')), items)[0] href = cpu.get_anyAttributes_().get('{http://www.vmware.com/vcloud/v1.5}href') en = cpu.get_ElementName() en.set_valueOf_('%s virtual CPU(s)' % cpus) cpu.set_ElementName(en) vq = cpu.get_VirtualQuantity() vq.set_valueOf_(cpus) cpu.set_VirtualQuantity(vq) cpu_string = CommonUtils.convertPythonObjToStr(cpu, 'CPU') output = StringIO() cpu.export(output, 0, name_ = 'Item', namespacedef_ = 'xmlns="http://www.vmware.com/vcloud/v1.5" xmlns:ovf="http://schemas.dmtf.org/ovf/envelope/1" xmlns:rasd="http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData"', pretty_print = True) body = output.getvalue().\ replace('Info msgid=""', "ovf:Info").replace("/Info", "/ovf:Info").\ replace("vmw:", "").replace("class:", "rasd:").replace("ResourceType", "rasd:ResourceType") response = self._invoke_api(requests, 'put', href, headers=self.headers, data=body, verify=self.verify) if response.status_code == requests.codes.accepted: task = taskType.parseString(response.content, True) return (True, task) else: return (False, response.content) raise Exception('can\'t find vm')
def create_or_update_task(self, status, namespace, operation_name, operation_description, owner_href, owner_name, owner_type, user_id, user_name, progress, details, org_id=None, task_id=None): if self.vcloud_session: o = urlparse(self.vcloud_session.url) api_url = '%s://%s%s' % (o.scheme, o.netloc, '/api') if progress is None: progress_indicator = '' else: progress_indicator = 'progress="%s"' % progress data = """ <Task xmlns="http://www.vmware.com/vcloud/v1.5" status="{status}" serviceNamespace="{namespace}" type="application/vnd.vmware.vcloud.task+xml" operation="{operation_description}" operationName="{operation_name}" {progress_indicator} name="task"> <Owner href="{owner_href}" name="{owner_name}" type="{owner_type}"/> <User href="{api_url}/admin/user/{user_id}" name="{user_name}" type="application/vnd.vmware.admin.user+xml"/> <Details>"{details}"</Details> </Task> """.format(status=status, namespace=namespace, operation_description=operation_description, operation_name=operation_name, progress_indicator=progress_indicator, api_url=api_url, details=details, owner_href=owner_href, owner_name=owner_name, owner_type=owner_type, user_id=user_id, user_name=user_name) if task_id is None: link = '%s/tasksList/%s' % (api_url, org_id) self.response = Http.post( link, headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify, logger=self.logger, data=data) else: link = '%s/task/%s' % (api_url, task_id) self.response = Http.put( link, headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify, logger=self.logger, data=data) if self.response.status_code == requests.codes.ok: return taskType.parseString(self.response.content, True) else: raise Exception(self.response.status_code) return None