command_shell.py 10.6 KB
Newer Older
1
2
3
4
5
6
7
# Copyright 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
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
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
47
def _init_shell(exe_string, parser):
    parser.arguments.pop('version', None)
48
49
50
51
52
53
54
55
56
    shell = Shell()
    shell.set_prompt(exe_string)
    from kamaki import __version__ as version
    shell.greet(version)
    shell.do_EOF = shell.do_exit
    from kamaki.cli.command_tree import CommandTree
    shell.cmd_tree = CommandTree(
        'kamaki', 'A command line tool for poking clouds')
    return shell
57

58
59

class Shell(Cmd):
60
61
    """Kamaki interactive shell"""
    _prefix = '['
62
    _suffix = ']: '
63
64
    cmd_tree = None
    _history = None
65
66
    _context_stack = []
    _prompt_stack = []
67
    _parser = None
68

69
70
    undoc_header = 'interactive shell commands:'

71
72
73
74
    def postcmd(self, post, line):
        if self._context_stack:
            self._roll_command()
            self._restore(self._context_stack.pop())
75
76
            self.set_prompt(
                self._prompt_stack.pop()[len(self._prefix):-len(self._suffix)])
77
78
79

        return Cmd.postcmd(self, post, line)

80
    def precmd(self, line):
81
        if line.startswith('/'):
82
83
            cur_cmd_path = self.prompt.replace(' ',
                '_')[len(self._prefix):-len(self._suffix)]
84
            if cur_cmd_path != self.cmd_tree.name:
85
86
87
88
                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
89
                self._roll_command(cur_cmd.path)
90
91
92
93
                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:]
94
95
        return line

96
97
98
99
100
    def greet(self, version):
        print('kamaki v%s - Interactive Shell\n\t(exit or ^D to exit)\n'\
            % version)

    def set_prompt(self, new_prompt):
101
        self.prompt = '%s%s%s' % (self._prefix, new_prompt, self._suffix)
102
103
104

    def do_exit(self, line):
        print('')
105
106
        if self.prompt[len(self._prefix):-len(self._suffix)]\
        == self.cmd_tree.name:
107
            exit(0)
108
109
110
111
112
113
114
115
116
        return True

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

    @property
    def path(self):
        if self._cmd:
117
            return self._cmd.path
118
119
120
121
122
123
124
125
126
127
128
129
130
        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

131
    def _roll_command(self, cmd_path=None):
132
133
134
135
136
137
138
139
140
141
142
143
144
        for subname in self.cmd_tree.get_subnames(cmd_path):
            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

Stavros Sachtouris's avatar
Stavros Sachtouris committed
145
    def _register_command(self, cmd_path):
146
        cmd = self.cmd_tree.get_command(cmd_path)
147
        arguments = self._parser.arguments
148

149
        def do_method(new_context, line):
150
151
152
153
154
            """ 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
            """
155
            subcmd, cmd_args = cmd.parse_out(split_input(line))
156
157
158
159
            self._history.add(' '.join([cmd.path.replace('_', ' '), line]))
            cmd_parser = ArgumentParseManager(
                cmd.name,
                dict(self._parser.arguments))
160
161
162
163
164
            cmd_parser.arguments.pop('options', None)
            cmd_parser.arguments.pop('debug', None)
            cmd_parser.arguments.pop('verbose', None)
            cmd_parser.arguments.pop('include', None)
            cmd_parser.arguments.pop('silent', None)
165
166

            cmd_parser.parser.description = subcmd.help
167
168
169
170

            # exec command or change context
            if subcmd.is_command:  # exec command
                cls = subcmd.get_class()
Stavros Sachtouris's avatar
Stavros Sachtouris committed
171
                if subcmd.path == 'history_run':
172
173
174
                    instance = cls(dict(cmd_parser.arguments), self.cmd_tree)
                else:
                    instance = cls(dict(cmd_parser.arguments))
175
                cmd_parser.update_arguments(instance.arguments)
