Apparently it was not needed
[gsh.git] / gsh / remote_dispatcher.py
blobbe0558acedc28ea88b0cee2c194c53d1c3df9988
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 reconnect(self):
129 """Relaunch and reconnect to this same remote process"""
130 self.disconnect()
131 self.close()
132 remote_dispatcher(self.hostname)
134 def configure_tty(self):
135 """We don't want \n to be replaced with \r\n, and we disable the echo"""
136 attr = termios.tcgetattr(self.fd)
137 attr[1] &= ~termios.ONLCR # oflag
138 attr[3] &= ~termios.ECHO # lflag
139 termios.tcsetattr(self.fd, termios.TCSANOW, attr)
140 # unsetopt zle prevents Zsh from resetting the tty
141 return 'unsetopt zle 2> /dev/null;stty -echo -onlcr;'
143 def seen_prompt_cb(self, unused):
144 if options.interactive:
145 self.change_state(STATE_IDLE)
146 elif self.command:
147 p1, p2 = callbacks.add('real prompt ends', lambda d: None, True)
148 self.dispatch_command('PS1="%s""%s\n"\n' % (p1, p2))
149 self.dispatch_command(self.command + '\n')
150 self.dispatch_command('exit 2>/dev/null\n')
151 self.command = None
153 def set_prompt(self):
154 """The prompt is important because we detect the readyness of a process
155 by waiting for its prompt."""
156 # No right prompt
157 command_line = 'RPS1=;RPROMPT=;'
158 command_line += 'PROMPT_COMMAND=;'
159 command_line += 'TERM=ansi;'
160 command_line += 'unset HISTFILE;'
161 prompt1, prompt2 = callbacks.add('prompt', self.seen_prompt_cb, True)
162 command_line += 'PS1="%s""%s\n"\n' % (prompt1, prompt2)
163 return command_line
165 def readable(self):
166 """We are always interested in reading from active remote processes if
167 the buffer is OK"""
168 return self.state != STATE_DEAD and buffered_dispatcher.readable(self)
170 def handle_expt(self):
171 if options.interactive:
172 console_output('Error talking to %s\n' % self.display_name)
173 else:
174 pid, status = os.waitpid(self.pid, 0)
175 exit_code = os.WEXITSTATUS(status)
176 options.exit_code = max(options.exit_code, exit_code)
177 self.disconnect()
179 def print_lines(self, lines):
180 from gsh.display_names import max_display_name_length
181 lines = lines.strip('\n')
182 while True:
183 no_empty_lines = lines.replace('\n\n', '\n')
184 if len(no_empty_lines) == len(lines):
185 break
186 lines = no_empty_lines
187 if not lines:
188 return
189 indent = max_display_name_length - len(self.display_name)
190 prefix = self.display_name + indent * ' ' + ' : '
191 console_output(prefix + lines.replace('\n', '\n' + prefix) + '\n')
192 self.last_printed_line = lines[lines.rfind('\n') + 1:]
194 def handle_read_fast_case(self, data):
195 """If we are in a fast case we'll avoid the long processing of each
196 line"""
197 if self.state is not STATE_RUNNING or callbacks.any_in(data):
198 # Slow case :-(
199 return False
201 last_nl = data.rfind('\n')
202 if last_nl == -1:
203 # No '\n' in data => slow case
204 return False
205 self.read_buffer = data[last_nl + 1:]
206 self.print_lines(data[:last_nl])
207 return True
209 def handle_read(self):
210 """We got some output from a remote shell, this is one of the state
211 machine"""
212 if self.state == STATE_DEAD:
213 return
214 global nr_handle_read
215 nr_handle_read += 1
216 new_data = buffered_dispatcher.handle_read(self)
217 if self.debug:
218 self.print_debug('==> ' + new_data)
219 if self.handle_read_fast_case(self.read_buffer):
220 return
221 lf_pos = new_data.find('\n')
222 if lf_pos >= 0:
223 # Optimization: we knew there were no '\n' in the previous read
224 # buffer, so we searched only in the new_data and we offset the
225 # found index by the length of the previous buffer
226 lf_pos += len(self.read_buffer) - len(new_data)
227 while lf_pos >= 0:
228 # For each line in the buffer
229 line = self.read_buffer[:lf_pos + 1]
230 if callbacks.process(line):
231 pass
232 elif self.state in (STATE_IDLE, STATE_RUNNING):
233 self.print_lines(line)
234 elif self.state is STATE_NOT_STARTED:
235 self.read_in_state_not_started += line
236 if 'The authenticity of host' in line:
237 msg = line.strip('\n') + ' Closing connection.'
238 self.disconnect()
239 elif 'REMOTE HOST IDENTIFICATION HAS CHANGED' in line:
240 msg = 'Remote host identification has changed.'
241 else:
242 msg = None
244 if msg:
245 self.print_lines(msg + ' Consider manually connecting or ' +
246 'using ssh-keyscan.')
248 # Go to the next line in the buffer
249 self.read_buffer = self.read_buffer[lf_pos + 1:]
250 if self.handle_read_fast_case(self.read_buffer):
251 return
252 lf_pos = self.read_buffer.find('\n')
253 if self.state is STATE_NOT_STARTED and not self.init_string_sent:
254 self.dispatch_write(self.init_string)
255 self.init_string_sent = True
257 def print_unfinished_line(self):
258 """The unfinished line stayed long enough in the buffer to be printed"""
259 if self.state is STATE_RUNNING:
260 if not callbacks.process(self.read_buffer):
261 self.print_lines(self.read_buffer)
262 self.read_buffer = ''
264 def writable(self):
265 """Do we want to write something?"""
266 return self.state != STATE_DEAD and buffered_dispatcher.writable(self)
268 def handle_write(self):
269 """Let's write as much as we can"""
270 num_sent = self.send(self.write_buffer)
271 if self.debug:
272 self.print_debug('<== ' + self.write_buffer[:num_sent])
273 self.write_buffer = self.write_buffer[num_sent:]
275 def print_debug(self, msg):
276 """Log some debugging information to the console"""
277 state = STATE_NAMES[self.state]
278 msg = msg.encode('string_escape')
279 console_output('[dbg] %s[%s]: %s\n' % (self.display_name, state, msg))
281 def get_info(self):
282 """Return a list with all information available about this process"""
283 return [self.display_name, self.enabled and 'enabled' or 'disabled',
284 STATE_NAMES[self.state] + ':', self.last_printed_line.strip()]
286 def dispatch_write(self, buf):
287 """There is new stuff to write when possible"""
288 if self.state != STATE_DEAD and self.enabled:
289 buffered_dispatcher.dispatch_write(self, buf)
290 return True
292 def dispatch_command(self, command):
293 if self.dispatch_write(command):
294 self.change_state(STATE_RUNNING)
296 def change_name(self, name):
297 """Change the name of the shell, possibly updating the maximum name
298 length"""
299 if not name:
300 name = self.hostname
301 self.display_name = display_names.change(self.display_name, name)
303 def rename(self, string):
304 """Send to the remote shell, its new name to be shell expanded"""
305 if string:
306 rename1, rename2 = callbacks.add('rename', self.change_name, False)
307 self.dispatch_command('/bin/echo "%s""%s"%s\n' %
308 (rename1, rename2, string))
309 else:
310 self.change_name(self.hostname)
312 def close(self):
313 display_names.change(self.display_name, None)
314 buffered_dispatcher.close(self)