Remove useless definition
[polysh.git] / gsh / remote_dispatcher.py
blobb6b1017c5ac58dfc68f94133016ae77499887a04
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."""
145 # No right prompt
146 command_line = 'RPS1=;RPROMPT=;'
147 command_line += 'TERM=ansi;'
148 prompt1, prompt2 = callbacks.add('prompt', self.seen_prompt_cb, True)
149 command_line += 'PS1="%s""%s\n"\n' % (prompt1, prompt2)
150 return command_line
152 def readable(self):
153 """We are always interested in reading from active remote processes if
154 the buffer is OK"""
155 return self.active and buffered_dispatcher.readable(self)
157 def handle_error(self):
158 """An exception may or may not lead to a disconnection"""
159 if buffered_dispatcher.handle_error(self):
160 console_output('Error talking to %s\n' % self.display_name)
161 self.disconnect()
163 def print_lines(self, lines):
164 from gsh.dispatchers import max_display_name_length
165 lines = lines.strip('\n')
166 while True:
167 no_empty_lines = lines.replace('\n\n', '\n')
168 if len(no_empty_lines) == len(lines):
169 break
170 lines = no_empty_lines
171 if not lines:
172 return
173 indent = max_display_name_length - len(self.display_name)
174 prefix = self.display_name + indent * ' ' + ': '
175 console_output(prefix + lines.replace('\n', '\n' + prefix) + '\n')
177 def handle_read_fast_case(self, data):
178 """If we are in a fast case we'll avoid the long processing of each
179 line"""
180 if self.state is not STATE_RUNNING or callbacks.any_in(data):
181 # Slow case :-(
182 return False
184 last_nl = data.rfind('\n')
185 if last_nl == -1:
186 # No '\n' in data => slow case
187 return False
188 self.read_buffer = data[last_nl + 1:]
189 self.print_lines(data[:last_nl])
190 return True
192 def handle_read(self):
193 """We got some output from a remote shell, this is one of the state
194 machine"""
195 if not self.active:
196 return
197 global nr_handle_read
198 nr_handle_read += 1
199 new_data = buffered_dispatcher.handle_read(self)
200 if self.debug:
201 self.print_debug('==> ' + new_data)
202 if self.handle_read_fast_case(self.read_buffer):
203 return
204 lf_pos = new_data.find('\n')
205 if lf_pos >= 0:
206 # Optimization: we knew there were no '\n' in the previous read
207 # buffer, so we searched only in the new_data and we offset the
208 # found index by the length of the previous buffer
209 lf_pos += len(self.read_buffer) - len(new_data)
210 while lf_pos >= 0:
211 # For each line in the buffer
212 line = self.read_buffer[:lf_pos + 1]
213 if callbacks.process(line):
214 pass
215 elif self.state in (STATE_IDLE, STATE_RUNNING):
216 self.print_lines(line)
217 elif self.state is STATE_NOT_STARTED:
218 if 'The authenticity of host' in line:
219 msg = line.strip('\n') + ' Closing connection.'
220 self.disconnect()
221 elif 'REMOTE HOST IDENTIFICATION HAS CHANGED' in line:
222 msg = 'Remote host identification has changed.'
223 else:
224 msg = None
226 if msg:
227 self.print_lines(msg + ' Consider manually connecting or ' +
228 'using ssh-keyscan.')
230 # Go to the next line in the buffer
231 self.read_buffer = self.read_buffer[lf_pos + 1:]
232 if self.handle_read_fast_case(self.read_buffer):
233 return
234 lf_pos = self.read_buffer.find('\n')
235 if self.state is STATE_NOT_STARTED and not self.init_string_sent:
236 self.dispatch_write(self.init_string)
237 self.init_string_sent = True
239 def print_unfinished_line(self):
240 """The unfinished line stayed long enough in the buffer to be printed"""
241 if self.state is STATE_RUNNING:
242 self.print_lines(self.read_buffer)
243 self.read_buffer = ''
245 def writable(self):
246 """Do we want to write something?"""
247 return self.active and buffered_dispatcher.writable(self)
249 def handle_write(self):
250 """Let's write as much as we can"""
251 num_sent = self.send(self.write_buffer)
252 if self.debug:
253 self.print_debug('<== ' + self.write_buffer[:num_sent])
254 self.write_buffer = self.write_buffer[num_sent:]
256 def print_debug(self, msg):
257 """Log some debugging information to the console"""
258 state = STATE_NAMES[self.state]
259 msg = msg.encode('string_escape')
260 console_output('[dbg] %s[%s]: %s\n' % (self.display_name, state, msg))
262 def get_info(self):
263 """Return a list with all information available about this process"""
264 if self.active:
265 state = STATE_NAMES[self.state]
266 else:
267 state = ''
269 if self.debug:
270 debug = 'debug'
271 else:
272 debug = ''
274 return [self.display_name, 'fd:%d' % (self.fd),
275 'r:%d' % (len(self.read_buffer)),
276 'w:%d' % (len(self.write_buffer)),
277 self.active and 'active' or 'dead',
278 self.enabled and 'enabled' or 'disabled',
279 state,
280 debug]
282 def dispatch_write(self, buf):
283 """There is new stuff to write when possible"""
284 if self.active 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 from gsh import dispatchers
296 if not name:
297 name = self.hostname
298 previous_name_len = len(self.display_name)
299 self.display_name = None
300 self.display_name = dispatchers.make_unique_name(name)
301 dispatchers.update_max_display_name_length(len(self.display_name))
302 dispatchers.update_max_display_name_length(-previous_name_len)
304 def rename(self, string):
305 """Send to the remote shell, its new name to be shell expanded"""
306 if string:
307 rename1, rename2 = callbacks.add('rename', self.change_name, False)
308 self.dispatch_command('/bin/echo "%s""%s"%s\n' %
309 (rename1, rename2, string))
310 else:
311 self.change_name(self.hostname)
313 def __str__(self):
314 return self.display_name