def Run(self, args):
     """List available routes."""
     conn_context = connection_context.GetConnectionContext(
         args, flags.Product.RUN, self.ReleaseTrack())
     namespace_ref = args.CONCEPTS.namespace.Parse()
     with serverless_operations.Connect(conn_context) as client:
         self.SetCompleteApiEndpoint(conn_context.endpoint)
         return commands.SortByName(client.ListRoutes(namespace_ref))
Beispiel #2
0
 def Run(self, args):
   """List available routes."""
   if args.uri:
     raise flags.ArgumentError('--uri flag is not supported for this resource')
   conn_context = connection_context.GetConnectionContext(args)
   namespace_ref = args.CONCEPTS.namespace.Parse()
   with serverless_operations.Connect(conn_context) as client:
     return client.ListRoutes(namespace_ref)
Beispiel #3
0
 def Run(self, args):
   """List available revisions."""
   service_name = args.service
   conn_context = connection_context.GetConnectionContext(args)
   namespace_ref = args.CONCEPTS.namespace.Parse()
   with serverless_operations.Connect(conn_context) as client:
     self.SetCompleteApiEndpoint(conn_context.endpoint)
     return client.ListRevisions(namespace_ref, service_name)
Beispiel #4
0
 def Run(self, args):
   """List available domain mappings."""
   conn_context = connection_context.GetConnectionContext(
       args, product=connection_context.Product.RUN)
   namespace_ref = args.CONCEPTS.namespace.Parse()
   with serverless_operations.Connect(conn_context) as client:
     self.SetCompleteApiEndpoint(conn_context.endpoint)
     return commands.SortByName(client.ListDomainMappings(namespace_ref))
Beispiel #5
0
def _SetInvokerPermissions(args, function, is_new_function):
    """Add the IAM binding for the invoker role on the Cloud Run service, if applicable.

  Args:
    args: argparse.Namespace, arguments that this command was invoked with
    function: cloudfunctions_v2alpha_messages.Function, recently created or
      updated GCF function
    is_new_function: bool, true if the function is being created

  Returns:
    None
  """
    service_ref_one_platform = resources.REGISTRY.ParseRelativeName(
        function.serviceConfig.service,
        _CLOUD_RUN_SERVICE_COLLECTION_ONE_PLATFORM)

    # This condition will be truthy if the user provided either
    # `--allow-unauthenticated` or `--no-allow-unauthenticated`. In other
    # words, it is only falsey when neither of those two flags is provided.
    if args.IsSpecified('allow_unauthenticated'):
        allow_unauthenticated = args.allow_unauthenticated
    else:
        if is_new_function:
            allow_unauthenticated = console_io.PromptContinue(prompt_string=(
                'Allow unauthenticated invocations of new function [{}]?'.
                format(args.NAME)),
                                                              default=False)
        else:
            # The function already exists, and the user didn't request any change to
            # the permissions. There is nothing to do in this case.
            return

    run_connection_context = connection_context.RegionalConnectionContext(
        service_ref_one_platform.locationsId,
        global_methods.SERVERLESS_API_NAME,
        global_methods.SERVERLESS_API_VERSION)

    with serverless_operations.Connect(run_connection_context) as operations:
        service_ref_k8s = resources.REGISTRY.ParseRelativeName(
            'namespaces/{}/services/{}'.format(
                properties.VALUES.core.project.GetOrFail(),
                service_ref_one_platform.Name()),
            _CLOUD_RUN_SERVICE_COLLECTION_K8S)

        if allow_unauthenticated:
            operations.AddOrRemoveIamPolicyBinding(
                service_ref_k8s,
                add_binding=True,
                member=serverless_operations.
                ALLOW_UNAUTH_POLICY_BINDING_MEMBER,
                role=serverless_operations.ALLOW_UNAUTH_POLICY_BINDING_ROLE)
        elif not is_new_function:
            operations.AddOrRemoveIamPolicyBinding(
                service_ref_k8s,
                add_binding=False,
                member=serverless_operations.
                ALLOW_UNAUTH_POLICY_BINDING_MEMBER,
                role=serverless_operations.ALLOW_UNAUTH_POLICY_BINDING_ROLE)
