def get_tkg_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_client_api.list_tkg_clusters(
             f"{DEF_VMWARE_VENDOR}/{DEF_TKG_ENTITY_TYPE_NSS}/{DEF_TKG_ENTITY_TYPE_VERSION}", # noqa: E501
             object_filter=filter_string)
     tkg_entities = []
     tkg_def_entities = []
     if response:
         tkg_entities = response[0]
         tkg_def_entities = response[3]
     if len(tkg_entities) == 0:
         raise cse_exceptions.ClusterNotFoundError(
             f"TKG 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
Exemple #2
0
    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
Exemple #3
0
 def get_right_bundle_by_name(self, right_bundle_name):
     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=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_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)
        # tkg_def_entities in the following statement represents the
        # information associated with the defined entity
        (entities, status, headers, tkg_def_entities) = \
            self._tkg_client_api.list_tkg_clusters(
                f"{DEF_VMWARE_VENDOR}/{DEF_TKG_ENTITY_TYPE_NSS}/{DEF_TKG_ENTITY_TYPE_VERSION}",  # noqa: E501
                _return_http_data_only=False,
                object_filter=filter_string)
        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)
        return clusters
Exemple #5
0
    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)
Exemple #6
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