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
def Run(self, args): """List available services.""" is_managed = flags.IsManaged(args) if is_managed and not getattr(args, 'region', None): self._SetFormat(args, show_region=True) client = global_methods.GetServerlessClientInstance() self.SetPartialApiEndpoint(client.url) args.CONCEPTS.namespace.Parse() # Error if no proj. locations_ref = args.CONCEPTS.region.Parse() return commands.SortByName( global_methods.ListServices(client, locations_ref.RelativeName())) else: conn_context = connection_context.GetConnectionContext(args) self._SetFormat(args, show_region=is_managed, show_namespace=(not is_managed)) namespace_ref = args.CONCEPTS.namespace.Parse() with serverless_operations.Connect(conn_context) as client: self.SetCompleteApiEndpoint(conn_context.endpoint) if not is_managed: 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 commands.SortByName(client.ListServices(namespace_ref))
def GetAllowUnauth(args, operations, service_ref, service_exists): """Returns allow_unauth value for a service change. Args: args: argparse.Namespace, Command line arguments operations: serverless_operations.ServerlessOperations, Serverless client. service_ref: protorpc.messages.Message, A resource reference object for the service See googlecloudsdk.core.resources.Registry.ParseResourceId for details. service_exists: True if the service being changed already exists. Returns: allow_unauth value where True means to enable unauthenticated acess for the service. False means to disable unauthenticated access for the service. None means to retain the current value for the service. """ allow_unauth = None if flags.IsManaged(args): allow_unauth = flags.GetAllowUnauthenticated(args, operations, service_ref, not service_exists) # Avoid failure removing a policy binding for a service that # doesn't exist. if not service_exists and not allow_unauth: allow_unauth = None return allow_unauth
def GetConnectionContext(args): """Gets the regional, kubeconfig, or GKE connection context. Args: args: Namespace, the args namespace. Raises: ArgumentError if region or cluster is not specified. Returns: A GKE or regional ConnectionInfo object. """ if flags.IsKubernetes(args): kubeconfig = flags.GetKubeconfig(args) return _KubeconfigConnectionContext(kubeconfig, args.context) if flags.IsGKE(args): cluster_ref = args.CONCEPTS.cluster.Parse() if not cluster_ref: raise flags.ArgumentError( 'You must specify a cluster in a given location. ' 'Either use the `--cluster` and `--cluster-location` flags ' 'or set the run/cluster and run/cluster_location properties.') return _GKEConnectionContext(cluster_ref) if flags.IsManaged(args): region = flags.GetRegion(args, prompt=True) if not region: raise flags.ArgumentError( 'You must specify a region. Either use the `--region` flag ' 'or set the run/region property.') return _RegionalConnectionContext(region)
def Run(self, args): """List available services.""" is_managed = flags.IsManaged(args) if is_managed and not args.IsSpecified('region'): self._SetFormat(args, show_region=True) client = global_methods.GetServerlessClientInstance() self.SetPartialApiEndpoint(client.url) args.CONCEPTS.namespace.Parse() # Error if no proj. # Don't consider region property here, we'll default to all regions return commands.SortByName(global_methods.ListServices(client)) else: conn_context = connection_context.GetConnectionContext( args, product=connection_context.Product.RUN) self._SetFormat(args, show_region=is_managed, show_namespace=(not is_managed)) namespace_ref = args.CONCEPTS.namespace.Parse() with serverless_operations.Connect(conn_context) as client: self.SetCompleteApiEndpoint(conn_context.endpoint) if not is_managed: 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 commands.SortByName(client.ListServices(namespace_ref))
def Run(self, args): """Create a domain mapping.""" conn_context = connection_context.GetConnectionContext( args, self.ReleaseTrack()) domain_mapping_ref = args.CONCEPTS.domain.Parse() # Check if the provided domain has already been verified # if mapping to a non-CRoGKE service if flags.IsManaged(args): client = global_methods.GetServerlessClientInstance() all_domains = global_methods.ListVerifiedDomains( client, flags.GetRegion(args)) # 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: mapping = client.CreateDomainMapping(domain_mapping_ref, args.service) for record in mapping.records: record.name = record.name or mapping.route_name return mapping.records
def Run(self, args): """Create or Update service from YAML.""" conn_context = connection_context.GetConnectionContext( args, self.ReleaseTrack()) with serverless_operations.Connect(conn_context) as client: new_service = service.Service( messages_util.DictToMessageWithErrorCheck( args.FILE, client.messages_module.Service), client.messages_module) # If managed, namespace must match project (or will default to project if # not specified). # If not managed, namespace simply must not conflict if specified in # multiple places (or will default to "default" if not specified). namespace = args.CONCEPTS.namespace.Parse().Name() # From flag or default if new_service.metadata.namespace is not None: if (args.IsSpecified('namespace') and namespace != new_service.metadata.namespace): raise exceptions.ConfigurationError( 'Namespace specified in file does not match passed flag.') namespace = new_service.metadata.namespace project = properties.VALUES.core.project.Get() if flags.IsManaged(args) and namespace != project: raise exceptions.ConfigurationError( 'Namespace must be [{}] for Cloud Run (fully managed).'.format( project)) new_service.metadata.namespace = namespace changes = [config_changes.ReplaceServiceChange(new_service)] service_ref = resources.REGISTRY.Parse( new_service.metadata.name, params={'namespacesId': 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))
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)
def Run(self, args): """List available configurations.""" is_managed = flags.IsManaged(args) conn_context = connection_context.GetConnectionContext(args) self._SetFormat( args, show_region=is_managed, show_namespace=(not is_managed)) namespace_ref = args.CONCEPTS.namespace.Parse() with serverless_operations.Connect(conn_context) as client: self.SetCompleteApiEndpoint(conn_context.endpoint) if not is_managed: zone_label = ' in zone [{}]'.format(conn_context.cluster_location) log.status.Print('For cluster [{cluster}]{zone}:'.format( cluster=conn_context.cluster_name, zone=zone_label if conn_context.cluster_location else '')) return commands.SortByName(client.ListConfigurations(namespace_ref))
def Run(self, args): """List available services.""" if flags.IsManaged(args) and not getattr(args, 'region', None): client = global_methods.GetServerlessClientInstance() self.SetPartialApiEndpoint(client.url) locations_ref = args.CONCEPTS.region.Parse() return commands.SortByName( global_methods.ListServices(client, locations_ref.RelativeName())) else: 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 commands.SortByName(client.ListServices(namespace_ref))
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)
def GetConnectionContext(args, track=base.ReleaseTrack.BETA): """Gets the regional, kubeconfig, or GKE connection context. Args: args: Namespace, the args namespace. track: ReleaseTrack, the release track. Raises: ArgumentError if region or cluster is not specified. Returns: A GKE or regional ConnectionInfo object. """ if flags.IsKubernetes(args): kubeconfig = flags.GetKubeconfig(args) return _KubeconfigConnectionContext(kubeconfig, args.context) if flags.IsGKE(args): cluster_ref = args.CONCEPTS.cluster.Parse() if not cluster_ref: raise flags.ArgumentError( 'You must specify a cluster in a given location. ' 'Either use the `--cluster` and `--cluster-location` flags ' 'or set the run/cluster and run/cluster_location properties.') return _GKEConnectionContext(cluster_ref) if flags.IsManaged(args): region = flags.GetRegion(args, prompt=True) if not region: raise flags.ArgumentError( 'You must specify a region. Either use the `--region` flag ' 'or set the run/region property.') if track == base.ReleaseTrack.ALPHA: version = 'v1' else: version = global_methods.SERVERLESS_API_VERSION return _RegionalConnectionContext(region, version)
def _CheckPlatform(self, args): if flags.IsManaged(args): raise exceptions.PlatformError( 'This command is in beta for fully managed Cloud Run; ' 'use `gcloud beta run domain-mappings delete`.')