Exemplo n.º 1
0
  def Run(self, args):
    conn_context = connection_context.EventsConnectionContext(args)
    namespace_ref = args.CONCEPTS.namespace.Parse()

    with eventflow_operations.Connect(conn_context) as client:
      brokers = client.ListBrokers(namespace_ref.RelativeName())
      return brokers
Exemplo n.º 2
0
  def Run(self, args):
    conn_context = connection_context.GetConnectionContext(
        args, product=connection_context.Product.EVENTS)

    with eventflow_operations.Connect(conn_context) as client:
      source_crds = client.ListSourceCustomResourceDefinitions()
      return [crd for crd in source_crds if crd.event_types]
Exemplo n.º 3
0
    def Run(self, args):
        conn_context = connection_context.EventsConnectionContext(args)

        with eventflow_operations.Connect(conn_context) as client:
            source_crds = client.ListSourceCustomResourceDefinitions()
            return util.EventTypeFromTypeString(source_crds, args.event_type,
                                                args.source)
Exemplo n.º 4
0
    def Run(self, args):
        """Executes when the user runs the describe command."""
        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()
        with eventflow_operations.Connect(conn_context) as client:
            trigger_obj = client.GetTrigger(trigger_ref)
            source_obj = None
            if trigger_obj is not None:
                source_crds = client.ListSourceCustomResourceDefinitions()
                source_obj_ref = trigger_obj.dependency
                source_crd = next((s for s in source_crds
                                   if s.source_kind == source_obj_ref.kind),
                                  None)
                if source_crd is not None:
                    source_ref = util.GetSourceRef(source_obj_ref.name,
                                                   source_obj_ref.namespace,
                                                   source_crd)
                    source_obj = client.GetSource(source_ref, source_crd)
        if not trigger_obj:
            raise exceptions.TriggerNotFound('Trigger [{}] not found.'.format(
                trigger_ref.Name()))
        if not source_obj:
            log.warning('No matching event source for trigger [{}].'.format(
                trigger_ref.Name()))
        return SerializedTriggerAndSource(
            trigger_obj.MakeSerializable(),
            source_obj.MakeSerializable() if source_obj else None)
Exemplo n.º 5
0
  def Run(self, args):
    """Executes when the user runs the delete command."""
    conn_context = connection_context.GetConnectionContext(
        args, serverless_flags.Product.EVENTS, self.ReleaseTrack())

    trigger_ref = args.CONCEPTS.trigger.Parse()
    console_io.PromptContinue(
        message='Trigger [{}] will be deleted.'.format(trigger_ref.Name()),
        throw_if_unattended=True,
        cancel_on_no=True)

    with eventflow_operations.Connect(conn_context) as client:
      # TODO(b/147308604): Don't delete source when Odin supports ownerRefs
      if serverless_flags.GetPlatform() == serverless_flags.PLATFORM_MANAGED:
        trigger_obj = client.GetTrigger(trigger_ref)
        if trigger_obj is not None:
          source_crds = client.ListSourceCustomResourceDefinitions()
          source_ref, source_crd = util.GetSourceRefAndCrdForTrigger(
              trigger_obj, source_crds)
          if source_ref and source_crd:
            # Delete the source before the trigger because we need the trigger
            # to exist to be able to find the source. Otherwise, we could end up
            # losing a reference to the source if trigger deletion succeeds but
            # source deletion fails.
            try:
              client.DeleteSource(source_ref, source_crd)
            except exceptions.SourceNotFound:
              # Source could have been deleted but trigger deletion failed
              # and this command was re-run, which is fine.
              pass
      client.DeleteTrigger(trigger_ref)

    log.DeletedResource(trigger_ref.Name(), 'trigger')
Exemplo n.º 6
0
    def Run(self, args):
        """Executes when user runs the init command."""
        if platforms.GetPlatform() == platforms.PLATFORM_MANAGED:
            raise exceptions.UnsupportedArgumentError(
                'This command is only available with Cloud Run for Anthos.')

        kuberun_events_flags.ValidateAuthenticationFlags(args)

        conn_context = connection_context.GetConnectionContext(
            args, serverless_flags.Product.EVENTS, self.ReleaseTrack())

        namespace_ref = args.CONCEPTS.namespace.Parse()

        with eventflow_operations.Connect(conn_context) as client:
            product_type = init_shared.determine_product_type(
                client, args.authentication)

            if not client.GetNamespace(namespace_ref):
                client.CreateNamespace(namespace_ref)

            if args.authentication == events_constants.AUTH_SECRETS:
                client.CreateOrReplaceSourcesSecret(namespace_ref,
                                                    product_type)

        log.status.Print(
            'Initialized namespace [{}] for Cloud Run eventing with '
            'secret {}'.format(namespace_ref.Name(),
                               anthosevents_operations.SOURCES_KEY))