Beispiel #6
0
    def Run(self, args):
        """Update configuration information about the service.

    Does not change the running code.

    Args:
      args: Args!
    """
        changes = flags.GetConfigurationChanges(args)
        if not changes:
            raise exceptions.NoConfigurationChangeError(
                'No configuration change requested. '
                'Did you mean to include the flags `--update-env-vars`, '
                '`--memory`, `--concurrency`, `--timeout`, `--connectivity`?')

        conn_context = connection_context.GetConnectionContext(
            args, product=connection_context.Product.RUN)
        service_ref = flags.GetService(args)

        with serverless_operations.Connect(conn_context) as client:
            service = client.GetService(service_ref)
            has_latest = (service is None
                          or traffic.LATEST_REVISION_KEY in service.traffic)
            deployment_stages = stages.ServiceStages(
                include_iam_policy_set=False, include_route=has_latest)
            with progress_tracker.StagedProgressTracker(
                    'Deploying...',
                    deployment_stages,
                    failure_message='Deployment failed',
                    suppress_output=args.async_) as tracker:
                client.ReleaseService(service_ref,
                                      changes,
                                      tracker,
                                      asyn=args.async_,
                                      prefetch=service)
            if args.async_:
                pretty_print.Success('Deploying asynchronously.')
            else:
                service = client.GetService(service_ref)
                latest_ready = service.status.latestReadyRevisionName
                latest_percent_traffic = sum(
                    target.percent for target in service.status.traffic
                    if target.latestRevision or (
                        latest_ready and target.revisionName == latest_ready))
                msg = (
                    'Service [{{bold}}{serv}{{reset}}] '
                    'revision [{{bold}}{rev}{{reset}}] '
                    'has been deployed and is serving '
                    '{{bold}}{latest_percent_traffic}{{reset}} percent of traffic'
                )
                if latest_percent_traffic:
                    msg += (' at {{bold}}{url}{{reset}}')
                msg = msg.format(serv=service_ref.servicesId,
                                 rev=latest_ready,
                                 url=service.domain
                                 if 'domain' in dir(service) else service.url,
                                 latest_percent_traffic=latest_percent_traffic)
                pretty_print.Success(msg)
Beispiel #7
0
    def Run(self, args):
        """Create a domain mapping."""
        # domains.cloudrun.com api group only supports v1alpha1 on clusters.
        conn_context = connection_context.GetConnectionContext(
            args,
            flags.Product.RUN,
            self.ReleaseTrack(),
            version_override=('v1alpha1' if platforms.GetPlatform() !=
                              platforms.PLATFORM_MANAGED else None))
        domain_mapping_ref = args.CONCEPTS.domain.Parse()
        changes = [
            config_changes.SetLaunchStageAnnotationChange(self.ReleaseTrack())
        ]

        # Check if the provided domain has already been verified
        # if mapping to a non-CRoGKE service
        if platforms.GetPlatform() == platforms.PLATFORM_MANAGED:
            client = global_methods.GetServerlessClientInstance()
            all_domains = global_methods.ListVerifiedDomains(client)
            # If not already verified, explain and error out
            if all(d.id not in domain_mapping_ref.Name() for d in all_domains):
                if not all_domains:
                    domains_text = 'You currently have no verified domains.'
                else:
                    domains = ['* {}'.format(d.id) for d in all_domains]
                    domains_text = ('Currently verified domains:\n{}'.format(
                        '\n'.join(domains)))
                raise exceptions.DomainMappingCreationError(
                    'The provided domain does not appear to be verified '
                    'for the current account so a domain mapping '
                    'cannot be created. Visit [{help}] for more information.'
                    '\n{domains}'.format(help=DOMAIN_MAPPINGS_HELP_DOCS_URL,
                                         domains=domains_text))

        with serverless_operations.Connect(conn_context) as client:
            try:
                mapping = client.CreateDomainMapping(domain_mapping_ref,
                                                     args.service, changes,
                                                     args.force_override)
            except exceptions.DomainMappingAlreadyExistsError as e:
                if console_io.CanPrompt() and console_io.PromptContinue(
                    ('This domain is already being used as a mapping elsewhere. '
                     'The existing mapping can be overriden by passing '
                     '`--force-override` or by continuing at the prompt below.'
                     ),
                        prompt_string='Override the existing mapping'):
                    deletion.Delete(domain_mapping_ref,
                                    client.GetDomainMapping,
                                    client.DeleteDomainMapping,
                                    async_=False)
                    mapping = client.CreateDomainMapping(
                        domain_mapping_ref, args.service, changes, True)
                else:
                    raise e

            for record in mapping.records:
                record.name = record.name or mapping.route_name
            return mapping.records
