Statistics
| Branch: | Tag: | Revision:

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

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

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

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

    
182
    def handle(self, *args, **options):
183
        if len(args) > 0:
184
            raise CommandError("List commands do not accept any argument")
185

    
186
        assert(self.object_class), "object_class variable must be declared"
187

    
188
        if options["list_fields"]:
189
            self.display_fields()
190
            return
191

    
192
        if options["list_filters"]:
193
            self.display_filters()
194
            return
195

    
196
        # --output option
197
        if options["fields"]:
198
            fields = options["fields"]
199
            fields = fields.split(",")
200
            self.validate_fields(fields)
201
            self.fields = options["fields"].split(",")
202

    
203
        # --filter-by option
204
        if options["filter_by"]:
205
            filters, excludes = utils.parse_filters(options["filter_by"])
206
        else:
207
            filters, excludes = ({}, {})
208

    
209
        self.filters.update(filters)
210
        self.excludes.update(excludes)
211

    
212
        # --user option
213
        user = options.get("user")
214
        if user:
215
            if "@" in user:
216
                ucache = UserCache(self.astakos_auth_url, self.astakos_token)
217
                user = ucache.get_uuid(user)
218
            self.filters[self.user_uuid_field] = user
219

    
220
        # --deleted option
221
        if self.deleted_field:
222
            deleted = options.get("deleted")
223
            if deleted:
224
                self.filters[self.deleted_field] = True
225
            else:
226
                self.filters[self.deleted_field] = False
227

    
228
        # Special handling of arguments
229
        self.handle_args(self, *args, **options)
230

    
231
        select_related = getattr(self, "select_related", [])
232
        prefetch_related = getattr(self, "prefetch_related", [])
233

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

    
247
        order_key = self.order_by if self.order_by is not None else 'pk'
248
        objects = objects.order_by(order_key)
249

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

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

    
266
        # Special handling of DB results
267
        objects = list(objects)
268
        self.handle_db_objects(objects, **options)
269

    
270
        headers = self.fields
271
        columns = [self.FIELDS[key][0] for key in headers]
272

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

    
287
        # Special handle of output
288
        self.handle_output(table, headers)
289

    
290
        # Print output
291
        output_format = options["output_format"]
292
        if output_format != "json" and not options["headers"]:
293
            headers = None
294
        utils.pprint_table(self.stdout, table, headers, output_format)
295

    
296
    def handle_args(self, *args, **kwargs):
297
        pass
298

    
299
    def handle_db_objects(self, objects, **options):
300
        pass
301

    
302
    def handle_output(self, table, headers):
303
        pass
304

    
305
    def display_fields(self):
306
        headers = ["Field", "Description"]
307
        table = []
308
        for field, (_, help_msg) in self.FIELDS.items():
309
            table.append((field, help_msg))
310
        utils.pprint_table(self.stdout, table, headers)
311

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

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

    
326

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

    
338
    def confirm_deletion(self, force, resource='', args=''):
339
        if force is True:
340
            return True
341

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