Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (7.6 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 string
35

    
36
from optparse import make_option
37
from collections import namedtuple
38

    
39
from django.core.management.base import BaseCommand, CommandError
40

    
41
from snf_django.lib.db.transaction import commit_on_success_strict
42
from astakos.im.models import AstakosUser, AstakosUserQuota, Resource
43
from astakos.im.quotas import qh_sync_user, qh_sync_users
44

    
45
from ._common import is_uuid, is_email
46

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

    
51

    
52

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

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

60
    <user> <resource name> <capacity>
61

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

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

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

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

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

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

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

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

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

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

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

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

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

    
158
        if capacity == 'default':
159
            try:
160
                q = AstakosUserQuota.objects.get(user=user,
161
                                                 resource__name=resource)
162
                q.delete()
163
            except Exception as e:
164
                import traceback
165
                traceback.print_exc()
166
                raise CommandError("Failed to remove policy: %s" % e)
167
        else:
168
            try:
169
                user.add_resource_policy(*args)
170
            except Exception as e:
171
                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
        with open(location) as f:
177
            for line in f.readlines():
178
                try:
179
                    t = line.rstrip('\n').split(' ')
180
                    user = t[0]
181
                    args = AddResourceArgs(*t[1:])
182
                except(IndexError, TypeError):
183
                    self.stdout.write('Invalid line format: %s:\n' % t)
184
                    continue
185
                else:
186
                    try:
187
                        user = AstakosUser.objects.get(uuid=user)
188
                        users.add(user.id)
189
                    except AstakosUser.DoesNotExist:
190
                        self.stdout.write('Not found user having uuid: %s\n'
191
                                          % 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
        qh_sync_users(users)