File: command.py

package info (click to toggle)
python-blazarclient 4.3.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 460 kB
  • sloc: python: 2,742; makefile: 18; sh: 2
file content (369 lines) | stat: -rw-r--r-- 12,448 bytes parent folder | download | duplicates (2)
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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
# Copyright (c) 2013 Mirantis Inc.
#
# 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 ast
import logging

from cliff import command
from cliff.formatters import table
from cliff import lister
from cliff import show

from blazarclient import exception
from blazarclient import utils

HEX_ELEM = '[0-9A-Fa-f]'
UUID_PATTERN = '-'.join([HEX_ELEM + '{8}', HEX_ELEM + '{4}',
                         HEX_ELEM + '{4}', HEX_ELEM + '{4}',
                         HEX_ELEM + '{12}'])


class OpenStackCommand(command.Command):
    """Base class for OpenStack commands."""

    api = None

    def run(self, parsed_args):
        if not self.api:
            return
        else:
            return super(OpenStackCommand, self).run(parsed_args)

    def get_data(self, parsed_args):
        pass

    def take_action(self, parsed_args):
        return self.get_data(parsed_args)


class TableFormatter(table.TableFormatter):
    """This class is used to keep consistency with prettytable 0.6."""

    def emit_list(self, column_names, data, stdout, parsed_args):
        if column_names:
            super(TableFormatter, self).emit_list(column_names, data, stdout,
                                                  parsed_args)
        else:
            stdout.write('\n')


class BlazarCommand(OpenStackCommand):

    """Base Blazar CLI command."""
    api = 'reservation'
    log = logging.getLogger(__name__ + '.BlazarCommand')
    values_specs = []
    json_indent = None
    resource = None
    allow_names = True
    name_key = None
    id_pattern = UUID_PATTERN

    def __init__(self, app, app_args):
        super(BlazarCommand, self).__init__(app, app_args)

        # NOTE(dbelova): This is no longer supported in cliff version 1.5.2
        # the same moment occurred in Neutron:
        # see https://bugs.launchpad.net/python-neutronclient/+bug/1265926

        # if hasattr(self, 'formatters'):
        #     self.formatters['table'] = TableFormatter()

    def get_client(self):
        # client_manager.reservation is used for osc_lib, and should be used
        # if it exists
        if hasattr(self.app, 'client_manager'):
            return self.app.client_manager.reservation
        else:
            return self.app.client

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

    def format_output_data(self, data):
        for k, v in data.items():
            if isinstance(v, str):
                try:
                    # Deserialize if possible into dict, lists, tuples...
                    v = ast.literal_eval(v)
                except SyntaxError:
                    # NOTE(sbauza): This is probably a datetime string, we need
                    #               to keep it unchanged.
                    pass
                except ValueError:
                    # NOTE(sbauza): This is not something AST can evaluate,
                    #               probably a string.
                    pass
            if isinstance(v, list):
                value = '\n'.join(utils.dumps(
                    i, indent=self.json_indent) if isinstance(i, dict)
                    else str(i) for i in v)
                data[k] = value
            elif isinstance(v, dict):
                value = utils.dumps(v, indent=self.json_indent)
                data[k] = value
            elif v is None:
                data[k] = ''

    def add_known_arguments(self, parser):
        pass

    def args2body(self, parsed_args):
        return {}


class CreateCommand(BlazarCommand, show.ShowOne):
    """Create resource with passed args."""

    api = 'reservation'
    resource = None
    log = None

    def get_data(self, parsed_args):
        self.log.debug('get_data(%s)' % parsed_args)
        blazar_client = self.get_client()
        body = self.args2body(parsed_args)
        resource_manager = getattr(blazar_client, self.resource)
        data = resource_manager.create(**body)
        self.format_output_data(data)

        if data:
            print('Created a new %s:' % self.resource, file=self.app.stdout)
        else:
            data = {'': ''}
        return list(zip(*sorted(data.items())))


class UpdateCommand(BlazarCommand):
    """Update resource's information."""

    api = 'reservation'
    resource = None
    log = None

    def get_parser(self, prog_name):
        parser = super(UpdateCommand, self).get_parser(prog_name)
        if self.allow_names:
            help_str = 'ID or name of %s to update'
        else:
            help_str = 'ID of %s to update'
        parser.add_argument(
            'id', metavar=self.resource.upper(),
            help=help_str % self.resource
        )
        self.add_known_arguments(parser)
        return parser

    def run(self, parsed_args):
        self.log.debug('run(%s)' % parsed_args)
        blazar_client = self.get_client()
        body = self.args2body(parsed_args)
        if self.allow_names:
            res_id = utils.find_resource_id_by_name_or_id(blazar_client,
                                                          self.resource,
                                                          parsed_args.id,
                                                          self.name_key,
                                                          self.id_pattern)
        else:
            res_id = parsed_args.id
        resource_manager = getattr(blazar_client, self.resource)
        resource_manager.update(res_id, **body)
        print('Updated %s: %s' % (self.resource, parsed_args.id),
              file=self.app.stdout)
        return


