def get_tkg_s_clusters_by_name(self, name, vdc=None, org=None): self.set_tenant_org_context(org_name=org) filters = {cli_constants.TKGEntityFilterKey.CLUSTER_NAME.value: name} if vdc: filters[cli_constants.TKGEntityFilterKey.VDC_NAME.value] = vdc filter_string = utils.construct_filter_string(filters) response = \ self._tkg_s_client_api.list_tkg_clusters( f"{Vendor.VMWARE}/{Nss.TKG}/1.0.0", object_filter=filter_string) tkg_entities = [] tkg_def_entities = [] if response: tkg_entities = response[0] tkg_def_entities = response[3]['entityDetails'] if len(tkg_entities) == 0: raise cse_exceptions.ClusterNotFoundError( f"TKG-S cluster with name '{name}' not found.") if len(tkg_entities) > 1: if not org: raise cse_exceptions.CseDuplicateClusterError( f"Multiple clusters with the name '{name}' found." " Please specify the org using --org flag.") raise cse_exceptions.CseDuplicateClusterError( f"Multiple clusters with the name '{name}' present in the" "same Organization. Please contact the administrator.") return tkg_entities, tkg_def_entities
def list_entities_by_entity_type(self, vendor: str, nss: str, version: str, filters: dict = None) -> List[DefEntity]: """List entities of a given entity type. vCD's behavior when invalid filter keys are passed: * It will throw a 400 if invalid first-level filter keys are passed Valid keys : [name, id, externalId, entityType, entity, state]. * It will simply return empty list on passing any invalid nested properties. :param str vendor: Vendor of the entity type :param str nss: nss of the entity type :param str version: version of the entity type :param dict filters: Key-value pairs representing filter options :return: List of entities of that entity type :rtype: Generator[DefEntity, None, None] """ filter_string = utils.construct_filter_string(filters) page_num = 0 while True: page_num += 1 query_string = f"page={page_num}&sortAsc=name" if filter_string: query_string = f"filter={filter_string}&{query_string}" response_body = self._cloudapi_client.do_request( method=RequestMethod.GET, cloudapi_version=CloudApiVersion.VERSION_1_0_0, resource_url_relative_path=f"{CloudApiResource.ENTITIES}/" f"{CloudApiResource.ENTITY_TYPES_TOKEN}/" # noqa: E501 f"{vendor}/{nss}/{version}?{query_string}") # noqa: E501 if len(response_body['values']) == 0: break for entity in response_body['values']: yield DefEntity(**entity)
def get_entities_per_page_by_entity_type( self, vendor: str, nss: str, version: str, # noqa: E501 filters: dict = None, page_number: int = CSE_PAGINATION_FIRST_PAGE_NUMBER, # noqa: E501 page_size: int = CSE_PAGINATION_DEFAULT_PAGE_SIZE): # noqa: E501 """List all the entities per page and entity type. :param str vendor: entity type vendor name :param str nss: entity type namespace :param str version: entity type version :param dict filters: additional filters :param int page_number: page to return :param int page_size: number of records per page :rtype: Generator[(List[DefEntity], int), None, None] """ filter_string = utils.construct_filter_string(filters) query_string = f"page={page_number}&pageSize={page_size}" if filter_string: query_string = f"filter={filter_string}&{query_string}" response_body = self._cloudapi_client.do_request( method=RequestMethod.GET, cloudapi_version=CloudApiVersion.VERSION_1_0_0, resource_url_relative_path=f"{CloudApiResource.ENTITIES}/" f"{CloudApiResource.ENTITY_TYPES_TOKEN}/" # noqa: E501 f"{vendor}/{nss}/{version}?{query_string}") # noqa: E501 result = {} entity_list: list[DefEntity] = [] for v in response_body['values']: entity_list.append(DefEntity(**v)) result[PaginationKey.RESULT_TOTAL] = int(response_body['resultTotal']) result[PaginationKey.VALUES] = entity_list return result
def get_all_entities_per_page_by_interface(self, vendor: str, nss: str, version: str, # noqa: E501 filters: dict = None, page_number: int = CSE_PAGINATION_FIRST_PAGE_NUMBER, # noqa: E501 page_size: int = CSE_PAGINATION_DEFAULT_PAGE_SIZE): # noqa: E501 """Get a page of entities belonging to an interface. An interface is uniquely identified by properties vendor, nss and version. :param str vendor: Vendor of the interface :param str nss: nss of the interface :param str version: version of the interface :return: Generator of entities of that interface type :rtype: Generator[List, None, None] """ filter_string = utils.construct_filter_string(filters) query_string = f"page={page_number}&pageSize={page_size}" if filter_string: query_string = f"filter={filter_string}&{query_string}" response_body = self._cloudapi_client.do_request( method=RequestMethod.GET, cloudapi_version=CloudApiVersion.VERSION_1_0_0, resource_url_relative_path=f"{CloudApiResource.ENTITIES}/" f"{CloudApiResource.INTERFACES}/" f"{vendor}/{nss}/{version}?{query_string}") # noqa: E501 result = {} entity_list = [] for entity in response_body['values']: entity_list.append(GenericClusterEntity(**entity)) result[PaginationKey.RESULT_TOTAL] = int(response_body['resultTotal']) result[PaginationKey.PAGE_COUNT] = int(response_body['pageCount']) result[PaginationKey.PAGE_NUMBER] = page_number result[PaginationKey.PAGE_SIZE] = page_size result[PaginationKey.VALUES] = entity_list return result
def get_all_vdc_compute_policies(self, filters=None): """Get all compute policies in vCD. Returns a generator that when iterated over will yield all compute policies in vCD, making multiple requests when necessary. This is implemented with a generator because cloudapi paginates the `GET /vdcComputePolicies` endpoint. :param dict filters: key and value pairs to filter the results :return: Generator that yields all compute policies in vCD :rtype: Generator[Dict, None, None] """ self._raise_error_if_not_supported() filter_string = utils.construct_filter_string(filters) cloudapiResource = cloudapi_constants.CloudApiResource page_num = 0 while True: page_num += 1 # without the &sortAsc parameter, vCD returns unpredictable results query_string = f"page={page_num}&sortAsc=name" if filter_string: query_string = f"filter={filter_string}&{query_string}" # without the &sortAsc parameter, vCD returns unpredictable results response_body = self._cloudapi_client.do_request( method=RequestMethod.GET, cloudapi_version=self._cloudapi_version, resource_url_relative_path= f"{cloudapiResource.VDC_COMPUTE_POLICIES}?{query_string}" ) # noqa: E501 if len(response_body['values']) == 0: break for policy in response_body['values']: yield policy
def list_tkg_clusters(self, vdc=None, org=None): """List all the TKG clusters. :param str vdc: name of vdc to filter by :param str org: name of the org to filter by :return: list of TKG cluster information. :rtype: List[dict] """ self.set_tenant_org_context(org_name=org) filters = {} if vdc: filters[cli_constants.TKGEntityFilterKey.VDC_NAME.value] = vdc filter_string = utils.construct_filter_string(filters) query_params = { shared_constants.PaginationKey.PAGE_NUMBER.value: shared_constants.CSE_PAGINATION_FIRST_PAGE_NUMBER, # noqa: E501 shared_constants.PaginationKey.PAGE_SIZE.value: shared_constants.CSE_PAGINATION_DEFAULT_PAGE_SIZE # noqa: E501 } has_more_results = True while has_more_results: (entities, status, headers, additional_details) = \ self._tkg_client_api.list_tkg_clusters( TKGEntityTypeMetadata_1_0_0.get_id(), _return_http_data_only=False, object_filter=filter_string, query_params=query_params) # tkg_def_entities in the following statement represents the # information associated with the defined entity tkg_def_entities = additional_details['entityDetails'] clusters = [] for i in range(len(entities)): # NOTE: tkg_def_entities will contain corresponding defined # entity details entity: TkgCluster = entities[i] entity_properties = tkg_def_entities[i] logger.CLIENT_LOGGER.debug(f"TKG Defined entity list from server: {entity}") # noqa: E501 cluster = { cli_constants.CLIOutputKey.CLUSTER_NAME.value: entity.metadata.name, # noqa: E501 cli_constants.CLIOutputKey.VDC.value: entity.metadata.virtual_data_center_name, # noqa: E501 cli_constants.CLIOutputKey.ORG.value: entity_properties['org']['name'], # noqa: E501 cli_constants.CLIOutputKey.K8S_RUNTIME.value: shared_constants.ClusterEntityKind.TKG.value, # noqa: E501 cli_constants.CLIOutputKey.K8S_VERSION.value: entity.spec.distribution.version, # noqa: E501 cli_constants.CLIOutputKey.STATUS.value: entity.status.phase if entity.status else 'N/A', # noqa: E501 cli_constants.CLIOutputKey.OWNER.value: entity_properties['owner']['name'], # noqa: E501 } clusters.append(cluster) has_more_results = additional_details['page'] < additional_details['pageCount'] # noqa: E501 yield clusters, has_more_results query_params[shared_constants.PaginationKey.PAGE_NUMBER.value] += 1
def get_right_bundle_by_name(self, right_bundle_name): """Get Right bundle by name. :param: right_bundle_name: string :returns: right bundle json object """ filters = {'name': right_bundle_name} filter_string = utils.construct_filter_string(filters) query_string = "" if filter_string: query_string = f"filter={filter_string}" response_body = self.cloudapi_client.do_request( method=shared_constants.RequestMethod.GET, cloudapi_version=CloudApiVersion.VERSION_1_0_0, resource_url_relative_path=f"{CloudApiResource.RIGHT_BUNDLES}?{query_string}") # noqa: E501 right_bundles = response_body['values'] if right_bundles and len(right_bundles) > 0: return right_bundles[0]
def list_compute_policies_on_vdc(self, vdc_id, filters=None): """List all compute policies currently assigned to a given vdc. :param str vdc_id: id of the vdc for which policies need to be retrieved. :param dict filters: dictionary of key value pairs for filtering :return: Generator that yields all vdc compute policies associated with the VDC after filtering :rtype: Generator[Dict, None, None] """ self._raise_error_if_not_supported() vdc_urn = self._generate_vdc_urn_from_id(vdc_id=vdc_id) relative_path = f"vdcs/{vdc_urn}/computePolicies" filter_string = utils.construct_filter_string(filters) page_num = 0 while True: page_num += 1 # without the &sortAsc parameter, vCD returns unpredictable results query_string = f"page={page_num}&sortAsc=name" if filter_string: query_string = f"filter={filter_string}&{query_string}" response_body = self._cloudapi_client.do_request( method=RequestMethod.GET, cloudapi_version=self._cloudapi_version, resource_url_relative_path=f"{relative_path}?{query_string}" ) # noqa: E501 if len(response_body['values']) == 0: break for cp in response_body['values']: policy = { 'name': cp.get('name'), 'href': self._get_policy_href(cp.get('id')), 'id': cp.get('id') } yield policy