1# -*- coding: utf-8 -*- #
2# Copyright 2019 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"""Import ssl policy command."""
16
17from __future__ import absolute_import
18from __future__ import division
19from __future__ import unicode_literals
20
21from apitools.base.py import exceptions as apitools_exceptions
22from googlecloudsdk.api_lib.compute import base_classes
23from googlecloudsdk.api_lib.compute.ssl_policies import ssl_policies_utils
24from googlecloudsdk.calliope import base
25from googlecloudsdk.calliope import exceptions
26from googlecloudsdk.command_lib.compute import flags as compute_flags
27from googlecloudsdk.command_lib.compute.ssl_policies import flags
28from googlecloudsdk.command_lib.export import util as export_util
29from googlecloudsdk.core import yaml_validator
30from googlecloudsdk.core.console import console_io
31
32
33@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
34class Import(base.UpdateCommand):
35  """Import an SSL policy.
36
37  If the specified SSL policy already exists, it will be overwritten.
38  Otherwise, a new SSL policy will be created.
39  To edit an SSL policy you can export the SSL policy to a file,
40  edit its configuration, and then import the new configuration.
41  """
42
43  SSL_POLICY_ARG = None
44
45  @classmethod
46  def GetApiVersion(cls):
47    """Returns the API version based on the release track."""
48    if cls.ReleaseTrack() == base.ReleaseTrack.ALPHA:
49      return 'alpha'
50    elif cls.ReleaseTrack() == base.ReleaseTrack.BETA:
51      return 'beta'
52    return 'v1'
53
54  @classmethod
55  def GetSchemaPath(cls, for_help=False):
56    """Returns the resource schema path."""
57    return export_util.GetSchemaPath(
58        'compute', cls.GetApiVersion(), 'SslPolicy', for_help=for_help)
59
60  @classmethod
61  def Args(cls, parser):
62    cls.SSL_POLICY_ARG = flags.GetSslPolicyArgument()
63    cls.SSL_POLICY_ARG.AddArgument(parser, operation_type='import')
64    export_util.AddImportFlags(parser, cls.GetSchemaPath(for_help=True))
65
66  def Run(self, args):
67    holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
68    helper = ssl_policies_utils.SslPolicyHelper(holder)
69    client = holder.client
70
71    ssl_policy_ref = self.SSL_POLICY_ARG.ResolveAsResource(
72        args,
73        holder.resources,
74        scope_lister=compute_flags.GetDefaultScopeLister(holder.client))
75
76    data = console_io.ReadFromFileOrStdin(args.source or '-', binary=False)
77
78    try:
79      ssl_policy = export_util.Import(
80          message_type=client.messages.SslPolicy,
81          stream=data,
82          schema_path=self.GetSchemaPath())
83    except yaml_validator.ValidationError as e:
84      raise exceptions.ToolException(str(e))
85
86    # Get existing SSL policy.
87    try:
88      ssl_policy_old = helper.Describe(ssl_policy_ref)
89    except apitools_exceptions.HttpError as error:
90      if error.status_code != 404:
91        raise error
92      # SSL policy does not exist, create a new one.
93      operation_ref = helper.Create(ssl_policy_ref, ssl_policy)
94      return helper.WaitForOperation(ssl_policy_ref, operation_ref,
95                                     'Creating SSL policy')
96
97    # No change, do not send requests to server.
98    if ssl_policy_old == ssl_policy:
99      return
100
101    console_io.PromptContinue(
102        message=('SSL Policy [{0}] will be overwritten.').format(
103            ssl_policy_ref.Name()),
104        cancel_on_no=True)
105
106    # Populate id and fingerprint fields. These two fields are manually
107    # removed from the schema files.
108    ssl_policy.id = ssl_policy_old.id
109    ssl_policy.fingerprint = ssl_policy_old.fingerprint
110
111    operation_ref = helper.Patch(ssl_policy_ref, ssl_policy, False)
112    return helper.WaitForOperation(ssl_policy_ref, operation_ref,
113                                   'Updating SSL policy')
114