Statistics
| Branch: | Tag: | Revision:

root / kamaki / clients / astakos / __init__.py @ b44a5a37

History | View | Annotate | Download (5.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 kamaki.clients import Client, ClientError
35
from logging import getLogger
36

    
37

    
38
class AstakosClient(Client):
39
    """Synnefo Astakos API client"""
40

    
41
    def __init__(self, base_url, token=None):
42
        super(AstakosClient, self).__init__(base_url, token)
43
        self._cache = {}
44
        self._uuids = {}
45
        self.log = getLogger('__name__')
46

    
47
    def authenticate(self, token=None):
48
        """Get authentication information and store it in this client
49
        As long as the AstakosClient instance is alive, the latest
50
        authentication information for this token will be available
51

52
        :param token: (str) custom token to authenticate
53

54
        :returns: (dict) authentication information
55
        """
56
        self.token = token or self.token
57
        body = dict(auth=dict(token=dict(id=self.token)))
58
        r = self.post('/tokens', json=body).json
59
        uuid = r['access']['user']['id']
60
        self._uuids[self.token] = uuid
61
        self._cache[uuid] = r
62
        return self._cache[uuid]
63

    
64
    def get_token(self, uuid):
65
        return self._cache[uuid]['access']['token']['id']
66

    
67
    def get_services(self, token=None):
68
        """
69
        :returns: (list) [{name:..., type:..., endpoints:[...]}, ...]
70
        """
71
        token_bu = self.token or token
72
        token = token or self.token
73
        try:
74
            r = self._cache[self._uuids[token]]
75
        except KeyError:
76
            r = self.authenticate(token)
77
        finally:
78
            self.token = token_bu
79
        return r['access']['serviceCatalog']
80

    
81
    def get_service_details(self, service_type, token=None):
82
        """
83
        :param service_type: (str) compute, object-store, image, account, etc.
84

85
        :returns: (dict) {name:..., type:..., endpoints:[...]}
86

87
        :raises ClientError: (600) if service_type not in service catalog
88
        """
89
        services = self.get_services(token)
90
        for service in services:
91
            try:
92
                if service['type'].lower() == service_type.lower():
93
                    return service
94
            except KeyError:
95
                self.log.warning('Misformated service %s' % service)
96
        raise ClientError(
97
            'Service type "%s" not in service catalog' % service_type, 600)
98

    
99
    def get_service_endpoints(self, service_type, version=None, token=None):
100
        """
101
        :param service_type: (str) can be compute, object-store, etc.
102

103
        :param version: (str) the version id of the service
104

105
        :returns: (dict) {SNF:uiURL, adminURL, internalURL, publicURL, ...}
106

107
        :raises ClientError: (600) if service_type not in service catalog
108

109
        :raises ClientError: (601) if #matching endpoints != 1
110
        """
111
        service = self.get_service_details(service_type, token)
112
        matches = []
113
        for endpoint in service['endpoints']:
114
            if (not version) or (
115
                    endpoint['versionId'].lower() == version.lower()):
116
                matches.append(endpoint)
117
        if len(matches) != 1:
118
            raise ClientError(
119
                '%s endpoints match type %s %s' % (
120
                    len(matches), service_type,
121
                    ('and versionId %s' % version) if version else ''),
122
                601)
123
        return matches[0]
124

    
125
    def list_users(self):
126
        """list cached users information"""
127
        if not self._cache:
128
            self.authenticate()
129
        r = []
130
        for k, v in self._cache.items():
131
            r.append(dict(v['access']['user']))
132
            r[-1].update(dict(auth_token=self.get_token(k)))
133
        return r
134

    
135
    def user_info(self, token=None):
136
        """Get (cached) user information"""
137
        token_bu = self.token or token
138
        token = token or self.token
139
        try:
140
            r = self._cache[self._uuids[token]]
141
        except KeyError:
142
            r = self.authenticate(token)
143
        finally:
144
            self.token = token_bu
145
        return r['access']['user']
146

    
147
    def term(self, key, token=None):
148
        """Get (cached) term, from user credentials"""
149
        return self.user_term(key, token)
150

    
151
    def user_term(self, key, token=None):
152
        """Get (cached) term, from user credentials"""
153
        return self.user_info(token).get(key, None)