__init__.py 9.96 KB
Newer Older
Olga Brani's avatar
Olga Brani committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# Copyright 2011-2012 GRNET S.A. All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
#   1. Redistributions of source code must retain the above
#      copyright notice, this list of conditions and the following
#      disclaimer.
#
#   2. Redistributions in binary form must reproduce the above
#      copyright notice, this list of conditions and the following
#      disclaimer in the documentation and/or other materials
#      provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# The views and conclusions contained in the software and
# documentation are those of the authors and should not be
# interpreted as representing official policies, either expressed
# or implied, of GRNET S.A.

from django.db import IntegrityError, transaction
from django.core.exceptions import ObjectDoesNotExist
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
36
from django.conf import settings
Olga Brani's avatar
Olga Brani committed
37
38
39
40

from functools import wraps
from smtplib import SMTPException

41
from astakos.im.models import (
42
43
    AstakosUser,
    Resource, Service, RESOURCE_SEPARATOR,
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
44
    Project, ProjectApplication, ProjectMembership)
45
46
from astakos.im.api.backends.base import (
    BaseBackend, SuccessResult, FailureResult)
47
from astakos.im.api.backends.errors import (
48
    ItemNotExists, ItemExists, MissingIdentifier, MultipleItemsExist)
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
49

Olga Brani's avatar
Olga Brani committed
50
from astakos.im.util import reserved_email, model_to_dict
51
from astakos.im.endpoints.qh import get_quota
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
52
53
54
55
try:
    from astakos.im.messages import astakos_messages
except:
    pass
Olga Brani's avatar
Olga Brani committed
56
57
58
59
60
61
62
63

import logging

logger = logging.getLogger(__name__)

DEFAULT_CONTENT_TYPE = None


64
def safe(func):
Olga Brani's avatar
Olga Brani committed
65
    """Decorator function for views that implement an API method."""
66
67
68
69
70
71
72
    @wraps(func)
    def wrapper(self, *args, **kwargs):
        logger.debug('%s %s %s' % (func, args, kwargs))
        try:
            data = func(self, *args, **kwargs) or ()
        except Exception, e:
            logger.exception(e)
73
            return FailureResult(e)
74
75
76
        else:
            return SuccessResult(data)
    return wrapper
Olga Brani's avatar
Olga Brani committed
77
78
79
80
81


class DjangoBackend(BaseBackend):
    def _lookup_object(self, model, **kwargs):
        """
82
83
        Returns an object of the specific model matching the given lookup
        parameters.
Olga Brani's avatar
Olga Brani committed
84
85
86
87
88
89
        """
        if not kwargs:
            raise MissingIdentifier
        try:
            return model.objects.get(**kwargs)
        except model.DoesNotExist:
90
91
92
            raise ItemNotExists(model._meta.verbose_name, **kwargs)
        except model.MultipleObjectsReturned:
            raise MultipleItemsExist(model._meta.verbose_name, **kwargs)
Olga Brani's avatar
Olga Brani committed
93
94
95
96
97

    def _lookup_user(self, id):
        """
        Returns an AstakosUser having this id.
        """
98
99
        if not isinstance(id, int):
            raise TypeError('User id should be of type int')
Olga Brani's avatar
Olga Brani committed
100
101
102
103
104
105
        return self._lookup_object(AstakosUser, id=id)

    def _lookup_service(self, id):
        """
        Returns an Service having this id.
        """
106
107
        if not isinstance(id, int):
            raise TypeError('Service id should be of type int')
Olga Brani's avatar
Olga Brani committed
108
109
110
111
112
113
        return self._lookup_object(Service, id=id)

    def _list(self, model, filter=()):
        q = model.objects.all()
        if filter:
            q = q.filter(id__in=filter)
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
114
115
116
117
        return map(lambda o: self._details(o), q)

    def _details(self, obj):
        return model_to_dict(obj, exclude=[])
Olga Brani's avatar
Olga Brani committed
118
119

    def _create_object(self, model, **kwargs):
120
        o = model.objects.create(**kwargs)
Olga Brani's avatar
Olga Brani committed
121
122
123
124
125
126
127
128
129
130
131
        o.save()
        return o

    def _update_object(self, model, id, save=True, **kwargs):
        o = self._lookup_object(model, id=id)
        if kwargs:
            o.__dict__.update(kwargs)
        if save:
            o.save()
        return o

132
    @safe
Olga Brani's avatar
Olga Brani committed
133
134
135
136
137
138
139
    def update_user(self, user_id, renew_token=False, **kwargs):
        user = self._update_object(AstakosUser, user_id, save=False, **kwargs)
        if renew_token:
            user.renew_token()
        if kwargs or renew_token:
            user.save()

140
    @safe
Olga Brani's avatar
Olga Brani committed
141
142
143
144
145
    def create_user(self, **kwargs):
        policies = kwargs.pop('policies', ())
        permissions = kwargs.pop('permissions', ())
        groups = kwargs.pop('groups', ())
        password = kwargs.pop('password', None)
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
146
        provider = kwargs.pop('provider', 'local')
Olga Brani's avatar
Olga Brani committed
147
148
149
150
151
152
153
154

        u = self._create_object(AstakosUser, **kwargs)

        if password:
            u.set_password(password)
        u.permissions = permissions
        u.policies = policies
        u.extended_groups = groups
155

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
156
157
        if not u.has_auth_provider(provider):
            u.add_auth_provider(provider)
