shell.py 12.8 KB
Newer Older
1
# Copyright 2012-2014 GRNET S.A. All rights reserved.
2
3
4
5
6
7
#
# 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
8
9
#      copyright notice, this list of conditions and the following
#      disclaimer.
10
11
#
#   2. Redistributions in binary form must reproduce the above
12
13
14
#      copyright notice, this list of conditions and the following
#      disclaimer in the documentation and/or other materials
#      provided with the distribution.
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#
# 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 cmd import Cmd
from os import popen
36
from sys import stdout
37

38
from kamaki.cli import exec_cmd, print_error_message, print_subcommands_help
39
from kamaki.cli.argument import ArgumentParseManager
40
from kamaki.cli.utils import print_dict, split_input, pref_enc
41
from kamaki.cli.history import History
Stavros Sachtouris's avatar
Stavros Sachtouris committed
42
from kamaki.cli.errors import CLIError
43
from kamaki.clients import ClientError
44
45
46
from kamaki.cli.logger import add_file_logger

log = add_file_logger(__name__)
47

48

49
def init_shell(exe_string, parser, username='', userid=''):
50
    parser.arguments.pop('version', None)
51
52
53
    shell = Shell()
    shell.set_prompt(exe_string)
    from kamaki import __version__ as version
54
    shell.greet(version, username, userid)
55
    shell.do_EOF = shell.do_exit
56
    from kamaki.cli.cmdtree import CommandTree
57
58
59
    shell.cmd_tree = CommandTree(
        'kamaki', 'A command line tool for poking clouds')
    return shell
60

61
62

class Shell(Cmd):
63
64
    """Kamaki interactive shell"""
    _prefix = '['
65
    _suffix = ']: '
66
67
    cmd_tree = None
    _history = None
68
69
    _context_stack = []
    _prompt_stack = []
70
    _parser = None
71
    astakos = None
72
    cloud = None
73

74
75
    undoc_header = 'interactive shell commands:'

76
77
78
    def emptyline(self):
        self.lastcmd = ''

79
80
81
82
    def postcmd(self, post, line):
        if self._context_stack:
            self._roll_command()
            self._restore(self._context_stack.pop())
83
84
            self.set_prompt(
                self._prompt_stack.pop()[len(self._prefix):-len(self._suffix)])
85
86
87

        return Cmd.postcmd(self, post, line)

88
    def precmd(self, line):
89
        if line.startswith('/'):
90
91
            start, end = len(self._prefix), -len(self._suffix)
            cur_cmd_path = self.prompt.replace(' ', '_')[start:end]
92
            if cur_cmd_path != self.cmd_tree.name:
93
94
95
96
                cur_cmd = self.cmd_tree.get_command(cur_cmd_path)
                self._context_stack.append(self._backup())
                self._prompt_stack.append(self.prompt)
                new_context = self
97
                self._roll_command(cur_cmd.path)
98
99
100
101
                new_context.set_prompt(self.cmd_tree.name)
                for grp_cmd in self.cmd_tree.get_subcommands():
                    self._register_command(grp_cmd.path)
            return line[1:]
102
103
        return line

104
    def greet(self, version, username='', userid=''):
105
        print('kamaki v%s - Interactive Shell\n' % version)
106
        print('\t/exit     \tterminate kamaki')
107
108
109
110
111
        print('\texit or ^D\texit context')
        print('\t? or help \tavailable commands')
        print('\t?command  \thelp on command')
        print('\t!<command>\texecute OS shell command')
        print('')
112
113
        if username or userid:
            print('Session user is %s (uuid: %s)' % (username, userid))
114
115

    def set_prompt(self, new_prompt):
116
        self.prompt = '%s%s%s' % (self._prefix, new_prompt, self._suffix)
117

118
119
120
121
122
123
124
125
126
    def cmdloop(self):
        while True:
            try:
                Cmd.cmdloop(self)
            except KeyboardInterrupt:
                print(' - interrupted')
                continue
            break

127
128
    def do_exit(self, line):
        print('')
129
130
        start, end = len(self._prefix), -len(self._suffix)
        if self.prompt[start:end] == self.cmd_tree.name:
131
            exit(0)
132
133
134
135
136
137
138
139
140
        return True

    def do_shell(self, line):
        output = popen(line).read()
        print(output)

    @property
    def path(self):
        if self._cmd:
141
            return self._cmd.path
