Statistics
| Branch: | Tag: | Revision:

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

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

    
37
from django.core.validators import validate_email
38
from django.utils.timesince import timesince, timeuntil
39
from django.contrib.auth.models import Permission
40
from django.contrib.contenttypes.models import ContentType
41
from django.core.exceptions import FieldError
42
from django.core.management import CommandError
43

    
44
from synnefo.util import units
45
from synnefo.lib.ordereddict import OrderedDict
46
from astakos.im.models import AstakosUser
47
from astakos.im.resources import get_resources
48

    
49
DEFAULT_CONTENT_TYPE = None
50

    
51

    
52
def get_user(email_or_id, **kwargs):
53
    try:
54
        if email_or_id.isdigit():
55
            return AstakosUser.objects.get(id=int(email_or_id))
56
        else:
57
            return AstakosUser.objects.get(email__iexact=email_or_id, **kwargs)
58
    except AstakosUser.DoesNotExist, AstakosUser.MultipleObjectsReturned:
59
        return None
60

    
61

    
62
def get_astakosuser_content_type():
63
    try:
64
        return ContentType.objects.get(app_label='im',
65
                                       model='astakosuser')
66
    except:
67
        return DEFAULT_CONTENT_TYPE
68

    
69

    
70
def add_user_permission(user, pname):
71
    content_type = get_astakosuser_content_type()
72
    if user.has_perm(pname):
73
        return 0, None
74
    p, created = Permission.objects.get_or_create(codename=pname,
75
                                                  name=pname.capitalize(),
76
                                                  content_type=content_type)
77
    user.user_permissions.add(p)
78
    return 1, created
79

    
80

    
81
def add_group_permission(group, pname):
82
    content_type = get_astakosuser_content_type()
83
    if pname in [p.codename for p in group.permissions.all()]:
84
        return 0, None
85
    content_type = ContentType.objects.get(app_label='im',
86
                                           model='astakosuser')
87
    p, created = Permission.objects.get_or_create(codename=pname,
88
                                                  name=pname.capitalize(),
89
                                                  content_type=content_type)
90
    group.permissions.add(p)
91
    return 1, created
92

    
93

    
94
def remove_user_permission(user, pname):
95
    content_type = get_astakosuser_content_type()
96
    if user.has_perm(pname):
97
        return 0
98
    try:
99
        p = Permission.objects.get(codename=pname,
100
                                   content_type=content_type)
101
        user.user_permissions.remove(p)
102
        return 1
103
    except Permission.DoesNotExist:
104
        return -1
105

    
106

    
107
def remove_group_permission(group, pname):
108
    content_type = get_astakosuser_content_type()
109
    if pname not in [p.codename for p in group.permissions.all()]:
110
        return 0
111
    try:
112
        p = Permission.objects.get(codename=pname,
113
                                   content_type=content_type)
114
        group.permissions.remove(p)
115
        return 1
116
    except Permission.DoesNotExist:
117
        return -1
118

    
119

    
120
def is_uuid(s):
121
    if s is None:
122
        return False
123
    try:
124
        uuid.UUID(s)
125
    except ValueError:
126
        return False
127
    else:
128
        return True
129

    
130

    
131
def is_email(s):
132
    if s is None:
133
        return False
134
    try:
135
        validate_email(s)
136
    except:
137
        return False
138
    else:
139
        return True
140

    
141

    
142
style_options = ', '.join(units.STYLES)
143

    
144

    
145
def check_style(style):
146
    if style not in units.STYLES:
147
        m = "Invalid unit style. Valid ones are %s." % style_options
148
        raise CommandError(m)
149

    
150

    
151
class ResourceDict(object):
152
    _object = None
153

    
154
    @classmethod
155
    def get(cls):
156
        if cls._object is None:
157
            cls._object = get_resources()
158
        return cls._object
159

    
160

    
161
def show_resource_value(number, resource, style):
162
    resource_dict = ResourceDict.get()
163
    unit = resource_dict[resource]['unit']
164
    return units.show(number, unit, style)
165

    
166

    
167
def show_quotas(qh_quotas, astakos_initial, info=None, style=None):
168
    labels = ('source', 'resource', 'base quota', 'total quota', 'usage')
169
    if info is not None:
170
        labels = ('uuid', 'email') + labels
171

    
172
    print_data = []
173
    for holder, holder_quotas in qh_quotas.iteritems():
174
        h_initial = astakos_initial.get(holder)
175
        if info is not None:
176
            email = info.get(holder, "")
177

    
178
        for source, source_quotas in holder_quotas.iteritems():
179
            s_initial = h_initial.get(source) if h_initial else None
180
            for resource, values in source_quotas.iteritems():
181
                initial = s_initial.get(resource) if s_initial else None
182
                initial = show_resource_value(initial, resource, style)
183
                limit = show_resource_value(values['limit'], resource, style)
184
                usage = show_resource_value(values['usage'], resource, style)
185
                fields = (source, resource, initial, limit, usage)
186
                if info is not None:
187
                    fields = (holder, email) + fields
188

    
189
                print_data.append(fields)
190
    return print_data, labels