Exemplo n.º 7
0
    def Run(self, args):
        conn_context = connection_context.GetConnectionContext(
            args, serverless_flags.Product.EVENTS, self.ReleaseTrack())

        with eventflow_operations.Connect(conn_context) as client:
            source_crds = client.ListSourceCustomResourceDefinitions()
            return [crd for crd in source_crds if crd.event_types]
Exemplo n.º 8
0
  def Run(self, args):
    """Executes when the user runs the describe command."""
    conn_context = connection_context.GetConnectionContext(
        args, product=connection_context.Product.EVENTS)

    trigger_ref = args.CONCEPTS.trigger.Parse()
    with eventflow_operations.Connect(conn_context) as client:
      trigger_obj = client.GetTrigger(trigger_ref)
      source_obj = None
      if trigger_obj is not None:
        source_crds = client.ListSourceCustomResourceDefinitions()
        source_ref, source_crd = util.GetSourceRefAndCrdForTrigger(
            trigger_obj, source_crds)
        if source_ref and source_crd:
          source_obj = client.GetSource(source_ref, source_crd)

    if not trigger_obj:
      raise exceptions.TriggerNotFound(
          'Trigger [{}] not found.'.format(trigger_ref.Name()))
    if not source_obj:
      log.warning('No matching event source for trigger [{}].'.format(
          trigger_ref.Name()))
    return SerializedTriggerAndSource(
        trigger_obj.MakeSerializable(),
        source_obj.MakeSerializable() if source_obj else None)
Exemplo n.º 9
0
    def Run(self, args):
        """Executes when the user runs the describe command."""
        conn_context = connection_context.GetConnectionContext(
            args, serverless_flags.Product.EVENTS, self.ReleaseTrack())

        trigger_ref = args.CONCEPTS.trigger.Parse()
        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)

            trigger_obj = client.GetTrigger(trigger_ref)
            source_obj = None
            if trigger_obj is not None:
                source_crds = client.ListSourceCustomResourceDefinitions()
                source_ref, source_crd = util.GetSourceRefAndCrdForTrigger(
                    trigger_obj, source_crds, client.IsCluster())
                if source_ref and source_crd:
                    source_obj = client.GetSource(source_ref, source_crd)

        if not trigger_obj:
            raise exceptions.TriggerNotFound('Trigger [{}] not found.'.format(
                trigger_ref.Name()))
        if not source_obj:
            log.warning('No matching event source for trigger [{}].'.format(
                trigger_ref.Name()))
        return SerializedTriggerAndSource(
            trigger_obj.MakeSerializable(),
            source_obj.MakeSerializable() if source_obj else None)
Exemplo n.º 10
0
  def Run(self, args):
    conn_context = connection_context.GetConnectionContext(
        args, serverless_flags.Product.EVENTS, self.ReleaseTrack())

    with eventflow_operations.Connect(conn_context) as client:
      source_crds = client.ListSourceCustomResourceDefinitions()
      return util.EventTypeFromTypeString(
          source_crds, args.event_type, args.source)
Exemplo n.º 11
0
    def Run(self, args):
        conn_context = connection_context.GetConnectionContext(args)
        if conn_context.supports_one_platform:
            raise exceptions.UnsupportedArgumentError(
                'Events are only available with Cloud Run for Anthos.')

        with eventflow_operations.Connect(conn_context) as client:
            source_crds = client.ListSourceCustomResourceDefinitions()
            return util.EventTypeFromTypeString(source_crds, args.event_type)
Exemplo n.º 12
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.')

        with eventflow_operations.Connect(conn_context) as client:
            source_crds = client.ListSourceCustomResourceDefinitions()
            return [crd for crd in source_crds if crd.event_types]
Exemplo n.º 13
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
        )
