feat: Add new gcloud commands, API clients, and third-party libraries across various services.

This commit is contained in:
2026-01-01 20:26:35 +01:00
parent 5e23cbece0
commit a19e592eb7
25221 changed files with 8324611 additions and 0 deletions

View File

@@ -0,0 +1,45 @@
# -*- coding: utf-8 -*- #
# Copyright 2019 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The command group for Cloud API Gateway CLI."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.ml_engine import flags
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core import resources
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class ApiGateway(base.Group):
"""Manage Cloud API Gateway resources.
Commands for managing Cloud API Gateway resources.
"""
category = base.API_PLATFORM_AND_ECOSYSTEMS_CATEGORY
def Filter(self, context, args):
# TODO(b/190524392): Determine if command group works with project number
base.RequireProjectID(args)
del context, args
base.DisableUserProjectQuota()
resources.REGISTRY.RegisterApiByName('apigateway', 'v1')

View File

@@ -0,0 +1,26 @@
# -*- coding: utf-8 -*- #
# Copyright 2019 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Package for the apigateway/api_configs CLI subcommands."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
class ApiConfigs(base.Group):
"""Manage Cloud API Gateway API Configs."""

View File

@@ -0,0 +1,317 @@
# -*- coding: utf-8 -*- #
# Copyright 2020 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""`gcloud api-gateway api-configs create` command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import os
import cloudsdk.google.protobuf.descriptor_pb2 as descriptor
from googlecloudsdk.api_lib.api_gateway import api_configs as api_configs_client
from googlecloudsdk.api_lib.api_gateway import apis as apis_client
from googlecloudsdk.api_lib.api_gateway import base as apigateway_base
from googlecloudsdk.api_lib.api_gateway import operations as operations_client
from googlecloudsdk.api_lib.endpoints import services_util as endpoints
from googlecloudsdk.calliope import arg_parsers
from googlecloudsdk.calliope import base
from googlecloudsdk.calliope import exceptions as calliope_exceptions
from googlecloudsdk.command_lib.api_gateway import common_flags
from googlecloudsdk.command_lib.api_gateway import operations_util
from googlecloudsdk.command_lib.api_gateway import resource_args
from googlecloudsdk.command_lib.util.args import labels_util
from googlecloudsdk.core import log
from googlecloudsdk.core.util import http_encoding
MAX_SERVICE_CONFIG_ID_LENGTH = 50
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class Create(base.CreateCommand):
"""Add a new config to an API."""
detailed_help = {
'DESCRIPTION':
"""\
{description}
NOTE: If the specified API does not exist it will be created.""",
'EXAMPLES':
"""\
To create an API config for the API 'my-api' with an OpenAPI spec, run:
$ {command} my-config --api=my-api --openapi-spec=path/to/openapi_spec.yaml
""",
}
@staticmethod
def Args(parser):
base.ASYNC_FLAG.AddToParser(parser)
common_flags.AddDisplayNameArg(parser)
labels_util.AddCreateLabelsFlags(parser)
resource_args.AddApiConfigResourceArg(parser, 'created', positional=True)
common_flags.AddBackendAuthServiceAccountFlag(parser)
group = parser.add_group(mutex=True,
required=True,
help='Configuration files for the API.')
group.add_argument(
'--openapi-spec',
type=arg_parsers.ArgList(),
metavar='FILE',
help=('The OpenAPI specifications containing service '
'configuration information, and API specification for the gateway'
'.'))
group.add_argument(
'--grpc-files',
type=arg_parsers.ArgList(),
metavar='FILE',
help=('Files describing the GRPC service. Google Service Configuration '
'files in JSON or YAML formats as well as Proto '
'descriptors should be listed.'))
def Run(self, args):
apis = apis_client.ApiClient()
api_configs = api_configs_client.ApiConfigClient()
ops = operations_client.OperationsClient()
api_config_ref = args.CONCEPTS.api_config.Parse()
api_ref = api_config_ref.Parent()
# Check to see if Api exists, create if not
if not apis.DoesExist(api_ref):
res = apis.Create(api_ref)
operations_util.PrintOperationResult(
res.name, ops,
wait_string='Waiting for API [{}] to be created'.format(
api_ref.Name()))
open_api_docs = []
svc_configs = []
grpc_svc_defs = []
# When we add gRPC support back, we can remove the 'hasattr' call.
if hasattr(args, 'grpc_files') and args.grpc_files:
args.grpc_files = [f.strip() for f in args.grpc_files]
svc_configs, grpc_svc_defs = self.__GrpcMessages(args.grpc_files)
else:
args.openapi_spec = [f.strip() for f in args.openapi_spec]
open_api_docs = self.__OpenApiMessage(args.openapi_spec)
# Create ApiConfig object.
# Only piece affected by async right now
resp = api_configs.Create(api_config_ref,
labels=args.labels,
display_name=args.display_name,
backend_auth=args.backend_auth_service_account,
managed_service_configs=svc_configs,
grpc_service_defs=grpc_svc_defs,
open_api_docs=open_api_docs)
wait = 'Waiting for API Config [{0}] to be created for API [{1}]'.format(
api_config_ref.Name(), api_ref.Name())
return operations_util.PrintOperationResult(
resp.name,
ops,
service=api_configs.service,
wait_string=wait,
is_async=args.async_)
def __OpenApiMessage(self, open_api_specs):
"""Parses the Open API scoped configuraiton files into their necessary API Gateway message types.
Args:
open_api_specs: Specs to be used with the API Gateway API Configuration
Returns:
List of ApigatewayApiConfigOpenApiDocument messages
Raises:
BadFileException: If there is something wrong with the files
"""
messages = apigateway_base.GetMessagesModule()
config_files = []
for config_file in open_api_specs:
config_contents = endpoints.ReadServiceConfigFile(config_file)
config_dict = self.__ValidJsonOrYaml(config_file, config_contents)
if config_dict:
if 'swagger' in config_dict or 'openapi' in config_dict:
# Always use YAML for OpenAPI because JSON is a subset of YAML.
document = self.__MakeApigatewayApiConfigFileMessage(config_contents,
config_file)
config_files.append(messages.ApigatewayApiConfigOpenApiDocument(
document=document))
else:
raise calliope_exceptions.BadFileException(
'The file {} is not a valid OpenAPI configuration file.'
.format(config_file))
else:
raise calliope_exceptions.BadFileException(
'OpenAPI files should be of JSON or YAML format')
return config_files
def __GrpcMessages(self, files):
"""Parses the GRPC scoped configuraiton files into their necessary API Gateway message types.
Args:
files: Files to be sent in as managed service configs and GRPC service
definitions
Returns:
List of ApigatewayApiConfigFileMessage, list of
ApigatewayApiConfigGrpcServiceDefinition messages
Raises:
BadFileException: If there is something wrong with the files
"""
grpc_service_definitions = []
service_configs = []
for config_file in files:
config_contents = endpoints.ReadServiceConfigFile(config_file)
config_dict = self.__ValidJsonOrYaml(config_file, config_contents)
if config_dict:
if config_dict.get('type') == 'google.api.Service':
service_configs.append(
self.__MakeApigatewayApiConfigFileMessage(config_contents,
config_file))
else:
raise calliope_exceptions.BadFileException(
'The file {} is not a valid api configuration file. The '
'configuration type is expected to be of "google.api.Service".'.
format(config_file))
elif endpoints.IsProtoDescriptor(config_file):
grpc_service_definitions.append(
self.__MakeApigatewayApiConfigGrpcServiceDefinitionMessage(
config_contents, config_file))
elif endpoints.IsRawProto(config_file):
raise calliope_exceptions.BadFileException(
('[{}] cannot be used as it is an uncompiled proto'
' file. However, uncompiled proto files can be included for'
' display purposes when compiled as a source for a passed in proto'
' descriptor.'
).format(config_file))
else:
raise calliope_exceptions.BadFileException(
('Could not determine the content type of file [{0}]. Supported '
'extensions are .descriptor .json .pb .yaml and .yml'
).format(config_file))
return service_configs, grpc_service_definitions
def __ValidJsonOrYaml(self, file_name, file_contents):
"""Whether or not this is a valid json or yaml file.
Args:
file_name: Name of the file
file_contents: data for the file
Returns:
Boolean for whether or not this is a JSON or YAML
Raises:
BadFileException: File appears to be json or yaml but cannot be parsed.
"""
if endpoints.FilenameMatchesExtension(file_name,
['.json', '.yaml', '.yml']):
config_dict = endpoints.LoadJsonOrYaml(file_contents)
if config_dict:
return config_dict
else:
raise calliope_exceptions.BadFileException(
'Could not read JSON or YAML from config file '
'[{0}].'.format(file_name))
else:
return False
def __MakeApigatewayApiConfigFileMessage(self, file_contents, filename,
is_binary=False):
"""Constructs a ConfigFile message from a config file.
Args:
file_contents: The contents of the config file.
filename: The path to the config file.
is_binary: If set to true, the file_contents won't be encoded.
Returns:
The constructed ApigatewayApiConfigFile message.
"""
messages = apigateway_base.GetMessagesModule()
if not is_binary:
# File is human-readable text, not binary; needs to be encoded.
file_contents = http_encoding.Encode(file_contents)
return messages.ApigatewayApiConfigFile(
contents=file_contents,
path=os.path.basename(filename),
)
def __MakeApigatewayApiConfigGrpcServiceDefinitionMessage(self,
proto_desc_contents,
proto_desc_file):
"""Constructs a GrpcServiceDefinition message from a proto descriptor and the provided list of input files.
Args:
proto_desc_contents: The contents of the proto descriptor file.
proto_desc_file: The path to the proto descriptor file.
Returns:
The constructed ApigatewayApiConfigGrpcServiceDefinition message.
"""
messages = apigateway_base.GetMessagesModule()
fds = descriptor.FileDescriptorSet.FromString(proto_desc_contents)
proto_desc_dir = os.path.dirname(proto_desc_file)
grpc_sources = []
included_source_paths = []
not_included_source_paths = []
# Iterate over the file descriptors dependency files and attempt to resolve
# the gRPC source proto files from it.
for file_descriptor in fds.file:
source_path = os.path.join(proto_desc_dir, file_descriptor.name)
if os.path.exists(source_path):
source_contents = endpoints.ReadServiceConfigFile(source_path)
file = self.__MakeApigatewayApiConfigFileMessage(source_contents,
source_path)
included_source_paths.append(source_path)
grpc_sources.append(file)
else:
not_included_source_paths.append(source_path)
if not_included_source_paths:
log.warning('Proto descriptor\'s source protos [{0}] were not found on'
' the file system and will not be included in the submitted'
' GRPC service definition. If you meant to include these'
' files, ensure the proto compiler was invoked in the same'
' directory where the proto descriptor [{1}] now resides.'.
format(', '.join(not_included_source_paths), proto_desc_file))
# Log which files are being passed in as to ensure the user is informed of
# all files being passed into the gRPC service definition.
if included_source_paths:
log.info('Added the source protos [{0}] to the GRPC service definition'
' for the provided proto descriptor [{1}].'.
format(', '.join(included_source_paths), proto_desc_file))
file_descriptor_set = self.__MakeApigatewayApiConfigFileMessage(
proto_desc_contents, proto_desc_file, True)
return messages.ApigatewayApiConfigGrpcServiceDefinition(
fileDescriptorSet=file_descriptor_set, source=grpc_sources)