Beispiel #8
0
 def Run(self, args):
   """Create a domain mapping."""
   conn_context = connection_context.GetConnectionContext(args)
   domain_mapping_ref = args.CONCEPTS.domain.Parse()
   with serverless_operations.Connect(conn_context) as client:
     client.CreateDomainMapping(domain_mapping_ref, args.service)
     msg = """{domain} now maps to service [{serv}]""".format(
         domain=domain_mapping_ref.domainmappingsId, serv=args.service)
     pretty_print.Success(msg)
    def Run(self, args):
        """Update the traffic split for the service.

    Args:
      args: Args!

    Returns:
      List of traffic.TrafficTargetStatus instances reflecting the change.
    """
        conn_context = connection_context.GetConnectionContext(
            args, flags.Product.RUN, self.ReleaseTrack())
        service_ref = args.CONCEPTS.service.Parse()
        flags.ValidateResource(service_ref)

        changes = flags.GetConfigurationChanges(args)
        if not changes:
            raise exceptions.NoConfigurationChangeError(
                'No traffic configuration change requested.')
        changes.insert(
            0,
            config_changes.DeleteAnnotationChange(
                k8s_object.BINAUTHZ_BREAKGLASS_ANNOTATION))
        changes.append(
            config_changes.SetLaunchStageAnnotationChange(self.ReleaseTrack()))

        is_managed = platforms.GetPlatform() == platforms.PLATFORM_MANAGED
        with serverless_operations.Connect(conn_context) as client:
            deployment_stages = stages.UpdateTrafficStages()
            try:
                with progress_tracker.StagedProgressTracker(
                        'Updating traffic...',
                        deployment_stages,
                        failure_message='Updating traffic failed',
                        suppress_output=args.async_) as tracker:
                    client.UpdateTraffic(service_ref, changes, tracker,
                                         args.async_)
            except:
                serv = client.GetService(service_ref)
                if serv:
                    resources = traffic_pair.GetTrafficTargetPairs(
                        serv.spec_traffic, serv.status_traffic, is_managed,
                        serv.status.latestReadyRevisionName, serv.status.url)
                    display.Displayer(
                        self,
                        args,
                        resources,
                        display_info=args.GetDisplayInfo()).Display()
                raise

        if args.async_:
            pretty_print.Success('Updating traffic asynchronously.')
        else:
            serv = client.GetService(service_ref)
            resources = traffic_pair.GetTrafficTargetPairs(
                serv.spec_traffic, serv.status_traffic, is_managed,
                serv.status.latestReadyRevisionName, serv.status.url)
            return resources
