Catch and handle KeyboardInterrupt in shell
[kamaki] / kamaki / cli / command_shell.py
1 # Copyright 2012 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.
33
34 from cmd import Cmd
35 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
42 from kamaki.cli.errors import CLIError
43 from kamaki.clients import ClientError
44
45
46 def _init_shell(exe_string, parser):
47     parser.arguments.pop('version', None)
48     shell = Shell()
49     shell.set_prompt(exe_string)
50     from kamaki import __version__ as version
51     shell.greet(version)
52     shell.do_EOF = shell.do_exit
53     from kamaki.cli.command_tree import CommandTree
54     shell.cmd_tree = CommandTree(
55         'kamaki', 'A command line tool for poking clouds')
56     return shell
57
58
59 class Shell(Cmd):
60     """Kamaki interactive shell"""
61     _prefix = '['
62     _suffix = ']: '
63     cmd_tree = None
64     _history = None
65     _context_stack = []
66     _prompt_stack = []
67     _parser = None
68
69     undoc_header = 'interactive shell commands:'
70
71     def postcmd(self, post, line):
72         if self._context_stack:
73             self._roll_command()
74             self._restore(self._context_stack.pop())
75             self.set_prompt(
76                 self._prompt_stack.pop()[len(self._prefix):-len(self._suffix)])
77
78         return Cmd.postcmd(self, post, line)
79
80     def precmd(self, line):
81         if line.startswith('/'):
82             cur_cmd_path = self.prompt.replace(' ',
83                 '_')[len(self._prefix):-len(self._suffix)]
84             if cur_cmd_path != self.cmd_tree.name:
85                 cur_cmd = self.cmd_tree.get_command(cur_cmd_path)
86                 self._context_stack.append(self._backup())
87                 self._prompt_stack.append(self.prompt)
88                 new_context = self
89                 self._roll_command(cur_cmd.path)
90                 new_context.set_prompt(self.cmd_tree.name)
91                 for grp_cmd in self.cmd_tree.get_subcommands():
92                     self._register_command(grp_cmd.path)
93             return line[1:]
94         return line
95
96     def greet(self, version):
97         print('kamaki v%s - Interactive Shell\n\t(exit or ^D to exit)\n'\
98             % version)
99
100     def set_prompt(self, new_prompt):
101         self.prompt = '%s%s%s' % (self._prefix, new_prompt, self._suffix)
102
103     def cmdloop(self):
104         while True:
105             try:
106                 Cmd.cmdloop(self)
107             except KeyboardInterrupt:
108                 print(' - interrupted')
109                 continue
110             break
111
112     def do_exit(self, line):
113         print('')
114         if self.prompt[len(self._prefix):-len(self._suffix)]\
115         == self.cmd_tree.name:
116             exit(0)
117         return True
118
119     def do_shell(self, line):
120         output = popen(line).read()
121         print(output)
122
123     @property
124     def path(self):
125         if self._cmd:
126             return self._cmd.path
127         return ''
128
129     @classmethod
130     def _register_method(self, method, name):
131         self.__dict__[name] = method
132
133     @classmethod
134     def _unregister_method(self, name):
135         try:
136             self.__dict__.pop(name)
137         except KeyError:
138             pass
139
140     def _roll_command(self, cmd_path=None):
141         for subname in self.cmd_tree.get_subnames(cmd_path):
142             self._unregister_method('do_%s' % subname)
143             self._unregister_method('complete_%s' % subname)
144             self._unregister_method('help_%s' % subname)
145
146     @classmethod
147     def _backup(self):
148         return dict(self.__dict__)
149
150     @classmethod
151     def _restore(self, oldcontext):
152         self.__dict__ = oldcontext
153
154     def _register_command(self, cmd_path):
155         cmd = self.cmd_tree.get_command(cmd_path)
156         arguments = self._parser.arguments
157
158         def do_method(new_context, line):
159             """ Template for all cmd.Cmd methods of the form do_<cmd name>
160                 Parse cmd + args and decide to execute or change context
161                 <cmd> <term> <term> <args> is always parsed to most specific
162                 even if cmd_term_term is not a terminal path
163             """
164             subcmd, cmd_args = cmd.parse_out(split_input(line))
165             self._history.add(' '.join([cmd.path.replace('_', ' '), line]))
166             tmp_args = dict(self._parser.arguments)
167             tmp_args.pop('options', None)
168             tmp_args.pop('debug', None)
169             tmp_args.pop('verbose', None)
170             tmp_args.pop('include', None)
171             tmp_args.pop('silent', None)
172             cmd_parser = ArgumentParseManager(cmd.name, dict(tmp_args))
173
174             cmd_parser.parser.description = subcmd.help
175
176             # exec command or change context
177             if subcmd.is_command:  # exec command
178                 try:
179                     cls = subcmd.get_class()
180                     ldescr = getattr(cls, 'long_description', '')
181                     if subcmd.path == 'history_run':
182                         instance = cls(dict(cmd_parser.arguments),
183                             self.cmd_tree)
184                     else:
185                         instance = cls(dict(cmd_parser.arguments))
186                     cmd_parser.update_arguments(instance.arguments)
187                     instance.arguments.pop('config')
188                     cmd_parser.arguments = instance.arguments
189                     cmd_parser.syntax = '%s %s' % (
190                         subcmd.path.replace('_', ' '), cls.syntax)
191                     if '-h' in cmd_args or '--help' in cmd_args:
192                         cmd_parser.parser.print_help()
193                         if ldescr.strip():
194                             print('\nDetails:')
195                             print('%s' % ldescr)
196                         return
197                     cmd_parser.parse(cmd_args)
198
199                     for name, arg in instance.arguments.items():
200                         arg.value = getattr(cmd_parser.parsed, name,
201                             arg.default)
202
203                     exec_cmd(instance,
204                         [term for term in cmd_parser.unparsed\
205                             if not term.startswith('-')],
206                         cmd_parser.parser.print_help)
207                 except (ClientError, CLIError) as err:
208                     print_error_message(err)
209             elif ('-h' in cmd_args or '--help' in cmd_args) \
210             or len(cmd_args):  # print options
211                 print('%s' % cmd.help)
212                 print_subcommands_help(cmd)
213             else:  # change context
214                 #new_context = this
215                 backup_context = self._backup()
216                 old_prompt = self.prompt
217                 new_context._roll_command(cmd.parent_path)
218                 new_context.set_prompt(subcmd.path.replace('_', ' '))
219                 newcmds = [subcmd for subcmd in subcmd.get_subcommands()]
220                 for subcmd in newcmds:
221                     new_context._register_command(subcmd.path)
222                 new_context.cmdloop()
223                 self.prompt = old_prompt
224                 #when new context is over, roll back to the old one
225                 self._restore(backup_context)
226         self._register_method(do_method, 'do_%s' % cmd.name)
227
228         def help_method(self):
229             print('%s (%s -h for more options)' % (cmd.help, cmd.name))
230             if cmd.is_command:
231                 cls = cmd.get_class()
232                 ldescr = getattr(cls, 'long_description', '')
233                 #_construct_command_syntax(cls)
234                 plist = self.prompt[len(self._prefix):-len(self._suffix)]
235                 plist = plist.split(' ')
236                 clist = cmd.path.split('_')
237                 upto = 0
238                 if ldescr:
239                     print('%s' % ldescr)
240                 for i, term in enumerate(plist):
241                     try:
242                         if clist[i] == term:
243                             upto += 1
244                     except IndexError:
245                         break
246                 print('Syntax: %s %s' % (' '.join(clist[upto:]), cls.syntax))
247             else:
248                 print_subcommands_help(cmd)
249
250         self._register_method(help_method, 'help_%s' % cmd.name)
251
252         def complete_method(self, text, line, begidx, endidx):
253             subcmd, cmd_args = cmd.parse_out(split_input(line)[1:])
254             if subcmd.is_command:
255                 cls = subcmd.get_class()
256                 instance = cls(dict(arguments))
257                 empty, sep, subname = subcmd.path.partition(cmd.path)
258                 cmd_name = '%s %s' % (cmd.name, subname.replace('_', ' '))
259                 print('\n%s\nSyntax:\t%s %s'\
260                     % (cls.description, cmd_name, cls.syntax))
261                 cmd_args = {}
262                 for arg in instance.arguments.values():
263                     cmd_args[','.join(arg.parsed_name)] = arg.help
264                 print_dict(cmd_args, ident=2)
265                 stdout.write('%s %s' % (self.prompt, line))
266             return subcmd.get_subnames()
267         self._register_method(complete_method, 'complete_%s' % cmd.name)
268
269     @property
270     def doc_header(self):
271         tmp_partition = self.prompt.partition(self._prefix)
272         tmp_partition = tmp_partition[2].partition(self._suffix)
273         hdr = tmp_partition[0].strip()
274         return '%s commands:' % hdr
275
276     def run(self, parser, path=''):
277         self._parser = parser
278         self._history = History(
279             parser.arguments['config'].get('history', 'file'))
280         if path:
281             cmd = self.cmd_tree.get_command(path)
282             intro = cmd.path.replace('_', ' ')
283         else:
284             intro = self.cmd_tree.name
285
286         for subcmd in self.cmd_tree.get_subcommands(path):
287             self._register_command(subcmd.path)
288
289         self.set_prompt(intro)
290
291         try:
292             self.cmdloop()
293         except Exception as e:
294             print('(%s)' % e)
295             from traceback import print_stack
296             print_stack()