Ejemplo n.º 1
0
 def testVerifyOnePlatformFlagsTimeout(self):
   parser = argparse.ArgumentParser()
   flags.AddTimeoutFlag(parser)
   args = parser.parse_args(['--timeout', '1h'],
                            parser_extensions.Namespace(timeout=None))
   with self.assertRaises(exceptions.ConfigurationError):
     flags.VerifyOnePlatformFlags(args, self.track, flags.Product.RUN)
Ejemplo n.º 2
0
 def testVerifyOnePlatformFlagsTimeoutGAOk(self):
     parser = argparse.ArgumentParser()
     flags.AddTimeoutFlag(parser)
     args = parser.parse_args(['--timeout', '15m'],
                              parser_extensions.Namespace(timeout=None))
     flags.VerifyOnePlatformFlags(args, calliope_base.ReleaseTrack.GA,
                                  flags.Product.RUN)
Ejemplo n.º 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)
Ejemplo n.º 4
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
Ejemplo n.º 5
0
    def Run(self, args):
        """Create or Update service from YAML."""
        conn_context = connection_context.GetConnectionContext(args)
        if conn_context.supports_one_platform:
            flags.VerifyOnePlatformFlags(args)
        else:
            flags.VerifyGKEFlags(args)

        with serverless_operations.Connect(conn_context) as client:
            message_dict = yaml.load_path(args.FILE)
            new_service = service.Service(
                messages_util.DictToMessageWithErrorCheck(
                    message_dict, client.messages_module.Service),
                client.messages_module)

            changes = [config_changes.ReplaceServiceChange(new_service)]
            service_ref = resources.REGISTRY.Parse(
                new_service.metadata.name,
                params={'namespacesId': new_service.metadata.namespace},
                collection='run.namespaces.services')
            original_service = client.GetService(service_ref)

            pretty_print.Info(
                deploy.GetStartDeployMessage(conn_context, service_ref))

            deployment_stages = stages.ServiceStages()
            header = ('Deploying...'
                      if original_service else 'Deploying new service...')
            with progress_tracker.StagedProgressTracker(
                    header,
                    deployment_stages,
                    failure_message='Deployment failed',
                    suppress_output=args. async) as tracker:
                client.ReleaseService(service_ref,
                                      changes,
                                      tracker,
                                      asyn=args. async,
                                      allow_unauthenticated=None,
                                      for_replace=True)
            if args. async:
                pretty_print.Success(
                    'Service [{{bold}}{serv}{{reset}}] is deploying '
                    'asynchronously.'.format(serv=service_ref.servicesId))
            else:
                pretty_print.Success(
                    deploy.GetSuccessMessageForSynchronousDeploy(
                        client, service_ref))
Ejemplo n.º 6
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)
Ejemplo n.º 7
0
 def testVerifyOnePlatformFlagsEventsIsAlphaOnly(self):
   # The "gcloud events" subcommand is alpha only for --platform=managed
   args = parser_extensions.Namespace()
   flags.VerifyOnePlatformFlags(args, self.track, flags.Product.EVENTS)
Ejemplo n.º 8
0
 def testVerifyOnePlatformFlagsMinInstanceBeta(self):
     args = parser_extensions.Namespace(min_instances=None)
     with self.assertRaises(exceptions.ConfigurationError):
         args.min_instances = 3
         flags.VerifyOnePlatformFlags(args, calliope_base.ReleaseTrack.BETA,
                                      flags.Product.RUN)
Ejemplo n.º 9
0
 def testVerifyOnePlatformFlagsMinInstance(self):
   args = parser_extensions.Namespace(min_instances=None)
   args.min_instances = 3
   flags.VerifyOnePlatformFlags(args, self.track, flags.Product.RUN)
Ejemplo n.º 10
0
 def testVerifyOnePlatformFlagsTimeout(self):
   parser = argparse.ArgumentParser()
   flags.AddTimeoutFlag(parser)
   args = parser.parse_args(['--timeout', '1h'],
                            parser_extensions.Namespace(timeout=None))
   flags.VerifyOnePlatformFlags(args, self.track, flags.Product.RUN)
Ejemplo n.º 11
0
 def testVerifyOnePlatformFlagsCpu(self):
   args = parser_extensions.Namespace(cpu=None)
   args.cpu = 2
   flags.VerifyOnePlatformFlags(args, self.track, flags.Product.RUN)
