Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / management / commands / user-set-initial-quota.py @ 44104cd3

History | View | Annotate | Download (7.9 kB)

1
# Copyright 2012, 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
import os
35
import uuid
36
import string
37

    
38
from optparse import make_option
39
from collections import namedtuple
40

    
41
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
47

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

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

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

59
    <user> <resource name> <capacity>
60

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

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
    option_list = BaseCommand.option_list + (
74
        make_option('--from-file',
75
                    dest='from_file',
76
                    metavar='<exported-quotas.txt>',
77
                    help="Import quotas from file"),
78
        make_option('--set-capacity',
79
                    dest='set_capacity',
80
                    metavar='<uuid or email> <resource> <capacity>',
81
                    nargs=3,
82
                    help="Set capacity for a specified user/resource pair"),
83

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

    
91
    @commit_on_success_strict()
92
    def handle(self, *args, **options):
93
        from_file = options['from_file']
94
        set_capacity = options['set_capacity']
95
        force = options['force']
96

    
97
        if from_file is not None:
98
            if set_capacity is not None:
99
                raise CommandError("Cannot combine option `--from-file' with "
100
                                   "`--set-capacity'.")
101
            self.import_from_file(from_file)
102
            return
103

    
104
        if set_capacity is not None:
105
            user, resource, capacity = set_capacity
106
            self.set_limit(user, resource, capacity, force)
107
            return
108

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

    
112
    def set_limit(self, user_ident, resource, capacity, force):
113
        if is_uuid(user_ident):
114
            try:
115
                user = AstakosUser.objects.get(uuid=user_ident)
116
            except AstakosUser.DoesNotExist:
117
                raise CommandError('Not found user having uuid: %s' %
118
                                   user_ident)
119
        elif is_email(user_ident):
120
            try:
121
                user = AstakosUser.objects.get(username=user_ident)
122
            except AstakosUser.DoesNotExist:
123
                raise CommandError('Not found user having email: %s' %
124
                                   user_ident)
125
        else:
126
            raise CommandError('Please specify user by uuid or email')
127

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

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

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

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

    
146
        if not force:
147
            self.stdout.write("user: %s (%s)\n" % (user.uuid, user.username))
148
            self.stdout.write("default capacity: %s\n" % default_capacity)
149
            self.stdout.write("current capacity: %s\n" % current)
150
            self.stdout.write("new capacity: %s\n" % capacity)
151
            self.stdout.write("Confirm? (y/n) ")
152
            response = raw_input()
153
            if string.lower(response) not in ['y', 'yes']:
154
                self.stdout.write("Aborted.\n")
155
                return
156

    
157
        if capacity == 'default':
158
            try:
159
                q = AstakosUserQuota.objects.get(user=user,
160
                                                 resource__name=resource)
161
                q.delete()
162
            except Exception as e:
163
                import traceback
164
                traceback.print_exc()
165
                raise CommandError("Failed to remove policy: %s" % e)
166
        else:
167
            try:
168
                user.add_resource_policy(*args)
169
            except Exception as e:
170
                raise CommandError("Failed to add policy: %s" % e)
171
        qh_sync_user(user.id)
172

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

    
179
        for line in f.readlines():
180
            try:
181
                t = line.rstrip('\n').split(' ')
182
                user = t[0]
183
                args = AddResourceArgs(*t[1:])
184
            except(IndexError, TypeError):
185
                self.stdout.write('Invalid line format: %s:\n' % t)
186
                continue
187
            else:
188
                try:
189
                    user = AstakosUser.objects.get(uuid=user)
190
                except AstakosUser.DoesNotExist:
191
                    self.stdout.write('Not found user having uuid: %s\n' % user)
192
                    continue
193
                else:
194
                    try:
195
                        user.add_resource_policy(*args)
196
                    except Exception, e:
197
                        self.stdout.write('Failed to policy: %s\n' % e)
198
                        continue
199
            finally:
200
                f.close()
201

    
202

    
203
def is_uuid(s):
204
    if s is None:
205
        return False
206
    try:
207
        uuid.UUID(s)
208
    except ValueError:
209
        return False
210
    else:
211
        return True
212

    
213

    
214
def is_email(s):
215
    if s is None:
216
        return False
217
    try:
218
        validate_email(s)
219
    except:
220
        return False
221
    else:
222
        return True