Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / management / commands / quota.py @ 7820534a

History | View | Annotate | Download (8 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
from optparse import make_option
35
from django.core.management.base import CommandError
36

    
37
from astakos.im.models import AstakosUser
38
from astakos.im.quotas import (
39
    qh_sync_users_diffs, list_user_quotas, add_base_quota)
40
from astakos.im.functions import get_user_by_uuid
41
from astakos.im.management.commands._common import is_uuid, is_email
42
from snf_django.lib.db.transaction import commit_on_success_strict
43
from synnefo.webproject.management.commands import SynnefoCommand
44
from synnefo.webproject.management import utils
45
from ._common import show_quotas
46

    
47
import logging
48
logger = logging.getLogger(__name__)
49

    
50

    
51
class Command(SynnefoCommand):
52
    help = "List and check the integrity of user quota"
53

    
54
    option_list = SynnefoCommand.option_list + (
55
        make_option('--list',
56
                    action='store_true',
57
                    dest='list',
58
                    default=False,
59
                    help="List all quota (default)"),
60
        make_option('--verify',
61
                    action='store_true',
62
                    dest='verify',
63
                    default=False,
64
                    help="Check if quotaholder is in sync with astakos"),
65
        make_option('--sync',
66
                    action='store_true',
67
                    dest='sync',
68
                    default=False,
69
                    help="Sync quotaholder"),
70
        make_option('--user',
71
                    metavar='<uuid or email>',
72
                    dest='user',
73
                    help="List quota for a specified user"),
74
        make_option('--import-base-quota',
75
                    dest='import_base_quota',
76
                    metavar='<exported-quota.txt>',
77
                    help=("Import base quota from file. "
78
                          "The file must contain non-empty lines, and each "
79
                          "line must contain a single-space-separated list "
80
                          "of values: <user> <resource name> <capacity>")
81
                    ),
82
    )
83

    
84
    @commit_on_success_strict()
85
    def handle(self, *args, **options):
86
        sync = options['sync']
87
        verify = options['verify']
88
        user_ident = options['user']
89
        list_ = options['list']
90
        import_base_quota = options['import_base_quota']
91

    
92
        if import_base_quota:
93
            if any([sync, verify, list_]):
94
                m = "--from-file cannot be combined with other options."
95
                raise CommandError(m)
96
            self.import_from_file(import_base_quota)
97
        else:
98
            self.quotas(sync, verify, user_ident, options["output_format"])
99

    
100
    def quotas(self, sync, verify, user_ident, output_format):
101
        list_only = not sync and not verify
102

    
103
        if user_ident is not None:
104
            users = [self.get_user(user_ident)]
105
        else:
106
            users = AstakosUser.objects.verified()
107

    
108
        if list_only:
109
            qh_quotas, astakos_i = list_user_quotas(users)
110

    
111
            info = {}
112
            for user in users:
113
                info[user.uuid] = user.email
114

    
115
            print_data, labels = show_quotas(qh_quotas, astakos_i, info)
116
            utils.pprint_table(self.stdout, print_data, labels,
117
                               output_format)
118

    
119
        elif verify or sync:
120
            qh_limits, diff_q = qh_sync_users_diffs(users, sync=sync)
121
            if verify:
122
                self.print_verify(qh_limits, diff_q)
123
            if sync:
124
                self.print_sync(diff_q)
125

    
126
    def get_user(self, user_ident):
127
        if is_uuid(user_ident):
128
            try:
129
                user = AstakosUser.objects.get(uuid=user_ident)
130
            except AstakosUser.DoesNotExist:
131
                raise CommandError('There is no user with uuid: %s' %
132
                                   user_ident)
133
        elif is_email(user_ident):
134
            try:
135
                user = AstakosUser.objects.get(username=user_ident)
136
            except AstakosUser.DoesNotExist:
137
                raise CommandError('There is no user with email: %s' %
138
                                   user_ident)
139
        else:
140
            raise CommandError('Please specify user by uuid or email')
141

    
142
        if not user.email_verified:
143
            raise CommandError('%s is not a verified user.\n' % user.uuid)
144

    
145
        return user
146

    
147
    def print_sync(self, diff_quotas):
148
        size = len(diff_quotas)
149
        if size == 0:
150
            self.stdout.write("No sync needed.\n")
151
        else:
152
            self.stdout.write("Synced %s users:\n" % size)
153
            for holder in diff_quotas.keys():
154
                user = get_user_by_uuid(holder)
155
                self.stdout.write("%s (%s)\n" % (holder, user.username))
156

    
157
    def print_verify(self,
158
                     qh_limits,
159
                     diff_quotas):
160

    
161
            for holder, local in diff_quotas.iteritems():
162
                registered = qh_limits.pop(holder, None)
163
                user = get_user_by_uuid(holder)
164
                if registered is None:
165
                    self.stdout.write(
166
                        "No quota for %s (%s) in quotaholder.\n" %
167
                        (holder, user.username))
168
                else:
169
                    self.stdout.write("Quota differ for %s (%s):\n" %
170
                                      (holder, user.username))
171
                    self.stdout.write("Quota according to quotaholder:\n")
172
                    self.stdout.write("%s\n" % (registered))
173
                    self.stdout.write("Quota according to astakos:\n")
174
                    self.stdout.write("%s\n\n" % (local))
175

    
176
            diffs = len(diff_quotas)
177
            if diffs:
178
                self.stdout.write("Quota differ for %d users.\n" % (diffs))
179

    
180
    def import_from_file(self, location):
181
        users = set()
182
        with open(location) as f:
183
            for line in f.readlines():
184
                try:
185
                    t = line.rstrip('\n').split(' ')
186
                    user = t[0]
187
                    resource = t[1]
188
                    capacity = t[2]
189
                except(IndexError, TypeError):
190
                    self.stdout.write('Invalid line format: %s:\n' % t)
191
                    continue
192
                else:
193
                    try:
194
                        user = self.get_user(user)
195
                        users.add(user.id)
196
                    except CommandError:
197
                        self.stdout.write('Not found user: %s\n' % user)
198
                        continue
199
                    else:
200
                        try:
201
                            add_base_quota(user, resource, capacity)
202
                        except Exception, e:
203
                            self.stdout.write('Failed to add quota: %s\n' % e)
204
                            continue