View File

@@ -0,0 +1,91 @@
# -*- coding: utf-8 -*- #
# Copyright 2019 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""`gcloud api-gateway api-configs delete` command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.api_gateway import api_configs
from googlecloudsdk.api_lib.api_gateway import operations
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.api_gateway import operations_util
from googlecloudsdk.command_lib.api_gateway import resource_args
from googlecloudsdk.core.console import console_io
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class Delete(base.DeleteCommand):
"""Deletes a config from an API."""
detailed_help = {
'DESCRIPTION':
'{description}',
'EXAMPLES':
"""\
To delete an API Config 'my-config' in 'my-api', run:
$ {command} my-config --api=my-api
""",
}
@staticmethod
def Args(parser):
"""Args is called by calliope to gather arguments for this command.
Args:
parser: An argparse parser that you can use to add arguments that go
on the command line after this command. Positional arguments are
allowed.
"""
base.ASYNC_FLAG.AddToParser(parser)
resource_args.AddApiConfigResourceArg(parser, 'deleted', positional=True)
def Run(self, args):
"""Run 'api-gateway api-configs delete'.
Args:
args: argparse.Namespace, The arguments that this command was invoked
with.
Returns:
The response from the Delete API call (or None if cancelled).
"""
api_config_ref = args.CONCEPTS.api_config.Parse()
# Prompt with a warning before continuing.
console_io.PromptContinue(
message='Are you sure? This will delete the API Config \'{}\', '
'along with all of the associated consumer '
'information.'.format(api_config_ref.RelativeName()),
prompt_string='Continue anyway',
default=True,
throw_if_unattended=True,
cancel_on_no=True)
client = api_configs.ApiConfigClient()
resp = client.Delete(api_config_ref)
wait = 'Waiting for API Config [{}] to be deleted'.format(
api_config_ref.Name())
return operations_util.PrintOperationResult(
resp.name, operations.OperationsClient(), wait_string=wait,
is_async=args.async_)

