__init__.py 19.5 KB
Newer Older
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
# Copyright (C) 2012, 2013 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.
33 34 35

import logging
import urlparse
36
import urllib
37
import hashlib
38
from copy import copy
39 40

import simplejson
41 42
from astakosclient.utils import \
    retry, scheme_to_class, parse_request, check_input
43
from astakosclient.errors import \
44
    AstakosClientException, Unauthorized, BadRequest, NotFound, Forbidden, \
45
    NoUserName, NoUUID, BadValue, QuotaLimit, InvalidResponse
46 47


48 49 50 51 52 53 54 55 56 57 58 59 60
# --------------------------------------------------------------------
# Astakos API urls
API_AUTHENTICATE = "/astakos/api/authenticate"
API_USERCATALOGS = "/astakos/api/user_catalogs"
API_SERVICE_USERCATALOGS = "/astakos/api/service/user_catalogs"
API_GETSERVICES = "/astakos/api/get_services"
API_RESOURCES = "/astakos/api/resources"
API_QUOTAS = "/astakos/api/quotas"
API_SERVICE_QUOTAS = "/astakos/api/service_quotas"
API_COMMISSIONS = "/astakos/api/commissions"
API_COMMISSIONS_ACTION = API_COMMISSIONS + "/action"


61
# --------------------------------------------------------------------
Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
62
# Astakos Client Class
63

64
def get_token_from_cookie(request, cookie_name):
65 66 67 68 69 70 71 72 73 74 75 76 77 78
    """Extract token from the cookie name provided

    Cookie should be in the same form as astakos
    service sets its cookie contents:
        <user_uniq>|<user_token>

    """
    try:
        cookie_content = urllib.unquote(request.COOKIE.get(cookie_name, None))
        return cookie_content.split("|")[1]
    except:
        return None


Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
79 80 81 82
class AstakosClient():
    """AstakosClient Class Implementation"""

    # ----------------------------------
83 84
    def __init__(self, astakos_url, retry=0,
                 use_pool=False, pool_size=8, logger=None):
85
        """Initialize AstakosClient Class
Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
86 87 88 89

        Keyword arguments:
        astakos_url -- i.e https://accounts.example.com (string)
        use_pool    -- use objpool for http requests (boolean)
90
        retry       -- how many time to retry (integer)
Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
91 92 93 94
        logger      -- pass a different logger

        """
        if logger is None:
95 96 97 98
            logging.basicConfig(
                format='%(asctime)s [%(levelname)s] %(name)s %(message)s',
                datefmt='%Y-%m-%d %H:%M:%S',
                level=logging.INFO)
Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
99
            logger = logging.getLogger("astakosclient")
100
        logger.debug("Intialize AstakosClient: astakos_url = %s, "
Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
101 102
                     "use_pool = %s" % (astakos_url, use_pool))

103
        check_input("__init__", logger, astakos_url=astakos_url)
Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
104 105 106

        # Check for supported scheme
        p = urlparse.urlparse(astakos_url)
107
        conn_class = scheme_to_class(p.scheme, use_pool, pool_size)
108
        if conn_class is None:
Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
109 110
            m = "Unsupported scheme: %s" % p.scheme
            logger.error(m)
111
            raise BadValue(m)
Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
112

Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
113
        # Save astakos_url etc. in our class
114
        self.retry = retry
Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
115 116 117
        self.logger = logger
        self.netloc = p.netloc
        self.scheme = p.scheme
118
        self.path = p.path.rstrip('/')
119
        self.conn_class = conn_class
Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
120

121 122
    # ----------------------------------
    @retry
123 124
    def _call_astakos(self, token, request_path,
                      headers=None, body=None, method="GET"):
Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
125
        """Make the actual call to Astakos Service"""
126 127 128 129 130 131
        if token is not None:
            hashed_token = hashlib.sha1()
            hashed_token.update(token)
            using_token = "using token %s" % (hashed_token.hexdigest())
        else:
            using_token = "without using token"
Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
132
        self.logger.debug(
133 134
            "Make a %s request to %s %s with headers %s and body %s"
            % (method, request_path, using_token, headers, body))
Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
135

Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
136
        # Check Input
137 138 139 140
        if headers is None:
            headers = {}
        if body is None:
            body = {}
141
        path = self.path + "/" + request_path.strip('/')
Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
142

Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
143 144
        # Build request's header and body
        kwargs = {}
145
        kwargs['headers'] = copy(headers)
146 147
        if token is not None:
            kwargs['headers']['X-Auth-Token'] = token
Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
148
        if body:
149
            kwargs['body'] = copy(body)
Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
150 151 152 153 154 155
            kwargs['headers'].setdefault(
                'content-type', 'application/octet-stream')
        kwargs['headers'].setdefault('content-length',
                                     len(body) if body else 0)

        try:
156 157 158
            # Get the connection object
            with self.conn_class(self.netloc) as conn:
                # Send request
159
                (message, data, status) = \
160
                    _do_request(conn, method, path, **kwargs)
Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
161
        except Exception as err:
162
            self.logger.error("Failed to send request: %s" % repr(err))
Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
163 164 165 166
            raise AstakosClientException(str(err))

        # Return
        self.logger.debug("Request returned with status %s" % status)
167
        if status == 400:
168
            raise BadRequest(message, data)
169
        elif status == 401:
170
            raise Unauthorized(message, data)
171
        elif status == 403:
172
            raise Forbidden(message, data)
173
        elif status == 404:
174
            raise NotFound(message, data)
175
        elif status < 200 or status >= 300:
176
            raise AstakosClientException(message, data, status)
177 178 179 180 181

        try:
            if data:
                return simplejson.loads(unicode(data))
            else:
182
                return None
183
        except Exception as err:
184 185
            self.logger.error("Cannot parse response \"%s\" with simplejson: %s"
                              % (data, str(err)))
186
            raise InvalidResponse(str(err), data)
Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
187 188

    # ------------------------
189
    # do a GET to ``API_AUTHENTICATE``
190
    def get_user_info(self, token, usage=False):
191
        """Authenticate user and get user's info as a dictionary
Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
192 193

        Keyword arguments:
Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
194
        token   -- user's token (string)
Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
195 196 197 198 199 200
        usage   -- return usage information for user (boolean)

        In case of success return user information (json parsed format).
        Otherwise raise an AstakosClientException.

        """
Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
201
        # Send request
202
        auth_path = copy(API_AUTHENTICATE)
Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
203 204
        if usage:
            auth_path += "?usage=1"
205
        return self._call_astakos(token, auth_path)
Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
206 207

    # ----------------------------------
208
    # do a POST to ``API_USERCATALOGS`` (or ``API_SERVICE_USERCATALOGS``)
209
    #   with {'uuids': uuids}
210
    def _uuid_catalog(self, token, uuids, req_path):
211
        req_headers = {'content-type': 'application/json'}
212
        req_body = parse_request({'uuids': uuids}, self.logger)
213
        data = self._call_astakos(
214
            token, req_path, req_headers, req_body, "POST")
215 216 217
        if "uuid_catalog" in data:
            return data.get("uuid_catalog")
        else:
218
            m = "_uuid_catalog request returned %s. No uuid_catalog found" \
219 220 221
                % data
            self.logger.error(m)
            raise AstakosClientException(m)
222

223
    def get_usernames(self, token, uuids):
Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
224 225 226
        """Return a uuid_catalog dictionary for the given uuids

        Keyword arguments:
Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
227
        token   -- user's token (string)
Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
228 229 230 231 232 233
        uuids   -- list of user ids (list of strings)

        The returned uuid_catalog is a dictionary with uuids as
        keys and the corresponding user names as values

        """
234
        req_path = copy(API_USERCATALOGS)
235
        return self._uuid_catalog(token, uuids, req_path)
Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
236

237 238
    def get_username(self, token, uuid):
        """Return the user name of a uuid (see get_usernames)"""
239
        check_input("get_username", self.logger, uuid=uuid)
240
        uuid_dict = self.get_usernames(token, [uuid])
241 242 243
        if uuid in uuid_dict:
            return uuid_dict.get(uuid)
        else:
244
            raise NoUserName(uuid)
Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
245

246
    def service_get_usernames(self, token, uuids):
247
        """Return a uuid_catalog dict using a service's token"""
248
        req_path = copy(API_SERVICE_USERCATALOGS)
249
        return self._uuid_catalog(token, uuids, req_path)
250

251
    def service_get_username(self, token, uuid):
252
        """Return the displayName of a uuid using a service's token"""
253
        check_input("service_get_username", self.logger, uuid=uuid)
254
        uuid_dict = self.service_get_usernames(token, [uuid])
255 256 257
        if uuid in uuid_dict:
            return uuid_dict.get(uuid)
        else:
258
            raise NoUserName(uuid)
259

260
    # ----------------------------------
261
    # do a POST to ``API_USERCATALOGS`` (or ``API_SERVICE_USERCATALOGS``)
262
    #   with {'displaynames': display_names}
263
    def _displayname_catalog(self, token, display_names, req_path):
264
        req_headers = {'content-type': 'application/json'}
265
        req_body = parse_request({'displaynames': display_names}, self.logger)
