1# -*- coding: utf-8 -*- #
2# Copyright 2015 Google LLC. All Rights Reserved.
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8#    http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15"""Command for creating HTTPS health checks."""
16
17from __future__ import absolute_import
18from __future__ import division
19from __future__ import unicode_literals
20
21from googlecloudsdk.api_lib.compute import base_classes
22from googlecloudsdk.api_lib.compute import health_checks_utils
23from googlecloudsdk.calliope import base
24from googlecloudsdk.command_lib.compute import completers
25from googlecloudsdk.command_lib.compute import scope as compute_scope
26from googlecloudsdk.command_lib.compute.health_checks import flags
27
28
29def _DetailedHelp():
30  return {
31      'brief':
32          'Create a HTTPS health check to monitor load balanced instances',
33      'DESCRIPTION':
34          """\
35        *{command}* is used to create a non-legacy health check using the HTTPS
36        protocol. You can use this health check for Google Cloud
37        load balancers or for managed instance group autohealing. For more
38        information, see the health checks overview at:
39        [](https://cloud.google.com/load-balancing/docs/health-check-concepts)
40        """,
41  }
42
43
44def _Args(parser, include_l7_internal_load_balancing, include_log_config):
45  """Set up arguments to create an HTTPS HealthCheck."""
46  parser.display_info.AddFormat(flags.DEFAULT_LIST_FORMAT)
47  flags.HealthCheckArgument(
48      'HTTPS',
49      include_l7_internal_load_balancing=include_l7_internal_load_balancing
50  ).AddArgument(
51      parser, operation_type='create')
52  health_checks_utils.AddHttpRelatedCreationArgs(parser)
53  health_checks_utils.AddProtocolAgnosticCreationArgs(parser, 'HTTPS')
54  health_checks_utils.AddHttpRelatedResponseArg(parser)
55  if include_log_config:
56    health_checks_utils.AddHealthCheckLoggingRelatedArgs(parser)
57  parser.display_info.AddCacheUpdater(completers.HealthChecksCompleterAlpha
58                                      if include_l7_internal_load_balancing else
59                                      completers.HttpsHealthChecksCompleter)
60
61
62def _Run(args, holder, include_l7_internal_load_balancing, include_log_config):
63  """Issues the request necessary for adding the health check."""
64  client = holder.client
65  messages = client.messages
66
67  health_check_ref = flags.HealthCheckArgument(
68      'HTTPS',
69      include_l7_internal_load_balancing=include_l7_internal_load_balancing
70  ).ResolveAsResource(
71      args, holder.resources, default_scope=compute_scope.ScopeEnum.GLOBAL)
72  proxy_header = messages.HTTPSHealthCheck.ProxyHeaderValueValuesEnum(
73      args.proxy_header)
74
75  https_health_check = messages.HTTPSHealthCheck(
76      host=args.host,
77      port=args.port,
78      portName=args.port_name,
79      requestPath=args.request_path,
80      proxyHeader=proxy_header,
81      response=args.response)
82
83  health_checks_utils.ValidateAndAddPortSpecificationToHealthCheck(
84      args, https_health_check)
85
86  if health_checks_utils.IsRegionalHealthCheckRef(health_check_ref):
87    request = messages.ComputeRegionHealthChecksInsertRequest(
88        healthCheck=messages.HealthCheck(
89            name=health_check_ref.Name(),
90            description=args.description,
91            type=messages.HealthCheck.TypeValueValuesEnum.HTTPS,
92            httpsHealthCheck=https_health_check,
93            checkIntervalSec=args.check_interval,
94            timeoutSec=args.timeout,
95            healthyThreshold=args.healthy_threshold,
96            unhealthyThreshold=args.unhealthy_threshold),
97        project=health_check_ref.project,
98        region=health_check_ref.region)
99    collection = client.apitools_client.regionHealthChecks
100  else:
101    request = messages.ComputeHealthChecksInsertRequest(
102        healthCheck=messages.HealthCheck(
103            name=health_check_ref.Name(),
104            description=args.description,
105            type=messages.HealthCheck.TypeValueValuesEnum.HTTPS,
106            httpsHealthCheck=https_health_check,
107            checkIntervalSec=args.check_interval,
108            timeoutSec=args.timeout,
109            healthyThreshold=args.healthy_threshold,
110            unhealthyThreshold=args.unhealthy_threshold),
111        project=health_check_ref.project)
112    collection = client.apitools_client.healthChecks
113
114  if include_log_config:
115    request.healthCheck.logConfig = health_checks_utils.CreateLogConfig(
116        client, args)
117
118  return client.MakeRequests([(collection, 'Insert', request)])
119
120
121@base.ReleaseTracks(base.ReleaseTrack.GA)
122class Create(base.CreateCommand):
123  """Create a HTTPS health check."""
124
125  _include_l7_internal_load_balancing = True
126  _include_log_config = True
127  detailed_help = _DetailedHelp()
128
129  @classmethod
130  def Args(cls, parser):
131    _Args(parser, cls._include_l7_internal_load_balancing,
132          cls._include_log_config)
133
134  def Run(self, args):
135    holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
136    return _Run(args, holder, self._include_l7_internal_load_balancing,
137                self._include_log_config)
138
139
140@base.ReleaseTracks(base.ReleaseTrack.BETA)
141class CreateBeta(Create):
142
143  pass
144
145
146@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
147class CreateAlpha(CreateBeta):
148
149  pass
150