user-set-initial-quota.py 7.98 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
from django.core.validators import validate_email
43

44
from snf_django.lib.db.transaction import commit_on_success_strict
45
from astakos.im.models import AstakosUser, AstakosUserQuota, Resource
46
from astakos.im.quotas import qh_sync_user, qh_sync_users
47
48
49

AddResourceArgs = namedtuple('AddQuotaArgs', ('resource',
                                              'capacity',
50
                                              ))
51

52

53
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

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

60
    <user> <resource name> <capacity>
61
62
63
64

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

65
    6119a50b-cbc7-42c0-bafc-4b6570e3f6ac cyclades.network.private 10
66

67
    Similar syntax is used when setting quota from the command line:
68
69

    --set-capacity 6119a50b-cbc7-42c0-bafc-4b6570e3f6ac cyclades.vm 10
70
71

    The special value of 'default' sets the user setting to the default.
72
    """
73
74
75
76
77
78
79
80
81
82
83

    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"),
84

85
        make_option('-f', '--no-confirm',
86
87
88
89
90
91
                    action='store_true',
                    default=False,
                    dest='force',
                    help="Do not ask for confirmation"),
    )

92
    @commit_on_success_strict()
93
    def handle(self, *args, **options):
94
95
96
97
98
99
100
101
102
        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)
103
            return
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128

        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')

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

136
137
138
139
140
        args = AddResourceArgs(resource=resource,
                               capacity=capacity,
                               )

        try:
141
            quota, default_capacity = user.get_resource_policy(resource)
142
143
144
        except Resource.DoesNotExist:
            raise CommandError("No such resource: %s" % resource)

145
        current = quota.capacity if quota is not None else 'default'
146
147
148

        if not force:
            self.stdout.write("user: %s (%s)\n" % (user.uuid, user.username))
149
            self.stdout.write("default capacity: %s\n" % default_capacity)
150
151
152
153
154
155
156
157
            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

158
159
        if capacity == 'default':
            try:
160
161
                q = AstakosUserQuota.objects.get(user=user,
                                                 resource__name=resource)
162
163
164
165
166
167
168
169
170
171
                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)
172
        qh_sync_user(user.id)
173
174

    def import_from_file(self, location):
175
        users = set()
176
177
        with open(location) as f:
            for line in f.readlines():
178
                try:
179
180
181
182
183
                    t = line.rstrip('\n').split(' ')
                    user = t[0]
                    args = AddResourceArgs(*t[1:])
                except(IndexError, TypeError):
                    self.stdout.write('Invalid line format: %s:\n' % t)
184
185
186
                    continue
                else:
                    try:
187
188
189
190
191
                        user = AstakosUser.objects.get(uuid=user)
                        users.add(user.id)
                    except AstakosUser.DoesNotExist:
                        self.stdout.write('Not found user having uuid: %s\n'
                                          % user)
192
                        continue
193
194
195
196
197
198
                    else:
                        try:
                            user.add_resource_policy(*args)
                        except Exception, e:
                            self.stdout.write('Failed to policy: %s\n' % e)
                            continue
199
        qh_sync_users(users)
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221


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