Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (5.3 kB)

1
# Copyright 2012 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.log = getLogger('__name__')
45

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

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

53
        :returns: (dict) authentication information
54
        """
55
        self.token = token or self.token
56
        body = dict(auth=dict(token=dict(id=self.token)))
57
        self._cache[self.token] = self.post('/tokens', json=body).json
58
        return self._cache[self.token]
59

    
60
    def get_services(self, token=None):
61
        """
62
        :returns: (list) [{name:..., type:..., endpoints:[...]}, ...]
63
        """
64
        token_bu = self.token or token
65
        token = token or self.token
66
        try:
67
            r = self._cache[token]
68
        except KeyError:
69
            r = self.authenticate(token)
70
        finally:
71
            self.token = token_bu
72
        return r['access']['serviceCatalog']
73

    
74
    def get_service_details(self, service_type, token=None):
75
        """
76
        :param service_type: (str) compute, object-store, image, account, etc.
77

78
        :returns: (dict) {name:..., type:..., endpoints:[...]}
79

80
        :raises ClientError: (600) if service_type not in service catalog
81
        """
82
        services = self.get_services(token)
83
        for service in services:
84
            try:
85
                if service['type'].lower() == service_type.lower():
86
                    return service
87
            except KeyError:
88
                self.log.warning('Misformated service %s' % service)
89
        raise ClientError(
90
            'Service type "%s" not in service catalog' % service_type, 600)
91

    
92
    def get_service_endpoints(self, service_type, version=None, token=None):
93
        """
94
        :param service_type: (str) can be compute, object-store, etc.
95

96
        :param version: (str) the version id of the service
97

98
        :returns: (dict) {SNF:uiURL, adminURL, internalURL, publicURL, ...}
99

100
        :raises ClientError: (600) if service_type not in service catalog
101

102
        :raises ClientError: (601) if #matching endpoints != 1
103
        """
104
        service = self.get_service_details(service_type, token)
105
        matches = []
106
        for endpoint in service['endpoints']:
107

    
108
            if (not version) or (
109
                    endpoint['versionId'].lower() == version.lower()):
110
                matches.append(endpoint)
111
        if len(matches) != 1:
112
            raise ClientError(
113
                '%s endpoints match type %s %s' % (
114
                    len(matches), service_type,
115
                    ('and versionId %s' % version) if version else ''),
116
                601)
117
        return matches[0]
118

    
119
    def list_users(self):
120
        """list cached users information"""
121
        r = []
122
        for k, v in self._cache.items():
123
            r.append(dict(v['access']['user']))
124
            r[-1].update(dict(auth_token=k))
125
        return r
126

    
127
    def user_info(self, token=None):
128
        """Get (cached) user information"""
129
        token_bu = self.token or token
130
        token = token or self.token
131
        try:
132
            r = self._cache[token]
133
        except KeyError:
134
            r = self.authenticate(token)
135
        finally:
136
            self.token = token_bu
137
        return r['access']['user']
138

    
139
    def term(self, key, token=None):
140
        """Get (cached) term, from user credentials"""
141
        return self.user_term(key, token)
142

    
143
    def user_term(self, key, token=None):
144
        """Get (cached) term, from user credentials"""
145
        return self.user_info(token).get(key, None)