Statistics
| Branch: | Tag: | Revision:

root / kamaki / clients / astakos / __init__.py @ 172ee8f9

History | View | Annotate | Download (7.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 logging import getLogger
35
from astakosclient import AstakosClient as SynnefoAstakosClient
36

    
37
from kamaki.clients import Client, ClientError
38

    
39

    
40
class AstakosClient(Client):
41
    """Synnefo Astakos cached client wraper"""
42

    
43
    def __init__(self, base_url, token=None):
44
        super(AstakosClient, self).__init__(base_url, token)
45
        self._astakos = dict()
46
        self._uuids = dict()
47
        self._cache = dict()
48
        self._uuids2usernames = dict()
49
        self._usernames2uuids = dict()
50

    
51
    def _resolve_token(self, token):
52
        """
53
        :returns: (str) a single token
54

55
        :raises AssertionError: if no token exists (either param or member)
56
        """
57
        token = token or self.token
58
        assert token, 'No token provided'
59
        return token[0] if (
60
            isinstance(token, list) or isinstance(token, tuple)) else token
61

    
62
    def get_client(self, token=None):
63
        """Get the Synnefo AstakosClient instance used by client"""
64
        token = self._resolve_token(token)
65
        self._validate_token(token)
66
        return self._astakos[self._uuids[token]]
67

    
68
    def authenticate(self, token=None):
69
        """Get authentication information and store it in this client
70
        As long as the AstakosClient instance is alive, the latest
71
        authentication information for this token will be available
72

73
        :param token: (str) custom token to authenticate
74
        """
75
        token = self._resolve_token(token)
76
        astakos = SynnefoAstakosClient(
77
            token, self.base_url, logger=getLogger('astakosclient'))
78
        r = astakos.get_endpoints()
79
        uuid = r['access']['user']['id']
80
        self._uuids[token] = uuid
81
        self._cache[uuid] = r
82
        self._astakos[uuid] = astakos
83
        self._uuids2usernames[uuid] = dict()
84
        self._usernames2uuids[uuid] = dict()
85
        return self._cache[uuid]
86

    
87
    def get_token(self, uuid):
88
        return self._cache[uuid]['access']['token']['id']
89

    
90
    def _validate_token(self, token):
91
        if (token not in self._uuids) or (
92
                self.get_token(self._uuids[token]) != token):
93
            self._uuids.pop(token, None)
94
            self.authenticate(token)
95

    
96
    def get_services(self, token=None):
97
        """
98
        :returns: (list) [{name:..., type:..., endpoints:[...]}, ...]
99
        """
100
        token = self._resolve_token(token)
101
        self._validate_token(token)
102
        r = self._cache[self._uuids[token]]
103
        return r['access']['serviceCatalog']
104

    
105
    def get_service_details(self, service_type, token=None):
106
        """
107
        :param service_type: (str) compute, object-store, image, account, etc.
108

109
        :returns: (dict) {name:..., type:..., endpoints:[...]}
110

111
        :raises ClientError: (600) if service_type not in service catalog
112
        """
113
        services = self.get_services(token)
114
        for service in services:
115
            try:
116
                if service['type'].lower() == service_type.lower():
117
                    return service
118
            except KeyError:
119
                self.log.warning('Misformated service %s' % service)
120
        raise ClientError(
121
            'Service type "%s" not in service catalog' % service_type, 600)
122

    
123
    def get_service_endpoints(self, service_type, version=None, token=None):
124
        """
125
        :param service_type: (str) can be compute, object-store, etc.
126

127
        :param version: (str) the version id of the service
128

129
        :returns: (dict) {SNF:uiURL, adminURL, internalURL, publicURL, ...}
130

131
        :raises ClientError: (600) if service_type not in service catalog
132

133
        :raises ClientError: (601) if #matching endpoints != 1
134
        """
135
        service = self.get_service_details(service_type, token)
136
        matches = []
137
        for endpoint in service['endpoints']:
138
            if (not version) or (
139
                    endpoint['versionId'].lower() == version.lower()):
140
                matches.append(endpoint)
141
        if len(matches) != 1:
142
            raise ClientError(
143
                '%s endpoints match type %s %s' % (
144
                    len(matches), service_type,
145
                    ('and versionId %s' % version) if version else ''),
146
                601)
147
        return matches[0]
148

    
149
    def list_users(self):
150
        """list cached users information"""
151
        if not self._cache:
152
            self.authenticate()
153
        r = []
154
        for k, v in self._cache.items():
155
            r.append(dict(v['access']['user']))
156
            r[-1].update(dict(auth_token=self.get_token(k)))
157
        return r
158

    
159
    def user_info(self, token=None):
160
        """Get (cached) user information"""
161
        token = self._resolve_token(token)
162
        self._validate_token(token)
163
        r = self._cache[self._uuids[token]]
164
        return r['access']['user']
165

    
166
    def term(self, key, token=None):
167
        """Get (cached) term, from user credentials"""
168
        return self.user_term(key, token)
169

    
170
    def user_term(self, key, token=None):
171
        """Get (cached) term, from user credentials"""
172
        return self.user_info(token).get(key, None)
173

    
174
    def post_user_catalogs(self, uuids=None, displaynames=None, token=None):
175
        """POST base_url/user_catalogs
176

177
        :param uuids: (list or tuple) user uuids
178

179
        :param displaynames: (list or tuple) usernames (mut. excl. to uuids)
180

181
        :returns: (dict) {uuid1: name1, uuid2: name2, ...} or oposite
182
        """
183
        return self.uuids2usernames(uuids, token) if (
184
            uuids) else self.usernnames2uuids(displaynames, token)
185

    
186
    def uuids2usernames(self, uuids, token=None):
187
        token = self._resolve_token(token)
188
        self._validate_token(token)
189
        uuid = self._uuids[token]
190
        astakos = self._astakos[uuid]
191
        if set(uuids).difference(self._uuids2usernames[uuid]):
192
            self._uuids2usernames[uuid].update(astakos.get_usernames(uuids))
193
        return self._uuids2usernames[uuid]
194

    
195
    def usernames2uuids(self, usernames, token=None):
196
        token = self._resolve_token(token)
197
        self._validate_token(token)
198
        uuid = self._uuids[token]
199
        astakos = self._astakos[uuid]
200
        if set(usernames).difference(self._usernames2uuids[uuid]):
201
            self._usernames2uuids[uuid].update(astakos.get_uuids(usernames))
202
        return self._usernames2uuids[uuid]