266
        data = self._call_astakos(
267
            token, req_path, req_headers, req_body, "POST")
268 269 270
        if "displayname_catalog" in data:
            return data.get("displayname_catalog")
        else:
271
            m = "_displayname_catalog request returned %s. " \
272 273 274
                "No displayname_catalog found" % data
            self.logger.error(m)
            raise AstakosClientException(m)
275

276
    def get_uuids(self, token, display_names):
277 278 279 280 281 282 283 284 285 286
        """Return a displayname_catalog for the given names

        Keyword arguments:
        token           -- user's token (string)
        display_names   -- list of user names (list of strings)

        The returned displayname_catalog is a dictionary with
        the names as keys and the corresponding uuids as values

        """
287
        req_path = copy(API_USERCATALOGS)
288
        return self._displayname_catalog(token, display_names, req_path)
289

290
    def get_uuid(self, token, display_name):
291
        """Return the uuid of a name (see getUUIDs)"""
292
        check_input("get_uuid", self.logger, display_name=display_name)
293
        name_dict = self.get_uuids(token, [display_name])
294 295 296 297
        if display_name in name_dict:
            return name_dict.get(display_name)
        else:
            raise NoUUID(display_name)
298

299
    def service_get_uuids(self, token, display_names):
300
        """Return a display_name catalog using a service's token"""
301
        req_path = copy(API_SERVICE_USERCATALOGS)
302
        return self._displayname_catalog(token, display_names, req_path)
303

304
    def service_get_uuid(self, token, display_name):
305
        """Return the uuid of a name using a service's token"""
306
        check_input("service_get_uuid", self.logger, display_name=display_name)
307
        name_dict = self.service_get_uuids(token, [display_name])
308 309 310 311
        if display_name in name_dict:
            return name_dict.get(display_name)
        else:
            raise NoUUID(display_name)
312

Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
313
    # ----------------------------------
314
    # do a GET to ``API_GETSERVICES``
315
    def get_services(self):
Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
316
        """Return a list of dicts with the registered services"""
317
        return self._call_astakos(None, copy(API_GETSERVICES))
318 319

    # ----------------------------------
320
    # do a GET to ``API_RESOURCES``
321 322
    def get_resources(self):
        """Return a dict of dicts with the available resources"""
323
        return self._call_astakos(None, copy(API_RESOURCES))
Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
324

325
    # ----------------------------------
326
    # do a GET to ``API_QUOTAS``
327
    def get_quotas(self, token):
328 329 330 331 332 333 334 335 336
        """Get user's quotas

        Keyword arguments:
        token   -- user's token (string)

        In case of success return a dict of dicts with user's current quotas.
        Otherwise raise an AstakosClientException

        """
337
        return self._call_astakos(token, copy(API_QUOTAS))
338

339
    # ----------------------------------
340
    # do a GET to ``API_SERVICE_QUOTAS``
341
    def service_get_quotas(self, token, user=None):
342 343 344 345
        """Get all quotas for resources associated with the service

        Keyword arguments:
        token   -- service's token (string)
346
        user    -- optionally, the uuid of a specific user
347 348

        In case of success return a dict of dicts of dicts with current quotas
349
        for all users, or of a specified user, if user argument is set.
350 351 352
        Otherwise raise an AstakosClientException

        """
353
        query = copy(API_SERVICE_QUOTAS)
354 355 356
        if user is not None:
            query += "?user=" + user
        return self._call_astakos(token, query)
357

358
    # ----------------------------------
359
    # do a POST to ``API_COMMISSIONS``
360 361 362 363
    def issue_commission(self, token, request):
        """Issue a commission

        Keyword arguments:
364
        token   -- service's token (string)
365 366 367 368 369 370 371
        request -- commision request (dict)

        In case of success return commission's id (int).
        Otherwise raise an AstakosClientException.

        """
        req_headers = {'content-type': 'application/json'}
372
        req_body = parse_request(request, self.logger)
373
        try:
374
            response = self._call_astakos(token, copy(API_COMMISSIONS),
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
                                          req_headers, req_body, "POST")
        except AstakosClientException as err:
            if err.status == 413:
                raise QuotaLimit(err.message, err.details)
            else:
                raise

        if "serial" in response:
            return response['serial']
        else:
            m = "issue_commission_core request returned %s. No serial found" \
                % response
            self.logger.error(m)
            raise AstakosClientException(m)

390
    def issue_one_commission(self, token, holder, source, provisions,
391
                             name="", force=False, auto_accept=False):
