:export_rank has been renamed to :export_vars as it now also exports the
[gsh.git] / gsh / remote_dispatcher.py
blobe2dd665cdfe4b3dbdd63c63f492366a021483af5
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 handle_close(self):
180 self.handle_expt()
182 def print_lines(self, lines):
183 from gsh.display_names import max_display_name_length
184 lines = lines.strip('\n')
185 while True:
186 no_empty_lines = lines.replace('\n\n', '\n')
187 if len(no_empty_lines) == len(lines):
188 break
189 lines = no_empty_lines
190 if not lines:
191 return
192 indent = max_display_name_length - len(self.display_name)
193 prefix = self.display_name + indent * ' ' + ' : '
194 console_output(prefix + lines.replace('\n', '\n' + prefix) + '\n')
195 self.last_printed_line = lines[lines.rfind('\n') + 1:]
197 def handle_read_fast_case(self, data):
198 """If we are in a fast case we'll avoid the long processing of each
199 line"""
200 if self.state is not STATE_RUNNING or callbacks.any_in(data):
201 # Slow case :-(
202 return False
204 last_nl = data.rfind('\n')
205 if last_nl == -1:
206 # No '\n' in data => slow case
207 return False
208 self.read_buffer = data[last_nl + 1:]
209 self.print_lines(data[:last_nl])
210 return True
212 def handle_read(self):
213 """We got some output from a remote shell, this is one of the state
214 machine"""
215 if self.state == STATE_DEAD:
216 return
217 global nr_handle_read
218 nr_handle_read += 1
219 new_data = buffered_dispatcher.handle_read(self)
220 if self.debug:
221 self.print_debug('==> ' + new_data)
222 if self.handle_read_fast_case(self.read_buffer):
223 return
224 lf_pos = new_data.find('\n')
225 if lf_pos >= 0:
226 # Optimization: we knew there were no '\n' in the previous read
227 # buffer, so we searched only in the new_data and we offset the
228 # found index by the length of the previous buffer
229 lf_pos += len(self.read_buffer) - len(new_data)
230 while lf_pos >= 0:
231 # For each line in the buffer
232 line = self.read_buffer[:lf_pos + 1]
233 if callbacks.process(line):
234 pass
235 elif self.state in (STATE_IDLE, STATE_RUNNING):
236 self.print_lines(line)
237 elif self.state is STATE_NOT_STARTED:
238 self.read_in_state_not_started += line
239 if 'The authenticity of host' in line:
240 msg = line.strip('\n') + ' Closing connection.'
241 self.disconnect()
242 elif 'REMOTE HOST IDENTIFICATION HAS CHANGED' in line:
243 msg = 'Remote host identification has changed.'
244 else:
245 msg = None
247 if msg:
248 self.print_lines(msg + ' Consider manually connecting or ' +
249 'using ssh-keyscan.')
251 # Go to the next line in the buffer
252 self.read_buffer = self.read_buffer[lf_pos + 1:]
253 if self.handle_read_fast_case(self.read_buffer):
254 return
255 lf_pos = self.read_buffer.find('\n')
256 if self.state is STATE_NOT_STARTED and not self.init_string_sent:
257 self.dispatch_write(self.init_string)
258 self.init_string_sent = True
260 def print_unfinished_line(self):
261 """The unfinished line stayed long enough in the buffer to be printed"""
262 if self.state is STATE_RUNNING:
263 if not callbacks.process(self.read_buffer):
264 self.print_lines(self.read_buffer)
265 self.read_buffer = ''
267 def writable(self):
268 """Do we want to write something?"""
269 return self.state != STATE_DEAD and buffered_dispatcher.writable(self)
271 def handle_write(self):
272 """Let's write as much as we can"""
273 num_sent = self.send(self.write_buffer)
274 if self.debug:
275 self.print_debug('<== ' + self.write_buffer[:num_sent])
276 self.write_buffer = self.write_buffer[num_sent:]
278 def print_debug(self, msg):
279 """Log some debugging information to the console"""
280 state = STATE_NAMES[self.state]
281 msg = msg.encode('string_escape')
282 console_output('[dbg] %s[%s]: %s\n' % (self.display_name, state, msg))
284 def get_info(self):
285 """Return a list with all information available about this process"""
286 return [self.display_name, self.enabled and 'enabled' or 'disabled',
287 STATE_NAMES[self.state] + ':', self.last_printed_line.strip()]
289 def dispatch_write(self, buf):
290 """There is new stuff to write when possible"""
291 if self.state != STATE_DEAD and self.enabled:
292 buffered_dispatcher.dispatch_write(self, buf)
293 return True
295 def dispatch_command(self, command):
296 if self.dispatch_write(command):
297 self.change_state(STATE_RUNNING)
299 def change_name(self, name):
300 """Change the name of the shell, possibly updating the maximum name
301 length"""
302 if not name:
303 name = self.hostname
304 self.display_name = display_names.change(self.display_name, name)
306 def rename(self, string):
307 """Send to the remote shell, its new name to be shell expanded"""
308 if string:
309 rename1, rename2 = callbacks.add('rename', self.change_name, False)
310 self.dispatch_command('/bin/echo "%s""%s"%s\n' %
311 (rename1, rename2, string))
312 else:
313 self.change_name(self.hostname)
315 def close(self):
316 display_names.change(self.display_name, None)
317 buffered_dispatcher.close(self)