Beispiel #10
0
    def Run(self, args):
        """Update the traffic split for the service.

    Args:
      args: Args!

    Returns:
      List of traffic.TrafficTargetStatus instances reflecting the change.
    """
        # TODO(b/143898356) Begin code that should be in Args
        resource_printer.RegisterFormatter(
            traffic_printer.TRAFFIC_PRINTER_FORMAT,
            traffic_printer.TrafficPrinter)
        args.GetDisplayInfo().AddFormat('traffic')
        # End code that should be in Args

        conn_context = connection_context.GetConnectionContext(
            args, flags.Product.RUN, self.ReleaseTrack())
        service_ref = flags.GetService(args)

        changes = flags.GetConfigurationChanges(args)
        if not changes:
            raise exceptions.NoConfigurationChangeError(
                'No traffic configuration change requested.')

        is_managed = flags.GetPlatform() == flags.PLATFORM_MANAGED
        with serverless_operations.Connect(conn_context) as client:
            deployment_stages = stages.UpdateTrafficStages()
            try:
                with progress_tracker.StagedProgressTracker(
                        'Updating traffic...',
                        deployment_stages,
                        failure_message='Updating traffic failed',
                        suppress_output=args.async_) as tracker:
                    client.UpdateTraffic(service_ref, changes, tracker,
                                         args.async_)
            except:
                serv = client.GetService(service_ref)
                if serv:
                    resources = traffic_pair.GetTrafficTargetPairs(
                        serv.spec_traffic, serv.status_traffic, is_managed,
                        serv.status.latestReadyRevisionName, serv.status.url)
                    display.Displayer(
                        self,
                        args,
                        resources,
                        display_info=args.GetDisplayInfo()).Display()
                raise

        if args.async_:
            pretty_print.Success('Updating traffic asynchronously.')
        else:
            serv = client.GetService(service_ref)
            resources = traffic_pair.GetTrafficTargetPairs(
                serv.spec_traffic, serv.status_traffic, is_managed,
                serv.status.latestReadyRevisionName, serv.status.url)
            return resources
Beispiel #11
0
 def Run(self, args):
   """Delete domain mappings."""
   conn_context = connection_context.GetConnectionContext(args)
   domain_mapping_ref = args.CONCEPTS.domain.Parse()
   with serverless_operations.Connect(conn_context) as client:
     client.DeleteDomainMapping(domain_mapping_ref)
     msg = """Mappings to [{domain}] now have been deleted.""".format(
         domain=domain_mapping_ref.domainmappingsId)
     pretty_print.Success(msg)
Beispiel #12
0
    def Run(self, args):
        """Update configuration information about the service.

    Does not change the running code.

    Args:
      args: Args!
    """
        changes = flags.GetConfigurationChanges(args)
        if not changes:
            raise exceptions.NoConfigurationChangeError(
                'No configuration change requested. '
                'Did you mean to include the flags `--update-env-vars`, '
                '`--memory`, `--concurrency`, `--timeout`, `--connectivity`?')

        conn_context = connection_context.GetConnectionContext(
            args, product=connection_context.Product.RUN)
        service_ref = flags.GetService(args)

        with serverless_operations.Connect(conn_context) as client:
            service = client.GetService(service_ref)
            has_latest = (service is None
                          or traffic.LATEST_REVISION_KEY in service.traffic)
            deployment_stages = stages.ServiceStages(
                include_iam_policy_set=False, include_route=has_latest)
            with progress_tracker.StagedProgressTracker(
                    'Deploying...',
                    deployment_stages,
                    failure_message='Deployment failed',
                    suppress_output=args.async_) as tracker:
                client.ReleaseService(service_ref,
                                      changes,
                                      tracker,
                                      asyn=args.async_,
                                      prefetch=service)
            if args.async_:
                pretty_print.Success('Deploying asynchronously.')
            else:
                service = client.GetService(service_ref)
                active_revs = client.GetActiveRevisions(service_ref)

                msg = (
                    'Service [{{bold}}{serv}{{reset}}] revision{plural} {rev_msg} '
                    'is active and serving traffic at {{bold}}{url}{{reset}}')

                rev_msg = ' '.join([
                    '[{{bold}}{}{{reset}}]'.format(rev) for rev in active_revs
                ])

                msg = msg.format(serv=service_ref.servicesId,
                                 plural='s' if len(active_revs) > 1 else '',
                                 rev_msg=rev_msg,
                                 url=service.domain
                                 if 'domain' in dir(service) else service.url)

                pretty_print.Success(msg)