392 393 394 395 396 397
        """Issue one commission (with specific holder and source)

        keyword arguments:
        token       -- service's token (string)
        holder      -- user's id (string)
        source      -- commission's source (ex system) (string)
398
        provisions  -- resources with their quantity (dict from string to int)
399
        name        -- description of the commission (string)
400 401 402 403 404 405 406 407
        force       -- force this commission (boolean)
        auto_accept -- auto accept this commission (boolean)

        In case of success return commission's id (int).
        Otherwise raise an AstakosClientException.
        (See also issue_commission)

        """
408 409 410
        check_input("issue_one_commission", self.logger,
                    holder=holder, source=source,
                    provisions=provisions)
411 412 413 414

        request = {}
        request["force"] = force
        request["auto_accept"] = auto_accept
415
        request["name"] = name
416 417
        try:
            request["provisions"] = []
418
            for resource, quantity in provisions.iteritems():
419 420 421 422 423 424 425 426 427
                t = {"holder": holder, "source": source,
                     "resource": resource, "quantity": quantity}
                request["provisions"].append(t)
        except Exception as err:
            self.logger.error(str(err))
            raise BadValue(str(err))

        return self.issue_commission(token, request)

428
    # ----------------------------------
429
    # do a GET to ``API_COMMISSIONS``
430 431 432 433
    def get_pending_commissions(self, token):
        """Get Pending Commissions

        Keyword arguments:
434
        token   -- service's token (string)
435 436 437 438 439

        In case of success return a list of pending commissions' ids
        (list of integers)

        """
440
        return self._call_astakos(token, copy(API_COMMISSIONS))
441

442
    # ----------------------------------
443
    # do a GET to ``API_COMMISSIONS``/<serial>
444 445 446 447
    def get_commission_info(self, token, serial):
        """Get Description of a Commission

        Keyword arguments:
448
        token   -- service's token (string)
449 450 451
        serial  -- commission's id (int)

        In case of success return a dict of dicts containing
452
        informations (details) about the requested commission
453 454

        """
455
        check_input("get_commission_info", self.logger, serial=serial)
456

457
        path = API_COMMISSIONS + "/" + str(serial)
458 459
        return self._call_astakos(token, path)

460
    # ----------------------------------
461
    # do a POST to ``API_COMMISSIONS``/<serial>/action"
462 463
    def commission_action(self, token, serial, action):
        """Perform a commission action
464 465

        Keyword arguments:
466
        token   -- service's token (string)
467 468 469 470 471 472
        serial  -- commission's id (int)
        action  -- action to perform, currently accept/reject (string)

        In case of success return nothing.

        """
473 474
        check_input("commission_action", self.logger,
                    serial=serial, action=action)
475

476
        path = API_COMMISSIONS + "/" + str(serial) + "/action"
477
        req_headers = {'content-type': 'application/json'}
478
        req_body = parse_request({str(action): ""}, self.logger)
479 480
        self._call_astakos(token, path, req_headers, req_body, "POST")

481 482 483
    def accept_commission(self, token, serial):
        """Accept a commission (see commission_action)"""
        self.commission_action(token, serial, "accept")
484

485 486 487
    def reject_commission(self, token, serial):
        """Reject a commission (see commission_action)"""
        self.commission_action(token, serial, "reject")
488

489
    # ----------------------------------
490
    # do a POST to ``API_COMMISSIONS_ACTION``
491 492 493 494 495 496 497 498 499 500 501 502 503
    def resolve_commissions(self, token, accept_serials, reject_serials):
        """Resolve multiple commissions at once

        Keyword arguments:
        token           -- service's token (string)
        accept_serials  -- commissions to accept (list of ints)
        reject_serials  -- commissions to reject (list of ints)

        In case of success return a dict of dicts describing which
        commissions accepted, which rejected and which failed to
        resolved.

        """
504 505 506
        check_input("resolve_commissions", self.logger,
                    accept_serials=accept_serials,
                    reject_serials=reject_serials)
507

508
        path = copy(API_COMMISSIONS_ACTION)
509 510 511 512 513 514
        req_headers = {'content-type': 'application/json'}
        req_body = parse_request({"accept": accept_serials,
                                  "reject": reject_serials},
                                 self.logger)
        return self._call_astakos(token, path, req_headers, req_body, "POST")

515

516 517
# --------------------------------------------------------------------
# Private functions
518 519
# We want _doRequest to be a distinct function
# so that we can replace it during unit tests.
520
def _do_request(conn, method, url, **kwargs):
521 522 523 524 525 526
    """The actual request. This function can easily be mocked"""
    conn.request(method, url, **kwargs)
    response = conn.getresponse()
    length = response.getheader('content-length', None)
    data = response.read(length)
    status = int(response.status)
527 528
    message = response.reason
    return (message, data, status)