blob: c3e2dd7ecda07aa1892ab7d313412b54d6a5a8ea [file] [log] [blame]
lmrbbc9dd52009-07-22 20:33:47 +00001#!/usr/bin/python
lmrbbc9dd52009-07-22 20:33:47 +00002"""
3A class and functions used for running and controlling child processes.
4
5@copyright: 2008-2009 Red Hat Inc.
6"""
7
lmr78fabe52009-10-05 18:52:51 +00008import os, sys, pty, select, termios, fcntl
9
10
11# The following helper functions are shared by the server and the client.
12
13def _lock(filename):
14 if not os.path.exists(filename):
15 open(filename, "w").close()
16 fd = os.open(filename, os.O_RDWR)
17 fcntl.lockf(fd, fcntl.LOCK_EX)
18 return fd
19
20
21def _unlock(fd):
22 fcntl.lockf(fd, fcntl.LOCK_UN)
23 os.close(fd)
24
25
26def _locked(filename):
27 try:
28 fd = os.open(filename, os.O_RDWR)
29 except:
30 return False
31 try:
32 fcntl.lockf(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
33 except:
34 os.close(fd)
35 return True
36 fcntl.lockf(fd, fcntl.LOCK_UN)
37 os.close(fd)
38 return False
39
40
41def _wait(filename):
42 fd = _lock(filename)
43 _unlock(fd)
44
45
46def _get_filenames(base_dir, id):
47 return [os.path.join(base_dir, s + id) for s in
48 "shell-pid-", "status-", "output-", "inpipe-",
49 "lock-server-running-", "lock-client-starting-"]
50
51
52def _get_reader_filename(base_dir, id, reader):
53 return os.path.join(base_dir, "outpipe-%s-%s" % (reader, id))
54
55
56# The following is the server part of the module.
57
58if __name__ == "__main__":
59 id = sys.stdin.readline().strip()
60 echo = sys.stdin.readline().strip() == "True"
61 readers = sys.stdin.readline().strip().split(",")
62 command = sys.stdin.readline().strip() + " && echo %s > /dev/null" % id
63
64 # Define filenames to be used for communication
65 base_dir = "/tmp/kvm_spawn"
66 (shell_pid_filename,
67 status_filename,
68 output_filename,
69 inpipe_filename,
70 lock_server_running_filename,
71 lock_client_starting_filename) = _get_filenames(base_dir, id)
72
73 # Populate the reader filenames list
74 reader_filenames = [_get_reader_filename(base_dir, id, reader)
75 for reader in readers]
76
77 # Set $TERM = dumb
78 os.putenv("TERM", "dumb")
79
80 (shell_pid, shell_fd) = pty.fork()
81 if shell_pid == 0:
82 # Child process: run the command in a subshell
83 os.execv("/bin/sh", ["/bin/sh", "-c", command])
84 else:
85 # Parent process
86 lock_server_running = _lock(lock_server_running_filename)
87
88 # Set terminal echo on/off and disable pre- and post-processing
89 attr = termios.tcgetattr(shell_fd)
90 attr[0] &= ~termios.INLCR
91 attr[0] &= ~termios.ICRNL
92 attr[0] &= ~termios.IGNCR
93 attr[1] &= ~termios.OPOST
94 if echo:
95 attr[3] |= termios.ECHO
96 else:
97 attr[3] &= ~termios.ECHO
98 termios.tcsetattr(shell_fd, termios.TCSANOW, attr)
99
100 # Open output file
101 output_file = open(output_filename, "w")
102 # Open input pipe
103 os.mkfifo(inpipe_filename)
104 inpipe_fd = os.open(inpipe_filename, os.O_RDWR)
105 # Open output pipes (readers)
106 reader_fds = []
107 for filename in reader_filenames:
108 os.mkfifo(filename)
109 reader_fds.append(os.open(filename, os.O_RDWR))
110
111 # Write shell PID to file
112 file = open(shell_pid_filename, "w")
113 file.write(str(shell_pid))
114 file.close()
115
116 # Print something to stdout so the client can start working
117 print "Server %s ready" % id
118 sys.stdout.flush()
119
120 # Initialize buffers
121 buffers = ["" for reader in readers]
122
123 # Read from child and write to files/pipes
124 while True:
125 check_termination = False
126 # Make a list of reader pipes whose buffers are not empty
127 fds = [fd for (i, fd) in enumerate(reader_fds) if buffers[i]]
128 # Wait until there's something to do
129 r, w, x = select.select([shell_fd, inpipe_fd], fds, [], 0.5)
130 # If a reader pipe is ready for writing --
131 for (i, fd) in enumerate(reader_fds):
132 if fd in w:
133 bytes_written = os.write(fd, buffers[i])
134 buffers[i] = buffers[i][bytes_written:]
135 # If there's data to read from the child process --
136 if shell_fd in r:
137 try:
138 data = os.read(shell_fd, 16384)
139 except OSError:
140 data = ""
141 if not data:
142 check_termination = True
143 # Remove carriage returns from the data -- they often cause
144 # trouble and are normally not needed
145 data = data.replace("\r", "")
146 output_file.write(data)
147 output_file.flush()
148 for i in range(len(readers)):
149 buffers[i] += data
150 # If os.read() raised an exception or there was nothing to read --
151 if check_termination or shell_fd not in r:
152 pid, status = os.waitpid(shell_pid, os.WNOHANG)
153 if pid:
154 status = os.WEXITSTATUS(status)
155 break
156 # If there's data to read from the client --
157 if inpipe_fd in r:
158 data = os.read(inpipe_fd, 1024)
159 os.write(shell_fd, data)
160
161 # Write the exit status to a file
162 file = open(status_filename, "w")
163 file.write(str(status))
164 file.close()
165
166 # Wait for the client to finish initializing
167 _wait(lock_client_starting_filename)
168
169 # Delete FIFOs
170 for filename in reader_filenames + [inpipe_filename]:
171 try:
172 os.unlink(filename)
173 except OSError:
174 pass
175
176 # Close all files and pipes
177 output_file.close()
178 os.close(inpipe_fd)
179 for fd in reader_fds:
180 os.close(fd)
181
182 _unlock(lock_server_running)
183 exit(0)
184
185
186# The following is the client part of the module.
187
188import subprocess, time, signal, re, threading, logging
lmrb635b862009-09-10 14:53:21 +0000189import common, kvm_utils
190
lmrbbc9dd52009-07-22 20:33:47 +0000191
Eric Li7edb3042011-01-06 17:57:17 -0800192class ExpectError(Exception):
193 def __init__(self, patterns, output):
194 Exception.__init__(self, patterns, output)
195 self.patterns = patterns
196 self.output = output
197
198 def _pattern_str(self):
199 if len(self.patterns) == 1:
200 return "pattern %r" % self.patterns[0]
201 else:
202 return "patterns %r" % self.patterns
203
204 def __str__(self):
205 return ("Unknown error occurred while looking for %s (output: %r)" %
206 (self._pattern_str(), self.output))
207
208
209class ExpectTimeoutError(ExpectError):
210 def __str__(self):
211 return ("Timeout expired while looking for %s (output: %r)" %
212 (self._pattern_str(), self.output))
213
214
215class ExpectProcessTerminatedError(ExpectError):
216 def __init__(self, patterns, status, output):
217 ExpectError.__init__(self, patterns, output)
218 self.status = status
219
220 def __str__(self):
221 return ("Process terminated while looking for %s (status: %s, output: "
222 "%r)" % (self._pattern_str(), self.status, self.output))
223
224
225class ShellError(Exception):
226 def __init__(self, cmd, output):
227 Exception.__init__(self, cmd, output)
228 self.cmd = cmd
229 self.output = output
230
231 def __str__(self):
232 return ("Could not execute shell command %r (output: %r)" %
233 (self.cmd, self.output))
234
235
236class ShellTimeoutError(ShellError):
237 def __str__(self):
238 return ("Timeout expired while waiting for shell command %r to "
239 "complete (output: %r)" % (self.cmd, self.output))
240
241
242class ShellProcessTerminatedError(ShellError):
243 # Raised when the shell process itself (e.g. ssh, netcat, telnet)
244 # terminates unexpectedly
245 def __init__(self, cmd, status, output):
246 ShellError.__init__(self, cmd, output)
247 self.status = status
248
249 def __str__(self):
250 return ("Shell process terminated while waiting for command %r to "
251 "complete (status: %s, output: %r)" %
252 (self.cmd, self.status, self.output))
253
254
255class ShellCmdError(ShellError):
256 # Raised when a command executed in a shell terminates with a nonzero
257 # exit code (status)
258 def __init__(self, cmd, status, output):
259 ShellError.__init__(self, cmd, output)
260 self.status = status
261
262 def __str__(self):
263 return ("Shell command %r failed with status %d (output: %r)" %
264 (self.cmd, self.status, self.output))
265
266
267class ShellStatusError(ShellError):
268 # Raised when the command's exit status cannot be obtained
269 def __str__(self):
270 return ("Could not get exit status of command %r (output: %r)" %
271 (self.cmd, self.output))
272
273
lmrbbc9dd52009-07-22 20:33:47 +0000274def run_bg(command, termination_func=None, output_func=None, output_prefix="",
275 timeout=1.0):
276 """
277 Run command as a subprocess. Call output_func with each line of output
278 from the subprocess (prefixed by output_prefix). Call termination_func
279 when the subprocess terminates. Return when timeout expires or when the
280 subprocess exits -- whichever occurs first.
281
282 @brief: Run a subprocess in the background and collect its output and
283 exit status.
284
285 @param command: The shell command to execute
286 @param termination_func: A function to call when the process terminates
287 (should take an integer exit status parameter)
288 @param output_func: A function to call with each line of output from
289 the subprocess (should take a string parameter)
290 @param output_prefix: A string to pre-pend to each line of the output,
291 before passing it to stdout_func
292 @param timeout: Time duration (in seconds) to wait for the subprocess to
293 terminate before returning
294
Eric Li7edb3042011-01-06 17:57:17 -0800295 @return: A Tail object.
lmrbbc9dd52009-07-22 20:33:47 +0000296 """
Eric Li7edb3042011-01-06 17:57:17 -0800297 process = Tail(command=command,
298 termination_func=termination_func,
299 output_func=output_func,
300 output_prefix=output_prefix)
lmrbbc9dd52009-07-22 20:33:47 +0000301
302 end_time = time.time() + timeout
303 while time.time() < end_time and process.is_alive():
304 time.sleep(0.1)
305
306 return process
307
308
309def run_fg(command, output_func=None, output_prefix="", timeout=1.0):
310 """
311 Run command as a subprocess. Call output_func with each line of output
312 from the subprocess (prefixed by prefix). Return when timeout expires or
313 when the subprocess exits -- whichever occurs first. If timeout expires
314 and the subprocess is still running, kill it before returning.
315
316 @brief: Run a subprocess in the foreground and collect its output and
317 exit status.
318
319 @param command: The shell command to execute
320 @param output_func: A function to call with each line of output from
321 the subprocess (should take a string parameter)
322 @param output_prefix: A string to pre-pend to each line of the output,
323 before passing it to stdout_func
324 @param timeout: Time duration (in seconds) to wait for the subprocess to
325 terminate before killing it and returning
326
327 @return: A 2-tuple containing the exit status of the process and its
328 STDOUT/STDERR output. If timeout expires before the process
329 terminates, the returned status is None.
330 """
331 process = run_bg(command, None, output_func, output_prefix, timeout)
332 output = process.get_output()
333 if process.is_alive():
334 status = None
335 else:
336 status = process.get_status()
337 process.close()
338 return (status, output)
339
340
Eric Li7edb3042011-01-06 17:57:17 -0800341class Spawn:
lmrbbc9dd52009-07-22 20:33:47 +0000342 """
343 This class is used for spawning and controlling a child process.
344
345 A new instance of this class can either run a new server (a small Python
346 program that reads output from the child process and reports it to the
347 client and to a text file) or attach to an already running server.
348 When a server is started it runs the child process.
349 The server writes output from the child's STDOUT and STDERR to a text file.
350 The text file can be accessed at any time using get_output().
351 In addition, the server opens as many pipes as requested by the client and
352 writes the output to them.
Eric Li7edb3042011-01-06 17:57:17 -0800353 The pipes are requested and accessed by classes derived from Spawn.
lmrbbc9dd52009-07-22 20:33:47 +0000354 These pipes are referred to as "readers".
355 The server also receives input from the client and sends it to the child
356 process.
357 An instance of this class can be pickled. Every derived class is
358 responsible for restoring its own state by properly defining
359 __getinitargs__().
360
361 The first named pipe is used by _tail(), a function that runs in the
362 background and reports new output from the child as it is produced.
363 The second named pipe is used by a set of functions that read and parse
364 output as requested by the user in an interactive manner, similar to
365 pexpect.
366 When unpickled it automatically
367 resumes _tail() if needed.
368 """
369
lmrcec66772010-06-22 01:55:50 +0000370 def __init__(self, command=None, id=None, auto_close=False, echo=False,
371 linesep="\n"):
lmrbbc9dd52009-07-22 20:33:47 +0000372 """
373 Initialize the class and run command as a child process.
374
375 @param command: Command to run, or None if accessing an already running
376 server.
377 @param id: ID of an already running server, if accessing a running
378 server, or None if starting a new one.
lmrcec66772010-06-22 01:55:50 +0000379 @param auto_close: If True, close() the instance automatically when its
380 reference count drops to zero (default False).
lmrbbc9dd52009-07-22 20:33:47 +0000381 @param echo: Boolean indicating whether echo should be initially
382 enabled for the pseudo terminal running the subprocess. This
383 parameter has an effect only when starting a new server.
384 @param linesep: Line separator to be appended to strings sent to the
385 child process by sendline().
386 """
387 self.id = id or kvm_utils.generate_random_string(8)
388
389 # Define filenames for communication with server
390 base_dir = "/tmp/kvm_spawn"
391 try:
392 os.makedirs(base_dir)
393 except:
394 pass
395 (self.shell_pid_filename,
396 self.status_filename,
397 self.output_filename,
398 self.inpipe_filename,
399 self.lock_server_running_filename,
400 self.lock_client_starting_filename) = _get_filenames(base_dir,
401 self.id)
402
403 # Remember some attributes
lmrcec66772010-06-22 01:55:50 +0000404 self.auto_close = auto_close
lmrbbc9dd52009-07-22 20:33:47 +0000405 self.echo = echo
406 self.linesep = linesep
407
408 # Make sure the 'readers' and 'close_hooks' attributes exist
409 if not hasattr(self, "readers"):
410 self.readers = []
411 if not hasattr(self, "close_hooks"):
412 self.close_hooks = []
413
414 # Define the reader filenames
415 self.reader_filenames = dict(
416 (reader, _get_reader_filename(base_dir, self.id, reader))
417 for reader in self.readers)
418
419 # Let the server know a client intends to open some pipes;
420 # if the executed command terminates quickly, the server will wait for
421 # the client to release the lock before exiting
422 lock_client_starting = _lock(self.lock_client_starting_filename)
423
424 # Start the server (which runs the command)
425 if command:
lmr24a82982010-06-14 17:18:42 +0000426 sub = subprocess.Popen("%s %s" % (sys.executable, __file__),
lmrbbc9dd52009-07-22 20:33:47 +0000427 shell=True,
428 stdin=subprocess.PIPE,
429 stdout=subprocess.PIPE,
430 stderr=subprocess.STDOUT)
431 # Send parameters to the server
432 sub.stdin.write("%s\n" % self.id)
433 sub.stdin.write("%s\n" % echo)
434 sub.stdin.write("%s\n" % ",".join(self.readers))
435 sub.stdin.write("%s\n" % command)
436 # Wait for the server to complete its initialization
lmrb8f53d62009-07-27 13:29:17 +0000437 while not "Server %s ready" % self.id in sub.stdout.readline():
438 pass
lmrbbc9dd52009-07-22 20:33:47 +0000439
440 # Open the reading pipes
441 self.reader_fds = {}
442 try:
443 assert(_locked(self.lock_server_running_filename))
444 for reader, filename in self.reader_filenames.items():
445 self.reader_fds[reader] = os.open(filename, os.O_RDONLY)
446 except:
447 pass
448
449 # Allow the server to continue
450 _unlock(lock_client_starting)
451
452
453 # The following two functions are defined to make sure the state is set
454 # exclusively by the constructor call as specified in __getinitargs__().
455
456 def __getstate__(self):
457 pass
458
459
460 def __setstate__(self, state):
461 pass
462
463
464 def __getinitargs__(self):
465 # Save some information when pickling -- will be passed to the
466 # constructor upon unpickling
lmrcec66772010-06-22 01:55:50 +0000467 return (None, self.id, self.auto_close, self.echo, self.linesep)
468
469
470 def __del__(self):
471 if self.auto_close:
472 self.close()
lmrbbc9dd52009-07-22 20:33:47 +0000473
474
475 def _add_reader(self, reader):
476 """
477 Add a reader whose file descriptor can be obtained with _get_fd().
478 Should be called before __init__(). Intended for use by derived
479 classes.
480
481 @param reader: The name of the reader.
482 """
483 if not hasattr(self, "readers"):
484 self.readers = []
485 self.readers.append(reader)
486
487
488 def _add_close_hook(self, hook):
489 """
490 Add a close hook function to be called when close() is called.
491 The function will be called after the process terminates but before
492 final cleanup. Intended for use by derived classes.
493
494 @param hook: The hook function.
495 """
496 if not hasattr(self, "close_hooks"):
497 self.close_hooks = []
498 self.close_hooks.append(hook)
499
500
501 def _get_fd(self, reader):
502 """
503 Return an open file descriptor corresponding to the specified reader
504 pipe. If no such reader exists, or the pipe could not be opened,
505 return None. Intended for use by derived classes.
506
507 @param reader: The name of the reader.
508 """
509 return self.reader_fds.get(reader)
510
511
512 def get_id(self):
513 """
514 Return the instance's id attribute, which may be used to access the
515 process in the future.
516 """
517 return self.id
518
519
lmrfb151b52009-09-09 22:19:11 +0000520 def get_pid(self):
lmrbbc9dd52009-07-22 20:33:47 +0000521 """
lmrfb151b52009-09-09 22:19:11 +0000522 Return the PID of the process.
523
524 Note: this may be the PID of the shell process running the user given
525 command.
lmrbbc9dd52009-07-22 20:33:47 +0000526 """
527 try:
528 file = open(self.shell_pid_filename, "r")
529 pid = int(file.read())
530 file.close()
531 return pid
532 except:
533 return None
534
535
lmrbbc9dd52009-07-22 20:33:47 +0000536 def get_status(self):
537 """
538 Wait for the process to exit and return its exit status, or None
539 if the exit status is not available.
540 """
541 _wait(self.lock_server_running_filename)
542 try:
543 file = open(self.status_filename, "r")
544 status = int(file.read())
545 file.close()
546 return status
547 except:
548 return None
549
550
551 def get_output(self):
552 """
553 Return the STDOUT and STDERR output of the process so far.
554 """
555 try:
556 file = open(self.output_filename, "r")
557 output = file.read()
558 file.close()
559 return output
560 except:
561 return ""
562
563
564 def is_alive(self):
565 """
566 Return True if the process is running.
567 """
lmr5df99f32009-08-13 04:46:16 +0000568 return _locked(self.lock_server_running_filename)
lmrbbc9dd52009-07-22 20:33:47 +0000569
570
lmrea1b64d2009-09-09 22:14:09 +0000571 def close(self, sig=signal.SIGKILL):
lmrbbc9dd52009-07-22 20:33:47 +0000572 """
573 Kill the child process if it's alive and remove temporary files.
574
575 @param sig: The signal to send the process when attempting to kill it.
576 """
577 # Kill it if it's alive
578 if self.is_alive():
lmrfb151b52009-09-09 22:19:11 +0000579 kvm_utils.kill_process_tree(self.get_pid(), sig)
lmrbbc9dd52009-07-22 20:33:47 +0000580 # Wait for the server to exit
581 _wait(self.lock_server_running_filename)
582 # Call all cleanup routines
583 for hook in self.close_hooks:
lmr16063962009-10-14 10:27:59 +0000584 hook(self)
lmrbbc9dd52009-07-22 20:33:47 +0000585 # Close reader file descriptors
586 for fd in self.reader_fds.values():
587 try:
588 os.close(fd)
589 except:
590 pass
lmr04d5b012009-11-10 16:28:22 +0000591 self.reader_fds = {}
lmrbbc9dd52009-07-22 20:33:47 +0000592 # Remove all used files
593 for filename in (_get_filenames("/tmp/kvm_spawn", self.id) +
594 self.reader_filenames.values()):
595 try:
596 os.unlink(filename)
597 except OSError:
598 pass
599
600
601 def set_linesep(self, linesep):
602 """
603 Sets the line separator string (usually "\\n").
604
605 @param linesep: Line separator string.
606 """
607 self.linesep = linesep
608
609
610 def send(self, str=""):
611 """
612 Send a string to the child process.
613
614 @param str: String to send to the child process.
615 """
616 try:
617 fd = os.open(self.inpipe_filename, os.O_RDWR)
618 os.write(fd, str)
619 os.close(fd)
620 except:
621 pass
622
623
624 def sendline(self, str=""):
625 """
626 Send a string followed by a line separator to the child process.
627
628 @param str: String to send to the child process.
629 """
630 self.send(str + self.linesep)
631
632
lmree4338e2010-07-08 23:40:10 +0000633_thread_kill_requested = False
634
635def kill_tail_threads():
636 """
Eric Li7edb3042011-01-06 17:57:17 -0800637 Kill all Tail threads.
lmree4338e2010-07-08 23:40:10 +0000638
639 After calling this function no new threads should be started.
640 """
641 global _thread_kill_requested
642 _thread_kill_requested = True
643 for t in threading.enumerate():
644 if hasattr(t, "name") and t.name.startswith("tail_thread"):
645 t.join(10)
Eric Lie0493a42010-11-15 13:05:43 -0800646 _thread_kill_requested = False
lmree4338e2010-07-08 23:40:10 +0000647
648
Eric Li7edb3042011-01-06 17:57:17 -0800649class Tail(Spawn):
lmrbbc9dd52009-07-22 20:33:47 +0000650 """
651 This class runs a child process in the background and sends its output in
652 real time, line-by-line, to a callback function.
653
Eric Li7edb3042011-01-06 17:57:17 -0800654 See Spawn's docstring.
lmrbbc9dd52009-07-22 20:33:47 +0000655
656 This class uses a single pipe reader to read data in real time from the
657 child process and report it to a given callback function.
658 When the child process exits, its exit status is reported to an additional
659 callback function.
660
661 When this class is unpickled, it automatically resumes reporting output.
662 """
663
lmrcec66772010-06-22 01:55:50 +0000664 def __init__(self, command=None, id=None, auto_close=False, echo=False,
665 linesep="\n", termination_func=None, termination_params=(),
666 output_func=None, output_params=(), output_prefix=""):
lmrbbc9dd52009-07-22 20:33:47 +0000667 """
668 Initialize the class and run command as a child process.
669
670 @param command: Command to run, or None if accessing an already running
671 server.
672 @param id: ID of an already running server, if accessing a running
673 server, or None if starting a new one.
lmrcec66772010-06-22 01:55:50 +0000674 @param auto_close: If True, close() the instance automatically when its
675 reference count drops to zero (default False).
lmrbbc9dd52009-07-22 20:33:47 +0000676 @param echo: Boolean indicating whether echo should be initially
677 enabled for the pseudo terminal running the subprocess. This
678 parameter has an effect only when starting a new server.
679 @param linesep: Line separator to be appended to strings sent to the
680 child process by sendline().
681 @param termination_func: Function to call when the process exits. The
682 function must accept a single exit status parameter.
lmr4fe15ba2009-08-13 04:11:26 +0000683 @param termination_params: Parameters to send to termination_func
684 before the exit status.
lmrbbc9dd52009-07-22 20:33:47 +0000685 @param output_func: Function to call whenever a line of output is
686 available from the STDOUT or STDERR streams of the process.
687 The function must accept a single string parameter. The string
688 does not include the final newline.
lmr4fe15ba2009-08-13 04:11:26 +0000689 @param output_params: Parameters to send to output_func before the
690 output line.
lmrbbc9dd52009-07-22 20:33:47 +0000691 @param output_prefix: String to prepend to lines sent to output_func.
692 """
693 # Add a reader and a close hook
694 self._add_reader("tail")
Eric Li7edb3042011-01-06 17:57:17 -0800695 self._add_close_hook(Tail._join_thread)
lmrbbc9dd52009-07-22 20:33:47 +0000696
697 # Init the superclass
Eric Li7edb3042011-01-06 17:57:17 -0800698 Spawn.__init__(self, command, id, auto_close, echo, linesep)
lmrbbc9dd52009-07-22 20:33:47 +0000699
700 # Remember some attributes
701 self.termination_func = termination_func
lmr4fe15ba2009-08-13 04:11:26 +0000702 self.termination_params = termination_params
lmrbbc9dd52009-07-22 20:33:47 +0000703 self.output_func = output_func
lmr4fe15ba2009-08-13 04:11:26 +0000704 self.output_params = output_params
lmrbbc9dd52009-07-22 20:33:47 +0000705 self.output_prefix = output_prefix
706
707 # Start the thread in the background
lmrc07f3812009-10-14 10:27:04 +0000708 self.tail_thread = None
lmrc07f3812009-10-14 10:27:04 +0000709 if termination_func or output_func:
710 self._start_thread()
lmrbbc9dd52009-07-22 20:33:47 +0000711
712
713 def __getinitargs__(self):
Eric Li7edb3042011-01-06 17:57:17 -0800714 return Spawn.__getinitargs__(self) + (self.termination_func,
715 self.termination_params,
716 self.output_func,
717 self.output_params,
718 self.output_prefix)
lmrbbc9dd52009-07-22 20:33:47 +0000719
720
721 def set_termination_func(self, termination_func):
722 """
723 Set the termination_func attribute. See __init__() for details.
724
725 @param termination_func: Function to call when the process terminates.
726 Must take a single parameter -- the exit status.
727 """
728 self.termination_func = termination_func
lmrc07f3812009-10-14 10:27:04 +0000729 if termination_func and not self.tail_thread:
730 self._start_thread()
lmrbbc9dd52009-07-22 20:33:47 +0000731
732
lmr4fe15ba2009-08-13 04:11:26 +0000733 def set_termination_params(self, termination_params):
734 """
735 Set the termination_params attribute. See __init__() for details.
736
737 @param termination_params: Parameters to send to termination_func
738 before the exit status.
739 """
740 self.termination_params = termination_params
741
742
lmrbbc9dd52009-07-22 20:33:47 +0000743 def set_output_func(self, output_func):
744 """
745 Set the output_func attribute. See __init__() for details.
746
747 @param output_func: Function to call for each line of STDOUT/STDERR
748 output from the process. Must take a single string parameter.
749 """
750 self.output_func = output_func
lmrc07f3812009-10-14 10:27:04 +0000751 if output_func and not self.tail_thread:
752 self._start_thread()
lmrbbc9dd52009-07-22 20:33:47 +0000753
754
lmr4fe15ba2009-08-13 04:11:26 +0000755 def set_output_params(self, output_params):
756 """
757 Set the output_params attribute. See __init__() for details.
758
759 @param output_params: Parameters to send to output_func before the
760 output line.
761 """
762 self.output_params = output_params
763
764
lmrbbc9dd52009-07-22 20:33:47 +0000765 def set_output_prefix(self, output_prefix):
766 """
767 Set the output_prefix attribute. See __init__() for details.
768
769 @param output_prefix: String to pre-pend to each line sent to
770 output_func (see set_output_callback()).
771 """
772 self.output_prefix = output_prefix
773
774
775 def _tail(self):
776 def print_line(text):
777 # Pre-pend prefix and remove trailing whitespace
778 text = self.output_prefix + text.rstrip()
lmrcf668fe2010-06-22 02:07:37 +0000779 # Pass text to output_func
lmrbbc9dd52009-07-22 20:33:47 +0000780 try:
lmr4fe15ba2009-08-13 04:11:26 +0000781 params = self.output_params + (text,)
782 self.output_func(*params)
lmrbbc9dd52009-07-22 20:33:47 +0000783 except TypeError:
784 pass
785
lmrbbc9dd52009-07-22 20:33:47 +0000786 try:
lmree4338e2010-07-08 23:40:10 +0000787 fd = self._get_fd("tail")
788 buffer = ""
789 while True:
790 global _thread_kill_requested
791 if _thread_kill_requested:
792 return
793 try:
794 # See if there's any data to read from the pipe
795 r, w, x = select.select([fd], [], [], 0.05)
796 except:
797 break
798 if fd in r:
799 # Some data is available; read it
800 new_data = os.read(fd, 1024)
801 if not new_data:
802 break
803 buffer += new_data
804 # Send the output to output_func line by line
805 # (except for the last line)
806 if self.output_func:
807 lines = buffer.split("\n")
808 for line in lines[:-1]:
809 print_line(line)
810 # Leave only the last line
811 last_newline_index = buffer.rfind("\n")
812 buffer = buffer[last_newline_index+1:]
813 else:
814 # No output is available right now; flush the buffer
815 if buffer:
816 print_line(buffer)
817 buffer = ""
818 # The process terminated; print any remaining output
819 if buffer:
820 print_line(buffer)
821 # Get the exit status, print it and send it to termination_func
822 status = self.get_status()
823 if status is None:
824 return
825 print_line("(Process terminated with status %s)" % status)
826 try:
827 params = self.termination_params + (status,)
828 self.termination_func(*params)
829 except TypeError:
830 pass
831 finally:
832 self.tail_thread = None
lmrbbc9dd52009-07-22 20:33:47 +0000833
834
lmrc07f3812009-10-14 10:27:04 +0000835 def _start_thread(self):
lmree4338e2010-07-08 23:40:10 +0000836 self.tail_thread = threading.Thread(target=self._tail,
837 name="tail_thread_%s" % self.id)
lmrc07f3812009-10-14 10:27:04 +0000838 self.tail_thread.start()
839
840
lmrbbc9dd52009-07-22 20:33:47 +0000841 def _join_thread(self):
842 # Wait for the tail thread to exit
lmree4338e2010-07-08 23:40:10 +0000843 # (it's done this way because self.tail_thread may become None at any
844 # time)
845 t = self.tail_thread
846 if t:
847 t.join()
lmrbbc9dd52009-07-22 20:33:47 +0000848
849
Eric Li7edb3042011-01-06 17:57:17 -0800850class Expect(Tail):
lmrbbc9dd52009-07-22 20:33:47 +0000851 """
852 This class runs a child process in the background and provides expect-like
853 services.
854
Eric Li7edb3042011-01-06 17:57:17 -0800855 It also provides all of Tail's functionality.
lmrbbc9dd52009-07-22 20:33:47 +0000856 """
857
Eric Li7edb3042011-01-06 17:57:17 -0800858 def __init__(self, command=None, id=None, auto_close=True, echo=False,
lmrcec66772010-06-22 01:55:50 +0000859 linesep="\n", termination_func=None, termination_params=(),
860 output_func=None, output_params=(), output_prefix=""):
lmrbbc9dd52009-07-22 20:33:47 +0000861 """
862 Initialize the class and run command as a child process.
863
864 @param command: Command to run, or None if accessing an already running
865 server.
866 @param id: ID of an already running server, if accessing a running
867 server, or None if starting a new one.
lmrcec66772010-06-22 01:55:50 +0000868 @param auto_close: If True, close() the instance automatically when its
869 reference count drops to zero (default False).
lmrbbc9dd52009-07-22 20:33:47 +0000870 @param echo: Boolean indicating whether echo should be initially
871 enabled for the pseudo terminal running the subprocess. This
872 parameter has an effect only when starting a new server.
873 @param linesep: Line separator to be appended to strings sent to the
874 child process by sendline().
875 @param termination_func: Function to call when the process exits. The
876 function must accept a single exit status parameter.
lmr4fe15ba2009-08-13 04:11:26 +0000877 @param termination_params: Parameters to send to termination_func
878 before the exit status.
lmrbbc9dd52009-07-22 20:33:47 +0000879 @param output_func: Function to call whenever a line of output is
880 available from the STDOUT or STDERR streams of the process.
881 The function must accept a single string parameter. The string
882 does not include the final newline.
lmr4fe15ba2009-08-13 04:11:26 +0000883 @param output_params: Parameters to send to output_func before the
884 output line.
lmrbbc9dd52009-07-22 20:33:47 +0000885 @param output_prefix: String to prepend to lines sent to output_func.
886 """
887 # Add a reader
888 self._add_reader("expect")
889
890 # Init the superclass
Eric Li7edb3042011-01-06 17:57:17 -0800891 Tail.__init__(self, command, id, auto_close, echo, linesep,
892 termination_func, termination_params,
893 output_func, output_params, output_prefix)
lmrbbc9dd52009-07-22 20:33:47 +0000894
895
896 def __getinitargs__(self):
Eric Li7edb3042011-01-06 17:57:17 -0800897 return Tail.__getinitargs__(self)
lmrbbc9dd52009-07-22 20:33:47 +0000898
899
900 def read_nonblocking(self, timeout=None):
901 """
902 Read from child until there is nothing to read for timeout seconds.
903
904 @param timeout: Time (seconds) to wait before we give up reading from
905 the child process, or None to use the default value.
906 """
907 if timeout is None:
908 timeout = 0.1
909 fd = self._get_fd("expect")
910 data = ""
911 while True:
912 try:
913 r, w, x = select.select([fd], [], [], timeout)
914 except:
915 return data
916 if fd in r:
917 new_data = os.read(fd, 1024)
918 if not new_data:
919 return data
920 data += new_data
921 else:
922 return data
923
924
925 def match_patterns(self, str, patterns):
926 """
927 Match str against a list of patterns.
928
929 Return the index of the first pattern that matches a substring of str.
930 None and empty strings in patterns are ignored.
931 If no match is found, return None.
932
933 @param patterns: List of strings (regular expression patterns).
934 """
935 for i in range(len(patterns)):
936 if not patterns[i]:
937 continue
938 if re.search(patterns[i], str):
939 return i
940
941
942 def read_until_output_matches(self, patterns, filter=lambda x: x,
Eric Li7edb3042011-01-06 17:57:17 -0800943 timeout=60, internal_timeout=None,
lmrbbc9dd52009-07-22 20:33:47 +0000944 print_func=None):
945 """
946 Read using read_nonblocking until a match is found using match_patterns,
947 or until timeout expires. Before attempting to search for a match, the
948 data is filtered using the filter function provided.
949
950 @brief: Read from child using read_nonblocking until a pattern
951 matches.
952 @param patterns: List of strings (regular expression patterns)
953 @param filter: Function to apply to the data read from the child before
954 attempting to match it against the patterns (should take and
955 return a string)
956 @param timeout: The duration (in seconds) to wait until a match is
957 found
958 @param internal_timeout: The timeout to pass to read_nonblocking
959 @param print_func: A function to be used to print the data being read
960 (should take a string parameter)
Eric Li7edb3042011-01-06 17:57:17 -0800961 @return: Tuple containing the match index and the data read so far
962 @raise ExpectTimeoutError: Raised if timeout expires
963 @raise ExpectProcessTerminatedError: Raised if the child process
964 terminates while waiting for output
965 @raise ExpectError: Raised if an unknown error occurs
lmrbbc9dd52009-07-22 20:33:47 +0000966 """
lmrf48c5cc2009-10-05 19:22:49 +0000967 fd = self._get_fd("expect")
Eric Li7edb3042011-01-06 17:57:17 -0800968 o = ""
lmrbbc9dd52009-07-22 20:33:47 +0000969 end_time = time.time() + timeout
lmrf48c5cc2009-10-05 19:22:49 +0000970 while True:
lmr04d5b012009-11-10 16:28:22 +0000971 try:
972 r, w, x = select.select([fd], [], [],
973 max(0, end_time - time.time()))
974 except (select.error, TypeError):
975 break
Eric Li7edb3042011-01-06 17:57:17 -0800976 if not r:
977 raise ExpectTimeoutError(patterns, o)
lmrbbc9dd52009-07-22 20:33:47 +0000978 # Read data from child
Eric Li7edb3042011-01-06 17:57:17 -0800979 data = self.read_nonblocking(internal_timeout)
980 if not data:
981 break
lmrbbc9dd52009-07-22 20:33:47 +0000982 # Print it if necessary
Eric Li7edb3042011-01-06 17:57:17 -0800983 if print_func:
984 for line in data.splitlines():
lmrcf668fe2010-06-22 02:07:37 +0000985 print_func(line)
lmrbbc9dd52009-07-22 20:33:47 +0000986 # Look for patterns
Eric Li7edb3042011-01-06 17:57:17 -0800987 o += data
988 match = self.match_patterns(filter(o), patterns)
lmrbbc9dd52009-07-22 20:33:47 +0000989 if match is not None:
Eric Li7edb3042011-01-06 17:57:17 -0800990 return match, o
lmrbbc9dd52009-07-22 20:33:47 +0000991
Eric Li7edb3042011-01-06 17:57:17 -0800992 # Check if the child has terminated
993 if kvm_utils.wait_for(lambda: not self.is_alive(), 5, 0, 0.1):
994 raise ExpectProcessTerminatedError(patterns, self.get_status(), o)
995 else:
996 # This shouldn't happen
997 raise ExpectError(patterns, o)
lmrbbc9dd52009-07-22 20:33:47 +0000998
999
Eric Li7edb3042011-01-06 17:57:17 -08001000 def read_until_last_word_matches(self, patterns, timeout=60,
lmrbbc9dd52009-07-22 20:33:47 +00001001 internal_timeout=None, print_func=None):
1002 """
1003 Read using read_nonblocking until the last word of the output matches
1004 one of the patterns (using match_patterns), or until timeout expires.
1005
1006 @param patterns: A list of strings (regular expression patterns)
1007 @param timeout: The duration (in seconds) to wait until a match is
1008 found
1009 @param internal_timeout: The timeout to pass to read_nonblocking
1010 @param print_func: A function to be used to print the data being read
1011 (should take a string parameter)
Eric Li7edb3042011-01-06 17:57:17 -08001012 @return: A tuple containing the match index and the data read so far
1013 @raise ExpectTimeoutError: Raised if timeout expires
1014 @raise ExpectProcessTerminatedError: Raised if the child process
1015 terminates while waiting for output
1016 @raise ExpectError: Raised if an unknown error occurs
lmrbbc9dd52009-07-22 20:33:47 +00001017 """
1018 def get_last_word(str):
1019 if str:
1020 return str.split()[-1]
1021 else:
1022 return ""
1023
1024 return self.read_until_output_matches(patterns, get_last_word,
1025 timeout, internal_timeout,
1026 print_func)
1027
1028
Eric Li7edb3042011-01-06 17:57:17 -08001029 def read_until_last_line_matches(self, patterns, timeout=60,
lmrbbc9dd52009-07-22 20:33:47 +00001030 internal_timeout=None, print_func=None):
1031 """
1032 Read using read_nonblocking until the last non-empty line of the output
1033 matches one of the patterns (using match_patterns), or until timeout
1034 expires. Return a tuple containing the match index (or None if no match
1035 was found) and the data read so far.
1036
1037 @brief: Read using read_nonblocking until the last non-empty line
1038 matches a pattern.
1039
1040 @param patterns: A list of strings (regular expression patterns)
1041 @param timeout: The duration (in seconds) to wait until a match is
1042 found
1043 @param internal_timeout: The timeout to pass to read_nonblocking
1044 @param print_func: A function to be used to print the data being read
1045 (should take a string parameter)
Eric Li7edb3042011-01-06 17:57:17 -08001046 @return: A tuple containing the match index and the data read so far
1047 @raise ExpectTimeoutError: Raised if timeout expires
1048 @raise ExpectProcessTerminatedError: Raised if the child process
1049 terminates while waiting for output
1050 @raise ExpectError: Raised if an unknown error occurs
lmrbbc9dd52009-07-22 20:33:47 +00001051 """
1052 def get_last_nonempty_line(str):
1053 nonempty_lines = [l for l in str.splitlines() if l.strip()]
1054 if nonempty_lines:
1055 return nonempty_lines[-1]
1056 else:
1057 return ""
1058
1059 return self.read_until_output_matches(patterns, get_last_nonempty_line,
1060 timeout, internal_timeout,
1061 print_func)
1062
1063
Eric Li7edb3042011-01-06 17:57:17 -08001064class ShellSession(Expect):
lmrbbc9dd52009-07-22 20:33:47 +00001065 """
1066 This class runs a child process in the background. It it suited for
1067 processes that provide an interactive shell, such as SSH and Telnet.
1068
Eric Li7edb3042011-01-06 17:57:17 -08001069 It provides all services of Expect and Tail. In addition, it
lmrbbc9dd52009-07-22 20:33:47 +00001070 provides command running services, and a utility function to test the
1071 process for responsiveness.
1072 """
1073
lmrcec66772010-06-22 01:55:50 +00001074 def __init__(self, command=None, id=None, auto_close=True, echo=False,
1075 linesep="\n", termination_func=None, termination_params=(),
1076 output_func=None, output_params=(), output_prefix="",
lmrbbc9dd52009-07-22 20:33:47 +00001077 prompt=r"[\#\$]\s*$", status_test_command="echo $?"):
1078 """
1079 Initialize the class and run command as a child process.
1080
1081 @param command: Command to run, or None if accessing an already running
1082 server.
1083 @param id: ID of an already running server, if accessing a running
1084 server, or None if starting a new one.
lmrcec66772010-06-22 01:55:50 +00001085 @param auto_close: If True, close() the instance automatically when its
1086 reference count drops to zero (default True).
lmrbbc9dd52009-07-22 20:33:47 +00001087 @param echo: Boolean indicating whether echo should be initially
1088 enabled for the pseudo terminal running the subprocess. This
1089 parameter has an effect only when starting a new server.
1090 @param linesep: Line separator to be appended to strings sent to the
1091 child process by sendline().
1092 @param termination_func: Function to call when the process exits. The
1093 function must accept a single exit status parameter.
lmr4fe15ba2009-08-13 04:11:26 +00001094 @param termination_params: Parameters to send to termination_func
1095 before the exit status.
lmrbbc9dd52009-07-22 20:33:47 +00001096 @param output_func: Function to call whenever a line of output is
1097 available from the STDOUT or STDERR streams of the process.
1098 The function must accept a single string parameter. The string
1099 does not include the final newline.
lmr4fe15ba2009-08-13 04:11:26 +00001100 @param output_params: Parameters to send to output_func before the
1101 output line.
lmrbbc9dd52009-07-22 20:33:47 +00001102 @param output_prefix: String to prepend to lines sent to output_func.
1103 @param prompt: Regular expression describing the shell's prompt line.
1104 @param status_test_command: Command to be used for getting the last
1105 exit status of commands run inside the shell (used by
Eric Li7edb3042011-01-06 17:57:17 -08001106 cmd_status_output() and friends).
lmrbbc9dd52009-07-22 20:33:47 +00001107 """
1108 # Init the superclass
Eric Li7edb3042011-01-06 17:57:17 -08001109 Expect.__init__(self, command, id, auto_close, echo, linesep,
1110 termination_func, termination_params,
1111 output_func, output_params, output_prefix)
lmrbbc9dd52009-07-22 20:33:47 +00001112
1113 # Remember some attributes
1114 self.prompt = prompt
1115 self.status_test_command = status_test_command
1116
1117
1118 def __getinitargs__(self):
Eric Li7edb3042011-01-06 17:57:17 -08001119 return Expect.__getinitargs__(self) + (self.prompt,
1120 self.status_test_command)
lmrbbc9dd52009-07-22 20:33:47 +00001121
1122
1123 def set_prompt(self, prompt):
1124 """
1125 Set the prompt attribute for later use by read_up_to_prompt.
1126
1127 @param: String that describes the prompt contents.
1128 """
1129 self.prompt = prompt
1130
1131
1132 def set_status_test_command(self, status_test_command):
1133 """
1134 Set the command to be sent in order to get the last exit status.
1135
1136 @param status_test_command: Command that will be sent to get the last
1137 exit status.
1138 """
1139 self.status_test_command = status_test_command
1140
1141
1142 def is_responsive(self, timeout=5.0):
1143 """
1144 Return True if the process responds to STDIN/terminal input.
1145
1146 Send a newline to the child process (e.g. SSH or Telnet) and read some
1147 output using read_nonblocking().
1148 If all is OK, some output should be available (e.g. the shell prompt).
1149 In that case return True. Otherwise return False.
1150
1151 @param timeout: Time duration to wait before the process is considered
1152 unresponsive.
1153 """
1154 # Read all output that's waiting to be read, to make sure the output
1155 # we read next is in response to the newline sent
lmr59b98db2009-10-05 19:11:21 +00001156 self.read_nonblocking(timeout=0)
lmrbbc9dd52009-07-22 20:33:47 +00001157 # Send a newline
1158 self.sendline()
1159 # Wait up to timeout seconds for some output from the child
1160 end_time = time.time() + timeout
1161 while time.time() < end_time:
1162 time.sleep(0.5)
1163 if self.read_nonblocking(timeout=0).strip():
1164 return True
1165 # No output -- report unresponsive
1166 return False
1167
1168
Eric Li7edb3042011-01-06 17:57:17 -08001169 def read_up_to_prompt(self, timeout=60, internal_timeout=None,
lmrbbc9dd52009-07-22 20:33:47 +00001170 print_func=None):
1171 """
1172 Read using read_nonblocking until the last non-empty line of the output
1173 matches the prompt regular expression set by set_prompt, or until
1174 timeout expires.
1175
1176 @brief: Read using read_nonblocking until the last non-empty line
1177 matches the prompt.
1178
1179 @param timeout: The duration (in seconds) to wait until a match is
1180 found
1181 @param internal_timeout: The timeout to pass to read_nonblocking
1182 @param print_func: A function to be used to print the data being
1183 read (should take a string parameter)
1184
Eric Li7edb3042011-01-06 17:57:17 -08001185 @return: The data read so far
1186 @raise ExpectTimeoutError: Raised if timeout expires
1187 @raise ExpectProcessTerminatedError: Raised if the shell process
1188 terminates while waiting for output
1189 @raise ExpectError: Raised if an unknown error occurs
lmrbbc9dd52009-07-22 20:33:47 +00001190 """
Eric Li7edb3042011-01-06 17:57:17 -08001191 m, o = self.read_until_last_line_matches([self.prompt], timeout,
1192 internal_timeout, print_func)
1193 return o
lmrbbc9dd52009-07-22 20:33:47 +00001194
1195
Eric Li7edb3042011-01-06 17:57:17 -08001196 def cmd_output(self, cmd, timeout=60, internal_timeout=None,
1197 print_func=None):
lmrbbc9dd52009-07-22 20:33:47 +00001198 """
Eric Li7edb3042011-01-06 17:57:17 -08001199 Send a command and return its output.
lmrbbc9dd52009-07-22 20:33:47 +00001200
Eric Li7edb3042011-01-06 17:57:17 -08001201 @param cmd: Command to send (must not contain newline characters)
1202 @param timeout: The duration (in seconds) to wait for the prompt to
1203 return
lmrbbc9dd52009-07-22 20:33:47 +00001204 @param internal_timeout: The timeout to pass to read_nonblocking
1205 @param print_func: A function to be used to print the data being read
1206 (should take a string parameter)
1207
Eric Li7edb3042011-01-06 17:57:17 -08001208 @return: The output of cmd
1209 @raise ShellTimeoutError: Raised if timeout expires
1210 @raise ShellProcessTerminatedError: Raised if the shell process
1211 terminates while waiting for output
1212 @raise ShellError: Raised if an unknown error occurs
lmrbbc9dd52009-07-22 20:33:47 +00001213 """
1214 def remove_command_echo(str, cmd):
1215 if str and str.splitlines()[0] == cmd:
1216 str = "".join(str.splitlines(True)[1:])
1217 return str
1218
1219 def remove_last_nonempty_line(str):
1220 return "".join(str.rstrip().splitlines(True)[:-1])
1221
Eric Li7edb3042011-01-06 17:57:17 -08001222 logging.debug("Sending command: %s" % cmd)
lmr59b98db2009-10-05 19:11:21 +00001223 self.read_nonblocking(timeout=0)
Eric Li7edb3042011-01-06 17:57:17 -08001224 self.sendline(cmd)
1225 try:
1226 o = self.read_up_to_prompt(timeout, internal_timeout, print_func)
1227 except ExpectError, e:
1228 o = remove_command_echo(e.output, cmd)
1229 if isinstance(e, ExpectTimeoutError):
1230 raise ShellTimeoutError(cmd, o)
1231 elif isinstance(e, ExpectProcessTerminatedError):
1232 raise ShellProcessTerminatedError(cmd, e.status, o)
1233 else:
1234 raise ShellError(cmd, o)
lmrbbc9dd52009-07-22 20:33:47 +00001235
Eric Li7edb3042011-01-06 17:57:17 -08001236 # Remove the echoed command and the final shell prompt
1237 return remove_last_nonempty_line(remove_command_echo(o, cmd))
lmrbbc9dd52009-07-22 20:33:47 +00001238
Eric Li7edb3042011-01-06 17:57:17 -08001239
1240 def cmd_status_output(self, cmd, timeout=60, internal_timeout=None,
1241 print_func=None):
1242 """
1243 Send a command and return its exit status and output.
1244
1245 @param cmd: Command to send (must not contain newline characters)
1246 @param timeout: The duration (in seconds) to wait for the prompt to
1247 return
1248 @param internal_timeout: The timeout to pass to read_nonblocking
1249 @param print_func: A function to be used to print the data being read
1250 (should take a string parameter)
1251
1252 @return: A tuple (status, output) where status is the exit status and
1253 output is the output of cmd
1254 @raise ShellTimeoutError: Raised if timeout expires
1255 @raise ShellProcessTerminatedError: Raised if the shell process
1256 terminates while waiting for output
1257 @raise ShellStatusError: Raised if the exit status cannot be obtained
1258 @raise ShellError: Raised if an unknown error occurs
1259 """
1260 o = self.cmd_output(cmd, timeout, internal_timeout, print_func)
1261 try:
1262 # Send the 'echo $?' (or equivalent) command to get the exit status
1263 s = self.cmd_output(self.status_test_command, 10, internal_timeout)
1264 except ShellError:
1265 raise ShellStatusError(cmd, o)
1266
lmrbbc9dd52009-07-22 20:33:47 +00001267 # Get the first line consisting of digits only
Eric Li7edb3042011-01-06 17:57:17 -08001268 digit_lines = [l for l in s.splitlines() if l.strip().isdigit()]
1269 if digit_lines:
1270 return int(digit_lines[0].strip()), o
1271 else:
1272 raise ShellStatusError(cmd, o)
lmrbbc9dd52009-07-22 20:33:47 +00001273
1274
Eric Li7edb3042011-01-06 17:57:17 -08001275 def cmd_status(self, cmd, timeout=60, internal_timeout=None,
1276 print_func=None):
lmrbbc9dd52009-07-22 20:33:47 +00001277 """
1278 Send a command and return its exit status.
1279
Eric Li7edb3042011-01-06 17:57:17 -08001280 @param cmd: Command to send (must not contain newline characters)
1281 @param timeout: The duration (in seconds) to wait for the prompt to
1282 return
lmrbbc9dd52009-07-22 20:33:47 +00001283 @param internal_timeout: The timeout to pass to read_nonblocking
1284 @param print_func: A function to be used to print the data being read
1285 (should take a string parameter)
1286
Eric Li7edb3042011-01-06 17:57:17 -08001287 @return: The exit status of cmd
1288 @raise ShellTimeoutError: Raised if timeout expires
1289 @raise ShellProcessTerminatedError: Raised if the shell process
1290 terminates while waiting for output
1291 @raise ShellStatusError: Raised if the exit status cannot be obtained
1292 @raise ShellError: Raised if an unknown error occurs
lmrbbc9dd52009-07-22 20:33:47 +00001293 """
Eric Li7edb3042011-01-06 17:57:17 -08001294 s, o = self.cmd_status_output(cmd, timeout, internal_timeout,
1295 print_func)
1296 return s
lmrbbc9dd52009-07-22 20:33:47 +00001297
1298
Eric Li7edb3042011-01-06 17:57:17 -08001299 def cmd(self, cmd, timeout=60, internal_timeout=None, print_func=None):
1300 """
1301 Send a command and return its output. If the command's exit status is
1302 nonzero, raise an exception.
1303
1304 @param cmd: Command to send (must not contain newline characters)
1305 @param timeout: The duration (in seconds) to wait for the prompt to
1306 return
1307 @param internal_timeout: The timeout to pass to read_nonblocking
1308 @param print_func: A function to be used to print the data being read
1309 (should take a string parameter)
1310
1311 @return: The output of cmd
1312 @raise ShellTimeoutError: Raised if timeout expires
1313 @raise ShellProcessTerminatedError: Raised if the shell process
1314 terminates while waiting for output
1315 @raise ShellError: Raised if the exit status cannot be obtained or if
1316 an unknown error occurs
1317 @raise ShellStatusError: Raised if the exit status cannot be obtained
1318 @raise ShellError: Raised if an unknown error occurs
1319 @raise ShellCmdError: Raised if the exit status is nonzero
1320 """
1321 s, o = self.cmd_status_output(cmd, timeout, internal_timeout,
1322 print_func)
1323 if s != 0:
1324 raise ShellCmdError(cmd, s, o)
1325 return o
1326
1327
1328 def get_command_output(self, cmd, timeout=60, internal_timeout=None,
lmrbbc9dd52009-07-22 20:33:47 +00001329 print_func=None):
1330 """
Eric Li7edb3042011-01-06 17:57:17 -08001331 Alias for cmd_output() for backward compatibility.
lmrbbc9dd52009-07-22 20:33:47 +00001332 """
Eric Li7edb3042011-01-06 17:57:17 -08001333 return self.cmd_output(cmd, timeout, internal_timeout, print_func)
1334
1335
1336 def get_command_status_output(self, cmd, timeout=60, internal_timeout=None,
1337 print_func=None):
1338 """
1339 Alias for cmd_status_output() for backward compatibility.
1340 """
1341 return self.cmd_status_output(cmd, timeout, internal_timeout,
1342 print_func)
1343
1344
1345 def get_command_status(self, cmd, timeout=60, internal_timeout=None,
1346 print_func=None):
1347 """
1348 Alias for cmd_status() for backward compatibility.
1349 """
1350 return self.cmd_status(cmd, timeout, internal_timeout, print_func)