Beispiel #13
0
 def Run(self, args):
   """List executions of a job."""
   job_name = args.job
   namespace_ref = args.CONCEPTS.namespace.Parse()
   conn_context = connection_context.GetConnectionContext(
       args, flags.Product.RUN, self.ReleaseTrack())
   with serverless_operations.Connect(conn_context) as client:
     self.SetCompleteApiEndpoint(conn_context.endpoint)
     return self._SortExecutions(
         client.ListExecutions(namespace_ref, job_name))
Beispiel #14
0
 def Run(self, args):
     """Obtain details about a given route."""
     conn_context = connection_context.GetConnectionContext(args)
     route_ref = args.CONCEPTS.route.Parse()
     with serverless_operations.Connect(conn_context) as client:
         conf = client.GetRoute(route_ref)
     if not conf:
         raise flags.ArgumentError('Cannot find route [{}]'.format(
             route_ref.routesId))
     return conf
Beispiel #15
0
 def Run(self, args):
     """Obtain details about a given service."""
     conn_context = connection_context.GetConnectionContext(args)
     service_ref = flags.GetService(args)
     with serverless_operations.Connect(conn_context) as client:
         serv = client.GetService(service_ref)
     if not serv:
         raise flags.ArgumentError('Cannot find service [{}]'.format(
             service_ref.servicesId))
     return serv
Beispiel #16
0
    def Run(self, args):
        """Update configuration information about the service.

    Does not change the running code.

    Args:
      args: Args!
    """
        changes = flags.GetConfigurationChanges(args)
        endpoint_visibility = flags.GetEndpointVisibility(args)
        allow_unauth = flags.GetAllowUnauthenticated(args)
        if not changes and endpoint_visibility is None and allow_unauth is None:
            raise exceptions.NoConfigurationChangeError(
                'No configuration change requested. '
                'Did you mean to include the flags `--update-env-vars`, '
                '`--memory`, `--concurrency`, `--timeout`, `--connectivity`, '
                'or `--allow-unauthenticated`?')

        conn_context = connection_context.GetConnectionContext(args)
        service_ref = flags.GetService(args)

        with serverless_operations.Connect(conn_context) as client:
            deployment_stages = stages.ServiceStages(allow_unauth is not None)
            with progress_tracker.StagedProgressTracker(
                    'Deploying...',
                    deployment_stages,
                    failure_message='Deployment failed',
                    suppress_output=args. async) as tracker:
                client.ReleaseService(service_ref,
                                      changes,
                                      tracker,
                                      asyn=args. async,
                                      private_endpoint=endpoint_visibility,
                                      allow_unauthenticated=allow_unauth)
            if args. async:
                pretty_print.Success('Deploying asynchronously.')
            else:
                url = client.GetServiceUrl(service_ref)
                active_revs = client.GetActiveRevisions(service_ref)

                msg = (
                    'Service [{{bold}}{serv}{{reset}}] revision{plural} {rev_msg} '
                    'is active and serving traffic at {{bold}}{url}{{reset}}')

                rev_msg = ' '.join([
                    '[{{bold}}{}{{reset}}]'.format(rev) for rev in active_revs
                ])

                msg = msg.format(serv=service_ref.servicesId,
                                 plural='s' if len(active_revs) > 1 else '',
                                 rev_msg=rev_msg,
                                 url=url)

                pretty_print.Success(msg)
