Statistics
| Branch: | Tag: | Revision:

root / snf-django-lib / snf_django / management / commands / __init__.py @ fa532396

History | View | Annotate | Download (14.3 kB)

1
# Copyright 2012-2014 GRNET S.A. All rights reserved.
2
#
3
# Redistribution and use in source and binary forms, with or
4
# without modification, are permitted provided that the following
5
# conditions are met:
6
#
7
#   1. Redistributions of source code must retain the above
8
#      copyright notice, this list of conditions and the following
9
#      disclaimer.
10
#
11
#   2. Redistributions in binary form must reproduce the above
12
#      copyright notice, this list of conditions and the following
13
#      disclaimer in the documentation and/or other materials
14
#      provided with the distribution.
15
#
16
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
17
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
20
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
23
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
24
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
26
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27
# POSSIBILITY OF SUCH DAMAGE.
28
#
29
# The views and conclusions contained in the software and
30
# documentation are those of the authors and should not be
31
# interpreted as representing official policies, either expressed
32
# or implied, of GRNET S.A.
33

    
34
from optparse import (make_option, OptionParser, OptionGroup,
35
                      TitledHelpFormatter)
36

    
37
from django.core.management.base import BaseCommand, CommandError
38
from django.core.exceptions import FieldError
39

    
40
from snf_django.management import utils
41
from snf_django.lib.astakos import UserCache
42

    
43
import distutils
44

    
45
USER_EMAIL_FIELD = "user.email"
46

    
47

    
48
class SynnefoCommandFormatter(TitledHelpFormatter):
49
    def format_heading(self, heading):
50
        if heading == "Options":
51
            return ""
52
        return "%s\n%s\n" % (heading, "=-"[self.level] * len(heading))
53

    
54

    
55
class SynnefoCommand(BaseCommand):
56
    option_list = BaseCommand.option_list + (
57
        make_option(
58
            "--output-format",
59
            dest="output_format",
60
            metavar="[pretty, csv, json]",
61
            default="pretty",
62
            choices=["pretty", "csv", "json"],
63
            help="Select the output format: pretty [the default], json, "
64
                 "csv [comma-separated output]"),
65
    )
66

    
67
    def create_parser(self, prog_name, subcommand):
68
        parser = OptionParser(prog=prog_name, add_help_option=False,
69
                              formatter=SynnefoCommandFormatter())
70

    
71
        parser.set_usage(self.usage(subcommand))
72
        parser.version = self.get_version()
73

    
74
        # Handle Django's and common options
75
        common_options = OptionGroup(parser, "Common Options")
76
        common_options.add_option("-h", "--help", action="help",
77
                                  help="show this help message and exit")
78

    
79
        common_options.add_option("--version", action="version",
80
                                  help="show program's version number and"
81
                                       "  exit")
82
        [common_options.add_option(o) for o in self.option_list]
83
        if common_options.option_list:
84
            parser.add_option_group(common_options)
85

    
86
        # Handle command specific options
87
        command_options = OptionGroup(parser, "Command Specific Options")
88
        [command_options.add_option(o)
89
         for o in getattr(self, "command_option_list", ())]
90
        if command_options.option_list:
91
            parser.add_option_group(command_options)
92

    
93
        return parser
94

    
95

    
96
class ListCommand(SynnefoCommand):
97
    """Generic *-list management command.
98

99
    Management command to handle common tasks when implementing a -list
100
    management command. This class handles the following tasks:
101

102
    * Retrieving objects from database.
103

104
    The DB model class is declared in ``object_class`` class attribute. Also,
105
    results can be filter using either the ``filters`` and ``excludes``
106
    attribute or the "--filter-by" option.
107

108
    * Display specific fields of the database objects.
109

110
    List of available fields is defined in the ``FIELDS`` class attribute,
111
    which is a dictionary mapping from field names to tuples containing the
112
    way the field is retrieved and a text help message to display. The first
113
    field of the tuple is either a string containing a chain of attribute
114
    accesses (e.g. "machine.flavor.cpu") either a callable function, taking
115
    as argument the DB object and returning a single value.
116

117
    The fields that will be displayed be default is contained in the ``fields``
118
    class attribute. The user can specify different fields using the "--fields"
119
    option.
120

121
    * Handling of user UUIDs and names.
122

123
    If the ``user_uuid_field`` is declared, then "--user" and "--display-mails"
124
    options will become available. The first one allows filtering via either
125
    a user's UUID or display name. The "--displayname" option will append
126
    the displayname of ther user with "user_uuid_field" to the output.
127

128
    * Pretty printing output to a nice table.
129

130
    """