Exemplo n.º 14
0
  def Run(self, args):
    conn_context = connection_context.GetConnectionContext(
        args, serverless_flags.Product.EVENTS, self.ReleaseTrack())

    with eventflow_operations.Connect(conn_context) as client:
      source_crds = client.ListSourceCustomResourceDefinitions()
      event_types = []
      for crd in source_crds:
        if not args.IsSpecified('source') or args.source == crd.source_kind:
          event_types.extend(crd.event_types)
      return event_types
Exemplo n.º 15
0
  def Run(self, args):
    if serverless_flags.GetPlatform() == serverless_flags.PLATFORM_MANAGED:
      raise exceptions.UnsupportedArgumentError(
          'This command is only available with Cloud Run for Anthos.')
    conn_context = connection_context.GetConnectionContext(
        args, serverless_flags.Product.EVENTS, self.ReleaseTrack())
    namespace_ref = args.CONCEPTS.namespace.Parse()

    with eventflow_operations.Connect(conn_context) as client:
      brokers = client.ListBrokers(namespace_ref.RelativeName())
      return brokers
Exemplo n.º 16
0
  def Run(self, args):
    conn_context = connection_context.GetConnectionContext(
        args, product=serverless_flags.Product.EVENTS)

    namespace_ref = args.CONCEPTS.namespace.Parse()
    with eventflow_operations.Connect(conn_context) as client:
      self.SetCompleteApiEndpoint(conn_context.endpoint)
      triggers = client.ListTriggers(namespace_ref)
      if args.target_service:
        triggers = [t for t in triggers if t.subscriber == args.target_service]
      return triggers
Exemplo n.º 17
0
    def Run(self, args):
        conn_context = connection_context.EventsConnectionContext(args)

        with eventflow_operations.Connect(conn_context) as client:
            source_crds = client.ListSourceCustomResourceDefinitions()
            event_types = []
            for crd in source_crds:
                if not args.IsSpecified(
                        'source') or args.source == crd.source_kind:
                    event_types.extend(crd.event_types)
            return event_types
Exemplo n.º 18
0
    def Run(self, args):
        conn_context = connection_context.GetConnectionContext(args)
        if conn_context.supports_one_platform:
            raise exceptions.ConfigurationError(
                'Triggers are not yet supported on the fully managed version '
                'of Cloud Run.')

        namespace_ref = args.CONCEPTS.namespace.Parse()
        with eventflow_operations.Connect(conn_context) as client:
            self.SetCompleteApiEndpoint(conn_context.endpoint)
            return client.ListTriggers(namespace_ref)
Exemplo n.º 19
0
    def Run(self, args):
        conn_context = connection_context.GetConnectionContext(
            args, product=connection_context.Product.EVENTS)

        with eventflow_operations.Connect(conn_context) as client:
            source_crds = client.ListSourceCustomResourceDefinitions()
            event_types = []
            for crd in source_crds:
                if not args.category or args.category == crd.source_kind:
                    event_types.extend(crd.event_types)
            return event_types
  def testConnectAnthos(self):
    mock_context = mock.Mock()
    mock_context.__enter__ = mock.Mock(return_value=mock_context)
    mock_context.__exit__ = mock.Mock(return_value=False)
    mock_context.supports_one_platform = False
    mock_context.region = None

    with eventflow_operations.Connect(mock_context) as eventflow_client:
      self.assertEqual(eventflow_client._client, self.mock_client)
      self.assertEqual(eventflow_client._core_client, self.mock_client)
      self.assertEqual(eventflow_client._crd_client, self.mock_client)
      self.assertEqual(eventflow_client._op_client, self.mock_client)
      self.assertIsNone(eventflow_client._region)
Exemplo n.º 21
0
    def Run(self, args):
        conn_context = connection_context.GetConnectionContext(args)
        if conn_context.supports_one_platform:
            raise exceptions.UnsupportedArgumentError(
                'Events are only available with Cloud Run for Anthos.')

        with eventflow_operations.Connect(conn_context) as client:
            source_crds = client.ListSourceCustomResourceDefinitions()
            event_types = []
            for crd in source_crds:
                if not args.category or args.category == crd.source_kind:
                    event_types.extend(crd.event_types)
            return event_types