Beispiel #17
0
 def Run(self, args):
     """Obtain details about a given configuration."""
     conn_context = connection_context.GetConnectionContext(
         args, product=connection_context.Product.RUN)
     configuration_ref = args.CONCEPTS.configuration.Parse()
     with serverless_operations.Connect(conn_context) as client:
         conf = client.GetConfiguration(configuration_ref)
     if not conf:
         raise flags.ArgumentError('Cannot find configuration [{}]'.format(
             configuration_ref.configurationsId))
     return conf
Beispiel #18
0
 def Run(self, args):
   """Describe a domain mapping."""
   conn_context = connection_context.GetConnectionContext(args)
   domain_mapping_ref = args.CONCEPTS.domain.Parse()
   with serverless_operations.Connect(conn_context) as client:
     domain_mapping = client.GetDomainMapping(domain_mapping_ref)
     if not domain_mapping:
       raise flags.ArgumentError(
           'Cannot find domain mapping for domain name [{}]'.format(
               domain_mapping_ref.domainmappingsId))
     return domain_mapping
Beispiel #19
0
    def Run(self, args):
        """Update the service resource.

       Different from `deploy` in that it can only update the service spec but
       no IAM or Cloud build changes.

    Args:
      args: Args!
    Returns:
      googlecloudsdk.api_lib.run.Service, the updated service
    """
        changes = flags.GetConfigurationChanges(args)
        if not changes:
            raise exceptions.NoConfigurationChangeError(
                'No configuration change requested. '
                'Did you mean to include the flags `--update-env-vars`, '
                '`--memory`, `--concurrency`, `--timeout`, `--connectivity`, '
                '`--image`?')
        changes.append(
            config_changes.SetLaunchStageAnnotationChange(self.ReleaseTrack()))

        conn_context = connection_context.GetConnectionContext(
            args, flags.Product.RUN, self.ReleaseTrack())
        service_ref = flags.GetService(args)

        with serverless_operations.Connect(conn_context) as client:
            service = client.GetService(service_ref)
            resource_change_validators.ValidateClearVpcConnector(service, args)
            has_latest = (service is None or traffic.LATEST_REVISION_KEY
                          in service.spec_traffic)
            deployment_stages = stages.ServiceStages(
                include_iam_policy_set=False, include_route=has_latest)
            with progress_tracker.StagedProgressTracker(
                    'Deploying...',
                    deployment_stages,
                    failure_message='Deployment failed',
                    suppress_output=args.async_) as tracker:
                service = client.ReleaseService(service_ref,
                                                changes,
                                                tracker,
                                                asyn=args.async_,
                                                prefetch=service)

            if args.async_:
                pretty_print.Success(
                    'Service [{{bold}}{serv}{{reset}}] is deploying '
                    'asynchronously.'.format(serv=service.name))
            else:
                service = client.GetService(service_ref)
                pretty_print.Success(
                    messages_util.GetSuccessMessageForSynchronousDeploy(
                        service))
            return service
Beispiel #20
0
    def Run(self, args):
        """Show details about a revision."""
        conn_context = connection_context.GetConnectionContext(args)
        revision_ref = args.CONCEPTS.revision.Parse()

        with serverless_operations.Connect(conn_context) as client:
            wrapped_revision = client.GetRevision(revision_ref)

        if not wrapped_revision:
            raise flags.ArgumentError('Cannot find revision [{}]'.format(
                revision_ref.revisionsId))
        return wrapped_revision
Beispiel #21
0
    def Run(self, args):
        """List tasks of a job execution."""
        execution_ref = args.CONCEPTS.execution.Parse()

        conn_context = connection_context.GetConnectionContext(
            args, flags.Product.RUN, self.ReleaseTrack())
        with serverless_operations.Connect(conn_context) as client:
            self.SetCompleteApiEndpoint(conn_context.endpoint)
            ret = client.ListTasks(execution_ref.Parent(),
                                   execution_ref.Name(), args.filter_flags
                                   or None)
            return sorted(ret, key=lambda x: x.index)
