Example #1
0
  def Run(self, args):
    """This is what gets called when the user runs this command.

    Args:
      args: an argparse namespace. All the arguments that were provided to this
        command invocation.

    Returns:
      Some value that we want to have printed later.
    """
    adapter = self.context['api_adapter']

    cluster_ref = adapter.ParseCluster(args.name)

    # Make sure it exists (will raise appropriate error if not)
    adapter.GetCluster(cluster_ref)

    options = api_adapter.UpdateClusterOptions(
        update_cluster=True,
        monitoring_service=args.monitoring_service)

    try:
      op_ref = adapter.UpdateCluster(cluster_ref, options)
    except apitools_base.HttpError as error:
      raise exceptions.HttpException(util.GetError(error))

    if args.wait:
      adapter.WaitForOperation(
          op_ref, 'Updating {0}'.format(cluster_ref.clusterId))

      log.UpdatedResource(cluster_ref)
Example #2
0
    def Run(self, args):
        """This is what gets called when the user runs this command.

    Args:
      args: an argparse namespace. All the arguments that were provided to this
        command invocation.

    Returns:
      Some value that we want to have printed later.
    """
        client = self.context['container_client']
        resources = self.context['registry']

        properties.VALUES.compute.zone.Get(required=True)
        properties.VALUES.core.project.Get(required=True)
        operation_ref = resources.Parse(
            args.operation_id,
            collection='container.projects.zones.operations')

        try:
            operation = client.projects_zones_operations.Get(
                operation_ref.Request())
            return util.WaitForOperation(
                operation, operation_ref.projectId, self.context,
                'Waiting for {0} to complete'.format(
                    operation_ref.operationId))
        except apitools_base.HttpError as error:
            raise exceptions.HttpException(util.GetError(error))
Example #3
0
    def Run(self, args):
        """This is what gets called when the user runs this command.

    Args:
      args: an argparse namespace. All the arguments that were provided to this
        command invocation.

    Returns:
      Some value that we want to have printed later.
    """
        client = self.context['container_client']
        messages = self.context['container_messages']
        resources = self.context['registry']

        # ensure the project is provided
        project_id = properties.VALUES.core.project.Get(required=True)
        zone_id = None
        if args.zone:
            zone_id = resources.Parse(args.zone,
                                      collection='compute.zones').zone

        try:
            if zone_id:
                # Zone-filtered list
                req = messages.ContainerProjectsZonesClustersListRequest(
                    projectId=project_id, zoneId=zone_id)
                return client.projects_zones_clusters.List(req)
            else:
                # Global list
                req = messages.ContainerProjectsClustersListRequest(
                    projectId=project_id)
                return client.projects_clusters.List(req)
        except apitools_base.HttpError as error:
            raise exceptions.HttpException(util.GetError(error))
Example #4
0
    def Run(self, args):
        """This is what gets called when the user runs this command.

    Args:
      args: an argparse namespace. All the arguments that were provided to this
        command invocation.

    Returns:
      Cluster message for the successfully created cluster.

    Raises:
      util.Error, if creation failed.
    """
        util.CheckKubectlInstalled()
        if not args.password:
            args.password = ''.join(
                random.SystemRandom().choice(string.ascii_letters +
                                             string.digits) for _ in range(16))

        adapter = self.context['api_adapter']

        if not args.scopes:
            args.scopes = []
        cluster_ref = adapter.ParseCluster(args.name)
        options = self.ParseCreateOptions(args)

        try:
            operation_ref = adapter.CreateCluster(cluster_ref, options)
            if not args.wait:
                return adapter.GetCluster(cluster_ref)

            adapter.WaitForOperation(operation_ref,
                                     'Creating cluster {0}'.format(
                                         cluster_ref.clusterId),
                                     timeout_s=args.timeout)
            cluster = adapter.GetCluster(cluster_ref)
        except apitools_base.HttpError as error:
            raise exceptions.HttpException(util.GetError(error))

        log.CreatedResource(cluster_ref)
        # Persist cluster config
        current_context = kconfig.Kubeconfig.Default().current_context
        c_config = util.ClusterConfig.Persist(cluster, cluster_ref.projectId,
                                              self.cli)
        if not c_config.has_certs:
            # Purge config so we retry the cert fetch on next kubectl command
            util.ClusterConfig.Purge(cluster.name, cluster.zone,
                                     cluster_ref.projectId)
            # reset current context
            if current_context:
                kubeconfig = kconfig.Kubeconfig.Default()
                kubeconfig.SetCurrentContext(current_context)
                kubeconfig.SaveToFile()
            raise util.Error(
                NO_CERTS_ERROR_FMT.format(
                    command=' '.join(args.command_path[:-1] +
                                     ['get-credentials', cluster.name])))
        return cluster