View File

@@ -0,0 +1,59 @@
# -*- coding: utf-8 -*- #
# Copyright 2019 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""`gcloud api-gateway api-configs describe` command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.api_gateway import api_configs
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.api_gateway import resource_args
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class Describe(base.DescribeCommand):
"""Show details about a specific API config."""
detailed_help = {
'DESCRIPTION':
'{description}',
'EXAMPLES':
"""\
To show details about an API config, run:
$ {command} my-config --api=my-api
""",
}
@staticmethod
def Args(parser):
parser.add_argument(
'--view',
default='BASIC',
choices=['BASIC', 'FULL'],
help="""\
The API Configuration view to return. If \
'FULL' is specified, the base64 encoded API Configuration's source file \
conent will be included in the response.
""")
resource_args.AddApiConfigResourceArg(parser, 'created', positional=True)
def Run(self, args):
config_ref = args.CONCEPTS.api_config.Parse()
return api_configs.ApiConfigClient().Get(config_ref, args.view)

View File

@@ -0,0 +1,73 @@
# -*- coding: utf-8 -*- #
# Copyright 2019 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""api-gateway gateways list command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.api_gateway import api_configs
from googlecloudsdk.api_lib.util import common_args
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.api_gateway import resource_args
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class List(base.ListCommand):
"""List configs for an API."""
detailed_help = {
'DESCRIPTION':
'{description}',
'EXAMPLES':
"""\
To list all API configs, run:
$ {command}
""",
}
LIST_FORMAT = """
table(
name.segment(7):label=CONFIG_ID,
name.segment(5):label=API_ID,
displayName,
serviceConfigId,
state,
createTime.date()
)
"""
@staticmethod
def Args(parser):
resource_args.AddApiResourceArg(parser, 'api configs will be listed from',
wildcard=True, required=False)
# Remove unneeded list-related flags from parser
base.URI_FLAG.RemoveFromParser(parser)
parser.display_info.AddFormat(List.LIST_FORMAT)
def Run(self, args):
parent_ref = args.CONCEPTS.api.Parse()
sort_by = common_args.ParseSortByArg(args.sort_by)
return api_configs.ApiConfigClient().List(parent_ref.RelativeName(),
filters=args.filter,
limit=args.limit,
page_size=args.page_size,
sort_by=sort_by)

View File

@@ -0,0 +1,94 @@
# -*- coding: utf-8 -*- #
# Copyright 2020 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""`gcloud api-gateway api_configs update` command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from googlecloudsdk.api_lib.api_gateway import api_configs
from googlecloudsdk.api_lib.api_gateway import operations
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.api_gateway import common_flags
from googlecloudsdk.command_lib.api_gateway import operations_util
from googlecloudsdk.command_lib.api_gateway import resource_args
from googlecloudsdk.command_lib.util.args import labels_util
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class Update(base.UpdateCommand):
"""Update an API Gateway API config."""
detailed_help = {
'DESCRIPTION':
"""\
{description}
NOTE: Only the name and labels may be updated on an API config.
""",
'EXAMPLES':
"""\
To update the display name of an API config, run:
$ {command} my-config --api=my-api --display-name="New Display Name"
NOTE: Only the display name and labels attributes are mutable on an API config.
""",
}
@staticmethod
def Args(parser):
base.ASYNC_FLAG.AddToParser(parser)
common_flags.AddDisplayNameArg(parser)
labels_util.AddUpdateLabelsFlags(parser)
resource_args.AddApiConfigResourceArg(parser, 'updated', positional=True)
def Run(self, args):
api_config_ref = args.CONCEPTS.api_config.Parse()
api_config_client = api_configs.ApiConfigClient()
api_cofig, mask = self.ProcessUpdates(api_config_client.Get(api_config_ref),
args)
resp = api_config_client.Update(api_cofig, update_mask=mask)
return operations_util.PrintOperationResult(
resp.name,
operations.OperationsClient(),
service=api_config_client.service,
wait_string='Waiting for API Config [{}] to be updated'.format(
api_config_ref.Name()),
is_async=args.async_)
def ProcessUpdates(self, api_cofig, args):
update_mask = []
labels_update = labels_util.ProcessUpdateArgsLazy(
args,
api_cofig.LabelsValue,
lambda: api_cofig.labels)
if labels_update.needs_update:
api_cofig.labels = labels_update.labels
update_mask.append('labels')
if args.display_name:
api_cofig.displayName = args.display_name
update_mask.append('displayName')
return api_cofig, ','.join(update_mask)

