コード例 #1
0
    def _VerifyClusterExclusivity(self, kube_client, parent, membership_id):
        """Verifies that the cluster can be registered to the project.

    Args:
      kube_client: a KubernetesClient
      parent: the parent collection the user is attempting to register the
        cluster with.
      membership_id: the ID of the membership to be created for the cluster.

    Raises:
      apitools.base.py.HttpError: if the API request returns an HTTP error.
      exceptions.Error: if the cluster is in an invalid exclusivity state.
    """

        cr_manifest = ''
        # The cluster has been registered.
        if kube_client.MembershipCRDExists():
            cr_manifest = kube_client.GetMembershipCR()

        res = api_util.ValidateExclusivity(cr_manifest, parent, membership_id,
                                           self.ReleaseTrack())

        if res.status.code:
            raise exceptions.Error(
                ('invalid exclusivity state: {}. If you want ' +
                 'to register the cluster to with {}, please ' +
                 'unregister this cluster first.').format(
                     parent, res.status.message))
コード例 #2
0
ファイル: register.py プロジェクト: saranraju90/multik8s
    def _VerifyClusterExclusivity(self, kube_client, parent, membership_id):
        """Verifies that the cluster can be registered to the project.

    Args:
      kube_client: a KubernetesClient
      parent: the parent collection the user is attempting to register the
        cluster with.
      membership_id: the ID of the membership to be created for the cluster.

    Raises:
      apitools.base.py.HttpError: if the API request returns an HTTP error.
      exceptions.Error: if the cluster is in an invalid exclusivity state.
    """

        cr_manifest = ''
        # The cluster has been registered.
        if kube_client.MembershipCRDExists():
            cr_manifest = kube_client.GetMembershipCR()

        res = api_util.ValidateExclusivity(cr_manifest, parent, membership_id,
                                           self.ReleaseTrack())

        if res.status.code:
            raise exceptions.Error(
                'Error validating cluster\'s exclusivity state '
                'with the Hub under parent collection [{}]: {}. '
                'Cannot proceed with the cluster registration.'.format(
                    parent, res.status.message))
コード例 #3
0
    def Run(self, args):
        project = arg_utils.GetFromNamespace(args,
                                             '--project',
                                             use_defaults=True)
        kube_client = kube_util.KubernetesClient(args)
        kube_client.CheckClusterAdminPermissions()
        kube_util.ValidateClusterIdentifierFlags(kube_client, args)
        membership_id = args.CLUSTER_NAME

        # Delete membership from Hub API.
        try:
            name = 'projects/{}/locations/global/memberships/{}'.format(
                project, membership_id)
            obj = api_util.GetMembership(name, self.ReleaseTrack())
            if not obj.externalId:
                console_io.PromptContinue(
                    'invalid membership {0} does not have '
                    'external_id field set. We cannot determine '
                    'if registration is requested against a '
                    'valid existing Membership. Consult the '
                    'documentation on container hub memberships '
                    'update for more information or run gcloud '
                    'container hub memberships delete {0} if you '
                    'are sure that this is an invalid or '
                    'otherwise stale Membership'.format(membership_id),
                    cancel_on_no=True)
            uuid = kube_util.GetClusterUUID(kube_client)
            if obj.externalId != uuid:
                raise exceptions.Error(
                    'Membership [{}] is not associated with the cluster you are trying'
                    ' to unregister. Please double check the cluster identifier that you'
                    ' have supplied.'.format(membership_id))

            api_util.DeleteMembership(name, self.ReleaseTrack())
        except apitools_exceptions.HttpUnauthorizedError as e:
            raise exceptions.Error(
                'You are not authorized to unregister clusters from project [{}]. '
                'Underlying error: {}'.format(project, e))
        except apitools_exceptions.HttpNotFoundError as e:
            log.status.Print(
                'Membership [{}] for the cluster [{}] was not found on the Hub. '
                'It may already have been deleted, or it may never have existed.'
                .format(name, args.CLUSTER_NAME))

        # enable_workload_identity and manage_workload_identity_bucket are only
        # properties if we are on the alpha track.
        if (self.ReleaseTrack() is base.ReleaseTrack.ALPHA
                and args.manage_workload_identity_bucket):
            # The issuer URL from the cluster indicates which bucket to delete.
            # --manage-workload-identity-bucket always uses the cluster's
            # built-in endpoints.
            openid_config_json = None
            try:
                openid_config_json = kube_client.GetOpenIDConfiguration()
            except exceptions.Error as e:
                log.status.Print(
                    'Cannot get the issuer URL that identifies the bucket associated '
                    'with this membership. Please double check that it is possible to '
                    'access the /.well-known/openid-configuration endpoint on the '
                    'cluster: {}'.format(e))

            if openid_config_json:
                issuer_url = json.loads(openid_config_json).get('issuer')
                if not issuer_url:
                    log.status.Print(
                        'Cannot get the issuer URL that identifies the bucket associated '
                        'with this membership. The OpenID Config from '
                        '/.well-known/openid-configuration is missing the issuer field: '
                        '{}'.format(openid_config_json))

                try:
                    api_util.DeleteWorkloadIdentityBucket(issuer_url)
                except exceptions.Error as e:
                    log.status.Print(
                        'Failed to delete bucket for issuer {}: {}'.format(
                            issuer_url, e))

        # Get namespace for the connect resource label.
        selector = '{}={}'.format(agent_util.CONNECT_RESOURCE_LABEL, project)
        namespaces = kube_client.NamespacesWithLabelSelector(selector)
        if not namespaces:
            log.status.Print(
                'There\'s no namespace for the label [{}]. '
                'If [gke-connect] is labeled with another project, '
                'You\'ll have to manually delete the namespace. '
                'You can find all namespaces by running:\n'
                '  `kubectl get ns -l {}`'.format(
                    agent_util.CONNECT_RESOURCE_LABEL,
                    agent_util.CONNECT_RESOURCE_LABEL))

        # Delete in-cluster membership resources.
        try:
            parent = api_util.ParentRef(project, 'global')
            cr_manifest = kube_client.GetMembershipCR()

            res = api_util.ValidateExclusivity(cr_manifest, parent,
                                               membership_id,
                                               self.ReleaseTrack())
            if res.status.code:
                console_io.PromptContinue(
                    'Error validating cluster\'s exclusivity state with the Hub under '
                    'parent collection [{}]: {}. The cluster you are trying to unregister'
                    ' is not associated with the membership [{}]. Continuing will delete'
                    ' membership related resources from your cluster, and the cluster'
                    ' will lose its association to the Hub in project [{}] and can be'
                    ' registered into a different project. '.format(
                        parent, res.status.message, membership_id, project),
                    cancel_on_no=True)
            exclusivity_util.DeleteMembershipResources(kube_client)
        except exceptions.Error as e:
            log.status.Print(
                '{} error in deleting in-cluster membership resources. '
                'You can manually delete these membership related '
                'resources from your cluster by running the command:\n'
                '  `kubectl delete memberships membership`.\nBy doing so, '
                'the cluster will lose its association to the Hub in '
                'project [{}] and can be registered into a different '
                'project. '.format(e, project))

        # Delete the connect agent.
        agent_util.DeleteConnectNamespace(kube_client, args)