Revert "Use bash --noediting by default to avoid readline problems. This means lines"
[polysh.git] / gsh / remote_dispatcher.py
blob8e55432d80e9f6d12ef16a69714df15b84ebcc82
1 # This program is free software; you can redistribute it and/or modify
2 # it under the terms of the GNU General Public License as published by
3 # the Free Software Foundation; either version 2 of the License, or
4 # (at your option) any later version.
6 # This program is distributed in the hope that it will be useful,
7 # but WITHOUT ANY WARRANTY; without even the implied warranty of
8 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
9 # GNU Library General Public License for more details.
11 # You should have received a copy of the GNU General Public License
12 # along with this program; if not, write to the Free Software
13 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
15 # See the COPYING file for license information.
17 # Copyright (c) 2006, 2007, 2008 Guillaume Chazarain <guichaz@gmail.com>
19 import asyncore
20 import os
21 import pty
22 import signal
23 import sys
24 import termios
26 from gsh.buffered_dispatcher import buffered_dispatcher
27 from gsh import callbacks
28 from gsh.console import console_output
29 from gsh import display_names
31 # Either the remote shell is expecting a command or one is already running
32 STATE_NAMES = ['not_started', 'idle', 'running', 'terminated', 'dead']
34 STATE_NOT_STARTED, \
35 STATE_IDLE, \
36 STATE_RUNNING, \
37 STATE_TERMINATED, \
38 STATE_DEAD = range(len(STATE_NAMES))
40 # Count the total number of remote_dispatcher.handle_read() invocations
41 nr_handle_read = 0
43 def main_loop_iteration(timeout=None):
44 """Return the number of remote_dispatcher.handle_read() calls made by this
45 iteration"""
46 prev_nr_read = nr_handle_read
47 asyncore.loop(count=1, timeout=timeout, use_poll=True)
48 return nr_handle_read - prev_nr_read
50 def log(msg):
51 if options.log_file:
52 fd = options.log_file.fileno()
53 while msg:
54 try:
55 written = os.write(fd, msg)
56 except OSError, e:
57 print 'Exception while writing log:', options.log_file.name
58 print e
59 raise asyncore.ExitNow(1)
60 msg = msg[written:]
62 class remote_dispatcher(buffered_dispatcher):
63 """A remote_dispatcher is a ssh process we communicate with"""
65 def __init__(self, hostname):
66 self.pid, fd = pty.fork()
67 if self.pid == 0:
68 # Child
69 self.launch_ssh(hostname)
70 sys.exit(1)
72 # Parent
73 buffered_dispatcher.__init__(self, fd)
74 self.hostname = hostname
75 self.debug = options.debug
76 self.enabled = True # shells can be enabled and disabled
77 self.state = STATE_NOT_STARTED
78 self.term_size = (-1, -1)
79 self.display_name = None
80 self.change_name(hostname)
81 self.init_string = self.configure_tty() + self.set_prompt()
82 self.init_string_sent = False
83 self.read_in_state_not_started = ''
84 self.command = options.command
85 self.last_printed_line = ''
87 def launch_ssh(self, name):
88 """Launch the ssh command in the child process"""
89 evaluated = options.ssh % {'host': name}
90 if evaluated == options.ssh:
91 evaluated = '%s %s' % (evaluated, name)
92 os.execlp('/bin/sh', 'sh', '-c', evaluated)
94 def set_enabled(self, enabled):
95 if enabled != self.enabled and options.interactive:
96 # In non-interactive mode, remote processes leave as soon
97 # as they are terminated, but we don't want to break the
98 # indentation if all the remaining processes have short names.
99 display_names.set_enabled(self.display_name, enabled)
100 self.enabled = enabled
102 def change_state(self, state):
103 """Change the state of the remote process, logging the change"""
104 if state is not self.state:
105 if self.debug:
106 self.print_debug('state => %s' % (STATE_NAMES[state]))
107 if self.state is STATE_NOT_STARTED:
108 self.read_in_state_not_started = ''
109 self.state = state
111 def disconnect(self):
112 """We are no more interested in this remote process"""
113 try:
114 os.kill(-self.pid, signal.SIGKILL)
115 except OSError:
116 # The process was already dead, no problem
117 pass
118 self.read_buffer = ''
119 self.write_buffer = ''
120 self.set_enabled(False)
121 if self.read_in_state_not_started:
122 self.print_lines(self.read_in_state_not_started)
123 self.read_in_state_not_started = ''
124 if options.abort_error and self.state is STATE_NOT_STARTED:
125 raise asyncore.ExitNow(1)
126 self.change_state(STATE_DEAD)
128 def configure_tty(self):
129 """We don't want \n to be replaced with \r\n, and we disable the echo"""
130 attr = termios.tcgetattr(self.fd)
131 attr[1] &= ~termios.ONLCR # oflag
132 attr[3] &= ~termios.ECHO # lflag
133 termios.tcsetattr(self.fd, termios.TCSANOW, attr)
134 # unsetopt zle prevents Zsh from resetting the tty
135 return 'unsetopt zle 2> /dev/null;stty -echo -onlcr;'
137 def seen_prompt_cb(self, unused):
138 if options.interactive:
139 self.change_state(STATE_IDLE)
140 elif self.command:
141 p1, p2 = callbacks.add('real prompt ends', lambda d: None, True)
142 self.dispatch_command('PS1="%s""%s\n"\n' % (p1, p2))
143 self.dispatch_command(self.command + '\n')
144 self.dispatch_command('exit 2>/dev/null\n')
145 self.command = None
147 def set_prompt(self):
148 """The prompt is important because we detect the readyness of a process
149 by waiting for its prompt."""
150 # No right prompt
151 command_line = 'RPS1=;RPROMPT=;'
152 command_line += 'PROMPT_COMMAND=;'
153 command_line += 'TERM=ansi;'
154 command_line += 'unset HISTFILE;'
155 prompt1, prompt2 = callbacks.add('prompt', self.seen_prompt_cb, True)
156 command_line += 'PS1="%s""%s\n"\n' % (prompt1, prompt2)
157 return command_line
159 def readable(self):
160 """We are always interested in reading from active remote processes if
161 the buffer is OK"""
162 return self.state != STATE_DEAD and buffered_dispatcher.readable(self)
164 def handle_expt(self):
165 pid, status = os.waitpid(self.pid, 0)
166 exit_code = os.WEXITSTATUS(status)
167 options.exit_code = max(options.exit_code, exit_code)
168 if exit_code and options.interactive:
169 console_output('Error talking to %s\n' % self.display_name)
170 self.disconnect()
172 def handle_close(self):
173 self.handle_expt()
175 def print_lines(self, lines):
176 from gsh.display_names import max_display_name_length
177 lines = lines.strip('\n')
178 while True:
179 no_empty_lines = lines.replace('\n\n', '\n')
180 if len(no_empty_lines) == len(lines):
181 break
182 lines = no_empty_lines
183 if not lines:
184 return
185 indent = max_display_name_length - len(self.display_name)
186 prefix = self.display_name + indent * ' ' + ' : '
187 console_output(prefix + lines.replace('\n', '\n' + prefix) + '\n')
188 self.last_printed_line = lines[lines.rfind('\n') + 1:]
190 def handle_read_fast_case(self, data):
191 """If we are in a fast case we'll avoid the long processing of each
192 line"""
193 if self.state is not STATE_RUNNING or callbacks.any_in(data):
194 # Slow case :-(
195 return False
197 last_nl = data.rfind('\n')
198 if last_nl == -1:
199 # No '\n' in data => slow case
200 return False
201 self.read_buffer = data[last_nl + 1:]
202 self.print_lines(data[:last_nl])
203 return True
205 def handle_read(self):
206 """We got some output from a remote shell, this is one of the state
207 machine"""
208 if self.state == STATE_DEAD:
209 return
210 global nr_handle_read
211 nr_handle_read += 1
212 new_data = buffered_dispatcher.handle_read(self)
213 if self.debug:
214 self.print_debug('==> ' + new_data)
215 if self.handle_read_fast_case(self.read_buffer):
216 return
217 lf_pos = new_data.find('\n')
218 if lf_pos >= 0:
219 # Optimization: we knew there were no '\n' in the previous read
220 # buffer, so we searched only in the new_data and we offset the
221 # found index by the length of the previous buffer
222 lf_pos += len(self.read_buffer) - len(new_data)
223 while lf_pos >= 0:
224 # For each line in the buffer
225 line = self.read_buffer[:lf_pos + 1]
226 if callbacks.process(line):
227 pass
228 elif self.state in (STATE_IDLE, STATE_RUNNING):
229 self.print_lines(line)
230 elif self.state is STATE_NOT_STARTED:
231 self.read_in_state_not_started += line
232 if 'The authenticity of host' in line:
233 msg = line.strip('\n') + ' Closing connection.'
234 self.disconnect()
235 elif 'REMOTE HOST IDENTIFICATION HAS CHANGED' in line:
236 msg = 'Remote host identification has changed.'
237 else:
238 msg = None
240 if msg:
241 self.print_lines(msg + ' Consider manually connecting or ' +
242 'using ssh-keyscan.')
244 # Go to the next line in the buffer
245 self.read_buffer = self.read_buffer[lf_pos + 1:]
246 if self.handle_read_fast_case(self.read_buffer):
247 return
248 lf_pos = self.read_buffer.find('\n')
249 if self.state is STATE_NOT_STARTED and not self.init_string_sent:
250 self.dispatch_write(self.init_string)
251 self.init_string_sent = True
253 def print_unfinished_line(self):
254 """The unfinished line stayed long enough in the buffer to be printed"""
255 if self.state is STATE_RUNNING:
256 if not callbacks.process(self.read_buffer):
257 self.print_lines(self.read_buffer)
258 self.read_buffer = ''
260 def writable(self):
261 """Do we want to write something?"""
262 return self.state != STATE_DEAD and buffered_dispatcher.writable(self)
264 def handle_write(self):
265 """Let's write as much as we can"""
266 num_sent = self.send(self.write_buffer)
267 if self.debug:
268 self.print_debug('<== ' + self.write_buffer[:num_sent])
269 self.write_buffer = self.write_buffer[num_sent:]
271 def print_debug(self, msg):
272 """Log some debugging information to the console"""
273 state = STATE_NAMES[self.state]
274 msg = msg.encode('string_escape')
275 console_output('[dbg] %s[%s]: %s\n' % (self.display_name, state, msg))
277 def get_info(self):
278 """Return a list with all information available about this process"""
279 return [self.display_name, self.enabled and 'enabled' or 'disabled',
280 STATE_NAMES[self.state] + ':', self.last_printed_line.strip()]
282 def dispatch_write(self, buf):
283 """There is new stuff to write when possible"""
284 if self.state != STATE_DEAD and self.enabled:
285 buffered_dispatcher.dispatch_write(self, buf)
286 return True
288 def dispatch_command(self, command):
289 if self.dispatch_write(command):
290 self.change_state(STATE_RUNNING)
292 def change_name(self, name):
293 """Change the name of the shell, possibly updating the maximum name
294 length"""
295 if not name:
296 name = self.hostname
297 self.display_name = display_names.change(self.display_name, name)
299 def rename(self, string):
300 """Send to the remote shell, its new name to be shell expanded"""
301 if string:
302 rename1, rename2 = callbacks.add('rename', self.change_name, False)
303 self.dispatch_command('/bin/echo "%s""%s"%s\n' %
304 (rename1, rename2, string))
305 else:
306 self.change_name(self.hostname)
308 def close(self):
309 display_names.change(self.display_name, None)
310 buffered_dispatcher.close(self)