__init__.py 11 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#!/usr/bin/env python

# Copyright 2011-2012 GRNET S.A. All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
#   1. Redistributions of source code must retain the above
#      copyright notice, this list of conditions and the following
#      disclaimer.
#
#   2. Redistributions in binary form must reproduce the above
#      copyright notice, this list of conditions and the following
#      disclaimer in the documentation and/or other materials
#      provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# The views and conclusions contained in the software and
# documentation are those of the authors and should not be
# interpreted as representing official policies, either expressed
# or implied, of GRNET S.A.

from __future__ import print_function

import gevent.monkey
#Monkey-patch everything for gevent early on
gevent.monkey.patch_all()

import inspect
import logging
import sys

from argparse import ArgumentParser
from base64 import b64encode
from os.path import abspath, basename, exists
from sys import exit, stdout, stderr

try:
    from collections import OrderedDict
except ImportError:
    from ordereddict import OrderedDict

from colors import magenta, red, yellow, bold

from kamaki import clients
59
from .errors import CLIError
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
from .config import Config

_commands = OrderedDict()

GROUPS = {}
CLI_LOCATIONS = ['kamaki.cli.commands', 'kamaki.commands', 'kamaki.cli', 'kamaki', '']

def command(group=None, name=None, syntax=None):
    """Class decorator that registers a class as a CLI command."""

    def decorator(cls):
        grp, sep, cmd = cls.__name__.partition('_')
        if not sep:
            grp, cmd = None, cls.__name__

        #cls.api = api
        cls.group = group or grp
        cls.name = name or cmd

        short_description, sep, long_description = cls.__doc__.partition('\n')
        cls.description = short_description
        cls.long_description = long_description or short_description

        cls.syntax = syntax
        if cls.syntax is None:
            # Generate a syntax string based on main's arguments
            spec = inspect.getargspec(cls.main.im_func)
            args = spec.args[1:]
            n = len(args) - len(spec.defaults or ())
            required = ' '.join('<%s>' % x.replace('____', '[:').replace('___', ':').replace('__',']').replace('_', ' ') for x in args[:n])
            optional = ' '.join('[%s]' % x.replace('____', '[:').replace('___', ':').replace('__', ']').replace('_', ' ') for x in args[n:])
            cls.syntax = ' '.join(x for x in [required, optional] if x)
            if spec.varargs:
                cls.syntax += ' <%s ...>' % spec.varargs

        if cls.group not in _commands:
            _commands[cls.group] = OrderedDict()
        _commands[cls.group][cls.name] = cls
        return cls
    return decorator

def set_api_description(api, description):
    """Method to be called by api CLIs
    Each CLI can set more than one api descriptions"""
    GROUPS[api] = description

