Example #1
0
 def GetLabelsReplacementRequest(
     self, disk_ref, disk, messages, update_labels, remove_labels):
   if disk_ref.Collection() == 'compute.disks':
     replacement = labels_util.UpdateLabels(
         disk.labels,
         messages.ZoneSetLabelsRequest.LabelsValue,
         update_labels=update_labels,
         remove_labels=remove_labels)
     if replacement:
       return messages.ComputeDisksSetLabelsRequest(
           project=disk_ref.project,
           resource=disk_ref.disk,
           zone=disk_ref.zone,
           zoneSetLabelsRequest=messages.ZoneSetLabelsRequest(
               labelFingerprint=disk.labelFingerprint,
               labels=replacement))
   else:
     replacement = labels_util.UpdateLabels(
         disk.labels,
         messages.RegionSetLabelsRequest.LabelsValue,
         update_labels=update_labels,
         remove_labels=remove_labels)
     if replacement:
       return messages.ComputeRegionDisksSetLabelsRequest(
           project=disk_ref.project,
           resource=disk_ref.disk,
           region=disk_ref.region,
           regionSetLabelsRequest=messages.RegionSetLabelsRequest(
               labelFingerprint=disk.labelFingerprint,
               labels=replacement))
   return None
Example #2
0
  def Run(self, args):
    holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
    client = holder.client.apitools_client
    messages = holder.client.messages

    disk_ref = self.DISK_ARG.ResolveAsResource(
        args, holder.resources,
        scope_lister=flags.GetDefaultScopeLister(holder.client))

    update_labels = labels_util.GetUpdateLabelsDictFromArgs(args)
    remove_labels = labels_util.GetRemoveLabelsListFromArgs(args)
    if update_labels is None and remove_labels is None:
      raise calliope_exceptions.RequiredArgumentException(
          'LABELS',
          'At least one of --update-labels or '
          '--remove-labels must be specified.')

    if disk_ref.Collection() == 'compute.disks':
      service = client.disks
      request_type = messages.ComputeDisksGetRequest
    elif disk_ref.Collection() == 'compute.regionDisks':
      service = client.regionDisks
      request_type = messages.ComputeRegionDisksGetRequest
    else:
      raise ValueError('Unexpected resource argument of {}'
                       .format(disk_ref.Collection()))

    disk = service.Get(request_type(**disk_ref.AsDict()))

    if disk_ref.Collection() == 'compute.disks':
      replacement = labels_util.UpdateLabels(
          disk.labels,
          messages.ZoneSetLabelsRequest.LabelsValue,
          update_labels=update_labels,
          remove_labels=remove_labels)
      request = messages.ComputeDisksSetLabelsRequest(
          project=disk_ref.project,
          resource=disk_ref.disk,
          zone=disk_ref.zone,
          zoneSetLabelsRequest=messages.ZoneSetLabelsRequest(
              labelFingerprint=disk.labelFingerprint,
              labels=replacement))
    else:
      replacement = labels_util.UpdateLabels(
          disk.labels,
          messages.RegionSetLabelsRequest.LabelsValue,
          update_labels=update_labels,
          remove_labels=remove_labels)
      request = messages.ComputeRegionDisksSetLabelsRequest(
          project=disk_ref.project,
          resource=disk_ref.disk,
          region=disk_ref.region,
          regionSetLabelsRequest=messages.RegionSetLabelsRequest(
              labelFingerprint=disk.labelFingerprint,
              labels=replacement))

    if not replacement:
      return disk

    return service.SetLabels(request)
  def Run(self, args):
    holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
    client = holder.client.apitools_client
    messages = holder.client.messages

    disk_ref = self.DISK_ARG.ResolveAsResource(
        args, holder.resources,
        scope_lister=flags.GetDefaultScopeLister(holder.client))

    remove_labels = labels_util.GetUpdateLabelsDictFromArgs(args)

    if disk_ref.Collection() == 'compute.disks':
      service = client.disks
      request_type = messages.ComputeDisksGetRequest
    elif disk_ref.Collection() == 'compute.regionDisks':
      service = client.regionDisks
      request_type = messages.ComputeRegionDisksGetRequest
    else:
      raise ValueError('Unexpected resource argument of {}'
                       .format(disk_ref.Collection()))

    disk = service.Get(request_type(**disk_ref.AsDict()))

    if args.all:
      # removing all existing labels from the disk.
      remove_labels = {}
      if disk.labels:
        for label in disk.labels.additionalProperties:
          remove_labels[label.key] = label.value

    if disk_ref.Collection() == 'compute.disks':
      replacement = labels_util.UpdateLabels(
          disk.labels,
          messages.ZoneSetLabelsRequest.LabelsValue,
          remove_labels=remove_labels)
      request = messages.ComputeDisksSetLabelsRequest(
          project=disk_ref.project,
          resource=disk_ref.disk,
          zone=disk_ref.zone,
          zoneSetLabelsRequest=messages.ZoneSetLabelsRequest(
              labelFingerprint=disk.labelFingerprint,
              labels=replacement))
    else:
      replacement = labels_util.UpdateLabels(
          disk.labels,
          messages.RegionSetLabelsRequest.LabelsValue,
          remove_labels=remove_labels)
      request = messages.ComputeRegionDisksSetLabelsRequest(
          project=disk_ref.project,
          resource=disk_ref.disk,
          region=disk_ref.region,
          regionSetLabelsRequest=messages.RegionSetLabelsRequest(
              labelFingerprint=disk.labelFingerprint,
              labels=replacement))

    if not replacement:
      return disk

    return service.SetLabels(request)
