Statistics
| Branch: | Tag: | Revision:

root / snf-webproject / synnefo / webproject / management / commands / __init__.py @ ffb5cca1

History | View | Annotate | Download (11.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 synnefo.webproject.management import utils
40
from synnefo.lib.astakos import UserCache
41

    
42

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

    
55

    
56
class ListCommand(BaseCommand):
57
    """Generic *-list management command.
58

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

62
    * Retrieving objects from database.
63

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

68
    * Display specific fields of the database objects.
69

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

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

81
    * Handling of user UUIDs and names.
82

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

88
    * Pretty printing output to a nice table.
89

90
    """
91

    
92
    # The following fields must be handled in the ListCommand subclasses!
93

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

    
108
    # Fields used only with user_user_field
109
    astakos_url = None
110
    astakos_token = None
111

    
112
    help = "Generic List Command"
113
    option_list = BaseCommand.option_list + (
114
        make_option(
115
            "-o", "--output",
116
            dest="fields",
117
            help="Comma-separated list of output fields"),
118
        make_option(
119
            "--list-fields",
120
            dest="list_fields",
121
            action="store_true",
122
            default=False,
123
            help="List available output fields"),
124
        make_option(
125
            "--filter-by",
126
            dest="filter_by",
127
            metavar="FILTERS",
128
            help="Filter results. Comma separated list of key `cond` val pairs"
129
                 " that displayed entries must satisfy. e.g."
130
                 " --filter-by \"deleted=False,id>=22\"."),
131
        make_option(
132
            "--list-filters",
133
            dest="list_filters",
134
            action="store_true",
135
            default=False,
136
            help="List available filters"),
137
        make_option(
138
            "--no-headers",
139
            dest="headers",
140
            action="store_false",
141
            default=True,
142
            help="Do not display headers"),
143
        make_option(
144
            "--output-format",
145
            dest="output_format",
146
            metavar="[pretty, csv, json]",
147
            default="pretty",
148
            choices=["pretty", "csv", "json"],
149
            help="Select the output format: pretty [the default], tabs"
150
                 " [tab-separated output], csv [comma-separated output]"),
151
    )
152

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

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

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

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

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

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

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

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

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

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

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

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

    
234
        objects = self.object_class.objects
235
        try:
236
            objects = objects.filter(**self.filters)
237
            objects = objects.exclude(**self.excludes)
238
        except FieldError as e:
239
            raise CommandError(e)
240
        except Exception as e:
241
            raise CommandError("Can not filter results: %s" % e)
242

    
243
        # --display-mails option
244
        display_mails = options.get("display_mails")
245
        if display_mails:
246
            if 'user_mail' in self.object_class._meta.get_all_field_names():
247
                raise RuntimeError("%s has already a 'user_mail' attribute")
248

    
249
            self.fields.append("user.email")
250
            self.FIELDS["user.email"] =\
251
                ("user_email", "The email of the owner.")
252
            uuids = [getattr(obj, self.user_uuid_field) for obj in objects]
253
            ucache = UserCache(self.astakos_url, self.astakos_token)
254
            ucache.fetch_names(list(set(uuids)))
255
            for obj in objects:
256
                uuid = getattr(obj, self.user_uuid_field)
257
                obj.user_email = ucache.get_name(uuid)
258

    
259
        # Special handling of DB results
260
        objects = list(objects)
261
        self.handle_db_objects(objects, **options)
262

    
263
        headers = self.fields
264
        columns = [self.FIELDS[key][0] for key in headers]
265

    
266
        table = []
267
        for obj in objects:
268
            row = []
269
            for attr in columns:
270
                if callable(attr):
271
                    row.append(attr(obj))
272
                else:
273
                    item = obj
274
                    attrs = attr.split(".")
275
                    for attr in attrs:
276
                        item = getattr(item, attr)
277
                    row.append(item)
278
            table.append(row)
279

    
280
        # Special handle of output
281
        self.handle_output(table, headers)
282

    
283
        # Print output
284
        output_format = options["output_format"]
285
        if output_format != "json" and not options["headers"]:
286
            headers = None
287
        utils.pprint_table(self.stdout, table, headers, output_format)
288

    
289
    def handle_args(self, *args, **kwargs):
290
        pass
291

    
292
    def handle_db_objects(self, objects, **options):
293
        pass
294

    
295
    def handle_output(self, table, headers):
296
        pass
297

    
298
    def display_fields(self):
299
        headers = ["Field", "Description"]
300
        table = []
301
        for field, (_, help_msg) in self.FIELDS.items():
302
            table.append((field, help_msg))
303
        utils.pprint_table(self.stdout, table, headers)
304

    
305
    def validate_fields(self, fields):
306
        for f in fields:
307
            if f not in self.FIELDS.keys():
308
                raise CommandError("Unknown field '%s'. 'Use --list-fields"
309
                                   " option to find out available fields."
310
                                   % f)
311

    
312
    def display_filters(self):
313
        headers = ["Filter", "Description", "Help"]
314
        table = []
315
        for field in self.object_class._meta.fields:
316
            table.append((field.name, field.verbose_name, field.help_text))
317
        utils.pprint_table(self.stdout, table, headers)