コード例 #1
0
  def Run(self, args):
    conn_context = connection_context.GetConnectionContext(
        args, product=connection_context.Product.EVENTS)
    if conn_context.supports_one_platform:
      raise exceptions.UnsupportedArgumentError(
          'Events are only available with Cloud Run for Anthos.')

    trigger_ref = args.CONCEPTS.trigger.Parse()
    namespace_ref = trigger_ref.Parent()
    with eventflow_operations.Connect(conn_context) as client:
      source_crds = client.ListSourceCustomResourceDefinitions()
      event_type = util.EventTypeFromTypeString(source_crds, args.type)
      source_obj = source.Source.New(client.client, namespace_ref.Name(),
                                     event_type.crd.source_kind,
                                     event_type.crd.source_api_category)
      source_obj.name = _SOURCE_NAME_PATTERN.format(
          trigger=trigger_ref.Name())

      trigger_obj = client.GetTrigger(trigger_ref)
      if trigger_obj is not None:
        # If trigger already exists, validate it has the attributes we're trying
        # to set right now.
        try:
          util.ValidateTrigger(trigger_obj, source_obj, event_type)
        except AssertionError:
          raise exceptions.TriggerCreationError(
              'Trigger [{}] already exists with attributes not '
              'matching this event type.'.format(trigger_obj.name))
        # If the trigger has the right attributes, check if there's already
        # a source that matches the attributes as well.
        source_ref = util.GetSourceRef(
            source_obj.name, source_obj.namespace, event_type.crd)
        if client.GetSource(source_ref, event_type.crd) is not None:
          raise exceptions.TriggerCreationError(
              'Trigger [{}] already exists.'.format(trigger_obj.name))

      parameters = events_flags.GetAndValidateParameters(args, event_type)

      # Create the trigger and source
      with progress_tracker.StagedProgressTracker(
          'Initializing trigger...',
          stages.TriggerSourceStages(),
          failure_message='Trigger creation failed') as tracker:
        client.CreateTriggerAndSource(
            trigger_obj,
            trigger_ref,
            namespace_ref,
            source_obj,
            event_type,
            parameters,
            args.broker,
            args.target_service,
            tracker
        )
コード例 #2
0
  def CreateTrigger(self, trigger_ref, source_obj, event_type, target_service):
    """Create a trigger that sends events to the target service.

    Args:
      trigger_ref: googlecloudsdk.core.resources.Resource, trigger resource.
      source_obj: source.Source. The source object to be created after the
        trigger.
      event_type: custom_resource_definition.EventTypeDefinition, the event
        type the source will filter by.
      target_service: str, name of the Cloud Run service to subscribe.

    Returns:
      trigger.Trigger of the created trigger.
    """
    trigger_obj = trigger.Trigger.New(self._client, trigger_ref.Parent().Name())
    trigger_obj.name = trigger_ref.Name()
    trigger_obj.dependency = source_obj
    # TODO(b/141617597): Set to str(random.random()) without prepended string
    trigger_obj.filter_attributes[
        trigger.SOURCE_TRIGGER_LINK_FIELD] = 'link{}'.format(random.random())
    trigger_obj.filter_attributes[
        trigger.EVENT_TYPE_FIELD] = event_type.type
    trigger_obj.subscriber = target_service

    request = self.messages.RunNamespacesTriggersCreateRequest(
        trigger=trigger_obj.Message(),
        parent=trigger_ref.Parent().RelativeName())
    with metrics.RecordDuration(metric_names.CREATE_TRIGGER):
      try:
        response = self._client.namespaces_triggers.Create(request)
      except api_exceptions.HttpConflictError:
        raise exceptions.TriggerCreationError(
            'Trigger [{}] already exists.'.format(trigger_obj.name))

    return trigger.Trigger(response, self.messages)