Example #4
0
def Create(project_ref,
           project_name,
           enable_cloud_apis=True,
           update_labels=None):
    """Create a new project."""
    client = projects_util.GetClient()
    messages = projects_util.GetMessages()

    # Create project.
    project_creation_result = client.projects.Create(
        messages.CloudresourcemanagerProjectsCreateRequest(
            project=messages.Project(
                projectId=project_ref.Name(),
                name=project_name if project_name else project_ref.Name(),
                labels=labels_util.UpdateLabels(None,
                                                messages.Project.LabelsValue,
                                                update_labels=update_labels))))

    if enable_cloud_apis:
        # Enable cloudapis.googleapis.com
        services_client = apis.GetClientInstance('servicemanagement', 'v1')
        enable_operation = services_enable_api.EnableServiceApiCall(
            project_ref.Name(), 'cloudapis.googleapis.com')
        services_util.WaitForOperation(enable_operation.name, services_client)
        # TODO(user): Retry in case it failed?

    return project_creation_result
Example #5
0
def Update(project_ref,
           name=None,
           organization=None,
           update_labels=None,
           remove_labels=None):
    """Update project information."""
    client = projects_util.GetClient()
    messages = projects_util.GetMessages()

    try:
        project = client.projects.Get(project_ref.Request())
    except exceptions.HttpError as error:
        raise projects_util.ConvertHttpError(error)

    if name:
        project.name = name
    if organization:
        if project.parent is not None:
            raise errors.ProjectMoveError(project, organization)
        project.parent = messages.ResourceId(id=organization,
                                             type='organization')
    project.labels = labels_util.UpdateLabels(project.labels,
                                              messages.Project.LabelsValue,
                                              update_labels=update_labels,
                                              remove_labels=remove_labels)
    try:
        return client.projects.Update(project)
    except exceptions.HttpError as error:
        raise projects_util.ConvertHttpError(error)
Example #6
0
    def ConfigureCluster(messages, args, cluster):
        """Performs any additional configuration of the cluster."""
        labels = labels_util.UpdateLabels(
            None, messages.Cluster.LabelsValue,
            labels_util.GetUpdateLabelsDictFromArgs(args), None)

        cluster.labels = labels
