Statistics
| Branch: | Tag: | Revision:

root / kamaki / clients / astakos / __init__.py @ 38db356b

History | View | Annotate | Download (6.2 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

    
36
from kamaki.clients import Client, ClientError
37

    
38

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
156
    def post_user_catalogs(self, uuids=None, displaynames=None):
157
        """POST base_url/user_catalogs
158

159
        :param uuids: (list or tuple) user uuids
160

161
        :param displaynames: (list or tuple) usernames (mut. excl. to uuids)
162

163
        :returns: (dict) {uuid1: name1, uuid2: name2, ...} or oposite
164
        """
165
        account_url = self.get_service_endpoints('account')['publicURL']
166
        account = AstakosClient(account_url, self.token)
167
        json_data = dict(uuids=uuids) if (
168
            uuids) else dict(displaynames=displaynames)
169
        return account.post('user_catalogs', json=json_data)