Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (6.6 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.register import get_resources
48
import sys
49

    
50

    
51
DEFAULT_CONTENT_TYPE = None
52

    
53

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

    
64

    
65
def get_user(email_or_id, **kwargs):
66
    try:
67
        if email_or_id.isdigit():
68
            return AstakosUser.objects.get(id=int(email_or_id))
69
        else:
70
            return AstakosUser.objects.get(email__iexact=email_or_id, **kwargs)
71
    except AstakosUser.DoesNotExist, AstakosUser.MultipleObjectsReturned:
72
        return None
73

    
74

    
75
def get_astakosuser_content_type():
76
    try:
77
        return ContentType.objects.get(app_label='im',
78
                                       model='astakosuser')
79
    except:
80
        return DEFAULT_CONTENT_TYPE
81

    
82

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

    
93

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

    
106

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

    
119

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

    
132

    
133
def is_uuid(s):
134
    if s is None:
135
        return False
136
    try:
137
        uuid.UUID(s)
138
    except ValueError:
139
        return False
140
    else:
141
        return True
142

    
143

    
144
def is_email(s):
145
    if s is None:
146
        return False
147
    try:
148
        validate_email(s)
149
    except:
150
        return False
151
    else:
152
        return True
153

    
154

    
155
style_options = ', '.join(units.STYLES)
156

    
157

    
158
def check_style(style):
159
    if style not in units.STYLES:
160
        m = "Invalid unit style. Valid ones are %s." % style_options
161
        raise CommandError(m)
162

    
163

    
164
class ResourceDict(object):
165
    _object = None
166

    
167
    @classmethod
168
    def get(cls):
169
        if cls._object is None:
170
            cls._object = get_resources()
171
        return cls._object
172

    
173

    
174
def show_resource_value(number, resource, style):
175
    resources = ResourceDict.get()
176
    resource_dict = resources.get(resource)
177
    unit = resource_dict.get('unit') if resource_dict else None
178
    return units.show(number, unit, style)
179

    
180

    
181
def show_quotas(qh_quotas, astakos_initial, info=None, style=None):
182
    labels = ('source', 'resource', 'base quota', 'total quota', 'usage')
183
    if info is not None:
184
        labels = ('uuid', 'email') + labels
185

    
186
    print_data = []
187
    for holder, holder_quotas in qh_quotas.iteritems():
188
        h_initial = astakos_initial.get(holder)
189
        if info is not None:
190
            email = info.get(holder, "")
191

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

    
203
                print_data.append(fields)
204
    return print_data, labels