Exemplo n.º 22
0
  def Run(self, args):
    conn_context = connection_context.GetConnectionContext(args)
    if conn_context.supports_one_platform:
      raise exceptions.UnsupportedArgumentError(
          'Events are only available with Cloud Run for Anthos.')

    namespace_ref = args.CONCEPTS.namespace.Parse()
    with eventflow_operations.Connect(conn_context) as client:
      self.SetCompleteApiEndpoint(conn_context.endpoint)
      triggers = client.ListTriggers(namespace_ref)
      if args.target_service:
        triggers = [t for t in triggers if t.subscriber == args.target_service]
      return triggers
Exemplo n.º 23
0
    def Run(self, args):
        """Executes when the user runs the delete command."""
        conn_context = connection_context.GetConnectionContext(
            args, product=connection_context.Product.EVENTS)

        trigger_ref = args.CONCEPTS.trigger.Parse()
        console_io.PromptContinue(
            message='Trigger [{}] will be deleted.'.format(trigger_ref.Name()),
            throw_if_unattended=True,
            cancel_on_no=True)

        with eventflow_operations.Connect(conn_context) as client:
            client.DeleteTrigger(trigger_ref)
        log.DeletedResource(trigger_ref.Name(), 'trigger')
Exemplo n.º 24
0
    def Run(self, args):
        """Executes when the user runs the delete command."""
        if serverless_flags.GetPlatform() == serverless_flags.PLATFORM_MANAGED:
            raise exceptions.UnsupportedArgumentError(
                'This command is only available with Cloud Run for Anthos.')
        project = properties.VALUES.core.project.Get(required=True)
        conn_context = connection_context.GetConnectionContext(
            args, serverless_flags.Product.EVENTS, self.ReleaseTrack())

        with eventflow_operations.Connect(conn_context) as client:
            cloud_run_obj = client.GetCloudRun()
            if cloud_run_obj is None:
                pass
            elif cloud_run_obj.eventing_enabled:
                log.status.Print('Eventing already enabled.')
            else:
                tracker_stages = stages.EventingStages()

                # Enable eventing
                with progress_tracker.StagedProgressTracker(
                        'Enabling eventing...',
                        tracker_stages,
                        failure_message='Failed to enable eventing'
                ) as tracker:
                    response = client.UpdateCloudRunWithEventingEnabled()

                    # Wait for Operator to enable eventing
                    client.PollCloudRunResource(tracker)
                    log.status.Print('Enabled eventing successfully.')

            if client.IsClusterInitialized():
                console_io.PromptContinue(
                    message='This cluster has already been initialized.',
                    prompt_string='Would you like to re-run initialization?',
                    cancel_on_no=True)

            _EnableMissingServices(project)

            for sa_config in [
                    _CONTROL_PLANE_SERVICE_ACCOUNT_CONFIG,
                    _BROKER_SERVICE_ACCOUNT_CONFIG,
                    _SOURCES_SERVICE_ACCOUNT_CONFIG
            ]:
                _ConfigureServiceAccount(sa_config, client, args)

            client.MarkClusterInitialized()

        log.status.Print(
            _InitializedMessage(self.ReleaseTrack(),
                                conn_context.cluster_name))
Exemplo n.º 25
0
    def Run(self, args):
        """Executes when the user runs the describe command."""
        conn_context = connection_context.GetConnectionContext(args)
        if conn_context.supports_one_platform:
            raise exceptions.UnsupportedArgumentError(
                'Events are only available with Cloud Run for Anthos.')

        trigger_ref = args.CONCEPTS.trigger.Parse()
        with eventflow_operations.Connect(conn_context) as client:
            trigger_obj = client.GetTrigger(trigger_ref)
        if not trigger_obj:
            raise exceptions.TriggerNotFound('Trigger [{}] not found.'.format(
                trigger_ref.Name()))
        return trigger_obj
  def testConnectManaged(self):
    region = 'us-central1'

    mock_context = mock.Mock()
    mock_context.__enter__ = mock.Mock(return_value=mock_context)
    mock_context.__exit__ = mock.Mock(return_value=False)
    mock_context.supports_one_platform = True
    mock_context.region = region

    with eventflow_operations.Connect(mock_context) as eventflow_client:
      self.assertEqual(eventflow_client._client, self.mock_client)
      self.assertIsNone(eventflow_client._core_client)
      self.assertEqual(eventflow_client._crd_client, self.mock_client)
      self.assertEqual(eventflow_client._op_client, self.mock_client)
      self.assertEqual(eventflow_client._region, region)