Example #5
0
    def GetCluster(self, cluster_ref):
        """Get a running cluster.

    Args:
      cluster_ref: cluster Resource to describe.
    Returns:
      Cluster message.
    Raises:
      Error: if cluster cannot be found.
    """
        try:
            return self.client.projects_zones_clusters.Get(
                cluster_ref.Request())
        except apitools_base.HttpError as error:
            api_error = util.GetError(error)
            if api_error.code != 404:
                raise api_error

        # Cluster couldn't be found, maybe user got zone wrong?
        try:
            clusters = self.ListClusters(cluster_ref.projectId).clusters
        except apitools_base.HttpError as error:
            raise exceptions.HttpException(util.GetError(error))
        for cluster in clusters:
            if cluster.name == cluster_ref.clusterId:
                # User likely got zone wrong.
                raise util.Error(
                    WRONG_ZONE_ERROR_MSG.format(
                        error=api_error,
                        name=cluster_ref.clusterId,
                        wrong_zone=self.Zone(cluster_ref),
                        zone=cluster.zone))
        # Couldn't find a cluster with that name.
        raise util.Error(
            NO_SUCH_CLUSTER_ERROR_MSG.format(error=api_error,
                                             name=cluster_ref.clusterId,
                                             project=cluster_ref.projectId))
Example #6
0
  def Run(self, args):
    """This is what gets called when the user runs this command.

    Args:
      args: an argparse namespace. All the arguments that were provided to this
        command invocation.

    Returns:
      Some value that we want to have printed later.
    """
    adapter = self.context['api_adapter']

    try:
      return adapter.GetOperation(adapter.ParseOperation(args.operation_id))
    except apitools_base.HttpError as error:
      raise exceptions.HttpException(util.GetError(error))
Example #7
0
    def Run(self, args):
        """This is what gets called when the user runs this command.

    Args:
      args: an argparse namespace. All the arguments that were provided to this
        command invocation.

    Returns:
      Some value that we want to have printed later.
    """
        adapter = self.context['api_adapter']

        project_id = properties.VALUES.core.project.Get(required=True)
        zone = None
        if args.zone:
            zone = adapter.registry.Parse(args.zone,
                                          collection='compute.zones').zone

        try:
            return adapter.ListOperations(project_id, zone)
        except apitools_base.HttpError as error:
            raise exceptions.HttpException(util.GetError(error))
Example #8
0
    def Run(self, args):
        """This is what gets called when the user runs this command.

    Args:
      args: an argparse namespace. All the arguments that were provided to this
        command invocation.

    Returns:
      Some value that we want to have printed later.
    """
        client = self.context['container_client']
        messages = self.context['container_messages']
        resources = self.context['registry']

        properties.VALUES.compute.zone.Get(required=True)
        properties.VALUES.core.project.Get(required=True)
        cluster_refs = []
        for name in args.names:
            cluster_refs.append(
                resources.Parse(
                    name, collection='container.projects.zones.clusters'))

        if not console_io.PromptContinue(message=util.ConstructList(
                'The following clusters will be deleted.', [
                    '[{name}] in [{zone}]'.format(name=ref.clusterId,
                                                  zone=ref.zoneId)
                    for ref in cluster_refs
                ]),
                                         throw_if_unattended=True):
            raise exceptions.ToolException('Deletion aborted by user.')

        operations = []
        errors = []
        # Issue all deletes first
        for ref in cluster_refs:
            try:
                # Make sure it exists (will raise appropriate error if not)
                util.DescribeCluster(ref, self.context)

                op = client.projects_zones_clusters.Delete(
                    messages.ContainerProjectsZonesClustersDeleteRequest(
                        clusterId=ref.clusterId,
                        zoneId=ref.zoneId,
                        projectId=ref.projectId))
                operations.append((op, ref))
            except apitools_base.HttpError as error:
                errors.append(util.GetError(error))
            except util.Error as error:
                errors.append(error)
        if args.wait:
            # Poll each operation for completion
            for operation, ref in operations:
                try:
                    util.WaitForOperation(
                        operation, ref.projectId, self.context,
                        'Deleting cluster {0}'.format(ref.clusterId))
                    # Purge cached config files
                    util.ClusterConfig.Purge(ref.clusterId, ref.zoneId,
                                             ref.projectId)
                    if properties.VALUES.container.cluster.Get(
                    ) == ref.clusterId:
                        properties.PersistProperty(
                            properties.VALUES.container.cluster, None)

                    log.DeletedResource(ref)
                except apitools_base.HttpError as error:
                    errors.append(util.GetError(error))
                except util.Error as error:
                    errors.append(error)

        if errors:
            raise exceptions.ToolException(
                util.ConstructList('Some requests did not succeed:', errors))