142
143
144
145
146
147
148
149
150
151
152
153
154
        return ''

    @classmethod
    def _register_method(self, method, name):
        self.__dict__[name] = method

    @classmethod
    def _unregister_method(self, name):
        try:
            self.__dict__.pop(name)
        except KeyError:
            pass

155
    def _roll_command(self, cmd_path=None):
Stavros Sachtouris's avatar
Stavros Sachtouris committed
156
        for subname in self.cmd_tree.subnames(cmd_path):
157
158
159
160
161
162
163
164
165
166
167
168
            self._unregister_method('do_%s' % subname)
            self._unregister_method('complete_%s' % subname)
            self._unregister_method('help_%s' % subname)

    @classmethod
    def _backup(self):
        return dict(self.__dict__)

    @classmethod
    def _restore(self, oldcontext):
        self.__dict__ = oldcontext

169
    @staticmethod
170
    def _create_help_method(cmd_name, args, required, descr, syntax):
171
        tmp_args = dict(args)
172
        #tmp_args.pop('options', None)
173
        tmp_args.pop('cloud', None)
174
175
176
        tmp_args.pop('debug', None)
        tmp_args.pop('verbose', None)
        tmp_args.pop('config', None)
177
178
        tmp_args.pop('ignore_ssl', None)
        tmp_args.pop('ca_file', None)
179
        help_parser = ArgumentParseManager(
180
181
            cmd_name, tmp_args, required,
            syntax=syntax, description=descr, check_required=False)
182
        return help_parser.print_help
183

Stavros Sachtouris's avatar
Stavros Sachtouris committed
184
    def _register_command(self, cmd_path):
185
        cmd = self.cmd_tree.get_command(cmd_path)
186
        arguments = self._parser.arguments
187

188
        def do_method(new_context, line):
189
190
191
192
193
            """ Template for all cmd.Cmd methods of the form do_<cmd name>
                Parse cmd + args and decide to execute or change context
                <cmd> <term> <term> <args> is always parsed to most specific
                even if cmd_term_term is not a terminal path
            """
194
            line = line.decode(pref_enc)
195
            subcmd, cmd_args = cmd.parse_out(split_input(line))
196
            self._history.add(' '.join([cmd.path.replace('_', ' '), line]))
197
198
            cmd_parser = ArgumentParseManager(
                cmd.name, dict(self._parser.arguments))
199
            cmd_parser.parser.description = subcmd.help
200
201
202

            # exec command or change context
            if subcmd.is_command:  # exec command
Stavros Sachtouris's avatar
Stavros Sachtouris committed
203
                try:
204
                    cls = subcmd.cmd_class
205
                    cmd_parser.required = getattr(cls, 'required', None)
206
207
                    ldescr = getattr(cls, 'long_description', '')
                    if subcmd.path == 'history_run':
208
                        instance = cls(
209
                            dict(cmd_parser.arguments), self.astakos,
210
                            cmd_tree=self.cmd_tree)
211
                    else:
212
                        instance = cls(
213
                            dict(cmd_parser.arguments),
214
                            self.astakos, self.cloud)
215
216
                    cmd_parser.update_arguments(instance.arguments)
                    cmd_parser.arguments = instance.arguments
217
218
                    subpath = subcmd.path.split('_')[
                        (len(cmd.path.split('_')) - 1):]
219
                    cmd_parser.syntax = '%s %s' % (
220
                        ' '.join(subpath), instance.syntax)
221
                    help_method = self._create_help_method(
222
223
                        cmd.name, cmd_parser.arguments,
                        cmd_parser.required, subcmd.help, cmd_parser.syntax)
224
                    if '-h' in cmd_args or '--help' in cmd_args:
225
                        help_method()
226
227
228
229
230
231
232
                        if ldescr.strip():
                            print('\nDetails:')
                            print('%s' % ldescr)
                        return
                    cmd_parser.parse(cmd_args)

                    for name, arg in instance.arguments.items():
233
                        arg.value = getattr(
234
                            cmd_parser.parsed, name, arg.default)
235

236
                    exec_cmd(instance, cmd_parser.unparsed, help_method)
237
238
                        #[term for term in cmd_parser.unparsed\
                        #    if not term.startswith('-')],
239
                except (ClientError, CLIError) as err:
240
                    print_error_message(err)
241
242
            elif ('-h' in cmd_args or '--help' in cmd_args) or len(cmd_args):
                # print options
