user-set-initial-quota.py 8.4 KB
Newer Older
1
# Copyright 2012, 2013 GRNET S.A. All rights reserved.
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
#
# 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.

import os
35
36
import uuid
import string
37
38
39
40
41

from optparse import make_option
from collections import namedtuple

from django.core.management.base import BaseCommand, CommandError
42
43
from django.core.validators import validate_email
from synnefo.lib.quotaholder.api import QH_PRACTICALLY_INFINITE
44

45
from astakos.im.models import AstakosUser, AstakosUserQuota, Resource
46
47
48

AddResourceArgs = namedtuple('AddQuotaArgs', ('resource',
                                              'capacity',
49
                                              'quantity',
50
51
52
53
                                              'import_limit',
                                              'export_limit'))

class Command(BaseCommand):
54
55
    help = """Import user quota limits from file or set quota
for a single user from the command line
56
57
58
59
60
61
62
63
64
65
66
67
68

    The file must contain non-empty lines, and each line must
    contain a single-space-separated list of values:

    <user> <resource name> <capacity> <quantity> <import_limit> <export_limit>

    For example to grant the following user with 10 private networks
    (independent of any he receives from projects):

    6119a50b-cbc7-42c0-bafc-4b6570e3f6ac cyclades.network.private 10 0 1000000 1000000

    The last two values are arbitrarily large to represent no
    import/export limit at all.
69

70
71
72
73
    When setting quota from the command line, specify only capacity.
    Quantity and import/export limit will get default values. Example:

    --set-capacity 6119a50b-cbc7-42c0-bafc-4b6570e3f6ac cyclades.vm 10
74
75

    The special value of 'default' sets the user setting to the default.
76
    """
77
78
79
80
81
82
83
84
85
86
87

    option_list = BaseCommand.option_list + (
        make_option('--from-file',
                    dest='from_file',
                    metavar='<exported-quotas.txt>',
                    help="Import quotas from file"),
        make_option('--set-capacity',
                    dest='set_capacity',
                    metavar='<uuid or email> <resource> <capacity>',
                    nargs=3,
                    help="Set capacity for a specified user/resource pair"),
88

89
        make_option('-f', '--no-confirm',
90
91
92
93
94
95
                    action='store_true',
                    default=False,
                    dest='force',
                    help="Do not ask for confirmation"),
    )

96
    def handle(self, *args, **options):
97
98
99
100
101
102
103
104
105
        from_file = options['from_file']
        set_capacity = options['set_capacity']
        force = options['force']

        if from_file is not None:
            if set_capacity is not None:
                raise CommandError("Cannot combine option `--from-file' with "
                                   "`--set-capacity'.")
            self.import_from_file(from_file)
106
            return
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131

        if set_capacity is not None:
            user, resource, capacity = set_capacity
            self.set_limit(user, resource, capacity, force)
            return

        m = "Please use either `--from-file' or `--set-capacity' options"
        raise CommandError(m)

    def set_limit(self, user_ident, resource, capacity, force):
        if is_uuid(user_ident):
            try:
                user = AstakosUser.objects.get(uuid=user_ident)
            except AstakosUser.DoesNotExist:
                raise CommandError('Not found user having uuid: %s' %
                                   user_ident)
        elif is_email(user_ident):
            try:
                user = AstakosUser.objects.get(username=user_ident)
            except AstakosUser.DoesNotExist:
                raise CommandError('Not found user having email: %s' %
                                   user_ident)
        else:
            raise CommandError('Please specify user by uuid or email')

132
133
134
135
136
137
138
        if capacity != 'default':
            try:
                capacity = int(capacity)
            except ValueError:
                m = "Please specify capacity as a decimal integer or 'default'"
                raise CommandError(m)

139
140
141
142
143
144
145
146
        args = AddResourceArgs(resource=resource,
                               capacity=capacity,
                               quantity=0,
                               import_limit=QH_PRACTICALLY_INFINITE,
                               export_limit=QH_PRACTICALLY_INFINITE,
                               )

        try:
147
            quota, default_capacity = user.get_resource_policy(resource)
148
149
150
        except Resource.DoesNotExist:
            raise CommandError("No such resource: %s" % resource)

151
        current = quota.capacity if quota is not None else 'default'
152
153
154

        if not force:
            self.stdout.write("user: %s (%s)\n" % (user.uuid, user.username))
155
            self.stdout.write("default capacity: %s\n" % default_capacity)
156
157
158
159
160
161
162
163
            self.stdout.write("current capacity: %s\n" % current)
            self.stdout.write("new capacity: %s\n" % capacity)
            self.stdout.write("Confirm? (y/n) ")
            response = raw_input()
            if string.lower(response) not in ['y', 'yes']:
                self.stdout.write("Aborted.\n")
                return

164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
        if capacity == 'default':
            try:
                service, sep, name = resource.partition('.')
                q = AstakosUserQuota.objects.get(
                        user=user,
                        resource__service__name=service,
                        resource__name=name)
                q.delete()
            except Exception as e:
                import traceback
                traceback.print_exc()
                raise CommandError("Failed to remove policy: %s" % e)
        else:
            try:
                user.add_resource_policy(*args)
            except Exception as e:
                raise CommandError("Failed to add policy: %s" % e)
181
182

    def import_from_file(self, location):
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
        try:
            f = open(location, 'r')
        except IOError, e:
            raise CommandError(e)

        for line in f.readlines():
            try:
                t = line.rstrip('\n').split(' ')
                user = t[0]
                args = AddResourceArgs(*t[1:])
            except(IndexError, TypeError):
                self.stdout.write('Invalid line format: %s:\n' % t)
                continue
            else:
                try:
                    user = AstakosUser.objects.get(uuid=user)
                except AstakosUser.DoesNotExist:
200
                    self.stdout.write('Not found user having uuid: %s\n' % user)
201
202
203
204
205
206
207
208
209
                    continue
                else:
                    try:
                        user.add_resource_policy(*args)
                    except Exception, e:
                        self.stdout.write('Failed to policy: %s\n' % e)
                        continue
            finally:
                f.close()
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231


def is_uuid(s):
    if s is None:
        return False
    try:
        uuid.UUID(s)
    except ValueError:
        return False
    else:
        return True


def is_email(s):
    if s is None:
        return False
    try:
        validate_email(s)
    except:
        return False
    else:
        return True