示例#1
0
    def get_cluster_info(self,
                         cluster_name,
                         cluster_id=None,
                         org=None,
                         vdc=None,
                         **kwargs):
        """Get cluster information using DEF API.

        :param str cluster_name: name of the cluster
        :param str vdc: name of vdc
        :param str org: name of org
        :param kwargs: *filter (dict): keys,values for DEF API query filter

        :return: cluster information
        :rtype: dict
        """
        if cluster_id:
            return self.get_cluster_info_by_id(cluster_id)
        filters = client_utils.construct_filters(org=org, vdc=vdc)
        entity_svc = def_entity_svc.DefEntityService(self._cloudapi_client)
        def_entity = entity_svc.get_native_entity_by_name(
            name=cluster_name, filters=filters)  # noqa: E501
        logger.CLIENT_LOGGER.debug(
            f"Defined entity info from server:{def_entity}")  # noqa: E501
        if not def_entity:
            logger.CLIENT_LOGGER.error(
                f"Cannot find native cluster with name {cluster_name}"
            )  # noqa: E501
            raise cse_exceptions.ClusterNotFoundError(
                f"Cluster '{cluster_name}' not found.")  # noqa: E501
        # TODO() relevant output
        if def_entity:
            return yaml.dump(asdict(def_entity.entity))
示例#2
0
    def upgrade_cluster(self,
                        cluster_name,
                        template_name,
                        template_revision,
                        org_name=None,
                        ovdc_name=None):
        """Get the upgrade plan for given cluster.

        :param str cluster_name: name of the cluster
        :param str template_name: Name of the template the cluster should be
        upgraded to.
        :param str template_revision: Revision of the template the cluster
        should be upgraded to.
        :param org_name: name of the org
        :param ovdc_name: name of the vdc
        :return: string containing upgrade cluster task href
        :rtype: str
        """
        filters = client_utils.construct_filters(org=org_name, vdc=ovdc_name)
        entity_svc = def_entity_svc.DefEntityService(self._cloudapi_client)
        current_entity = entity_svc.get_native_entity_by_name(
            name=cluster_name, filters=filters)  # noqa: E501
        if current_entity:
            current_entity.entity.spec.k8_distribution.template_name = template_name  # noqa: E501
            current_entity.entity.spec.k8_distribution.template_revision = template_revision  # noqa: E501
            return self.upgrade_cluster_by_cluster_id(
                current_entity.id,
                cluster_def_entity=asdict(current_entity))  # noqa: E501
        raise cse_exceptions.ClusterNotFoundError(
            f"Cluster '{cluster_name}' not found.")  # noqa: E501
示例#3
0
    def get_cluster_config(self,
                           cluster_name,
                           cluster_id=None,
                           org=None,
                           vdc=None):
        """Get cluster config for the given cluster name.

        :param str cluster_name: name of the cluster
        :param str vdc: name of vdc
        :param str org: name of org

        :return: cluster information
        :rtype: str
        :raises ClusterNotFoundError, CseDuplicateClusterError
        """
        if not cluster_id:
            filters = client_utils.construct_filters(org=org, vdc=vdc)
            entity_svc = def_entity_svc.DefEntityService(self._cloudapi_client)
            def_entity = entity_svc.get_native_entity_by_name(
                name=cluster_name, filters=filters)  # noqa: E501
            if not def_entity:
                raise cse_exceptions.ClusterNotFoundError(
                    f"Cluster '{cluster_name}' not found.")  # noqa: E501
            cluster_id = def_entity.id
        return self.get_cluster_config_by_id(cluster_id)
    def get_cluster_config_by_id(self, cluster_id, org=None):
        """Fetch kube config of the cluster using cluster ID.

        :param str cluster_id:
        :param str org:
        """
        entity_svc = def_entity_svc.DefEntityService(self._cloudapi_client)
        if entity_svc.is_native_entity(cluster_id):
            return self._nativeCluster.get_cluster_config_by_id(cluster_id)
        return self._tkgCluster.get_cluster_config_by_id(cluster_id, org=org)