View File

@@ -0,0 +1,26 @@
# -*- coding: utf-8 -*- #
# Copyright 2020 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Package for the apigateway/apis CLI subcommands."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
class Apis(base.Group):
"""Manage Cloud API Gateway APIs."""

View File

@@ -0,0 +1,57 @@
# -*- coding: utf-8 -*- #
# Copyright 2020 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command to add IAM policy binding for a model."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.api_gateway import apis
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.api_gateway import common_flags
from googlecloudsdk.command_lib.api_gateway import resource_args
from googlecloudsdk.command_lib.iam import iam_util
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class AddIamPolicyBinding(base.Command):
"""Add IAM policy binding to a gateway."""
detailed_help = {
'EXAMPLES':
"""\
To add an IAM policy binding for the role of 'roles/editor' for the
user 'test-user@gmail.com' on the API 'my-api', run:
$ {command} my-api --member='user:test-user@gmail.com' --role='roles/editor
""",
}
@staticmethod
def Args(parser):
resource_args.AddApiResourceArg(parser,
'IAM policy binding will be added to',
positional=True)
iam_util.AddArgsForAddIamPolicyBinding(
parser,
common_flags.GatewayIamRolesCompleter)
def Run(self, args):
api_ref = args.CONCEPTS.api.Parse()
return apis.ApiClient().AddIamPolicyBinding(
api_ref, args.member, args.role)

View File

@@ -0,0 +1,70 @@
# -*- coding: utf-8 -*- #
# Copyright 2019 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""`gcloud api-gateway apis create` command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.api_gateway import apis
from googlecloudsdk.api_lib.api_gateway import operations as ops
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.api_gateway import common_flags
from googlecloudsdk.command_lib.api_gateway import operations_util
from googlecloudsdk.command_lib.api_gateway import resource_args
from googlecloudsdk.command_lib.util.args import labels_util
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class Create(base.CreateCommand):
"""Create a new API."""
detailed_help = {
'DESCRIPTION':
'{description}',
'EXAMPLES':
"""\
To create an API, run:
$ {command} my-api
""",
}
@staticmethod
def Args(parser):
base.ASYNC_FLAG.AddToParser(parser)
common_flags.AddDisplayNameArg(parser)
common_flags.AddManagedServiceFlag(parser)
labels_util.AddCreateLabelsFlags(parser)
resource_args.AddApiResourceArg(parser, 'created', positional=True)
def Run(self, args):
api_ref = args.CONCEPTS.api.Parse()
api_client = apis.ApiClient()
resp = api_client.Create(api_ref,
managed_service=args.managed_service,
labels=args.labels,
display_name=args.display_name)
return operations_util.PrintOperationResult(
resp.name,
ops.OperationsClient(),
service=api_client.service,
wait_string='Waiting for API [{}] to be created'.format(api_ref.Name()),
is_async=args.async_)

View File

@@ -0,0 +1,96 @@
# -*- coding: utf-8 -*- #
# Copyright 2020 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""`gcloud api-gateway apis delete` command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.api_gateway import apis
from googlecloudsdk.api_lib.api_gateway import operations
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.api_gateway import operations_util
from googlecloudsdk.command_lib.api_gateway import resource_args
from googlecloudsdk.core.console import console_io
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class Delete(base.DeleteCommand):
"""Deletes an API."""
detailed_help = {
'DESCRIPTION':
"""\
{description}
NOTE: All API configs belonging to the API will need to be deleted before
the API can be deleted.
""",
'EXAMPLES':
"""\
To delete an API 'my-api', run:
$ {command} my-api
NOTE: All API configs belonging to the API will need to be deleted before
the API can be deleted.
""",
}
@staticmethod
def Args(parser):
"""Args is called by calliope to gather arguments for this command.
Args:
parser: An argparse parser that you can use to add arguments that go
on the command line after this command. Positional arguments are
allowed.
"""
base.ASYNC_FLAG.AddToParser(parser)
resource_args.AddApiResourceArg(parser, 'will be deleted', positional=True)
def Run(self, args):
"""Run 'api-gateway apis delete'.
Args:
args: argparse.Namespace, The arguments that this command was invoked
with.
Returns:
The response from the Delete API call (or None if cancelled).
"""
api_ref = args.CONCEPTS.api.Parse()
# Prompt with a warning before continuing.
console_io.PromptContinue(
message='Are you sure? This will delete the API \'{}\', '
'along with all of the associated consumer '
'information.'.format(api_ref.RelativeName()),
prompt_string='Continue anyway',
default=True,
throw_if_unattended=True,
cancel_on_no=True)
resp = apis.ApiClient().Delete(api_ref)
wait = 'Waiting for API [{}] to be deleted'.format(
api_ref.Name())
return operations_util.PrintOperationResult(
resp.name, operations.OperationsClient(), wait_string=wait,
is_async=args.async_)