class DeleteCommand(BlazarCommand):
    """Delete a given resource."""

    api = 'reservation'
    resource = None
    log = None

    def get_parser(self, prog_name):
        parser = super(DeleteCommand, self).get_parser(prog_name)
        if self.allow_names:
            help_str = 'ID or name of %s to delete'
        else:
            help_str = 'ID of %s to delete'
        parser.add_argument(
            'id', metavar=self.resource.upper(),
            help=help_str % self.resource)
        return parser

    def run(self, parsed_args):
        self.log.debug('run(%s)' % parsed_args)
        blazar_client = self.get_client()
        resource_manager = getattr(blazar_client, self.resource)
        if self.allow_names:
            res_id = utils.find_resource_id_by_name_or_id(blazar_client,
                                                          self.resource,
                                                          parsed_args.id,
                                                          self.name_key,
                                                          self.id_pattern)
        else:
            res_id = parsed_args.id
        resource_manager.delete(res_id)
        print('Deleted %s: %s' % (self.resource, parsed_args.id),
              file=self.app.stdout)
        return


class ListCommand(BlazarCommand, lister.Lister):
    """List resources that belong to a given tenant."""

    api = 'reservation'
    resource = None
    log = None
    _formatters = {}
    list_columns = []
    unknown_parts_flag = True

    def args2body(self, parsed_args):
        params = {}
        if parsed_args.sort_by:
            if parsed_args.sort_by in self.list_columns:
                params['sort_by'] = parsed_args.sort_by
            else:
                msg = 'Invalid sort option %s' % parsed_args.sort_by
                raise exception.BlazarClientException(msg)
        return params

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

    def retrieve_list(self, parsed_args):
        """Retrieve a list of resources from Blazar server."""
        blazar_client = self.get_client()
        body = self.args2body(parsed_args)
        resource_manager = getattr(blazar_client, self.resource)
        data = resource_manager.list(**body)
        return data

    def setup_columns(self, info, parsed_args):
        columns = len(info) > 0 and sorted(info[0].keys()) or []
        if not columns:
            parsed_args.columns = []
        elif parsed_args.columns:
            columns = [col for col in parsed_args.columns if col in columns]
        elif self.list_columns:
            columns = [col for col in self.list_columns if col in columns]
        return (
            columns,
            (utils.get_item_properties(s, columns, formatters=self._formatters)
             for s in info)
        )

    def get_data(self, parsed_args):
        self.log.debug('get_data(%s)' % parsed_args)
        data = self.retrieve_list(parsed_args)
        return self.setup_columns(data, parsed_args)


class ShowCommand(BlazarCommand, show.ShowOne):
    """Show information of a given resource."""

    api = 'reservation'
    resource = None
    log = None

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

    def get_data(self, parsed_args):
        self.log.debug('get_data(%s)' % parsed_args)
        blazar_client = self.get_client()

        if self.allow_names:
            res_id = utils.find_resource_id_by_name_or_id(blazar_client,
                                                          self.resource,
                                                          parsed_args.id,
                                                          self.name_key,
                                                          self.id_pattern)
        else:
            res_id = parsed_args.id

        resource_manager = getattr(blazar_client, self.resource)
        data = resource_manager.get(res_id)
        self.format_output_data(data)
        return list(zip(*sorted(data.items())))


class ShowPropertyCommand(BlazarCommand, show.ShowOne):
    """Show information of a given resource property."""

    api = 'reservation'
    resource = None
    log = None

    def get_parser(self, prog_name):
        parser = super(ShowPropertyCommand, self).get_parser(prog_name)
        parser.add_argument('property_name', metavar='PROPERTY_NAME',
                            help='Name of property.')
        return parser

    def get_data(self, parsed_args):
        self.log.debug('get_data(%s)' % parsed_args)
        blazar_client = self.get_client()
        resource_manager = getattr(blazar_client, self.resource)
        data = resource_manager.get_property(parsed_args.property_name)
        if parsed_args.formatter == 'table':
            self.format_output_data(data)
        return list(zip(*sorted(data.items())))


class UpdatePropertyCommand(BlazarCommand):
    api = 'reservation'
    resource = None
    log = None

    def run(self, parsed_args):
        self.log.debug('run(%s)' % parsed_args)
        blazar_client = self.get_client()
        body = self.args2body(parsed_args)
        resource_manager = getattr(blazar_client, self.resource)
        resource_manager.set_property(**body)
        print(
            'Updated %s property: %s' % (
                self.resource, parsed_args.property_name),
            file=self.app.stdout)
        return

    def get_parser(self, prog_name):
        parser = super(UpdatePropertyCommand, self).get_parser(prog_name)
        parser.add_argument(
            'property_name', metavar='PROPERTY_NAME',
            help='Name of property to patch.'
        )
        parser.add_argument(
            '--private',
            action='store_true',
            default=False,
            help='Set property to private.'
        )
        parser.add_argument(
            '--public',
            action='store_true',
            default=False,
            help='Set property to public.'
        )
        return parser

    def args2body(self, parsed_args):
        return dict(
            property_name=parsed_args.property_name,
            private=(parsed_args.private is True))