Ejemplo n.º 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.

    Yields:
      A serialized object (dict) describing the results of the operation.
      This description fits the Resource described in the ResourceRegistry under
      'pubsub.projects.subscriptions'.
    """
        msgs = self.context['pubsub_msgs']
        pubsub = self.context['pubsub']

        for subscription_name in args.subscription:
            subscription = msgs.Subscription(
                name=util.SubscriptionFormat(subscription_name))
            delete_req = msgs.PubsubProjectsSubscriptionsDeleteRequest(
                subscription=util.SubscriptionFormat(subscription.name))

            try:
                pubsub.projects_subscriptions.Delete(delete_req)
                failed = None
            except api_ex.HttpError as error:
                exc = exceptions.HttpException(error)
                failed = exc.payload.status_message

            result = util.SubscriptionDisplayDict(subscription, failed)
            log.DeletedResource(subscription.name,
                                kind='subscription',
                                failed=failed)
            yield result
Ejemplo n.º 2
0
def _Run(args, legacy_output=False):
    """Deletes one or more subscriptions."""
    client = subscriptions.SubscriptionsClient()

    failed = []
    for subscription_ref in args.CONCEPTS.subscription.Parse():

        try:
            result = client.Delete(subscription_ref)
        except api_ex.HttpError as error:
            exc = exceptions.HttpException(error)
            log.DeletedResource(subscription_ref.RelativeName(),
                                kind='subscription',
                                failed=exc.payload.status_message)
            failed.append(subscription_ref.subscriptionsId)
            continue

        subscription = client.messages.Subscription(
            name=subscription_ref.RelativeName())

        if legacy_output:
            result = util.SubscriptionDisplayDict(subscription)

        log.DeletedResource(subscription_ref.RelativeName(),
                            kind='subscription')
        yield result

    if failed:
        raise util.RequestsFailedError(failed, 'delete')
Ejemplo n.º 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.

    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')
Ejemplo n.º 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:
      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.
    """
        msgs = self.context['pubsub_msgs']
        pubsub = self.context['pubsub']

        name = util.SubscriptionFormat(args.subscription)

        mask = []
        subscription = msgs.Subscription(name=name)
        if args.ack_deadline is not None:
            mask.append('ackDeadlineSeconds')
            subscription.ackDeadlineSeconds = args.ack_deadline
        if args.push_endpoint is not None:
            mask.append('pushConfig')
            subscription.pushConfig = msgs.PushConfig(
                pushEndpoint=args.push_endpoint)
        if args.retain_acked_messages is not None:
            mask.append('retainAckedMessages')
            subscription.retainAckedMessages = args.retain_acked_messages
        if args.message_retention_duration is not None:
            mask.append('messageRetentionDuration')
            if args.message_retention_duration != DEFAULT_MESSAGE_RETENTION_VALUE:
                subscription.messageRetentionDuration = args.message_retention_duration

        patch_req = msgs.PubsubProjectsSubscriptionsPatchRequest(
            updateSubscriptionRequest=msgs.UpdateSubscriptionRequest(
                subscription=subscription, updateMask=','.join(mask)),
            name=name)

        # TODO(b/32275310): Conform to gcloud error handling guidelines.  This is
        # currently consistent with the rest of the gcloud pubsub commands.
        try:
            result = pubsub.projects_subscriptions.Patch(patch_req)
            failed = None
        except api_ex.HttpError as error:
            result = subscription
            exc = exceptions.HttpException(error)
            failed = exc.payload.status_message

        result = util.SubscriptionDisplayDict(result, failed)
        log.UpdatedResource(name, kind='subscription', failed=failed)
        return result
Ejemplo n.º 5
0
def _Run(args, enable_labels=False, legacy_output=False):
    """Creates one or more subscriptions."""
    client = subscriptions.SubscriptionsClient()

    topic_ref = args.CONCEPTS.topic.Parse()
    push_config = util.ParsePushConfig(args)
    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)

    no_expiration = False
    expiration_period = getattr(args, 'expiration_period', None)
    if expiration_period:
        if expiration_period == subscriptions.NEVER_EXPIRATION_PERIOD_VALUE:
            no_expiration = True
            expiration_period = None

    labels = None
    if enable_labels:
        labels = labels_util.ParseCreateArgs(
            args, client.messages.Subscription.LabelsValue)

    failed = []
    for subscription_ref in args.CONCEPTS.subscription.Parse():

        try:
            result = client.Create(subscription_ref,
                                   topic_ref,
                                   args.ack_deadline,
                                   push_config,
                                   retain_acked_messages,
                                   retention_duration,
                                   labels=labels,
                                   no_expiration=no_expiration,
                                   expiration_period=expiration_period)
        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_ref.subscriptionsId)
            continue

        if legacy_output:
            result = util.SubscriptionDisplayDict(result)

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

    if failed:
        raise util.RequestsFailedError(failed, 'create')
