def Run(self, args): """Create a domain mapping.""" conn_context = connection_context.GetConnectionContext( args, product=flags.Product.RUN) 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.GetPlatform() == flags.PLATFORM_MANAGED: 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, args.force_override) for record in mapping.records: record.name = record.name or mapping.route_name return mapping.records
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 GetConnectionContext(args, product=flags.Product.RUN, release_track=base.ReleaseTrack.GA, version_override=None, platform=None): """Gets the regional, kubeconfig, or GKE connection context. Args: args: Namespace, the args namespace. product: Which product is requesting connection context. release_track: Release track of the command being run. version_override: If specified, the given api version will be used no matter the other parameters. platform: 'gke', 'kubernetes', or 'managed'. If not specified, the value of the --platform flag will be used instead. Raises: ArgumentError if region or cluster is not specified. Returns: A GKE or regional ConnectionInfo object. """ if platform is None: platform = platforms.GetPlatform() if platform == platforms.PLATFORM_KUBERNETES: kubeconfig = flags.GetKubeconfig(getattr(args, 'kubeconfig', None)) api_name = _GetApiName(product, release_track, is_cluster=True) api_version = _GetApiVersion( product, release_track, is_cluster=True, version_override=version_override) return KubeconfigConnectionContext(kubeconfig, api_name, api_version, args.context) if platform == platforms.PLATFORM_GKE: cluster_ref = args.CONCEPTS.cluster.Parse() if not cluster_ref: raise serverless_exceptions.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.') api_name = _GetApiName(product, release_track, is_cluster=True) api_version = _GetApiVersion( product, release_track, is_cluster=True, version_override=version_override) return GKEConnectionContext(cluster_ref, api_name, api_version) if platform == platforms.PLATFORM_MANAGED: region = flags.GetRegion(args, prompt=True) if not region: raise serverless_exceptions.ArgumentError( 'You must specify a region. Either use the `--region` flag ' 'or set the run/region property.') api_name = _GetApiName(product, release_track) api_version = _GetApiVersion( product, release_track, version_override=version_override) return _RegionalConnectionContext(region, api_name, api_version)
def RepoRegion(args, cluster_location=None): """Returns the region for the Artifact Registry repo. The intended behavior is platform-specific: * managed: Same region as the service (run/region or --region) * gke: Appropriate region based on cluster zone (cluster_location arg) * kubernetes: The run/region config value will be used or an exception raised when unset. Args: args: Namespace, the args namespace. cluster_location: The zone which a Cloud Run for Anthos cluster resides. When specified, this will result in the region for this zone being returned. Returns: The appropriate region for the repository. """ if cluster_location: return _RegionFromZone(cluster_location) region = flags.GetRegion(args, prompt=False) if region: return region raise exceptions.ArgumentError( 'To deploy from source with this platform, you must set run/region via ' '"gcloud config set run/region REGION".')
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 flags.GetPlatform() != flags.PLATFORM_MANAGED else None)) 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.GetPlatform() == flags.PLATFORM_MANAGED: 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: try: mapping = client.CreateDomainMapping(domain_mapping_ref, args.service, 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'): mapping = client.CreateDomainMapping( domain_mapping_ref, args.service, True) else: raise e for record in mapping.records: record.name = record.name or mapping.route_name return mapping.records
def testGetFromPrompt(self): with mock.patch( 'googlecloudsdk.api_lib.run.global_methods.GetServerlessClientInstance', return_value=self.mock_serverless_client): with mock.patch( 'googlecloudsdk.api_lib.run.global_methods.ListRegions', return_value=[base.DEFAULT_REGION]): properties.VALUES.run.region.Set(None) fake_idx = 0 self.WriteInput('{}\n'.format(fake_idx + 1)) expected_region = base.DEFAULT_REGION actual_region = flags.GetRegion(self.args, prompt=True) self.AssertErrContains( 'To make this the default region, run ' '`gcloud config set run/region {}`'.format(expected_region)) self.assertEqual(expected_region, actual_region)
def GetConnectionContext(args): """Gets the regional or GKE connection context. Args: args: Namespace, the args namespace. Raises: ConfigurationError if cluster is specified without a location. Returns: A GKE or regional ConnectionInfo object. """ if flags.ValidateIsGKE(args): cluster_ref = args.CONCEPTS.cluster.Parse() return _GKEConnectionContext(cluster_ref) region = flags.GetRegion(args, prompt=True) if not region: raise flags.ArgumentError( 'You must specify either a cluster or a region.') return _RegionalConnectionContext(region)
def GetConnectionContext(args, product=Product.RUN): """Gets the regional, kubeconfig, or GKE connection context. Args: args: Namespace, the args namespace. product: Which product is requesting connection context. Raises: ArgumentError if region or cluster is not specified. Returns: A GKE or regional ConnectionInfo object. """ if flags.GetPlatform() == flags.PLATFORM_KUBERNETES: kubeconfig = flags.GetKubeconfig(args) return _KubeconfigConnectionContext(kubeconfig, _CLUSTER_API_VERSION, args.context) if flags.GetPlatform() == flags.PLATFORM_GKE: 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, _CLUSTER_API_VERSION) if flags.GetPlatform() == flags.PLATFORM_MANAGED: 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 product == Product.RUN: version = global_methods.SERVERLESS_API_VERSION elif product == Product.EVENTS: version = _EVENTS_API_VERSION else: raise ValueError('Unrecognized product: ' + six.u(product)) return _RegionalConnectionContext(region, version)
def Run(self, args): filters = [args.log_filter] if args.IsSpecified('log_filter') else [] filters.append('resource.type = %s \n' % 'cloud_run_revision') filters.append('resource.labels.service_name = %s \n' % args.service) filters.append('resource.labels.location = %s \n' % flags.GetRegion(args, prompt=False)) filters.append('severity >= DEFAULT') filters += read_logs_lib.MakeTimestampFilters(args) lines = [] logs = common.FetchLogs(read_logs_lib.JoinFilters(filters), order_by=args.order, limit=args.limit) for log_line in logs: output_log = FormatLog(log_line) if output_log: lines.append(output_log) for line in reversed(lines): log.out.Print(line)
def Run(self, args): filters = [] if args.IsSpecified('log_filter'): filters.append(args.log_filter + ' \n') filters.append('resource.type = %s \n' % 'cloud_run_revision') filters.append('resource.labels.service_name = %s \n' % args.service) filters.append('resource.labels.location = %s \n' % flags.GetRegion(args, prompt=False)) filters.append('severity >= DEFAULT') parent = 'projects/{project_id}'.format( project_id=properties.VALUES.core.project.Get(required=True)) filter_str = ''.join(str(filter) for filter in filters) # pylint: disable=g-import-not-at-top from googlecloudsdk.api_lib.logging import tailing # pylint: enable=g-import-not-at-top tailer = tailing.LogTailer() logs = tailer.TailLogs([parent], filter_str) for log_line in logs: output_log = FormatLog(log_line) if output_log: log.out.Print(output_log)
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 testGetFromServerlessConfig(self): self.assertEqual('serverless-config-region', flags.GetRegion(self.args))
def testGetFromFlag(self): self.args.region = 'region1' self.assertEqual('region1', flags.GetRegion(self.args, prompt=True))