示例#5
0
    def get_cluster_info_by_id(self, cluster_id, **kwargs):
        """Get cluster information by cluster ID.

        :param str cluster_id: ID of the cluster
        :return: cluster information in yaml format
        :rtype: str
        """
        entity_svc = def_entity_svc.DefEntityService(self._cloudapi_client)
        def_entity = entity_svc.get_entity(cluster_id)
        logger.CLIENT_LOGGER.debug(
            f"Defined entity info from server: {def_entity}")  # noqa: E501
        return yaml.dump(asdict(def_entity.entity))
    def delete_cluster_by_id(self, cluster_id, org=None):
        """Delete cluster using cluster id.

        :param str cluster_id: id of the cluster to be deleted
        :return: deleted cluster information
        :rtype: str
        :raises: ClusterNotFoundError
        """
        entity_svc = def_entity_svc.DefEntityService(self._cloudapi_client)
        if entity_svc.is_native_entity(cluster_id):
            return self._nativeCluster.delete_cluster_by_id(cluster_id)
        return self._tkgCluster.delete_cluster_by_id(cluster_id, org=org)
    def get_cluster_info_by_id(self, cluster_id, org=None):
        """Obtain cluster information using cluster ID.

        :param str cluster_id
        :return: yaml representation of the cluster information
        :rtype: str
        """
        entity_svc = def_entity_svc.DefEntityService(self._cloudapi_client)
        if entity_svc.is_native_entity(cluster_id):
            return self._nativeCluster.get_cluster_info_by_id(
                cluster_id=cluster_id)  # noqa: E501
        return self._tkgCluster.get_cluster_info_by_id(cluster_id,
                                                       org=org)  # noqa: E501
示例#8
0
    def get_upgrade_plan(self, cluster_name, org=None, vdc=None):
        """Get the upgrade plan for given cluster.

        :param cluster_name: name of the cluster
        :param org: name of the org
        :param vdc: name of the vdc
        :return: upgrade plan info
        :rtype: dict
        """
        filters = client_utils.construct_filters(org=org, vdc=vdc)
        entity_svc = def_entity_svc.DefEntityService(self._cloudapi_client)
        def_entity = entity_svc.get_native_entity_by_name(
            name=cluster_name, filters=filters)  # noqa: E501
        if def_entity:
            return self.get_upgrade_plan_by_cluster_id(def_entity.id)
        raise cse_exceptions.ClusterNotFoundError(
            f"Cluster '{cluster_name}' not found.")  # noqa: E501
示例#9
0
    def delete_nfs_node(self, cluster_name, node_name, org=None, vdc=None):
        """Delete nfs node given the cluster name and node name.

        :param str cluster_name: native cluster name
        :param str node_name: nfs-node name
        :param str org: name of the org
        :param str vdc: name of the vdc
        :return: string containing delete operation task href
        :rtype: str
        :raises ClusterNotFoundError
        """
        filters = client_utils.construct_filters(org=org, vdc=vdc)
        entity_svc = def_entity_svc.DefEntityService(self._cloudapi_client)
        def_entity = entity_svc.get_native_entity_by_name(
            name=cluster_name, filters=filters)  # noqa: E501
        if def_entity:
            return self.delete_nfs_by_cluster_id(def_entity.id, node_name)
        raise cse_exceptions.ClusterNotFoundError(
            f"Cluster '{cluster_name}' not found.")  # noqa: E501
示例#10
0
    def apply(self, cluster_config, cluster_id=None, **kwargs):
        """Apply the configuration either to create or update the cluster.

        :param dict cluster_config: cluster configuration information
        :return: dictionary containing the apply operation task
        :rtype: dict
        """
        entity_svc = def_entity_svc.DefEntityService(self._cloudapi_client)
        cluster_spec = def_models.ClusterEntity(**cluster_config)
        cluster_name = cluster_spec.metadata.cluster_name
        if cluster_id:
            # If cluster id doesn't exist, an exception will be raised
            def_entity = entity_svc.get_entity(cluster_id)
        else:
            def_entity = entity_svc.get_native_entity_by_name(cluster_name)
        if not def_entity:
            cluster_entity = self._native_cluster_api.create_cluster(
                cluster_spec)  # noqa: E501
        else:
            cluster_id = def_entity.id
            cluster_entity = \
                self._native_cluster_api.update_cluster_by_cluster_id(cluster_id, cluster_spec)  # noqa: E501
        return client_utils.construct_task_console_message(
            cluster_entity.entity.status.task_href)  # noqa: E501
