Statistics
| Branch: | Tag: | Revision:

root / kamaki / clients / astakos / __init__.py @ 54b6be76

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.set_headers('content-type', 'application/json')
58
        self._cache[self.token] = self.post('/tokens', data=body).json
59
        return self._cache[self.token]
60

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

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

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

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

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

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

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

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

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

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

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

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

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

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