__init__.py 7.99 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 36 37 38 39 40 41

import logging
import urlparse
import httplib

import simplejson
import objpool.http


Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
42 43 44 45 46 47 48 49 50
# --------------------------------------------------------------------
# Astakos Client Exception
class AstakosClientException(Exception):
    def __init__(self, message, status=0):
        self.message = message
        self.status = status

    def __str__(self):
        return repr(self.message)
51 52


53
# --------------------------------------------------------------------
Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
# Astakos Client Class
class AstakosClient():
    """AstakosClient Class Implementation"""

    # ----------------------------------
    def __init__(self, token, astakos_url, use_pool=False, logger=None):
        """Intialize AstakosClient Class

        Keyword arguments:
        token       -- user's token (string)
        astakos_url -- i.e https://accounts.example.com (string)
        use_pool    -- use objpool for http requests (boolean)
        logger      -- pass a different logger

        """
        if logger is None:
            logger = logging.getLogger("astakosclient")
        logger.debug("Intialize AstakosClient: astakos_url = %s"
                     "use_pool = %s" % (astakos_url, use_pool))

        # Check Input
        if not token:
            m = "Token not given"
            logger.error(m)
            raise ValueError(m)
        if not astakos_url:
            m = "Astakos url not given"
            logger.error(m)
            raise ValueError(m)

        # Check for supported scheme
        p = urlparse.urlparse(astakos_url)
        conn = _scheme_to_class(p.scheme, use_pool)
        if conn is None:
            m = "Unsupported scheme: %s" % p.scheme
            logger.error(m)
            raise ValueError(m)

        # Save token and url
        self.logger = logger
        self.token = token
        self.netloc = p.netloc
        self.scheme = p.scheme
        self.conn = conn

    # ----------------------------------
    def _callAstakos(self, request_path, headers={}, body={}, method="GET"):
        """Make the actual call to Astakos Service"""
        self.logger.debug(
            "Make a %s request to %s with headers %s "
            "and body %s" % (method, request_path, headers, body))

        # Build request's header and body
        kwargs = {}
        kwargs['headers'] = headers
        kwargs['headers']['X-Auth-Token'] = self.token
        if body:
            kwargs['body'] = body
            kwargs['headers'].setdefault(
                'content-type', 'application/octet-stream')
        kwargs['headers'].setdefault('content-length',
                                     len(body) if body else 0)

        # Get the connection object
        conn = self.conn(self.netloc)

        # Send request
        try:
            (data, status) = _doRequest(conn, method, request_path, **kwargs)
        except Exception as err:
            self.logger.error("Failed to send request: %s" % err)
            raise AstakosClientException(str(err))
        finally:
            conn.close()

        # Return
        self.logger.debug("Request returned with status %s" % status)
        if status < 200 or status >= 300:
            raise AstakosClientException(data, status)
        return simplejson.loads(unicode(data))

    # ------------------------
    def authenticate(self, usage=False):
        """Check if user is authenticated Astakos user

        Keyword arguments:
        usage   -- return usage information for user (boolean)

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

        """
        auth_path = "/im/authenticate"
        if usage:
            auth_path += "?usage=1"
        return self._callAstakos(auth_path)

    # ----------------------------------
    def getDisplayNames(self, uuids):
        """Return a uuid_catalog dictionary for the given uuids

        Keyword arguments:
        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

        """
        req_headers = {'content-type': 'application/json'}
        req_body = simplejson.dumps({'uuids': uuids})
        req_path = "/user_catalogs"

        data = self._callAstakos(req_path, req_headers, req_body, "POST")
        # XXX: check if exists
        return data.get("uuid_catalog")

    def getDisplayName(self, uuid):
        """Return the displayName of a uuid (see getDisplayNames)"""
        if not uuid:
            m = "No uuid was given"
            self.logger.error(m)
            raise ValueError(m)
        uuid_dict = self.getDisplayNames([uuid])
        # XXX: check if exists
        return uuid_dict.get(uuid)

180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203

# A simple retry decorator
def retry(howmany):
    def decorator(func):
        def f(*args, **kwargs):
            attemps = 0
            while True:
                try:
                    return func(*args, **kwargs)
                except Exception as e:
                    is_last_attempt = attemps == howmany - 1
                    if is_last_attempt:
                        raise e
                    if e.args:
                        status = e[0]
                        # In case of Unauthorized response
                        # or Not Found return immediately
                        if status == 401 or status == 404:
                            raise e
                    attemps += 1
        return f
    return decorator


204 205
# --------------------------------------------------------------------
# Private functions
Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
206 207
def _scheme_to_class(scheme, use_pool):
    """Return the appropriate conn class for given scheme"""
208
    if scheme == "http":
Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
209 210 211 212
        if use_pool:
            return _objpoolHttpScheme
        else:
            return httplib.HTTPConnection
213
    elif scheme == "https":
Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
214 215 216 217
        if use_pool:
            return _objpoolHttpsScheme
        else:
            return httplib.HTTPSConnection
218 219 220 221
    else:
        return None


Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
222 223 224 225 226 227 228 229 230 231
def _objpoolHttpScheme(netloc):
    """Intialize the appropriate objpool.http class"""
    return objpool.http.get_http_connection(netloc, "http")


def _objpoolHttpsScheme(netloc):
    """Intialize the appropriate objpool.http class"""
    return objpool.http.get_http_connection(netloc, "https")


232 233 234 235 236 237 238
def _doRequest(conn, method, url, **kwargs):
    """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)
Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
239
    return (data, status)