示例#11
0
    def delete_cluster(self,
                       cluster_name,
                       cluster_id=None,
                       org=None,
                       vdc=None):
        """Delete DEF native cluster by name.

        :param str cluster_name: native cluster name
        :param str org: name of the org
        :param str vdc: name of the vdc
        :return: string containing delete operation task href
        :rtype: str
        :raises ClusterNotFoundError
        """
        if not cluster_id:
            filters = client_utils.construct_filters(org=org, vdc=vdc)
            entity_svc = def_entity_svc.DefEntityService(self._cloudapi_client)
            def_entity = entity_svc.get_native_entity_by_name(
                name=cluster_name, filters=filters)  # noqa: E501
            if not def_entity:
                raise cse_exceptions.ClusterNotFoundError(
                    f"Cluster '{cluster_name}' not found.")  # noqa: E501
            cluster_id = def_entity.id
        return self.delete_cluster_by_id(cluster_id)
    def list_clusters(self, vdc=None, org=None, **kwargs):
        """Get collection of clusters using DEF API.

        :param str vdc: name of vdc
        :param str org: name of org
        :param kwargs: *filter (dict): keys,values for DEF API query filter

        :return: cluster list information
        :rtype: list(dict)
        """
        has_native_rights = True
        has_tkg_rights = True
        clusters = []
        try:
            clusters += self._tkgCluster.list_tkg_clusters(vdc=vdc, org=org)
        except tkg_rest.ApiException as e:
            if e.status not in [
                    requests.codes.FORBIDDEN, requests.codes.UNAUTHORIZED
            ]:  # noqa: E501
                server_message = json.loads(e.body).get('message') or e.reason
                msg = cli_constants.TKG_RESPONSE_MESSAGES_BY_STATUS_CODE.get(
                    e.status, f"{server_message}")  # noqa: E501
                logger.CLIENT_LOGGER.error(msg)
                raise Exception(msg)
            logger.CLIENT_LOGGER.debug(
                f"No rights present to fetch TKG clusters: {e}")  # noqa: E501
            has_tkg_rights = False
        if not client_utils.is_cli_for_tkg_only():
            filters = client_utils.construct_filters(org=org, vdc=vdc)
            entity_svc = def_entity_svc.DefEntityService(self._cloudapi_client)
            native_entities = entity_svc.list_entities_by_entity_type(
                vendor=DEF_CSE_VENDOR,
                nss=DEF_NATIVE_ENTITY_TYPE_NSS,
                version=DEF_NATIVE_ENTITY_TYPE_VERSION,
                filters=filters)
            try:
                for def_entity in native_entities:
                    entity = def_entity.entity
                    logger.CLIENT_LOGGER.debug(
                        f"Native Defined entity list from server: {def_entity}"
                    )  # noqa: E501
                    cluster = {
                        cli_constants.CLIOutputKey.CLUSTER_NAME.value:
                        def_entity.name,  # noqa: E501
                        cli_constants.CLIOutputKey.VDC.value:
                        entity.metadata.ovdc_name,  # noqa: E501
                        cli_constants.CLIOutputKey.ORG.value:
                        entity.metadata.org_name,  # noqa: E501
                        cli_constants.CLIOutputKey.K8S_RUNTIME.value:
                        entity.kind,  # noqa: E501
                        cli_constants.CLIOutputKey.K8S_VERSION.value:
                        entity.status.kubernetes,  # noqa: E501
                        cli_constants.CLIOutputKey.STATUS.value:
                        entity.status.phase,  # noqa: E501
                        cli_constants.CLIOutputKey.OWNER.value:
                        def_entity.owner.name  # noqa: E501
                    }
                    clusters.append(cluster)
            except requests.exceptions.HTTPError as e:
                if e.response.status_code not in [
                        requests.codes.FORBIDDEN, requests.codes.UNAUTHORIZED
                ]:  # noqa: E501
                    logger.CLIENT_LOGGER.error(
                        f"Failed to fetch native clusters: {str(e)}"
                    )  # noqa: E501
                    raise
                logger.CLIENT_LOGGER.debug(
                    f"No rights present to fetch native clusters: {str(e)}"
                )  # noqa: E501
                has_native_rights = False
        if not (has_tkg_rights or has_native_rights):
            raise Exception("Logged in user doesn't have Native cluster rights"
                            " or TKG rights. Please contact administrator.")
        return clusters
    def _get_tkg_native_clusters_by_name(self,
                                         cluster_name: str,
                                         org=None,
                                         vdc=None):
        """Get native and TKG clusters by name.

        Assumption: Native clusters cannot have name collision among them.
        But there can be multiple TKG clusters with the same name and 2 or
        more TKG clusters can also have the same name.

        :param str cluster_name: Cluster name to search for
        :param str org: Org to filter by
        :param str vdc: VDC to filter by
        :returns: tkg entity or native def entity with entity properties and
            boolean indicating cluster type
        :rtype: (cluster, dict,  bool)
        """
        filters = client_utils.construct_filters(org=org, vdc=vdc)
        entity_svc = def_entity_svc.DefEntityService(self._cloudapi_client)
        has_native_rights = True
        has_tkg_rights = True
        native_def_entity = None
        additional_entity_properties = None
        # NOTE: The following can throw error if invoked by users who
        # doesn't have the necessary rights.
        try:
            native_def_entity = entity_svc.get_native_entity_by_name(
                name=cluster_name, filters=filters)
        except cse_exceptions.DefSchemaServiceError:
            # NOTE: 500 status code is returned which is not ideal
            # when user doesn't have native rights
            has_native_rights = False

        tkg_entity = []
        tkg_def_entity = []
        # NOTE: The following can throw error if invoked by users who
        # doesn't have the necessary rights.
        try:
            tkg_entity, tkg_def_entity = \
                self._tkgCluster.get_tkg_clusters_by_name(cluster_name,
                                                          vdc=vdc, org=org)
        except tkg_rest.ApiException as e:
            if e.status not in [
                    requests.codes.FORBIDDEN, requests.codes.UNAUTHORIZED
            ]:  # noqa: E501
                raise
            has_tkg_rights = False
        except cse_exceptions.ClusterNotFoundError:
            logger.CLIENT_LOGGER.debug(
                f"No TKG cluster with name {cluster_name}")  # noqa: E501
        if not (has_native_rights or has_tkg_rights):
            raise Exception("User cannot access native or TKG clusters."
                            " Please contact administrator")
        msg = "Multiple clusters with the same name found."
        if len(tkg_entity) > 0 and native_def_entity:
            # If org filter is not provided, ask the user to provide org
            # filter
            if not org:
                # handles the case where there is are TKG clusters and native
                # clusters with the same name in different organizations
                raise Exception(f"{msg} Please specify the org to use "
                                "using --org flag.")
            # handles the case where there is a TKG cluster and a native
            # native cluster with the same name in the same organization
            raise Exception(f"{msg} Please specify the k8-runtime to use using"
                            " --k8-runtime flag.")
        if not native_def_entity and len(tkg_entity) == 0:
            # handles the case where no clusters are found
            msg = f"Cluster '{cluster_name}' not found."
            logger.CLIENT_LOGGER.error(msg)
            raise cse_exceptions.ClusterNotFoundError(msg)
        if native_def_entity:
            cluster = native_def_entity
            is_native_cluster = True
        else:
            additional_entity_properties = tkg_def_entity[0]
            cluster = tkg_entity[0]
            is_native_cluster = False

        return cluster, additional_entity_properties, is_native_cluster