Statistics
| Branch: | Tag: | Revision:

root / kamaki / cli / commands / snf-astakos.py @ 0155548b

History | View | Annotate | Download (13.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, AstakosClientException
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.argument import CommaSeparatedListArgument
44
from kamaki.cli.logger import get_logger
45

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

    
49

    
50
def astakoserror(foo):
51
    def _raise(self, *args, **kwargs):
52
        try:
53
            return foo(self, *args, **kwargs)
54
        except AstakosClientException as ace:
55
            try:
56
                ace.details = ['%s' % ace.details]
57
            except Exception:
58
                pass
59
            finally:
60
                raise ace
61
    return _raise
62

    
63

    
64
class _astakos_init(_command_init):
65

    
66
    def __init__(self, arguments=dict(), auth_base=None, cloud=None):
67
        super(_astakos_init, self).__init__(arguments, auth_base, cloud)
68
        self['token'] = ValueArgument('Custom token', '--token')
69

    
70
    @errors.generic.all
71
    @astakoserror
72
    @addLogSettings
73
    def _run(self):
74
        self.cloud = self.cloud if self.cloud else 'default'
75
        self.token = self['token'] or self._custom_token('astakos')\
76
            or self.config.get_cloud(self.cloud, 'token')
77
        if getattr(self, 'auth_base', False):
78
            astakos_endpoints = self.auth_base.get_service_endpoints(
79
                self._custom_type('astakos') or 'identity',
80
                self._custom_version('astakos') or '')
81
            base_url = astakos_endpoints['SNF:uiURL']
82
            base_url = base_url[:-3]
83
            #base_url = ''.join(base_url.split('/ui'))
84
        else:
85
            base_url = self._custom_url('astakos')
86
        if not base_url:
87
            raise CLIBaseUrlError(service='astakos')
88
        self.client = AstakosClient(
89
            base_url, logger=get_logger('kamaki.clients'))
90

    
91
    def main(self):
92
        self._run()
93

    
94

    
95
@command(snfastakos_cmds)
96
class astakos_user_info(_astakos_init, _optional_json):
97
    """Authenticate a user
98
    Get user information (e.g. unique account name) from token
99
    Token should be set in settings:
100
    *  check if a token is set    /config get cloud.default.token
101
    *  permanently set a token    /config set cloud.default.token <token>
102
    Token can also be provided as a parameter
103
    (To use a named cloud, use its name instead of "default")
104
    """
105

    
106
    arguments = dict(
107
        usage=FlagArgument('also return usage information', ('--with-usage'))
108
    )
109

    
110
    @errors.generic.all
111
    @astakoserror
112
    def _run(self):
113
        self._print(
114
            self.client.get_user_info(self.token, self['usage']), print_dict)
115

    
116
    def main(self):
117
        super(self.__class__, self)._run()
118
        self._run()
119

    
120

    
121
@command(snfastakos_cmds)
122
class astakos_user_name(_astakos_init, _optional_json):
123
    """Get username(s) from uuid(s)"""
124

    
125
    arguments = dict(
126
        service_token=ValueArgument(
127
            'Use service token instead', '--service-token')
128
    )
129

    
130
    @errors.generic.all
131
    @astakoserror
132
    def _run(self, uuids):
133
        assert uuids and isinstance(uuids, list), 'No valid uuids'
134
        if 1 == len(uuids):
135
            self._print(self.client.get_username(self.token, uuids[0]))
136
        else:
137
            self._print(
138
                self.client.get_username(self.token, uuids), print_dict)
139

    
140
    def main(self, uuid, *more_uuids):
141
        super(self.__class__, self)._run()
142
        self._run([uuid] + list(more_uuids))
143

    
144

    
145
@command(snfastakos_cmds)
146
class astakos_user_uuid(_astakos_init, _optional_json):
147
    """Get uuid(s) from username(s)"""
148

    
149
    @errors.generic.all
150
    @astakoserror
151
    def _run(self, usernames):
152
        assert usernames and isinstance(usernames, list), 'No valid usernames'
153
        if 1 == len(usernames):
154
            self._print(self.client.get_uuid(self.token, usernames[0]))
155
        else:
156
            self._print(
157
                self.client.get_uuids(self.token, usernames), print_dict)
158

    
159
    def main(self, usernames, *more_usernames):
160
        super(self.__class__, self)._run()
161
        self._run([usernames] + list(more_usernames))
162

    
163

    
164
@command(snfastakos_cmds)
165
class astakos_quotas(_astakos_init, _optional_json):
166
    """Get user (or service) quotas"""
167

    
168
    @staticmethod
169
    def _print_with_format(d):
170
        """ Print d with size formating when needed
171
        :param d: (dict) {system: {<service>: {usage: ..., limit: ..., }, ...}}
172
        """
173
        newd = dict()
174
        for k, service in d['system'].items():
175
            newd[k] = dict(service)
176
            for term in ('usage', 'limit'):
177
                if term in service:
178
                    newd[k][term] = format_size(service[term])
179
        print_dict(newd)
180

    
181
    @errors.generic.all
182
    @astakoserror
183
    def _run(self):
184
            self._print(
185
                self.client.get_quotas(self.token), self._print_with_format)
186

    
187
    def main(self):
188
        super(self.__class__, self)._run()
189
        self._run()
190

    
191

    
192
@command(snfastakos_cmds)
193
class astakos_services(_astakos_init):
194
    """Astakos operations filtered by services"""
195

    
196

    
197
@command(snfastakos_cmds)
198
class astakos_services_list(_astakos_init, _optional_json):
199
    """List available services"""
200

    
201
    @errors.generic.all
202
    @astakoserror
203
    def _run(self):
204
        self._print(self.client.get_services())
205

    
206
    def main(self):
207
        super(self.__class__, self)._run()
208
        self._run()
209

    
210

    
211
@command(snfastakos_cmds)
212
class astakos_services_username(_astakos_init, _optional_json):
213
    """Get service username(s) from uuid(s)"""
214

    
215
    @errors.generic.all
216
    @astakoserror
217
    def _run(self, stoken, uuids):
218
        assert uuids and isinstance(uuids, list), 'No valid uuids'
219
        if 1 == len(uuids):
220
            self._print(self.client.service_get_username(stoken, uuids[0]))
221
        else:
222
            self._print(
223
                self.client.service_get_usernames(stoken, uuids), print_dict)
224

    
225
    def main(self, service_token, uuid, *more_uuids):
226
        super(self.__class__, self)._run()
227
        self._run(service_token, [uuid] + list(more_uuids))
228

    
229

    
230
@command(snfastakos_cmds)
231
class astakos_services_uuid(_astakos_init, _optional_json):
232
    """Get service uuid(s) from username(s)"""
233

    
234
    @errors.generic.all
235
    @astakoserror
236
    def _run(self, stoken, usernames):
237
        assert usernames and isinstance(usernames, list), 'No valid usernames'
238
        if 1 == len(usernames):
239
            self._print(self.client.service_get_uuid(self.token, usernames[0]))
240
        else:
241
            self._print(
242
                self.client.service_get_uuids(self.token, usernames),
243
                print_dict)
244

    
245
    def main(self, service_token, usernames, *more_usernames):
246
        super(self.__class__, self)._run()
247
        self._run(service_token, [usernames] + list(more_usernames))
248

    
249

    
250
@command(snfastakos_cmds)
251
class astakos_services_quotas(_astakos_init, _optional_json):
252
    """Get user (or service) quotas"""
253

    
254
    arguments = dict(
255
        uuid=ValueArgument('A user unique id to get quotas for', '--uuid')
256
    )
257

    
258
    @errors.generic.all
259
    @astakoserror
260
    def _run(self, stoken):
261
        self._print(self.client.service_get_quotas(stoken, self['uuid']))
262

    
263
    def main(self, service_token):
264
        super(self.__class__, self)._run()
265
        self._run(service_token)
266

    
267

    
268
@command(snfastakos_cmds)
269
class astakos_resources(_astakos_init, _optional_json):
270
    """List user resources"""
271

    
272
    @errors.generic.all
273
    @astakoserror
274
    def _run(self):
275
        self._print(self.client.get_resources(), print_dict)
276

    
277
    def main(self):
278
        super(self.__class__, self)._run()
279
        self._run()
280

    
281

    
282
@command(snfastakos_cmds)
283
class astakos_feedback(_astakos_init):
284
    """Send feedback to astakos server"""
285

    
286
    @errors.generic.all
287
    @astakoserror
288
    def _run(self, msg, more_info=None):
289
        self.client.send_feedback(self.token, msg, more_info or '')
290

    
291
    def main(self, message, more_info=None):
292
        super(self.__class__, self)._run()
293
        self._run(message, more_info)
294

    
295

    
296
@command(snfastakos_cmds)
297
class astakos_endpoints(_astakos_init, _optional_json):
298
    """Get endpoints service endpoints"""
299

    
300
    arguments = dict(uuid=ValueArgument('User uuid', '--uuid'))
301

    
302
    @errors.generic.all
303
    @astakoserror
304
    def _run(self):
305
        self._print(
306
            self.client.get_endpoints(self.token, self['uuid']),
307
            print_dict)
308

    
309
    def main(self):
310
        super(self.__class__, self)._run()
311
        self._run()
312

    
313

    
314
@command(snfastakos_cmds)
315
class astakos_commission(_astakos_init):
316
    """Manage commissions (special privileges required)"""
317

    
318

    
319
@command(snfastakos_cmds)
320
class astakos_commission_pending(_astakos_init, _optional_json):
321
    """List pending commissions (special privileges required)"""
322

    
323
    @errors.generic.all
324
    @astakoserror
325
    def _run(self):
326
        self._print(self.client.get_pending_commissions(self.token))
327

    
328
    def main(self):
329
        super(self.__class__, self)._run()
330
        self._run()
331

    
332

    
333
@command(snfastakos_cmds)
334
class astakos_commission_info(_astakos_init, _optional_json):
335
    """Get commission info (special privileges required)"""
336

    
337
    @errors.generic.all
338
    @astakoserror
339
    def _run(self, commission_id):
340
        commission_id = int(commission_id)
341
        self._print(
342
            self.client.get_commission_info(self.token, commission_id),
343
            print_dict)
344

    
345
    def main(self, commission_id):
346
        super(self.__class__, self)._run()
347
        self._run(commission_id)
348

    
349

    
350
@command(snfastakos_cmds)
351
class astakos_commission_action(_astakos_init, _optional_json):
352
    """Invoke an action in a commission (special privileges required)
353
    Actions can be accept or reject
354
    """
355

    
356
    actions = ('accept', 'reject')
357

    
358
    @errors.generic.all
359
    @astakoserror
360
    def _run(self, commission_id, action):
361
        commission_id = int(commission_id)
362
        action = action.lower()
363
        assert action in self.actions, 'Actions can be %s' % (
364
            ' or '.join(self.actions))
365
        self._print(
366
            self.client.commission_acction(self.token, commission_id, action),
367
            print_dict)
368

    
369
    def main(self, commission_id, action):
370
        super(self.__class__, self)._run()
371
        self._run(commission_id, action)
372

    
373

    
374
@command(snfastakos_cmds)
375
class astakos_commission_accept(_astakos_init):
376
    """Accept a pending commission  (special privileges required)"""
377

    
378
    @errors.generic.all
379
    @astakoserror
380
    def _run(self, commission_id):
381
        commission_id = int(commission_id)
382
        self.client.accept_commission(self.token, commission_id)
383

    
384
    def main(self, commission_id):
385
        super(self.__class__, self)._run()
386
        self._run(commission_id)
387

    
388

    
389
@command(snfastakos_cmds)
390
class astakos_commission_reject(_astakos_init):
391
    """Reject a pending commission  (special privileges required)"""
392

    
393
    @errors.generic.all
394
    @astakoserror
395
    def _run(self, commission_id):
396
        commission_id = int(commission_id)
397
        self.client.reject_commission(self.token, commission_id)
398

    
399
    def main(self, commission_id):
400
        super(self.__class__, self)._run()
401
        self._run(commission_id)
402

    
403

    
404
@command(snfastakos_cmds)
405
class astakos_commission_resolve(_astakos_init, _optional_json):
406
    """Resolve multiple commissions  (special privileges required)"""
407

    
408
    arguments = dict(
409
        accept=CommaSeparatedListArgument(
410
            'commission ids to accept (e.g. --accept=11,12,13,...',
411
            '--accept'),
412
        reject=CommaSeparatedListArgument(
413
            'commission ids to reject (e.g. --reject=11,12,13,...',
414
            '--reject'),
415
    )
416

    
417
    @errors.generic.all
418
    @astakoserror
419
    def _run(self):
420
        print 'accepted ', self['accept']
421
        print 'rejected ', self['reject']
422
        self._print(
423
            self.client.resolve_commissions(
424
                self.token, self['accept'], self['reject']),
425
            print_dict)
426

    
427
    def main(self):
428
        super(self.__class__, self)._run()
429
        self._run()
430

    
431
# commission pending
432
# commission info
433
# commission action
434
# commission accept
435
# commission reject
436
# commission resolve
437

    
438
# XXX issue_commission, issue_one_commission
439

    
440

    
441
@command(snfastakos_cmds)
442
class astakos_test(_astakos_init):
443
    """Test an astakos command"""
444

    
445
    @errors.generic.all
446
    @astakoserror
447
    def _run(self, *args):
448
        r = self.client.get_pending_commissions(self.token)
449
        print r
450

    
451
    def main(self, *args):
452
        super(self.__class__, self)._run()
453
        self._run(*args)