Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (8.1 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
from synnefo.lib.quotaholder.api import QH_PRACTICALLY_INFINITE
44

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

    
47
AddResourceArgs = namedtuple('AddQuotaArgs', ('resource',
48
                                              'capacity',
49
                                              'quantity',
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> <quantity>
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 0
65

66
    When setting quota from the command line, specify only capacity.
67
    Quantity and import/export limit will get default values. Example:
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
    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
                               quantity=0,
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
                service, sep, name = resource.partition('.')
161
                q = AstakosUserQuota.objects.get(
162
                        user=user,
163
                        resource__service__name=service,
164
                        resource__name=name)
165
                q.delete()
166
            except Exception as e:
167
                import traceback
168
                traceback.print_exc()
169
                raise CommandError("Failed to remove policy: %s" % e)
170
        else:
171
            try:
172
                user.add_resource_policy(*args)
173
            except Exception as e:
174
                raise CommandError("Failed to add policy: %s" % e)
175

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

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

    
205

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

    
216

    
217
def is_email(s):
218
    if s is None:
219
        return False
220
    try:
221
        validate_email(s)
222
    except:
223
        return False
224
    else:
225
        return True