Example #9
0
    def Run(self, args):
        """This is what gets called when the user runs this command.

    Args:
      args: an argparse namespace. All the arguments that were provided to this
        command invocation.

    Returns:
      Some value that we want to have printed later.
    """
        adapter = self.context['api_adapter']

        cluster_refs = []
        for name in args.names:
            cluster_refs.append(adapter.ParseCluster(name))

        if not console_io.PromptContinue(message=util.ConstructList(
                'The following clusters will be deleted.', [
                    '[{name}] in [{zone}]'.format(name=ref.clusterId,
                                                  zone=adapter.Zone(ref))
                    for ref in cluster_refs
                ]),
                                         throw_if_unattended=True):
            raise exceptions.ToolException('Deletion aborted by user.')

        operations = []
        errors = []
        # Issue all deletes first
        for cluster_ref in cluster_refs:
            try:
                # Make sure it exists (will raise appropriate error if not)
                adapter.GetCluster(cluster_ref)

                op_ref = adapter.DeleteCluster(cluster_ref)
                operations.append((op_ref, cluster_ref))
            except apitools_base.HttpError as error:
                errors.append(util.GetError(error))
            except util.Error as error:
                errors.append(error)
        if args.wait:
            # Poll each operation for completion
            for operation_ref, cluster_ref in operations:
                try:
                    adapter.WaitForOperation(
                        operation_ref,
                        'Deleting cluster {0}'.format(cluster_ref.clusterId))
                    # Purge cached config files
                    util.ClusterConfig.Purge(cluster_ref.clusterId,
                                             adapter.Zone(cluster_ref),
                                             cluster_ref.projectId)
                    if properties.VALUES.container.cluster.Get(
                    ) == cluster_ref.clusterId:
                        properties.PersistProperty(
                            properties.VALUES.container.cluster, None)
                    log.DeletedResource(cluster_ref)
                except apitools_base.HttpError as error:
                    errors.append(util.GetError(error))
                except util.Error as error:
                    errors.append(error)

        if errors:
            raise exceptions.ToolException(
                util.ConstructList('Some requests did not succeed:', errors))
Example #10
0
    def Run(self, args):
        """This is what gets called when the user runs this command.

    Args:
      args: an argparse namespace. All the arguments that were provided to this
        command invocation.

    Returns:
      Cluster message for the successfully created cluster.

    Raises:
      ToolException, if creation failed.
    """
        client = self.context['container_client']
        messages = self.context['container_messages']
        cluster_ref = util.ParseCluster(args.name, self.context)

        if args.password:
            password = args.password
        else:
            password = ''.join(
                random.SystemRandom().choice(string.ascii_letters +
                                             string.digits) for _ in range(16))

        node_config = messages.NodeConfig()
        if args.machine_type:
            node_config.machineType = args.machine_type
        if args.source_image:
            node_config.sourceImage = args.source_image
        node_config.serviceAccounts = self.CreateServiceAccountMessages(
            args, messages)

        create_cluster_req = messages.CreateClusterRequest(
            cluster=messages.Cluster(
                name=cluster_ref.clusterId,
                numNodes=args.num_nodes,
                nodeConfig=node_config,
                masterAuth=messages.MasterAuth(user=args.user,
                                               password=password),
                enableCloudLogging=args.enable_cloud_logging))
        if args.cluster_api_version:
            create_cluster_req.cluster.clusterApiVersion = args.cluster_api_version
        if args.network:
            create_cluster_req.cluster.network = args.network
        if args.container_ipv4_cidr:
            create_cluster_req.cluster.containerIpv4Cidr = args.container_ipv4_cidr

        req = messages.ContainerProjectsZonesClustersCreateRequest(
            createClusterRequest=create_cluster_req,
            projectId=cluster_ref.projectId,
            zoneId=cluster_ref.zoneId)

        cluster = None
        try:
            operation = client.projects_zones_clusters.Create(req)

            if not args.wait:
                return util.DescribeCluster(cluster_ref, self.context)

            operation = util.WaitForOperation(
                operation, cluster_ref.projectId, self.context,
                'Creating cluster {0}'.format(cluster_ref.clusterId))

            # Get Cluster
            cluster = util.DescribeCluster(cluster_ref, self.context)
        except apitools_base.HttpError as error:
            raise exceptions.HttpException(util.GetError(error))

        log.CreatedResource(cluster_ref)
        # Persist cluster config
        c_config = util.ClusterConfig.Persist(cluster, cluster_ref.projectId,
                                              self.cli)
        if c_config:
            if not c_config.has_certs:
                # Purge config so we retry the cert fetch on next kubectl command
                util.ClusterConfig.Purge(cluster.name, cluster.zone,
                                         cluster_ref.projectId)
                # Exit with non-success returncode if certs could not be fetched
                self.exit_code = 1
            else:
                # Set current-context to new cluster if one is not already set
                kubeconfig = kconfig.Kubeconfig.Default()
                if not kubeconfig.current_context:
                    kubeconfig.SetCurrentContext(c_config.kube_context)
                    kubeconfig.SaveToFile()

        return cluster