1# -*- coding: utf-8 -*- #
2# Copyright 2021 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"""gcloud dns response-policies rules create command."""
16
17from __future__ import absolute_import
18from __future__ import division
19from __future__ import unicode_literals
20
21from googlecloudsdk.api_lib.dns import util
22from googlecloudsdk.api_lib.util import apis
23from googlecloudsdk.calliope import base
24from googlecloudsdk.calliope import exceptions
25from googlecloudsdk.command_lib.dns import flags
26from googlecloudsdk.command_lib.dns import resource_args
27from googlecloudsdk.command_lib.dns import util as command_util
28from googlecloudsdk.core import log
29
30
31def _AddArgsCommon(parser, messages):
32  """Adds the common arguments for all versions."""
33  flags.GetLocalDataResourceRecordSets().AddToParser(parser)
34  flags.AddResponsePolicyRulesBehaviorFlagArgs(parser, messages)
35
36  parser.add_argument(
37      '--dns-name',
38      required=True,
39      help='DNS name (wildcard or exact) to apply this rule to.')
40
41
42@base.ReleaseTracks(base.ReleaseTrack.BETA)
43class CreateBeta(base.UpdateCommand):
44  r"""Creates a new Cloud DNS response policy rule.
45
46      This command creates a new Cloud DNS response policy rule.
47
48      ## EXAMPLES
49
50      To create a new response policy rule with local data rrsets, run:
51
52        $ {command} myresponsepolicyrule --response-policy="myresponsepolicy" --dns-name="www.zone.com." --local-data=name=www.zone.com.,type=CNAME,ttl=21600,rrdatas=zone.com.
53
54      To create a new response policy rule with behavior, run:
55
56        $ {command} myresponsepolicyrule --response-policy="myresponsepolicy" --dns-name="www.zone.com." --behavior=bypassResponsePolicy
57  """
58
59  @staticmethod
60  def Args(parser):
61    messages = apis.GetMessagesModule('dns', 'v1beta2')
62    _AddArgsCommon(parser, messages)
63    resource_args.AddResponsePolicyRuleArg(
64        parser, verb='to create', api_version='v1beta2')
65    parser.display_info.AddFormat('json')
66
67  def Run(self, args):
68    api_version = util.GetApiFromTrack(self.ReleaseTrack())
69    client = util.GetApiClient(api_version)
70    messages = apis.GetMessagesModule('dns', api_version)
71
72    # Get Response Policy Rule
73    response_policy_rule_ref = args.CONCEPTS.response_policy_rule.Parse()
74    response_policy_rule_name = response_policy_rule_ref.Name()
75
76    response_policy_rule = messages.ResponsePolicyRule(
77        ruleName=response_policy_rule_name)
78
79    response_policy_rule.dnsName = args.dns_name
80    response_policy = messages.ResponsePolicy(
81        responsePolicyName=args.response_policy)
82
83    if args.IsSpecified('behavior') and args.IsSpecified('local_data'):
84      raise exceptions.ConflictingArgumentsException(
85          'Only one of arguments [--behavior, --local-data] is allowed.')
86
87    if args.IsSpecified('behavior'):
88      response_policy_rule.behavior = command_util\
89          .ParseResponsePolicyRulesBehavior(args, api_version)
90    elif args.IsSpecified('local_data'):
91      rrsets = []
92      for rrset in args.local_data:
93        resource_record_set = messages.ResourceRecordSet(
94            name=rrset.get('name'),
95            type=rrset.get('type'),
96            ttl=rrset.get('ttl'),
97            rrdatas=rrset.get('rrdatas').split('|'))
98        rrsets.append(resource_record_set)
99
100      local_data = messages.ResponsePolicyRuleLocalData(
101          localDatas=rrsets)
102      response_policy_rule.localData = local_data
103
104    create_request = messages.DnsResponsePolicyRulesCreateRequest(
105        responsePolicy=response_policy.responsePolicyName,
106        project=response_policy_rule_ref.project,
107        responsePolicyRule=response_policy_rule)
108
109    result = client.responsePolicyRules.Create(create_request)
110
111    log.CreatedResource(response_policy_rule, kind='ResponsePolicyRule')
112
113    return result
114
115
116@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
117class CreateAlpha(CreateBeta):
118  r"""Creates a new Cloud DNS response policy rule.
119
120      This command creates a new Cloud DNS response policy rule.
121
122       ## EXAMPLES
123
124      To create a new response policy rule with local data rrsets, run:
125
126        $ {command} myresponsepolicyrule --response-policy="myresponsepolicy" --dns-name="www.zone.com." --local-data=name=www.zone.com.,type=CNAME,ttl=21600,rrdatas=zone.com.
127
128      To create a new response policy rule with behavior, run:
129
130        $ {command} myresponsepolicyrule --response-policy="myresponsepolicy" --dns-name="www.zone.com." --behavior=bypassResponsePolicy
131  """
132
133  @staticmethod
134  def Args(parser):
135    resource_args.AddResponsePolicyRuleArg(
136        parser, verb='to create', api_version='v1alpha2')
137    messages = apis.GetMessagesModule('dns', 'v1alpha2')
138    _AddArgsCommon(parser, messages)
139    parser.display_info.AddFormat('json')
140