Exemplo n.º 27
0
    def Run(self, args):
        """Executes when the user runs the describe command."""
        conn_context = connection_context.EventsConnectionContext(args)

        namespace_ref = args.CONCEPTS.namespace.Parse()
        broker_name = args.BROKER
        broker_full_name = namespace_ref.RelativeName(
        ) + '/brokers/' + broker_name

        with eventflow_operations.Connect(conn_context) as client:
            broker_obj = client.GetBroker(broker_full_name)

        if not broker_obj:
            raise exceptions.BrokerNotFound(
                'Broker [{}] not found.'.format(broker_name))
        return broker_obj
Exemplo n.º 28
0
    def Run(self, args):
        """Executes when the user runs the delete command."""
        conn_context = connection_context.GetConnectionContext(args)
        if conn_context.supports_one_platform:
            raise exceptions.UnsupportedArgumentError(
                'Events are only available with Cloud Run for Anthos.')

        trigger_ref = args.CONCEPTS.trigger.Parse()
        console_io.PromptContinue(
            message='Trigger [{}] will be deleted.'.format(trigger_ref.Name()),
            throw_if_unattended=True,
            cancel_on_no=True)

        with eventflow_operations.Connect(conn_context) as client:
            client.DeleteTrigger(trigger_ref)
        log.DeletedResource(trigger_ref.Name(), 'trigger')
Exemplo n.º 29
0
    def Run(self, args):
        """Executes when the user runs the delete command."""
        conn_context = connection_context.EventsConnectionContext(args)

        namespace_ref = args.CONCEPTS.namespace.Parse()
        broker_name = args.BROKER

        console_io.PromptContinue(
            message='Broker [{}] will be deleted.'.format(broker_name),
            throw_if_unattended=True,
            cancel_on_no=True)

        with eventflow_operations.Connect(conn_context) as client:
            client.DeleteBroker(namespace_ref.Name(), broker_name)

        log.DeletedResource(broker_name, 'broker')
Exemplo n.º 30
0
    def Run(self, args):
        """Executes when the user runs the delete command."""
        if serverless_flags.GetPlatform() == serverless_flags.PLATFORM_MANAGED:
            raise exceptions.UnsupportedArgumentError(
                'This command is only available with Cloud Run for Anthos.')

        if args.BROKER != _DEFAULT_BROKER_NAME:
            raise exceptions.UnsupportedArgumentError(
                'Only brokers named "default" may be created.')

        conn_context = connection_context.GetConnectionContext(
            args, product=serverless_flags.Product.EVENTS)

        service_account_ref = resources.REGISTRY.Parse(
            args.service_account,
            params={'projectsId': '-'},
            collection=core_iam_util.SERVICE_ACCOUNTS_COLLECTION)
        namespace_ref = args.CONCEPTS.namespace.Parse()
        secret_ref = resources.REGISTRY.Parse(
            _DATA_PLANE_SECRET_NAME,
            params={'namespacesId': namespace_ref.Name()},
            collection='run.api.v1.namespaces.secrets',
            api_version='v1')

        # Validate the service account has the necessary roles
        roles = iam_util.GetProjectRolesForServiceAccount(service_account_ref)
        if not (_OWNER_ROLE in roles
                or _DATA_PLANE_SECRET_MIN_REQUIRED_ROLES.issubset(roles)):
            missing_roles = _DATA_PLANE_SECRET_MIN_REQUIRED_ROLES - roles
            raise exceptions.ServiceAccountMissingRequiredPermissions(
                'Service account [{}] does not have necessary role(s): {}'.
                format(service_account_ref.Name(), ', '.join(missing_roles)))

        with eventflow_operations.Connect(conn_context) as client:
            if console_io.CanPrompt():
                console_io.PromptContinue(
                    message='This will create a new key for the provided '
                    'service account.',
                    cancel_on_no=True)
            _, key_ref = client.CreateOrReplaceServiceAccountSecret(
                secret_ref, service_account_ref)
            client.UpdateNamespaceWithLabels(namespace_ref, _INJECTION_LABELS)

        log.status.Print('Created broker [{}] in namespace [{}] with '
                         'key [{}] for service account [{}].'.format(
                             args.BROKER, namespace_ref.Name(), key_ref.Name(),
                             service_account_ref.Name()))