Ejemplo n.º 6
0
def _Run(cmd, args, field_adder):
  """Common function to run the Create command.

  Args:
    cmd: a base.CreateCommand object
    args: an argparse namespace. All the arguments that were provided to this
      command invocation.
    field_adder: Function that populates additional fields in a subscription.

  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:
    An HttpException if there was a problem calling the
    API subscriptions.Create command.
  """
  msgs = cmd.context['pubsub_msgs']
  pubsub = cmd.context['pubsub']

  topic_project = ''
  if args.topic_project:
    topic_project = projects_util.ParseProject(args.topic_project).Name()
  topic_name = args.topic

  for subscription_name in args.subscription:
    name = util.SubscriptionFormat(subscription_name)
    subscription = msgs.Subscription(
        name=name,
        topic=util.TopicFormat(topic_name, topic_project),
        ackDeadlineSeconds=args.ack_deadline)
    if args.push_endpoint:
      subscription.pushConfig = msgs.PushConfig(
          pushEndpoint=args.push_endpoint)

    field_adder(subscription, args)

    # TODO(b/32275310): Conform to gcloud error handling guidelines.
    try:
      result = pubsub.projects_subscriptions.Create(subscription)
      failed = None
    except api_ex.HttpError as error:
      result = subscription
      exc = exceptions.HttpException(error)
      failed = exc.payload.status_message

    result = util.SubscriptionDisplayDict(result, failed)
    log.CreatedResource(name, kind='subscription', failed=failed)

    yield result
  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.topics'.

    Raises:
      An HttpException if there was a problem calling the
      API subscriptions.Create command.
    """
    msgs = self.context['pubsub_msgs']
    pubsub = self.context['pubsub']

    topic_project = ''
    if args.topic_project:
      topic_project = projects_util.ParseProject(args.topic_project).Name()
    topic_name = args.topic

    for subscription_name in args.subscription:
      subscription = msgs.Subscription(
          name=util.SubscriptionFormat(subscription_name),
          topic=util.TopicFormat(topic_name, topic_project),
          ackDeadlineSeconds=args.ack_deadline)
      if args.push_endpoint:
        subscription.pushConfig = msgs.PushConfig(
            pushEndpoint=args.push_endpoint)

      try:
        result = pubsub.projects_subscriptions.Create(subscription)
        failed = None
      except api_ex.HttpError as error:
        result = subscription
        exc = exceptions.HttpException(error)
        failed = exc.payload.status_message

      result = util.SubscriptionDisplayDict(result, failed)
      log.CreatedResource(subscription_name, kind='subscription', failed=failed)
      yield result
Ejemplo n.º 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.
      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
Ejemplo n.º 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.

    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()

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

            try:
                client.Delete(subscription_ref)
            except api_ex.HttpError as error:
                exc = exceptions.HttpException(error)
                log.DeletedResource(subscription_ref.RelativeName(),
                                    kind='subscription',
                                    failed=exc.payload.status_message)
                failed.append(subscription_name)
                continue

            subscription = client.messages.Subscription(
                name=subscription_ref.RelativeName())
            result = util.SubscriptionDisplayDict(subscription)
            log.DeletedResource(subscription_ref.RelativeName(),
                                kind='subscription')
            yield result

        if failed:
            raise util.RequestsFailedError(failed, 'delete')
Ejemplo n.º 10
0
def _Run(args, enable_labels=False, legacy_output=False):
  """Creates one or more subscriptions."""
  flags.ValidateDeadLetterPolicy(args)

  client = subscriptions.SubscriptionsClient()

  topic_ref = args.CONCEPTS.topic.Parse()
  push_config = util.ParsePushConfig(args)
  enable_message_ordering = getattr(args, 'enable_message_ordering', None)
  filter_string = getattr(args, 'message_filter', None)
  dead_letter_topic = getattr(args, 'dead_letter_topic', None)
  max_delivery_attempts = getattr(args, 'max_delivery_attempts', None)
  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)
  min_retry_delay = getattr(args, 'min_retry_delay', None)
  if min_retry_delay:
    min_retry_delay = util.FormatDuration(min_retry_delay)
  max_retry_delay = getattr(args, 'max_retry_delay', None)
  if max_retry_delay:
    max_retry_delay = util.FormatDuration(max_retry_delay)

  no_expiration = False
  expiration_period = getattr(args, 'expiration_period', None)
  if expiration_period:
    if expiration_period == subscriptions.NEVER_EXPIRATION_PERIOD_VALUE:
      no_expiration = True
      expiration_period = None

  if dead_letter_topic:
    dead_letter_topic = args.CONCEPTS.dead_letter_topic.Parse().RelativeName()

  labels = None
  if enable_labels:
    labels = labels_util.ParseCreateArgs(
        args, client.messages.Subscription.LabelsValue)

  failed = []
  for subscription_ref in args.CONCEPTS.subscription.Parse():

    try:
      result = client.Create(
          subscription_ref,
          topic_ref,
          args.ack_deadline,
          push_config,
          retain_acked_messages,
          retention_duration,
          labels=labels,
          no_expiration=no_expiration,
          expiration_period=expiration_period,
          enable_message_ordering=enable_message_ordering,
          filter_string=filter_string,
          dead_letter_topic=dead_letter_topic,
          max_delivery_attempts=max_delivery_attempts,
          min_retry_delay=min_retry_delay,
          max_retry_delay=max_retry_delay)
    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_ref.subscriptionsId)
      continue

    if legacy_output:
      result = util.SubscriptionDisplayDict(result)

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

  if failed:
    raise util.RequestsFailedError(failed, 'create')