176
                instance.arguments.pop('config')
177
178
179
                #cmd_parser = ArgumentParseManager(subcmd.path,
                #    instance.arguments)
                cmd_parser.arguments = instance.arguments
180
181
                cmd_parser.syntax = '%s %s' % (
                    subcmd.path.replace('_', ' '), cls.syntax)
182
                if '-h' in cmd_args or '--help' in cmd_args:
183
                    cmd_parser.parser.print_help()
184
                    print('\n%s' % subcmd.help)
185
                    return
Stavros Sachtouris's avatar
Stavros Sachtouris committed
186
                cmd_parser.parse(cmd_args)
187
188

                for name, arg in instance.arguments.items():
189
                    arg.value = getattr(cmd_parser.parsed, name, arg.default)
190

Stavros Sachtouris's avatar
Stavros Sachtouris committed
191
                try:
192
                    exec_cmd(instance,
193
194
                        cmd_parser.unparsed,
                        cmd_parser.parser.print_help)
195
                except (ClientError, CLIError) as err:
196
                    print_error_message(err)
197
198
            elif ('-h' in cmd_args or '--help' in cmd_args) \
            or len(cmd_args):  # print options
199
                print('%s' % cmd.help)
200
                print_subcommands_help(cmd)
201
            else:  # change context
202
                #new_context = this
203
204
205
206
207
208
                backup_context = self._backup()
                old_prompt = self.prompt
                new_context._roll_command(cmd.parent_path)
                new_context.set_prompt(subcmd.path.replace('_', ' '))
                newcmds = [subcmd for subcmd in subcmd.get_subcommands()]
                for subcmd in newcmds:
Stavros Sachtouris's avatar
Stavros Sachtouris committed
209
                    new_context._register_command(subcmd.path)
210
211
212
213
214
215
216
217
                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))
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
            if cmd.is_command:
                cls = cmd.get_class()
                #_construct_command_syntax(cls)
                plist = self.prompt[len(self._prefix):-len(self._suffix)]
                plist = plist.split(' ')
                clist = cmd.path.split('_')
                upto = 0
                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))
            else:
233
                print_subcommands_help(cmd)
234

235
236
237
        self._register_method(help_method, 'help_%s' % cmd.name)

        def complete_method(self, text, line, begidx, endidx):
238
            subcmd, cmd_args = cmd.parse_out(split_input(line)[1:])
239
240
            if subcmd.is_command:
                cls = subcmd.get_class()
241
                instance = cls(dict(arguments))
242
243
244
245
246
247
248
                empty, sep, subname = subcmd.path.partition(cmd.path)
                cmd_name = '%s %s' % (cmd.name, subname.replace('_', ' '))
                print('\n%s\nSyntax:\t%s %s'\
                    % (cls.description, cmd_name, cls.syntax))
                cmd_args = {}
                for arg in instance.arguments.values():
                    cmd_args[','.join(arg.parsed_name)] = arg.help
Stavros Sachtouris's avatar
Stavros Sachtouris committed
249
                print_dict(cmd_args, ident=2)
250
251
252
253
254
255
256
257
258
259
260
                stdout.write('%s %s' % (self.prompt, line))
            return subcmd.get_subnames()
        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

261
262
263
264
    def run(self, parser, path=''):
        self._parser = parser
        self._history = History(
            parser.arguments['config'].get('history', 'file'))
Stavros Sachtouris's avatar
Stavros Sachtouris committed
265
        if path:
266
267
268
269
270
271
            cmd = self.cmd_tree.get_command(path)
            intro = cmd.path.replace('_', ' ')
        else:
            intro = self.cmd_tree.name

        for subcmd in self.cmd_tree.get_subcommands(path):
Stavros Sachtouris's avatar
Stavros Sachtouris committed
272
            self._register_command(subcmd.path)
273
274

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

276
277
278
279
280
        try:
            self.cmdloop()
        except Exception:
            from traceback import print_stack
            print_stack()