Example #1
0
    def Run(self, args):
        """Update environment variables."""
        conn_context = connection_context.GetConnectionContext(args)
        service_ref = flags.GetService(args)

        with serverless_operations.Connect(conn_context) as client:
            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, or --concurrency?')
            client.ReleaseService(service_ref, changes, args. async)
            url = client.GetServiceUrl(service_ref)
            active_revs = client.GetActiveRevisions(service_ref)

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

        rev_msg = ' '.join(['[{}]'.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)
Example #2
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
Example #3
0
    def Run(self, args):
        """Update configuration information about the service.

    Does not change the running code.

    Args:
      args: Args!
    """
        conn_context = connection_context.GetConnectionContext(args)
        service_ref = flags.GetService(args)

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

        with serverless_operations.Connect(conn_context) as client:
            changes = flags.GetConfigurationChanges(args)
            endpoint_visibility = flags.GetEndpointVisibility(args)
            allow_unauth = None
            if conn_context.supports_one_platform:
                allow_unauth = flags.GetAllowUnauthenticated(
                    args, client, service_ref)
            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`?')
            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 = (
                    '{{bold}}Service [{serv}] revision{plural} {rev_msg} is active'
                    ' and serving traffic at{{reset}} {url}')

                rev_msg = ' '.join(['[{}]'.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)
Example #4
0
  def Run(self, args):
    """Deploy a container to Cloud Run."""
    service_ref = flags.GetService(args)
    image = args.image
    # Build an image from source if source specified.
    if flags.FlagIsExplicitlySet(args, 'source'):
      # Create a tag for the image creation
      if image is None and not args.IsSpecified('config'):
        image = 'gcr.io/{projectID}/cloud-run-source-deploy/{service}:{tag}'.format(
            projectID=properties.VALUES.core.project.Get(required=True),
            service=service_ref.servicesId,
            tag=uuid.uuid4().hex)
      messages = cloudbuild_util.GetMessagesModule()
      build_config = submit_util.CreateBuildConfig(
          image, args.no_cache, messages, args.substitutions, args.config,
          args.IsSpecified('source'), False, args.source,
          args.gcs_source_staging_dir, args.ignore_file, args.gcs_log_dir,
          args.machine_type, args.disk_size)
      submit_util.Build(messages, args.async_, build_config)

    # Deploy a container with an image
    conn_context = connection_context.GetConnectionContext(
        args, flags.Product.RUN, self.ReleaseTrack())
    config_changes = flags.GetConfigurationChanges(args)

    with serverless_operations.Connect(conn_context) as operations:
      image_change = config_changes_mod.ImageChange(image)
      changes = [image_change]
      if config_changes:
        changes.extend(config_changes)
      service = operations.GetService(service_ref)
      allow_unauth = GetAllowUnauth(args, operations, service_ref, service)

      pretty_print.Info(GetStartDeployMessage(conn_context, service_ref))
      has_latest = (service is None or
                    traffic.LATEST_REVISION_KEY in service.spec_traffic)
      deployment_stages = stages.ServiceStages(
          include_iam_policy_set=allow_unauth is not None,
          include_route=has_latest)
      header = 'Deploying...' if service else 'Deploying new service...'
      with progress_tracker.StagedProgressTracker(
          header,
          deployment_stages,
          failure_message='Deployment failed',
          suppress_output=args.async_) as tracker:
        operations.ReleaseService(
            service_ref,
            changes,
            tracker,
            asyn=args.async_,
            allow_unauthenticated=allow_unauth,
            prefetch=service)
      if args.async_:
        pretty_print.Success(
            'Service [{{bold}}{serv}{{reset}}] is deploying '
            'asynchronously.'.format(serv=service_ref.servicesId))
      else:
        pretty_print.Success(GetSuccessMessageForSynchronousDeploy(
            operations, service_ref))
Example #5
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)
Example #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)
                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)
Example #7
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
Example #8
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
Example #9
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
Example #10
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')
Example #11
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)
 def Run(self, args):
     """Obtain details about a given service."""
     # TODO(b/143898356) Begin code that should be in Args
     resource_printer.RegisterFormatter(
         service_printer.SERVICE_PRINTER_FORMAT,
         service_printer.ServicePrinter)
     args.GetDisplayInfo().AddFormat('service')
     # End code that should be in Args
     conn_context = connection_context.GetConnectionContext(
         args, flags.Product.RUN, self.ReleaseTrack())
     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
Example #13
0
    def Run(self, args):
        """Deploy a container to Cloud Run."""
        image = args.image

        conn_context = connection_context.GetConnectionContext(
            args, product=connection_context.Product.RUN)
        config_changes = flags.GetConfigurationChanges(args)

        service_ref = flags.GetService(args)

        with serverless_operations.Connect(conn_context) as operations:
            image_change = config_changes_mod.ImageChange(image)
            changes = [image_change]
            if config_changes:
                changes.extend(config_changes)
            service = operations.GetService(service_ref)
            allow_unauth = GetAllowUnauth(args, operations, service_ref,
                                          service)

            pretty_print.Info(GetStartDeployMessage(conn_context, service_ref))
            has_latest = (service is None
                          or traffic.LATEST_REVISION_KEY in service.traffic)
            deployment_stages = stages.ServiceStages(
                include_iam_policy_set=allow_unauth is not None,
                include_route=has_latest)
            header = 'Deploying...' if service else 'Deploying new service...'
            with progress_tracker.StagedProgressTracker(
                    header,
                    deployment_stages,
                    failure_message='Deployment failed',
                    suppress_output=args.async_) as tracker:
                operations.ReleaseService(service_ref,
                                          changes,
                                          tracker,
                                          asyn=args.async_,
                                          allow_unauthenticated=allow_unauth,
                                          prefetch=service)
            if args.async_:
                pretty_print.Success(
                    'Service [{{bold}}{serv}{{reset}}] is deploying '
                    'asynchronously.'.format(serv=service_ref.servicesId))
            else:
                pretty_print.Success(
                    GetSuccessMessageForSynchronousDeploy(
                        operations, service_ref))
Example #14
0
    def Run(self, args):
        """Update configuration information about the service.

    Does not change the running code.

    Args:
      args: Args!
    """
        conn_context = connection_context.GetConnectionContext(args)
        service_ref = flags.GetService(args)

        with serverless_operations.Connect(conn_context) as client:
            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`, or `--timeout`?')
            deployment_stages = stages.ServiceStages()
            with progress_tracker.StagedProgressTracker(
                    'Deploying...',
                    deployment_stages,
                    failure_message='Deployment failed',
                    suppress_output=args. async) as tracker:
                client.ReleaseService(service_ref, changes, tracker,
                                      args. async)
            if args. async:
                pretty_print.Success('Deploying asynchronously.')
            else:
                url = client.GetServiceUrl(service_ref)
                active_revs = client.GetActiveRevisions(service_ref)

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

                rev_msg = ' '.join(['[{}]'.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)
Example #15
0
    def Run(self, args):
        """Update the traffic split for the service.

    Args:
      args: Args!
    """
        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.')

        with serverless_operations.Connect(conn_context) as client:
            deployment_stages = stages.SetTrafficStages()
            with progress_tracker.StagedProgressTracker(
                    'Setting traffic...',
                    deployment_stages,
                    failure_message='Setting traffic failed',
                    suppress_output=args. async) as tracker:
                client.SetTraffic(service_ref, changes, tracker, args. async,
                                  flags.IsManaged(args))
                if args. async:
                    pretty_print.Success('Setting traffic asynchronously.')
                else:
                    serv = client.GetService(service_ref)
                    splits = [
                        '{{bold}}{rev}{{reset}}={percent}'.format(
                            rev='latest'
                            if target.latestRevision else target.revisionName,
                            percent=target.percent)
                        for target in serv.spec.traffic
                    ]
                    msg = 'Traffic set to %s.' % ', '.join(splits)

            pretty_print.Success(msg)
Example #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)
        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, flags.Product.RUN, self.ReleaseTrack())
        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.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:
                client.ReleaseService(service_ref,
                                      changes,
                                      tracker,
                                      asyn=args.async_,
                                      prefetch=service)
            if args.async_:
                pretty_print.Success('Deploying asynchronously.')
            else:
                pretty_print.Success(
                    messages_util.GetSuccessMessageForSynchronousDeploy(
                        client, service_ref))
Example #17
0
    def Run(self, args):
        """Deploy a container to Cloud Run."""
        image = args.image

        conn_context = connection_context.GetConnectionContext(
            args, self.ReleaseTrack())
        config_changes = flags.GetConfigurationChanges(args)

        service_ref = flags.GetService(args)

        with serverless_operations.Connect(conn_context) as operations:
            image_change = config_changes_mod.ImageChange(image)
            changes = [image_change]
            if config_changes:
                changes.extend(config_changes)
            exists = operations.GetService(service_ref)
            allow_unauth = GetAllowUnauth(args, operations, service_ref,
                                          exists)

            pretty_print.Info(GetStartDeployMessage(conn_context, service_ref))

            deployment_stages = stages.ServiceStages(allow_unauth is not None)
            header = 'Deploying...' if exists else 'Deploying new service...'
            with progress_tracker.StagedProgressTracker(
                    header,
                    deployment_stages,
                    failure_message='Deployment failed',
                    suppress_output=args.async_) as tracker:
                operations.ReleaseService(service_ref,
                                          changes,
                                          tracker,
                                          asyn=args.async_,
                                          allow_unauthenticated=allow_unauth)
            if args.async_:
                pretty_print.Success(
                    'Service [{{bold}}{serv}{{reset}}] is deploying '
                    'asynchronously.'.format(serv=service_ref.servicesId))
            else:
                pretty_print.Success(
                    GetSuccessMessageForSynchronousDeploy(
                        operations, service_ref))
Example #18
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)

    # pylint: disable=protected-access
    if (not isinstance(conn_context, connection_context._GKEConnectionContext)
        and getattr(args, 'endpoint', None)):
      raise exceptions.ConfigurationError(
          'The `--endpoint=[internal|external]` flag '
          'is only supported with Cloud Run on GKE.')
    # pylint: enable=protected-access

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

    msg += conn_context.location_label

    if function_entrypoint:
      dep_type = 'function [{{bold}}{}{{reset}}]'.format(function_entrypoint)
      pretty_print.Info(msg.format(
          operator=conn_context.operator,
          ns_label=conn_context.ns_label,
          dep_type=dep_type,
          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(
          operator=conn_context.operator,
          ns_label=conn_context.ns_label,
          dep_type='container',
          service=service_ref.servicesId,
          ns=service_ref.namespacesId))
    else:
      pretty_print.Info(msg.format(
          operator=conn_context.operator,
          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)

      if args.endpoint == 'internal':
        private_endpoint = True
      elif args.endpoint == 'external':
        private_endpoint = False
      else:
        private_endpoint = None

      operations.ReleaseService(service_ref, changes, asyn=args.async,
                                private_endpoint=private_endpoint)
      url = operations.GetServiceUrl(service_ref)
      conf = operations.GetConfiguration(service_ref)

    msg = (
        'Service [{{bold}}{serv}{{reset}}] revision [{{bold}}{rev}{{reset}}] '
        'has been deployed and is serving traffic at {{bold}}{url}{{reset}}')
    msg = msg.format(
        serv=service_ref.servicesId,
        rev=conf.status.latestReadyRevisionName,
        url=url)
    pretty_print.Success(msg)
Example #19
0
 def testServiceContainsDash(self):
   args = mock.Mock()
   args.CONCEPTS.service.Parse.return_value = self._ServiceRef('s3rv-ice')
   self.assertEqual(self._ServiceRef('s3rv-ice'), flags.GetService(args))
Example #20
0
 def testServiceOneCharacter(self):
   args = mock.Mock()
   args.CONCEPTS.service.Parse.return_value = self._ServiceRef('a')
   self.assertEqual(self._ServiceRef('a'), flags.GetService(args))
Example #21
0
    def Run(self, args):
        """Deploy a container to Cloud Run."""
        image = args.image

        conn_context = connection_context.GetConnectionContext(args)
        config_changes = flags.GetConfigurationChanges(args)

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

        service_ref = flags.GetService(args)

        with serverless_operations.Connect(conn_context) as operations:
            image_change = config_changes_mod.ImageChange(image)
            changes = [image_change]
            if config_changes:
                changes.extend(config_changes)
            endpoint_visibility = flags.GetEndpointVisibility(args)
            exists = operations.GetService(service_ref)
            allow_unauth = None
            if conn_context.supports_one_platform:
                allow_unauth = flags.GetAllowUnauthenticated(
                    args, operations, service_ref, not exists)
                # Don't try to remove a policy binding from a service that doesn't exist
                if not exists and not allow_unauth:
                    allow_unauth = None

            msg = ('Deploying {dep_type} to {operator} '
                   'service [{{bold}}{service}{{reset}}]'
                   ' in {ns_label} [{{bold}}{ns}{{reset}}]')
            msg += conn_context.location_label

            pretty_print.Info(
                msg.format(operator=conn_context.operator,
                           ns_label=conn_context.ns_label,
                           dep_type='container',
                           service=service_ref.servicesId,
                           ns=service_ref.namespacesId))

            deployment_stages = stages.ServiceStages(allow_unauth is not None)
            header = 'Deploying...' if exists else 'Deploying new service...'
            with progress_tracker.StagedProgressTracker(
                    header,
                    deployment_stages,
                    failure_message='Deployment failed',
                    suppress_output=args. async) as tracker:
                operations.ReleaseService(service_ref,
                                          changes,
                                          tracker,
                                          asyn=args. async,
                                          private_endpoint=endpoint_visibility,
                                          allow_unauthenticated=allow_unauth)
            if args. async:
                pretty_print.Success(
                    'Service [{{bold}}{serv}{{reset}}] is deploying '
                    'asynchronously.'.format(serv=service_ref.servicesId))
            else:
                url = operations.GetServiceUrl(service_ref)
                conf = operations.GetConfiguration(service_ref)
                msg = ('Service [{{bold}}{serv}{{reset}}] '
                       'revision [{{bold}}{rev}{{reset}}] '
                       'has been deployed and is serving traffic at '
                       '{{bold}}{url}{{reset}}')
                msg = msg.format(serv=service_ref.servicesId,
                                 rev=conf.status.latestReadyRevisionName,
                                 url=url)
                pretty_print.Success(msg)
Example #22
0
 def testServiceDigits(self):
   args = mock.Mock()
   args.CONCEPTS.service.Parse.return_value = self._ServiceRef('123abc123')
   self.assertEqual(self._ServiceRef('123abc123'), flags.GetService(args))
Example #23
0
 def testServiceTooLong(self):
   args = mock.Mock()
   args.CONCEPTS.service.Parse.return_value = self._ServiceRef(
       'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
   with self.assertRaises(flags.ArgumentError):
     flags.GetService(args)
Example #24
0
  def Run(self, args):
    """Deploy a container to Cloud Run."""
    image = args.image

    conn_context = connection_context.GetConnectionContext(args)
    config_changes = flags.GetConfigurationChanges(args)

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

    service_ref = flags.GetService(args)

    with serverless_operations.Connect(conn_context) as operations:
      image_change = config_changes_mod.ImageChange(image)
      changes = [image_change]
      if config_changes:
        changes.extend(config_changes)
      if args.connectivity == 'internal':
        private_endpoint = True
      elif args.connectivity == 'external':
        private_endpoint = False
      else:
        private_endpoint = None
      exists = operations.GetService(service_ref)

      if (not exists and not args.allow_unauthenticated and
          conn_context.supports_one_platform):

        if operations.CanAddIamPolicyBinding(service_ref):
          allow_unauth = console_io.PromptContinue(
              prompt_string=(
                  'Allow unauthenticated invocations '
                  'to new service [{}]?'.format(
                      service_ref.servicesId)),
              default=False)
        else:
          allow_unauth = False
          pretty_print.Info(
              'This new service will require authentication to be invoked.')
      else:
        allow_unauth = False

      msg = ('Deploying {dep_type} to {operator} '
             'service [{{bold}}{service}{{reset}}]'
             ' in {ns_label} [{{bold}}{ns}{{reset}}]')
      msg += conn_context.location_label

      pretty_print.Info(msg.format(
          operator=conn_context.operator,
          ns_label=conn_context.ns_label,
          dep_type='container',
          service=service_ref.servicesId,
          ns=service_ref.namespacesId))

      deployment_stages = stages.ServiceStages(
          allow_unauth or args.allow_unauthenticated)
      header = 'Deploying...' if exists else 'Deploying new service...'
      with progress_tracker.StagedProgressTracker(
          header,
          deployment_stages,
          failure_message='Deployment failed',
          suppress_output=args.async) as tracker:
        operations.ReleaseService(
            service_ref,
            changes,
            tracker,
            asyn=args.async,
            private_endpoint=private_endpoint,
            allow_unauthenticated=allow_unauth or args.allow_unauthenticated)
      if args.async:
        pretty_print.Success(
            'Service [{{bold}}{serv}{{reset}}] is deploying '
            'asynchronously.'.format(serv=service_ref.servicesId))
      else:
        url = operations.GetServiceUrl(service_ref)
        conf = operations.GetConfiguration(service_ref)
        msg = (
            'Service [{{bold}}{serv}{{reset}}] '
            'revision [{{bold}}{rev}{{reset}}] '
            'has been deployed and is serving traffic at '
            '{{bold}}{url}{{reset}}')
        msg = msg.format(
            serv=service_ref.servicesId,
            rev=conf.status.latestReadyRevisionName,
            url=url)
        pretty_print.Success(msg)
Example #25
0
 def testServiceBeginDash(self):
   args = mock.Mock()
   args.CONCEPTS.service.Parse.return_value = self._ServiceRef('-s3rvice')
   with self.assertRaises(flags.ArgumentError):
     flags.GetService(args)
Example #26
0
    def Run(self, args):
        """Deploy a container to Cloud Run."""
        service_ref = flags.GetService(args)
        messages = None
        build_type = None
        build_config = None
        image = None
        include_build = flags.FlagIsExplicitlySet(args, 'source')
        operation_message = 'Deploying container'
        # Build an image from source if source specified
        if include_build:
            # Create a tag for the image creation
            if not args.IsSpecified('image'):
                args.image = 'gcr.io/{projectID}/cloud-run-source-deploy/{service}:{tag}'.format(
                    projectID=properties.VALUES.core.project.Get(
                        required=True),
                    service=service_ref.servicesId,
                    tag=uuid.uuid4().hex)
            # Use GCP Buildpacks if Dockerfile doesn't exist
            docker_file = args.source + '/Dockerfile'
            if os.path.exists(docker_file):
                build_type = BuildType.DOCKERFILE
            else:
                args.pack = [{'image': args.image}]
                build_type = BuildType.BUILDPACKS
            operation_message = 'Building using {build_type} and deploying container'.format(
                build_type=build_type.value)
            messages = cloudbuild_util.GetMessagesModule()
            image = None if args.pack else args.image
            build_config = submit_util.CreateBuildConfigAlpha(
                image, args.no_cache, messages, args.substitutions, None,
                args.IsSpecified('source'), False, args.source,
                args.gcs_source_staging_dir, args.ignore_file,
                args.gcs_log_dir, args.machine_type, args.disk_size,
                args.worker_pool, args.pack)
        elif not args.IsSpecified('image'):
            raise c_exceptions.RequiredArgumentException(
                '--image', 'Requires a container image to deploy (e.g. '
                '`gcr.io/cloudrun/hello:latest`) if no build source is provided.'
            )
        # Deploy a container with an image
        conn_context = connection_context.GetConnectionContext(
            args, flags.Product.RUN, self.ReleaseTrack())
        changes = flags.GetConfigurationChanges(args)
        changes.append(
            config_changes.SetLaunchStageAnnotationChange(self.ReleaseTrack()))

        with serverless_operations.Connect(conn_context) as operations:
            service = operations.GetService(service_ref)
            allow_unauth = GetAllowUnauth(args, operations, service_ref,
                                          service)
            resource_change_validators.ValidateClearVpcConnector(service, args)

            pretty_print.Info(
                messages_util.GetStartDeployMessage(conn_context, service_ref,
                                                    operation_message))
            has_latest = (service is None or traffic.LATEST_REVISION_KEY
                          in service.spec_traffic)
            deployment_stages = stages.ServiceStages(
                include_iam_policy_set=allow_unauth is not None,
                include_route=has_latest,
                include_build=include_build)
            header = None
            if include_build:
                header = 'Building and deploying'
            else:
                header = 'Deploying'
            if service is None:
                header += ' new service'
            header += '...'
            with progress_tracker.StagedProgressTracker(
                    header,
                    deployment_stages,
                    failure_message='Deployment failed',
                    suppress_output=args.async_) as tracker:
                service = operations.ReleaseService(
                    service_ref,
                    changes,
                    tracker,
                    asyn=args.async_,
                    allow_unauthenticated=allow_unauth,
                    prefetch=service,
                    build_config=build_config,
                    build_messages=messages)

            if args.async_:
                pretty_print.Success(
                    'Service [{{bold}}{serv}{{reset}}] is deploying '
                    'asynchronously.'.format(serv=service.name))
            else:
                service = operations.GetService(service_ref)
                pretty_print.Success(
                    messages_util.GetSuccessMessageForSynchronousDeploy(
                        service))
            return service
Example #27
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)

        if (conn_context.supports_one_platform
                and getattr(args, 'connectivity', None)):
            raise exceptions.ConfigurationError(
                'The `--endpoint=[internal|external]` flag '
                'is only supported with Cloud Run on GKE.')

        if (not conn_context.supports_one_platform
                and getattr(args, 'allow_unauthenticated', None)):
            raise exceptions.ConfigurationError(
                'The `--allow-unauthenticated` flag '
                'is not supported with Cloud Run on GKE.')

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

        msg += conn_context.location_label

        if function_entrypoint:
            dep_type = 'function [{{bold}}{}{{reset}}]'.format(
                function_entrypoint)
            pretty_print.Info(
                msg.format(operator=conn_context.operator,
                           ns_label=conn_context.ns_label,
                           dep_type=dep_type,
                           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(operator=conn_context.operator,
                           ns_label=conn_context.ns_label,
                           dep_type='container',
                           service=service_ref.servicesId,
                           ns=service_ref.namespacesId))
        else:
            pretty_print.Info(
                msg.format(operator=conn_context.operator,
                           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)
            if args.connectivity == 'internal':
                private_endpoint = True
            elif args.connectivity == 'external':
                private_endpoint = False
            else:
                private_endpoint = None
            deployment_stages = stages.ServiceStages()
            exists = operations.GetService(service_ref)

            if (not exists and not args.allow_unauthenticated
                    and conn_context.supports_one_platform):

                if operations.CanAddIamPolicyBinding(service_ref):
                    allow_unauth = console_io.PromptContinue(
                        prompt_string=('Allow unauthenticated invocations '
                                       'to new service [{}]?'.format(
                                           service_ref.servicesId)),
                        default=False)
                else:
                    allow_unauth = False
                    pretty_print.Info(
                        'This new service will require authentication to be invoked.'
                    )
            else:
                allow_unauth = False

            header = 'Deploying...' if exists else 'Deploying new service...'
            with progress_tracker.StagedProgressTracker(
                    header,
                    deployment_stages,
                    failure_message='Deployment failed',
                    suppress_output=args. async) as tracker:
                operations.ReleaseService(service_ref,
                                          changes,
                                          tracker,
                                          asyn=args. async,
                                          private_endpoint=private_endpoint,
                                          allow_unauthenticated=allow_unauth
                                          or args.allow_unauthenticated)
            if args. async:
                pretty_print.Success(
                    'Service [{{bold}}{serv}{{reset}}] is deploying '
                    'asynchronously.'.format(serv=service_ref.servicesId))
            else:
                url = operations.GetServiceUrl(service_ref)
                conf = operations.GetConfiguration(service_ref)
                msg = ('Service [{{bold}}{serv}{{reset}}] '
                       'revision [{{bold}}{rev}{{reset}}] '
                       'has been deployed and is serving traffic at '
                       '{{bold}}{url}{{reset}}')
                msg = msg.format(serv=service_ref.servicesId,
                                 rev=conf.status.latestReadyRevisionName,
                                 url=url)
                pretty_print.Success(msg)