def main():

    def print_groups():
        print('\nGroups:')
        for group in _commands:
            description = GROUPS.get(group, '')
            print(' ', group.ljust(12), description)

    def print_commands(group):
        description = GROUPS.get(group, '')
        if description:
            print('\n' + description)

        print('\nCommands:')
        for name, cls in _commands[group].items():
            print(' ', name.ljust(14), cls.description)

    def manage_logging_handlers(args):
        """This is mostly to handle logging for clients package"""

        def add_handler(name, level, prefix=''):
            h = logging.StreamHandler()
            fmt = logging.Formatter(prefix + '%(message)s')
            h.setFormatter(fmt)
            logger = logging.getLogger(name)
            logger.addHandler(h)
            logger.setLevel(level)

        if args.silent:
            add_handler('', logging.CRITICAL)
        elif args.debug:
            add_handler('requests', logging.INFO, prefix='* ')
            add_handler('clients.send', logging.DEBUG, prefix='> ')
            add_handler('clients.recv', logging.DEBUG, prefix='< ')
        elif args.verbose:
            add_handler('requests', logging.INFO, prefix='* ')
            add_handler('clients.send', logging.INFO, prefix='> ')
            add_handler('clients.recv', logging.INFO, prefix='< ')
        elif args.include:
            add_handler('clients.recv', logging.INFO)
        else:
            add_handler('', logging.WARNING)

    def load_groups(config):
        """load groups and import CLIs and Modules"""
        loaded_modules = {}
        for api in config.apis():
            api_cli = config.get(api, 'cli')
            if None == api_cli or len(api_cli)==0:
                print('Warnig: No Command Line Interface "%s" given for API "%s"'%(api_cli, api))
                print('\t(cli option in config file)')
                continue
            if not loaded_modules.has_key(api_cli):
                loaded_modules[api_cli] = False
                for location in CLI_LOCATIONS:
                    location += api_cli if location == '' else '.%s'%api_cli
                    try:
                        __import__(location)
                        loaded_modules[api_cli] = True
                        break
                    except ImportError:
                        pass
                if not loaded_modules[api_cli]:
                    print('Warning: failed to load Command Line Interface "%s" for API "%s"'%(api_cli, api))
                    print('\t(No suitable cli in known paths)')
                    continue
            if not GROUPS.has_key(api):
                GROUPS[api] = 'No description (interface: %s)'%api_cli

    def init_parser(exe):
        parser = ArgumentParser(add_help=False)
        parser.prog = '%s <group> <command>' % exe
        parser.add_argument('-h', '--help', dest='help', action='store_true',
                          default=False,
                          help="Show this help message and exit")
        parser.add_argument('--config', dest='config', metavar='PATH',
                          help="Specify the path to the configuration file")
        parser.add_argument('-d', '--debug', dest='debug', action='store_true',
                          default=False,
                          help="Include debug output")
        parser.add_argument('-i', '--include', dest='include', action='store_true',
                          default=False,
                          help="Include protocol headers in the output")
        parser.add_argument('-s', '--silent', dest='silent', action='store_true',
                          default=False,
                          help="Silent mode, don't output anything")
        parser.add_argument('-v', '--verbose', dest='verbose', action='store_true',
                          default=False,
                          help="Make the operation more talkative")
        parser.add_argument('-V', '--version', dest='version', action='store_true',
                          default=False,
                          help="Show version number and quit")
        parser.add_argument('-o', dest='options', action='append',
                          default=[], metavar="KEY=VAL",
                          help="Override a config value")
        return parser

    def find_term_in_args(arg_list, term_list):
        """find an arg_list term in term_list. All other terms up to found
        term are rearanged at the end of arg_list, preserving relative order
        """
        arg_tail = []
        while len(arg_list) > 0:
            group = arg_list.pop(0)
            if group not in term_list:
                arg_tail.append(group)
            else:
                arg_list += arg_tail
                return group
        return None

    """Main Code"""
    exe = basename(sys.argv[0])
    parser = init_parser(exe)
    args, argv = parser.parse_known_args()

    #print version
    if args.version:
        import kamaki
        print("kamaki %s" % kamaki.__version__)
        exit(0)

    config = Config(args.config) if args.config else Config()

    #load config options from command line
    for option in args.options:
        keypath, sep, val = option.partition('=')
        if not sep:
            print("Invalid option '%s'" % option)
            exit(1)
        section, sep, key = keypath.partition('.')
        if not sep:
            print("Invalid option '%s'" % option)
            exit(1)
        config.override(section.strip(), key.strip(), val.strip())

    load_groups(config)
    group = find_term_in_args(argv, _commands)
    if not group:
        parser.print_help()
        print_groups()
        exit(0)

    parser.prog = '%s %s <command>' % (exe, group)
    command = find_term_in_args(argv, _commands[group])

    if not command:
        parser.print_help()
        print_commands(group)
        exit(0)

    cmd = _commands[group][command]()

    parser.prog = '%s %s %s' % (exe, group, command)
    if cmd.syntax:
        parser.prog += '  %s' % cmd.syntax
    parser.description = cmd.description
    parser.epilog = ''
    if hasattr(cmd, 'update_parser'):
        cmd.update_parser(parser)

    #check other args
    args, argv = parser.parse_known_args()
    if group != argv[0]:
        errmsg = red('Invalid command group '+argv[0])
        print(errmsg, file=stderr)
        exit(1)
    if command != argv[1]:
        errmsg = red('Invalid command "%s" in group "%s"'%(argv[1], argv[0]))
        print(errmsg, file=stderr)
        exit(1)

    if args.help:
        parser.print_help()
        exit(0)

    manage_logging_handlers(args)
    cmd.args = args
    cmd.config = config
    try:
        ret = cmd.main(*argv[2:])
        exit(ret)
    except TypeError as e:
        if e.args and e.args[0].startswith('main()'):
            parser.print_help()
            exit(1)
        else:
            raise
    except CLIError as err:
        errmsg = 'CLI Error '
        errmsg += '(%s): '%err.status if err.status else ': '
297
        errmsg += unicode(err.message) if err.message else ''
298
299
300
301
302
303
304
305
306
307
308
        if err.importance == 1:
            errmsg = yellow(errmsg)
        elif err.importance == 2:
            errmsg = magenta(errmsg)
        elif err.importance > 2:
            errmsg = red(errmsg)
        print(errmsg, file=stderr)
        exit(1)

if __name__ == '__main__':
    main()