View File

@@ -0,0 +1,52 @@
# -*- coding: utf-8 -*- #
# Copyright 2020 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""`gcloud api-gateway apis describe` command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.api_gateway import apis
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.api_gateway import resource_args
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class Describe(base.DescribeCommand):
"""Show details about a specific API."""
detailed_help = {
'DESCRIPTION':
'{description}',
'EXAMPLES':
"""\
To show details about an API, run:
$ {command} my-api
""",
}
@staticmethod
def Args(parser):
resource_args.AddApiResourceArg(parser, 'will be described',
positional=True)
def Run(self, args):
api_ref = args.CONCEPTS.api.Parse()
return apis.ApiClient().Get(api_ref)

View File

@@ -0,0 +1,53 @@
# -*- coding: utf-8 -*- #
# Copyright 2020 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command for getting IAM policies for apis."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.api_gateway import apis
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.api_gateway import resource_args
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class GetIamPolicy(base.ListCommand):
"""Get the IAM policy for an API."""
detailed_help = {
'DESCRIPTION':
'{description}',
'EXAMPLES':
"""\
To print the IAM policy for a given API, run:
$ {command} my-api
""",
}
@staticmethod
def Args(parser):
resource_args.AddApiResourceArg(parser, 'for which to get IAM policy',
positional=True)
base.URI_FLAG.RemoveFromParser(parser)
def Run(self, args):
api_ref = args.CONCEPTS.api.Parse()
return apis.ApiClient().GetIamPolicy(api_ref)

View File

@@ -0,0 +1,73 @@
# -*- coding: utf-8 -*- #
# Copyright 2020 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""api-gateway gateways list command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.api_gateway import apis
from googlecloudsdk.api_lib.util import common_args
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.api_gateway import resource_args
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class List(base.ListCommand):
"""List APIs."""
detailed_help = {
'DESCRIPTION':
'{description}',
'EXAMPLES':
"""\
To list all apis, run:
$ {command}
""",
}
LIST_FORMAT = """
table(
name.segment(5):label=API_ID,
displayName,
managedService,
state,
createTime.date()
)
"""
@staticmethod
def Args(parser):
resource_args.AddLocationResourceArg(parser,
'apis will be listed from',
default='global')
# Remove unneeded list-related flags from parser
base.URI_FLAG.RemoveFromParser(parser)
parser.display_info.AddFormat(List.LIST_FORMAT)
def Run(self, args):
parent_ref = args.CONCEPTS.location.Parse()
sort_by = common_args.ParseSortByArg(args.sort_by)
return apis.ApiClient().List(parent_ref.RelativeName(),
filters=args.filter,
limit=args.limit,
page_size=args.page_size,
sort_by=sort_by)

View File

@@ -0,0 +1,58 @@
# -*- coding: utf-8 -*- #
# Copyright 2020 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command to add IAM policy binding for a model."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.api_gateway import apis
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.api_gateway import common_flags
from googlecloudsdk.command_lib.api_gateway import resource_args
from googlecloudsdk.command_lib.iam import iam_util
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class RemoveIamPolicyBinding(base.Command):
"""Remove IAM policy binding to a gateway."""
detailed_help = {
'EXAMPLES':
"""\
To remove an IAM policy binding for the role of 'roles/editor' for the
user 'test-user@gmail.com' on API 'my-api', run:
$ {command} my-api --member='user:test-user@gmail.com'
--role='roles/editor'
""",
}
@staticmethod
def Args(parser):
resource_args.AddApiResourceArg(parser,
'IAM policy binding will be added to',
positional=True)
iam_util.AddArgsForRemoveIamPolicyBinding(
parser,
common_flags.GatewayIamRolesCompleter)
def Run(self, args):
api_ref = args.CONCEPTS.api.Parse()
return apis.ApiClient().RemoveIamPolicyBinding(
api_ref, args.member, args.role)

View File

@@ -0,0 +1,92 @@
# -*- coding: utf-8 -*- #
# Copyright 2020 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""`gcloud api-gateway apis update` command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from googlecloudsdk.api_lib.api_gateway import apis
from googlecloudsdk.api_lib.api_gateway import operations
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.api_gateway import common_flags
from googlecloudsdk.command_lib.api_gateway import operations_util
from googlecloudsdk.command_lib.api_gateway import resource_args
from googlecloudsdk.command_lib.util.args import labels_util
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class Update(base.UpdateCommand):
"""Update an API Gateway API."""
detailed_help = {
'DESCRIPTION':
"""\
{description}
NOTE: Only the display name and labels attributes are mutable on an API.
""",
'EXAMPLES':
"""\
To update the display name of an API, run:
$ {command} my-api --display-name="New Display Name"
NOTE: Only the display name and labels attributes are mutable on an API.
""",
}
@staticmethod
def Args(parser):
base.ASYNC_FLAG.AddToParser(parser)
common_flags.AddDisplayNameArg(parser)
labels_util.AddUpdateLabelsFlags(parser)
resource_args.AddApiResourceArg(parser, 'updated', positional=True)
def Run(self, args):
api_ref = args.CONCEPTS.api.Parse()
api_client = apis.ApiClient()
api, mask = self.ProcessUpdates(api_client.Get(api_ref), args)
resp = api_client.Update(api, update_mask=mask)
return operations_util.PrintOperationResult(
resp.name,
operations.OperationsClient(),
service=api_client.service,
wait_string='Waiting for API [{}] to be updated'.format(api_ref.Name()),
is_async=args.async_)
def ProcessUpdates(self, api, args):
update_mask = []
labels_update = labels_util.ProcessUpdateArgsLazy(
args,
api.LabelsValue,
lambda: api.labels)
if labels_update.needs_update:
api.labels = labels_update.labels
update_mask.append('labels')
if args.display_name:
api.displayName = args.display_name
update_mask.append('displayName')
return api, ','.join(update_mask)

