Fast test first
[polysh.git] / gsh / remote_dispatcher.py
blob64ce139daefc6139ae5ef500a43fe5d6af5c20f5
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 file_transfer
31 # Either the remote shell is expecting a command or one is already running
32 STATE_NAMES = ['not_started', 'idle', 'running', 'terminated']
34 STATE_NOT_STARTED, \
35 STATE_IDLE, \
36 STATE_RUNNING, \
37 STATE_TERMINATED = range(len(STATE_NAMES))
39 # Count the total number of remote_dispatcher.handle_read() invocations
40 nr_handle_read = 0
42 def main_loop_iteration(timeout=None):
43 """Return the number of remote_dispatcher.handle_read() calls made by this
44 iteration"""
45 prev_nr_read = nr_handle_read
46 asyncore.loop(count=1, timeout=timeout, use_poll=True)
47 return nr_handle_read - prev_nr_read
49 def log(msg):
50 if options.log_file:
51 options.log_file.write(msg)
53 class remote_dispatcher(buffered_dispatcher):
54 """A remote_dispatcher is a ssh process we communicate with"""
56 def __init__(self, hostname):
57 self.pid, fd = pty.fork()
58 if self.pid == 0:
59 # Child
60 self.launch_ssh(hostname)
61 sys.exit(1)
63 # Parent
64 buffered_dispatcher.__init__(self, fd)
65 self.hostname = hostname
66 self.debug = options.debug
67 self.active = True # deactived shells are dead forever
68 self.enabled = True # shells can be enabled and disabled
69 self.state = STATE_NOT_STARTED
70 self.term_size = (-1, -1)
71 self.display_name = ''
72 self.change_name(hostname)
73 self.init_string = self.configure_tty() + self.set_prompt()
74 self.init_string_sent = False
75 self.command = options.command
77 def launch_ssh(self, name):
78 """Launch the ssh command in the child process"""
79 evaluated = options.ssh % {'host': name}
80 if evaluated == options.ssh:
81 evaluated = '%s %s' % (evaluated, name)
82 os.execlp('/bin/sh', 'sh', '-c', evaluated)
84 def set_enabled(self, enabled):
85 from gsh.dispatchers import update_max_display_name_length
86 self.enabled = enabled
87 if options.interactive:
88 # In non-interactive mode, remote processes leave as soon
89 # as they are terminated, but we don't want to break the
90 # indentation if all the remaining processes have short names.
91 l = len(self.display_name)
92 if not enabled:
93 l = -l
94 update_max_display_name_length(l)
96 def change_state(self, state):
97 """Change the state of the remote process, logging the change"""
98 if state is not self.state:
99 if self.debug:
100 self.print_debug('state => %s' % (STATE_NAMES[state]))
101 self.state = state
103 def disconnect(self):
104 """We are no more interested in this remote process"""
105 try:
106 os.kill(self.pid, signal.SIGKILL)
107 except OSError:
108 # The process was already dead, no problem
109 pass
110 self.read_buffer = ''
111 self.write_buffer = ''
112 self.active = False
113 self.set_enabled(False)
114 if options.abort_error and self.state is STATE_NOT_STARTED:
115 raise asyncore.ExitNow(1)
117 def reconnect(self):
118 """Relaunch and reconnect to this same remote process"""
119 self.disconnect()
120 self.close()
121 remote_dispatcher(self.hostname)
123 def configure_tty(self):
124 """We don't want \n to be replaced with \r\n, and we disable the echo"""
125 attr = termios.tcgetattr(self.fd)
126 attr[1] &= ~termios.ONLCR # oflag
127 attr[3] &= ~termios.ECHO # lflag
128 termios.tcsetattr(self.fd, termios.TCSANOW, attr)
129 # unsetopt zle prevents Zsh from resetting the tty
130 return 'unsetopt zle 2> /dev/null;stty -echo -onlcr;'
132 def seen_prompt_cb(self, unused):
133 if options.interactive:
134 self.change_state(STATE_IDLE)
135 elif self.command:
136 self.dispatch_command(self.command + '\n')
137 self.command = None
138 else:
139 self.change_state(STATE_TERMINATED)
140 self.disconnect()
142 def set_prompt(self):
143 """The prompt is important because we detect the readyness of a process
144 by waiting for its prompt. The prompt is built in two parts for it not
145 to appear in its building"""
146 # No right prompt
147 command_line = 'RPS1=;RPROMPT=;'
148 command_line += 'TERM=ansi;'
149 prompt1, prompt2 = callbacks.add('prompt', self.seen_prompt_cb, True)
150 command_line += 'PS1="%s""%s\n"\n' % (prompt1, prompt2)
151 return command_line
153 def readable(self):
154 """We are always interested in reading from active remote processes if
155 the buffer is OK"""
156 return self.active and buffered_dispatcher.readable(self)
158 def handle_error(self):
159 """An exception may or may not lead to a disconnection"""
160 if buffered_dispatcher.handle_error(self):
161 console_output('Error talking to %s\n' % self.display_name)
162 self.disconnect()
164 def print_lines(self, lines):
165 from gsh.dispatchers import max_display_name_length
166 lines = lines.strip('\n')
167 while True:
168 no_empty_lines = lines.replace('\n\n', '\n')
169 if len(no_empty_lines) == len(lines):
170 break
171 lines = no_empty_lines
172 if not lines:
173 return
174 indent = max_display_name_length - len(self.display_name)
175 prefix = self.display_name + indent * ' ' + ': '
176 console_output(prefix + lines.replace('\n', '\n' + prefix) + '\n')
178 def handle_read_fast_case(self, data):
179 """If we are in a fast case we'll avoid the long processing of each
180 line"""
181 if self.state is not STATE_RUNNING or callbacks.any_in(data):
182 # Slow case :-(
183 return False
185 last_nl = data.rfind('\n')
186 if last_nl == -1:
187 # No '\n' in data => slow case
188 return False
189 self.read_buffer = data[last_nl + 1:]
190 self.print_lines(data[:last_nl])
191 return True
193 def handle_read(self):
194 """We got some output from a remote shell, this is one of the state
195 machine"""
196 if not self.active:
197 return
198 global nr_handle_read
199 nr_handle_read += 1
200 new_data = buffered_dispatcher.handle_read(self)
201 if self.debug:
202 self.print_debug('==> ' + new_data)
203 if self.handle_read_fast_case(self.read_buffer):
204 return
205 lf_pos = new_data.find('\n')
206 if lf_pos >= 0:
207 # Optimization: we knew there were no '\n' in the previous read
208 # buffer, so we searched only in the new_data and we offset the
209 # found index by the length of the previous buffer
210 lf_pos += len(self.read_buffer) - len(new_data)
211 while lf_pos >= 0:
212 # For each line in the buffer
213 line = self.read_buffer[:lf_pos + 1]
214 if callbacks.process(line):
215 pass
216 elif self.state in (STATE_IDLE, STATE_RUNNING):
217 self.print_lines(line)
218 elif self.state is STATE_NOT_STARTED:
219 if 'The authenticity of host' in line:
220 msg = line.strip('\n') + ' Closing connection.'
221 self.disconnect()
222 elif 'REMOTE HOST IDENTIFICATION HAS CHANGED' in line:
223 msg = 'Remote host identification has changed.'
224 else:
225 msg = None
227 if msg:
228 self.print_lines(msg + ' Consider manually connecting or ' +
229 'using ssh-keyscan.')
231 # Go to the next line in the buffer
232 self.read_buffer = self.read_buffer[lf_pos + 1:]
233 if self.handle_read_fast_case(self.read_buffer):
234 return
235 lf_pos = self.read_buffer.find('\n')
236 if self.state is STATE_NOT_STARTED and not self.init_string_sent:
237 self.dispatch_write(self.init_string)
238 self.init_string_sent = True
240 def print_unfinished_line(self):
241 """The unfinished line stayed long enough in the buffer to be printed"""
242 if self.state is STATE_RUNNING:
243 self.print_lines(self.read_buffer)
244 self.read_buffer = ''
246 def writable(self):
247 """Do we want to write something?"""
248 return self.active and buffered_dispatcher.writable(self)
250 def handle_write(self):
251 """Let's write as much as we can"""
252 num_sent = self.send(self.write_buffer)
253 if self.debug:
254 self.print_debug('<== ' + self.write_buffer[:num_sent])
255 self.write_buffer = self.write_buffer[num_sent:]
257 def print_debug(self, msg):
258 """Log some debugging information to the console"""
259 state = STATE_NAMES[self.state]
260 msg = msg.encode('string_escape')
261 console_output('[dbg] %s[%s]: %s\n' % (self.display_name, state, msg))
263 def get_info(self):
264 """Return a list with all information available about this process"""
265 if self.active:
266 state = STATE_NAMES[self.state]
267 else:
268 state = ''
270 if self.debug:
271 debug = 'debug'
272 else:
273 debug = ''
275 return [self.display_name, 'fd:%d' % (self.fd),
276 'r:%d' % (len(self.read_buffer)),
277 'w:%d' % (len(self.write_buffer)),
278 self.active and 'active' or 'dead',
279 self.enabled and 'enabled' or 'disabled',
280 state,
281 debug]
283 def dispatch_write(self, buf):
284 """There is new stuff to write when possible"""
285 if self.active and self.enabled:
286 buffered_dispatcher.dispatch_write(self, buf)
287 return True
289 def dispatch_command(self, command):
290 if self.dispatch_write(command):
291 self.change_state(STATE_RUNNING)
293 def change_name(self, name):
294 """Change the name of the shell, possibly updating the maximum name
295 length"""
296 from gsh import dispatchers
297 if not name:
298 name = self.hostname
299 previous_name_len = len(self.display_name)
300 self.display_name = None
301 self.display_name = dispatchers.make_unique_name(name)
302 dispatchers.update_max_display_name_length(len(self.display_name))
303 dispatchers.update_max_display_name_length(-previous_name_len)
305 def rename(self, string):
306 """Send to the remote shell, its new name to be shell expanded"""
307 if string:
308 rename1, rename2 = callbacks.add('rename', self.change_name, False)
309 self.dispatch_command('/bin/echo "%s""%s"%s\n' %
310 (rename1, rename2, string))
311 else:
312 self.change_name(self.hostname)
314 def __str__(self):
315 return self.display_name