Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (7.5 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
                                              'import_limit',
51
                                              'export_limit'))
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> <quantity> <import_limit> <export_limit>
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 0 1000000 1000000
66

67
    The last two values are arbitrarily large to represent no
68
    import/export limit at all.
69

70
    When setting quota from the command line, specify only capacity.
71
    Quantity and import/export limit will get default values. Example:
72

73
    --set-capacity 6119a50b-cbc7-42c0-bafc-4b6570e3f6ac cyclades.vm 10
74
    """
75

    
76
    option_list = BaseCommand.option_list + (
77
        make_option('--from-file',
78
                    dest='from_file',
79
                    metavar='<exported-quotas.txt>',
80
                    help="Import quotas from file"),
81
        make_option('--set-capacity',
82
                    dest='set_capacity',
83
                    metavar='<uuid or email> <resource> <capacity>',
84
                    nargs=3,
85
                    help="Set capacity for a specified user/resource pair"),
86
        make_option('-f', '--force',
87
                    action='store_true',
88
                    default=False,
89
                    dest='force',
90
                    help="Do not ask for confirmation"),
91
    )
92

    
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

    
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
        args = AddResourceArgs(resource=resource,
129
                               capacity=capacity,
130
                               quantity=0,
131
                               import_limit=QH_PRACTICALLY_INFINITE,
132
                               export_limit=QH_PRACTICALLY_INFINITE,
133
                               )
134

    
135
        try:
136
            quota = user.get_resource_policy(resource)
137
        except Resource.DoesNotExist:
138
            raise CommandError("No such resource: %s" % resource)
139

    
140
        current = quota.capacity if quota is not None else None
141

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

    
152
        try:
153
            user.add_resource_policy(*args)
154
        except Exception as e:
155
            raise CommandError("Failed to add policy: %s" % e)
156

    
157
    def import_from_file(self, location):
158
        try:
159
            f = open(location, 'r')
160
        except IOError, e:
161
            raise CommandError(e)
162

    
163
        for line in f.readlines():
164
            try:
165
                t = line.rstrip('\n').split(' ')
166
                user = t[0]
167
                args = AddResourceArgs(*t[1:])
168
            except(IndexError, TypeError):
169
                self.stdout.write('Invalid line format: %s:\n' % t)
170
                continue
171
            else:
172
                try:
173
                    user = AstakosUser.objects.get(uuid=user)
174
                except AstakosUser.DoesNotExist:
175
                    self.stdout.write('Not found user having uuid: %s\n' % user)
176
                    continue
177
                else:
178
                    try:
179
                        user.add_resource_policy(*args)
180
                    except Exception, e:
181
                        self.stdout.write('Failed to policy: %s\n' % e)
182
                        continue
183
            finally:
184
                f.close()
185

    
186

    
187
def is_uuid(s):
188
    if s is None:
189
        return False
190
    try:
191
        uuid.UUID(s)
192
    except ValueError:
193
        return False
194
    else:
195
        return True
196

    
197

    
198
def is_email(s):
199
    if s is None:
200
        return False
201
    try:
202
        validate_email(s)
203
    except:
204
        return False
205
    else:
206
        return True