View File

@@ -0,0 +1,29 @@
# -*- coding: utf-8 -*- #
# Copyright 2019 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Package for the apigateway/gateways CLI subcommands."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
class Gateways(base.Group):
"""Manage Cloud API Gateway Gateways.
Commands for managing Cloud API Gateway Gateways.
"""

View File

@@ -0,0 +1,57 @@
# -*- coding: utf-8 -*- #
# Copyright 2020 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command to add IAM policy binding for a model."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.api_gateway import gateways
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.api_gateway import common_flags
from googlecloudsdk.command_lib.api_gateway import resource_args
from googlecloudsdk.command_lib.iam import iam_util
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class AddIamPolicyBinding(base.Command):
"""Add IAM policy binding to a gateway."""
detailed_help = {
'EXAMPLES':
"""\
To add an IAM policy binding for the role of 'roles/editor' for the
user 'test-user@gmail.com' on the gateway 'my-gateway', run:
$ {command} my-gateway --member='user:test-user@gmail.com' --role='roles/editor
"""
}
@staticmethod
def Args(parser):
resource_args.AddGatewayResourceArg(parser,
'IAM policy binding will be added to',
positional=True)
iam_util.AddArgsForAddIamPolicyBinding(
parser,
common_flags.GatewayIamRolesCompleter)
def Run(self, args):
gateway_ref = args.CONCEPTS.gateway.Parse()
return gateways.GatewayClient().AddIamPolicyBinding(
gateway_ref, args.member, args.role)

View File

@@ -0,0 +1,73 @@
# -*- coding: utf-8 -*- #
# Copyright 2019 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""`gcloud api-gateway gateways create` command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.api_gateway import gateways
from googlecloudsdk.api_lib.api_gateway import operations
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.api_gateway import common_flags
from googlecloudsdk.command_lib.api_gateway import operations_util
from googlecloudsdk.command_lib.api_gateway import resource_args
from googlecloudsdk.command_lib.util.args import labels_util
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class Create(base.CreateCommand):
"""Create a new gateway."""
detailed_help = {
'DESCRIPTION':
'{description}',
'EXAMPLES':
"""\
To create a gateway in 'us-central1' run:
$ {command} my-gateway --api=my-api --api-config=my-config --location=us-central1
""",
}
@staticmethod
def Args(parser):
base.ASYNC_FLAG.AddToParser(parser)
common_flags.AddDisplayNameArg(parser)
labels_util.AddCreateLabelsFlags(parser)
resource_args.AddGatewayApiConfigResourceArgs(parser, 'created')
def Run(self, args):
gateway_ref = args.CONCEPTS.gateway.Parse()
api_config_ref = args.CONCEPTS.api_config.Parse()
gateways_client = gateways.GatewayClient()
resp = gateways_client.Create(gateway_ref,
api_config_ref,
display_name=args.display_name,
labels=args.labels)
wait = 'Waiting for API Gateway [{}] to be created with [{}] config'.format(
gateway_ref.Name(), api_config_ref.RelativeName())
return operations_util.PrintOperationResult(
resp.name,
operations.OperationsClient(),
service=gateways_client.service,
wait_string=wait,
is_async=args.async_)

View File

@@ -0,0 +1,91 @@
# -*- coding: utf-8 -*- #
# Copyright 2019 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""`gcloud api-gateway gateways delete` command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.api_gateway import gateways
from googlecloudsdk.api_lib.api_gateway import operations
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.api_gateway import operations_util
from googlecloudsdk.command_lib.api_gateway import resource_args
from googlecloudsdk.core.console import console_io
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class Delete(base.DeleteCommand):
"""Delete an API Gateway."""
detailed_help = {
'DESCRIPTION':
'{description}',
'EXAMPLES':
"""\
To delete a gateway 'my-gateway' in 'us-central1', run:
$ {command} my-gateway --location=us-central1
""",
}
@staticmethod
def Args(parser):
"""Args is called by calliope to gather arguments for this command.
Args:
parser: An argparse parser that you can use to add arguments that go
on the command line after this command. Positional arguments are
allowed.
"""
base.ASYNC_FLAG.AddToParser(parser)
resource_args.AddGatewayResourceArg(parser, 'deleted', positional=True)
def Run(self, args):
"""Run 'api-gateway gateways delete'.
Args:
args: argparse.Namespace, The arguments that this command was invoked
with.
Raises:
OperationCancelledError
Returns:
The response from the Delete API call.
"""
gateway_ref = args.CONCEPTS.gateway.Parse()
# Prompt with a warning before continuing.
console_io.PromptContinue(
message='Are you sure? This will delete the gateway \'{}\', '
'along with all of the associated consumer '
'information.'.format(gateway_ref.RelativeName()),
prompt_string='Continue anyway',
default=True,
throw_if_unattended=True,
cancel_on_no=True)
resp = gateways.GatewayClient().Delete(gateway_ref)
wait = 'Waiting for API Gateway [{}] to be deleted'.format(
gateway_ref.Name())
return operations_util.PrintOperationResult(
resp.name, operations.OperationsClient(), wait_string=wait,
is_async=args.async_)

View File

@@ -0,0 +1,51 @@
# -*- coding: utf-8 -*- #
# Copyright 2019 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""`gcloud api-gateway gateways describe` command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.api_gateway import gateways
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.api_gateway import resource_args
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class Describe(base.DescribeCommand):
"""Show details about a specific gateway."""
detailed_help = {
'DESCRIPTION':
'{description}',
'EXAMPLES':
"""\
To show details about a Gateway in us-central1, run:
$ {command} my-gateway --location=us-central1
""",
}
@staticmethod
def Args(parser):
resource_args.AddGatewayResourceArg(parser, 'created', positional=True)
def Run(self, args):
gateway_ref = args.CONCEPTS.gateway.Parse()
return gateways.GatewayClient().Get(gateway_ref)

