blob: 730f20ec863bd0f431609c42e1859469325fb1df [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
851 end_time = time.time() + timeout
852 while time.time() < end_time:
853 # Read data from child
854 newdata = self.read_nonblocking(internal_timeout)
855 # Print it if necessary
856 if print_func and newdata:
857 str = newdata
858 if str.endswith("\n"):
859 str = str[:-1]
860 for line in str.split("\n"):
861 print_func(line.decode("utf-8", "replace"))
862 data += newdata
863
864 done = False
865 # Look for patterns
866 match = self.match_patterns(filter(data), patterns)
867 if match is not None:
868 done = True
869 # Check if child has died
870 if not self.is_alive():
871 logging.debug("Process terminated with status %s" % self.get_status())
872 done = True
873 # Are we done?
874 if done: break
875
876 # Print some debugging info
877 if match is None and (self.is_alive() or self.get_status() != 0):
878 logging.debug("Timeout elapsed or process terminated. Output:" +
879 kvm_utils.format_str_for_message(data.strip()))
880
881 return (match, data)
882
883
884 def read_until_last_word_matches(self, patterns, timeout=30.0,
885 internal_timeout=None, print_func=None):
886 """
887 Read using read_nonblocking until the last word of the output matches
888 one of the patterns (using match_patterns), or until timeout expires.
889
890 @param patterns: A list of strings (regular expression patterns)
891 @param timeout: The duration (in seconds) to wait until a match is
892 found
893 @param internal_timeout: The timeout to pass to read_nonblocking
894 @param print_func: A function to be used to print the data being read
895 (should take a string parameter)
896 @return: A tuple containing the match index (or None if no match was
897 found) and the data read so far.
898 """
899 def get_last_word(str):
900 if str:
901 return str.split()[-1]
902 else:
903 return ""
904
905 return self.read_until_output_matches(patterns, get_last_word,
906 timeout, internal_timeout,
907 print_func)
908
909
910 def read_until_last_line_matches(self, patterns, timeout=30.0,
911 internal_timeout=None, print_func=None):
912 """
913 Read using read_nonblocking until the last non-empty line of the output
914 matches one of the patterns (using match_patterns), or until timeout
915 expires. Return a tuple containing the match index (or None if no match
916 was found) and the data read so far.
917
918 @brief: Read using read_nonblocking until the last non-empty line
919 matches a pattern.
920
921 @param patterns: A list of strings (regular expression patterns)
922 @param timeout: The duration (in seconds) to wait until a match is
923 found
924 @param internal_timeout: The timeout to pass to read_nonblocking
925 @param print_func: A function to be used to print the data being read
926 (should take a string parameter)
927 """
928 def get_last_nonempty_line(str):
929 nonempty_lines = [l for l in str.splitlines() if l.strip()]
930 if nonempty_lines:
931 return nonempty_lines[-1]
932 else:
933 return ""
934
935 return self.read_until_output_matches(patterns, get_last_nonempty_line,
936 timeout, internal_timeout,
937 print_func)
938
939
940class kvm_shell_session(kvm_expect):
941 """
942 This class runs a child process in the background. It it suited for
943 processes that provide an interactive shell, such as SSH and Telnet.
944
945 It provides all services of kvm_expect and kvm_tail. In addition, it
946 provides command running services, and a utility function to test the
947 process for responsiveness.
948 """
949
950 def __init__(self, command=None, id=None, echo=False, linesep="\n",
lmr4fe15ba2009-08-13 04:11:26 +0000951 termination_func=None, termination_params=(),
952 output_func=None, output_params=(),
953 output_prefix="",
lmrbbc9dd52009-07-22 20:33:47 +0000954 prompt=r"[\#\$]\s*$", status_test_command="echo $?"):
955 """
956 Initialize the class and run command as a child process.
957
958 @param command: Command to run, or None if accessing an already running
959 server.
960 @param id: ID of an already running server, if accessing a running
961 server, or None if starting a new one.
962 @param echo: Boolean indicating whether echo should be initially
963 enabled for the pseudo terminal running the subprocess. This
964 parameter has an effect only when starting a new server.
965 @param linesep: Line separator to be appended to strings sent to the
966 child process by sendline().
967 @param termination_func: Function to call when the process exits. The
968 function must accept a single exit status parameter.
lmr4fe15ba2009-08-13 04:11:26 +0000969 @param termination_params: Parameters to send to termination_func
970 before the exit status.
lmrbbc9dd52009-07-22 20:33:47 +0000971 @param output_func: Function to call whenever a line of output is
972 available from the STDOUT or STDERR streams of the process.
973 The function must accept a single string parameter. The string
974 does not include the final newline.
lmr4fe15ba2009-08-13 04:11:26 +0000975 @param output_params: Parameters to send to output_func before the
976 output line.
lmrbbc9dd52009-07-22 20:33:47 +0000977 @param output_prefix: String to prepend to lines sent to output_func.
978 @param prompt: Regular expression describing the shell's prompt line.
979 @param status_test_command: Command to be used for getting the last
980 exit status of commands run inside the shell (used by
981 get_command_status_output() and friends).
982 """
983 # Init the superclass
984 kvm_expect.__init__(self, command, id, echo, linesep,
lmr4fe15ba2009-08-13 04:11:26 +0000985 termination_func, termination_params,
986 output_func, output_params, output_prefix)
lmrbbc9dd52009-07-22 20:33:47 +0000987
988 # Remember some attributes
989 self.prompt = prompt
990 self.status_test_command = status_test_command
991
992
993 def __getinitargs__(self):
994 return kvm_expect.__getinitargs__(self) + (self.prompt,
995 self.status_test_command)
996
997
998 def set_prompt(self, prompt):
999 """
1000 Set the prompt attribute for later use by read_up_to_prompt.
1001
1002 @param: String that describes the prompt contents.
1003 """
1004 self.prompt = prompt
1005
1006
1007 def set_status_test_command(self, status_test_command):
1008 """
1009 Set the command to be sent in order to get the last exit status.
1010
1011 @param status_test_command: Command that will be sent to get the last
1012 exit status.
1013 """
1014 self.status_test_command = status_test_command
1015
1016
1017 def is_responsive(self, timeout=5.0):
1018 """
1019 Return True if the process responds to STDIN/terminal input.
1020
1021 Send a newline to the child process (e.g. SSH or Telnet) and read some
1022 output using read_nonblocking().
1023 If all is OK, some output should be available (e.g. the shell prompt).
1024 In that case return True. Otherwise return False.
1025
1026 @param timeout: Time duration to wait before the process is considered
1027 unresponsive.
1028 """
1029 # Read all output that's waiting to be read, to make sure the output
1030 # we read next is in response to the newline sent
lmr59b98db2009-10-05 19:11:21 +00001031 self.read_nonblocking(timeout=0)
lmrbbc9dd52009-07-22 20:33:47 +00001032 # Send a newline
1033 self.sendline()
1034 # Wait up to timeout seconds for some output from the child
1035 end_time = time.time() + timeout
1036 while time.time() < end_time:
1037 time.sleep(0.5)
1038 if self.read_nonblocking(timeout=0).strip():
1039 return True
1040 # No output -- report unresponsive
1041 return False
1042
1043
1044 def read_up_to_prompt(self, timeout=30.0, internal_timeout=None,
1045 print_func=None):
1046 """
1047 Read using read_nonblocking until the last non-empty line of the output
1048 matches the prompt regular expression set by set_prompt, or until
1049 timeout expires.
1050
1051 @brief: Read using read_nonblocking until the last non-empty line
1052 matches the prompt.
1053
1054 @param timeout: The duration (in seconds) to wait until a match is
1055 found
1056 @param internal_timeout: The timeout to pass to read_nonblocking
1057 @param print_func: A function to be used to print the data being
1058 read (should take a string parameter)
1059
1060 @return: A tuple containing True/False indicating whether the prompt
1061 was found, and the data read so far.
1062 """
1063 (match, output) = self.read_until_last_line_matches([self.prompt],
1064 timeout,
1065 internal_timeout,
1066 print_func)
1067 return (match is not None, output)
1068
1069
1070 def get_command_status_output(self, command, timeout=30.0,
1071 internal_timeout=None, print_func=None):
1072 """
1073 Send a command and return its exit status and output.
1074
1075 @param command: Command to send (must not contain newline characters)
1076 @param timeout: The duration (in seconds) to wait until a match is
1077 found
1078 @param internal_timeout: The timeout to pass to read_nonblocking
1079 @param print_func: A function to be used to print the data being read
1080 (should take a string parameter)
1081
1082 @return: A tuple (status, output) where status is the exit status or
1083 None if no exit status is available (e.g. timeout elapsed), and
1084 output is the output of command.
1085 """
1086 def remove_command_echo(str, cmd):
1087 if str and str.splitlines()[0] == cmd:
1088 str = "".join(str.splitlines(True)[1:])
1089 return str
1090
1091 def remove_last_nonempty_line(str):
1092 return "".join(str.rstrip().splitlines(True)[:-1])
1093
1094 # Print some debugging info
1095 logging.debug("Sending command: %s" % command)
1096
1097 # Read everything that's waiting to be read
lmr59b98db2009-10-05 19:11:21 +00001098 self.read_nonblocking(timeout=0)
lmrbbc9dd52009-07-22 20:33:47 +00001099
1100 # Send the command and get its output
1101 self.sendline(command)
1102 (match, output) = self.read_up_to_prompt(timeout, internal_timeout,
1103 print_func)
1104 # Remove the echoed command from the output
1105 output = remove_command_echo(output, command)
1106 # If the prompt was not found, return the output so far
1107 if not match:
1108 return (None, output)
1109 # Remove the final shell prompt from the output
1110 output = remove_last_nonempty_line(output)
1111
1112 # Send the 'echo ...' command to get the last exit status
1113 self.sendline(self.status_test_command)
1114 (match, status) = self.read_up_to_prompt(10.0, internal_timeout)
1115 if not match:
1116 return (None, output)
1117 status = remove_command_echo(status, self.status_test_command)
1118 status = remove_last_nonempty_line(status)
1119 # Get the first line consisting of digits only
1120 digit_lines = [l for l in status.splitlines() if l.strip().isdigit()]
1121 if not digit_lines:
1122 return (None, output)
1123 status = int(digit_lines[0].strip())
1124
1125 # Print some debugging info
1126 if status != 0:
1127 logging.debug("Command failed; status: %d, output:%s", status,
1128 kvm_utils.format_str_for_message(output.strip()))
1129
1130 return (status, output)
1131
1132
1133 def get_command_status(self, command, timeout=30.0, internal_timeout=None,
1134 print_func=None):
1135 """
1136 Send a command and return its exit status.
1137
1138 @param command: Command to send
1139 @param timeout: The duration (in seconds) to wait until a match is
1140 found
1141 @param internal_timeout: The timeout to pass to read_nonblocking
1142 @param print_func: A function to be used to print the data being read
1143 (should take a string parameter)
1144
1145 @return: Exit status or None if no exit status is available (e.g.
1146 timeout elapsed).
1147 """
1148 (status, output) = self.get_command_status_output(command, timeout,
1149 internal_timeout,
1150 print_func)
1151 return status
1152
1153
1154 def get_command_output(self, command, timeout=30.0, internal_timeout=None,
1155 print_func=None):
1156 """
1157 Send a command and return its output.
1158
1159 @param command: Command to send
1160 @param timeout: The duration (in seconds) to wait until a match is
1161 found
1162 @param internal_timeout: The timeout to pass to read_nonblocking
1163 @param print_func: A function to be used to print the data being read
1164 (should take a string parameter)
1165 """
1166 (status, output) = self.get_command_status_output(command, timeout,
1167 internal_timeout,
1168 print_func)
1169 return output