Statistics
| Branch: | Tag: | Revision:

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

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

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

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

58
    <user> <resource name> <capacity>
59

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

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

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

67
    --set-capacity 6119a50b-cbc7-42c0-bafc-4b6570e3f6ac cyclades.vm 10
68

69
    The special value of 'default' sets the user setting to the default.
70
    """
71

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

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

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

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

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

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

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

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

    
133
        args = AddResourceArgs(resource=resource,
134
                               capacity=capacity,
135
                               )
136

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

    
142
        current = quota.capacity if quota is not None else 'default'
143

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

    
155
        if capacity == 'default':
156
            try:
157
                service, sep, name = resource.partition('.')
158
                q = AstakosUserQuota.objects.get(
159
                        user=user,
160
                        resource__service__name=service,
161
                        resource__name=name)
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

    
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