131

    
132
    # The following fields must be handled in the ListCommand subclasses!
133

    
134
    # The django DB model
135
    object_class = None
136
    # The name of the field containg the user ID of the user, if any.
137
    user_uuid_field = None
138
    # The name of the field containg the deleted flag, if any.
139
    deleted_field = None
140
    # Dictionary with all available fields
141
    FIELDS = {}
142
    # List of fields to display by default
143
    fields = []
144
    # Default filters and excludes
145
    filters = {}
146
    excludes = {}
147
    # Order results
148
    order_by = None
149

    
150
    # Fields used only with user_user_field
151
    astakos_auth_url = None
152
    astakos_token = None
153

    
154
    # Optimize DB queries
155
    prefetch_related = []
156
    select_related = []
157

    
158
    help = "Generic List Command"
159
    option_list = SynnefoCommand.option_list + (
160
        make_option(
161
            "-o", "--output",
162
            dest="fields",
163
            help="Comma-separated list of output fields"),
164
        make_option(
165
            "--list-fields",
166
            dest="list_fields",
167
            action="store_true",
168
            default=False,
169
            help="List available output fields"),
170
        make_option(
171
            "--filter-by",
172
            dest="filter_by",
173
            metavar="FILTERS",
174
            help="Filter results. Comma separated list of key `cond` val pairs"
175
                 " that displayed entries must satisfy. e.g."
176
                 " --filter-by \"deleted=False,id>=22\"."),
177
        make_option(
178
            "--list-filters",
179
            dest="list_filters",
180
            action="store_true",
181
            default=False,
182
            help="List available filters"),
183
        make_option(
184
            "--no-headers",
185
            dest="headers",
186
            action="store_false",
187
            default=True,
188
            help="Do not display headers"),
189
    )
190

    
191
    def __init__(self, *args, **kwargs):
192
        if self.user_uuid_field:
193
            assert(self.astakos_auth_url), "astakos_auth_url attribute is "\
194
                                           "needed when user_uuid_field "\
195
                                           "is declared"
196
            assert(self.astakos_token), "astakos_token attribute is needed"\
197
                                        " when user_uuid_field is declared"
198
            self.option_list += (
199
                make_option(
200
                    "-u", "--user",
201
                    dest="user",
202
                    metavar="USER",
203
                    help="List items only for this user."
204
                         " 'USER' can be either a user UUID or a display"
205
                         " name"),
206
                make_option(
207
                    "--display-mails",
208
                    dest="display_mails",
209
                    action="store_true",
210
                    default=False,
211
                    help="Include the user's email"),
212
            )
213

    
214
        if self.deleted_field:
215
            self.option_list += (
216
                make_option(
217
                    "-d", "--deleted",
218
                    dest="deleted",
219
                    action="store_true",
220
                    help="Display only deleted items"),
221
            )
222
        super(ListCommand, self).__init__(*args, **kwargs)
223

    
224
    def handle(self, *args, **options):
225
        if len(args) > 0:
226
            raise CommandError("List commands do not accept any argument")
227

    
228
        assert(self.object_class), "object_class variable must be declared"
229

    
230
        # If an user field is declared, include the USER_EMAIL_FIELD in the
231
        # available fields
232
        if self.user_uuid_field is not None:
233
            self.FIELDS[USER_EMAIL_FIELD] =\
234
                ("_user_email", "The email of the owner")
235

    
236
        if options["list_fields"]:
237
            self.display_fields()
238
            return
239

    
240
        if options["list_filters"]:
241
            self.display_filters()
242
            return
243

    
244
        # --output option
245
        if options["fields"]:
246
            fields = options["fields"]
247
            fields = fields.split(",")
248
            self.validate_fields(fields)
249
            self.fields = options["fields"].split(",")
250

    
251
        # --display-mails option
252
        if options.get("display_mails"):
253
            self.fields.append(USER_EMAIL_FIELD)
254

    
255
        # --filter-by option
256
        if options["filter_by"]:
257
            filters, excludes = \
258
                utils.parse_queryset_filters(options["filter_by"])
259
        else:
260
            filters, excludes = ({}, {})
261

    
262
        self.filters.update(filters)
263
        self.excludes.update(excludes)
264

    
265
        # --user option
266
        user = options.get("user")
267
        if user:
268
            if "@" in user:
269
                ucache = UserCache(self.astakos_auth_url, self.astakos_token)
270
                user = ucache.get_uuid(user)
271
            self.filters[self.user_uuid_field] = user
