blob: a6253154ed8333f7189f820d0cd8074507cf3307 [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:
lmr16063962009-10-14 10:27:59 +0000493 hook(self)
lmrbbc9dd52009-07-22 20:33:47 +0000494 # 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")
lmr16063962009-10-14 10:27:59 +0000586 self._add_close_hook(kvm_tail._join_thread)
lmrbbc9dd52009-07-22 20:33:47 +0000587
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
lmrc07f3812009-10-14 10:27:04 +0000599 self.tail_thread = None
lmra4197002009-08-13 05:00:51 +0000600 self.__thread_kill_requested = False
lmrc07f3812009-10-14 10:27:04 +0000601 if termination_func or output_func:
602 self._start_thread()
lmrbbc9dd52009-07-22 20:33:47 +0000603
604
605 def __getinitargs__(self):
606 return kvm_spawn.__getinitargs__(self) + (self.termination_func,
lmr4fe15ba2009-08-13 04:11:26 +0000607 self.termination_params,
lmrbbc9dd52009-07-22 20:33:47 +0000608 self.output_func,
lmr4fe15ba2009-08-13 04:11:26 +0000609 self.output_params,
lmrbbc9dd52009-07-22 20:33:47 +0000610 self.output_prefix)
611
612
613 def set_termination_func(self, termination_func):
614 """
615 Set the termination_func attribute. See __init__() for details.
616
617 @param termination_func: Function to call when the process terminates.
618 Must take a single parameter -- the exit status.
619 """
620 self.termination_func = termination_func
lmrc07f3812009-10-14 10:27:04 +0000621 if termination_func and not self.tail_thread:
622 self._start_thread()
lmrbbc9dd52009-07-22 20:33:47 +0000623
624
lmr4fe15ba2009-08-13 04:11:26 +0000625 def set_termination_params(self, termination_params):
626 """
627 Set the termination_params attribute. See __init__() for details.
628
629 @param termination_params: Parameters to send to termination_func
630 before the exit status.
631 """
632 self.termination_params = termination_params
633
634
lmrbbc9dd52009-07-22 20:33:47 +0000635 def set_output_func(self, output_func):
636 """
637 Set the output_func attribute. See __init__() for details.
638
639 @param output_func: Function to call for each line of STDOUT/STDERR
640 output from the process. Must take a single string parameter.
641 """
642 self.output_func = output_func
lmrc07f3812009-10-14 10:27:04 +0000643 if output_func and not self.tail_thread:
644 self._start_thread()
lmrbbc9dd52009-07-22 20:33:47 +0000645
646
lmr4fe15ba2009-08-13 04:11:26 +0000647 def set_output_params(self, output_params):
648 """
649 Set the output_params attribute. See __init__() for details.
650
651 @param output_params: Parameters to send to output_func before the
652 output line.
653 """
654 self.output_params = output_params
655
656
lmrbbc9dd52009-07-22 20:33:47 +0000657 def set_output_prefix(self, output_prefix):
658 """
659 Set the output_prefix attribute. See __init__() for details.
660
661 @param output_prefix: String to pre-pend to each line sent to
662 output_func (see set_output_callback()).
663 """
664 self.output_prefix = output_prefix
665
666
lmra4197002009-08-13 05:00:51 +0000667 def kill_tail_thread(self):
668 """
669 Stop the tailing thread which calls output_func() and
670 termination_func().
671 """
672 self.__thread_kill_requested = True
673 self._join_thread()
674
675
lmrbbc9dd52009-07-22 20:33:47 +0000676 def _tail(self):
677 def print_line(text):
678 # Pre-pend prefix and remove trailing whitespace
679 text = self.output_prefix + text.rstrip()
680 # Sanitize text
681 text = text.decode("utf-8", "replace")
682 # Pass it to output_func
683 try:
lmr4fe15ba2009-08-13 04:11:26 +0000684 params = self.output_params + (text,)
685 self.output_func(*params)
lmrbbc9dd52009-07-22 20:33:47 +0000686 except TypeError:
687 pass
688
689 fd = self._get_fd("tail")
690 buffer = ""
691 while True:
lmra4197002009-08-13 05:00:51 +0000692 if self.__thread_kill_requested:
693 return
lmrbbc9dd52009-07-22 20:33:47 +0000694 try:
695 # See if there's any data to read from the pipe
696 r, w, x = select.select([fd], [], [], 0.05)
697 except:
698 break
699 if fd in r:
700 # Some data is available; read it
701 new_data = os.read(fd, 1024)
702 if not new_data:
703 break
704 buffer += new_data
705 # Send the output to output_func line by line
706 # (except for the last line)
707 if self.output_func:
708 lines = buffer.split("\n")
709 for line in lines[:-1]:
710 print_line(line)
711 # Leave only the last line
712 last_newline_index = buffer.rfind("\n")
713 buffer = buffer[last_newline_index+1:]
714 else:
715 # No output is available right now; flush the buffer
716 if buffer:
717 print_line(buffer)
718 buffer = ""
719 # The process terminated; print any remaining output
720 if buffer:
721 print_line(buffer)
722 # Get the exit status, print it and send it to termination_func
723 status = self.get_status()
724 if status is None:
725 return
726 print_line("(Process terminated with status %s)" % status)
727 try:
lmr4fe15ba2009-08-13 04:11:26 +0000728 params = self.termination_params + (status,)
729 self.termination_func(*params)
lmrbbc9dd52009-07-22 20:33:47 +0000730 except TypeError:
731 pass
732
733
lmrc07f3812009-10-14 10:27:04 +0000734 def _start_thread(self):
735 self.tail_thread = threading.Thread(None, self._tail)
736 self.tail_thread.start()
737
738
lmrbbc9dd52009-07-22 20:33:47 +0000739 def _join_thread(self):
740 # Wait for the tail thread to exit
741 if self.tail_thread:
742 self.tail_thread.join()
743
744
745class kvm_expect(kvm_tail):
746 """
747 This class runs a child process in the background and provides expect-like
748 services.
749
750 It also provides all of kvm_tail's functionality.
751 """
752
753 def __init__(self, command=None, id=None, echo=False, linesep="\n",
lmr4fe15ba2009-08-13 04:11:26 +0000754 termination_func=None, termination_params=(),
755 output_func=None, output_params=(),
756 output_prefix=""):
lmrbbc9dd52009-07-22 20:33:47 +0000757 """
758 Initialize the class and run command as a child process.
759
760 @param command: Command to run, or None if accessing an already running
761 server.
762 @param id: ID of an already running server, if accessing a running
763 server, or None if starting a new one.
764 @param echo: Boolean indicating whether echo should be initially
765 enabled for the pseudo terminal running the subprocess. This
766 parameter has an effect only when starting a new server.
767 @param linesep: Line separator to be appended to strings sent to the
768 child process by sendline().
769 @param termination_func: Function to call when the process exits. The
770 function must accept a single exit status parameter.
lmr4fe15ba2009-08-13 04:11:26 +0000771 @param termination_params: Parameters to send to termination_func
772 before the exit status.
lmrbbc9dd52009-07-22 20:33:47 +0000773 @param output_func: Function to call whenever a line of output is
774 available from the STDOUT or STDERR streams of the process.
775 The function must accept a single string parameter. The string
776 does not include the final newline.
lmr4fe15ba2009-08-13 04:11:26 +0000777 @param output_params: Parameters to send to output_func before the
778 output line.
lmrbbc9dd52009-07-22 20:33:47 +0000779 @param output_prefix: String to prepend to lines sent to output_func.
780 """
781 # Add a reader
782 self._add_reader("expect")
783
784 # Init the superclass
785 kvm_tail.__init__(self, command, id, echo, linesep,
lmr4fe15ba2009-08-13 04:11:26 +0000786 termination_func, termination_params,
787 output_func, output_params, output_prefix)
lmrbbc9dd52009-07-22 20:33:47 +0000788
789
790 def __getinitargs__(self):
791 return kvm_tail.__getinitargs__(self)
792
793
794 def read_nonblocking(self, timeout=None):
795 """
796 Read from child until there is nothing to read for timeout seconds.
797
798 @param timeout: Time (seconds) to wait before we give up reading from
799 the child process, or None to use the default value.
800 """
801 if timeout is None:
802 timeout = 0.1
803 fd = self._get_fd("expect")
804 data = ""
805 while True:
806 try:
807 r, w, x = select.select([fd], [], [], timeout)
808 except:
809 return data
810 if fd in r:
811 new_data = os.read(fd, 1024)
812 if not new_data:
813 return data
814 data += new_data
815 else:
816 return data
817
818
819 def match_patterns(self, str, patterns):
820 """
821 Match str against a list of patterns.
822
823 Return the index of the first pattern that matches a substring of str.
824 None and empty strings in patterns are ignored.
825 If no match is found, return None.
826
827 @param patterns: List of strings (regular expression patterns).
828 """
829 for i in range(len(patterns)):
830 if not patterns[i]:
831 continue
832 if re.search(patterns[i], str):
833 return i
834
835
836 def read_until_output_matches(self, patterns, filter=lambda x: x,
837 timeout=30.0, internal_timeout=None,
838 print_func=None):
839 """
840 Read using read_nonblocking until a match is found using match_patterns,
841 or until timeout expires. Before attempting to search for a match, the
842 data is filtered using the filter function provided.
843
844 @brief: Read from child using read_nonblocking until a pattern
845 matches.
846 @param patterns: List of strings (regular expression patterns)
847 @param filter: Function to apply to the data read from the child before
848 attempting to match it against the patterns (should take and
849 return a string)
850 @param timeout: The duration (in seconds) to wait until a match is
851 found
852 @param internal_timeout: The timeout to pass to read_nonblocking
853 @param print_func: A function to be used to print the data being read
854 (should take a string parameter)
855 @return: Tuple containing the match index (or None if no match was
856 found) and the data read so far.
857 """
858 match = None
859 data = ""
860
lmrf48c5cc2009-10-05 19:22:49 +0000861 fd = self._get_fd("expect")
lmrbbc9dd52009-07-22 20:33:47 +0000862 end_time = time.time() + timeout
lmrf48c5cc2009-10-05 19:22:49 +0000863 while True:
864 r, w, x = select.select([fd], [], [],
865 max(0, end_time - time.time()))
866 if fd not in r: break
lmrbbc9dd52009-07-22 20:33:47 +0000867 # Read data from child
868 newdata = self.read_nonblocking(internal_timeout)
869 # Print it if necessary
870 if print_func and newdata:
871 str = newdata
872 if str.endswith("\n"):
873 str = str[:-1]
874 for line in str.split("\n"):
875 print_func(line.decode("utf-8", "replace"))
876 data += newdata
877
878 done = False
879 # Look for patterns
880 match = self.match_patterns(filter(data), patterns)
881 if match is not None:
882 done = True
883 # Check if child has died
884 if not self.is_alive():
lmrf48c5cc2009-10-05 19:22:49 +0000885 logging.debug("Process terminated with status %s" %
886 self.get_status())
lmrbbc9dd52009-07-22 20:33:47 +0000887 done = True
888 # Are we done?
889 if done: break
890
891 # Print some debugging info
892 if match is None and (self.is_alive() or self.get_status() != 0):
893 logging.debug("Timeout elapsed or process terminated. Output:" +
894 kvm_utils.format_str_for_message(data.strip()))
895
896 return (match, data)
897
898
899 def read_until_last_word_matches(self, patterns, timeout=30.0,
900 internal_timeout=None, print_func=None):
901 """
902 Read using read_nonblocking until the last word of the output matches
903 one of the patterns (using match_patterns), or until timeout expires.
904
905 @param patterns: A list of strings (regular expression patterns)
906 @param timeout: The duration (in seconds) to wait until a match is
907 found
908 @param internal_timeout: The timeout to pass to read_nonblocking
909 @param print_func: A function to be used to print the data being read
910 (should take a string parameter)
911 @return: A tuple containing the match index (or None if no match was
912 found) and the data read so far.
913 """
914 def get_last_word(str):
915 if str:
916 return str.split()[-1]
917 else:
918 return ""
919
920 return self.read_until_output_matches(patterns, get_last_word,
921 timeout, internal_timeout,
922 print_func)
923
924
925 def read_until_last_line_matches(self, patterns, timeout=30.0,
926 internal_timeout=None, print_func=None):
927 """
928 Read using read_nonblocking until the last non-empty line of the output
929 matches one of the patterns (using match_patterns), or until timeout
930 expires. Return a tuple containing the match index (or None if no match
931 was found) and the data read so far.
932
933 @brief: Read using read_nonblocking until the last non-empty line
934 matches a pattern.
935
936 @param patterns: A list of strings (regular expression patterns)
937 @param timeout: The duration (in seconds) to wait until a match is
938 found
939 @param internal_timeout: The timeout to pass to read_nonblocking
940 @param print_func: A function to be used to print the data being read
941 (should take a string parameter)
942 """
943 def get_last_nonempty_line(str):
944 nonempty_lines = [l for l in str.splitlines() if l.strip()]
945 if nonempty_lines:
946 return nonempty_lines[-1]
947 else:
948 return ""
949
950 return self.read_until_output_matches(patterns, get_last_nonempty_line,
951 timeout, internal_timeout,
952 print_func)
953
954
955class kvm_shell_session(kvm_expect):
956 """
957 This class runs a child process in the background. It it suited for
958 processes that provide an interactive shell, such as SSH and Telnet.
959
960 It provides all services of kvm_expect and kvm_tail. In addition, it
961 provides command running services, and a utility function to test the
962 process for responsiveness.
963 """
964
965 def __init__(self, command=None, id=None, echo=False, linesep="\n",
lmr4fe15ba2009-08-13 04:11:26 +0000966 termination_func=None, termination_params=(),
967 output_func=None, output_params=(),
968 output_prefix="",
lmrbbc9dd52009-07-22 20:33:47 +0000969 prompt=r"[\#\$]\s*$", status_test_command="echo $?"):
970 """
971 Initialize the class and run command as a child process.
972
973 @param command: Command to run, or None if accessing an already running
974 server.
975 @param id: ID of an already running server, if accessing a running
976 server, or None if starting a new one.
977 @param echo: Boolean indicating whether echo should be initially
978 enabled for the pseudo terminal running the subprocess. This
979 parameter has an effect only when starting a new server.
980 @param linesep: Line separator to be appended to strings sent to the
981 child process by sendline().
982 @param termination_func: Function to call when the process exits. The
983 function must accept a single exit status parameter.
lmr4fe15ba2009-08-13 04:11:26 +0000984 @param termination_params: Parameters to send to termination_func
985 before the exit status.
lmrbbc9dd52009-07-22 20:33:47 +0000986 @param output_func: Function to call whenever a line of output is
987 available from the STDOUT or STDERR streams of the process.
988 The function must accept a single string parameter. The string
989 does not include the final newline.
lmr4fe15ba2009-08-13 04:11:26 +0000990 @param output_params: Parameters to send to output_func before the
991 output line.
lmrbbc9dd52009-07-22 20:33:47 +0000992 @param output_prefix: String to prepend to lines sent to output_func.
993 @param prompt: Regular expression describing the shell's prompt line.
994 @param status_test_command: Command to be used for getting the last
995 exit status of commands run inside the shell (used by
996 get_command_status_output() and friends).
997 """
998 # Init the superclass
999 kvm_expect.__init__(self, command, id, echo, linesep,
lmr4fe15ba2009-08-13 04:11:26 +00001000 termination_func, termination_params,
1001 output_func, output_params, output_prefix)
lmrbbc9dd52009-07-22 20:33:47 +00001002
1003 # Remember some attributes
1004 self.prompt = prompt
1005 self.status_test_command = status_test_command
1006
1007
1008 def __getinitargs__(self):
1009 return kvm_expect.__getinitargs__(self) + (self.prompt,
1010 self.status_test_command)
1011
1012
1013 def set_prompt(self, prompt):
1014 """
1015 Set the prompt attribute for later use by read_up_to_prompt.
1016
1017 @param: String that describes the prompt contents.
1018 """
1019 self.prompt = prompt
1020
1021
1022 def set_status_test_command(self, status_test_command):
1023 """
1024 Set the command to be sent in order to get the last exit status.
1025
1026 @param status_test_command: Command that will be sent to get the last
1027 exit status.
1028 """
1029 self.status_test_command = status_test_command
1030
1031
1032 def is_responsive(self, timeout=5.0):
1033 """
1034 Return True if the process responds to STDIN/terminal input.
1035
1036 Send a newline to the child process (e.g. SSH or Telnet) and read some
1037 output using read_nonblocking().
1038 If all is OK, some output should be available (e.g. the shell prompt).
1039 In that case return True. Otherwise return False.
1040
1041 @param timeout: Time duration to wait before the process is considered
1042 unresponsive.
1043 """
1044 # Read all output that's waiting to be read, to make sure the output
1045 # we read next is in response to the newline sent
lmr59b98db2009-10-05 19:11:21 +00001046 self.read_nonblocking(timeout=0)
lmrbbc9dd52009-07-22 20:33:47 +00001047 # Send a newline
1048 self.sendline()
1049 # Wait up to timeout seconds for some output from the child
1050 end_time = time.time() + timeout
1051 while time.time() < end_time:
1052 time.sleep(0.5)
1053 if self.read_nonblocking(timeout=0).strip():
1054 return True
1055 # No output -- report unresponsive
1056 return False
1057
1058
1059 def read_up_to_prompt(self, timeout=30.0, internal_timeout=None,
1060 print_func=None):
1061 """
1062 Read using read_nonblocking until the last non-empty line of the output
1063 matches the prompt regular expression set by set_prompt, or until
1064 timeout expires.
1065
1066 @brief: Read using read_nonblocking until the last non-empty line
1067 matches the prompt.
1068
1069 @param timeout: The duration (in seconds) to wait until a match is
1070 found
1071 @param internal_timeout: The timeout to pass to read_nonblocking
1072 @param print_func: A function to be used to print the data being
1073 read (should take a string parameter)
1074
1075 @return: A tuple containing True/False indicating whether the prompt
1076 was found, and the data read so far.
1077 """
1078 (match, output) = self.read_until_last_line_matches([self.prompt],
1079 timeout,
1080 internal_timeout,
1081 print_func)
1082 return (match is not None, output)
1083
1084
1085 def get_command_status_output(self, command, timeout=30.0,
1086 internal_timeout=None, print_func=None):
1087 """
1088 Send a command and return its exit status and output.
1089
1090 @param command: Command to send (must not contain newline characters)
1091 @param timeout: The duration (in seconds) to wait until a match is
1092 found
1093 @param internal_timeout: The timeout to pass to read_nonblocking
1094 @param print_func: A function to be used to print the data being read
1095 (should take a string parameter)
1096
1097 @return: A tuple (status, output) where status is the exit status or
1098 None if no exit status is available (e.g. timeout elapsed), and
1099 output is the output of command.
1100 """
1101 def remove_command_echo(str, cmd):
1102 if str and str.splitlines()[0] == cmd:
1103 str = "".join(str.splitlines(True)[1:])
1104 return str
1105
1106 def remove_last_nonempty_line(str):
1107 return "".join(str.rstrip().splitlines(True)[:-1])
1108
1109 # Print some debugging info
1110 logging.debug("Sending command: %s" % command)
1111
1112 # Read everything that's waiting to be read
lmr59b98db2009-10-05 19:11:21 +00001113 self.read_nonblocking(timeout=0)
lmrbbc9dd52009-07-22 20:33:47 +00001114
1115 # Send the command and get its output
1116 self.sendline(command)
1117 (match, output) = self.read_up_to_prompt(timeout, internal_timeout,
1118 print_func)
1119 # Remove the echoed command from the output
1120 output = remove_command_echo(output, command)
1121 # If the prompt was not found, return the output so far
1122 if not match:
1123 return (None, output)
1124 # Remove the final shell prompt from the output
1125 output = remove_last_nonempty_line(output)
1126
1127 # Send the 'echo ...' command to get the last exit status
1128 self.sendline(self.status_test_command)
1129 (match, status) = self.read_up_to_prompt(10.0, internal_timeout)
1130 if not match:
1131 return (None, output)
1132 status = remove_command_echo(status, self.status_test_command)
1133 status = remove_last_nonempty_line(status)
1134 # Get the first line consisting of digits only
1135 digit_lines = [l for l in status.splitlines() if l.strip().isdigit()]
1136 if not digit_lines:
1137 return (None, output)
1138 status = int(digit_lines[0].strip())
1139
1140 # Print some debugging info
1141 if status != 0:
1142 logging.debug("Command failed; status: %d, output:%s", status,
1143 kvm_utils.format_str_for_message(output.strip()))
1144
1145 return (status, output)
1146
1147
1148 def get_command_status(self, command, timeout=30.0, internal_timeout=None,
1149 print_func=None):
1150 """
1151 Send a command and return its exit status.
1152
1153 @param command: Command to send
1154 @param timeout: The duration (in seconds) to wait until a match is
1155 found
1156 @param internal_timeout: The timeout to pass to read_nonblocking
1157 @param print_func: A function to be used to print the data being read
1158 (should take a string parameter)
1159
1160 @return: Exit status or None if no exit status is available (e.g.
1161 timeout elapsed).
1162 """
1163 (status, output) = self.get_command_status_output(command, timeout,
1164 internal_timeout,
1165 print_func)
1166 return status
1167
1168
1169 def get_command_output(self, command, timeout=30.0, internal_timeout=None,
1170 print_func=None):
1171 """
1172 Send a command and return its output.
1173
1174 @param command: Command to send
1175 @param timeout: The duration (in seconds) to wait until a match is
1176 found
1177 @param internal_timeout: The timeout to pass to read_nonblocking
1178 @param print_func: A function to be used to print the data being read
1179 (should take a string parameter)
1180 """
1181 (status, output) = self.get_command_status_output(command, timeout,
1182 internal_timeout,
1183 print_func)
1184 return output