summaryrefslogtreecommitdiff
path: root/designateclient/v2/cli/recordsets.py
blob: 229c3465845a9fb4b20e04dc36520abc5ebe431d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
# Copyright 2014 Hewlett-Packard Development Company, L.P.
#
# Author: Endre Karlson <endre.karlson@hp.com>
#
# 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.

import argparse
import logging

from osc_lib.command import command
import six

from designateclient import utils
from designateclient.v2.cli import common
from designateclient.v2.utils import get_all


LOG = logging.getLogger(__name__)


def _format_recordset(recordset):
    # Remove unneeded fields for display output formatting
    recordset['records'] = "\n".join(recordset['records'])
    recordset.pop('links', None)
    return recordset


def _has_project_id(data):
    if len(data) < 1:
        return False
    if 'project_id' in data[0]:
        return True
    return False


class ListRecordSetsCommand(command.Lister):
    """List recordsets"""

    columns = ['id', 'name', 'type', 'records', 'status', 'action']

    def get_parser(self, prog_name):
        parser = super(ListRecordSetsCommand, self).get_parser(prog_name)

        parser.add_argument('--name', help="RecordSet Name", required=False)
        parser.add_argument('--type', help="RecordSet Type", required=False)
        parser.add_argument('--data', help="RecordSet Record Data",
                            required=False)
        parser.add_argument('--ttl', help="Time To Live (Seconds)",
                            required=False)
        parser.add_argument('--description', help="Description",
                            required=False)
        parser.add_argument('--status', help="RecordSet Status",
                            required=False)
        parser.add_argument('--action', help="RecordSet Action",
                            required=False)

        parser.add_argument('zone_id', help="Zone ID. To list all"
                            " recordsets specify 'all'")

        common.add_all_common_options(parser)

        return parser

    def take_action(self, parsed_args):
        client = self.app.client_manager.dns
        common.set_all_common_headers(client, parsed_args)

        criterion = {}
        if parsed_args.type is not None:
            criterion["type"] = parsed_args.type

        if parsed_args.name is not None:
            criterion["name"] = parsed_args.name

        if parsed_args.data is not None:
            criterion["data"] = parsed_args.data

        if parsed_args.ttl is not None:
            criterion["ttl"] = parsed_args.ttl

        if parsed_args.description is not None:
            criterion["description"] = parsed_args.description

        if parsed_args.status is not None:
            criterion["status"] = parsed_args.status

        if parsed_args.action is not None:
            criterion["action"] = parsed_args.action

        cols = list(self.columns)

        if parsed_args.zone_id == 'all':
            data = get_all(client.recordsets.list_all_zones,
                           criterion=criterion)
            cols.insert(2, 'zone_name')
        else:
            data = get_all(client.recordsets.list, args=[parsed_args.zone_id],
                           criterion=criterion)

        if client.session.all_projects and _has_project_id(data):
            cols.insert(1, 'project_id')

        for i, rs in enumerate(data):
            data[i] = _format_recordset(rs)

        return cols, (utils.get_item_properties(s, cols) for s in data)


class ShowRecordSetCommand(command.ShowOne):
    """Show recordset details"""

    def get_parser(self, prog_name):
        parser = super(ShowRecordSetCommand, self).get_parser(prog_name)

        parser.add_argument('zone_id', help="Zone ID")
        parser.add_argument('id', help="RecordSet ID")

        common.add_all_common_options(parser)

        return parser

    def take_action(self, parsed_args):
        client = self.app.client_manager.dns
        common.set_all_common_headers(client, parsed_args)
        data = client.recordsets.get(parsed_args.zone_id, parsed_args.id)

        _format_recordset(data)
        return six.moves.zip(*sorted(six.iteritems(data)))


class CreateRecordSetCommand(command.ShowOne):
    """Create new recordset"""

    log = logging.getLogger('deprecated')

    def get_parser(self, prog_name):
        parser = super(CreateRecordSetCommand, self).get_parser(prog_name)

        parser.add_argument('zone_id', help="Zone ID")
        parser.add_argument('name', help="RecordSet Name")
        req_group = parser.add_mutually_exclusive_group(required=True)
        req_group.add_argument(
            '--records',
            help=argparse.SUPPRESS,
            nargs='+')
        req_group.add_argument(
            '--record',
            help="RecordSet Record, repeat if necessary",
            action='append')
        parser.add_argument('--type', help="RecordSet Type", required=True)
        parser.add_argument('--ttl', type=int, help="Time To Live (Seconds)")
        parser.add_argument('--description', help="Description")

        common.add_all_common_options(parser)

        return parser

    def take_action(self, parsed_args):
        client = self.app.client_manager.dns
        common.set_all_common_headers(client, parsed_args)

        all_records = parsed_args.record or parsed_args.records
        if parsed_args.records:
            self.log.warning(
                "Option --records is deprecated, use --record instead.")
        data = client.recordsets.create(
            parsed_args.zone_id,
            parsed_args.name,
            parsed_args.type,
            all_records,
            description=parsed_args.description,
            ttl=parsed_args.ttl)

        _format_recordset(data)
        return six.moves.zip(*sorted(six.iteritems(data)))


class SetRecordSetCommand(command.ShowOne):
    """Set recordset properties"""

    def get_parser(self, prog_name):
        parser = super(SetRecordSetCommand, self).get_parser(prog_name)

        parser.add_argument('zone_id', help="Zone ID")
        parser.add_argument('id', help="RecordSet ID")
        req_group = parser.add_mutually_exclusive_group()
        req_group.add_argument(
            '--records',
            help=argparse.SUPPRESS,
            nargs='+')
        req_group.add_argument(
            '--record',
            help="RecordSet Record, repeat if necessary",
            action='append')

        description_group = parser.add_mutually_exclusive_group()
        description_group.add_argument('--description', help="Description")
        description_group.add_argument('--no-description', action='store_true')

        ttl_group = parser.add_mutually_exclusive_group()
        ttl_group.add_argument('--ttl', type=int, help="TTL")
        ttl_group.add_argument('--no-ttl', action='store_true')

        common.add_all_common_options(parser)

        return parser

    def take_action(self, parsed_args):
        data = {}

        if parsed_args.no_description:
            data['description'] = None
        elif parsed_args.description:
            data['description'] = parsed_args.description

        if parsed_args.no_ttl:
            data['ttl'] = None
        elif parsed_args.ttl:
            data['ttl'] = parsed_args.ttl

        all_records = parsed_args.record or parsed_args.records
        if parsed_args.records:
            self.log.warning(
                "Option --records is deprecated, use --record instead.")

        if all_records:
            data['records'] = all_records

        client = self.app.client_manager.dns
        common.set_all_common_headers(client, parsed_args)

        updated = client.recordsets.update(
            parsed_args.zone_id,
            parsed_args.id,
            data)

        _format_recordset(updated)

        return six.moves.zip(*sorted(six.iteritems(updated)))


class DeleteRecordSetCommand(command.ShowOne):
    """Delete recordset"""

    def get_parser(self, prog_name):
        parser = super(DeleteRecordSetCommand, self).get_parser(prog_name)

        parser.add_argument('zone_id', help="Zone ID")
        parser.add_argument('id', help="RecordSet ID")

        common.add_all_common_options(parser)

        return parser

    def take_action(self, parsed_args):
        client = self.app.client_manager.dns
        common.set_all_common_headers(client, parsed_args)
        data = client.recordsets.delete(parsed_args.zone_id, parsed_args.id)

        LOG.info('RecordSet %s was deleted', parsed_args.id)

        _format_recordset(data)
        return six.moves.zip(*sorted(six.iteritems(data)))