158

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
159
        return self._details(u)
Olga Brani's avatar
Olga Brani committed
160

161
    @safe
Olga Brani's avatar
Olga Brani committed
162
163
164
165
166
167
168
169
170
171
172
173
    def add_policies(self, user_id, update=False, policies=()):
        user = self._lookup_user(user_id)
        rejected = []
        append = rejected.append
        for p in policies:
            service = p.get('service')
            resource = p.get('resource')
            uplimit = p.get('uplimit')
            try:
                user.add_policy(service, resource, uplimit, update)
            except (ObjectDoesNotExist, IntegrityError), e:
                append((service, resource, e))
174
        return rejected
175

176
    @safe
Olga Brani's avatar
Olga Brani committed
177
178
179
180
181
182
183
184
185
186
187
188
189
    def remove_policies(self, user_id, policies=()):
        user = self._lookup_user(user_id)
        if not user:
            return user_id
        rejected = []
        append = rejected.append
        for p in policies:
            service = p.get('service')
            resource = p.get('resource')
            try:
                user.delete_policy(service, resource)
            except ObjectDoesNotExist, e:
                append((service, resource, e))
190
        return rejected
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
191
    
192
    @safe
Olga Brani's avatar
Olga Brani committed
193
194
195
196
197
198
199
200
201
    def add_permissions(self, user_id, permissions=()):
        user = self._lookup_user(user_id)
        rejected = []
        append = rejected.append
        for p in permissions:
            try:
                user.add_permission(p)
            except IntegrityError, e:
                append((p, e))
202
        return rejected
203

204
    @safe
Olga Brani's avatar
Olga Brani committed
205
206
207
208
209
210
211
212
213
    def remove_permissions(self, user_id, permissions=()):
        user = self._lookup_user(user_id)
        rejected = []
        append = rejected.append
        for p in permissions:
            try:
                user.remove_permission(p)
            except (ObjectDoesNotExist, IntegrityError), e:
                append((p, e))
214
        return rejected
215

216
    @safe
Olga Brani's avatar
Olga Brani committed
217
218
219
220
221
    def invite_users(self, senderid, recipients=()):
        user = self._lookup_user(senderid)
        rejected = []
        append = rejected.append
        for r in recipients:
222
223
            email = r.get('email')
            realname = r.get('realname')
Olga Brani's avatar
Olga Brani committed
224
            try:
225
                user.invite(email, realname)
Olga Brani's avatar
Olga Brani committed
226
227
            except (IntegrityError, SMTPException), e:
                append((email, e))
228
        return rejected
229

230
    @safe
Olga Brani's avatar
Olga Brani committed
231
232
233
    def list_users(self, filter=()):
        return self._list(AstakosUser, filter=filter)

234
    @safe
Olga Brani's avatar
Olga Brani committed
235
236
    def get_resource_usage(self, user_id):
        user = self._lookup_user(user_id)
237
        data = get_quota((user,))
Olga Brani's avatar
Olga Brani committed
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
        resources = []
        append = resources.append
        for t in data:
            t = (i if i else 0 for i in t)
            (entity, name, quantity, capacity, importLimit, exportLimit,
             imported, exported, returned, released, flags) = t
            service, sep, resource = name.partition(RESOURCE_SEPARATOR)
            resource = Resource.objects.select_related().get(
                service__name=service, name=resource)
            d = dict(name=name,
                     description=resource.desc,
                     unit=resource.unit or '',
                     maxValue=quantity + capacity,
                     currValue=quantity + imported - released - exported + returned)
            append(d)
        return resources

255
    @safe
Olga Brani's avatar
Olga Brani committed
256
257
258
    def list_resources(self, filter=()):
        return self._list(Resource, filter=filter)

259
    @safe
Olga Brani's avatar
Olga Brani committed
260
261
262
263
    def create_service(self, **kwargs):
        resources = kwargs.pop('resources', ())
        s = self._create_object(Service, **kwargs)
        s.resources = resources
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
264
        return self._details(s)
Olga Brani's avatar
Olga Brani committed
265

266
    @safe
Olga Brani's avatar
Olga Brani committed
267
268
269
270
    def remove_services(self, ids=()):
        # TODO return information for unknown ids
        q = Service.objects.filter(id__in=ids)
        q.delete()
271

272
    @safe
Olga Brani's avatar
Olga Brani committed
273
274
275
276
277
278
279
280
    def update_service(self, service_id, renew_token=False, **kwargs):
        s = self._update_object(Service, service_id, save=False, **kwargs)
        if renew_token:
            s.renew_token()

        if kwargs or renew_token:
            s.save()

281
    @safe
Olga Brani's avatar
Olga Brani committed
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
    def add_resources(self, service_id, update=False, resources=()):
        s = self._lookup_service(service_id)
        rejected = []
        append = rejected.append
        for r in resources:
            try:
                rr = r.copy()
                resource_id = rr.pop('id', None)
                if update:
                    if not resource_id:
                        raise MissingIdentifier
                    resource = self._update_object(Resource, resource_id, **rr)
                else:
                    resource = self._create_object(Resource, service=s, **rr)
            except Exception, e:
                append((r, e))
298
        return rejected
299

300
    @safe
Olga Brani's avatar
Olga Brani committed
301
302
303
304
    def remove_resources(self, service_id, ids=()):
        # TODO return information for unknown ids
        q = Resource.objects.filter(service__id=service_id,
                                id__in=ids)
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
305
        q.delete()