def ListIntegrations(self, integration_type_filter, service_name_filter):
        """Returns the list of integrations.

    Args:
      integration_type_filter: str, if populated integration type to filter by.
      service_name_filter: str, if populated service name to filter by.

    Returns:
      List of Dicts containing name, type, and services.

    """
        app = api_utils.GetApplication(self._client,
                                       self.GetAppRef(_DEFAULT_APP_NAME))
        if not app:
            return []

        app_dict = encoding.MessageToDict(app)
        app_resources = app_dict.get('config', {}).get('resources')
        if not app_resources:
            return []

        # Filter by type and/or service.
        output = []
        for name, resource in app_resources.items():
            resource_type = self.GetResourceTypeFromConfig(resource)
            integration_type = types_utils.GetIntegrationType(resource_type)

            # Remove invalid integrations.
            if integration_type is None:
                continue

            # Always remove services.
            if integration_type == 'service':
                continue

            # TODO(b/217744072): Support Cloud SDK topic filtering.
            # Optionally filter by type.
            if (integration_type_filter
                    and integration_type != integration_type_filter):
                continue

            # Optionally filter by service.
            services = self._GetRefServices(name, resource_type, resource,
                                            app_resources)
            if service_name_filter and service_name_filter not in services:
                continue

            # Assemble for Cloud SDK table formater.
            resource = {
                'name': name,
                'type': integration_type,
                'services': ','.join(services)
            }
            output.append(resource)

        return output
    def DeleteIntegration(self, name, tracker):
        """Delete an integration.

    Args:
      name:  str, the name of the resource to update.
      tracker: StagedProgressTracker, to report on the progress.

    Raises:
      IntegrationNotFoundError: If the integration is not found.

    Returns:
      str, the type of the integration that is deleted.
    """
        app_dict = self._GetDefaultAppDict()
        resources_map = app_dict[_CONFIG_KEY][_RESOURCES_KEY]
        resource = resources_map.get(name)
        if resource is None:
            raise exceptions.IntegrationNotFoundError(
                'Integration [{}] cannot be found'.format(name))
        resource_type = self.GetResourceTypeFromConfig(resource)

        # TODO(b/222748706): revisit whether this apply to future ingress services.
        services = []
        if not self._IsIngressResource(resource_type):
            # Unbind services
            services = self._GetRefServices(name, resource_type, resource,
                                            resources_map)
        if services:
            match_type_names = []
            for service in services:
                self._RemoveServiceToIntegrationRef(name, resource_type,
                                                    resources_map[service])
                match_type_names.append({'type': 'service', 'name': service})
            application = encoding.DictToMessage(app_dict,
                                                 self.messages.Application)
            # TODO(b/222748706): refine message on failure.
            self.ApplyAppConfig(tracker=tracker,
                                appname=_DEFAULT_APP_NAME,
                                appconfig=application.config,
                                match_type_names=match_type_names,
                                etag=application.etag)
        else:
            tracker.CompleteStage(stages.UPDATE_APPLICATION)
            tracker.CompleteStage(stages.CREATE_DEPLOYMENT)

        # TODO(b/222748706): refine message on failure.
        # Undeploy integration resource
        self._UndeployResource(resource_type, name, tracker)

        integration_type = types_utils.GetIntegrationType(resource_type)
        return integration_type
 def Run(self, args):
     """Describe an integration type."""
     name = args.name
     conn_context = connection_context.GetConnectionContext(
         args, run_flags.Product.RUN_APPS, self.ReleaseTrack())
     with run_apps_operations.Connect(conn_context) as client:
         resource_config = client.GetIntegration(name)
         resource_status = client.GetIntegrationStatus(name)
         resource_type = client.GetResourceTypeFromConfig(resource_config)
         integration_type = types_utils.GetIntegrationType(resource_type)
         return {
             'name': name,
             'region': conn_context.region,
             'type': integration_type,
             'config': resource_config,
             'status': resource_status
         }
    def Run(self, args):
        """Update a Cloud Run Integration."""

        add_service = args.add_service
        remove_service = args.remove_service
        integration_name = args.name
        parameters = flags.GetParameters(args)

        conn_context = connection_context.GetConnectionContext(
            args, run_flags.Product.RUN_APPS, self.ReleaseTrack())
        with run_apps_operations.Connect(conn_context) as client:

            with progress_tracker.StagedProgressTracker(
                    'Updating Integration...',
                    stages.IntegrationStages(create=False),
                    failure_message='Failed to update integration.'
            ) as tracker:
                client.UpdateIntegration(tracker=tracker,
                                         name=integration_name,
                                         parameters=parameters,
                                         add_service=add_service,
                                         remove_service=remove_service)

            resource_config = client.GetIntegration(integration_name)
            resource_status = client.GetIntegrationStatus(integration_name)
            resource_type = client.GetResourceTypeFromConfig(resource_config)
            integration_type = types_utils.GetIntegrationType(resource_type)

            pretty_print.Info('')
            pretty_print.Success(
                messages_util.GetSuccessMessage(
                    integration_type=integration_type,
                    integration_name=integration_name,
                    action='updated'))

            call_to_action = messages_util.GetCallToAction(
                integration_type, resource_config, resource_status)
            if call_to_action:
                pretty_print.Info('')
                pretty_print.Info(call_to_action)
                pretty_print.Info(
                    messages_util.CheckStatusMessage(self.ReleaseTrack(),
                                                     integration_name))
    def UpdateIntegration(self,
                          tracker,
                          name,
                          parameters,
                          add_service=None,
                          remove_service=None):
        """Update an integration.

    Args:
      tracker: StagedProgressTracker, to report on the progress of releasing.
      name:  str, the name of the resource to update.
      parameters: dict, the parameters from args.
      add_service: the service to attach to the integration.
      remove_service: the service to remove from the integration.

    Raises:
      IntegrationNotFoundError: If the integration is not found.

    Returns:
      The name of the integration.
    """
        app_dict = self._GetDefaultAppDict()
        resources_map = app_dict[_CONFIG_KEY][_RESOURCES_KEY]
        existing_resource = resources_map.get(name)
        if existing_resource is None:
            raise exceptions.IntegrationNotFoundError(
                'Integration [{}] cannot be found'.format(name))

        resource_type = self.GetResourceTypeFromConfig(existing_resource)
        integration_type = types_utils.GetIntegrationType(resource_type)
        flags.ValidateUpdateParameters(integration_type, parameters)
        resource_config = self._GetResourceConfig(resource_type, parameters,
                                                  add_service, remove_service,
                                                  existing_resource)
        resources_map[name] = resource_config
        match_type_names = self._GetCreateSelectors(name, resource_type,
                                                    add_service,
                                                    remove_service)

        if add_service:
            self._EnsureServiceConfig(resources_map, add_service)
            self._AddServiceToIntegrationRef(name, resource_type,
                                             resources_map[add_service])
        if remove_service and remove_service in resources_map:
            self._RemoveServiceToIntegrationRef(name, resource_type,
                                                resources_map[remove_service])

        services = []
        if self._IsIngressResource(resource_type):
            # For ingress resource, expand the check list and selector to include all
            # binded services.
            services = self._GetRefServices(name, resource_type,
                                            resource_config, resources_map)
            for service in services:
                if service != add_service:
                    match_type_names.append({
                        'type': 'service',
                        'name': service
                    })
        elif add_service:
            services.append(add_service)
        elif self._IsBackingResource(resource_type) and remove_service is None:
            services.extend(
                self._GetRefServices(name, resource_type, resource_config,
                                     resources_map))
            for service in services:
                match_type_names.append({'type': 'service', 'name': service})

        if services:
            self.CheckCloudRunServices(services)

        deploy_message = messages_util.GetDeployMessage(resource_type)
        application = encoding.DictToMessage(app_dict,
                                             self.messages.Application)
        return self.ApplyAppConfig(tracker=tracker,
                                   appname=_DEFAULT_APP_NAME,
                                   appconfig=application.config,
                                   integration_name=name,
                                   deploy_message=deploy_message,
                                   match_type_names=match_type_names,
                                   etag=application.etag)