Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / management / commands / _common.py @ 5a0f9d6c

History | View | Annotate | Download (7.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
import uuid
35

    
36
from django.core.validators import validate_email
37
from django.contrib.auth.models import Permission
38
from django.contrib.contenttypes.models import ContentType
39
from django.core.management import CommandError
40

    
41
from synnefo.util import units
42
from astakos.im.models import AstakosUser
43
from astakos.im import register
44
import sys
45

    
46

    
47
DEFAULT_CONTENT_TYPE = None
48

    
49

    
50
def read_from_file(f_name):
51
    if f_name == '-':
52
        return sys.stdin.read()
53
    else:
54
        try:
55
            with open(f_name) as file_desc:
56
                return file_desc.read()
57
        except IOError as e:
58
            raise CommandError(e)
59

    
60

    
61
def get_user(email_or_id, **kwargs):
62
    try:
63
        if email_or_id.isdigit():
64
            return AstakosUser.objects.get(id=int(email_or_id))
65
        else:
66
            return AstakosUser.objects.get(email__iexact=email_or_id, **kwargs)
67
    except (AstakosUser.DoesNotExist, AstakosUser.MultipleObjectsReturned):
68
        return None
69

    
70

    
71
def get_accepted_user(user_ident):
72
    if is_uuid(user_ident):
73
        try:
74
            user = AstakosUser.objects.get(uuid=user_ident)
75
        except AstakosUser.DoesNotExist:
76
            raise CommandError('There is no user with uuid: %s' %
77
                               user_ident)
78
    elif is_email(user_ident):
79
        try:
80
            user = AstakosUser.objects.get(username=user_ident)
81
        except AstakosUser.DoesNotExist:
82
            raise CommandError('There is no user with email: %s' %
83
                               user_ident)
84
    else:
85
        raise CommandError('Please specify user by uuid or email')
86

    
87
    if not user.is_accepted():
88
        raise CommandError('%s is not an accepted user.' % user.uuid)
89

    
90
    return user
91

    
92

    
93
def get_astakosuser_content_type():
94
    try:
95
        return ContentType.objects.get(app_label='im',
96
                                       model='astakosuser')
97
    except:
98
        return DEFAULT_CONTENT_TYPE
99

    
100

    
101
def add_user_permission(user, pname):
102
    content_type = get_astakosuser_content_type()
103
    if user.has_perm(pname):
104
        return 0, None
105
    p, created = Permission.objects.get_or_create(codename=pname,
106
                                                  name=pname.capitalize(),
107
                                                  content_type=content_type)
108
    user.user_permissions.add(p)
109
    return 1, created
110

    
111

    
112
def add_group_permission(group, pname):
113
    content_type = get_astakosuser_content_type()
114
    if pname in [p.codename for p in group.permissions.all()]:
115
        return 0, None
116
    content_type = ContentType.objects.get(app_label='im',
117
                                           model='astakosuser')
118
    p, created = Permission.objects.get_or_create(codename=pname,
119
                                                  name=pname.capitalize(),
120
                                                  content_type=content_type)
121
    group.permissions.add(p)
122
    return 1, created
123

    
124

    
125
def remove_user_permission(user, pname):
126
    content_type = get_astakosuser_content_type()
127
    if user.has_perm(pname):
128
        return 0
129
    try:
130
        p = Permission.objects.get(codename=pname,
131
                                   content_type=content_type)
132
        user.user_permissions.remove(p)
133
        return 1
134
    except Permission.DoesNotExist:
135
        return -1
136

    
137

    
138
def remove_group_permission(group, pname):
139
    content_type = get_astakosuser_content_type()
140
    if pname not in [p.codename for p in group.permissions.all()]:
141
        return 0
142
    try:
143
        p = Permission.objects.get(codename=pname,
144
                                   content_type=content_type)
145
        group.permissions.remove(p)
146
        return 1
147
    except Permission.DoesNotExist:
148
        return -1
149

    
150

    
151
def is_uuid(s):
152
    if s is None:
153
        return False
154
    try:
155
        uuid.UUID(s)
156
    except ValueError:
157
        return False
158
    else:
159
        return True
160

    
161

    
162
def is_email(s):
163
    if s is None:
164
        return False
165
    try:
166
        validate_email(s)
167
    except:
168
        return False
169
    else:
170
        return True
171

    
172

    
173
style_options = ', '.join(units.STYLES)
174

    
175

    
176
def check_style(style):
177
    if style not in units.STYLES:
178
        m = "Invalid unit style. Valid ones are %s." % style_options
179
        raise CommandError(m)
180

    
181

    
182
class ResourceDict(object):
183
    _object = None
184

    
185
    @classmethod
186
    def get(cls):
187
        if cls._object is None:
188
            rs = register.get_resources()
189
            cls._object = register.resources_to_dict(rs)
190
        return cls._object
191

    
192

    
193
def show_resource_value(number, resource, style):
194
    resources = ResourceDict.get()
195
    resource_dict = resources.get(resource)
196
    unit = resource_dict.get('unit') if resource_dict else None
197
    return units.show(number, unit, style)
198

    
199

    
200
def collect_holder_quotas(holder_quotas, h_initial, style=None):
201
    print_data = []
202
    for source, source_quotas in holder_quotas.iteritems():
203
        try:
204
            s_initial = h_initial[source]
205
        except KeyError:
206
            continue
207
        for resource, values in source_quotas.iteritems():
208
            try:
209
                initial = s_initial[resource]
210
            except KeyError:
211
                continue
212
            initial = show_resource_value(initial, resource, style)
213
            limit = show_resource_value(values['limit'], resource, style)
214
            usage = show_resource_value(values['usage'], resource, style)
215
            fields = (source, resource, initial, limit, usage)
216
            print_data.append(fields)
217
    return print_data
218

    
219

    
220
def show_user_quotas(holder_quotas, h_initial, style=None):
221
    labels = ('source', 'resource', 'base_quota', 'total_quota', 'usage')
222
    print_data = collect_holder_quotas(holder_quotas, h_initial, style=style)
223
    return print_data, labels
224

    
225

    
226
def show_quotas(qh_quotas, astakos_initial, info=None, style=None):
227
    labels = ('user', 'source', 'resource', 'base_quota', 'total_quota',
228
              'usage')
229
    if info is not None:
230
        labels = ('displayname',) + labels
231

    
232
    print_data = []
233
    for holder, holder_quotas in qh_quotas.iteritems():
234
        h_initial = astakos_initial.get(holder)
235
        if h_initial is None:
236
            continue
237

    
238
        if info is not None:
239
            email = info.get(holder, "")
240

    
241
        h_data = collect_holder_quotas(holder_quotas, h_initial, style=style)
242
        if info is not None:
243
            h_data = [(email, holder) + fields for fields in h_data]
244
        else:
245
            h_data = [(holder,) + fields for fields in h_data]
246
        print_data += h_data
247
    return print_data, labels