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,42 @@
# -*- coding: utf-8 -*- #
# Copyright 2015 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.
"""Commands for reading and manipulating health checks."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.ReleaseTracks(
base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA, base.ReleaseTrack.GA)
class HealthChecks(base.Group):
"""Read and manipulate health checks for load balanced instances."""
HealthChecks.category = base.LOAD_BALANCING_CATEGORY
HealthChecks.detailed_help = {
'DESCRIPTION': """
Read and manipulate health checks for load balanced instances.
For more information about health checks, see the
[health checks documentation](https://cloud.google.com/load-balancing/docs/health-check-concepts).
See also: [Health checks API](https://cloud.google.com/compute/docs/reference/rest/v1/healthChecks)
and [Regional health checks API](https://cloud.google.com/compute/docs/reference/rest/v1/regionHealthChecks).
""",
}

View File

@@ -0,0 +1,30 @@
# -*- coding: utf-8 -*- #
# Copyright 2015 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.
"""Commands for creating health checks."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
class HealthChecksCreate(base.Group):
"""Create (non-legacy) health checks for load balanced instances."""
HealthChecksCreate.detailed_help = {
'brief': ('Create (non-legacy) health checks for load balanced instances')
}

View File

@@ -0,0 +1,138 @@
# -*- 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 creating gRPC health checks."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.compute import base_classes
from googlecloudsdk.api_lib.compute import health_checks_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.calliope import exceptions
from googlecloudsdk.command_lib.compute import completers
from googlecloudsdk.command_lib.compute import scope as compute_scope
from googlecloudsdk.command_lib.compute.health_checks import flags
def _DetailedHelp():
return {
'brief':
'Create a gRPC health check to monitor load balanced instances.',
'DESCRIPTION':
"""\
*{command}* is used to create a non-legacy health check using the gRPC
protocol. You can use this health check for Google Cloud load
balancers or for managed instance group autohealing. For more information,
see the health checks overview at:
[](https://cloud.google.com/load-balancing/docs/health-check-concepts)
""",
}
def _Args(parser, include_log_config):
"""Set up arguments to create a gRPC HealthCheck."""
parser.display_info.AddFormat(flags.DEFAULT_LIST_FORMAT)
flags.HealthCheckArgument('gRPC').AddArgument(parser, operation_type='create')
health_checks_utils.AddGrpcRelatedCreationArgs(parser)
health_checks_utils.AddProtocolAgnosticCreationArgs(parser, 'gRPC')
if include_log_config:
health_checks_utils.AddHealthCheckLoggingRelatedArgs(parser)
parser.display_info.AddCacheUpdater(completers.HealthChecksCompleterAlpha)
def _Run(args, holder, include_log_config):
"""Issues the request necessary for adding the health check."""
client = holder.client
messages = client.messages
# Check that port related flags are set for gRPC health check.
args_unset = not (args.port or args.use_serving_port)
if args_unset:
raise exceptions.OneOfArgumentsRequiredException([
'--port', '--use-serving-port'
], 'Either --port or --use-serving-port must be set for gRPC health check.')
health_check_ref = flags.HealthCheckArgument('gRPC').ResolveAsResource(
args, holder.resources, default_scope=compute_scope.ScopeEnum.GLOBAL)
grpc_health_check = messages.GRPCHealthCheck(
port=args.port, grpcServiceName=args.grpc_service_name)
health_checks_utils.ValidateAndAddPortSpecificationToGRPCHealthCheck(
args, grpc_health_check)
if health_checks_utils.IsRegionalHealthCheckRef(health_check_ref):
request = messages.ComputeRegionHealthChecksInsertRequest(
healthCheck=messages.HealthCheck(
name=health_check_ref.Name(),
description=args.description,
type=messages.HealthCheck.TypeValueValuesEnum.GRPC,
grpcHealthCheck=grpc_health_check,
checkIntervalSec=args.check_interval,
timeoutSec=args.timeout,
healthyThreshold=args.healthy_threshold,
unhealthyThreshold=args.unhealthy_threshold),
project=health_check_ref.project,
region=health_check_ref.region)
collection = client.apitools_client.regionHealthChecks
else:
request = messages.ComputeHealthChecksInsertRequest(
healthCheck=messages.HealthCheck(
name=health_check_ref.Name(),
description=args.description,
type=messages.HealthCheck.TypeValueValuesEnum.GRPC,
grpcHealthCheck=grpc_health_check,
checkIntervalSec=args.check_interval,
timeoutSec=args.timeout,
healthyThreshold=args.healthy_threshold,
unhealthyThreshold=args.unhealthy_threshold),
project=health_check_ref.project)
collection = client.apitools_client.healthChecks
if include_log_config:
request.healthCheck.logConfig = health_checks_utils.CreateLogConfig(
client, args)
return client.MakeRequests([(collection, 'Insert', request)])
@base.ReleaseTracks(base.ReleaseTrack.GA)
class Create(base.CreateCommand):
"""Create a gRPC health check."""
detailed_help = _DetailedHelp()
_include_log_config = True
@classmethod
def Args(cls, parser):
_Args(parser, cls._include_log_config)
def Run(self, args):
holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
return _Run(args, holder, self._include_log_config)
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class CreateBeta(Create):
pass
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class CreateAlpha(CreateBeta):
pass

View File

@@ -0,0 +1,186 @@
# -*- coding: utf-8 -*- #
# Copyright 2025 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 creating gRPC with TLS health checks."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.compute import base_classes
from googlecloudsdk.api_lib.compute import health_checks_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.calliope import exceptions
from googlecloudsdk.command_lib.compute import completers
from googlecloudsdk.command_lib.compute import scope as compute_scope
from googlecloudsdk.command_lib.compute.health_checks import flags
def _DetailedHelp():
return {
'brief': (
'Create a gRPC with TLS health check to monitor load balanced'
' instances.'
),
'DESCRIPTION': """\
*{command}* is used to create a non-legacy health check using the gRPC with TLS
protocol. You can use this health check for Google Cloud load
balancers or for managed instance group autohealing. For more information,
see the health checks overview at:
[](https://cloud.google.com/load-balancing/docs/health-check-concepts)
""",
}
def _Args(parser, include_log_config):
"""Set up arguments to create a gRPC with TLS HealthCheck."""
parser.display_info.AddFormat(flags.DEFAULT_LIST_FORMAT)
flags.HealthCheckArgument('gRPC with TLS').AddArgument(
parser, operation_type='create'
)
health_checks_utils.AddGrpcRelatedCreationArgs(parser)
health_checks_utils.AddProtocolAgnosticCreationArgs(parser, 'gRPC with TLS')
if include_log_config:
health_checks_utils.AddHealthCheckLoggingRelatedArgs(parser)
parser.display_info.AddCacheUpdater(completers.HealthChecksCompleterAlpha)
def _Run(args, holder, include_log_config):
"""Issues the request necessary for adding the health check."""
client = holder.client
messages = client.messages
# Check that port related flags are set for gRPC with TLS health check.
args_unset = not (args.port or args.use_serving_port)
if args_unset:
raise exceptions.OneOfArgumentsRequiredException(
['--port', '--use-serving-port'],
'Either --port or --use-serving-port must be set for gRPC with TLS'
' health check.',
)
health_check_ref = flags.HealthCheckArgument(
'gRPC with TLS'
).ResolveAsResource(
args, holder.resources, default_scope=compute_scope.ScopeEnum.GLOBAL
)
grpc_tls_health_check = messages.GRPCTLSHealthCheck(
port=args.port, grpcServiceName=args.grpc_service_name
)
health_checks_utils.ValidateAndAddPortSpecificationToGRPCHealthCheck(
args, grpc_tls_health_check
)
if health_checks_utils.IsRegionalHealthCheckRef(health_check_ref):
request = messages.ComputeRegionHealthChecksInsertRequest(
healthCheck=messages.HealthCheck(
name=health_check_ref.Name(),
description=args.description,
type=messages.HealthCheck.TypeValueValuesEnum.GRPC_WITH_TLS,
grpcTlsHealthCheck=grpc_tls_health_check,
checkIntervalSec=args.check_interval,
timeoutSec=args.timeout,
healthyThreshold=args.healthy_threshold,
unhealthyThreshold=args.unhealthy_threshold,
),
project=health_check_ref.project,
region=health_check_ref.region,
)
collection = client.apitools_client.regionHealthChecks
else:
request = messages.ComputeHealthChecksInsertRequest(
healthCheck=messages.HealthCheck(
name=health_check_ref.Name(),
description=args.description,
type=messages.HealthCheck.TypeValueValuesEnum.GRPC_WITH_TLS,
grpcTlsHealthCheck=grpc_tls_health_check,
checkIntervalSec=args.check_interval,
timeoutSec=args.timeout,
healthyThreshold=args.healthy_threshold,
unhealthyThreshold=args.unhealthy_threshold,
),
project=health_check_ref.project,
)
collection = client.apitools_client.healthChecks
if include_log_config:
request.healthCheck.logConfig = health_checks_utils.CreateLogConfig(
client, args)
return client.MakeRequests([(collection, 'Insert', request)])
@base.DefaultUniverseOnly
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class CreateAlpha(base.CreateCommand):
"""Create a gRPC with TLS health check."""
detailed_help = _DetailedHelp()
_include_log_config = True
@classmethod
def Args(cls, parser):
_Args(parser, cls._include_log_config)
def Run(self, args):
return _Run(
args,
base_classes.ComputeApiHolder(self.ReleaseTrack()),
self._include_log_config,
)
@base.DefaultUniverseOnly
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class CreateBeta(base.CreateCommand):
"""Create a gRPC with TLS health check."""
detailed_help = _DetailedHelp()
_include_log_config = True
@classmethod
def Args(cls, parser):
_Args(parser, cls._include_log_config)
def Run(self, args):
return _Run(
args,
base_classes.ComputeApiHolder(self.ReleaseTrack()),
self._include_log_config,
)
@base.DefaultUniverseOnly
@base.ReleaseTracks(base.ReleaseTrack.GA)
class CreateGa(base.CreateCommand):
"""Create a gRPC with TLS health check."""
detailed_help = _DetailedHelp()
_include_log_config = True
@classmethod
def Args(cls, parser):
_Args(parser, cls._include_log_config)
def Run(self, args):
return _Run(
args,
base_classes.ComputeApiHolder(self.ReleaseTrack()),
self._include_log_config,
)

View File

@@ -0,0 +1,175 @@
# -*- coding: utf-8 -*- #
# Copyright 2015 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 creating HTTP health checks."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.compute import base_classes
from googlecloudsdk.api_lib.compute import health_checks_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.compute import completers
from googlecloudsdk.command_lib.compute import scope as compute_scope
from googlecloudsdk.command_lib.compute.health_checks import flags
def _DetailedHelp():
return {
'brief':
'Create a HTTP health check to monitor load balanced instances.',
'DESCRIPTION':
"""\
*{command}* is used to create a non-legacy health check using the HTTP
protocol. You can use this health check for Google Cloud load
balancers or for managed instance group autohealing. For more information,
see the health checks overview at:
[](https://cloud.google.com/load-balancing/docs/health-check-concepts)
""",
}
def _Args(
parser,
include_log_config,
include_weighted_load_balancing,
include_source_regions,
):
"""Set up arguments to create a HTTP HealthCheck."""
parser.display_info.AddFormat(flags.DEFAULT_LIST_FORMAT)
flags.HealthCheckArgument('HTTP').AddArgument(parser, operation_type='create')
health_checks_utils.AddHttpRelatedCreationArgs(
parser, include_weighted_load_balancing)
health_checks_utils.AddProtocolAgnosticCreationArgs(parser, 'HTTP')
health_checks_utils.AddHttpRelatedResponseArg(parser)
if include_source_regions:
health_checks_utils.AddHealthCheckSourceRegionsRelatedArgs(parser)
if include_log_config:
health_checks_utils.AddHealthCheckLoggingRelatedArgs(parser)
parser.display_info.AddCacheUpdater(completers.HealthChecksCompleterAlpha)
def _Run(
args,
holder,
include_log_config,
include_weighted_load_balancing,
include_source_regions,
):
"""Issues the request necessary for adding the health check."""
client = holder.client
messages = client.messages
health_check_ref = flags.HealthCheckArgument('HTTP').ResolveAsResource(
args, holder.resources, default_scope=compute_scope.ScopeEnum.GLOBAL)
proxy_header = messages.HTTPHealthCheck.ProxyHeaderValueValuesEnum(
args.proxy_header)
http_health_check = messages.HTTPHealthCheck(
host=args.host,
port=args.port,
portName=args.port_name,
requestPath=args.request_path,
proxyHeader=proxy_header,
response=args.response)
if include_weighted_load_balancing and args.weight_report_mode:
weight_report_mode = messages.HTTPHealthCheck.WeightReportModeValueValuesEnum(
args.weight_report_mode)
http_health_check.weightReportMode = weight_report_mode
health_checks_utils.ValidateAndAddPortSpecificationToHealthCheck(
args, http_health_check)
if health_checks_utils.IsRegionalHealthCheckRef(health_check_ref):
request = messages.ComputeRegionHealthChecksInsertRequest(
healthCheck=messages.HealthCheck(
name=health_check_ref.Name(),
description=args.description,
type=messages.HealthCheck.TypeValueValuesEnum.HTTP,
httpHealthCheck=http_health_check,
checkIntervalSec=args.check_interval,
timeoutSec=args.timeout,
healthyThreshold=args.healthy_threshold,
unhealthyThreshold=args.unhealthy_threshold),
project=health_check_ref.project,
region=health_check_ref.region)
collection = client.apitools_client.regionHealthChecks
else:
request = messages.ComputeHealthChecksInsertRequest(
healthCheck=messages.HealthCheck(
name=health_check_ref.Name(),
description=args.description,
type=messages.HealthCheck.TypeValueValuesEnum.HTTP,
httpHealthCheck=http_health_check,
checkIntervalSec=args.check_interval,
timeoutSec=args.timeout,
healthyThreshold=args.healthy_threshold,
unhealthyThreshold=args.unhealthy_threshold),
project=health_check_ref.project)
collection = client.apitools_client.healthChecks
if include_log_config:
request.healthCheck.logConfig = health_checks_utils.CreateLogConfig(
client, args)
if include_source_regions and (args.source_regions is not None):
request.healthCheck.sourceRegions = args.source_regions
return client.MakeRequests([(collection, 'Insert', request)])
@base.ReleaseTracks(base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class Create(base.CreateCommand):
"""Create a HTTP health check."""
detailed_help = _DetailedHelp()
_include_log_config = True
_include_weighted_load_balancing = False
_include_source_regions = True
@classmethod
def Args(cls, parser):
_Args(
parser,
cls._include_log_config,
cls._include_weighted_load_balancing,
cls._include_source_regions,
)
def Run(self, args):
holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
return _Run(
args,
holder,
self._include_log_config,
self._include_weighted_load_balancing,
self._include_source_regions,
)
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class CreateBeta(Create):
_include_weighted_load_balancing = False
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class CreateAlpha(CreateBeta):
_include_weighted_load_balancing = True

View File

@@ -0,0 +1,153 @@
# -*- coding: utf-8 -*- #
# Copyright 2015 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 creating HTTP2 health checks."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.compute import base_classes
from googlecloudsdk.api_lib.compute import health_checks_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.compute import completers
from googlecloudsdk.command_lib.compute import scope as compute_scope
from googlecloudsdk.command_lib.compute.health_checks import flags
def _DetailedHelp():
return {
'brief':
'Create a HTTP2 health check to monitor load balanced instances',
'DESCRIPTION':
"""\
*{command}* is used to create a non-legacy health check using the
HTTP/2 protocol. You can use this health check for Google Cloud
load balancers or for managed instance group autohealing.
For more information, see the health checks overview at:
[](https://cloud.google.com/load-balancing/docs/health-check-concepts)
""",
'EXAMPLES':
"""\
To create a HTTP2 health check with default options, run:
$ {command} my-health-check-name
""",
}
def _Args(parser, include_log_config, include_weighted_load_balancing):
"""Set up arguments to create an HTTP2 HealthCheck."""
parser.display_info.AddFormat(flags.DEFAULT_LIST_FORMAT)
flags.HealthCheckArgument('HTTP2').AddArgument(
parser, operation_type='create')
health_checks_utils.AddHttpRelatedCreationArgs(
parser, include_weighted_load_balancing)
health_checks_utils.AddHttpRelatedResponseArg(parser)
health_checks_utils.AddProtocolAgnosticCreationArgs(parser, 'HTTP2')
if include_log_config:
health_checks_utils.AddHealthCheckLoggingRelatedArgs(parser)
parser.display_info.AddCacheUpdater(completers.HealthChecksCompleterAlpha)
def _Run(args, holder, include_log_config, include_weighted_load_balancing):
"""Issues the request necessary for adding the health check."""
client = holder.client
messages = client.messages
health_check_ref = flags.HealthCheckArgument('HTTP2').ResolveAsResource(
args, holder.resources, default_scope=compute_scope.ScopeEnum.GLOBAL)
proxy_header = messages.HTTP2HealthCheck.ProxyHeaderValueValuesEnum(
args.proxy_header)
http2_health_check = messages.HTTP2HealthCheck(
host=args.host,
port=args.port,
portName=args.port_name,
requestPath=args.request_path,
proxyHeader=proxy_header,
response=args.response)
if include_weighted_load_balancing and args.weight_report_mode:
weight_report_mode = messages.HTTP2HealthCheck.WeightReportModeValueValuesEnum(
args.weight_report_mode)
http2_health_check.weightReportMode = weight_report_mode
health_checks_utils.ValidateAndAddPortSpecificationToHealthCheck(
args, http2_health_check)
if health_checks_utils.IsRegionalHealthCheckRef(health_check_ref):
request = messages.ComputeRegionHealthChecksInsertRequest(
healthCheck=messages.HealthCheck(
name=health_check_ref.Name(),
description=args.description,
type=messages.HealthCheck.TypeValueValuesEnum.HTTP2,
http2HealthCheck=http2_health_check,
checkIntervalSec=args.check_interval,
timeoutSec=args.timeout,
healthyThreshold=args.healthy_threshold,
unhealthyThreshold=args.unhealthy_threshold,
),
project=health_check_ref.project,
region=health_check_ref.region)
collection = client.apitools_client.regionHealthChecks
else:
request = messages.ComputeHealthChecksInsertRequest(
healthCheck=messages.HealthCheck(
name=health_check_ref.Name(),
description=args.description,
type=messages.HealthCheck.TypeValueValuesEnum.HTTP2,
http2HealthCheck=http2_health_check,
checkIntervalSec=args.check_interval,
timeoutSec=args.timeout,
healthyThreshold=args.healthy_threshold,
unhealthyThreshold=args.unhealthy_threshold),
project=health_check_ref.project)
collection = client.apitools_client.healthChecks
if include_log_config:
request.healthCheck.logConfig = health_checks_utils.CreateLogConfig(
client, args)
return client.MakeRequests([(collection, 'Insert', request)])
@base.ReleaseTracks(base.ReleaseTrack.GA)
class Create(base.CreateCommand):
"""Create a HTTP2 health check."""
_include_log_config = True
_include_weighted_load_balancing = False
detailed_help = _DetailedHelp()
@classmethod
def Args(cls, parser):
_Args(parser, cls._include_log_config, cls._include_weighted_load_balancing)
def Run(self, args):
holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
return _Run(args, holder, self._include_log_config,
self._include_weighted_load_balancing)
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class CreateBeta(Create):
_include_weighted_load_balancing = False
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class CreateAlpha(CreateBeta):
_include_weighted_load_balancing = True

View File

@@ -0,0 +1,174 @@
# -*- coding: utf-8 -*- #
# Copyright 2015 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 creating HTTPS health checks."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.compute import base_classes
from googlecloudsdk.api_lib.compute import health_checks_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.compute import completers
from googlecloudsdk.command_lib.compute import scope as compute_scope
from googlecloudsdk.command_lib.compute.health_checks import flags
def _DetailedHelp():
return {
'brief':
'Create a HTTPS health check to monitor load balanced instances',
'DESCRIPTION':
"""\
*{command}* is used to create a non-legacy health check using the HTTPS
protocol. You can use this health check for Google Cloud
load balancers or for managed instance group autohealing. For more
information, see the health checks overview at:
[](https://cloud.google.com/load-balancing/docs/health-check-concepts)
""",
}
def _Args(
parser,
include_log_config,
include_weighted_load_balancing,
include_source_regions,
):
"""Set up arguments to create an HTTPS HealthCheck."""
parser.display_info.AddFormat(flags.DEFAULT_LIST_FORMAT)
flags.HealthCheckArgument('HTTPS').AddArgument(
parser, operation_type='create')
health_checks_utils.AddHttpRelatedCreationArgs(
parser, include_weighted_load_balancing)
health_checks_utils.AddProtocolAgnosticCreationArgs(parser, 'HTTPS')
health_checks_utils.AddHttpRelatedResponseArg(parser)
if include_source_regions:
health_checks_utils.AddHealthCheckSourceRegionsRelatedArgs(parser)
if include_log_config:
health_checks_utils.AddHealthCheckLoggingRelatedArgs(parser)
parser.display_info.AddCacheUpdater(completers.HealthChecksCompleterAlpha)
def _Run(
args,
holder,
include_log_config,
include_weighted_load_balancing,
include_source_regions,
):
"""Issues the request necessary for adding the health check."""
client = holder.client
messages = client.messages
health_check_ref = flags.HealthCheckArgument('HTTPS').ResolveAsResource(
args, holder.resources, default_scope=compute_scope.ScopeEnum.GLOBAL)
proxy_header = messages.HTTPSHealthCheck.ProxyHeaderValueValuesEnum(
args.proxy_header)
https_health_check = messages.HTTPSHealthCheck(
host=args.host,
port=args.port,
portName=args.port_name,
requestPath=args.request_path,
proxyHeader=proxy_header,
response=args.response)
if include_weighted_load_balancing and args.weight_report_mode:
weight_report_mode = messages.HTTPSHealthCheck.WeightReportModeValueValuesEnum(
args.weight_report_mode)
https_health_check.weightReportMode = weight_report_mode
health_checks_utils.ValidateAndAddPortSpecificationToHealthCheck(
args, https_health_check)
if health_checks_utils.IsRegionalHealthCheckRef(health_check_ref):
request = messages.ComputeRegionHealthChecksInsertRequest(
healthCheck=messages.HealthCheck(
name=health_check_ref.Name(),
description=args.description,
type=messages.HealthCheck.TypeValueValuesEnum.HTTPS,
httpsHealthCheck=https_health_check,
checkIntervalSec=args.check_interval,
timeoutSec=args.timeout,
healthyThreshold=args.healthy_threshold,
unhealthyThreshold=args.unhealthy_threshold),
project=health_check_ref.project,
region=health_check_ref.region)
collection = client.apitools_client.regionHealthChecks
else:
request = messages.ComputeHealthChecksInsertRequest(
healthCheck=messages.HealthCheck(
name=health_check_ref.Name(),
description=args.description,
type=messages.HealthCheck.TypeValueValuesEnum.HTTPS,
httpsHealthCheck=https_health_check,
checkIntervalSec=args.check_interval,
timeoutSec=args.timeout,
healthyThreshold=args.healthy_threshold,
unhealthyThreshold=args.unhealthy_threshold),
project=health_check_ref.project)
collection = client.apitools_client.healthChecks
if include_log_config:
request.healthCheck.logConfig = health_checks_utils.CreateLogConfig(
client, args)
if include_source_regions and (args.source_regions is not None):
request.healthCheck.sourceRegions = args.source_regions
return client.MakeRequests([(collection, 'Insert', request)])
@base.ReleaseTracks(base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class Create(base.CreateCommand):
"""Create a HTTPS health check."""
_include_log_config = True
_include_weighted_load_balancing = False
_include_source_regions = True
detailed_help = _DetailedHelp()
@classmethod
def Args(cls, parser):
_Args(
parser,
cls._include_log_config,
cls._include_weighted_load_balancing,
cls._include_source_regions,
)
def Run(self, args):
holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
return _Run(
args,
holder,
self._include_log_config,
self._include_weighted_load_balancing,
self._include_source_regions,
)
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class CreateBeta(Create):
_include_weighted_load_balancing = False
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class CreateAlpha(CreateBeta):
_include_weighted_load_balancing = True

View File

@@ -0,0 +1,132 @@
# -*- coding: utf-8 -*- #
# Copyright 2015 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 creating SSL health checks."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.compute import base_classes
from googlecloudsdk.api_lib.compute import health_checks_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.compute import scope as compute_scope
from googlecloudsdk.command_lib.compute.health_checks import flags
def _DetailedHelp():
return {
'brief':
'Create a SSL health check to monitor load balanced instances.',
'DESCRIPTION':
"""\
*{command}* is used to create a non-legacy health check using the SSL
protocol. You can use this health check for Google Cloud
load balancers or for managed instance group autohealing. For more
information, see the health checks overview at:
[](https://cloud.google.com/load-balancing/docs/health-check-concepts)
""",
}
def _Args(parser, include_log_config):
"""Set up arguments to create an SSL HealthCheck."""
parser.display_info.AddFormat(flags.DEFAULT_LIST_FORMAT)
flags.HealthCheckArgument('SSL').AddArgument(parser, operation_type='create')
health_checks_utils.AddTcpRelatedCreationArgs(parser)
health_checks_utils.AddProtocolAgnosticCreationArgs(parser, 'SSL')
if include_log_config:
health_checks_utils.AddHealthCheckLoggingRelatedArgs(parser)
def _Run(args, holder, include_log_config):
"""Issues the request necessary for adding the health check."""
client = holder.client
messages = client.messages
health_check_ref = flags.HealthCheckArgument('SSL').ResolveAsResource(
args, holder.resources, default_scope=compute_scope.ScopeEnum.GLOBAL)
proxy_header = messages.SSLHealthCheck.ProxyHeaderValueValuesEnum(
args.proxy_header)
ssl_health_check = messages.SSLHealthCheck(
request=args.request,
response=args.response,
port=args.port,
portName=args.port_name,
proxyHeader=proxy_header)
health_checks_utils.ValidateAndAddPortSpecificationToHealthCheck(
args, ssl_health_check)
if health_checks_utils.IsRegionalHealthCheckRef(health_check_ref):
request = messages.ComputeRegionHealthChecksInsertRequest(
healthCheck=messages.HealthCheck(
name=health_check_ref.Name(),
description=args.description,
type=messages.HealthCheck.TypeValueValuesEnum.SSL,
sslHealthCheck=ssl_health_check,
checkIntervalSec=args.check_interval,
timeoutSec=args.timeout,
healthyThreshold=args.healthy_threshold,
unhealthyThreshold=args.unhealthy_threshold),
project=health_check_ref.project,
region=health_check_ref.region)
collection = client.apitools_client.regionHealthChecks
else:
request = messages.ComputeHealthChecksInsertRequest(
healthCheck=messages.HealthCheck(
name=health_check_ref.Name(),
description=args.description,
type=messages.HealthCheck.TypeValueValuesEnum.SSL,
sslHealthCheck=ssl_health_check,
checkIntervalSec=args.check_interval,
timeoutSec=args.timeout,
healthyThreshold=args.healthy_threshold,
unhealthyThreshold=args.unhealthy_threshold),
project=health_check_ref.project)
collection = client.apitools_client.healthChecks
if include_log_config:
request.healthCheck.logConfig = health_checks_utils.CreateLogConfig(
client, args)
return client.MakeRequests([(collection, 'Insert', request)])
@base.ReleaseTracks(base.ReleaseTrack.GA)
class Create(base.CreateCommand):
"""Create a SSL health check."""
_include_log_config = True
detailed_help = _DetailedHelp()
@classmethod
def Args(cls, parser):
_Args(parser, cls._include_log_config)
def Run(self, args):
holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
return _Run(args, holder, self._include_log_config)
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class CreateBeta(Create):
pass
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class CreateAlpha(CreateBeta):
pass

View File

@@ -0,0 +1,141 @@
# -*- coding: utf-8 -*- #
# Copyright 2015 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 creating TCP health checks."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.compute import base_classes
from googlecloudsdk.api_lib.compute import health_checks_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.compute import scope as compute_scope
from googlecloudsdk.command_lib.compute.health_checks import flags
def _DetailedHelp():
return {
'brief':
'Create a TCP health check to monitor load balanced instances.',
'DESCRIPTION':
"""\
*{command}* is used to create a non-legacy health check using the TCP
protocol. You can use this health check for Google Cloud
load balancers or for managed instance group autohealing. For more
information, see the health checks overview at:
[](https://cloud.google.com/load-balancing/docs/health-check-concepts)
""",
}
def _Args(parser, include_log_config, include_source_regions):
"""Set up arguments to create an HTTP2 HealthCheck."""
parser.display_info.AddFormat(flags.DEFAULT_LIST_FORMAT)
flags.HealthCheckArgument('TCP').AddArgument(parser, operation_type='create')
health_checks_utils.AddTcpRelatedCreationArgs(parser)
health_checks_utils.AddProtocolAgnosticCreationArgs(parser, 'TCP')
if include_source_regions:
health_checks_utils.AddHealthCheckSourceRegionsRelatedArgs(parser)
if include_log_config:
health_checks_utils.AddHealthCheckLoggingRelatedArgs(parser)
def _Run(args, holder, include_log_config, include_source_regions):
"""Issues the request necessary for adding the health check."""
client = holder.client
messages = client.messages
health_check_ref = flags.HealthCheckArgument('TCP').ResolveAsResource(
args, holder.resources, default_scope=compute_scope.ScopeEnum.GLOBAL)
proxy_header = messages.TCPHealthCheck.ProxyHeaderValueValuesEnum(
args.proxy_header)
tcp_health_check = messages.TCPHealthCheck(
request=args.request,
response=args.response,
port=args.port,
portName=args.port_name,
proxyHeader=proxy_header)
health_checks_utils.ValidateAndAddPortSpecificationToHealthCheck(
args, tcp_health_check)
if health_checks_utils.IsRegionalHealthCheckRef(health_check_ref):
request = messages.ComputeRegionHealthChecksInsertRequest(
healthCheck=messages.HealthCheck(
name=health_check_ref.Name(),
description=args.description,
type=messages.HealthCheck.TypeValueValuesEnum.TCP,
tcpHealthCheck=tcp_health_check,
checkIntervalSec=args.check_interval,
timeoutSec=args.timeout,
healthyThreshold=args.healthy_threshold,
unhealthyThreshold=args.unhealthy_threshold),
project=health_check_ref.project,
region=health_check_ref.region)
collection = client.apitools_client.regionHealthChecks
else:
request = messages.ComputeHealthChecksInsertRequest(
healthCheck=messages.HealthCheck(
name=health_check_ref.Name(),
description=args.description,
type=messages.HealthCheck.TypeValueValuesEnum.TCP,
tcpHealthCheck=tcp_health_check,
checkIntervalSec=args.check_interval,
timeoutSec=args.timeout,
healthyThreshold=args.healthy_threshold,
unhealthyThreshold=args.unhealthy_threshold),
project=health_check_ref.project)
collection = client.apitools_client.healthChecks
if include_log_config:
request.healthCheck.logConfig = health_checks_utils.CreateLogConfig(
client, args)
if include_source_regions and (args.source_regions is not None):
request.healthCheck.sourceRegions = args.source_regions
return client.MakeRequests([(collection, 'Insert', request)])
@base.ReleaseTracks(base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class Create(base.CreateCommand):
"""Create a TCP health."""
_include_log_config = True
_include_source_regions = True
detailed_help = _DetailedHelp()
@classmethod
def Args(cls, parser):
_Args(parser, cls._include_log_config, cls._include_source_regions)
def Run(self, args):
holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
return _Run(
args, holder, self._include_log_config, self._include_source_regions
)
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class CreateBeta(Create):
pass
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class CreateAlpha(CreateBeta):
pass

View File

@@ -0,0 +1,122 @@
# -*- coding: utf-8 -*- #
# Copyright 2016 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 creating UDP health checks."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.compute import base_classes
from googlecloudsdk.api_lib.compute import health_checks_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.compute.health_checks import exceptions
from googlecloudsdk.command_lib.compute.health_checks import flags
def _DetailedHelp():
return {
'brief':
'Create a UDP health check to monitor load balanced instances.',
'DESCRIPTION':
"""\
*{command}* is used to create a UDP health check. UDP health checks
monitor instances in a load balancer controlled by a target pool. All
arguments to the command are optional except for the name of the health
check, request and response. For more information on load balancing, see
[](https://cloud.google.com/compute/docs/load-balancing-and-autoscaling/)
""",
}
def _Args(parser):
parser.display_info.AddFormat(flags.DEFAULT_LIST_FORMAT)
flags.HealthCheckArgument('UDP').AddArgument(parser, operation_type='create')
health_checks_utils.AddUdpRelatedArgs(parser)
health_checks_utils.AddProtocolAgnosticCreationArgs(parser, 'UDP')
def _Run(args, holder):
"""Issues the request necessary for adding the health check."""
client = holder.client
health_check_ref = flags.HealthCheckArgument('UDP').ResolveAsResource(
args, holder.resources)
# Check that request and response are not None and empty.
if not args.request:
raise exceptions.ArgumentError('"request" field for UDP can not be empty.')
if not args.response:
raise exceptions.ArgumentError('"response" field for UDP can not be empty.')
if health_checks_utils.IsRegionalHealthCheckRef(health_check_ref):
request = client.messages.ComputeRegionHealthChecksInsertRequest(
healthCheck=client.messages.HealthCheck(
name=health_check_ref.Name(),
description=args.description,
type=client.messages.HealthCheck.TypeValueValuesEnum.UDP,
udpHealthCheck=client.messages.UDPHealthCheck(
request=args.request,
response=args.response,
port=args.port,
portName=args.port_name),
checkIntervalSec=args.check_interval,
timeoutSec=args.timeout,
healthyThreshold=args.healthy_threshold,
unhealthyThreshold=args.unhealthy_threshold,
),
project=health_check_ref.project,
region=health_check_ref.region)
collection = client.apitools_client.regionHealthChecks
else:
request = client.messages.ComputeHealthChecksInsertRequest(
healthCheck=client.messages.HealthCheck(
name=health_check_ref.Name(),
description=args.description,
type=client.messages.HealthCheck.TypeValueValuesEnum.UDP,
udpHealthCheck=client.messages.UDPHealthCheck(
request=args.request,
response=args.response,
port=args.port,
portName=args.port_name),
checkIntervalSec=args.check_interval,
timeoutSec=args.timeout,
healthyThreshold=args.healthy_threshold,
unhealthyThreshold=args.unhealthy_threshold,
),
project=health_check_ref.project)
collection = client.apitools_client.healthChecks
return client.MakeRequests([(collection, 'Insert', request)])
@base.Hidden
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class CreateAlpha(base.CreateCommand):
"""Create an Alpha UDP health check to monitor load balanced instances.
Business logic should be put in helper functions. Classes annotated with
@base.ReleaseTracks should only be concerned with calling helper functions
with the correct feature parameters.
"""
detailed_help = _DetailedHelp()
@classmethod
def Args(cls, parser):
_Args(parser)
def Run(self, args):
holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
return _Run(args, holder)

View File

@@ -0,0 +1,90 @@
# -*- coding: utf-8 -*- #
# Copyright 2015 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 deleting health checks."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.compute import base_classes
from googlecloudsdk.api_lib.compute import health_checks_utils
from googlecloudsdk.api_lib.compute import utils
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.compute import completers
from googlecloudsdk.command_lib.compute import flags as compute_flags
from googlecloudsdk.command_lib.compute import scope as compute_scope
from googlecloudsdk.command_lib.compute.health_checks import flags
def _DetailedHelp():
return {
'brief':
'Delete health checks.',
'DESCRIPTION':
"""\
*{command}* deletes one or more Compute Engine
health checks.
""",
}
def _Args(parser):
health_check_arg = flags.HealthCheckArgument('', plural=True)
health_check_arg.AddArgument(parser, operation_type='delete')
parser.display_info.AddCacheUpdater(completers.HealthChecksCompleterAlpha)
def _Run(holder, args):
"""Issues the request necessary for deleting the health check."""
client = holder.client
health_check_arg = flags.HealthCheckArgument('', plural=True)
health_check_refs = health_check_arg.ResolveAsResource(
args,
holder.resources,
default_scope=compute_scope.ScopeEnum.GLOBAL,
scope_lister=compute_flags.GetDefaultScopeLister(client))
utils.PromptForDeletion(health_check_refs)
requests = []
for health_check_ref in health_check_refs:
if health_checks_utils.IsRegionalHealthCheckRef(health_check_ref):
requests.append((client.apitools_client.regionHealthChecks, 'Delete',
client.messages.ComputeRegionHealthChecksDeleteRequest(
**health_check_ref.AsDict())))
else:
requests.append((client.apitools_client.healthChecks, 'Delete',
client.messages.ComputeHealthChecksDeleteRequest(
**health_check_ref.AsDict())))
return client.MakeRequests(requests)
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
class Delete(base.DeleteCommand):
"""Delete Ga/Beta health checks."""
detailed_help = _DetailedHelp()
@classmethod
def Args(cls, parser):
_Args(parser)
def Run(self, args):
holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
return _Run(holder, args)

View File

@@ -0,0 +1,64 @@
# -*- coding: utf-8 -*- #
# Copyright 2015 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 describing health checks."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.compute import base_classes
from googlecloudsdk.api_lib.compute import health_checks_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.compute import flags as compute_flags
from googlecloudsdk.command_lib.compute import scope as compute_scope
from googlecloudsdk.command_lib.compute.health_checks import flags
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
class Describe(base.DescribeCommand):
"""Display detailed information about a health check.
*{command}* displays all data associated with a Google Compute
Engine health check in a project.
"""
HEALTH_CHECK_ARG = None
@classmethod
def Args(cls, parser):
cls.HEALTH_CHECK_ARG = flags.HealthCheckArgument('')
cls.HEALTH_CHECK_ARG.AddArgument(parser, operation_type='describe')
def Run(self, args):
holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
client = holder.client
health_check_ref = self.HEALTH_CHECK_ARG.ResolveAsResource(
args,
holder.resources,
default_scope=compute_scope.ScopeEnum.GLOBAL,
scope_lister=compute_flags.GetDefaultScopeLister(client))
if health_checks_utils.IsRegionalHealthCheckRef(health_check_ref):
request = client.messages.ComputeRegionHealthChecksGetRequest(
**health_check_ref.AsDict())
collection = client.apitools_client.regionHealthChecks
else:
request = client.messages.ComputeHealthChecksGetRequest(
**health_check_ref.AsDict())
collection = client.apitools_client.healthChecks
return client.MakeRequests([(collection, 'Get', request)])[0]

View File

@@ -0,0 +1,237 @@
# -*- coding: utf-8 -*- #
# Copyright 2015 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 listing health checks."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.compute import base_classes
from googlecloudsdk.api_lib.compute import lister
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.compute.health_checks import exceptions
@base.UniverseCompatible
@base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.GA)
class List(base.ListCommand):
"""List health checks in GA."""
messages = None
@staticmethod
def Args(parser):
lister.AddMultiScopeListerFlags(parser, regional=True, global_=True)
parser.add_argument(
'--protocol',
help="""\
If protocol is specified, only health checks for that protocol are
listed, and protocol-specific columns are added to the output. By
default, health checks for all protocols are listed.
""")
def _ConvertProtocolArgsToProtocolEnumName(self, args):
return args.protocol.upper().replace('-', '_')
def _ConvertProtocolArgToValue(self, args):
# Get the dictionary that maps strings to numbers, e.g. "HTTP" to 0.
protocol_dict = self.messages.HealthCheck.TypeValueValuesEnum.to_dict()
return protocol_dict.get(self._ConvertProtocolArgsToProtocolEnumName(args))
def _ProtocolAllowlist(self):
# Returns a list of allowlisted protocols.
return [
self.messages.HealthCheck.TypeValueValuesEnum.GRPC.number,
self.messages.HealthCheck.TypeValueValuesEnum.GRPC_WITH_TLS.number,
self.messages.HealthCheck.TypeValueValuesEnum.HTTP.number,
self.messages.HealthCheck.TypeValueValuesEnum.HTTPS.number,
self.messages.HealthCheck.TypeValueValuesEnum.HTTP2.number,
self.messages.HealthCheck.TypeValueValuesEnum.TCP.number,
self.messages.HealthCheck.TypeValueValuesEnum.SSL.number,
]
def _GetValidColumns(self, args):
"""Returns a list of valid columns."""
# Start with the columns that apply to all protocols.
columns = [
'name:label=NAME', 'region.basename():label=REGION',
'type:label=PROTOCOL'
]
# Add protocol-specific columns. Note that we only need to worry about
# protocols that were allowlisted in our GetResources method below.
if args.protocol is not None:
protocol_value = self._ConvertProtocolArgToValue(args)
if (protocol_value ==
self.messages.HealthCheck.TypeValueValuesEnum.GRPC.number):
columns.extend([
'grpcHealthCheck.port:label=PORT',
'grpcHealthCheck.grpcServiceName:label=GRPC_SERVICE_NAME'
])
elif (
protocol_value
== self.messages.HealthCheck.TypeValueValuesEnum.GRPC_WITH_TLS.number
):
columns.extend([
'grpcTlsHealthCheck.port:label=PORT',
'grpcTlsHealthCheck.grpcServiceName:label=GRPC_SERVICE_NAME',
])
elif (protocol_value ==
self.messages.HealthCheck.TypeValueValuesEnum.HTTP.number):
columns.extend(['httpHealthCheck.host:label=HOST',
'httpHealthCheck.port:label=PORT',
'httpHealthCheck.requestPath:label=REQUEST_PATH',
'httpHealthCheck.proxyHeader:label=PROXY_HEADER'])
elif (protocol_value ==
self.messages.HealthCheck.TypeValueValuesEnum.HTTPS.number):
columns.extend(['httpsHealthCheck.host:label=HOST',
'httpsHealthCheck.port:label=PORT',
'httpsHealthCheck.requestPath:label=REQUEST_PATH',
'httpsHealthCheck.proxyHeader:label=PROXY_HEADER'])
elif (protocol_value ==
self.messages.HealthCheck.TypeValueValuesEnum.HTTP2.number):
columns.extend(['http2HealthCheck.host:label=HOST',
'http2HealthCheck.port:label=PORT',
'http2HealthCheck.requestPath:label=REQUEST_PATH',
'http2HealthCheck.proxyHeader:label=PROXY_HEADER'])
elif (protocol_value ==
self.messages.HealthCheck.TypeValueValuesEnum.TCP.number):
columns.extend(['tcpHealthCheck.port:label=PORT',
'tcpHealthCheck.request:label=REQUEST',
'tcpHealthCheck.response:label=RESPONSE',
'tcpHealthCheck.proxyHeader:label=PROXY_HEADER'])
elif (protocol_value ==
self.messages.HealthCheck.TypeValueValuesEnum.SSL.number):
columns.extend(['sslHealthCheck.port:label=PORT',
'sslHealthCheck.request:label=REQUEST',
'sslHealthCheck.response:label=RESPONSE',
'sslHealthCheck.proxyHeader:label=PROXY_HEADER'])
return columns
def Collection(self):
"""Override the default collection from the base class."""
return None
def Run(self, args):
holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
client = holder.client
self.messages = client.messages
if args.protocol is not None:
self._validateProtocol(args)
if not args.IsSpecified('format') and not args.uri:
args.format = self._Format(args)
request_data = lister.ParseMultiScopeFlags(args, holder.resources)
list_implementation = lister.MultiScopeLister(
client,
regional_service=client.apitools_client.regionHealthChecks,
global_service=client.apitools_client.healthChecks,
aggregation_service=client.apitools_client.healthChecks,
)
items = lister.Invoke(request_data, list_implementation)
if args.protocol is None:
return items
# Filter the resources that do not match the specified protocol.
health_checks = []
for health_check in items:
if health_check['type'] == self._ConvertProtocolArgsToProtocolEnumName(
args
):
health_checks.append(health_check)
return health_checks
def _validateProtocol(self, args):
protocol_value = self._ConvertProtocolArgToValue(args)
if protocol_value not in self._ProtocolAllowlist():
raise exceptions.ArgumentError(
'Invalid health check protocol ' + args.protocol + '.'
)
def _Format(self, args):
columns = self._GetValidColumns(args)
return 'table[]({columns})'.format(columns=','.join(columns))
@property
def service(self):
return self.compute.healthChecks
@property
def resource_type(self):
return 'healthChecks'
@property
def global_service(self):
"""The service used to list global resources."""
return self.compute.healthChecks
@property
def regional_service(self):
"""The service used to list regional resources."""
return self.compute.regionHealthChecks
@property
def zonal_service(self):
"""The service used to list regional resources."""
return None
@property
def aggregation_service(self):
"""The service used to get aggregated list of resources."""
return self.compute.healthChecks
def GetResources(self, args, errors):
health_checks = super(List, self).GetResources(args, errors)
# If a protocol is specified, check that it is one we support, and convert
# it to a number.
protocol_value = None
if args.protocol is not None:
protocol_value = self._ConvertProtocolArgToValue(args)
if protocol_value not in self._ProtocolAllowlist():
raise exceptions.ArgumentError('Invalid health check protocol ' +
args.protocol + '.')
for health_check in health_checks:
if (protocol_value is None or
health_check['type'] == args.protocol.upper()):
yield health_check
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class ListAlpha(List):
"""List health checks in Alpha."""
def _Format(self, args):
columns = super(ListAlpha, self)._GetValidColumns(args)
if args.protocol is not None:
protocol_value = self._ConvertProtocolArgToValue(args)
if (protocol_value ==
self.messages.HealthCheck.TypeValueValuesEnum.UDP.number):
columns.extend([
'udpHealthCheck.port:label=PORT',
'udpHealthCheck.request:label=REQUEST',
'udpHealthCheck.response:label=RESPONSE'
])
return 'table[]({columns})'.format(columns=','.join(columns))
List.detailed_help = base_classes.GetGlobalListerHelp('health checks')
ListAlpha.detailed_help = base_classes.GetGlobalListerHelp('health checks')

View File

@@ -0,0 +1,30 @@
# -*- coding: utf-8 -*- #
# Copyright 2015 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.
"""Commands for updating health checks."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
class HealthChecksUpdate(base.Group):
"""Update health checks for load balanced instances."""
HealthChecksUpdate.detailed_help = {
'brief': ('Update health checks for load balanced instances')
}

View File

@@ -0,0 +1,218 @@
# -*- 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 updating health checks."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.compute import base_classes
from googlecloudsdk.api_lib.compute import health_checks_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.compute import scope as compute_scope
from googlecloudsdk.command_lib.compute.health_checks import exceptions
from googlecloudsdk.command_lib.compute.health_checks import flags
from googlecloudsdk.core import exceptions as core_exceptions
from googlecloudsdk.core import log
def _DetailedHelp():
return {
'brief':
'Update a gRPC health check.',
'DESCRIPTION':
"""\
*{command}* is used to update an existing gRPC health check. Only
arguments passed in will be updated on the health check. Other
attributes will remain unaffected.
""",
}
def _Args(parser, include_log_config):
health_check_arg = flags.HealthCheckArgument('gRPC')
health_check_arg.AddArgument(parser, operation_type='update')
health_checks_utils.AddGrpcRelatedUpdateArgs(parser)
health_checks_utils.AddProtocolAgnosticUpdateArgs(parser, 'gRPC')
if include_log_config:
health_checks_utils.AddHealthCheckLoggingRelatedArgs(parser)
def _GetGetRequest(client, health_check_ref):
"""Returns a request for fetching the existing health check."""
return (client.apitools_client.healthChecks, 'Get',
client.messages.ComputeHealthChecksGetRequest(
healthCheck=health_check_ref.Name(),
project=health_check_ref.project))
def _GetSetRequest(client, health_check_ref, replacement):
"""Returns a request for updating the health check."""
return (client.apitools_client.healthChecks, 'Update',
client.messages.ComputeHealthChecksUpdateRequest(
healthCheck=health_check_ref.Name(),
healthCheckResource=replacement,
project=health_check_ref.project))
def _GetRegionalGetRequest(client, health_check_ref):
"""Returns a request for fetching the existing health check."""
return (client.apitools_client.regionHealthChecks, 'Get',
client.messages.ComputeRegionHealthChecksGetRequest(
healthCheck=health_check_ref.Name(),
project=health_check_ref.project,
region=health_check_ref.region))
def _GetRegionalSetRequest(client, health_check_ref, replacement):
"""Returns a request for updating the health check."""
return (client.apitools_client.regionHealthChecks, 'Update',
client.messages.ComputeRegionHealthChecksUpdateRequest(
healthCheck=health_check_ref.Name(),
healthCheckResource=replacement,
project=health_check_ref.project,
region=health_check_ref.region))
def _Modify(client, args, existing_check, include_log_config):
"""Returns a modified HealthCheck message."""
# We do not support using 'update grpc' with a health check of a
# different protocol.
if (existing_check.type !=
client.messages.HealthCheck.TypeValueValuesEnum.GRPC):
raise core_exceptions.Error(
'update grpc subcommand applied to health check with protocol ' +
existing_check.type.name)
# Description, PortName, and GrpcServiceName are the only attributes that can
# be cleared by passing in an empty string (but we don't want to set it to
# an empty string).
if args.description:
description = args.description
elif args.description is None:
description = existing_check.description
else:
description = None
if args.grpc_service_name:
grpc_service_name = args.grpc_service_name
elif args.grpc_service_name is None:
grpc_service_name = existing_check.grpcHealthCheck.grpcServiceName
else:
grpc_service_name = None
port, port_specification = health_checks_utils.\
HandlePortRelatedFlagsForGRPCUpdate(
args, existing_check.grpcHealthCheck)
new_health_check = client.messages.HealthCheck(
name=existing_check.name,
description=description,
type=client.messages.HealthCheck.TypeValueValuesEnum.GRPC,
grpcHealthCheck=client.messages.GRPCHealthCheck(
port=port,
portSpecification=port_specification,
grpcServiceName=grpc_service_name),
checkIntervalSec=(args.check_interval or existing_check.checkIntervalSec),
timeoutSec=args.timeout or existing_check.timeoutSec,
healthyThreshold=(args.healthy_threshold or
existing_check.healthyThreshold),
unhealthyThreshold=(args.unhealthy_threshold or
existing_check.unhealthyThreshold),
)
if include_log_config:
new_health_check.logConfig = health_checks_utils.ModifyLogConfig(
client, args, existing_check.logConfig)
return new_health_check
def _ValidateArgs(args, include_log_config):
"""Validates given args and raises exception if any args are invalid."""
health_checks_utils.CheckProtocolAgnosticArgs(args)
args_unset = not (args.port or args.check_interval or args.timeout or
args.healthy_threshold or args.unhealthy_threshold or
args.use_serving_port)
if include_log_config:
args_unset = (args.enable_logging is None and args_unset)
if (args.description is None and args.grpc_service_name is None and
args_unset):
raise exceptions.ArgumentError('At least one property must be modified.')
def _Run(args, holder, include_log_config):
"""Issues the requests necessary for updating the health check."""
client = holder.client
_ValidateArgs(args, include_log_config)
health_check_arg = flags.HealthCheckArgument('gRPC')
health_check_ref = health_check_arg.ResolveAsResource(
args, holder.resources, default_scope=compute_scope.ScopeEnum.GLOBAL)
if health_checks_utils.IsRegionalHealthCheckRef(health_check_ref):
get_request = _GetRegionalGetRequest(client, health_check_ref)
else:
get_request = _GetGetRequest(client, health_check_ref)
objects = client.MakeRequests([get_request])
new_object = _Modify(client, args, objects[0], include_log_config)
# If existing object is equal to the proposed object or if
# _Modify() returns None, then there is no work to be done, so we
# print the resource and return.
if objects[0] == new_object:
log.status.Print('No change requested; skipping update for [{0}].'.format(
objects[0].name))
return objects
if health_checks_utils.IsRegionalHealthCheckRef(health_check_ref):
set_request = _GetRegionalSetRequest(client, health_check_ref, new_object)
else:
set_request = _GetSetRequest(client, health_check_ref, new_object)
return client.MakeRequests([set_request])
@base.ReleaseTracks(base.ReleaseTrack.GA)
class Update(base.UpdateCommand):
"""Update a gRPC health check."""
_include_log_config = True
detailed_help = _DetailedHelp()
@classmethod
def Args(cls, parser):
_Args(parser, cls._include_log_config)
def Run(self, args):
holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
return _Run(args, holder, self._include_log_config)
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class UpdateBeta(Update):
pass
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class UpdateAlpha(UpdateBeta):
pass

View File

@@ -0,0 +1,256 @@
# -*- coding: utf-8 -*- #
# Copyright 2025 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 updating health checks."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.compute import base_classes
from googlecloudsdk.api_lib.compute import health_checks_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.compute import scope as compute_scope
from googlecloudsdk.command_lib.compute.health_checks import exceptions
from googlecloudsdk.command_lib.compute.health_checks import flags
from googlecloudsdk.core import exceptions as core_exceptions
from googlecloudsdk.core import log
def _DetailedHelp():
return {
'brief': 'Update a gRPC with TLS health check.',
'DESCRIPTION': """\
*{command}* is used to update an existing gRPC with TLS health check. Only
arguments passed in will be updated on the health check. Other
attributes will remain unaffected.
""",
}
def _Args(parser, include_log_config):
health_check_arg = flags.HealthCheckArgument('gRPC with TLS')
health_check_arg.AddArgument(parser, operation_type='update')
health_checks_utils.AddGrpcRelatedUpdateArgs(parser)
health_checks_utils.AddProtocolAgnosticUpdateArgs(parser, 'gRPC with TLS')
if include_log_config:
health_checks_utils.AddHealthCheckLoggingRelatedArgs(parser)
def _GetGetRequest(client, health_check_ref):
"""Returns a request for fetching the existing health check."""
return (client.apitools_client.healthChecks, 'Get',
client.messages.ComputeHealthChecksGetRequest(
healthCheck=health_check_ref.Name(),
project=health_check_ref.project))
def _GetSetRequest(client, health_check_ref, replacement):
"""Returns a request for updating the health check."""
return (client.apitools_client.healthChecks, 'Update',
client.messages.ComputeHealthChecksUpdateRequest(
healthCheck=health_check_ref.Name(),
healthCheckResource=replacement,
project=health_check_ref.project))
def _GetRegionalGetRequest(client, health_check_ref):
"""Returns a request for fetching the existing health check."""
return (client.apitools_client.regionHealthChecks, 'Get',
client.messages.ComputeRegionHealthChecksGetRequest(
healthCheck=health_check_ref.Name(),
project=health_check_ref.project,
region=health_check_ref.region))
def _GetRegionalSetRequest(client, health_check_ref, replacement):
"""Returns a request for updating the health check."""
return (client.apitools_client.regionHealthChecks, 'Update',
client.messages.ComputeRegionHealthChecksUpdateRequest(
healthCheck=health_check_ref.Name(),
healthCheckResource=replacement,
project=health_check_ref.project,
region=health_check_ref.region))
def _Modify(client, args, existing_check, include_log_config):
"""Returns a modified HealthCheck message."""
# We do not support using 'update grpc-with-tls' with a health check of a
# different protocol.
if (
existing_check.type
!= client.messages.HealthCheck.TypeValueValuesEnum.GRPC_WITH_TLS
):
raise core_exceptions.Error(
'update grpc-with-tls subcommand applied to health check with protocol '
+ existing_check.type.name
)
# Description, PortName, and GrpcServiceName are the only attributes that can
# be cleared by passing in an empty string (but we don't want to set it to
# an empty string).
if args.description:
description = args.description
elif args.description is None:
description = existing_check.description
else:
description = None
if args.grpc_service_name:
grpc_service_name = args.grpc_service_name
elif args.grpc_service_name is None:
grpc_service_name = existing_check.grpcTlsHealthCheck.grpcServiceName
else:
grpc_service_name = None
port, port_specification = (
health_checks_utils.HandlePortRelatedFlagsForGRPCUpdate(
args, existing_check.grpcTlsHealthCheck
)
)
new_health_check = client.messages.HealthCheck(
name=existing_check.name,
description=description,
type=client.messages.HealthCheck.TypeValueValuesEnum.GRPC_WITH_TLS,
grpcTlsHealthCheck=client.messages.GRPCTLSHealthCheck(
port=port,
portSpecification=port_specification,
grpcServiceName=grpc_service_name,
),
checkIntervalSec=(args.check_interval or existing_check.checkIntervalSec),
timeoutSec=args.timeout or existing_check.timeoutSec,
healthyThreshold=(
args.healthy_threshold or existing_check.healthyThreshold
),
unhealthyThreshold=(
args.unhealthy_threshold or existing_check.unhealthyThreshold
),
)
if include_log_config:
new_health_check.logConfig = health_checks_utils.ModifyLogConfig(
client, args, existing_check.logConfig)
return new_health_check
def _ValidateArgs(args, include_log_config):
"""Validates given args and raises exception if any args are invalid."""
health_checks_utils.CheckProtocolAgnosticArgs(args)
args_unset = not (args.port or args.check_interval or args.timeout or
args.healthy_threshold or args.unhealthy_threshold or
args.use_serving_port)
if include_log_config:
args_unset = (args.enable_logging is None and args_unset)
if (args.description is None and args.grpc_service_name is None and
args_unset):
raise exceptions.ArgumentError('At least one property must be modified.')
def _Run(args, holder, include_log_config):
"""Issues the requests necessary for updating the health check."""
client = holder.client
_ValidateArgs(args, include_log_config)
health_check_arg = flags.HealthCheckArgument('gRPC with TLS')
health_check_ref = health_check_arg.ResolveAsResource(
args, holder.resources, default_scope=compute_scope.ScopeEnum.GLOBAL)
if health_checks_utils.IsRegionalHealthCheckRef(health_check_ref):
get_request = _GetRegionalGetRequest(client, health_check_ref)
else:
get_request = _GetGetRequest(client, health_check_ref)
objects = client.MakeRequests([get_request])
new_object = _Modify(client, args, objects[0], include_log_config)
# If existing object is equal to the proposed object or if
# _Modify() returns None, then there is no work to be done, so we
# print the resource and return.
if objects[0] == new_object:
log.status.Print('No change requested; skipping update for [{0}].'.format(
objects[0].name))
return objects
if health_checks_utils.IsRegionalHealthCheckRef(health_check_ref):
set_request = _GetRegionalSetRequest(client, health_check_ref, new_object)
else:
set_request = _GetSetRequest(client, health_check_ref, new_object)
return client.MakeRequests([set_request])
@base.DefaultUniverseOnly
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class UpdateAlpha(base.UpdateCommand):
"""Update a gRPC with TLS health check."""
_include_log_config = True
detailed_help = _DetailedHelp()
@classmethod
def Args(cls, parser):
_Args(parser, cls._include_log_config)
def Run(self, args):
return _Run(
args,
base_classes.ComputeApiHolder(self.ReleaseTrack()),
self._include_log_config,
)
@base.DefaultUniverseOnly
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class UpdateBeta(base.UpdateCommand):
"""Update a gRPC with TLS health check."""
_include_log_config = True
detailed_help = _DetailedHelp()
@classmethod
def Args(cls, parser):
_Args(parser, cls._include_log_config)
def Run(self, args):
return _Run(
args,
base_classes.ComputeApiHolder(self.ReleaseTrack()),
self._include_log_config,
)
@base.DefaultUniverseOnly
@base.ReleaseTracks(base.ReleaseTrack.GA)
class UpdateGa(base.UpdateCommand):
"""Update a gRPC with TLS health check."""
_include_log_config = True
detailed_help = _DetailedHelp()
@classmethod
def Args(cls, parser):
_Args(parser, cls._include_log_config)
def Run(self, args):
return _Run(
args,
base_classes.ComputeApiHolder(self.ReleaseTrack()),
self._include_log_config,
)

View File

@@ -0,0 +1,323 @@
# -*- coding: utf-8 -*- #
# Copyright 2015 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 updating health checks."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.compute import base_classes
from googlecloudsdk.api_lib.compute import health_checks_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.compute import scope as compute_scope
from googlecloudsdk.command_lib.compute.health_checks import exceptions
from googlecloudsdk.command_lib.compute.health_checks import flags
from googlecloudsdk.core import exceptions as core_exceptions
from googlecloudsdk.core import log
def _DetailedHelp():
return {
'brief':
'Update a HTTP health check.',
'DESCRIPTION':
"""\
*{command}* is used to update an existing HTTP health check. Only
arguments passed in will be updated on the health check. Other
attributes will remain unaffected.
""",
}
def _Args(
parser,
include_log_config,
include_weighted_load_balancing,
include_source_regions,
):
"""Adds all the args in the parser."""
health_check_arg = flags.HealthCheckArgument('HTTP')
health_check_arg.AddArgument(parser, operation_type='update')
health_checks_utils.AddHttpRelatedUpdateArgs(parser,
include_weighted_load_balancing)
health_checks_utils.AddProtocolAgnosticUpdateArgs(parser, 'HTTP')
health_checks_utils.AddHttpRelatedResponseArg(parser)
if include_source_regions:
health_checks_utils.AddHealthCheckSourceRegionsRelatedArgs(parser)
if include_log_config:
health_checks_utils.AddHealthCheckLoggingRelatedArgs(parser)
def _GetGetRequest(client, health_check_ref):
"""Returns a request for fetching the existing health check."""
return (client.apitools_client.healthChecks, 'Get',
client.messages.ComputeHealthChecksGetRequest(
healthCheck=health_check_ref.Name(),
project=health_check_ref.project))
def _GetSetRequest(client, health_check_ref, replacement):
"""Returns a request for updating the health check."""
return (client.apitools_client.healthChecks, 'Update',
client.messages.ComputeHealthChecksUpdateRequest(
healthCheck=health_check_ref.Name(),
healthCheckResource=replacement,
project=health_check_ref.project))
def _GetRegionalGetRequest(client, health_check_ref):
"""Returns a request for fetching the existing health check."""
return (client.apitools_client.regionHealthChecks, 'Get',
client.messages.ComputeRegionHealthChecksGetRequest(
healthCheck=health_check_ref.Name(),
project=health_check_ref.project,
region=health_check_ref.region))
def _GetRegionalSetRequest(client, health_check_ref, replacement):
"""Returns a request for updating the health check."""
return (client.apitools_client.regionHealthChecks, 'Update',
client.messages.ComputeRegionHealthChecksUpdateRequest(
healthCheck=health_check_ref.Name(),
healthCheckResource=replacement,
project=health_check_ref.project,
region=health_check_ref.region))
def _Modify(
client,
args,
existing_check,
include_log_config,
include_weighted_load_balancing,
include_source_regions,
):
"""Returns a modified HealthCheck message."""
# We do not support using 'update http' with a health check of a
# different protocol.
if (existing_check.type !=
client.messages.HealthCheck.TypeValueValuesEnum.HTTP):
raise core_exceptions.Error(
'update http subcommand applied to health check with protocol ' +
existing_check.type.name)
# Description, PortName, and Host are the only attributes that can be
# cleared by passing in an empty string (but we don't want to set it to
# an empty string).
if args.description:
description = args.description
elif args.description is None:
description = existing_check.description
else:
description = None
if args.host:
host = args.host
elif args.host is None:
host = existing_check.httpHealthCheck.host
else:
host = None
port, port_name, port_specification = health_checks_utils.\
HandlePortRelatedFlagsForUpdate(
args, existing_check.httpHealthCheck)
if include_weighted_load_balancing:
weight_report_mode = existing_check.httpHealthCheck.weightReportMode
if args.IsSpecified('weight_report_mode'):
weight_report_mode = client.messages.HTTPHealthCheck.WeightReportModeValueValuesEnum(
args.weight_report_mode)
proxy_header = existing_check.httpHealthCheck.proxyHeader
if args.proxy_header is not None:
proxy_header = client.messages.HTTPHealthCheck.ProxyHeaderValueValuesEnum(
args.proxy_header)
if args.response:
response = args.response
elif args.response is None:
response = existing_check.httpHealthCheck.response
else:
response = None
http_health_check = client.messages.HTTPHealthCheck(
host=host,
port=port,
portName=port_name,
requestPath=(args.request_path or
existing_check.httpHealthCheck.requestPath),
portSpecification=port_specification,
proxyHeader=proxy_header,
response=response)
if include_weighted_load_balancing:
http_health_check.weightReportMode = weight_report_mode
new_health_check = client.messages.HealthCheck(
name=existing_check.name,
description=description,
type=client.messages.HealthCheck.TypeValueValuesEnum.HTTP,
httpHealthCheck=http_health_check,
checkIntervalSec=(args.check_interval or existing_check.checkIntervalSec),
timeoutSec=args.timeout or existing_check.timeoutSec,
healthyThreshold=(args.healthy_threshold or
existing_check.healthyThreshold),
unhealthyThreshold=(args.unhealthy_threshold or
existing_check.unhealthyThreshold),
)
if include_log_config:
new_health_check.logConfig = health_checks_utils.ModifyLogConfig(
client, args, existing_check.logConfig)
if include_source_regions:
source_regions = existing_check.sourceRegions
if args.IsSpecified('source_regions'):
source_regions = args.source_regions
new_health_check.sourceRegions = source_regions
return new_health_check
def _ValidateArgs(
args,
include_log_config,
include_weighted_load_balancing,
include_source_regions,
):
"""Validates given args and raises exception if any args are invalid."""
health_checks_utils.CheckProtocolAgnosticArgs(args)
args_unset = not (args.port or args.request_path or args.check_interval or
args.timeout or args.healthy_threshold or
args.unhealthy_threshold or args.proxy_header or
args.use_serving_port)
if include_log_config:
args_unset = (args.enable_logging is None and args_unset)
source_regions_modified = False
if include_source_regions and args.IsSpecified('source_regions'):
source_regions_modified = True
weight_report_mode_modified = False
if include_weighted_load_balancing and args.IsSpecified('weight_report_mode'):
weight_report_mode_modified = True
if (
args.description is None
and args.host is None
and args.response is None
and args.port_name is None
and not weight_report_mode_modified
and not source_regions_modified
and args_unset
):
raise exceptions.ArgumentError('At least one property must be modified.')
def _Run(
args,
holder,
include_log_config,
include_weighted_load_balancing,
include_source_regions,
):
"""Issues the requests necessary for updating the health check."""
client = holder.client
_ValidateArgs(
args,
include_log_config,
include_weighted_load_balancing,
include_source_regions,
)
health_check_arg = flags.HealthCheckArgument('HTTP')
health_check_ref = health_check_arg.ResolveAsResource(
args, holder.resources, default_scope=compute_scope.ScopeEnum.GLOBAL)
if health_checks_utils.IsRegionalHealthCheckRef(health_check_ref):
get_request = _GetRegionalGetRequest(client, health_check_ref)
else:
get_request = _GetGetRequest(client, health_check_ref)
objects = client.MakeRequests([get_request])
new_object = _Modify(
client,
args,
objects[0],
include_log_config,
include_weighted_load_balancing,
include_source_regions,
)
# If existing object is equal to the proposed object or if
# _Modify() returns None, then there is no work to be done, so we
# print the resource and return.
if objects[0] == new_object:
log.status.Print('No change requested; skipping update for [{0}].'.format(
objects[0].name))
return objects
if health_checks_utils.IsRegionalHealthCheckRef(health_check_ref):
set_request = _GetRegionalSetRequest(client, health_check_ref, new_object)
else:
set_request = _GetSetRequest(client, health_check_ref, new_object)
return client.MakeRequests([set_request])
@base.ReleaseTracks(base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class Update(base.UpdateCommand):
"""Update a HTTP health check."""
_include_log_config = True
_include_weighted_load_balancing = False
_include_source_regions = True
detailed_help = _DetailedHelp()
@classmethod
def Args(cls, parser):
_Args(
parser,
cls._include_log_config,
cls._include_weighted_load_balancing,
cls._include_source_regions,
)
def Run(self, args):
holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
return _Run(
args,
holder,
self._include_log_config,
self._include_weighted_load_balancing,
self._include_source_regions,
)
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class UpdateBeta(Update):
_include_weighted_load_balancing = False
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class UpdateAlpha(UpdateBeta):
_include_weighted_load_balancing = True

View File

@@ -0,0 +1,266 @@
# -*- coding: utf-8 -*- #
# Copyright 2015 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 updating health checks."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.compute import base_classes
from googlecloudsdk.api_lib.compute import health_checks_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.compute import scope as compute_scope
from googlecloudsdk.command_lib.compute.health_checks import exceptions
from googlecloudsdk.command_lib.compute.health_checks import flags
from googlecloudsdk.core import exceptions as core_exceptions
from googlecloudsdk.core import log
def _DetailedHelp():
return {
'brief':
'Update a HTTP2 health check.',
'DESCRIPTION':
"""\
*{command}* is used to update an existing HTTP2 health check. Only
arguments passed in will be updated on the health check. Other
attributes will remain unaffected.
""",
'EXAMPLES':
"""\
To update health check interval to 10s, run:
$ {command} my-health-check-name --check-interval=10s
""",
}
def _Args(parser, include_log_config, include_weighted_load_balancing):
"""Adds all the args in the parser."""
health_check_arg = flags.HealthCheckArgument('HTTP2')
health_check_arg.AddArgument(parser, operation_type='update')
health_checks_utils.AddHttpRelatedUpdateArgs(parser,
include_weighted_load_balancing)
health_checks_utils.AddHttpRelatedResponseArg(parser)
health_checks_utils.AddProtocolAgnosticUpdateArgs(parser, 'HTTP2')
if include_log_config:
health_checks_utils.AddHealthCheckLoggingRelatedArgs(parser)
def _GetGetRequest(client, health_check_ref):
"""Returns a request for fetching the existing health check."""
return (client.apitools_client.healthChecks, 'Get',
client.messages.ComputeHealthChecksGetRequest(
healthCheck=health_check_ref.Name(),
project=health_check_ref.project))
def _GetSetRequest(client, health_check_ref, replacement):
"""Returns a request for updating the health check."""
return (client.apitools_client.healthChecks, 'Update',
client.messages.ComputeHealthChecksUpdateRequest(
healthCheck=health_check_ref.Name(),
healthCheckResource=replacement,
project=health_check_ref.project))
def _GetRegionalGetRequest(client, health_check_ref):
"""Returns a request for fetching the existing health check."""
return (client.apitools_client.regionHealthChecks, 'Get',
client.messages.ComputeRegionHealthChecksGetRequest(
healthCheck=health_check_ref.Name(),
project=health_check_ref.project,
region=health_check_ref.region))
def _GetRegionalSetRequest(client, health_check_ref, replacement):
"""Returns a request for updating the health check."""
return (client.apitools_client.regionHealthChecks, 'Update',
client.messages.ComputeRegionHealthChecksUpdateRequest(
healthCheck=health_check_ref.Name(),
healthCheckResource=replacement,
project=health_check_ref.project,
region=health_check_ref.region))
def _Modify(client, args, existing_check, include_log_config,
include_weighted_load_balancing):
"""Returns a modified HealthCheck message."""
# We do not support using 'update http2' with a health check of a
# different protocol.
if (existing_check.type !=
client.messages.HealthCheck.TypeValueValuesEnum.HTTP2):
raise core_exceptions.Error(
'update http2 subcommand applied to health check with protocol ' +
existing_check.type.name)
# Description, PortName, Response and Host are the only attributes that can
# be cleared by passing in an empty string (but we don't want to set it to
# an empty string).
if args.description:
description = args.description
elif args.description is None:
description = existing_check.description
else:
description = None
if args.host:
host = args.host
elif args.host is None:
host = existing_check.http2HealthCheck.host
else:
host = None
if args.response:
response = args.response
elif args.response is None:
response = existing_check.http2HealthCheck.response
else:
response = None
port, port_name, port_specification = health_checks_utils.\
HandlePortRelatedFlagsForUpdate(args, existing_check.http2HealthCheck)
if include_weighted_load_balancing:
weight_report_mode = existing_check.http2HealthCheck.weightReportMode
if args.IsSpecified('weight_report_mode'):
weight_report_mode = client.messages.HTTP2HealthCheck.WeightReportModeValueValuesEnum(
args.weight_report_mode)
proxy_header = existing_check.http2HealthCheck.proxyHeader
if args.proxy_header is not None:
proxy_header = (
client.messages.HTTP2HealthCheck.ProxyHeaderValueValuesEnum(
args.proxy_header))
http2_health_check = client.messages.HTTP2HealthCheck(
host=host,
port=port,
portName=port_name,
portSpecification=port_specification,
requestPath=(args.request_path or
existing_check.http2HealthCheck.requestPath),
proxyHeader=proxy_header,
response=response)
if include_weighted_load_balancing:
http2_health_check.weightReportMode = weight_report_mode
new_health_check = client.messages.HealthCheck(
name=existing_check.name,
description=description,
type=client.messages.HealthCheck.TypeValueValuesEnum.HTTP2,
http2HealthCheck=http2_health_check,
checkIntervalSec=(args.check_interval or existing_check.checkIntervalSec),
timeoutSec=args.timeout or existing_check.timeoutSec,
healthyThreshold=(args.healthy_threshold or
existing_check.healthyThreshold),
unhealthyThreshold=(args.unhealthy_threshold or
existing_check.unhealthyThreshold),
)
if include_log_config:
new_health_check.logConfig = health_checks_utils.ModifyLogConfig(
client, args, existing_check.logConfig)
return new_health_check
def _ValidateArgs(args,
include_log_config,
include_weighted_load_balancing=False):
"""Validates given args and raises exception if any args are invalid."""
health_checks_utils.CheckProtocolAgnosticArgs(args)
args_unset = not (args.port or args.request_path or args.check_interval or
args.timeout or args.healthy_threshold or
args.unhealthy_threshold or args.proxy_header or
args.use_serving_port)
if include_log_config:
args_unset = (args.enable_logging is None and args_unset)
weight_report_mode_modified = False
if include_weighted_load_balancing and args.IsSpecified('weight_report_mode'):
weight_report_mode_modified = True
if (args.description is None and args.host is None and
args.response is None and args.port_name is None and
not weight_report_mode_modified and args_unset):
raise exceptions.ArgumentError('At least one property must be modified.')
def _Run(args, holder, include_log_config, include_weighted_load_balancing):
"""Issues requests necessary to update the HTTP2 Health Checks."""
client = holder.client
_ValidateArgs(args, include_log_config, include_weighted_load_balancing)
health_check_arg = flags.HealthCheckArgument('HTTP2')
health_check_ref = health_check_arg.ResolveAsResource(
args, holder.resources, default_scope=compute_scope.ScopeEnum.GLOBAL)
if health_checks_utils.IsRegionalHealthCheckRef(health_check_ref):
get_request = _GetRegionalGetRequest(client, health_check_ref)
else:
get_request = _GetGetRequest(client, health_check_ref)
objects = client.MakeRequests([get_request])
new_object = _Modify(client, args, objects[0], include_log_config,
include_weighted_load_balancing)
# If existing object is equal to the proposed object or if
# _Modify() returns None, then there is no work to be done, so we
# print the resource and return.
if objects[0] == new_object:
log.status.Print('No change requested; skipping update for [{0}].'.format(
objects[0].name))
return objects
if health_checks_utils.IsRegionalHealthCheckRef(health_check_ref):
set_request = _GetRegionalSetRequest(client, health_check_ref, new_object)
else:
set_request = _GetSetRequest(client, health_check_ref, new_object)
return client.MakeRequests([set_request])
@base.ReleaseTracks(base.ReleaseTrack.GA)
class Update(base.UpdateCommand):
"""Update a HTTP2 health check."""
_include_log_config = True
_include_weighted_load_balancing = False
detailed_help = _DetailedHelp()
@classmethod
def Args(cls, parser):
_Args(parser, cls._include_log_config, cls._include_weighted_load_balancing)
def Run(self, args):
holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
return _Run(args, holder, self._include_log_config,
self._include_weighted_load_balancing)
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class UpdateBeta(Update):
_include_weighted_load_balancing = False
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class UpdateAlpha(UpdateBeta):
_include_weighted_load_balancing = True

View File

@@ -0,0 +1,321 @@
# -*- coding: utf-8 -*- #
# Copyright 2015 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 updating health checks."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.compute import base_classes
from googlecloudsdk.api_lib.compute import health_checks_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.compute import scope as compute_scope
from googlecloudsdk.command_lib.compute.health_checks import exceptions
from googlecloudsdk.command_lib.compute.health_checks import flags
from googlecloudsdk.core import exceptions as core_exceptions
from googlecloudsdk.core import log
def _DetailedHelp():
return {
'brief':
'Update a HTTPS health check.',
'DESCRIPTION':
"""\
*{command}* is used to update an existing HTTPS health check. Only
arguments passed in will be updated on the health check. Other
attributes will remain unaffected.
""",
}
def _Args(
parser,
include_log_config,
include_weighted_load_balancing,
include_source_regions,
):
"""Adds all the args in the parser."""
health_check_arg = flags.HealthCheckArgument('HTTPS')
health_check_arg.AddArgument(parser, operation_type='update')
health_checks_utils.AddHttpRelatedUpdateArgs(parser,
include_weighted_load_balancing)
health_checks_utils.AddProtocolAgnosticUpdateArgs(parser, 'HTTPS')
health_checks_utils.AddHttpRelatedResponseArg(parser)
if include_source_regions:
health_checks_utils.AddHealthCheckSourceRegionsRelatedArgs(parser)
if include_log_config:
health_checks_utils.AddHealthCheckLoggingRelatedArgs(parser)
def _GetGetRequest(client, health_check_ref):
"""Returns a request for fetching the existing health check."""
return (client.apitools_client.healthChecks, 'Get',
client.messages.ComputeHealthChecksGetRequest(
healthCheck=health_check_ref.Name(),
project=health_check_ref.project))
def _GetSetRequest(client, health_check_ref, replacement):
"""Returns a request for updating the health check."""
return (client.apitools_client.healthChecks, 'Update',
client.messages.ComputeHealthChecksUpdateRequest(
healthCheck=health_check_ref.Name(),
healthCheckResource=replacement,
project=health_check_ref.project))
def _GetRegionalGetRequest(client, health_check_ref):
"""Returns a request for fetching the existing health check."""
return (client.apitools_client.regionHealthChecks, 'Get',
client.messages.ComputeRegionHealthChecksGetRequest(
healthCheck=health_check_ref.Name(),
project=health_check_ref.project,
region=health_check_ref.region))
def _GetRegionalSetRequest(client, health_check_ref, replacement):
"""Returns a request for updating the health check."""
return (client.apitools_client.regionHealthChecks, 'Update',
client.messages.ComputeRegionHealthChecksUpdateRequest(
healthCheck=health_check_ref.Name(),
healthCheckResource=replacement,
project=health_check_ref.project,
region=health_check_ref.region))
def _Modify(
client,
args,
existing_check,
include_log_config,
include_weighted_load_balancing,
include_source_regions,
):
"""Returns a modified HealthCheck message."""
# We do not support using 'update https' with a health check of a
# different protocol.
if (existing_check.type !=
client.messages.HealthCheck.TypeValueValuesEnum.HTTPS):
raise core_exceptions.Error(
'update https subcommand applied to health check with protocol ' +
existing_check.type.name)
# Description, PortName, and Host are the only attributes that can be
# cleared by passing in an empty string (but we don't want to set it to
# an empty string).
if args.description:
description = args.description
elif args.description is None:
description = existing_check.description
else:
description = None
if args.host:
host = args.host
elif args.host is None:
host = existing_check.httpsHealthCheck.host
else:
host = None
port, port_name, port_specification = health_checks_utils. \
HandlePortRelatedFlagsForUpdate(args, existing_check.httpsHealthCheck)
if include_weighted_load_balancing:
weight_report_mode = existing_check.httpsHealthCheck.weightReportMode
if args.IsSpecified('weight_report_mode'):
weight_report_mode = client.messages.HTTPSHealthCheck.WeightReportModeValueValuesEnum(
args.weight_report_mode)
proxy_header = existing_check.httpsHealthCheck.proxyHeader
if args.proxy_header is not None:
proxy_header = (
client.messages.HTTPSHealthCheck.ProxyHeaderValueValuesEnum(
args.proxy_header))
if args.response:
response = args.response
elif args.response is None:
response = existing_check.httpsHealthCheck.response
else:
response = None
https_health_check = client.messages.HTTPSHealthCheck(
host=host,
port=port,
portName=port_name,
requestPath=(args.request_path or
existing_check.httpsHealthCheck.requestPath),
portSpecification=port_specification,
proxyHeader=proxy_header,
response=response)
if include_weighted_load_balancing:
https_health_check.weightReportMode = weight_report_mode
new_health_check = client.messages.HealthCheck(
name=existing_check.name,
description=description,
type=client.messages.HealthCheck.TypeValueValuesEnum.HTTPS,
httpsHealthCheck=https_health_check,
checkIntervalSec=(args.check_interval or existing_check.checkIntervalSec),
timeoutSec=args.timeout or existing_check.timeoutSec,
healthyThreshold=(args.healthy_threshold or
existing_check.healthyThreshold),
unhealthyThreshold=(args.unhealthy_threshold or
existing_check.unhealthyThreshold),
)
if include_log_config:
new_health_check.logConfig = health_checks_utils.ModifyLogConfig(
client, args, existing_check.logConfig)
if include_source_regions:
source_regions = existing_check.sourceRegions
if args.IsSpecified('source_regions'):
source_regions = args.source_regions
new_health_check.sourceRegions = source_regions
return new_health_check
def _ValidateArgs(
args,
include_log_config,
include_weighted_load_balancing,
include_source_regions,
):
"""Validates given args and raises exception if any args are invalid."""
health_checks_utils.CheckProtocolAgnosticArgs(args)
args_unset = not (args.port or args.request_path or args.check_interval or
args.timeout or args.healthy_threshold or
args.unhealthy_threshold or args.proxy_header or
args.use_serving_port)
if include_log_config:
args_unset = (args.enable_logging is None and args_unset)
source_regions_modified = False
if include_source_regions and args.IsSpecified('source_regions'):
source_regions_modified = True
weight_report_mode_modified = False
if include_weighted_load_balancing and args.IsSpecified('weight_report_mode'):
weight_report_mode_modified = True
if (
args.description is None
and args.host is None
and args.response is None
and args.port_name is None
and not weight_report_mode_modified
and not source_regions_modified
and args_unset
):
raise exceptions.ArgumentError('At least one property must be modified.')
def _Run(
args,
holder,
include_log_config,
include_weighted_load_balancing,
include_source_regions,
):
"""Issues the requests necessary for updating the health check."""
client = holder.client
_ValidateArgs(
args,
include_log_config,
include_weighted_load_balancing,
include_source_regions,
)
health_check_arg = flags.HealthCheckArgument('HTTPS')
health_check_ref = health_check_arg.ResolveAsResource(
args, holder.resources, default_scope=compute_scope.ScopeEnum.GLOBAL)
if health_checks_utils.IsRegionalHealthCheckRef(health_check_ref):
get_request = _GetRegionalGetRequest(client, health_check_ref)
else:
get_request = _GetGetRequest(client, health_check_ref)
objects = client.MakeRequests([get_request])
new_object = _Modify(
client,
args,
objects[0],
include_log_config,
include_weighted_load_balancing,
include_source_regions,
)
# If existing object is equal to the proposed object or if
# _Modify() returns None, then there is no work to be done, so we
# print the resource and return.
if objects[0] == new_object:
log.status.Print('No change requested; skipping update for [{0}].'.format(
objects[0].name))
return objects
if health_checks_utils.IsRegionalHealthCheckRef(health_check_ref):
set_request = _GetRegionalSetRequest(client, health_check_ref, new_object)
else:
set_request = _GetSetRequest(client, health_check_ref, new_object)
return client.MakeRequests([set_request])
@base.ReleaseTracks(base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class Update(base.UpdateCommand):
"""Update a HTTPS health check."""
_include_log_config = True
_include_weighted_load_balancing = False
_include_source_regions = True
detailed_help = _DetailedHelp()
@classmethod
def Args(cls, parser):
_Args(
parser,
cls._include_log_config,
cls._include_weighted_load_balancing,
cls._include_source_regions,
)
def Run(self, args):
holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
return _Run(
args,
holder,
self._include_log_config,
self._include_weighted_load_balancing,
self._include_source_regions,
)
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class UpdateBeta(Update):
_include_weighted_load_balancing = False
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class UpdateAlpha(UpdateBeta):
_include_weighted_load_balancing = True

View File

@@ -0,0 +1,230 @@
# -*- coding: utf-8 -*- #
# Copyright 2015 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 updating health checks."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.compute import base_classes
from googlecloudsdk.api_lib.compute import health_checks_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.compute import scope as compute_scope
from googlecloudsdk.command_lib.compute.health_checks import exceptions
from googlecloudsdk.command_lib.compute.health_checks import flags
from googlecloudsdk.core import exceptions as core_exceptions
from googlecloudsdk.core import log
def _DetailedHelp():
return {
'brief':
'Update a SSL health check.',
'DESCRIPTION':
"""\
*{command}* is used to update an existing SSL health check. Only
arguments passed in will be updated on the health check. Other
attributes will remain unaffected.
""",
}
def _Args(parser, include_log_config):
health_check_arg = flags.HealthCheckArgument('SSL')
health_check_arg.AddArgument(parser, operation_type='update')
health_checks_utils.AddTcpRelatedUpdateArgs(parser)
health_checks_utils.AddProtocolAgnosticUpdateArgs(parser, 'SSL')
if include_log_config:
health_checks_utils.AddHealthCheckLoggingRelatedArgs(parser)
def _GetGetRequest(client, health_check_ref):
"""Returns a request for fetching the existing health check."""
return (client.apitools_client.healthChecks, 'Get',
client.messages.ComputeHealthChecksGetRequest(
healthCheck=health_check_ref.Name(),
project=health_check_ref.project))
def _GetSetRequest(client, health_check_ref, replacement):
"""Returns a request for updating the health check."""
return (client.apitools_client.healthChecks, 'Update',
client.messages.ComputeHealthChecksUpdateRequest(
healthCheck=health_check_ref.Name(),
healthCheckResource=replacement,
project=health_check_ref.project))
def _GetRegionalGetRequest(client, health_check_ref):
"""Returns a request for fetching the existing health check."""
return (client.apitools_client.regionHealthChecks, 'Get',
client.messages.ComputeRegionHealthChecksGetRequest(
healthCheck=health_check_ref.Name(),
project=health_check_ref.project,
region=health_check_ref.region))
def _GetRegionalSetRequest(client, health_check_ref, replacement):
"""Returns a request for updating the health check."""
return (client.apitools_client.regionHealthChecks, 'Update',
client.messages.ComputeRegionHealthChecksUpdateRequest(
healthCheck=health_check_ref.Name(),
healthCheckResource=replacement,
project=health_check_ref.project,
region=health_check_ref.region))
def _Modify(client, args, existing_check, include_log_config):
"""Returns a modified HealthCheck message."""
# We do not support using 'update ssl' with a health check of a
# different protocol.
if (existing_check.type !=
client.messages.HealthCheck.TypeValueValuesEnum.SSL):
raise core_exceptions.Error(
'update ssl subcommand applied to health check with protocol ' +
existing_check.type.name)
# Description, PortName, Request, and Response are the only attributes that
# can be cleared by passing in an empty string (but we don't want to set it
# to an empty string).
if args.description:
description = args.description
elif args.description is None:
description = existing_check.description
else:
description = None
port, port_name, port_specification = health_checks_utils. \
HandlePortRelatedFlagsForUpdate(args, existing_check.sslHealthCheck)
if args.request:
request = args.request
elif args.request is None:
request = existing_check.sslHealthCheck.request
else:
request = None
if args.response:
response = args.response
elif args.response is None:
response = existing_check.sslHealthCheck.response
else:
response = None
proxy_header = existing_check.sslHealthCheck.proxyHeader
if args.proxy_header is not None:
proxy_header = client.messages.SSLHealthCheck.ProxyHeaderValueValuesEnum(
args.proxy_header)
new_health_check = client.messages.HealthCheck(
name=existing_check.name,
description=description,
type=client.messages.HealthCheck.TypeValueValuesEnum.SSL,
sslHealthCheck=client.messages.SSLHealthCheck(
request=request,
response=response,
port=port,
portName=port_name,
portSpecification=port_specification,
proxyHeader=proxy_header),
checkIntervalSec=(args.check_interval or existing_check.checkIntervalSec),
timeoutSec=args.timeout or existing_check.timeoutSec,
healthyThreshold=(args.healthy_threshold or
existing_check.healthyThreshold),
unhealthyThreshold=(args.unhealthy_threshold or
existing_check.unhealthyThreshold),
)
if include_log_config:
new_health_check.logConfig = health_checks_utils.ModifyLogConfig(
client, args, existing_check.logConfig)
return new_health_check
def _ValidateArgs(args, include_log_config):
"""Validates given args and raises exception if any args are invalid."""
health_checks_utils.CheckProtocolAgnosticArgs(args)
args_unset = not (args.port or args.check_interval or args.timeout or
args.healthy_threshold or args.unhealthy_threshold or
args.proxy_header or args.use_serving_port)
if include_log_config:
args_unset = (args.enable_logging is None and args_unset)
if (args.description is None and args.request is None and
args.response is None and args.port_name is None and args_unset):
raise exceptions.ArgumentError('At least one property must be modified.')
def _Run(args, holder, include_log_config):
"""Issues the requests necessary for updating the health check."""
client = holder.client
_ValidateArgs(args, include_log_config)
health_check_arg = flags.HealthCheckArgument('SSL')
health_check_ref = health_check_arg.ResolveAsResource(
args, holder.resources, default_scope=compute_scope.ScopeEnum.GLOBAL)
if health_checks_utils.IsRegionalHealthCheckRef(health_check_ref):
get_request = _GetRegionalGetRequest(client, health_check_ref)
else:
get_request = _GetGetRequest(client, health_check_ref)
objects = client.MakeRequests([get_request])
new_object = _Modify(client, args, objects[0], include_log_config)
# If existing object is equal to the proposed object or if
# _Modify() returns None, then there is no work to be done, so we
# print the resource and return.
if objects[0] == new_object:
log.status.Print('No change requested; skipping update for [{0}].'.format(
objects[0].name))
return objects
if health_checks_utils.IsRegionalHealthCheckRef(health_check_ref):
set_request = _GetRegionalSetRequest(client, health_check_ref, new_object)
else:
set_request = _GetSetRequest(client, health_check_ref, new_object)
return client.MakeRequests([set_request])
@base.ReleaseTracks(base.ReleaseTrack.GA)
class Update(base.UpdateCommand):
"""Update a SSL health check."""
_include_log_config = True
detailed_help = _DetailedHelp()
@classmethod
def Args(cls, parser):
_Args(parser, cls._include_log_config)
def Run(self, args):
holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
return _Run(args, holder, self._include_log_config)
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class UpdateBeta(Update):
pass
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class UpdateAlpha(UpdateBeta):
pass

View File

@@ -0,0 +1,262 @@
# -*- coding: utf-8 -*- #
# Copyright 2015 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 updating health checks."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.compute import base_classes
from googlecloudsdk.api_lib.compute import health_checks_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.compute import scope as compute_scope
from googlecloudsdk.command_lib.compute.health_checks import exceptions
from googlecloudsdk.command_lib.compute.health_checks import flags
from googlecloudsdk.core import exceptions as core_exceptions
from googlecloudsdk.core import log
def _DetailedHelp():
return {
'brief':
'Update a TCP health check.',
'DESCRIPTION':
"""\
*{command}* is used to update an existing TCP health check. Only
arguments passed in will be updated on the health check. Other
attributes will remain unaffected.
""",
}
def _Args(parser, include_log_config, include_source_regions):
health_check_arg = flags.HealthCheckArgument('TCP')
health_check_arg.AddArgument(parser, operation_type='update')
health_checks_utils.AddTcpRelatedUpdateArgs(parser)
health_checks_utils.AddProtocolAgnosticUpdateArgs(parser, 'TCP')
if include_source_regions:
health_checks_utils.AddHealthCheckSourceRegionsRelatedArgs(parser)
if include_log_config:
health_checks_utils.AddHealthCheckLoggingRelatedArgs(parser)
def _GetGetRequest(client, health_check_ref):
"""Returns a request for fetching the existing health check."""
return (client.apitools_client.healthChecks, 'Get',
client.messages.ComputeHealthChecksGetRequest(
healthCheck=health_check_ref.Name(),
project=health_check_ref.project))
def _GetSetRequest(client, health_check_ref, replacement):
"""Returns a request for updating the health check."""
return (client.apitools_client.healthChecks, 'Update',
client.messages.ComputeHealthChecksUpdateRequest(
healthCheck=health_check_ref.Name(),
healthCheckResource=replacement,
project=health_check_ref.project))
def _GetRegionalGetRequest(client, health_check_ref):
"""Returns a request for fetching the existing health check."""
return (client.apitools_client.regionHealthChecks, 'Get',
client.messages.ComputeRegionHealthChecksGetRequest(
healthCheck=health_check_ref.Name(),
project=health_check_ref.project,
region=health_check_ref.region))
def _GetRegionalSetRequest(client, health_check_ref, replacement):
"""Returns a request for updating the health check."""
return (client.apitools_client.regionHealthChecks, 'Update',
client.messages.ComputeRegionHealthChecksUpdateRequest(
healthCheck=health_check_ref.Name(),
healthCheckResource=replacement,
project=health_check_ref.project,
region=health_check_ref.region))
def _Modify(
client, args, existing_check, include_log_config, include_source_regions
):
"""Returns a modified HealthCheck message."""
# We do not support using 'update tcp' with a health check of a
# different protocol.
if (existing_check.type !=
client.messages.HealthCheck.TypeValueValuesEnum.TCP):
raise core_exceptions.Error(
'update tcp subcommand applied to health check with protocol ' +
existing_check.type.name)
# Description, PortName, Request, and Response are the only attributes that
# can be cleared by passing in an empty string (but we don't want to set it
# to an empty string).
if args.description:
description = args.description
elif args.description is None:
description = existing_check.description
else:
description = None
port, port_name, port_specification = health_checks_utils. \
HandlePortRelatedFlagsForUpdate(args, existing_check.tcpHealthCheck)
if args.request:
request = args.request
elif args.request is None:
request = existing_check.tcpHealthCheck.request
else:
request = None
if args.response:
response = args.response
elif args.response is None:
response = existing_check.tcpHealthCheck.response
else:
response = None
proxy_header = existing_check.tcpHealthCheck.proxyHeader
if args.proxy_header is not None:
proxy_header = client.messages.TCPHealthCheck.ProxyHeaderValueValuesEnum(
args.proxy_header)
new_health_check = client.messages.HealthCheck(
name=existing_check.name,
description=description,
type=client.messages.HealthCheck.TypeValueValuesEnum.TCP,
tcpHealthCheck=client.messages.TCPHealthCheck(
request=request,
response=response,
port=port,
portName=port_name,
portSpecification=port_specification,
proxyHeader=proxy_header),
checkIntervalSec=(args.check_interval or existing_check.checkIntervalSec),
timeoutSec=args.timeout or existing_check.timeoutSec,
healthyThreshold=(args.healthy_threshold or
existing_check.healthyThreshold),
unhealthyThreshold=(args.unhealthy_threshold or
existing_check.unhealthyThreshold),
)
if include_log_config:
new_health_check.logConfig = health_checks_utils.ModifyLogConfig(
client, args, existing_check.logConfig)
if include_source_regions:
source_regions = existing_check.sourceRegions
if args.IsSpecified('source_regions'):
source_regions = args.source_regions
new_health_check.sourceRegions = source_regions
return new_health_check
def _ValidateArgs(
args,
include_log_config,
include_source_regions,
):
"""Validates given args and raises exception if any args are invalid."""
health_checks_utils.CheckProtocolAgnosticArgs(args)
args_unset = not (args.port or args.check_interval or args.timeout or
args.healthy_threshold or args.unhealthy_threshold or
args.proxy_header or args.use_serving_port)
if include_log_config:
args_unset = (args.enable_logging is None and args_unset)
source_regions_modified = False
if include_source_regions and args.IsSpecified('source_regions'):
source_regions_modified = True
if (
args.description is None
and args.request is None
and args.response is None
and args.port_name is None
and not source_regions_modified
and args_unset
):
raise exceptions.ArgumentError('At least one property must be modified.')
def _Run(args, holder, include_log_config, include_source_regions):
"""Issues the requests necessary for updating the health check."""
client = holder.client
_ValidateArgs(args, include_log_config, include_source_regions)
health_check_arg = flags.HealthCheckArgument('TCP')
health_check_ref = health_check_arg.ResolveAsResource(
args, holder.resources, default_scope=compute_scope.ScopeEnum.GLOBAL)
if health_checks_utils.IsRegionalHealthCheckRef(health_check_ref):
get_request = _GetRegionalGetRequest(client, health_check_ref)
else:
get_request = _GetGetRequest(client, health_check_ref)
objects = client.MakeRequests([get_request])
new_object = _Modify(
client, args, objects[0], include_log_config, include_source_regions
)
# If existing object is equal to the proposed object or if
# _Modify() returns None, then there is no work to be done, so we
# print the resource and return.
if objects[0] == new_object:
log.status.Print('No change requested; skipping update for [{0}].'.format(
objects[0].name))
return objects
if health_checks_utils.IsRegionalHealthCheckRef(health_check_ref):
set_request = _GetRegionalSetRequest(client, health_check_ref, new_object)
else:
set_request = _GetSetRequest(client, health_check_ref, new_object)
return client.MakeRequests([set_request])
@base.ReleaseTracks(base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class Update(base.UpdateCommand):
"""Update a TCP health check."""
_include_log_config = True
_include_source_regions = True
detailed_help = _DetailedHelp()
@classmethod
def Args(cls, parser):
_Args(parser, cls._include_log_config, cls._include_source_regions)
def Run(self, args):
holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
return _Run(
args, holder, self._include_log_config, self._include_source_regions
)
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class UpdateBeta(Update):
pass
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class UpdateAlpha(UpdateBeta):
pass

View File

@@ -0,0 +1,174 @@
# -*- coding: utf-8 -*- #
# Copyright 2016 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 updating health checks."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.compute import base_classes
from googlecloudsdk.api_lib.compute import health_checks_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.compute.health_checks import exceptions
from googlecloudsdk.command_lib.compute.health_checks import flags
from googlecloudsdk.core import exceptions as core_exceptions
from googlecloudsdk.core import log
@base.Hidden
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class Update(base.UpdateCommand):
"""Update a UDP health check.
*{command}* is used to update an existing UDP health check. Only
arguments passed in will be updated on the health check. Other
attributes will remain unaffected.
"""
HEALTH_CHECK_ARG = None
@classmethod
def Args(cls, parser):
cls.HEALTH_CHECK_ARG = flags.HealthCheckArgument('UDP')
cls.HEALTH_CHECK_ARG.AddArgument(parser, operation_type='update')
health_checks_utils.AddUdpRelatedArgs(
parser, request_and_response_required=False)
health_checks_utils.AddProtocolAgnosticUpdateArgs(parser, 'UDP')
def _GetGetRequest(self, client, health_check_ref):
"""Returns a request for fetching the existing health check."""
return (client.apitools_client.healthChecks, 'Get',
client.messages.ComputeHealthChecksGetRequest(
healthCheck=health_check_ref.Name(),
project=health_check_ref.project))
def _GetSetRequest(self, client, health_check_ref, replacement):
"""Returns a request for updating the health check."""
return (client.apitools_client.healthChecks, 'Update',
client.messages.ComputeHealthChecksUpdateRequest(
healthCheck=health_check_ref.Name(),
healthCheckResource=replacement,
project=health_check_ref.project))
def _GetRegionalGetRequest(self, client, health_check_ref):
"""Returns a request for fetching the existing health check."""
return (client.apitools_client.regionHealthChecks, 'Get',
client.messages.ComputeRegionHealthChecksGetRequest(
healthCheck=health_check_ref.Name(),
project=health_check_ref.project,
region=health_check_ref.region))
def _GetRegionalSetRequest(self, client, health_check_ref, replacement):
"""Returns a request for updating the health check."""
return (client.apitools_client.regionHealthChecks, 'Update',
client.messages.ComputeRegionHealthChecksUpdateRequest(
healthCheck=health_check_ref.Name(),
healthCheckResource=replacement,
project=health_check_ref.project,
region=health_check_ref.region))
def Modify(self, client, args, existing_check):
"""Returns a modified HealthCheck message."""
# We do not support using 'update udp' with a health check of a
# different protocol.
if (existing_check.type !=
client.messages.HealthCheck.TypeValueValuesEnum.UDP):
raise core_exceptions.Error(
'update udp subcommand applied to health check with protocol ' +
existing_check.type.name)
# Description and PortName are the only attributes that can be cleared by
# passing in an empty string (but we don't want to set it to empty string).
if args.description:
description = args.description
elif args.description is None:
description = existing_check.description
else:
description = None
if args.port_name:
port_name = args.port_name
elif args.port_name is None:
port_name = existing_check.udpHealthCheck.portName
else:
port_name = None
new_health_check = client.messages.HealthCheck(
name=existing_check.name,
description=description,
type=client.messages.HealthCheck.TypeValueValuesEnum.UDP,
udpHealthCheck=client.messages.UDPHealthCheck(
request=args.request or existing_check.udpHealthCheck.request,
response=args.response or existing_check.udpHealthCheck.response,
port=args.port or existing_check.udpHealthCheck.port,
portName=port_name),
checkIntervalSec=(args.check_interval or
existing_check.checkIntervalSec),
timeoutSec=args.timeout or existing_check.timeoutSec,
healthyThreshold=(args.healthy_threshold or
existing_check.healthyThreshold),
unhealthyThreshold=(args.unhealthy_threshold or
existing_check.unhealthyThreshold),
)
return new_health_check
def Run(self, args):
"""Issues requests necessary to update UDP Health Checks."""
holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
client = holder.client
health_checks_utils.CheckProtocolAgnosticArgs(args)
args_unset = not (args.port or args.check_interval or args.timeout or
args.healthy_threshold or args.unhealthy_threshold or
args.request or args.response)
if args.description is None and args.port_name is None and args_unset:
raise exceptions.ArgumentError('At least one property must be modified.')
# Check that request and response are not empty. It is acceptable for it to
# be None.
if args.request is not None and not args.request:
raise exceptions.ArgumentError(
'"request" field for UDP can not be empty.')
if args.response is not None and not args.response:
raise exceptions.ArgumentError(
'"response" field for UDP can not be empty.')
health_check_ref = self.HEALTH_CHECK_ARG.ResolveAsResource(
args, holder.resources)
if health_checks_utils.IsRegionalHealthCheckRef(health_check_ref):
get_request = self._GetRegionalGetRequest(client, health_check_ref)
else:
get_request = self._GetGetRequest(client, health_check_ref)
objects = client.MakeRequests([get_request])
new_object = self.Modify(client, args, objects[0])
# If existing object is equal to the proposed object or if
# Modify() returns None, then there is no work to be done, so we
# print the resource and return.
if objects[0] == new_object:
log.status.Print('No change requested; skipping update for [{0}].'.format(
objects[0].name))
return objects
if health_checks_utils.IsRegionalHealthCheckRef(health_check_ref):
set_request = self._GetRegionalSetRequest(client, health_check_ref,
new_object)
else:
set_request = self._GetSetRequest(client, health_check_ref, new_object)
return client.MakeRequests([set_request])