Beispiel #22
0
 def Run(self, args):
     """Obtain details about a given service."""
     conn_context = connection_context.GetConnectionContext(
         args, flags.Product.RUN, self.ReleaseTrack())
     service_ref = args.CONCEPTS.service.Parse()
     flags.ValidateResource(service_ref)
     with serverless_operations.Connect(conn_context) as client:
         serv = client.GetService(service_ref)
     if not serv:
         raise exceptions.ArgumentError('Cannot find service [{}]'.format(
             service_ref.servicesId))
     return serv
Beispiel #23
0
    def Run(self, args):
        """Update the traffic split for the service.

    Args:
      args: Args!

    Returns:
      List of traffic.TrafficTargetStatus instances reflecting the change.
    """
        conn_context = connection_context.GetConnectionContext(args)
        service_ref = flags.GetService(args)

        if conn_context.supports_one_platform:
            flags.VerifyOnePlatformFlags(args)
        else:
            flags.VerifyGKEFlags(args)

        changes = flags.GetConfigurationChanges(args)
        if not changes:
            raise exceptions.NoConfigurationChangeError(
                'No traffic configuration change requested.')

        self._SetFormat(args)

        with serverless_operations.Connect(conn_context) as client:
            deployment_stages = stages.UpdateTrafficStages()
            try:
                with progress_tracker.StagedProgressTracker(
                        'Updating traffic...',
                        deployment_stages,
                        failure_message='Updating traffic failed',
                        suppress_output=args.async_) as tracker:
                    client.UpdateTraffic(service_ref, changes, tracker,
                                         args.async_)
            except:
                serv = client.GetService(service_ref)
                resources = traffic.GetTrafficTargetPairs(
                    serv.spec.traffic, serv.status.traffic,
                    flags.IsManaged(args), serv.status.latestReadyRevisionName)
                display.Displayer(
                    self, args, resources,
                    display_info=args.GetDisplayInfo()).Display()
                raise

        if args.async_:
            pretty_print.Success('Updating traffic asynchronously.')
        else:
            serv = client.GetService(service_ref)
            resources = traffic.GetTrafficTargetPairs(
                serv.spec.traffic, serv.status.traffic, flags.IsManaged(args),
                serv.status.latestReadyRevisionName)
            return resources
Beispiel #24
0
    def Run(self, args):
        """Delete a service."""
        conn_context = connection_context.GetConnectionContext(args)
        service_ref = flags.GetService(args)
        console_io.PromptContinue(
            message='Service [{service}] will be deleted.'.format(
                service=service_ref.servicesId),
            throw_if_unattended=True,
            cancel_on_no=True)

        with serverless_operations.Connect(conn_context) as client:
            client.DeleteService(service_ref)
        log.DeletedResource(service_ref.servicesId, 'service')
Beispiel #25
0
 def Run(self, args):
     """List available services."""
     if args.uri:
         raise flags.ArgumentError(
             '--uri flag is not supported for this resource')
     if not flags.IsGKE(args) and not getattr(args, 'region', None):
         locations_ref = args.CONCEPTS.region.Parse()
         return global_methods.ListServices(locations_ref.RelativeName())
     else:
         conn_context = connection_context.GetConnectionContext(args)
         namespace_ref = args.CONCEPTS.namespace.Parse()
         with serverless_operations.Connect(conn_context) as client:
             return client.ListServices(namespace_ref)