243
                print('%s' % cmd.help)
244
                print_subcommands_help(cmd)
245
            else:  # change context
246
                #new_context = this
247
248
249
250
                backup_context = self._backup()
                old_prompt = self.prompt
                new_context._roll_command(cmd.parent_path)
                new_context.set_prompt(subcmd.path.replace('_', ' '))
251
                newcmds = [subcmd for subcmd in subcmd.subcommands.values()]
252
                for subcmd in newcmds:
Stavros Sachtouris's avatar
Stavros Sachtouris committed
253
                    new_context._register_command(subcmd.path)
254
255
256
257
258
259
260
261
                new_context.cmdloop()
                self.prompt = old_prompt
                #when new context is over, roll back to the old one
                self._restore(backup_context)
        self._register_method(do_method, 'do_%s' % cmd.name)

        def help_method(self):
            print('%s (%s -h for more options)' % (cmd.help, cmd.name))
262
            if cmd.is_command:
263
                cls = cmd.cmd_class
264
                ldescr = getattr(cls, 'long_description', '')
265
266
267
268
269
                #_construct_command_syntax(cls)
                plist = self.prompt[len(self._prefix):-len(self._suffix)]
                plist = plist.split(' ')
                clist = cmd.path.split('_')
                upto = 0
270
271
                if ldescr:
                    print('%s' % ldescr)
272
273
274
275
276
277
278
                for i, term in enumerate(plist):
                    try:
                        if clist[i] == term:
                            upto += 1
                    except IndexError:
                        break
                print('Syntax: %s %s' % (' '.join(clist[upto:]), cls.syntax))
279
            if cmd.subcommands:
280
                print_subcommands_help(cmd)
281

282
283
284
        self._register_method(help_method, 'help_%s' % cmd.name)

        def complete_method(self, text, line, begidx, endidx):
285
            subcmd, cmd_args = cmd.parse_out(split_input(line)[1:])
286
            if subcmd.is_command:
287
                cls = subcmd.cmd_class
288
                instance = cls(dict(arguments))
289
290
                empty, sep, subname = subcmd.path.partition(cmd.path)
                cmd_name = '%s %s' % (cmd.name, subname.replace('_', ' '))
291
                print('\n%s\nSyntax:\t%s %s' % (
292
                    cls.help, cmd_name, cls.syntax))
293
294
295
                cmd_args = {}
                for arg in instance.arguments.values():
                    cmd_args[','.join(arg.parsed_name)] = arg.help
Stavros Sachtouris's avatar
Stavros Sachtouris committed
296
                print_dict(cmd_args, indent=2)
297
                stdout.write('%s %s' % (self.prompt, line))
Stavros Sachtouris's avatar
Stavros Sachtouris committed
298
            return subcmd.subnames()
299
300
301
302
303
304
305
306
307
        self._register_method(complete_method, 'complete_%s' % cmd.name)

    @property
    def doc_header(self):
        tmp_partition = self.prompt.partition(self._prefix)
        tmp_partition = tmp_partition[2].partition(self._suffix)
        hdr = tmp_partition[0].strip()
        return '%s commands:' % hdr

308
309
    def run(self, astakos, cloud, parser, path=''):
        self.astakos = astakos
310
        self.cloud = cloud
311
        self._parser = parser
312
313
314
        cnf = parser.arguments['config']
        self._history = History(cnf.get('global', 'history_file'))
        self._history.limit = cnf.get('global', 'history_limit')
Stavros Sachtouris's avatar
Stavros Sachtouris committed
315
        if path:
316
317
318
319
320
            cmd = self.cmd_tree.get_command(path)
            intro = cmd.path.replace('_', ' ')
        else:
            intro = self.cmd_tree.name

321
        acceptable = parser.arguments['config'].groups
Stavros Sachtouris's avatar
Stavros Sachtouris committed
322
        total = self.cmd_tree.groups.keys()
323
324
        self.cmd_tree.exclude(set(total).difference(acceptable))

325
        for subcmd in self.cmd_tree.get_subcommands(path):
Stavros Sachtouris's avatar
Stavros Sachtouris committed
326
            self._register_command(subcmd.path)
327
328

        self.set_prompt(intro)
Stavros Sachtouris's avatar
Stavros Sachtouris committed
329

330
331
        try:
            self.cmdloop()
332
333
        except Exception as e:
            print('(%s)' % e)
334
335
            from traceback import print_stack
            print_stack()