View File

@@ -0,0 +1,53 @@
# -*- coding: utf-8 -*- #
# Copyright 2020 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command for getting IAM policies for gateways."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.api_gateway import gateways
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.api_gateway import resource_args
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class GetIamPolicy(base.ListCommand):
"""Get the IAM policy for a gateway."""
detailed_help = {
'DESCRIPTION':
'{description}',
'EXAMPLES':
"""\
To print the IAM policy for a given gateway, run:
$ {command} my-gateway --location=us-central1
""",
}
@staticmethod
def Args(parser):
resource_args.AddGatewayResourceArg(parser, 'for which to get IAM policy',
positional=True)
base.URI_FLAG.RemoveFromParser(parser)
def Run(self, args):
gateway_ref = args.CONCEPTS.gateway.Parse()
return gateways.GatewayClient().GetIamPolicy(gateway_ref)

View File

@@ -0,0 +1,77 @@
# -*- coding: utf-8 -*- #
# Copyright 2019 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""api-gateway gateways list command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.api_gateway import gateways
from googlecloudsdk.api_lib.util import common_args
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.api_gateway import resource_args
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class List(base.ListCommand):
"""List API Gateways."""
detailed_help = {
'DESCRIPTION':
'{description}',
'EXAMPLES':
"""\
To list all gateways, run:
$ {command}
To list all gateways within the 'us-central1' location:
$ {command} --location=us-central1
""",
}
LIST_FORMAT = """
table(
name.segment(5):label=GATEWAY_ID,
name.segment(3):label=LOCATION,
displayName,
state,
createTime.date(),
updateTime.date()
)"""
@staticmethod
def Args(parser):
resource_args.AddLocationResourceArg(parser,
'gateways will be listed from',
default='-',
required=False)
# Remove unneeded list-related flags from parser
base.URI_FLAG.RemoveFromParser(parser)
parser.display_info.AddFormat(List.LIST_FORMAT)
def Run(self, args):
parent_ref = args.CONCEPTS.location.Parse()
sort_by = common_args.ParseSortByArg(args.sort_by)
return gateways.GatewayClient().List(parent_ref.RelativeName(),
filters=args.filter,
limit=args.limit,
page_size=args.page_size,
sort_by=sort_by)

View File

@@ -0,0 +1,59 @@
# -*- coding: utf-8 -*- #
# Copyright 2020 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command to add IAM policy binding for a model."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.api_gateway import gateways
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.api_gateway import common_flags
from googlecloudsdk.command_lib.api_gateway import resource_args
from googlecloudsdk.command_lib.iam import iam_util
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class RemoveIamPolicyBinding(base.Command):
"""Remove IAM policy binding from a gateway."""
detailed_help = {
'EXAMPLES':
"""\
To remove an IAM policy binding for the role of 'roles/editor' for the
user 'test-user@gmail.com' on Gateway 'my-gateway' in us-central1, run:
$ {command} my-gateway --location='us-central1'
--member='user:test-user@gmail.com'
--role='roles/editor'
""",
}
@staticmethod
def Args(parser):
resource_args.AddGatewayResourceArg(parser,
'IAM policy binding will be added to',
positional=True)
iam_util.AddArgsForRemoveIamPolicyBinding(
parser,
common_flags.GatewayIamRolesCompleter)
def Run(self, args):
gateway_ref = args.CONCEPTS.gateway.Parse()
return gateways.GatewayClient().RemoveIamPolicyBinding(
gateway_ref, args.member, args.role)

View File

@@ -0,0 +1,92 @@
# -*- coding: utf-8 -*- #
# Copyright 2019 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""`gcloud api-gateway gateways update` command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.api_gateway import gateways
from googlecloudsdk.api_lib.api_gateway import operations
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.api_gateway import common_flags
from googlecloudsdk.command_lib.api_gateway import operations_util
from googlecloudsdk.command_lib.api_gateway import resource_args
from googlecloudsdk.command_lib.util.args import labels_util
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class Update(base.UpdateCommand):
"""Update an API Gateway."""
detailed_help = {
'EXAMPLES':
"""\
To update the display name of a gateway, run:
$ {command} my-gateway --location=us-central1 --display-name="New Display Name"
""",
}
@staticmethod
def Args(parser):
base.ASYNC_FLAG.AddToParser(parser)
common_flags.AddDisplayNameArg(parser)
labels_util.AddUpdateLabelsFlags(parser)
resource_args.AddGatewayApiConfigResourceArgs(parser, 'updated',
api_config_required=False)
def Run(self, args):
gateway_ref = args.CONCEPTS.gateway.Parse()
gateways_client = gateways.GatewayClient()
gateway, mask = self.ProcessUpdates(gateways_client.Get(gateway_ref), args)
resp = gateways_client.Update(gateway, update_mask=mask)
wait = 'Waiting for API Gateway [{}] to be updated'.format(
gateway_ref.Name())
return operations_util.PrintOperationResult(
resp.name,
operations.OperationsClient(),
service=gateways_client.service,
wait_string=wait,
is_async=args.async_)
def ProcessUpdates(self, gateway, args):
api_config_ref = args.CONCEPTS.api_config.Parse()
update_mask = []
labels_update = labels_util.ProcessUpdateArgsLazy(
args,
gateway.LabelsValue,
lambda: gateway.labels)
if labels_update.needs_update:
gateway.labels = labels_update.labels
update_mask.append('labels')
if api_config_ref:
gateway.apiConfig = api_config_ref.RelativeName()
update_mask.append('apiConfig')
if args.display_name:
gateway.displayName = args.display_name
update_mask.append('displayName')
return gateway, ','.join(update_mask)