Ejemplo n.º 12
0
 def testVerifyOnePlatformFlagsEventsIsAlphaOnly(self):
   # The "gcloud events" subcommand is alpha only for --platform=managed
   args = parser_extensions.Namespace()
   with self.assertRaises(exceptions.ConfigurationError):
     flags.VerifyOnePlatformFlags(args, self.track, flags.Product.EVENTS)
Ejemplo n.º 13
0
 def testVerifyOnePlatformFlagsCpu(self):
     args = parser_extensions.Namespace(cpu=None)
     args.cpu = 2
     flags.VerifyOnePlatformFlags(args, calliope_base.ReleaseTrack.GA,
                                  flags.Product.RUN)
Ejemplo n.º 14
0
 def testVerifyOnePlatformFlagsMinInstanceAlpha(self):
     args = parser_extensions.Namespace(min_instances=None)
     args.min_instances = 3
     flags.VerifyOnePlatformFlags(args, calliope_base.ReleaseTrack.ALPHA,
                                  flags.Product.RUN)
Ejemplo n.º 15
0
 def testVerifyOnePlatformFlagsContext(self):
   args = parser_extensions.Namespace(context=None)
   with self.assertRaises(exceptions.ConfigurationError):
     args.context = 'some-context'
     flags.VerifyOnePlatformFlags(args, self.track, flags.Product.RUN)
Ejemplo n.º 16
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)
Ejemplo n.º 17
0
 def testVerifyOnePlatformFlagsKubeconfig(self):
   args = parser_extensions.Namespace(kubeconfig=None)
   with self.assertRaises(exceptions.ConfigurationError):
     args.kubeconfig = '~/.kube/config'
     flags.VerifyOnePlatformFlags(args, self.track, flags.Product.RUN)
Ejemplo n.º 18
0
 def testVerifyOnePlatformFlagsLocation(self):
   args = parser_extensions.Namespace(cluster_location=None)
   with self.assertRaises(exceptions.ConfigurationError):
     args.cluster_location = 'us-central1-a'
     flags.VerifyOnePlatformFlags(args, self.track, flags.Product.RUN)
Ejemplo n.º 19
0
 def testVerifyOnePlatformFlagsCluster(self):
   args = parser_extensions.Namespace(cluster=None)
   with self.assertRaises(exceptions.ConfigurationError):
     args.cluster = 'cluster-1'
     flags.VerifyOnePlatformFlags(args, self.track, flags.Product.RUN)
Ejemplo n.º 20
0
    def Run(self, args):
        """Deploy a container to Cloud Run."""
        source_ref = flags.GetSourceRef(args.source, 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)
        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
            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

            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)
Ejemplo n.º 21
0
 def testVerifyOnePlatformFlagsEgressSettings(self):
   args = parser_extensions.Namespace(vpc_egress='private-ranges-only')
   flags.VerifyOnePlatformFlags(args, self.track, flags.Product.RUN)
Ejemplo n.º 22
0
 def testVerifyOnePlatformFlagsMinInstance(self):
   args = parser_extensions.Namespace(min_instances=None)
   with self.assertRaises(exceptions.ConfigurationError):
     args.min_instances = 3
     flags.VerifyOnePlatformFlags(args, self.track, flags.Product.RUN)
Ejemplo n.º 23
0
 def testVerifyOnePlatformFlagsNoTrafficAlpha(self):
     args = parser_extensions.Namespace(no_traffic=None)
     args.no_traffic = True
     flags.VerifyOnePlatformFlags(args, calliope_base.ReleaseTrack.ALPHA,
                                  flags.Product.RUN)
Ejemplo n.º 24
0
 def testVerifyOnePlatformFlagsNoTraffic(self):
   args = parser_extensions.Namespace(no_traffic=None)
   args.no_traffic = True
   flags.VerifyOnePlatformFlags(args, self.track, flags.Product.RUN)
Ejemplo n.º 25
0
 def testVerifyOnePlatformFlagsConnectivity(self):
     args = parser_extensions.Namespace(connectivity=None)
     with self.assertRaises(exceptions.ConfigurationError):
         args.connectivity = True
         flags.VerifyOnePlatformFlags(args, calliope_base.ReleaseTrack.GA,
                                      flags.Product.RUN)