Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (13.5 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
35
from django.core.management.base import (BaseCommand, CommandError,
36
                                         handle_default_options)
37
from django.core.exceptions import FieldError
38

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

    
42
import distutils
43

    
44
USER_EMAIL_FIELD = "user.email"
45

    
46

    
47
class SynnefoCommand(BaseCommand):
48
    option_list = BaseCommand.option_list + (
49
        make_option(
50
            "--output-format",
51
            dest="output_format",
52
            metavar="[pretty, csv, json]",
53
            default="pretty",
54
            choices=["pretty", "csv", "json"],
55
            help="Select the output format: pretty [the default], json, "
56
                 "csv [comma-separated output]"),
57
    )
58

    
59
    def run_from_argv(self, argv):
60
        """Override BaseCommand.run_from_argv to decode arguments and options
61

62
        Convert command line arguments and options to unicode objects using
63
        user's preferred encoding.
64

65
        """
66
        parser = self.create_parser(argv[0], argv[1])
67
        options, args = parser.parse_args(argv[2:])
68
        handle_default_options(options)
69
        args = [utils.smart_locale_unicode(a, strings_only=True) for a in args]
70
        options.__dict__.update(
71
            (k, utils.smart_locale_unicode(v, strings_only=True))
72
            for k, v in options.__dict__.items())
73
        self.execute(*args, **options.__dict__)
74

    
75

    
76
class ListCommand(SynnefoCommand):
77
    """Generic *-list management command.
78

79
    Management command to handle common tasks when implementing a -list
80
    management command. This class handles the following tasks:
81

82
    * Retrieving objects from database.
83

84
    The DB model class is declared in ``object_class`` class attribute. Also,
85
    results can be filter using either the ``filters`` and ``excludes``
86
    attribute or the "--filter-by" option.
87

88
    * Display specific fields of the database objects.
89

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

97
    The fields that will be displayed be default is contained in the ``fields``
98
    class attribute. The user can specify different fields using the "--fields"
99
    option.
100

101
    * Handling of user UUIDs and names.
102

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

108
    * Pretty printing output to a nice table.
109

110
    """
111

    
112
    # The following fields must be handled in the ListCommand subclasses!
113

    
114
    # The django DB model
115
    object_class = None
116
    # The name of the field containg the user ID of the user, if any.
117
    user_uuid_field = None
118
    # The name of the field containg the deleted flag, if any.
119
    deleted_field = None
120
    # Dictionary with all available fields
121
    FIELDS = {}
122
    # List of fields to display by default
123
    fields = []
124
    # Default filters and excludes
125
    filters = {}
126
    excludes = {}
127
    # Order results
128
    order_by = None
129

    
130
    # Fields used only with user_user_field
131
    astakos_auth_url = None
132
    astakos_token = None
133

    
134
    # Optimize DB queries
135
    prefetch_related = []
136
    select_related = []
137

    
138
    help = "Generic List Command"
139
    option_list = SynnefoCommand.option_list + (
140
        make_option(
141
            "-o", "--output",
142
            dest="fields",
143
            help="Comma-separated list of output fields"),
144
        make_option(
145
            "--list-fields",
146
            dest="list_fields",
147
            action="store_true",
148
            default=False,
149
            help="List available output fields"),
150
        make_option(
151
            "--filter-by",
152
            dest="filter_by",
153
            metavar="FILTERS",
154
            help="Filter results. Comma separated list of key `cond` val pairs"
155
                 " that displayed entries must satisfy. e.g."
156
                 " --filter-by \"deleted=False,id>=22\"."),
157
        make_option(
158
            "--list-filters",
159
            dest="list_filters",
160
            action="store_true",
161
            default=False,
162
            help="List available filters"),
163
        make_option(
164
            "--no-headers",
165
            dest="headers",
166
            action="store_false",
167
            default=True,
168
            help="Do not display headers"),
169
    )
170

    
171
    def __init__(self, *args, **kwargs):
172
        if self.user_uuid_field:
173
            assert(self.astakos_auth_url), "astakos_auth_url attribute is "\
174
                                           "needed when user_uuid_field "\
175
                                           "is declared"
176
            assert(self.astakos_token), "astakos_token attribute is needed"\
177
                                        " when user_uuid_field is declared"
178
            self.option_list += (
179
                make_option(
180
                    "-u", "--user",
181
                    dest="user",
182
                    metavar="USER",
183
                    help="List items only for this user."
184
                         " 'USER' can be either a user UUID or a display"
185
                         " name"),
186
                make_option(
187
                    "--display-mails",
188
                    dest="display_mails",
189
                    action="store_true",
190
                    default=False,
191
                    help="Include the user's email"),
192
            )
193

    
194
        if self.deleted_field:
195
            self.option_list += (
196
                make_option(
197
                    "-d", "--deleted",
198
                    dest="deleted",
199
                    action="store_true",
200
                    help="Display only deleted items"),
201
            )
202
        super(ListCommand, self).__init__(*args, **kwargs)
203

    
204
    def handle(self, *args, **options):
205
        if len(args) > 0:
206
            raise CommandError("List commands do not accept any argument")
207

    
208
        assert(self.object_class), "object_class variable must be declared"
209

    
210
        # If an user field is declared, include the USER_EMAIL_FIELD in the
211
        # available fields
212
        if self.user_uuid_field is not None:
213
            self.FIELDS[USER_EMAIL_FIELD] =\
214
                ("_user_email", "The email of the owner")
215

    
216
        if options["list_fields"]:
217
            self.display_fields()
218
            return
219

    
220
        if options["list_filters"]:
221
            self.display_filters()
222
            return
223

    
224
        # --output option
225
        if options["fields"]:
226
            fields = options["fields"]
227
            fields = fields.split(",")
228
            self.validate_fields(fields)
229
            self.fields = options["fields"].split(",")
230

    
231
        # --display-mails option
232
        if options.get("display_mails"):
233
            self.fields.append(USER_EMAIL_FIELD)
234

    
235
        # --filter-by option
236
        if options["filter_by"]:
237
            filters, excludes = \
238
                utils.parse_queryset_filters(options["filter_by"])
239
        else:
240
            filters, excludes = ({}, {})
241

    
242
        self.filters.update(filters)
243
        self.excludes.update(excludes)
244

    
245
        # --user option
246
        user = options.get("user")
247
        if user:
248
            if "@" in user:
249
                ucache = UserCache(self.astakos_auth_url, self.astakos_token)
250
                user = ucache.get_uuid(user)
251
            self.filters[self.user_uuid_field] = user
252

    
253
        # --deleted option
254
        if self.deleted_field:
255
            deleted = options.get("deleted")
256
            if deleted:
257
                self.filters[self.deleted_field] = True
258
            else:
259
                self.filters[self.deleted_field] = False
260

    
261
        # Special handling of arguments
262
        self.handle_args(self, *args, **options)
263

    
264
        select_related = getattr(self, "select_related", [])
265
        prefetch_related = getattr(self, "prefetch_related", [])
266

    
267
        objects = self.object_class.objects
268
        try:
269
            if select_related:
270
                objects = objects.select_related(*select_related)
271
            if prefetch_related:
272
                objects = objects.prefetch_related(*prefetch_related)
273
            objects = objects.filter(**self.filters)
274
            for key, value in self.excludes.iteritems():
275
                objects = objects.exclude(**{key: value})
276
        except FieldError as e:
277
            raise CommandError(e)
278
        except Exception as e:
279
            raise CommandError("Can not filter results: %s" % e)
280

    
281
        order_key = self.order_by if self.order_by is not None else 'pk'
282
        objects = objects.order_by(order_key)
283

    
284
        if USER_EMAIL_FIELD in self.fields:
285
            if '_user_email' in self.object_class._meta.get_all_field_names():
286
                raise RuntimeError("%s has already a 'user_mail' attribute")
287
            uuids = [getattr(obj, self.user_uuid_field) for obj in objects]
288
            ucache = UserCache(self.astakos_auth_url, self.astakos_token)
289
            ucache.fetch_names(list(set(uuids)))
290
            for obj in objects:
291
                uuid = getattr(obj, self.user_uuid_field)
292
                obj._user_email = ucache.get_name(uuid)
293

    
294
        # Special handling of DB results
295
        objects = list(objects)
296
        self.handle_db_objects(objects, **options)
297

    
298
        headers = self.fields
299
        columns = [self.FIELDS[key][0] for key in headers]
300

    
301
        table = []
302
        for obj in objects:
303
            row = []
304
            for attr in columns:
305
                if callable(attr):
306
                    row.append(attr(obj))
307
                else:
308
                    item = obj
309
                    attrs = attr.split(".")
310
                    for attr in attrs:
311
                        item = getattr(item, attr)
312
                    row.append(item)
313
            table.append(row)
314

    
315
        # Special handle of output
316
        self.handle_output(table, headers)
317

    
318
        # Print output
319
        output_format = options["output_format"]
320
        if output_format != "json" and not options["headers"]:
321
            headers = None
322
        utils.pprint_table(self.stdout, table, headers, output_format)
323

    
324
    def handle_args(self, *args, **kwargs):
325
        pass
326

    
327
    def handle_db_objects(self, objects, **options):
328
        pass
329

    
330
    def handle_output(self, table, headers):
331
        pass
332

    
333
    def display_fields(self):
334
        headers = ["Field", "Description"]
335
        table = []
336
        for field, (_, help_msg) in self.FIELDS.items():
337
            table.append((field, help_msg))
338
        utils.pprint_table(self.stdout, table, headers)
339

    
340
    def validate_fields(self, fields):
341
        for f in fields:
342
            if f not in self.FIELDS.keys():
343
                raise CommandError("Unknown field '%s'. 'Use --list-fields"
344
                                   " option to find out available fields."
345
                                   % f)
346

    
347
    def display_filters(self):
348
        headers = ["Filter", "Description", "Help"]
349
        table = []
350
        for field in self.object_class._meta.fields:
351
            table.append((field.name, field.verbose_name, field.help_text))
352
        utils.pprint_table(self.stdout, table, headers)
353

    
354

    
355
class RemoveCommand(BaseCommand):
356
    help = "Generic remove command"
357
    option_list = BaseCommand.option_list + (
358
        make_option(
359
            "-f", "--force",
360
            dest="force",
361
            action="store_true",
362
            default=False,
363
            help="Do not prompt for confirmation"),
364
    )
365

    
366
    def confirm_deletion(self, force, resource='', args=''):
367
        if force is True:
368
            return True
369

    
370
        ids = ', '.join(args)
371
        self.stdout.write("Are you sure you want to delete %s %s?"
372
                          " [Y/N] " % (resource, ids))
373
        try:
374
            answer = distutils.util.strtobool(raw_input())
375
            if answer != 1:
376
                raise CommandError("Aborting deletion")
377
        except ValueError:
378
            raise CommandError("Unaccepted input value. Please choose yes/no"
379
                               " (y/n).")