Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (7.4 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 or self.tokenlist[0]
58
        assert token, 'No token provided'
59
        return token[0] if (
60
            isinstance(token, list) or isinstance(token, tuple)) else token
61

    
62
    def authenticate(self, token=None):
63
        """Get authentication information and store it in this client
64
        As long as the AstakosClient instance is alive, the latest
65
        authentication information for this token will be available
66

67
        :param token: (str) custom token to authenticate
68
        """
69
        token = self._resolve_token(token)
70
        astakos = SynnefoAstakosClient(
71
            token, self.base_url, logger=getLogger('_my_.astakosclient'))
72
        r = astakos.get_endpoints()
73
        uuid = r['access']['user']['id']
74
        self._uuids[token] = uuid
75
        self._cache[uuid] = r
76
        self._astakos[uuid] = astakos
77
        self._uuids2usernames[token] = dict()
78
        self._usernames2uuids[token] = dict()
79
        return self._cache[uuid]
80

    
81
    def get_token(self, uuid):
82
        return self._cache[uuid]['access']['token']['id']
83

    
84
    def _validate_token(self, token):
85
        if (token not in self._uuids) or (
86
                self.get_token(self._uuids[token]) != token):
87
            self._uuids.pop(token, None)
88
            self.authenticate(token)
89

    
90
    def get_services(self, token=None):
91
        """
92
        :returns: (list) [{name:..., type:..., endpoints:[...]}, ...]
93
        """
94
        token = self._resolve_token(token)
95
        self._validate_token(token)
96
        r = self._cache[self._uuids[token]]
97
        return r['access']['serviceCatalog']
98

    
99
    def get_service_details(self, service_type, token=None):
100
        """
101
        :param service_type: (str) compute, object-store, image, account, etc.
102

103
        :returns: (dict) {name:..., type:..., endpoints:[...]}
104

105
        :raises ClientError: (600) if service_type not in service catalog
106
        """
107
        services = self.get_services(token)
108
        for service in services:
109
            try:
110
                if service['type'].lower() == service_type.lower():
111
                    return service
112
            except KeyError:
113
                self.log.warning('Misformated service %s' % service)
114
        raise ClientError(
115
            'Service type "%s" not in service catalog' % service_type, 600)
116

    
117
    def get_service_endpoints(self, service_type, version=None, token=None):
118
        """
119
        :param service_type: (str) can be compute, object-store, etc.
120

121
        :param version: (str) the version id of the service
122

123
        :returns: (dict) {SNF:uiURL, adminURL, internalURL, publicURL, ...}
124

125
        :raises ClientError: (600) if service_type not in service catalog
126

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

    
143
    def list_users(self):
144
        """list cached users information"""
145
        if not self._cache:
146
            self.authenticate()
147
        r = []
148
        for k, v in self._cache.items():
149
            r.append(dict(v['access']['user']))
150
            r[-1].update(dict(auth_token=self.get_token(k)))
151
        return r
152

    
153
    def user_info(self, token=None):
154
        """Get (cached) user information"""
155
        token = self._resolve_token(token)
156
        self._validate_token(token)
157
        r = self._cache[self._uuids[token]]
158
        return r['access']['user']
159

    
160
    def term(self, key, token=None):
161
        """Get (cached) term, from user credentials"""
162
        return self.user_term(key, token)
163

    
164
    def user_term(self, key, token=None):
165
        """Get (cached) term, from user credentials"""
166
        return self.user_info(token).get(key, None)
167

    
168
    def post_user_catalogs(self, uuids=None, displaynames=None, token=None):
169
        """POST base_url/user_catalogs
170

171
        :param uuids: (list or tuple) user uuids
172

173
        :param displaynames: (list or tuple) usernames (mut. excl. to uuids)
174

175
        :returns: (dict) {uuid1: name1, uuid2: name2, ...} or oposite
176
        """
177
        return self.uuids2usernames(uuids, token) if (
178
            uuids) else self.usernnames2uuids(displaynames, token)
179

    
180
    def uuids2usernames(self, uuids, token=None):
181
        token = self._resolve_token(token)
182
        self._validate_token(token)
183
        astakos = self._astakos[self._uuids[token]]
184
        if set(uuids).difference(self._uuids2usernames[token]):
185
            self._uuids2usernames[token].update(astakos.get_usernames(uuids))
186
        return self._uuids2usernames[token]
187

    
188
    def usernames2uuids(self, usernames, token=None):
189
        token = self._resolve_token(token)
190
        self._validate_token(token)
191
        astakos = self._astakos[self._uuids[token]]
192
        if set(usernames).difference(self._usernames2uuids[token]):
193
            self._usernames2uuids[token].update(astakos.get_uuids(usernames))
194
        return self._usernames2uuids