resource-modify.py 6.27 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# Copyright 2013 GRNET S.A. All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
#   1. Redistributions of source code must retain the above
#      copyright notice, this list of conditions and the following
#      disclaimer.
#
#   2. Redistributions in binary form must reproduce the above
#      copyright notice, this list of conditions and the following
#      disclaimer in the documentation and/or other materials
#      provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# The views and conclusions contained in the software and
# documentation are those of the authors and should not be
# interpreted as representing official policies, either expressed
# or implied, of GRNET S.A.

from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
36
from django.utils import simplejson as json
37
38
39

from astakos.im.models import Resource
from astakos.im.resources import update_resource
40
from ._common import show_resource_value, style_options, check_style, units
41
42
43
44


class Command(BaseCommand):
    args = "<resource name>"
45
46
    help = ("Modify a resource (currently only change the default base quota)."
            "\nIf no resource is specified, all resources are considered.")
47
48
49
50

    option_list = BaseCommand.option_list + (
        make_option('--limit',
                    dest='limit',
51
52
53
54
55
56
57
58
59
60
                    help="Specify default base quota"),
        make_option('--interactive',
                    action='store_true',
                    dest='interactive',
                    default=None,
                    help="Prompt user to change default base quotas"),
        make_option('--from-file',
                    dest='from_file',
                    metavar='<limits_file.json>',
                    help="Read default base quotas from a json file"),
61
62
63
64
        make_option('--unit-style',
                    default='mb',
                    help=("Specify display unit for resource values "
                          "(one of %s); defaults to mb") % style_options),
65
66
67
    )

    def handle(self, *args, **options):
68
69
70
71
72
73
74
75
76
77
78
79
80
        resource_name = args[0] if len(args) > 0 else None

        actions = {
            'limit': self.change_limit,
            'interactive': self.change_interactive,
            'from_file': self.change_from_file,
        }

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

        if len(opts) != 1:
81
82
83
84
85
            raise CommandError("Please provide exactly one of the options: %s."
                               % ", ".join(actions.keys()))

        self.unit_style = options['unit_style']
        check_style(self.unit_style)
86
87
88
89
90
91
92
93
94
95
96
97
98
99

        key, value = opts[0]
        action = actions[key]
        action(resource_name, value)

    def get_resource(self, resource_name):
        try:
            return Resource.objects.get_for_update(name=resource_name)
        except Resource.DoesNotExist:
            raise CommandError("Resource %s does not exist."
                               % resource_name)

    def change_limit(self, resource_name, limit):
        if resource_name is None:
100
101
            raise CommandError("Please provide a resource name.")

102
103
        resource = self.get_resource(resource_name)
        self.change_resource_limit(resource, limit)
104

105
106
107
108
109
110
111
112
113
    def change_from_file(self, resource_name, filename):
        with open(filename) as file_data:
            try:
                config = json.load(file_data)
            except json.JSONDecodeError:
                raise CommandError("Malformed JSON file.")
            if not isinstance(config, dict):
                raise CommandError("Malformed JSON file.")
            self.change_with_conf(resource_name, config)
114

115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
    def change_with_conf(self, resource_name, config):
        if resource_name is None:
            resources = Resource.objects.all().select_for_update()
        else:
            resources = [self.get_resource(resource_name)]

        for resource in resources:
            limit = config.get(resource.name)
            if limit is not None:
                self.change_resource_limit(resource, limit)

    def change_interactive(self, resource_name, _placeholder):
        if resource_name is None:
            resources = Resource.objects.all().select_for_update()
        else:
            resources = [self.get_resource(resource_name)]

        for resource in resources:
            self.stdout.write("Resource '%s' (%s)\n" %
                              (resource.name, resource.desc))
135
136
137
            value = show_resource_value(resource.uplimit, resource.name,
                                        self.unit_style)
            self.stdout.write("Current limit: %s\n" % value)
138
            while True:
139
                self.stdout.write("New limit (leave blank to keep current): ")
140
141
142
143
144
                response = raw_input()
                if response == "":
                    break
                else:
                    try:
145
146
                        value = units.parse(response)
                    except units.ParseError:
147
148
149
150
151
                        continue
                    update_resource(resource, value)
                    break

    def change_resource_limit(self, resource, limit):
152
153
154
155
156
157
158
159
        if not isinstance(limit, (int, long)):
            try:
                limit = units.parse(limit)
            except units.ParseError:
                m = ("Limit should be an integer, optionally followed "
                     "by a unit.")
                raise CommandError(m)
            update_resource(resource, limit)