user-set-initial-quota.py 7.97 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

class Command(BaseCommand):
53
54
    help = """Import user quota limits from file or set quota
for a single user from the command line
55
56
57
58

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    def import_from_file(self, location):
174
175
176
177
178
        try:
            f = open(location, 'r')
        except IOError, e:
            raise CommandError(e)

179
        users = set()
180
181
182
183
184
185
186
187
188
189
190
        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)
191
                    users.add(user.id)
192
                except AstakosUser.DoesNotExist:
193
                    self.stdout.write('Not found user having uuid: %s\n' % user)
194
195
196
197
198
199
200
                    continue
                else:
                    try:
                        user.add_resource_policy(*args)
                    except Exception, e:
                        self.stdout.write('Failed to policy: %s\n' % e)
                        continue
201

202
203
            finally:
                f.close()
204
        qh_sync_users(users)
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226


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