Beispiel #26
0
    def Run(self, args):
        """Deploy an app, function or container to Cloud Run."""
        source_ref = flags.GetSourceRef(args.source, args.image)
        config_changes = flags.GetConfigurationChanges(args)

        conn_context = connection_context.GetConnectionContext(args)
        service_ref = flags.GetService(args)
        function_entrypoint = flags.GetFunction(args.function)
        msg = ('Deploying {dep_type} to service [{{bold}}{{service}}{{reset}}]'
               ' in {ns_label} [{{bold}}{{ns}}{{reset}}]')

        msg += conn_context.location_label

        if function_entrypoint:
            pretty_print.Info(msg.format(
                ns_label=conn_context.ns_label,
                dep_type='function [{bold}{function}{reset}]'),
                              function=function_entrypoint,
                              service=service_ref.servicesId,
                              ns=service_ref.namespacesId)
        elif source_ref.source_type is source_ref.SourceType.IMAGE:
            pretty_print.Info(msg.format(ns_label=conn_context.ns_label,
                                         dep_type='container'),
                              service=service_ref.servicesId,
                              ns=service_ref.namespacesId)
        else:
            pretty_print.Info(msg.format(ns_label=conn_context.ns_label,
                                         dep_type='app'),
                              service=service_ref.servicesId,
                              ns=service_ref.namespacesId)

        with serverless_operations.Connect(conn_context) as operations:
            if not (source_ref.source_type is source_ref.SourceType.IMAGE
                    or operations.IsSourceBranch()):
                raise exceptions.SourceNotSupportedError()
            new_deployable = operations.Detect(service_ref.Parent(),
                                               source_ref, function_entrypoint)
            operations.Upload(new_deployable)
            changes = [new_deployable]
            if config_changes:
                changes.extend(config_changes)
            operations.ReleaseService(service_ref, changes, asyn=args. async)
            url = operations.GetServiceUrl(service_ref)
            conf = operations.GetConfiguration(service_ref)

        msg = ('{{bold}}Service [{serv}] revision [{rev}] has been deployed'
               ' and is serving traffic at{{reset}} {url}')
        msg = msg.format(serv=service_ref.servicesId,
                         rev=conf.status.latestReadyRevisionName,
                         url=url)
        pretty_print.Success(msg)
Beispiel #27
0
    def Run(self, args):
        """Delete a revision."""
        conn_context = connection_context.GetConnectionContext(args)
        revision_ref = args.CONCEPTS.revision.Parse()

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

        with serverless_operations.Connect(conn_context) as client:
            client.DeleteRevision(revision_ref)
        log.DeletedResource(revision_ref.revisionsId, 'revision')
Beispiel #28
0
 def Run(self, args):
     """List available domain mappings."""
     # domains.cloudrun.com api group only supports v1alpha1 on clusters.
     conn_context = connection_context.GetConnectionContext(
         args,
         flags.Product.RUN,
         self.ReleaseTrack(),
         version_override=('v1alpha1' if platforms.GetPlatform() !=
                           platforms.PLATFORM_MANAGED else None))
     namespace_ref = args.CONCEPTS.namespace.Parse()
     with serverless_operations.Connect(conn_context) as client:
         self.SetCompleteApiEndpoint(conn_context.endpoint)
         return commands.SortByName(
             client.ListDomainMappings(namespace_ref))
Beispiel #29
0
 def Run(self, args):
     """List available revisions."""
     service_name = args.service
     conn_context = connection_context.GetConnectionContext(args)
     namespace_ref = args.CONCEPTS.namespace.Parse()
     with serverless_operations.Connect(conn_context) as client:
         self.SetCompleteApiEndpoint(conn_context.endpoint)
         if not flags.IsManaged(args):
             location_msg = ' in [{}]'.format(conn_context.cluster_location)
             log.status.Print('For cluster [{cluster}]{zone}:'.format(
                 cluster=conn_context.cluster_name,
                 zone=location_msg
                 if conn_context.cluster_location else ''))
         return client.ListRevisions(namespace_ref, service_name)
Beispiel #30
0
  def Run(self, args):
    """Delete an execution."""
    conn_context = connection_context.GetConnectionContext(
        args, flags.Product.RUN, self.ReleaseTrack())
    ex_ref = args.CONCEPTS.execution.Parse()

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

    with serverless_operations.Connect(conn_context) as client:
      client.DeleteExecution(ex_ref)
    log.DeletedResource(ex_ref.executionsId, 'execution')