blob: 2ac062a8003918b126b7f418b9bf21766be2ef82 [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
192def run_bg(command, termination_func=None, output_func=None, output_prefix="",
193 timeout=1.0):
194 """
195 Run command as a subprocess. Call output_func with each line of output
196 from the subprocess (prefixed by output_prefix). Call termination_func
197 when the subprocess terminates. Return when timeout expires or when the
198 subprocess exits -- whichever occurs first.
199
200 @brief: Run a subprocess in the background and collect its output and
201 exit status.
202
203 @param command: The shell command to execute
204 @param termination_func: A function to call when the process terminates
205 (should take an integer exit status parameter)
206 @param output_func: A function to call with each line of output from
207 the subprocess (should take a string parameter)
208 @param output_prefix: A string to pre-pend to each line of the output,
209 before passing it to stdout_func
210 @param timeout: Time duration (in seconds) to wait for the subprocess to
211 terminate before returning
212
213 @return: A kvm_tail object.
214 """
215 process = kvm_tail(command=command,
216 termination_func=termination_func,
217 output_func=output_func,
218 output_prefix=output_prefix)
219
220 end_time = time.time() + timeout
221 while time.time() < end_time and process.is_alive():
222 time.sleep(0.1)
223
224 return process
225
226
227def run_fg(command, output_func=None, output_prefix="", timeout=1.0):
228 """
229 Run command as a subprocess. Call output_func with each line of output
230 from the subprocess (prefixed by prefix). Return when timeout expires or
231 when the subprocess exits -- whichever occurs first. If timeout expires
232 and the subprocess is still running, kill it before returning.
233
234 @brief: Run a subprocess in the foreground and collect its output and
235 exit status.
236
237 @param command: The shell command to execute
238 @param output_func: A function to call with each line of output from
239 the subprocess (should take a string parameter)
240 @param output_prefix: A string to pre-pend to each line of the output,
241 before passing it to stdout_func
242 @param timeout: Time duration (in seconds) to wait for the subprocess to
243 terminate before killing it and returning
244
245 @return: A 2-tuple containing the exit status of the process and its
246 STDOUT/STDERR output. If timeout expires before the process
247 terminates, the returned status is None.
248 """
249 process = run_bg(command, None, output_func, output_prefix, timeout)
250 output = process.get_output()
251 if process.is_alive():
252 status = None
253 else:
254 status = process.get_status()
255 process.close()
256 return (status, output)
257
258
lmrbbc9dd52009-07-22 20:33:47 +0000259class kvm_spawn:
260 """
261 This class is used for spawning and controlling a child process.
262
263 A new instance of this class can either run a new server (a small Python
264 program that reads output from the child process and reports it to the
265 client and to a text file) or attach to an already running server.
266 When a server is started it runs the child process.
267 The server writes output from the child's STDOUT and STDERR to a text file.
268 The text file can be accessed at any time using get_output().
269 In addition, the server opens as many pipes as requested by the client and
270 writes the output to them.
271 The pipes are requested and accessed by classes derived from kvm_spawn.
272 These pipes are referred to as "readers".
273 The server also receives input from the client and sends it to the child
274 process.
275 An instance of this class can be pickled. Every derived class is
276 responsible for restoring its own state by properly defining
277 __getinitargs__().
278
279 The first named pipe is used by _tail(), a function that runs in the
280 background and reports new output from the child as it is produced.
281 The second named pipe is used by a set of functions that read and parse
282 output as requested by the user in an interactive manner, similar to
283 pexpect.
284 When unpickled it automatically
285 resumes _tail() if needed.
286 """
287
288 def __init__(self, command=None, id=None, echo=False, linesep="\n"):
289 """
290 Initialize the class and run command as a child process.
291
292 @param command: Command to run, or None if accessing an already running
293 server.
294 @param id: ID of an already running server, if accessing a running
295 server, or None if starting a new one.
296 @param echo: Boolean indicating whether echo should be initially
297 enabled for the pseudo terminal running the subprocess. This
298 parameter has an effect only when starting a new server.
299 @param linesep: Line separator to be appended to strings sent to the
300 child process by sendline().
301 """
302 self.id = id or kvm_utils.generate_random_string(8)
303
304 # Define filenames for communication with server
305 base_dir = "/tmp/kvm_spawn"
306 try:
307 os.makedirs(base_dir)
308 except:
309 pass
310 (self.shell_pid_filename,
311 self.status_filename,
312 self.output_filename,
313 self.inpipe_filename,
314 self.lock_server_running_filename,
315 self.lock_client_starting_filename) = _get_filenames(base_dir,
316 self.id)
317
318 # Remember some attributes
319 self.echo = echo
320 self.linesep = linesep
321
322 # Make sure the 'readers' and 'close_hooks' attributes exist
323 if not hasattr(self, "readers"):
324 self.readers = []
325 if not hasattr(self, "close_hooks"):
326 self.close_hooks = []
327
328 # Define the reader filenames
329 self.reader_filenames = dict(
330 (reader, _get_reader_filename(base_dir, self.id, reader))
331 for reader in self.readers)
332
333 # Let the server know a client intends to open some pipes;
334 # if the executed command terminates quickly, the server will wait for
335 # the client to release the lock before exiting
336 lock_client_starting = _lock(self.lock_client_starting_filename)
337
338 # Start the server (which runs the command)
339 if command:
340 sub = subprocess.Popen("python %s" % __file__,
341 shell=True,
342 stdin=subprocess.PIPE,
343 stdout=subprocess.PIPE,
344 stderr=subprocess.STDOUT)
345 # Send parameters to the server
346 sub.stdin.write("%s\n" % self.id)
347 sub.stdin.write("%s\n" % echo)
348 sub.stdin.write("%s\n" % ",".join(self.readers))
349 sub.stdin.write("%s\n" % command)
350 # Wait for the server to complete its initialization
lmrb8f53d62009-07-27 13:29:17 +0000351 while not "Server %s ready" % self.id in sub.stdout.readline():
352 pass
lmrbbc9dd52009-07-22 20:33:47 +0000353
354 # Open the reading pipes
355 self.reader_fds = {}
356 try:
357 assert(_locked(self.lock_server_running_filename))
358 for reader, filename in self.reader_filenames.items():
359 self.reader_fds[reader] = os.open(filename, os.O_RDONLY)
360 except:
361 pass
362
363 # Allow the server to continue
364 _unlock(lock_client_starting)
365
366
367 # The following two functions are defined to make sure the state is set
368 # exclusively by the constructor call as specified in __getinitargs__().
369
370 def __getstate__(self):
371 pass
372
373
374 def __setstate__(self, state):
375 pass
376
377
378 def __getinitargs__(self):
379 # Save some information when pickling -- will be passed to the
380 # constructor upon unpickling
381 return (None, self.id, self.echo, self.linesep)
382
383
384 def _add_reader(self, reader):
385 """
386 Add a reader whose file descriptor can be obtained with _get_fd().
387 Should be called before __init__(). Intended for use by derived
388 classes.
389
390 @param reader: The name of the reader.
391 """
392 if not hasattr(self, "readers"):
393 self.readers = []
394 self.readers.append(reader)
395
396
397 def _add_close_hook(self, hook):
398 """
399 Add a close hook function to be called when close() is called.
400 The function will be called after the process terminates but before
401 final cleanup. Intended for use by derived classes.
402
403 @param hook: The hook function.
404 """
405 if not hasattr(self, "close_hooks"):
406 self.close_hooks = []
407 self.close_hooks.append(hook)
408
409
410 def _get_fd(self, reader):
411 """
412 Return an open file descriptor corresponding to the specified reader
413 pipe. If no such reader exists, or the pipe could not be opened,
414 return None. Intended for use by derived classes.
415
416 @param reader: The name of the reader.
417 """
418 return self.reader_fds.get(reader)
419
420
421 def get_id(self):
422 """
423 Return the instance's id attribute, which may be used to access the
424 process in the future.
425 """
426 return self.id
427
428
lmrfb151b52009-09-09 22:19:11 +0000429 def get_pid(self):
lmrbbc9dd52009-07-22 20:33:47 +0000430 """
lmrfb151b52009-09-09 22:19:11 +0000431 Return the PID of the process.
432
433 Note: this may be the PID of the shell process running the user given
434 command.
lmrbbc9dd52009-07-22 20:33:47 +0000435 """
436 try:
437 file = open(self.shell_pid_filename, "r")
438 pid = int(file.read())
439 file.close()
440 return pid
441 except:
442 return None
443
444
lmrbbc9dd52009-07-22 20:33:47 +0000445 def get_status(self):
446 """
447 Wait for the process to exit and return its exit status, or None
448 if the exit status is not available.
449 """
450 _wait(self.lock_server_running_filename)
451 try:
452 file = open(self.status_filename, "r")
453 status = int(file.read())
454 file.close()
455 return status
456 except:
457 return None
458
459
460 def get_output(self):
461 """
462 Return the STDOUT and STDERR output of the process so far.
463 """
464 try:
465 file = open(self.output_filename, "r")
466 output = file.read()
467 file.close()
468 return output
469 except:
470 return ""
471
472
473 def is_alive(self):
474 """
475 Return True if the process is running.
476 """
lmr5df99f32009-08-13 04:46:16 +0000477 return _locked(self.lock_server_running_filename)
lmrbbc9dd52009-07-22 20:33:47 +0000478
479
lmrea1b64d2009-09-09 22:14:09 +0000480 def close(self, sig=signal.SIGKILL):
lmrbbc9dd52009-07-22 20:33:47 +0000481 """
482 Kill the child process if it's alive and remove temporary files.
483
484 @param sig: The signal to send the process when attempting to kill it.
485 """
486 # Kill it if it's alive
487 if self.is_alive():
lmrfb151b52009-09-09 22:19:11 +0000488 kvm_utils.kill_process_tree(self.get_pid(), sig)
lmrbbc9dd52009-07-22 20:33:47 +0000489 # Wait for the server to exit
490 _wait(self.lock_server_running_filename)
491 # Call all cleanup routines
492 for hook in self.close_hooks:
493 hook()
494 # Close reader file descriptors
495 for fd in self.reader_fds.values():
496 try:
497 os.close(fd)
498 except:
499 pass
500 # Remove all used files
501 for filename in (_get_filenames("/tmp/kvm_spawn", self.id) +
502 self.reader_filenames.values()):
503 try:
504 os.unlink(filename)
505 except OSError:
506 pass
507
508
509 def set_linesep(self, linesep):
510 """
511 Sets the line separator string (usually "\\n").
512
513 @param linesep: Line separator string.
514 """
515 self.linesep = linesep
516
517
518 def send(self, str=""):
519 """
520 Send a string to the child process.
521
522 @param str: String to send to the child process.
523 """
524 try:
525 fd = os.open(self.inpipe_filename, os.O_RDWR)
526 os.write(fd, str)
527 os.close(fd)
528 except:
529 pass
530
531
532 def sendline(self, str=""):
533 """
534 Send a string followed by a line separator to the child process.
535
536 @param str: String to send to the child process.
537 """
538 self.send(str + self.linesep)
539
540
541class kvm_tail(kvm_spawn):
542 """
543 This class runs a child process in the background and sends its output in
544 real time, line-by-line, to a callback function.
545
546 See kvm_spawn's docstring.
547
548 This class uses a single pipe reader to read data in real time from the
549 child process and report it to a given callback function.
550 When the child process exits, its exit status is reported to an additional
551 callback function.
552
553 When this class is unpickled, it automatically resumes reporting output.
554 """
555
556 def __init__(self, command=None, id=None, echo=False, linesep="\n",
lmr4fe15ba2009-08-13 04:11:26 +0000557 termination_func=None, termination_params=(),
558 output_func=None, output_params=(),
559 output_prefix=""):
lmrbbc9dd52009-07-22 20:33:47 +0000560 """
561 Initialize the class and run command as a child process.
562
563 @param command: Command to run, or None if accessing an already running
564 server.
565 @param id: ID of an already running server, if accessing a running
566 server, or None if starting a new one.
567 @param echo: Boolean indicating whether echo should be initially
568 enabled for the pseudo terminal running the subprocess. This
569 parameter has an effect only when starting a new server.
570 @param linesep: Line separator to be appended to strings sent to the
571 child process by sendline().
572 @param termination_func: Function to call when the process exits. The
573 function must accept a single exit status parameter.
lmr4fe15ba2009-08-13 04:11:26 +0000574 @param termination_params: Parameters to send to termination_func
575 before the exit status.
lmrbbc9dd52009-07-22 20:33:47 +0000576 @param output_func: Function to call whenever a line of output is
577 available from the STDOUT or STDERR streams of the process.
578 The function must accept a single string parameter. The string
579 does not include the final newline.
lmr4fe15ba2009-08-13 04:11:26 +0000580 @param output_params: Parameters to send to output_func before the
581 output line.
lmrbbc9dd52009-07-22 20:33:47 +0000582 @param output_prefix: String to prepend to lines sent to output_func.
583 """
584 # Add a reader and a close hook
585 self._add_reader("tail")
586 self._add_close_hook(self._join_thread)
587
588 # Init the superclass
589 kvm_spawn.__init__(self, command, id, echo, linesep)
590
591 # Remember some attributes
592 self.termination_func = termination_func
lmr4fe15ba2009-08-13 04:11:26 +0000593 self.termination_params = termination_params
lmrbbc9dd52009-07-22 20:33:47 +0000594 self.output_func = output_func
lmr4fe15ba2009-08-13 04:11:26 +0000595 self.output_params = output_params
lmrbbc9dd52009-07-22 20:33:47 +0000596 self.output_prefix = output_prefix
597
598 # Start the thread in the background
lmra4197002009-08-13 05:00:51 +0000599 self.__thread_kill_requested = False
lmrbbc9dd52009-07-22 20:33:47 +0000600 self.tail_thread = threading.Thread(None, self._tail)
601 self.tail_thread.start()
602
603
604 def __getinitargs__(self):
605 return kvm_spawn.__getinitargs__(self) + (self.termination_func,
lmr4fe15ba2009-08-13 04:11:26 +0000606 self.termination_params,
lmrbbc9dd52009-07-22 20:33:47 +0000607 self.output_func,
lmr4fe15ba2009-08-13 04:11:26 +0000608 self.output_params,
lmrbbc9dd52009-07-22 20:33:47 +0000609 self.output_prefix)
610
611
612 def set_termination_func(self, termination_func):
613 """
614 Set the termination_func attribute. See __init__() for details.
615
616 @param termination_func: Function to call when the process terminates.
617 Must take a single parameter -- the exit status.
618 """
619 self.termination_func = termination_func
620
621
lmr4fe15ba2009-08-13 04:11:26 +0000622 def set_termination_params(self, termination_params):
623 """
624 Set the termination_params attribute. See __init__() for details.
625
626 @param termination_params: Parameters to send to termination_func
627 before the exit status.
628 """
629 self.termination_params = termination_params
630
631
lmrbbc9dd52009-07-22 20:33:47 +0000632 def set_output_func(self, output_func):
633 """
634 Set the output_func attribute. See __init__() for details.
635
636 @param output_func: Function to call for each line of STDOUT/STDERR
637 output from the process. Must take a single string parameter.
638 """
639 self.output_func = output_func
640
641
lmr4fe15ba2009-08-13 04:11:26 +0000642 def set_output_params(self, output_params):
643 """
644 Set the output_params attribute. See __init__() for details.
645
646 @param output_params: Parameters to send to output_func before the
647 output line.
648 """
649 self.output_params = output_params
650
651
lmrbbc9dd52009-07-22 20:33:47 +0000652 def set_output_prefix(self, output_prefix):
653 """
654 Set the output_prefix attribute. See __init__() for details.
655
656 @param output_prefix: String to pre-pend to each line sent to
657 output_func (see set_output_callback()).
658 """
659 self.output_prefix = output_prefix
660
661
lmra4197002009-08-13 05:00:51 +0000662 def kill_tail_thread(self):
663 """
664 Stop the tailing thread which calls output_func() and
665 termination_func().
666 """
667 self.__thread_kill_requested = True
668 self._join_thread()
669
670
lmrbbc9dd52009-07-22 20:33:47 +0000671 def _tail(self):
672 def print_line(text):
673 # Pre-pend prefix and remove trailing whitespace
674 text = self.output_prefix + text.rstrip()
675 # Sanitize text
676 text = text.decode("utf-8", "replace")
677 # Pass it to output_func
678 try:
lmr4fe15ba2009-08-13 04:11:26 +0000679 params = self.output_params + (text,)
680 self.output_func(*params)
lmrbbc9dd52009-07-22 20:33:47 +0000681 except TypeError:
682 pass
683
684 fd = self._get_fd("tail")
685 buffer = ""
686 while True:
lmra4197002009-08-13 05:00:51 +0000687 if self.__thread_kill_requested:
688 return
lmrbbc9dd52009-07-22 20:33:47 +0000689 try:
690 # See if there's any data to read from the pipe
691 r, w, x = select.select([fd], [], [], 0.05)
692 except:
693 break
694 if fd in r:
695 # Some data is available; read it
696 new_data = os.read(fd, 1024)
697 if not new_data:
698 break
699 buffer += new_data
700 # Send the output to output_func line by line
701 # (except for the last line)
702 if self.output_func:
703 lines = buffer.split("\n")
704 for line in lines[:-1]:
705 print_line(line)
706 # Leave only the last line
707 last_newline_index = buffer.rfind("\n")
708 buffer = buffer[last_newline_index+1:]
709 else:
710 # No output is available right now; flush the buffer
711 if buffer:
712 print_line(buffer)
713 buffer = ""
714 # The process terminated; print any remaining output
715 if buffer:
716 print_line(buffer)
717 # Get the exit status, print it and send it to termination_func
718 status = self.get_status()
719 if status is None:
720 return
721 print_line("(Process terminated with status %s)" % status)
722 try:
lmr4fe15ba2009-08-13 04:11:26 +0000723 params = self.termination_params + (status,)
724 self.termination_func(*params)
lmrbbc9dd52009-07-22 20:33:47 +0000725 except TypeError:
726 pass
727
728
729 def _join_thread(self):
730 # Wait for the tail thread to exit
731 if self.tail_thread:
732 self.tail_thread.join()
733
734
735class kvm_expect(kvm_tail):
736 """
737 This class runs a child process in the background and provides expect-like
738 services.
739
740 It also provides all of kvm_tail's functionality.
741 """
742
743 def __init__(self, command=None, id=None, echo=False, linesep="\n",
lmr4fe15ba2009-08-13 04:11:26 +0000744 termination_func=None, termination_params=(),
745 output_func=None, output_params=(),
746 output_prefix=""):
lmrbbc9dd52009-07-22 20:33:47 +0000747 """
748 Initialize the class and run command as a child process.
749
750 @param command: Command to run, or None if accessing an already running
751 server.
752 @param id: ID of an already running server, if accessing a running
753 server, or None if starting a new one.
754 @param echo: Boolean indicating whether echo should be initially
755 enabled for the pseudo terminal running the subprocess. This
756 parameter has an effect only when starting a new server.
757 @param linesep: Line separator to be appended to strings sent to the
758 child process by sendline().
759 @param termination_func: Function to call when the process exits. The
760 function must accept a single exit status parameter.
lmr4fe15ba2009-08-13 04:11:26 +0000761 @param termination_params: Parameters to send to termination_func
762 before the exit status.
lmrbbc9dd52009-07-22 20:33:47 +0000763 @param output_func: Function to call whenever a line of output is
764 available from the STDOUT or STDERR streams of the process.
765 The function must accept a single string parameter. The string
766 does not include the final newline.
lmr4fe15ba2009-08-13 04:11:26 +0000767 @param output_params: Parameters to send to output_func before the
768 output line.
lmrbbc9dd52009-07-22 20:33:47 +0000769 @param output_prefix: String to prepend to lines sent to output_func.
770 """
771 # Add a reader
772 self._add_reader("expect")
773
774 # Init the superclass
775 kvm_tail.__init__(self, command, id, echo, linesep,
lmr4fe15ba2009-08-13 04:11:26 +0000776 termination_func, termination_params,
777 output_func, output_params, output_prefix)
lmrbbc9dd52009-07-22 20:33:47 +0000778
779
780 def __getinitargs__(self):
781 return kvm_tail.__getinitargs__(self)
782
783
784 def read_nonblocking(self, timeout=None):
785 """
786 Read from child until there is nothing to read for timeout seconds.
787
788 @param timeout: Time (seconds) to wait before we give up reading from
789 the child process, or None to use the default value.
790 """
791 if timeout is None:
792 timeout = 0.1
793 fd = self._get_fd("expect")
794 data = ""
795 while True:
796 try:
797 r, w, x = select.select([fd], [], [], timeout)
798 except:
799 return data
800 if fd in r:
801 new_data = os.read(fd, 1024)
802 if not new_data:
803 return data
804 data += new_data
805 else:
806 return data
807
808
809 def match_patterns(self, str, patterns):
810 """
811 Match str against a list of patterns.
812
813 Return the index of the first pattern that matches a substring of str.
814 None and empty strings in patterns are ignored.
815 If no match is found, return None.
816
817 @param patterns: List of strings (regular expression patterns).
818 """
819 for i in range(len(patterns)):
820 if not patterns[i]:
821 continue
822 if re.search(patterns[i], str):
823 return i
824
825
826 def read_until_output_matches(self, patterns, filter=lambda x: x,
827 timeout=30.0, internal_timeout=None,
828 print_func=None):
829 """
830 Read using read_nonblocking until a match is found using match_patterns,
831 or until timeout expires. Before attempting to search for a match, the
832 data is filtered using the filter function provided.
833
834 @brief: Read from child using read_nonblocking until a pattern
835 matches.
836 @param patterns: List of strings (regular expression patterns)
837 @param filter: Function to apply to the data read from the child before
838 attempting to match it against the patterns (should take and
839 return a string)
840 @param timeout: The duration (in seconds) to wait until a match is
841 found
842 @param internal_timeout: The timeout to pass to read_nonblocking
843 @param print_func: A function to be used to print the data being read
844 (should take a string parameter)
845 @return: Tuple containing the match index (or None if no match was
846 found) and the data read so far.
847 """
848 match = None
849 data = ""
850
lmrf48c5cc2009-10-05 19:22:49 +0000851 fd = self._get_fd("expect")
lmrbbc9dd52009-07-22 20:33:47 +0000852 end_time = time.time() + timeout
lmrf48c5cc2009-10-05 19:22:49 +0000853 while True:
854 r, w, x = select.select([fd], [], [],
855 max(0, end_time - time.time()))
856 if fd not in r: break
lmrbbc9dd52009-07-22 20:33:47 +0000857 # Read data from child
858 newdata = self.read_nonblocking(internal_timeout)
859 # Print it if necessary
860 if print_func and newdata:
861 str = newdata
862 if str.endswith("\n"):
863 str = str[:-1]
864 for line in str.split("\n"):
865 print_func(line.decode("utf-8", "replace"))
866 data += newdata
867
868 done = False
869 # Look for patterns
870 match = self.match_patterns(filter(data), patterns)
871 if match is not None:
872 done = True
873 # Check if child has died
874 if not self.is_alive():
lmrf48c5cc2009-10-05 19:22:49 +0000875 logging.debug("Process terminated with status %s" %
876 self.get_status())
lmrbbc9dd52009-07-22 20:33:47 +0000877 done = True
878 # Are we done?
879 if done: break
880
881 # Print some debugging info
882 if match is None and (self.is_alive() or self.get_status() != 0):
883 logging.debug("Timeout elapsed or process terminated. Output:" +
884 kvm_utils.format_str_for_message(data.strip()))
885
886 return (match, data)
887
888
889 def read_until_last_word_matches(self, patterns, timeout=30.0,
890 internal_timeout=None, print_func=None):
891 """
892 Read using read_nonblocking until the last word of the output matches
893 one of the patterns (using match_patterns), or until timeout expires.
894
895 @param patterns: A list of strings (regular expression patterns)
896 @param timeout: The duration (in seconds) to wait until a match is
897 found
898 @param internal_timeout: The timeout to pass to read_nonblocking
899 @param print_func: A function to be used to print the data being read
900 (should take a string parameter)
901 @return: A tuple containing the match index (or None if no match was
902 found) and the data read so far.
903 """
904 def get_last_word(str):
905 if str:
906 return str.split()[-1]
907 else:
908 return ""
909
910 return self.read_until_output_matches(patterns, get_last_word,
911 timeout, internal_timeout,
912 print_func)
913
914
915 def read_until_last_line_matches(self, patterns, timeout=30.0,
916 internal_timeout=None, print_func=None):
917 """
918 Read using read_nonblocking until the last non-empty line of the output
919 matches one of the patterns (using match_patterns), or until timeout
920 expires. Return a tuple containing the match index (or None if no match
921 was found) and the data read so far.
922
923 @brief: Read using read_nonblocking until the last non-empty line
924 matches a pattern.
925
926 @param patterns: A list of strings (regular expression patterns)
927 @param timeout: The duration (in seconds) to wait until a match is
928 found
929 @param internal_timeout: The timeout to pass to read_nonblocking
930 @param print_func: A function to be used to print the data being read
931 (should take a string parameter)
932 """
933 def get_last_nonempty_line(str):
934 nonempty_lines = [l for l in str.splitlines() if l.strip()]
935 if nonempty_lines:
936 return nonempty_lines[-1]
937 else:
938 return ""
939
940 return self.read_until_output_matches(patterns, get_last_nonempty_line,
941 timeout, internal_timeout,
942 print_func)
943
944
945class kvm_shell_session(kvm_expect):
946 """
947 This class runs a child process in the background. It it suited for
948 processes that provide an interactive shell, such as SSH and Telnet.
949
950 It provides all services of kvm_expect and kvm_tail. In addition, it
951 provides command running services, and a utility function to test the
952 process for responsiveness.
953 """
954
955 def __init__(self, command=None, id=None, echo=False, linesep="\n",
lmr4fe15ba2009-08-13 04:11:26 +0000956 termination_func=None, termination_params=(),
957 output_func=None, output_params=(),
958 output_prefix="",
lmrbbc9dd52009-07-22 20:33:47 +0000959 prompt=r"[\#\$]\s*$", status_test_command="echo $?"):
960 """
961 Initialize the class and run command as a child process.
962
963 @param command: Command to run, or None if accessing an already running
964 server.
965 @param id: ID of an already running server, if accessing a running
966 server, or None if starting a new one.
967 @param echo: Boolean indicating whether echo should be initially
968 enabled for the pseudo terminal running the subprocess. This
969 parameter has an effect only when starting a new server.
970 @param linesep: Line separator to be appended to strings sent to the
971 child process by sendline().
972 @param termination_func: Function to call when the process exits. The
973 function must accept a single exit status parameter.
lmr4fe15ba2009-08-13 04:11:26 +0000974 @param termination_params: Parameters to send to termination_func
975 before the exit status.
lmrbbc9dd52009-07-22 20:33:47 +0000976 @param output_func: Function to call whenever a line of output is
977 available from the STDOUT or STDERR streams of the process.
978 The function must accept a single string parameter. The string
979 does not include the final newline.
lmr4fe15ba2009-08-13 04:11:26 +0000980 @param output_params: Parameters to send to output_func before the
981 output line.
lmrbbc9dd52009-07-22 20:33:47 +0000982 @param output_prefix: String to prepend to lines sent to output_func.
983 @param prompt: Regular expression describing the shell's prompt line.
984 @param status_test_command: Command to be used for getting the last
985 exit status of commands run inside the shell (used by
986 get_command_status_output() and friends).
987 """
988 # Init the superclass
989 kvm_expect.__init__(self, command, id, echo, linesep,
lmr4fe15ba2009-08-13 04:11:26 +0000990 termination_func, termination_params,
991 output_func, output_params, output_prefix)
lmrbbc9dd52009-07-22 20:33:47 +0000992
993 # Remember some attributes
994 self.prompt = prompt
995 self.status_test_command = status_test_command
996
997
998 def __getinitargs__(self):
999 return kvm_expect.__getinitargs__(self) + (self.prompt,
1000 self.status_test_command)
1001
1002
1003 def set_prompt(self, prompt):
1004 """
1005 Set the prompt attribute for later use by read_up_to_prompt.
1006
1007 @param: String that describes the prompt contents.
1008 """
1009 self.prompt = prompt
1010
1011
1012 def set_status_test_command(self, status_test_command):
1013 """
1014 Set the command to be sent in order to get the last exit status.
1015
1016 @param status_test_command: Command that will be sent to get the last
1017 exit status.
1018 """
1019 self.status_test_command = status_test_command
1020
1021
1022 def is_responsive(self, timeout=5.0):
1023 """
1024 Return True if the process responds to STDIN/terminal input.
1025
1026 Send a newline to the child process (e.g. SSH or Telnet) and read some
1027 output using read_nonblocking().
1028 If all is OK, some output should be available (e.g. the shell prompt).
1029 In that case return True. Otherwise return False.
1030
1031 @param timeout: Time duration to wait before the process is considered
1032 unresponsive.
1033 """
1034 # Read all output that's waiting to be read, to make sure the output
1035 # we read next is in response to the newline sent
lmr59b98db2009-10-05 19:11:21 +00001036 self.read_nonblocking(timeout=0)
lmrbbc9dd52009-07-22 20:33:47 +00001037 # Send a newline
1038 self.sendline()
1039 # Wait up to timeout seconds for some output from the child
1040 end_time = time.time() + timeout
1041 while time.time() < end_time:
1042 time.sleep(0.5)
1043 if self.read_nonblocking(timeout=0).strip():
1044 return True
1045 # No output -- report unresponsive
1046 return False
1047
1048
1049 def read_up_to_prompt(self, timeout=30.0, internal_timeout=None,
1050 print_func=None):
1051 """
1052 Read using read_nonblocking until the last non-empty line of the output
1053 matches the prompt regular expression set by set_prompt, or until
1054 timeout expires.
1055
1056 @brief: Read using read_nonblocking until the last non-empty line
1057 matches the prompt.
1058
1059 @param timeout: The duration (in seconds) to wait until a match is
1060 found
1061 @param internal_timeout: The timeout to pass to read_nonblocking
1062 @param print_func: A function to be used to print the data being
1063 read (should take a string parameter)
1064
1065 @return: A tuple containing True/False indicating whether the prompt
1066 was found, and the data read so far.
1067 """
1068 (match, output) = self.read_until_last_line_matches([self.prompt],
1069 timeout,
1070 internal_timeout,
1071 print_func)
1072 return (match is not None, output)
1073
1074
1075 def get_command_status_output(self, command, timeout=30.0,
1076 internal_timeout=None, print_func=None):
1077 """
1078 Send a command and return its exit status and output.
1079
1080 @param command: Command to send (must not contain newline characters)
1081 @param timeout: The duration (in seconds) to wait until a match is
1082 found
1083 @param internal_timeout: The timeout to pass to read_nonblocking
1084 @param print_func: A function to be used to print the data being read
1085 (should take a string parameter)
1086
1087 @return: A tuple (status, output) where status is the exit status or
1088 None if no exit status is available (e.g. timeout elapsed), and
1089 output is the output of command.
1090 """
1091 def remove_command_echo(str, cmd):
1092 if str and str.splitlines()[0] == cmd:
1093 str = "".join(str.splitlines(True)[1:])
1094 return str
1095
1096 def remove_last_nonempty_line(str):
1097 return "".join(str.rstrip().splitlines(True)[:-1])
1098
1099 # Print some debugging info
1100 logging.debug("Sending command: %s" % command)
1101
1102 # Read everything that's waiting to be read
lmr59b98db2009-10-05 19:11:21 +00001103 self.read_nonblocking(timeout=0)
lmrbbc9dd52009-07-22 20:33:47 +00001104
1105 # Send the command and get its output
1106 self.sendline(command)
1107 (match, output) = self.read_up_to_prompt(timeout, internal_timeout,
1108 print_func)
1109 # Remove the echoed command from the output
1110 output = remove_command_echo(output, command)
1111 # If the prompt was not found, return the output so far
1112 if not match:
1113 return (None, output)
1114 # Remove the final shell prompt from the output
1115 output = remove_last_nonempty_line(output)
1116
1117 # Send the 'echo ...' command to get the last exit status
1118 self.sendline(self.status_test_command)
1119 (match, status) = self.read_up_to_prompt(10.0, internal_timeout)
1120 if not match:
1121 return (None, output)
1122 status = remove_command_echo(status, self.status_test_command)
1123 status = remove_last_nonempty_line(status)
1124 # Get the first line consisting of digits only
1125 digit_lines = [l for l in status.splitlines() if l.strip().isdigit()]
1126 if not digit_lines:
1127 return (None, output)
1128 status = int(digit_lines[0].strip())
1129
1130 # Print some debugging info
1131 if status != 0:
1132 logging.debug("Command failed; status: %d, output:%s", status,
1133 kvm_utils.format_str_for_message(output.strip()))
1134
1135 return (status, output)
1136
1137
1138 def get_command_status(self, command, timeout=30.0, internal_timeout=None,
1139 print_func=None):
1140 """
1141 Send a command and return its exit status.
1142
1143 @param command: Command to send
1144 @param timeout: The duration (in seconds) to wait until a match is
1145 found
1146 @param internal_timeout: The timeout to pass to read_nonblocking
1147 @param print_func: A function to be used to print the data being read
1148 (should take a string parameter)
1149
1150 @return: Exit status or None if no exit status is available (e.g.
1151 timeout elapsed).
1152 """
1153 (status, output) = self.get_command_status_output(command, timeout,
1154 internal_timeout,
1155 print_func)
1156 return status
1157
1158
1159 def get_command_output(self, command, timeout=30.0, internal_timeout=None,
1160 print_func=None):
1161 """
1162 Send a command and return its output.
1163
1164 @param command: Command to send
1165 @param timeout: The duration (in seconds) to wait until a match is
1166 found
1167 @param internal_timeout: The timeout to pass to read_nonblocking
1168 @param print_func: A function to be used to print the data being read
1169 (should take a string parameter)
1170 """
1171 (status, output) = self.get_command_status_output(command, timeout,
1172 internal_timeout,
1173 print_func)
1174 return output