Statistics
| Branch: | Tag: | Revision:

root / kamaki / cli / commands / snf-astakos.py @ 31618e2a

History | View | Annotate | Download (8 kB)

1
# Copyright 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.command
33

    
34
from astakosclient import AstakosClient
35

    
36
from kamaki.cli import command
37
from kamaki.cli.errors import CLIBaseUrlError
38
from kamaki.cli.commands import (
39
    _command_init, errors, _optional_json, addLogSettings)
40
from kamaki.cli.command_tree import CommandTree
41
from kamaki.cli.utils import print_dict, format_size
42
from kamaki.cli.argument import FlagArgument, ValueArgument
43
from kamaki.cli.logger import get_logger
44

    
45
snfastakos_cmds = CommandTree('astakos', 'astakosclient CLI')
46
_commands = [snfastakos_cmds]
47

    
48

    
49
class _astakos_init(_command_init):
50

    
51
    def __init__(self, arguments=dict(), auth_base=None, cloud=None):
52
        super(_astakos_init, self).__init__(arguments, auth_base, cloud)
53
        self['token'] = ValueArgument('Custom token', '--token')
54

    
55
    @errors.generic.all
56
    #@errors.user.load
57
    @addLogSettings
58
    def _run(self):
59
        self.cloud = self.cloud if self.cloud else 'default'
60
        self.token = self['token'] or self._custom_token('astakos')\
61
            or self.config.get_cloud(self.cloud, 'token')
62
        if getattr(self, 'auth_base', False):
63
            astakos_endpoints = self.auth_base.get_service_endpoints(
64
                self._custom_type('astakos') or 'identity',
65
                self._custom_version('astakos') or '')
66
            base_url = astakos_endpoints['SNF:uiURL']
67
            base_url = ''.join(base_url.split('/ui'))
68
        else:
69
            base_url = self._custom_url('astakos')
70
        if not base_url:
71
            raise CLIBaseUrlError(service='astakos')
72
        self.client = AstakosClient(
73
            base_url, logger=get_logger('kamaki.clients'))
74

    
75
    def main(self):
76
        self._run()
77

    
78

    
79
@command(snfastakos_cmds)
80
class astakos_authenticate(_astakos_init, _optional_json):
81
    """Authenticate a user
82
    Get user information (e.g. unique account name) from token
83
    Token should be set in settings:
84
    *  check if a token is set    /config get cloud.default.token
85
    *  permanently set a token    /config set cloud.default.token <token>
86
    Token can also be provided as a parameter
87
    (To use a named cloud, use its name instead of "default")
88
    """
89

    
90
    arguments = dict(
91
        usage=FlagArgument('also return usage information', ('--with-usage'))
92
    )
93

    
94
    def _run(self):
95
        self._print(
96
            self.client.get_user_info(self.token, self['usage']), print_dict)
97

    
98
    def main(self):
99
        super(self.__class__, self)._run()
100
        self._run()
101

    
102

    
103
@command(snfastakos_cmds)
104
class astakos_username(_astakos_init, _optional_json):
105
    """Get username(s) from uuid(s)"""
106

    
107
    arguments = dict(
108
        service_token=ValueArgument(
109
            'Use service token instead', '--service-token')
110
    )
111

    
112
    def _run(self, uuids):
113
        assert uuids and isinstance(uuids, list), 'No valid uuids'
114
        if 1 == len(uuids):
115
            self._print(self.client.get_username(self.token, uuids[0]))
116
        else:
117
            self._print(
118
                self.client.get_username(self.token, uuids), print_dict)
119

    
120
    def main(self, uuid, *more_uuids):
121
        super(self.__class__, self)._run()
122
        self._run([uuid] + list(more_uuids))
123

    
124

    
125
@command(snfastakos_cmds)
126
class astakos_uuid(_astakos_init, _optional_json):
127
    """Get uuid(s) from username(s)"""
128

    
129
    def _run(self, usernames):
130
        assert usernames and isinstance(usernames, list), 'No valid usernames'
131
        if 1 == len(usernames):
132
            self._print(self.client.get_uuid(self.token, usernames[0]))
133
        else:
134
            self._print(
135
                self.client.get_uuids(self.token, usernames), print_dict)
136

    
137
    def main(self, usernames, *more_usernames):
138
        super(self.__class__, self)._run()
139
        self._run([usernames] + list(more_usernames))
140

    
141

    
142
@command(snfastakos_cmds)
143
class astakos_quotas(_astakos_init, _optional_json):
144
    """Get user (or service) quotas"""
145

    
146
    @staticmethod
147
    def _print_with_format(d):
148
        """ Print d with size formating when needed
149
        :param d: (dict) {system: {<service>: {usage: ..., limit: ..., }, ...}}
150
        """
151
        newd = dict()
152
        for k, service in d['system'].items():
153
            newd[k] = dict(service)
154
            for term in ('usage', 'limit'):
155
                if term in service:
156
                    newd[k][term] = format_size(service[term])
157
        print_dict(newd)
158

    
159
    def _run(self):
160
            self._print(
161
                self.client.get_quotas(self.token), self._print_with_format)
162

    
163
    def main(self):
164
        super(self.__class__, self)._run()
165
        self._run()
166

    
167

    
168
@command(snfastakos_cmds)
169
class astakos_services(_astakos_init):
170
    """Astakos operations filtered by services"""
171

    
172

    
173
@command(snfastakos_cmds)
174
class astakos_services_list(_astakos_init, _optional_json):
175
    """List available services"""
176

    
177
    def _run(self):
178
        self._print(self.client.get_services())
179

    
180
    def main(self):
181
        super(self.__class__, self)._run()
182
        self._run()
183

    
184

    
185
@command(snfastakos_cmds)
186
class astakos_services_username(_astakos_init, _optional_json):
187
    """Get service username(s) from uuid(s)"""
188

    
189
    def _run(self, stoken, uuids):
190
        assert uuids and isinstance(uuids, list), 'No valid uuids'
191
        if 1 == len(uuids):
192
            self._print(self.client.service_get_username(stoken, uuids[0]))
193
        else:
194
            self._print(
195
                self.client.service_get_usernames(stoken, uuids), print_dict)
196

    
197
    def main(self, service_token, uuid, *more_uuids):
198
        super(self.__class__, self)._run()
199
        self._run(service_token, [uuid] + list(more_uuids))
200

    
201

    
202
@command(snfastakos_cmds)
203
class astakos_services_uuid(_astakos_init, _optional_json):
204
    """Get service uuid(s) from username(s)"""
205

    
206
    def _run(self, stoken, usernames):
207
        assert usernames and isinstance(usernames, list), 'No valid usernames'
208
        if 1 == len(usernames):
209
            self._print(self.client.service_get_uuid(self.token, usernames[0]))
210
        else:
211
            self._print(
212
                self.client.service_get_uuids(self.token, usernames),
213
                print_dict)
214

    
215
    def main(self, service_token, usernames, *more_usernames):
216
        super(self.__class__, self)._run()
217
        self._run(service_token, [usernames] + list(more_usernames))
218

    
219

    
220
@command(snfastakos_cmds)
221
class astakos_services_quotas(_astakos_init, _optional_json):
222
    """Get user (or service) quotas"""
223

    
224
    arguments = dict(
225
        uuid=ValueArgument('A user unique id to get quotas for', '--uuid')
226
    )
227

    
228
    def _run(self, stoken):
229
        self._print(self.client.service_get_quotas(stoken, self['uuid']))
230

    
231
    def main(self, service_token):
232
        super(self.__class__, self)._run()
233
        self._run(service_token)