272

    
273
        # --deleted option
274
        if self.deleted_field:
275
            deleted = options.get("deleted")
276
            if deleted:
277
                self.filters[self.deleted_field] = True
278
            else:
279
                self.filters[self.deleted_field] = False
280

    
281
        # Special handling of arguments
282
        self.handle_args(self, *args, **options)
283

    
284
        select_related = getattr(self, "select_related", [])
285
        prefetch_related = getattr(self, "prefetch_related", [])
286

    
287
        objects = self.object_class.objects
288
        try:
289
            if select_related:
290
                objects = objects.select_related(*select_related)
291
            if prefetch_related:
292
                objects = objects.prefetch_related(*prefetch_related)
293
            objects = objects.filter(**self.filters)
294
            for key, value in self.excludes.iteritems():
295
                objects = objects.exclude(**{key:value})
296
        except FieldError as e:
297
            raise CommandError(e)
298
        except Exception as e:
299
            raise CommandError("Can not filter results: %s" % e)
300

    
301
        order_key = self.order_by if self.order_by is not None else 'pk'
302
        objects = objects.order_by(order_key)
303

    
304
        if USER_EMAIL_FIELD in self.fields:
305
            if '_user_email' in self.object_class._meta.get_all_field_names():
306
                raise RuntimeError("%s has already a 'user_mail' attribute")
307
            uuids = [getattr(obj, self.user_uuid_field) for obj in objects]
308
            ucache = UserCache(self.astakos_auth_url, self.astakos_token)
309
            ucache.fetch_names(list(set(uuids)))
310
            for obj in objects:
311
                uuid = getattr(obj, self.user_uuid_field)
312
                obj._user_email = ucache.get_name(uuid)
313

    
314
        # Special handling of DB results
315
        objects = list(objects)
316
        self.handle_db_objects(objects, **options)
317

    
318
        headers = self.fields
319
        columns = [self.FIELDS[key][0] for key in headers]
320

    
321
        table = []
322
        for obj in objects:
323
            row = []
324
            for attr in columns:
325
                if callable(attr):
326
                    row.append(attr(obj))
327
                else:
328
                    item = obj
329
                    attrs = attr.split(".")
330
                    for attr in attrs:
331
                        item = getattr(item, attr)
332
                    row.append(item)
333
            table.append(row)
334

    
335
        # Special handle of output
336
        self.handle_output(table, headers)
337

    
338
        # Print output
339
        output_format = options["output_format"]
340
        if output_format != "json" and not options["headers"]:
341
            headers = None
342
        utils.pprint_table(self.stdout, table, headers, output_format)
343

    
344
    def handle_args(self, *args, **kwargs):
345
        pass
346

    
347
    def handle_db_objects(self, objects, **options):
348
        pass
349

    
350
    def handle_output(self, table, headers):
351
        pass
352

    
353
    def display_fields(self):
354
        headers = ["Field", "Description"]
355
        table = []
356
        for field, (_, help_msg) in self.FIELDS.items():
357
            table.append((field, help_msg))
358
        utils.pprint_table(self.stdout, table, headers)
359

    
360
    def validate_fields(self, fields):
361
        for f in fields:
362
            if f not in self.FIELDS.keys():
363
                raise CommandError("Unknown field '%s'. 'Use --list-fields"
364
                                   " option to find out available fields."
365
                                   % f)
366

    
367
    def display_filters(self):
368
        headers = ["Filter", "Description", "Help"]
369
        table = []
370
        for field in self.object_class._meta.fields:
371
            table.append((field.name, field.verbose_name, field.help_text))
372
        utils.pprint_table(self.stdout, table, headers)
373

    
374

    
375
class RemoveCommand(BaseCommand):
376
    help = "Generic remove command"
377
    option_list = BaseCommand.option_list + (
378
        make_option(
379
            "-f", "--force",
380
            dest="force",
381
            action="store_true",
382
            default=False,
383
            help="Do not prompt for confirmation"),
384
    )
385

    
386
    def confirm_deletion(self, force, resource='', args=''):
387
        if force is True:
388
            return True
389

    
390
        ids = ', '.join(args)
391
        self.stdout.write("Are you sure you want to delete %s %s?"
392
                          " [Y/N] " % (resource, ids))
393
        try:
394
            answer = distutils.util.strtobool(raw_input())
395
            if answer != 1:
396
                raise CommandError("Aborting deletion")
397
        except ValueError:
398
            raise CommandError("Unaccepted input value. Please choose yes/no"
399
                               " (y/n).")