View File

@@ -0,0 +1,29 @@
# -*- coding: utf-8 -*- #
# Copyright 2019 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The operations command group for the Cloud API Gateways CLI."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
class Operations(base.Group):
"""Manage operations for Cloud API Gateways.
Commands for managing operations for Google API Gateways.
"""

View File

@@ -0,0 +1,71 @@
# -*- coding: utf-8 -*- #
# Copyright 2020 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""`gcloud api-gateway operations cancel` command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.api_gateway import operations
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.api_gateway import operations_util
from googlecloudsdk.command_lib.api_gateway import resource_args
from googlecloudsdk.core.console import console_io
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class Cancel(base.Command):
"""Cancel a Cloud API Gateway operation."""
detailed_help = {
'DESCRIPTION':
'{description}',
'EXAMPLES':
"""\
To cancel a Cloud API Gateway operation named ``NAME'' in the ``us-central1''
region, run:
$ {command} NAME --location=us-central1
To cancel a Cloud API Gateway operation with a resource name of ``RESOURCE'',
run:
$ {command} RESOURCE
"""
}
@staticmethod
def Args(parser):
resource_args.AddOperationResourceArgs(parser, 'cancel')
def Run(self, args):
client = operations.OperationsClient()
operation_ref = args.CONCEPTS.operation.Parse()
console_io.PromptContinue(
message='The operation [{}] will be cancelled.'.format(
operation_ref.RelativeName()),
throw_if_unattended=True,
cancel_on_no=True)
client.Cancel(operation_ref)
operations_util.PrintOperationResultWithWaitEpilogue(
operation_ref,
'Operation cancellation requested')

View File

@@ -0,0 +1,60 @@
# -*- coding: utf-8 -*- #
# Copyright 2019 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""`gcloud api-gateway operations describe` command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.api_gateway import operations
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.api_gateway import resource_args
from googlecloudsdk.core import exceptions
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class Describe(base.DescribeCommand):
"""Show details about the Cloud API Gateway operation."""
detailed_help = {
'DESCRIPTION':
'{description}',
'EXAMPLES':
"""\
To describe a Cloud API Gateway operation named ``NAME'' in the ``us-central1''
region, run:
$ {command} NAME --location=us-central1
To describe a Cloud API Gateway operation with a resource name of ``RESOURCE'',
run:
$ {command} RESOURCE
"""
}
@staticmethod
def Args(parser):
resource_args.AddOperationResourceArgs(parser, 'describe')
def Run(self, args):
client = operations.OperationsClient()
operation_ref = args.CONCEPTS.operation.Parse()
return client.Get(operation_ref)

View File

@@ -0,0 +1,77 @@
# -*- coding: utf-8 -*- #
# Copyright 2020 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""`gcloud api-gateway operations list` command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.api_gateway import operations
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.api_gateway import resource_args
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class List(base.ListCommand):
"""List API Gateway operations."""
detailed_help = {
'DESCRIPTION':
'{description}',
'EXAMPLES':
"""\
To list all Cloud API Gateway operations, run:
$ {command}
To list all Cloud API Gateway operations in the ``us-central1'' region, run:
$ {command} --location=us-central1
"""
}
@staticmethod
def Args(parser):
# --sort-by and --uri are inherited for all ListCommands but are not
# implemented here.
base.SORT_BY_FLAG.RemoveFromParser(parser)
base.URI_FLAG.RemoveFromParser(parser)
resource_args.AddLocationResourceArg(parser,
'operations will be listed from',
default='-')
parser.display_info.AddFormat("""
table(
name.segment(5):label=OPERATION_ID,
name.segment(3):label=LOCATION,
done,
metadata.requestedCancellation:label=CANCELLED,
metadata.createTime.date(),
metadata.verb,
metadata.target
)
""")
parser.display_info.AddCacheUpdater(None)
def Run(self, args):
parent_ref = args.CONCEPTS.location.Parse()
return operations.OperationsClient().List(parent_ref.RelativeName(),
filters=args.filter,
limit=args.limit,
page_size=args.page_size)

View File

@@ -0,0 +1,75 @@
# -*- coding: utf-8 -*- #
# Copyright 2020 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""`gcloud api-gateway operations wait` command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.api_gateway import operations
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.api_gateway import resource_args
from googlecloudsdk.core import log
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class Wait(base.Command):
"""Wait for a Cloud API Gateway operation to complete."""
detailed_help = {
'DESCRIPTION':
'{description}',
'EXAMPLES':
"""\
To wait for a Cloud API Gateway operation named ``NAME'' in the ``us-central1''
region, run:
$ {command} NAME --location=us-central1
To wait for a Cloud API Gateway operation with a resource name of ``RESOURCE'',
run:
$ {command} RESOURCE
"""
}
@staticmethod
def Args(parser):
resource_args.AddOperationResourceArgs(parser, 'poll')
def Run(self, args):
client = operations.OperationsClient()
operation_ref = args.CONCEPTS.operation.Parse()
# To give a better message for already-completed operations, get the
# operation here and check if it's already completed.
operation = client.Get(operation_ref)
if operation.done:
msg_prefix = 'Operation has already completed.'
else:
# No need to check for the result, errors and timeouts are handled already
client.WaitForOperation(operation_ref)
msg_prefix = 'Operation completed successfully.'
log.status.Print('{} Use the following command for more details:\n\n'
'gcloud api-gateway operations describe {}\n'.format(
msg_prefix,
operation_ref.RelativeName()))