Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (6.4 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.register import get_resources
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_astakosuser_content_type():
72
    try:
73
        return ContentType.objects.get(app_label='im',
74
                                       model='astakosuser')
75
    except:
76
        return DEFAULT_CONTENT_TYPE
77

    
78

    
79
def add_user_permission(user, pname):
80
    content_type = get_astakosuser_content_type()
81
    if user.has_perm(pname):
82
        return 0, None
83
    p, created = Permission.objects.get_or_create(codename=pname,
84
                                                  name=pname.capitalize(),
85
                                                  content_type=content_type)
86
    user.user_permissions.add(p)
87
    return 1, created
88

    
89

    
90
def add_group_permission(group, pname):
91
    content_type = get_astakosuser_content_type()
92
    if pname in [p.codename for p in group.permissions.all()]:
93
        return 0, None
94
    content_type = ContentType.objects.get(app_label='im',
95
                                           model='astakosuser')
96
    p, created = Permission.objects.get_or_create(codename=pname,
97
                                                  name=pname.capitalize(),
98
                                                  content_type=content_type)
99
    group.permissions.add(p)
100
    return 1, created
101

    
102

    
103
def remove_user_permission(user, pname):
104
    content_type = get_astakosuser_content_type()
105
    if user.has_perm(pname):
106
        return 0
107
    try:
108
        p = Permission.objects.get(codename=pname,
109
                                   content_type=content_type)
110
        user.user_permissions.remove(p)
111
        return 1
112
    except Permission.DoesNotExist:
113
        return -1
114

    
115

    
116
def remove_group_permission(group, pname):
117
    content_type = get_astakosuser_content_type()
118
    if pname not in [p.codename for p in group.permissions.all()]:
119
        return 0
120
    try:
121
        p = Permission.objects.get(codename=pname,
122
                                   content_type=content_type)
123
        group.permissions.remove(p)
124
        return 1
125
    except Permission.DoesNotExist:
126
        return -1
127

    
128

    
129
def is_uuid(s):
130
    if s is None:
131
        return False
132
    try:
133
        uuid.UUID(s)
134
    except ValueError:
135
        return False
136
    else:
137
        return True
138

    
139

    
140
def is_email(s):
141
    if s is None:
142
        return False
143
    try:
144
        validate_email(s)
145
    except:
146
        return False
147
    else:
148
        return True
149

    
150

    
151
style_options = ', '.join(units.STYLES)
152

    
153

    
154
def check_style(style):
155
    if style not in units.STYLES:
156
        m = "Invalid unit style. Valid ones are %s." % style_options
157
        raise CommandError(m)
158

    
159

    
160
class ResourceDict(object):
161
    _object = None
162

    
163
    @classmethod
164
    def get(cls):
165
        if cls._object is None:
166
            cls._object = get_resources()
167
        return cls._object
168

    
169

    
170
def show_resource_value(number, resource, style):
171
    resources = ResourceDict.get()
172
    resource_dict = resources.get(resource)
173
    unit = resource_dict.get('unit') if resource_dict else None
174
    return units.show(number, unit, style)
175

    
176

    
177
def show_quotas(qh_quotas, astakos_initial, info=None, style=None):
178
    labels = ('source', 'resource', 'base quota', 'total quota', 'usage')
179
    if info is not None:
180
        labels = ('uuid', 'email') + labels
181

    
182
    print_data = []
183
    for holder, holder_quotas in qh_quotas.iteritems():
184
        h_initial = astakos_initial.get(holder)
185
        if info is not None:
186
            email = info.get(holder, "")
187

    
188
        for source, source_quotas in holder_quotas.iteritems():
189
            s_initial = h_initial.get(source) if h_initial else None
190
            for resource, values in source_quotas.iteritems():
191
                initial = s_initial.get(resource) if s_initial else None
192
                initial = show_resource_value(initial, resource, style)
193
                limit = show_resource_value(values['limit'], resource, style)
194
                usage = show_resource_value(values['usage'], resource, style)
195
                fields = (source, resource, initial, limit, usage)
196
                if info is not None:
197
                    fields = (holder, email) + fields
198

    
199
                print_data.append(fields)
200
    return print_data, labels