Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / management / commands / resource-modify.py @ 2dc27ac1

History | View | Annotate | Download (8.5 kB)

1
# Copyright 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
from django.core.management.base import BaseCommand, CommandError
36
from django.utils import simplejson as json
37

    
38
from snf_django.management import utils
39
from astakos.im.models import Resource
40
from astakos.im.register import update_resources
41
from ._common import show_resource_value, style_options, check_style, units
42

    
43

    
44
class Command(BaseCommand):
45
    args = "<resource name>"
46
    help = "Modify a resource's default base quota and boolean flags."
47

    
48
    option_list = BaseCommand.option_list + (
49
        make_option('--default-quota',
50
                    metavar='<limit>',
51
                    help="Specify default base quota"),
52
        make_option('--default-quota-interactive',
53
                    action='store_true',
54
                    default=None,
55
                    help=("Prompt user to change default base quota. "
56
                          "If no resource is given, prompts for all "
57
                          "resources.")),
58
        make_option('--default-quota-from-file',
59
                    metavar='<limits_file.json>',
60
                    help=("Read default base quota from a file. "
61
                          "File should contain a json dict mapping resource "
62
                          "names to limits")),
63
        make_option('--unit-style',
64
                    default='mb',
65
                    help=("Specify display unit for resource values "
66
                          "(one of %s); defaults to mb") % style_options),
67
        make_option('--api-visible',
68
                    metavar='True|False',
69
                    help="Control visibility of this resource in the API"),
70
        make_option('--ui-visible',
71
                    metavar='True|False',
72
                    help="Control visibility of this resource in the UI"),
73
    )
74

    
75
    def handle(self, *args, **options):
76
        resource_name = args[0] if len(args) > 0 else None
77

    
78
        actions = {
79
            'default_quota': self.change_limit,
80
            'default_quota_interactive': self.change_interactive,
81
            'default_quota_from_file': self.change_from_file,
82
            'api_visible': self.set_api_visible,
83
            'ui_visible': self.set_ui_visible,
84
        }
85

    
86
        opts = [(key, value)
87
                for (key, value) in options.items()
88
                if key in actions and value is not None]
89

    
90
        if len(opts) != 1:
91
            raise CommandError("Please provide exactly one of the options: "
92
                               "--default-quota, --default-quota-interactive, "
93
                               "--default-quota-from-file, "
94
                               "--api-visible, --ui-visible.")
95

    
96
        self.unit_style = options['unit_style']
97
        check_style(self.unit_style)
98

    
99
        key, value = opts[0]
100
        action = actions[key]
101
        action(resource_name, value)
102

    
103
    def set_api_visible(self, resource_name, allow):
104
        if resource_name is None:
105
            raise CommandError("Please provide a resource name.")
106

    
107
        try:
108
            allow = utils.parse_bool(allow)
109
        except ValueError:
110
            raise CommandError("Expecting a boolean value.")
111
        resource = self.get_resource(resource_name)
112
        resource.api_visible = allow
113
        if not allow and resource.ui_visible:
114
            self.stdout.write("Also resetting 'ui_visible' for consistency.\n")
115
            resource.ui_visible = False
116
        resource.save()
117

    
118
    def set_ui_visible(self, resource_name, allow):
119
        if resource_name is None:
120
            raise CommandError("Please provide a resource name.")
121

    
122
        try:
123
            allow = utils.parse_bool(allow)
124
        except ValueError:
125
            raise CommandError("Expecting a boolean value.")
126
        resource = self.get_resource(resource_name)
127

    
128
        resource.ui_visible = allow
129
        if allow and not resource.api_visible:
130
            self.stdout.write("Also setting 'api_visible' for consistency.\n")
131
            resource.api_visible = True
132
        resource.save()
133

    
134
    def get_resource(self, resource_name):
135
        try:
136
            return Resource.objects.select_for_update().get(name=resource_name)
137
        except Resource.DoesNotExist:
138
            raise CommandError("Resource %s does not exist."
139
                               % resource_name)
140

    
141
    def change_limit(self, resource_name, limit):
142
        if resource_name is None:
143
            raise CommandError("Please provide a resource name.")
144

    
145
        resource = self.get_resource(resource_name)
146
        self.change_resource_limit(resource, limit)
147

    
148
    def change_from_file(self, resource_name, filename):
149
        with open(filename) as file_data:
150
            try:
151
                config = json.load(file_data)
152
            except json.JSONDecodeError:
153
                raise CommandError("Malformed JSON file.")
154
            if not isinstance(config, dict):
155
                raise CommandError("Malformed JSON file.")
156
            self.change_with_conf(resource_name, config)
157

    
158
    def change_with_conf(self, resource_name, config):
159
        if resource_name is None:
160
            resources = Resource.objects.all().select_for_update()
161
        else:
162
            resources = [self.get_resource(resource_name)]
163

    
164
        updates = []
165
        for resource in resources:
166
            limit = config.get(resource.name)
167
            if limit is not None:
168
                limit = self.parse_limit(limit)
169
                updates.append((resource, limit))
170
        if updates:
171
            update_resources(updates)
172

    
173
    def change_interactive(self, resource_name, _placeholder):
174
        if resource_name is None:
175
            resources = Resource.objects.all().select_for_update()
176
        else:
177
            resources = [self.get_resource(resource_name)]
178

    
179
        updates = []
180
        for resource in resources:
181
            self.stdout.write("Resource '%s' (%s)\n" %
182
                              (resource.name, resource.desc))
183
            value = show_resource_value(resource.uplimit, resource.name,
184
                                        self.unit_style)
185
            self.stdout.write("Current limit: %s\n" % value)
186
            while True:
187
                self.stdout.write("New limit (leave blank to keep current): ")
188
                response = raw_input()
189
                if response == "":
190
                    break
191
                else:
192
                    try:
193
                        value = units.parse(response)
194
                    except units.ParseError:
195
                        continue
196
                    updates.append((resource, value))
197
                    break
198
        if updates:
199
            self.stdout.write("Updating...\n")
200
            update_resources(updates)
201

    
202
    def parse_limit(self, limit):
203
        try:
204
            if isinstance(limit, (int, long)):
205
                return limit
206
            if isinstance(limit, basestring):
207
                return units.parse(limit)
208
            raise units.ParseError()
209
        except units.ParseError:
210
            m = ("Limit should be an integer, optionally followed by a unit,"
211
                 " or 'inf'.")
212
            raise CommandError(m)
213

    
214
    def change_resource_limit(self, resource, limit):
215
        limit = self.parse_limit(limit)
216
        update_resources([(resource, limit)])