コード例 #3
0
    def CreateTrigger(self, trigger_ref, source_obj, event_type,
                      trigger_filters, target_service, broker):
        """Create a trigger that sends events to the target service.

    Args:
      trigger_ref: googlecloudsdk.core.resources.Resource, trigger resource.
      source_obj: source.Source. The source object to be created after the
        trigger. If creating a custom event, this may be None.
      event_type: str, the event type the source will filter by.
      trigger_filters: collections.OrderedDict()
      target_service: str, name of the Cloud Run service to subscribe.
      broker: str, name of the broker to act as a sink for the source.

    Returns:
      trigger.Trigger of the created trigger.
    """
        trigger_obj = trigger.Trigger.New(self._client,
                                          trigger_ref.Parent().Name())
        trigger_obj.name = trigger_ref.Name()
        if source_obj is not None:
            trigger_obj.dependency = source_obj
            # TODO(b/141617597): Set to str(random.random()) without prepended string
            trigger_obj.filter_attributes[
                trigger.SOURCE_TRIGGER_LINK_FIELD] = 'link{}'.format(
                    random.random())
        trigger_obj.filter_attributes[trigger.EVENT_TYPE_FIELD] = event_type

        # event/flags.py ensures filter key doesn't include disallowed fields
        trigger_obj.filter_attributes.update(trigger_filters)

        trigger_obj.subscriber = target_service
        trigger_obj.broker = broker

        request = self.messages.RunNamespacesTriggersCreateRequest(
            trigger=trigger_obj.Message(),
            parent=trigger_ref.Parent().RelativeName())
        try:
            with metrics.RecordDuration(metric_names.CREATE_TRIGGER):
                response = self._client.namespaces_triggers.Create(request)
        except api_exceptions.HttpConflictError:
            raise exceptions.TriggerCreationError(
                'Trigger [{}] already exists.'.format(trigger_obj.name))

        return trigger.Trigger(response, self.messages)
コード例 #4
0
    def Run(self, args):
        conn_context = connection_context.GetConnectionContext(
            args, serverless_flags.Product.EVENTS, self.ReleaseTrack())

        trigger_ref = args.CONCEPTS.trigger.Parse()
        namespace_ref = trigger_ref.Parent()
        with eventflow_operations.Connect(conn_context) as client:
            if client.IsCluster():
                trigger_ref = resources.REGISTRY.Parse(
                    trigger_ref.RelativeName(),
                    collection=util.ANTHOS_TRIGGER_COLLECTION_NAME,
                    api_version=client.api_version)

                namespace_ref = trigger_ref.Parent()
            if args.custom_type:
                event_type = args.type
                source_obj = None
                tracker_stages = stages.TriggerStages()
            else:
                source_crds = client.ListSourceCustomResourceDefinitions()
                event_type = util.EventTypeFromTypeString(
                    source_crds, args.type, args.source)
                source_obj = source.Source.New(
                    client.client, namespace_ref.Name(),
                    event_type.crd.source_kind,
                    event_type.crd.source_api_category)
                source_obj.name = _SOURCE_NAME_PATTERN.format(
                    trigger=trigger_ref.Name())
                parameters = flags.GetAndValidateParameters(args, event_type)
                tracker_stages = stages.TriggerAndSourceStages()

            trigger_obj = client.GetTrigger(trigger_ref)
            if trigger_obj is not None:
                if args.custom_type:
                    # If custom type, no need to check idempotency since there's only
                    # a trigger to worry about.
                    raise exceptions.TriggerCreationError(
                        'Trigger [{}] already exists.'.format(
                            trigger_obj.name))
                else:
                    # If trigger already exists, validate it has the attributes we're
                    # trying to set right now to see if this is a case of idempotency.
                    try:
                        util.ValidateTrigger(trigger_obj, source_obj,
                                             event_type)
                    except AssertionError:
                        raise exceptions.TriggerCreationError(
                            'Trigger [{}] already exists with attributes not '
                            'matching this event type.'.format(
                                trigger_obj.name))
                    # If the trigger has the right attributes, check if there's already
                    # a source that matches the attributes as well.
                    source_ref = util.GetSourceRef(source_obj.name,
                                                   source_obj.namespace,
                                                   event_type.crd,
                                                   client.IsCluster())
                    if client.GetSource(source_ref,
                                        event_type.crd) is not None:
                        raise exceptions.TriggerCreationError(
                            'Trigger [{}] already exists.'.format(
                                trigger_obj.name))

            # Create the trigger and source
            with progress_tracker.StagedProgressTracker(
                    'Initializing trigger...',
                    tracker_stages,
                    failure_message='Trigger creation failed') as tracker:
                if trigger_obj is None:
                    trigger_obj = client.CreateTrigger(
                        trigger_ref, source_obj,
                        event_type if args.custom_type else event_type.type,
                        args.trigger_filters, args.target_service, args.broker)
                if not args.custom_type:
                    client.CreateSource(source_obj, event_type.crd,
                                        trigger_obj, namespace_ref,
                                        args.broker, parameters)
                    client.PollSource(source_obj, event_type, tracker)
                client.PollTrigger(trigger_ref, tracker)