Example #7
0
def Update(project_ref,
           name=None,
           parent=None,
           update_labels=None,
           remove_labels=None):
    """Update project information."""
    client = projects_util.GetClient()
    messages = projects_util.GetMessages()

    try:
        project = client.projects.Get(
            client.MESSAGES_MODULE.CloudresourcemanagerProjectsGetRequest(
                projectId=project_ref.projectId))
    except exceptions.HttpError as error:
        raise projects_util.ConvertHttpError(error)

    if name:
        project.name = name

    if parent:
        project.parent = parent

    project.labels = labels_util.UpdateLabels(project.labels,
                                              messages.Project.LabelsValue,
                                              update_labels=update_labels,
                                              remove_labels=remove_labels)
    try:
        return client.projects.Update(project)
    except exceptions.HttpError as error:
        raise projects_util.ConvertHttpError(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:
      A serialized object (dict) describing the results of the operation.

    Raises:
      An HttpException if there was a problem calling the
      API topics.Patch command.
    """
        client = topics.TopicsClient()
        topic_ref = util.ParseTopic(args.topic)

        update_labels = labels_util.GetUpdateLabelsDictFromArgs(args)
        remove_labels = labels_util.GetRemoveLabelsListFromArgs(args)
        if update_labels or remove_labels:
            original_topic = client.Get(topic_ref)
            labels = labels_util.UpdateLabels(
                original_topic.labels,
                client.messages.Topic.LabelsValue,
                update_labels=update_labels,
                remove_labels=remove_labels)
        else:
            labels = None
        result = client.Patch(topic_ref, labels=labels)

        log.UpdatedResource(topic_ref.RelativeName(), kind='topic')
        return result
    def Run(self, args):
        dataproc = dp.Dataproc(self.ReleaseTrack())

        template = util.ParseWorkflowTemplates(args.template, dataproc)

        workflow_template = dataproc.GetRegionsWorkflowTemplate(
            template, args.version)

        cluster_name = template.workflowTemplatesId

        compute_resources = compute_helpers.GetComputeResources(
            self.ReleaseTrack(), cluster_name)
        use_accelerators = self.ReleaseTrack() == base.ReleaseTrack.BETA
        use_auto_delete_ttl = self.ReleaseTrack() == base.ReleaseTrack.BETA

        cluster_config = clusters.GetClusterConfig(args, dataproc,
                                                   template.projectsId,
                                                   compute_resources,
                                                   use_accelerators,
                                                   use_auto_delete_ttl)

        labels = labels_util.UpdateLabels(
            None, dataproc.messages.ManagedCluster.LabelsValue,
            labels_util.GetUpdateLabelsDictFromArgs(args), None)

        managed_cluster = dataproc.messages.ManagedCluster(
            clusterName=cluster_name, config=cluster_config, labels=labels)

        workflow_template.placement = dataproc.messages.WorkflowTemplatePlacement(
            managedCluster=managed_cluster)

        response = dataproc.client.projects_regions_workflowTemplates.Update(
            workflow_template)
        return response
Example #10
0
    def Run(self, args):
        client = cloudkms_base.GetClientInstance()
        messages = cloudkms_base.GetMessagesModule()

        crypto_key_ref = flags.ParseCryptoKeyName(args)
        parent_ref = flags.ParseParentFromResource(crypto_key_ref)

        req = messages.CloudkmsProjectsLocationsKeyRingsCryptoKeysCreateRequest(
            parent=parent_ref.RelativeName(),
            cryptoKeyId=crypto_key_ref.Name(),
            cryptoKey=messages.CryptoKey(
                # TODO(b/35914817): Find a better way to get the enum value by name.
                purpose=getattr(messages.CryptoKey.PurposeValueValuesEnum,
                                PURPOSE_MAP[args.purpose]),
                labels=labels_util.UpdateLabels(
                    None,
                    messages.CryptoKey.LabelsValue,
                    update_labels=labels_util.GetUpdateLabelsDictFromArgs(
                        args))),
        )

        flags.SetNextRotationTime(args, req.cryptoKey)
        flags.SetRotationPeriod(args, req.cryptoKey)

        return client.projects_locations_keyRings_cryptoKeys.Create(req)
 def ConfigureJob(self, messages, job, args):
     """Add type-specific job configuration to job message."""
     # Parse labels (if present)
     labels = labels_util.UpdateLabels(
         None, messages.Job.LabelsValue,
         labels_util.GetUpdateLabelsDictFromArgs(args), None)
     job.labels = labels
Example #12
0
  def Run(self, args):
    holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
    client = holder.client.apitools_client
    messages = holder.client.messages

    forwarding_rule_ref = self.FORWARDING_RULE_ARG.ResolveAsResource(
        args,
        holder.resources,
        scope_lister=compute_flags.GetDefaultScopeLister(holder.client))

    update_labels = labels_util.GetUpdateLabelsDictFromArgs(args)
    remove_labels = labels_util.GetRemoveLabelsListFromArgs(args)
    if update_labels is None and remove_labels is None:
      raise calliope_exceptions.RequiredArgumentException(
          'LABELS', 'At least one of --update-labels or '
          '--remove-labels must be specified.')

    if forwarding_rule_ref.Collection() == 'compute.globalForwardingRules':
      forwarding_rule = client.globalForwardingRules.Get(
          messages.ComputeGlobalForwardingRulesGetRequest(
              **forwarding_rule_ref.AsDict()))
      labels_value = messages.GlobalSetLabelsRequest.LabelsValue
    else:
      forwarding_rule = client.forwardingRules.Get(
          messages.ComputeForwardingRulesGetRequest(
              **forwarding_rule_ref.AsDict()))
      labels_value = messages.RegionSetLabelsRequest.LabelsValue

    replacement = labels_util.UpdateLabels(
        forwarding_rule.labels,
        labels_value,
        update_labels=update_labels,
        remove_labels=remove_labels)

    if not replacement:
      return forwarding_rule

    if forwarding_rule_ref.Collection() == 'compute.globalForwardingRules':
      request = self._CreateGlobalSetLabelsRequest(
          messages, forwarding_rule_ref, forwarding_rule, replacement)

      operation = client.globalForwardingRules.SetLabels(request)
      operation_ref = holder.resources.Parse(
          operation.selfLink, collection='compute.globalOperations')

      operation_poller = poller.Poller(client.globalForwardingRules)
    else:
      request = self._CreateRegionalSetLabelsRequest(
          messages, forwarding_rule_ref, forwarding_rule, replacement)

      operation = client.forwardingRules.SetLabels(request)
      operation_ref = holder.resources.Parse(
          operation.selfLink, collection='compute.regionOperations')

      operation_poller = poller.Poller(client.forwardingRules)

    return waiter.WaitFor(operation_poller, operation_ref,
                          'Updating labels of forwarding rule [{0}]'.format(
                              forwarding_rule_ref.Name()))
Example #13
0
    def ConfigureJob(self, job, args):
        messages = self.context['dataproc_messages']

        # Parse labels (if present)
        labels = labels_util.UpdateLabels(
            None, messages.Job.LabelsValue,
            labels_util.GetUpdateLabelsDictFromArgs(args), None)
        job.labels = labels
  def ConfigureCluster(messages, args, cluster):
    labels = labels_util.UpdateLabels(
        None,
        messages.Cluster.LabelsValue,
        labels_util.GetUpdateLabelsDictFromArgs(args),
        None)

    cluster.labels = labels
Example #15
0
    def _ApplyArgsToFunction(self, base_function, is_new_function,
                             trigger_params, name, args, project):
        """Apply values from args to base_function.

    Args:
        base_function: function message to modify
        is_new_function: bool, indicates if this is a new function (and source
                         code for it must be deployed) or an existing function
                         (so it may keep its old source code).
        trigger_params: parameters for creating functions trigger.
        name: relative name of the function.
        args: commandline args specyfying how to modify the function.
        project: project of the function.
    """
        if args.IsSpecified('retry'):
            retry = args.retry
        else:
            retry = None
        self._ApplyNonSourceArgsToFunction(base_function, name,
                                           args.entry_point, args.timeout,
                                           args.trigger_http, trigger_params,
                                           retry, args.memory)
        messages = util.GetApiMessagesModule()
        if args.source:
            deploy_util.AddSourceToFunction(base_function, args.source,
                                            args.include_ignored_files,
                                            args.name, args.stage_bucket,
                                            messages)
        elif args.source_url:
            deploy_util.CleanOldSourceInfo(base_function)
            source_path = args.source_path
            source_branch = args.source_branch or 'master'
            base_function.sourceRepository = messages.SourceRepository(
                url=self._GetSourceUrlFromArgs(project,
                                               tag=args.source_tag,
                                               branch=source_branch,
                                               revision=args.source_revision,
                                               source_url=args.source_url,
                                               source_path=source_path))

        elif args.stage_bucket:
            # Do not change source of existing function unless instructed to.
            deploy_util.CleanOldSourceInfo(base_function)
            base_function.sourceArchiveUrl = self._PrepareSourcesOnGcs(args)
        elif is_new_function or args.local_path:
            raise exceptions.FunctionsError(
                'argument --stage-bucket: required when the function is deployed '
                'from a local directory.')
        # Set information about deplouyment tool.
        labels_to_update = args.update_labels or {}
        labels_to_update['deployment-tool'] = 'cli-gcloud'
        updated_labels = labels_util.UpdateLabels(
            base_function.labels,
            messages.CloudFunction.LabelsValue,
            update_labels=labels_to_update,
            remove_labels=args.remove_labels)
        if updated_labels is not None:
            base_function.labels = updated_labels
Example #16
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.

    Yields:
      A serialized object (dict) describing the results of the operation.
      This description fits the Resource described in the ResourceRegistry under
      'pubsub.projects.subscriptions'.

    Raises:
      util.RequestFailedError: if any of the requests to the API failed.
    """
        client = subscriptions.SubscriptionsClient()

        topic_ref = util.ParseTopic(args.topic, args.topic_project)
        push_config = util.ParsePushConfig(args.push_endpoint)
        retain_acked_messages = getattr(args, 'retain_acked_messages', None)
        retention_duration = getattr(args, 'message_retention_duration', None)
        if retention_duration:
            retention_duration = util.FormatDuration(retention_duration)

        labels = labels_util.UpdateLabels(
            None,
            client.messages.Subscription.LabelsValue,
            update_labels=labels_util.GetUpdateLabelsDictFromArgs(args))

        failed = []
        for subscription_name in args.subscription:
            subscription_ref = util.ParseSubscription(subscription_name)

            try:
                result = client.Create(subscription_ref,
                                       topic_ref,
                                       args.ack_deadline,
                                       push_config,
                                       retain_acked_messages,
                                       retention_duration,
                                       labels=labels)
            except api_ex.HttpError as error:
                exc = exceptions.HttpException(error)
                log.CreatedResource(subscription_ref.RelativeName(),
                                    kind='subscription',
                                    failed=exc.payload.status_message)
                failed.append(subscription_name)
                continue

            result = util.SubscriptionDisplayDict(result)
            log.CreatedResource(subscription_ref.RelativeName(),
                                kind='subscription')

            yield result

        if failed:
            raise util.RequestsFailedError(failed, 'create')
Example #17
0
 def ConfigureJob(self, job, args):
     messages = self.context['dataproc_messages']
     # Configure Restartable job.
     if args.max_failures_per_hour:
         scheduling = messages.JobScheduling(
             maxFailuresPerHour=args.max_failures_per_hour)
         job.scheduling = scheduling
     # Parse labels (if present)
     labels = labels_util.UpdateLabels(
         None, messages.Job.LabelsValue,
         labels_util.GetUpdateLabelsDictFromArgs(args), None)
     job.labels = labels
Example #18
0
  def Run(self, args):
    """Issues API requests to update a Target VPN Gateway.

    Args:
      args: argparse.Namespace, The arguments received by this command.
    Returns:
      [protorpc.messages.Message], A list of responses returned
      by the compute API.
    """
    holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
    client = holder.client.apitools_client
    messages = holder.client.messages

    target_vpn_gateway_ref = self.TARGET_VPN_GATEWAY_ARG.ResolveAsResource(
        args,
        holder.resources,
        scope_lister=compute_flags.GetDefaultScopeLister(holder.client))

    update_labels = labels_util.GetUpdateLabelsDictFromArgs(args)
    remove_labels = labels_util.GetRemoveLabelsListFromArgs(args)
    if update_labels is None and remove_labels is None:
      raise calliope_exceptions.RequiredArgumentException(
          'LABELS', 'At least one of --update-labels or '
          '--remove-labels must be specified.')

    target_vpn_gateway = client.targetVpnGateways.Get(
        messages.ComputeTargetVpnGatewaysGetRequest(
            **target_vpn_gateway_ref.AsDict()))
    labels_value = messages.RegionSetLabelsRequest.LabelsValue

    replacement = labels_util.UpdateLabels(
        target_vpn_gateway.labels,
        labels_value,
        update_labels=update_labels,
        remove_labels=remove_labels)

    if not replacement:
      return target_vpn_gateway

    request = self._CreateRegionalSetLabelsRequest(
        messages, target_vpn_gateway_ref, target_vpn_gateway, replacement)

    operation = client.targetVpnGateways.SetLabels(request)
    operation_ref = holder.resources.Parse(
        operation.selfLink, collection='compute.regionOperations')

    operation_poller = poller.Poller(client.targetVpnGateways)

    return waiter.WaitFor(operation_poller, operation_ref,
                          'Updating labels of target VPN gateway [{0}]'.format(
                              target_vpn_gateway_ref.Name()))
    def Run(self, args):
        pipelines = bio.Pipelines(properties.VALUES.core.project.Get())
        op = pipelines.RunDeepVariant(
            compute_zones=args.zones,
            input_fastq1=[args.input_pair[0]],
            input_fastq2=[args.input_pair[1]],
            labels=labels_util.UpdateLabels(
                None,
                pipelines.GetMessages().PipelineOptions.LabelsValue,
                labels_util.GetUpdateLabelsDictFromArgs(args), None),
            output_path=args.output_path,
            sample_name=args.sample_name)

        log.status.Print('Running [{0}].'.format(op.name))
        return op
Example #20
0
    def Run(self, args):
        client = self.context['dataproc_client']
        messages = self.context['dataproc_messages']

        job_ref = util.ParseJob(args.id, self.context)

        changed_fields = []

        has_changes = False

        # Update labels if the user requested it
        labels = None
        if args.update_labels or args.remove_labels:
            has_changes = True
            changed_fields.append('labels')

            # We need to fetch the job first so we know what the labels look like. The
            # labels_util.UpdateLabels will fill out the proto for us with all the
            # updates and removals, but first we need to provide the current state
            # of the labels
            orig_job = client.projects_regions_jobs.Get(
                client.MESSAGES_MODULE.DataprocProjectsRegionsJobsGetRequest(
                    projectId=job_ref.projectId,
                    region=job_ref.region,
                    jobId=job_ref.jobId))

            labels = labels_util.UpdateLabels(orig_job.labels,
                                              messages.Job.LabelsValue,
                                              args.update_labels,
                                              args.remove_labels)

        if not has_changes:
            raise exceptions.ArgumentError(
                'Must specify at least one job parameter to update.')

        updated_job = orig_job
        updated_job.labels = labels
        request = messages.DataprocProjectsRegionsJobsPatchRequest(
            projectId=job_ref.projectId,
            region=job_ref.region,
            jobId=job_ref.jobId,
            job=updated_job,
            updateMask=','.join(changed_fields))

        returned_job = client.projects_regions_jobs.Patch(request)

        log.UpdatedResource(returned_job)
        return returned_job
def UserLabels(sql_messages,
               instance=None,
               labels=None,
               update_labels=None,
               remove_labels=None,
               clear_labels=None):
    """Generates the labels message for the instance.

  Args:
    sql_messages: module, The messages module that should be used.
    instance: sql_messages.DatabaseInstance, The original instance, if
        prior labels might be needed needed.
    labels: dict, the full set of labels to set.
    update_labels: dict, the key-value pairs to update existing labels with.
    remove_labels: the list of label keys to remove.
    clear_labels: boolean, True if all labels should be cleared.

  Returns:
    sql_messages.Settings.UserLabelsValue, an object w/ labels updates applied.
  """

    # Parse labels args
    if labels:
        update_labels = labels
    elif clear_labels:
        remove_labels = [
            label.key
            for label in instance.settings.userLabels.additionalProperties
        ]

    # Removing labels with a patch request requires explicitly setting values
    # to null. If the user did not specify labels in this patch request, we
    # keep their existing labels.
    if remove_labels:
        if not update_labels:
            update_labels = {}
        for key in remove_labels:
            update_labels[key] = None

    # Generate the actual UserLabelsValue message.
    existing_labels = None
    if instance:
        existing_labels = instance.settings.userLabels
    return labels_util.UpdateLabels(existing_labels,
                                    sql_messages.Settings.UserLabelsValue,
                                    update_labels)
  def Run(self, args):
    holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
    client = holder.client.apitools_client
    messages = holder.client.messages

    instance_ref = instances_flags.INSTANCE_ARG.ResolveAsResource(
        args, holder.resources,
        scope_lister=flags.GetDefaultScopeLister(holder.client))

    remove_labels = labels_util.GetUpdateLabelsDictFromArgs(args)

    instance = client.instances.Get(
        messages.ComputeInstancesGetRequest(**instance_ref.AsDict()))

    if args.all:
      # removing all existing labels from the instance.
      remove_labels = {}
      if instance.labels:
        for label in instance.labels.additionalProperties:
          remove_labels[label.key] = label.value

    replacement = labels_util.UpdateLabels(
        instance.labels,
        messages.InstancesSetLabelsRequest.LabelsValue,
        remove_labels=remove_labels)
    request = messages.ComputeInstancesSetLabelsRequest(
        project=instance_ref.project,
        instance=instance_ref.instance,
        zone=instance_ref.zone,
        instancesSetLabelsRequest=
        messages.InstancesSetLabelsRequest(
            labelFingerprint=instance.labelFingerprint,
            labels=replacement))

    if not replacement:
      return instance

    operation = client.instances.SetLabels(request)
    operation_ref = holder.resources.Parse(
        operation.selfLink, collection='compute.zoneOperations')
    operation_poller = poller.Poller(client.instances)
    return waiter.WaitFor(
        operation_poller, operation_ref,
        'Changing labels of instance [{0}]'.format(
            instance_ref.Name()))
Example #23
0
    def _ConstructLabelsFromArgs(cls, sql_messages, args, instance=None):
        """Constructs the labels message for the instance.

    Args:
      sql_messages: module, The messages module that should be used.
      args: Flags specified on the gcloud command; looking for
          args.labels, args.update_labels, args.remove_labels, ags.clear_labels.
      instance: sql_messages.DatabaseInstance, The original instance, if
          the original labels are needed.

    Returns:
      sql_messages.Settings.UserLabelsValue, the labels message for the patch.
    """
        # Parse labels args
        update_labels, remove_labels = {}, []
        if hasattr(args, 'labels'):
            update_labels = args.labels
        elif (hasattr(args, 'update_labels')
              and args.update_labels) or (hasattr(args, 'remove_labels')
                                          and args.remove_labels):
            update_labels, remove_labels = labels_util.GetAndValidateOpsFromArgs(
                args)
        elif hasattr(args, 'clear_labels') and args.clear_labels:
            remove_labels = [
                label.key
                for label in instance.settings.userLabels.additionalProperties
            ]

        # Removing labels with a patch request requires explicitly setting values
        # to null. If the user did not specify labels in this patch request, we
        # keep their existing labels.
        if remove_labels:
            if not update_labels:
                update_labels = {}
            for key in remove_labels:
                update_labels[key] = None

        # Generate the actual UserLabelsValue message.
        existing_labels = None
        if instance:
            existing_labels = instance.settings.userLabels
        return labels_util.UpdateLabels(existing_labels,
                                        sql_messages.Settings.UserLabelsValue,
                                        update_labels)
Example #24
0
  def Run(self, args):
    holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
    client = holder.client.apitools_client
    messages = holder.client.messages

    snapshot_ref = SnapshotsRemoveLabels.SnapshotArg.ResolveAsResource(
        args, holder.resources)

    remove_labels = labels_util.GetUpdateLabelsDictFromArgs(args)

    snapshot = client.snapshots.Get(
        messages.ComputeSnapshotsGetRequest(**snapshot_ref.AsDict()))

    if args.all:
      # removing all existing labels from the snapshot.
      remove_labels = {}
      if snapshot.labels:
        for label in snapshot.labels.additionalProperties:
          remove_labels[label.key] = label.value

    replacement = labels_util.UpdateLabels(
        snapshot.labels,
        messages.GlobalSetLabelsRequest.LabelsValue,
        remove_labels=remove_labels)
    if not replacement:
      return snapshot

    request = messages.ComputeSnapshotsSetLabelsRequest(
        project=snapshot_ref.project,
        resource=snapshot_ref.snapshot,
        globalSetLabelsRequest=
        messages.GlobalSetLabelsRequest(
            labelFingerprint=snapshot.labelFingerprint,
            labels=replacement))

    operation = client.snapshots.SetLabels(request)
    operation_ref = holder.resources.Parse(
        operation.selfLink, collection='compute.globalOperations')

    operation_poller = poller.Poller(client.snapshots)
    return waiter.WaitFor(
        operation_poller, operation_ref,
        'Updating labels of snapshot [{0}]'.format(
            snapshot_ref.Name()))
Example #25
0
    def _ApplyArgsToFunction(self, base_function, is_new_function,
                             trigger_params, name, args):
        """Apply values from args to base_function.

    Args:
        base_function: function message to modify
        is_new_function: bool, indicates if this is a new function (and source
                         code for it must be deployed) or an existing function
                         (so it may keep its old source code).
        trigger_params: parameters for creating functions trigger.
        name: relative name of the function.
        args: commandline args specyfying how to modify the function.
    """
        if args.IsSpecified('retry'):
            retry = args.retry
        else:
            retry = None
        self._ApplyNonSourceArgsToFunction(base_function, name,
                                           args.entry_point, args.timeout,
                                           args.trigger_http, trigger_params,
                                           retry, args.memory)
        messages = util.GetApiMessagesModule()
        if args.source:
            deploy_util.AddSourceToFunction(base_function, args.source,
                                            args.include_ignored_files,
                                            args.name, args.stage_bucket)
        elif args.source_url:
            source_path = args.source_path
            source_branch = args.source_branch or 'master'
            base_function.sourceRepository = messages.SourceRepository(
                tag=args.source_tag,
                branch=source_branch,
                revision=args.source_revision,
                repositoryUrl=args.source_url,
                sourcePath=source_path)
        elif is_new_function or args.local_path or args.stage_bucket:
            # Do not change source of existing function unless instructed to.
            base_function.sourceArchiveUrl = self._PrepareSourcesOnGcs(args)
        base_function.labels = labels_util.UpdateLabels(
            base_function.labels,
            messages.CloudFunction.LabelsValue,
            update_labels=args.update_labels,
            remove_labels=args.remove_labels)
Example #26
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.

    Yields:
      A serialized object (dict) describing the results of the operation.
      This description fits the Resource described in the ResourceRegistry under
      'pubsub.projects.snapshots'.

    Raises:
      util.RequestFailedError: if any of the requests to the API failed.
    """
    client = snapshots.SnapshotsClient()

    subscription_ref = util.ParseSubscription(
        args.subscription, args.subscription_project)

    labels = labels_util.UpdateLabels(
        None, client.messages.CreateSnapshotRequest.LabelsValue,
        update_labels=labels_util.GetUpdateLabelsDictFromArgs(args))

    failed = []
    for snapshot_name in args.snapshot:
      snapshot_ref = util.ParseSnapshot(snapshot_name)

      try:
        result = client.Create(snapshot_ref, subscription_ref, labels=labels)
      except api_ex.HttpError as error:
        exc = exceptions.HttpException(error)
        log.CreatedResource(snapshot_ref.RelativeName(), kind='snapshot',
                            failed=exc.payload.status_message)
        failed.append(snapshot_name)
        continue

      result = util.SnapshotDisplayDict(result)
      log.CreatedResource(snapshot_ref.RelativeName(), kind='snapshot')
      yield result

    if failed:
      raise util.RequestsFailedError(failed, 'create')
Example #27
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:
      A serialized object (dict) describing the results of the operation.
      This description fits the Resource described in the ResourceRegistry under
      'pubsub.projects.subscriptions'.

    Raises:
      An HttpException if there was a problem calling the
      API subscriptions.Patch command.
    """
        client = subscriptions.SubscriptionsClient()
        subscription_ref = util.ParseSubscription(args.subscription)

        update_labels = labels_util.GetUpdateLabelsDictFromArgs(args)
        remove_labels = labels_util.GetRemoveLabelsListFromArgs(args)
        if update_labels or remove_labels:
            original_subscription = client.Get(subscription_ref)
            labels = labels_util.UpdateLabels(
                original_subscription.labels,
                client.messages.Subscription.LabelsValue,
                update_labels=update_labels,
                remove_labels=remove_labels)
        else:
            labels = None
        result = client.Patch(
            subscription_ref,
            ack_deadline=args.ack_deadline,
            push_config=util.ParsePushConfig(args.push_endpoint),
            retain_acked_messages=args.retain_acked_messages,
            labels=labels,
            message_retention_duration=args.message_retention_duration)

        result = util.SubscriptionDisplayDict(result)
        log.UpdatedResource(subscription_ref.RelativeName(),
                            kind='subscription')
        return result
def Create(project_ref, display_name=None, update_labels=None):
  """Create a new project.

  Args:
    project_ref: The identifier for the project
    display_name: Optional display name for the project
    update_labels: Optional labels to apply to the project

  Returns:
    An Operation object which can be used to check on the progress of the
    project creation.
  """
  client = projects_util.GetClient()
  messages = projects_util.GetMessages()
  return client.projects.Create(
      messages.Project(
          projectId=project_ref.Name(),
          name=display_name if display_name else project_ref.Name(),
          labels=labels_util.UpdateLabels(
              None, messages.Project.LabelsValue, update_labels=update_labels)))
    def Run(self, args):
        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        client = holder.client.apitools_client
        messages = holder.client.messages

        image_ref = self.DISK_IMAGE_ARG.ResolveAsResource(
            args, holder.resources)

        remove_labels = labels_util.GetUpdateLabelsDictFromArgs(args)

        image = client.images.Get(
            messages.ComputeImagesGetRequest(**image_ref.AsDict()))

        if args.all:
            # removing all existing labels from the image.
            remove_labels = {}
            if image.labels:
                for label in image.labels.additionalProperties:
                    remove_labels[label.key] = label.value

        replacement = labels_util.UpdateLabels(
            image.labels,
            messages.GlobalSetLabelsRequest.LabelsValue,
            remove_labels=remove_labels)
        request = messages.ComputeImagesSetLabelsRequest(
            project=image_ref.project,
            resource=image_ref.image,
            globalSetLabelsRequest=messages.GlobalSetLabelsRequest(
                labelFingerprint=image.labelFingerprint, labels=replacement))

        if not replacement:
            return image

        operation = client.images.SetLabels(request)
        operation_ref = holder.resources.Parse(
            operation.selfLink, collection='compute.globalOperations')

        operation_poller = poller.Poller(client.images)
        return waiter.WaitFor(
            operation_poller, operation_ref,
            'Updating labels of image [{0}]'.format(image_ref.Name()))
Example #30
0
  def Run(self, args):
    holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
    client = holder.client.apitools_client
    messages = holder.client.messages

    disk_ref = self.DISK_ARG.ResolveAsResource(
        args, holder.resources,
        scope_lister=flags.GetDefaultScopeLister(holder.client))

    update_labels, remove_labels = labels_util.GetAndValidateOpsFromArgs(args)

    service = client.disks
    request_type = messages.ComputeDisksGetRequest

    disk = service.Get(request_type(**disk_ref.AsDict()))

    replacement = labels_util.UpdateLabels(
        disk.labels,
        messages.ZoneSetLabelsRequest.LabelsValue,
        update_labels=update_labels,
        remove_labels=remove_labels)
    request = messages.ComputeDisksSetLabelsRequest(
        project=disk_ref.project,
        resource=disk_ref.disk,
        zone=disk_ref.zone,
        zoneSetLabelsRequest=messages.ZoneSetLabelsRequest(
            labelFingerprint=disk.labelFingerprint,
            labels=replacement))

    if not replacement:
      return disk

    operation = service.SetLabels(request)
    operation_ref = holder.resources.Parse(
        operation.selfLink, collection='compute.zoneOperations')

    operation_poller = poller.Poller(service)
    return waiter.WaitFor(
        operation_poller, operation_ref,
        'Updating labels of disk [{0}]'.format(
            disk_ref.Name()))