Esempio 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
Esempio n. 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:
      A PullResponse message with the response of the Pull operation.
    """
        msgs = self.context['pubsub_msgs']
        pubsub = self.context['pubsub']

        subscription = util.SubscriptionFormat(args.subscription)
        pull_req = msgs.PubsubProjectsSubscriptionsPullRequest(
            pullRequest=msgs.PullRequest(maxMessages=args.max_messages,
                                         returnImmediately=True),
            subscription=subscription)

        pull_response = pubsub.projects_subscriptions.Pull(pull_req)

        if args.auto_ack and pull_response.receivedMessages:
            ack_ids = [
                message.ackId for message in pull_response.receivedMessages
            ]

            ack_req = msgs.PubsubProjectsSubscriptionsAcknowledgeRequest(
                acknowledgeRequest=msgs.AcknowledgeRequest(ackIds=ack_ids),
                subscription=subscription)
            pubsub.projects_subscriptions.Acknowledge(ack_req)

        return pull_response.receivedMessages
Esempio 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.

    Returns:
      A 2-tuple of lists, one populated with the subscription paths that were
      successfully deleted, the other one with the list of subscription paths
      that could not be deleted.
    """
        msgs = self.context['pubsub_msgs']
        pubsub = self.context['pubsub']

        succeeded = []
        failed = []

        for subscription_name in args.subscription:
            delete_req = msgs.PubsubProjectsSubscriptionsDeleteRequest(
                subscription=util.SubscriptionFormat(subscription_name))
            try:
                pubsub.projects_subscriptions.Delete(delete_req)
                succeeded.append(delete_req.subscription)
            except api_ex.HttpError as e:
                failed.append((delete_req.subscription,
                               json.loads(e.content)['error']['message']))

        return succeeded, failed
Esempio 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:
      None
    """
        msgs = self.context['pubsub_msgs']
        pubsub = self.context['pubsub']

        subscription = util.SubscriptionFormat(
            resources.REGISTRY.Parse(
                args.subscription,
                collection=util.SUBSCRIPTIONS_COLLECTION).Name())
        mod_req = msgs.PubsubProjectsSubscriptionsModifyPushConfigRequest(
            modifyPushConfigRequest=msgs.ModifyPushConfigRequest(
                pushConfig=msgs.PushConfig(pushEndpoint=args.push_endpoint)),
            subscription=subscription)

        pubsub.projects_subscriptions.ModifyPushConfig(mod_req)
        return {
            'subscriptionId': subscription,
            'pushEndpoint': args.push_endpoint
        }
Esempio n. 5
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:
      Display dictionary with information about the new ACK deadline seconds
      for the given subscription and ackId.
    """
        msgs = self.context['pubsub_msgs']
        pubsub = self.context['pubsub']

        subscription = util.SubscriptionFormat(args.subscription)
        mod_req = msgs.PubsubProjectsSubscriptionsModifyAckDeadlineRequest(
            modifyAckDeadlineRequest=msgs.ModifyAckDeadlineRequest(
                ackDeadlineSeconds=args.ack_deadline, ackIds=args.ackid),
            subscription=subscription)

        pubsub.projects_subscriptions.ModifyAckDeadline(mod_req)
        return {
            'subscriptionId': subscription,
            'ackId': args.ackid,
            'ackDeadlineSeconds': args.ack_deadline
        }
Esempio n. 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:
      Ack display dictionary with information about the acknowledged messages
      and related subscription.
    """
        msgs = self.context['pubsub_msgs']
        pubsub = self.context['pubsub']

        ack_req = msgs.PubsubProjectsSubscriptionsAcknowledgeRequest(
            acknowledgeRequest=msgs.AcknowledgeRequest(ackIds=args.ackid),
            subscription=util.SubscriptionFormat(args.subscription))

        pubsub.projects_subscriptions.Acknowledge(ack_req)

        # Using this dict, instead of returning the AcknowledgeRequest directly,
        # to preserve the naming conventions for subscriptionId.
        return {
            'subscriptionId': ack_req.subscription,
            'ackIds': ack_req.acknowledgeRequest.ackIds
        }
Esempio n. 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:
      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
Esempio n. 8
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
Esempio n. 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.

    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 = resources.REGISTRY.Parse(
            args.topic, collection=util.TOPICS_COLLECTION).Name()

        for subscription in args.subscription:
            subscription_name = resources.REGISTRY.Parse(
                subscription, collection=util.SUBSCRIPTIONS_COLLECTION).Name()
            create_req = msgs.Subscription(
                name=util.SubscriptionFormat(subscription_name),
                topic=util.TopicFormat(topic_name, topic_project),
                ackDeadlineSeconds=args.ack_deadline)
            if args.push_endpoint:
                create_req.pushConfig = msgs.PushConfig(
                    pushEndpoint=args.push_endpoint)

            try:
                yield SubscriptionDisplayDict(
                    pubsub.projects_subscriptions.Create(create_req))
            except api_ex.HttpError as exc:
                raise exceptions.HttpException(
                    json.loads(exc.content)['error']['message'])
Esempio n. 11
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'.
    """
        msgs = self.context['pubsub_msgs']
        pubsub = self.context['pubsub']

        subscription_project = ''
        if args.subscription_project:
            subscription_project = projects_util.ParseProject(
                args.subscription_project).Name()
        subscription_name = args.subscription

        for snapshot_name in args.snapshot:
            snapshot_path = util.SnapshotFormat(snapshot_name)
            create_req = msgs.PubsubProjectsSnapshotsCreateRequest(
                createSnapshotRequest=msgs.CreateSnapshotRequest(
                    subscription=util.SubscriptionFormat(
                        subscription_name, subscription_project)),
                name=snapshot_path)

            # TODO(b/32275310): Conform to gcloud error handling guidelines.
            try:
                result = pubsub.projects_snapshots.Create(create_req)
                failed = None
            except api_ex.HttpError as error:
                result = msgs.Snapshot(name=snapshot_path)
                exc = exceptions.HttpException(error)
                failed = exc.payload.status_message

            result = util.SnapshotDisplayDict(result, failed)
            log.CreatedResource(snapshot_path, kind='snapshot', failed=failed)
            yield result
Esempio n. 12
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.subscriptions.seek'.
    """
        msgs = self.context['pubsub_msgs']
        pubsub = self.context['pubsub']

        subscription_path = util.SubscriptionFormat(args.subscription)
        result = {'subscriptionId': subscription_path}

        seek_req = msgs.SeekRequest()
        if args.snapshot:
            if args.snapshot_project:
                snapshot_project = (projects_util.ParseProject(
                    args.snapshot_project).Name())
            else:
                snapshot_project = ''
            seek_req.snapshot = util.SnapshotFormat(args.snapshot,
                                                    snapshot_project)
            result['snapshotId'] = seek_req.snapshot
        else:
            seek_req.time = args.time.strftime('%Y-%m-%dT%H:%M:%S.%fZ')
            result['time'] = seek_req.time

        pubsub.projects_subscriptions.Seek(
            msgs.PubsubProjectsSubscriptionsSeekRequest(
                seekRequest=seek_req, subscription=subscription_path))

        return result