Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (12.5 kB)

1
# Copyright 2012-2013 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

    
36
from django.core.management.base import BaseCommand, CommandError
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

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

    
57

    
58
class ListCommand(SynnefoCommand):
59
    """Generic *-list management command.
60

61
    Management command to handle common tasks when implementing a -list
62
    management command. This class handles the following tasks:
63

64
    * Retrieving objects from database.
65

66
    The DB model class is declared in ``object_class`` class attribute. Also,
67
    results can be filter using either the ``filters`` and ``excludes``
68
    attribute or the "--filter-by" option.
69

70
    * Display specific fields of the database objects.
71

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

79
    The fields that will be displayed be default is contained in the ``fields``
80
    class attribute. The user can specify different fields using the "--fields"
81
    option.
82

83
    * Handling of user UUIDs and names.
84

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

90
    * Pretty printing output to a nice table.
91

92
    """
93

    
94
    # The following fields must be handled in the ListCommand subclasses!
95

    
96
    # The django DB model
97
    object_class = None
98
    # The name of the field containg the user ID of the user, if any.
99
    user_uuid_field = None
100
    # The name of the field containg the deleted flag, if any.
101
    deleted_field = None
102
    # Dictionary with all available fields
103
    FIELDS = {}
104
    # List of fields to display by default
105
    fields = []
106
    # Default filters and excludes
107
    filters = {}
108
    excludes = {}
109
    # Order results
110
    order_by = None
111

    
112
    # Fields used only with user_user_field
113
    astakos_auth_url = None
114
    astakos_token = None
115

    
116
    # Optimize DB queries
117
    prefetch_related = []
118
    select_related = []
119

    
120
    help = "Generic List Command"
121
    option_list = SynnefoCommand.option_list + (
122
        make_option(
123
            "-o", "--output",
124
            dest="fields",
125
            help="Comma-separated list of output fields"),
126
        make_option(
127
            "--list-fields",
128
            dest="list_fields",
129
            action="store_true",
130
            default=False,
131
            help="List available output fields"),
132
        make_option(
133
            "--filter-by",
134
            dest="filter_by",
135
            metavar="FILTERS",
136
            help="Filter results. Comma separated list of key `cond` val pairs"
137
                 " that displayed entries must satisfy. e.g."
138
                 " --filter-by \"deleted=False,id>=22\"."),
139
        make_option(
140
            "--list-filters",
141
            dest="list_filters",
142
            action="store_true",
143
            default=False,
144
            help="List available filters"),
145
        make_option(
146
            "--no-headers",
147
            dest="headers",
148
            action="store_false",
149
            default=True,
150
            help="Do not display headers"),
151
    )
152

    
153
    def __init__(self, *args, **kwargs):
154
        if self.user_uuid_field:
155
            assert(self.astakos_auth_url), "astakos_auth_url attribute is "\
156
                                           "needed when user_uuid_field "\
157
                                           "is declared"
158
            assert(self.astakos_token), "astakos_token attribute is needed"\
159
                                        " when user_uuid_field is declared"
160
            self.option_list += (
161
                make_option(
162
                    "-u", "--user",
163
                    dest="user",
164
                    metavar="USER",
165
                    help="List items only for this user."
166
                         " 'USER' can be either a user UUID or a display"
167
                         " name"),
168
                make_option(
169
                    "--display-mails",
170
                    dest="display_mails",
171
                    action="store_true",
172
                    default=False,
173
                    help="Include the user's email"),
174
            )
175

    
176
        if self.deleted_field:
177
            self.option_list += (
178
                make_option(
179
                    "-d", "--deleted",
180
                    dest="deleted",
181
                    action="store_true",
182
                    help="Display only deleted items"),
183
            )
184
        super(ListCommand, self).__init__(*args, **kwargs)
185

    
186
    def handle(self, *args, **options):
187
        if len(args) > 0:
188
            raise CommandError("List commands do not accept any argument")
189

    
190
        assert(self.object_class), "object_class variable must be declared"
191

    
192
        if options["list_fields"]:
193
            self.display_fields()
194
            return
195

    
196
        if options["list_filters"]:
197
            self.display_filters()
198
            return
199

    
200
        # --output option
201
        if options["fields"]:
202
            fields = options["fields"]
203
            fields = fields.split(",")
204
            self.validate_fields(fields)
205
            self.fields = options["fields"].split(",")
206

    
207
        # --filter-by option
208
        if options["filter_by"]:
209
            filters, excludes = utils.parse_filters(options["filter_by"])
210
        else:
211
            filters, excludes = ({}, {})
212

    
213
        self.filters.update(filters)
214
        self.excludes.update(excludes)
215

    
216
        # --user option
217
        user = options.get("user")
218
        if user:
219
            if "@" in user:
220
                ucache = UserCache(self.astakos_auth_url, self.astakos_token)
221
                user = ucache.get_uuid(user)
222
            self.filters[self.user_uuid_field] = user
223

    
224
        # --deleted option
225
        if self.deleted_field:
226
            deleted = options.get("deleted")
227
            if deleted:
228
                self.filters[self.deleted_field] = True
229
            else:
230
                self.filters[self.deleted_field] = False
231

    
232
        # Special handling of arguments
233
        self.handle_args(self, *args, **options)
234

    
235
        select_related = getattr(self, "select_related", [])
236
        prefetch_related = getattr(self, "prefetch_related", [])
237

    
238
        objects = self.object_class.objects
239
        try:
240
            for sr in select_related:
241
                objects = objects.select_related(sr)
242
            for pr in prefetch_related:
243
                objects = objects.prefetch_related(pr)
244
            objects = objects.filter(**self.filters)
245
            objects = objects.exclude(**self.excludes)
246
        except FieldError as e:
247
            raise CommandError(e)
248
        except Exception as e:
249
            raise CommandError("Can not filter results: %s" % e)
250

    
251
        order_key = self.order_by if self.order_by is not None else 'pk'
252
        objects = objects.order_by(order_key)
253

    
254
        # --display-mails option
255
        display_mails = options.get("display_mails")
256
        if display_mails:
257
            if 'user_mail' in self.object_class._meta.get_all_field_names():
258
                raise RuntimeError("%s has already a 'user_mail' attribute")
259

    
260
            self.fields.append("user.email")
261
            self.FIELDS["user.email"] =\
262
                ("user_email", "The email of the owner.")
263
            uuids = [getattr(obj, self.user_uuid_field) for obj in objects]
264
            ucache = UserCache(self.astakos_auth_url, self.astakos_token)
265
            ucache.fetch_names(list(set(uuids)))
266
            for obj in objects:
267
                uuid = getattr(obj, self.user_uuid_field)
268
                obj.user_email = ucache.get_name(uuid)
269

    
270
        # Special handling of DB results
271
        objects = list(objects)
272
        self.handle_db_objects(objects, **options)
273

    
274
        headers = self.fields
275
        columns = [self.FIELDS[key][0] for key in headers]
276

    
277
        table = []
278
        for obj in objects:
279
            row = []
280
            for attr in columns:
281
                if callable(attr):
282
                    row.append(attr(obj))
283
                else:
284
                    item = obj
285
                    attrs = attr.split(".")
286
                    for attr in attrs:
287
                        item = getattr(item, attr)
288
                    row.append(item)
289
            table.append(row)
290

    
291
        # Special handle of output
292
        self.handle_output(table, headers)
293

    
294
        # Print output
295
        output_format = options["output_format"]
296
        if output_format != "json" and not options["headers"]:
297
            headers = None
298
        utils.pprint_table(self.stdout, table, headers, output_format)
299

    
300
    def handle_args(self, *args, **kwargs):
301
        pass
302

    
303
    def handle_db_objects(self, objects, **options):
304
        pass
305

    
306
    def handle_output(self, table, headers):
307
        pass
308

    
309
    def display_fields(self):
310
        headers = ["Field", "Description"]
311
        table = []
312
        for field, (_, help_msg) in self.FIELDS.items():
313
            table.append((field, help_msg))
314
        utils.pprint_table(self.stdout, table, headers)
315

    
316
    def validate_fields(self, fields):
317
        for f in fields:
318
            if f not in self.FIELDS.keys():
319
                raise CommandError("Unknown field '%s'. 'Use --list-fields"
320
                                   " option to find out available fields."
321
                                   % f)
322

    
323
    def display_filters(self):
324
        headers = ["Filter", "Description", "Help"]
325
        table = []
326
        for field in self.object_class._meta.fields:
327
            table.append((field.name, field.verbose_name, field.help_text))
328
        utils.pprint_table(self.stdout, table, headers)
329

    
330

    
331
class RemoveCommand(BaseCommand):
332
    help = "Generic remove command"
333
    option_list = BaseCommand.option_list + (
334
        make_option(
335
            "-f", "--force",
336
            dest="force",
337
            action="store_true",
338
            default=False,
339
            help="Do not prompt for confirmation"),
340
    )
341

    
342
    def confirm_deletion(self, force, resource='', args=''):
343
        if force is True:
344
            return True
345

    
346
        ids = ', '.join(args)
347
        self.stdout.write("Are you sure you want to delete %s %s?"
348
                          " [Y/N] " % (resource, ids))
349
        try:
350
            answer = distutils.util.strtobool(raw_input())
351
            if answer != 1:
352
                raise CommandError("Aborting deletion")
353
        except ValueError:
354
            raise CommandError("Unaccepted input value. Please choose yes/no"
355
                               " (y/n).")