def get_user_in_org(self, user_name, org_href): """Retrieve user from a particular org. :param user_name: user name to be retrieved. :param org_href: org where the user belongs. :return: A :class:`lxml.objectify.StringElement` object representing the user """ resource_type = 'user' org_filter = None if self.is_sysadmin(): resource_type = 'adminUser' org_filter = 'org==%s' % org_href query = self.get_typed_query( resource_type, query_result_format=QueryResultFormat.REFERENCES, equality_filter=('name', user_name), qfilter=org_filter) records = list(query.execute()) if len(records) == 0: raise EntityNotFoundException('user \'%s\' not found' % user_name) elif len(records) > 1: raise MultipleRecordsException('multiple users found') return self.get_resource(records[0].get('href'))
def find_unique(self): """Convenience wrapper over execute(). Convenience wrapper over execute() for the case where exactly one match is expected. """ query_results = self.execute() # Make sure we got at least one result record try: if sys.version_info[0] < 3: item = query_results.next() else: item = next(query_results) except StopIteration: raise MissingRecordException() # Make sure we didn't get more than one result record try: if sys.version_info[0] < 3: query_results.next() else: next(query_results) raise MultipleRecordsException() except StopIteration: pass return item
def _get_extension_record(self, name, namespace=None, format=QueryResultFormat.ID_RECORDS): """Fetch info about a particular API extension service as a record. :param str name: the name of the extension service whose info we want to retrieve. :param str namespace: the namespace of the extension service. If omitted, all extension services matching the given name will be retrieved and that would lead to a MultipleRecordsException. :param format QueryResultFormat: dictates whether id or href should be part of the returned record. By default id is returned. :return: the extension service record. :rtype: generator object that returns lxml.objectify.ObjectifiedElement object containing AdminServiceRecord XML data representing the service. :raises MissingRecordException: if a service with the given name and namespace couldn't be found. :raise MultipleRecordsException: if more than one service with the given name and namespace are found. """ qfilter = 'name==%s' % urllib.parse.quote_plus(name) if namespace is not None: qfilter += ';namespace==%s' % urllib.parse.quote_plus(namespace) try: ext = self.client.get_typed_query( ResourceType.ADMIN_SERVICE.value, qfilter=qfilter, query_result_format=format).find_unique() except OperationNotSupportedException as e: msg = 'User doesn\'t have permission to interact with extensions.' raise OperationNotSupportedException(msg) except MissingRecordException as e: msg = 'API Extension service (name:' + name if namespace is not None: msg += ', namespace:' + namespace msg += ') not found.' raise MissingRecordException(msg) except MultipleRecordsException as e: msg = 'Found multiple API Extension service with (name:' + name if namespace is not None: msg += ', namespace:' + namespace + ').' else: msg += '). Consider providing value for the namespace.' raise MultipleRecordsException(msg) return ext
def ___validate_vapp_records(self, vapp_name, resource_type): name_filter = ('name', vapp_name) q1 = self.client.get_typed_query( resource_type, query_result_format=QueryResultFormat.REFERENCES, equality_filter=name_filter) records = list(q1.execute()) if records is None or len(records) == 0: raise EntityNotFoundException('Vapp with name \'%s\' not found.' % vapp_name) elif len(records) > 1: raise MultipleRecordsException("Found multiple vapp named " "'%s'," % vapp_name) return records
def _get_gateway( client: vcd_client.Client, org_name: str, network_name: str, ): config = server_utils.get_server_runtime_config() logger_wire = NULL_LOGGER if utils.str_to_bool(config.get_value_at('service.log_wire')): logger_wire = SERVER_CLOUDAPI_WIRE_LOGGER cloudapi_client = vcd_utils.get_cloudapi_client_from_vcd_client( client=client, logger_debug=LOGGER, logger_wire=logger_wire) gateway_name, gateway_href, gateway_exists = None, None, False page, page_count = 1, 1 base_path = f'{cloudapi_constants.CloudApiResource.ORG_VDC_NETWORKS}?filter=name=={network_name};_context==includeAccessible&pageSize=1&page=' # noqa: E501 while page <= page_count: response, headers = cloudapi_client.do_request( method=RequestMethod.GET, cloudapi_version=cloudapi_constants.CloudApiVersion.VERSION_1_0_0, resource_url_relative_path=base_path + f'{page}', return_response_headers=True) for entry in response['values']: # only routed networks allowed is_target_network = entry['orgRef']['name'] == org_name and \ entry['networkType'] == 'NAT_ROUTED' if is_target_network: if gateway_exists: raise MultipleRecordsException( f"Multiple routed networks named {network_name} found. CSE Server expects unique network names." ) # noqa: E501 gateway_exists = True gateway_name = entry['connection']['routerRef']['name'] gateway_id = entry['connection']['routerRef']['id'].split( ':').pop() # noqa: E501 gateway_href = headers['Content-Location'].split('cloudapi')[ 0] + f'api/admin/edgeGateway/{gateway_id}' # noqa: E501 page += 1 page_count = response['pageCount'] if not gateway_exists: raise EntityNotFoundException( f"No routed networks named {network_name} found.") # noqa: E501 gateway = vcd_gateway.Gateway(client, name=gateway_name, href=gateway_href) return gateway
def get_disk(self, name=None, disk_id=None): """Return information for an independent disk. :param name: (str): The name of the disk. :param disk_id: (str): The id of the disk. :return: A :class:`lxml.objectify.StringElement` object describing the existing disk. :raises: Exception: If the named disk cannot be located or some other error occurs. """ if name is None and disk_id is None: raise InvalidParameterException( 'Unable to idendify disk without name or id.') if self.resource is None: self.resource = self.client.get_resource(self.href) disks = self.get_disks() result = None if disk_id is not None: if not disk_id.startswith('urn:vcloud:disk:'): disk_id = 'urn:vcloud:disk:' + disk_id for disk in disks: if disk.get('id') == disk_id: result = disk # disk-id's are unique so it's ok to break the loop # and stop looking further. break elif name is not None: for disk in disks: if disk.get('name') == name: if result is None: result = disk else: raise MultipleRecordsException( 'Found multiple disks with name %s' ', please identify disk via disk-id.' % disk.get('name')) if result is None: raise EntityNotFoundException( 'No disk found with the given name/id.') else: return result
def get_resource_href(self, name, entity_type=EntityType.VAPP): if self.resource is None: self.resource = self.client.get_resource(self.href) result = [] if hasattr(self.resource, 'ResourceEntities') and \ hasattr(self.resource.ResourceEntities, 'ResourceEntity'): for vapp in self.resource.ResourceEntities.ResourceEntity: if entity_type is None or \ entity_type.value == vapp.get('type'): if vapp.get('name') == name: result.append(vapp.get('href')) if len(result) == 0: raise EntityNotFoundException('vApp named \'%s\' not found' % name) elif len(result) > 1: raise MultipleRecordsException("Found multiple vApps named " + "\'%s\', use the vapp-id to " "identify." % name) return result[0]
def _get_parent_by_name(self): """Get a gateway by name. :return: gateway :rtype: lxml.objectify.ObjectifiedElement :raises: EntityNotFoundException: if the named gateway can not be found. :raises: MultipleRecordsException: if more than one gateway with the provided name are found. """ name_filter = ('name', self.gateway_name) query = self.client.get_typed_query( ResourceType.EDGE_GATEWAY.value, query_result_format=QueryResultFormat.RECORDS, equality_filter=name_filter) records = list(query.execute()) if records is None or len(records) == 0: raise EntityNotFoundException( 'Gateway with name \'%s\' not found.' % self.gateway_name) elif len(records) > 1: raise MultipleRecordsException("Found multiple gateway named " "'%s'," % self.gateway_name) return records[0]