blob: 8321bb3de778f07e33aac5f3f91e63ef2583a257 [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
lmrcec66772010-06-22 01:55:50 +0000288 def __init__(self, command=None, id=None, auto_close=False, echo=False,
289 linesep="\n"):
lmrbbc9dd52009-07-22 20:33:47 +0000290 """
291 Initialize the class and run command as a child process.
292
293 @param command: Command to run, or None if accessing an already running
294 server.
295 @param id: ID of an already running server, if accessing a running
296 server, or None if starting a new one.
lmrcec66772010-06-22 01:55:50 +0000297 @param auto_close: If True, close() the instance automatically when its
298 reference count drops to zero (default False).
lmrbbc9dd52009-07-22 20:33:47 +0000299 @param echo: Boolean indicating whether echo should be initially
300 enabled for the pseudo terminal running the subprocess. This
301 parameter has an effect only when starting a new server.
302 @param linesep: Line separator to be appended to strings sent to the
303 child process by sendline().
304 """
305 self.id = id or kvm_utils.generate_random_string(8)
306
307 # Define filenames for communication with server
308 base_dir = "/tmp/kvm_spawn"
309 try:
310 os.makedirs(base_dir)
311 except:
312 pass
313 (self.shell_pid_filename,
314 self.status_filename,
315 self.output_filename,
316 self.inpipe_filename,
317 self.lock_server_running_filename,
318 self.lock_client_starting_filename) = _get_filenames(base_dir,
319 self.id)
320
321 # Remember some attributes
lmrcec66772010-06-22 01:55:50 +0000322 self.auto_close = auto_close
lmrbbc9dd52009-07-22 20:33:47 +0000323 self.echo = echo
324 self.linesep = linesep
325
326 # Make sure the 'readers' and 'close_hooks' attributes exist
327 if not hasattr(self, "readers"):
328 self.readers = []
329 if not hasattr(self, "close_hooks"):
330 self.close_hooks = []
331
332 # Define the reader filenames
333 self.reader_filenames = dict(
334 (reader, _get_reader_filename(base_dir, self.id, reader))
335 for reader in self.readers)
336
337 # Let the server know a client intends to open some pipes;
338 # if the executed command terminates quickly, the server will wait for
339 # the client to release the lock before exiting
340 lock_client_starting = _lock(self.lock_client_starting_filename)
341
342 # Start the server (which runs the command)
343 if command:
lmr24a82982010-06-14 17:18:42 +0000344 sub = subprocess.Popen("%s %s" % (sys.executable, __file__),
lmrbbc9dd52009-07-22 20:33:47 +0000345 shell=True,
346 stdin=subprocess.PIPE,
347 stdout=subprocess.PIPE,
348 stderr=subprocess.STDOUT)
349 # Send parameters to the server
350 sub.stdin.write("%s\n" % self.id)
351 sub.stdin.write("%s\n" % echo)
352 sub.stdin.write("%s\n" % ",".join(self.readers))
353 sub.stdin.write("%s\n" % command)
354 # Wait for the server to complete its initialization
lmrb8f53d62009-07-27 13:29:17 +0000355 while not "Server %s ready" % self.id in sub.stdout.readline():
356 pass
lmrbbc9dd52009-07-22 20:33:47 +0000357
358 # Open the reading pipes
359 self.reader_fds = {}
360 try:
361 assert(_locked(self.lock_server_running_filename))
362 for reader, filename in self.reader_filenames.items():
363 self.reader_fds[reader] = os.open(filename, os.O_RDONLY)
364 except:
365 pass
366
367 # Allow the server to continue
368 _unlock(lock_client_starting)
369
370
371 # The following two functions are defined to make sure the state is set
372 # exclusively by the constructor call as specified in __getinitargs__().
373
374 def __getstate__(self):
375 pass
376
377
378 def __setstate__(self, state):
379 pass
380
381
382 def __getinitargs__(self):
383 # Save some information when pickling -- will be passed to the
384 # constructor upon unpickling
lmrcec66772010-06-22 01:55:50 +0000385 return (None, self.id, self.auto_close, self.echo, self.linesep)
386
387
388 def __del__(self):
389 if self.auto_close:
390 self.close()
lmrbbc9dd52009-07-22 20:33:47 +0000391
392
393 def _add_reader(self, reader):
394 """
395 Add a reader whose file descriptor can be obtained with _get_fd().
396 Should be called before __init__(). Intended for use by derived
397 classes.
398
399 @param reader: The name of the reader.
400 """
401 if not hasattr(self, "readers"):
402 self.readers = []
403 self.readers.append(reader)
404
405
406 def _add_close_hook(self, hook):
407 """
408 Add a close hook function to be called when close() is called.
409 The function will be called after the process terminates but before
410 final cleanup. Intended for use by derived classes.
411
412 @param hook: The hook function.
413 """
414 if not hasattr(self, "close_hooks"):
415 self.close_hooks = []
416 self.close_hooks.append(hook)
417
418
419 def _get_fd(self, reader):
420 """
421 Return an open file descriptor corresponding to the specified reader
422 pipe. If no such reader exists, or the pipe could not be opened,
423 return None. Intended for use by derived classes.
424
425 @param reader: The name of the reader.
426 """
427 return self.reader_fds.get(reader)
428
429
430 def get_id(self):
431 """
432 Return the instance's id attribute, which may be used to access the
433 process in the future.
434 """
435 return self.id
436
437
lmrfb151b52009-09-09 22:19:11 +0000438 def get_pid(self):
lmrbbc9dd52009-07-22 20:33:47 +0000439 """
lmrfb151b52009-09-09 22:19:11 +0000440 Return the PID of the process.
441
442 Note: this may be the PID of the shell process running the user given
443 command.
lmrbbc9dd52009-07-22 20:33:47 +0000444 """
445 try:
446 file = open(self.shell_pid_filename, "r")
447 pid = int(file.read())
448 file.close()
449 return pid
450 except:
451 return None
452
453
lmrbbc9dd52009-07-22 20:33:47 +0000454 def get_status(self):
455 """
456 Wait for the process to exit and return its exit status, or None
457 if the exit status is not available.
458 """
459 _wait(self.lock_server_running_filename)
460 try:
461 file = open(self.status_filename, "r")
462 status = int(file.read())
463 file.close()
464 return status
465 except:
466 return None
467
468
469 def get_output(self):
470 """
471 Return the STDOUT and STDERR output of the process so far.
472 """
473 try:
474 file = open(self.output_filename, "r")
475 output = file.read()
476 file.close()
477 return output
478 except:
479 return ""
480
481
482 def is_alive(self):
483 """
484 Return True if the process is running.
485 """
lmr5df99f32009-08-13 04:46:16 +0000486 return _locked(self.lock_server_running_filename)
lmrbbc9dd52009-07-22 20:33:47 +0000487
488
lmrea1b64d2009-09-09 22:14:09 +0000489 def close(self, sig=signal.SIGKILL):
lmrbbc9dd52009-07-22 20:33:47 +0000490 """
491 Kill the child process if it's alive and remove temporary files.
492
493 @param sig: The signal to send the process when attempting to kill it.
494 """
495 # Kill it if it's alive
496 if self.is_alive():
lmrfb151b52009-09-09 22:19:11 +0000497 kvm_utils.kill_process_tree(self.get_pid(), sig)
lmrbbc9dd52009-07-22 20:33:47 +0000498 # Wait for the server to exit
499 _wait(self.lock_server_running_filename)
500 # Call all cleanup routines
501 for hook in self.close_hooks:
lmr16063962009-10-14 10:27:59 +0000502 hook(self)
lmrbbc9dd52009-07-22 20:33:47 +0000503 # Close reader file descriptors
504 for fd in self.reader_fds.values():
505 try:
506 os.close(fd)
507 except:
508 pass
lmr04d5b012009-11-10 16:28:22 +0000509 self.reader_fds = {}
lmrbbc9dd52009-07-22 20:33:47 +0000510 # Remove all used files
511 for filename in (_get_filenames("/tmp/kvm_spawn", self.id) +
512 self.reader_filenames.values()):
513 try:
514 os.unlink(filename)
515 except OSError:
516 pass
517
518
519 def set_linesep(self, linesep):
520 """
521 Sets the line separator string (usually "\\n").
522
523 @param linesep: Line separator string.
524 """
525 self.linesep = linesep
526
527
528 def send(self, str=""):
529 """
530 Send a string to the child process.
531
532 @param str: String to send to the child process.
533 """
534 try:
535 fd = os.open(self.inpipe_filename, os.O_RDWR)
536 os.write(fd, str)
537 os.close(fd)
538 except:
539 pass
540
541
542 def sendline(self, str=""):
543 """
544 Send a string followed by a line separator to the child process.
545
546 @param str: String to send to the child process.
547 """
548 self.send(str + self.linesep)
549
550
lmree4338e2010-07-08 23:40:10 +0000551_thread_kill_requested = False
552
553def kill_tail_threads():
554 """
555 Kill all kvm_tail threads.
556
557 After calling this function no new threads should be started.
558 """
559 global _thread_kill_requested
560 _thread_kill_requested = True
561 for t in threading.enumerate():
562 if hasattr(t, "name") and t.name.startswith("tail_thread"):
563 t.join(10)
Eric Lie0493a42010-11-15 13:05:43 -0800564 _thread_kill_requested = False
lmree4338e2010-07-08 23:40:10 +0000565
566
lmrbbc9dd52009-07-22 20:33:47 +0000567class kvm_tail(kvm_spawn):
568 """
569 This class runs a child process in the background and sends its output in
570 real time, line-by-line, to a callback function.
571
572 See kvm_spawn's docstring.
573
574 This class uses a single pipe reader to read data in real time from the
575 child process and report it to a given callback function.
576 When the child process exits, its exit status is reported to an additional
577 callback function.
578
579 When this class is unpickled, it automatically resumes reporting output.
580 """
581
lmrcec66772010-06-22 01:55:50 +0000582 def __init__(self, command=None, id=None, auto_close=False, echo=False,
583 linesep="\n", termination_func=None, termination_params=(),
584 output_func=None, output_params=(), output_prefix=""):
lmrbbc9dd52009-07-22 20:33:47 +0000585 """
586 Initialize the class and run command as a child process.
587
588 @param command: Command to run, or None if accessing an already running
589 server.
590 @param id: ID of an already running server, if accessing a running
591 server, or None if starting a new one.
lmrcec66772010-06-22 01:55:50 +0000592 @param auto_close: If True, close() the instance automatically when its
593 reference count drops to zero (default False).
lmrbbc9dd52009-07-22 20:33:47 +0000594 @param echo: Boolean indicating whether echo should be initially
595 enabled for the pseudo terminal running the subprocess. This
596 parameter has an effect only when starting a new server.
597 @param linesep: Line separator to be appended to strings sent to the
598 child process by sendline().
599 @param termination_func: Function to call when the process exits. The
600 function must accept a single exit status parameter.
lmr4fe15ba2009-08-13 04:11:26 +0000601 @param termination_params: Parameters to send to termination_func
602 before the exit status.
lmrbbc9dd52009-07-22 20:33:47 +0000603 @param output_func: Function to call whenever a line of output is
604 available from the STDOUT or STDERR streams of the process.
605 The function must accept a single string parameter. The string
606 does not include the final newline.
lmr4fe15ba2009-08-13 04:11:26 +0000607 @param output_params: Parameters to send to output_func before the
608 output line.
lmrbbc9dd52009-07-22 20:33:47 +0000609 @param output_prefix: String to prepend to lines sent to output_func.
610 """
611 # Add a reader and a close hook
612 self._add_reader("tail")
lmr16063962009-10-14 10:27:59 +0000613 self._add_close_hook(kvm_tail._join_thread)
lmrbbc9dd52009-07-22 20:33:47 +0000614
615 # Init the superclass
lmrcec66772010-06-22 01:55:50 +0000616 kvm_spawn.__init__(self, command, id, auto_close, echo, linesep)
lmrbbc9dd52009-07-22 20:33:47 +0000617
618 # Remember some attributes
619 self.termination_func = termination_func
lmr4fe15ba2009-08-13 04:11:26 +0000620 self.termination_params = termination_params
lmrbbc9dd52009-07-22 20:33:47 +0000621 self.output_func = output_func
lmr4fe15ba2009-08-13 04:11:26 +0000622 self.output_params = output_params
lmrbbc9dd52009-07-22 20:33:47 +0000623 self.output_prefix = output_prefix
624
625 # Start the thread in the background
lmrc07f3812009-10-14 10:27:04 +0000626 self.tail_thread = None
lmrc07f3812009-10-14 10:27:04 +0000627 if termination_func or output_func:
628 self._start_thread()
lmrbbc9dd52009-07-22 20:33:47 +0000629
630
631 def __getinitargs__(self):
632 return kvm_spawn.__getinitargs__(self) + (self.termination_func,
lmr4fe15ba2009-08-13 04:11:26 +0000633 self.termination_params,
lmrbbc9dd52009-07-22 20:33:47 +0000634 self.output_func,
lmr4fe15ba2009-08-13 04:11:26 +0000635 self.output_params,
lmrbbc9dd52009-07-22 20:33:47 +0000636 self.output_prefix)
637
638
639 def set_termination_func(self, termination_func):
640 """
641 Set the termination_func attribute. See __init__() for details.
642
643 @param termination_func: Function to call when the process terminates.
644 Must take a single parameter -- the exit status.
645 """
646 self.termination_func = termination_func
lmrc07f3812009-10-14 10:27:04 +0000647 if termination_func and not self.tail_thread:
648 self._start_thread()
lmrbbc9dd52009-07-22 20:33:47 +0000649
650
lmr4fe15ba2009-08-13 04:11:26 +0000651 def set_termination_params(self, termination_params):
652 """
653 Set the termination_params attribute. See __init__() for details.
654
655 @param termination_params: Parameters to send to termination_func
656 before the exit status.
657 """
658 self.termination_params = termination_params
659
660
lmrbbc9dd52009-07-22 20:33:47 +0000661 def set_output_func(self, output_func):
662 """
663 Set the output_func attribute. See __init__() for details.
664
665 @param output_func: Function to call for each line of STDOUT/STDERR
666 output from the process. Must take a single string parameter.
667 """
668 self.output_func = output_func
lmrc07f3812009-10-14 10:27:04 +0000669 if output_func and not self.tail_thread:
670 self._start_thread()
lmrbbc9dd52009-07-22 20:33:47 +0000671
672
lmr4fe15ba2009-08-13 04:11:26 +0000673 def set_output_params(self, output_params):
674 """
675 Set the output_params attribute. See __init__() for details.
676
677 @param output_params: Parameters to send to output_func before the
678 output line.
679 """
680 self.output_params = output_params
681
682
lmrbbc9dd52009-07-22 20:33:47 +0000683 def set_output_prefix(self, output_prefix):
684 """
685 Set the output_prefix attribute. See __init__() for details.
686
687 @param output_prefix: String to pre-pend to each line sent to
688 output_func (see set_output_callback()).
689 """
690 self.output_prefix = output_prefix
691
692
693 def _tail(self):
694 def print_line(text):
695 # Pre-pend prefix and remove trailing whitespace
696 text = self.output_prefix + text.rstrip()
lmrcf668fe2010-06-22 02:07:37 +0000697 # Pass text to output_func
lmrbbc9dd52009-07-22 20:33:47 +0000698 try:
lmr4fe15ba2009-08-13 04:11:26 +0000699 params = self.output_params + (text,)
700 self.output_func(*params)
lmrbbc9dd52009-07-22 20:33:47 +0000701 except TypeError:
702 pass
703
lmrbbc9dd52009-07-22 20:33:47 +0000704 try:
lmree4338e2010-07-08 23:40:10 +0000705 fd = self._get_fd("tail")
706 buffer = ""
707 while True:
708 global _thread_kill_requested
709 if _thread_kill_requested:
710 return
711 try:
712 # See if there's any data to read from the pipe
713 r, w, x = select.select([fd], [], [], 0.05)
714 except:
715 break
716 if fd in r:
717 # Some data is available; read it
718 new_data = os.read(fd, 1024)
719 if not new_data:
720 break
721 buffer += new_data
722 # Send the output to output_func line by line
723 # (except for the last line)
724 if self.output_func:
725 lines = buffer.split("\n")
726 for line in lines[:-1]:
727 print_line(line)
728 # Leave only the last line
729 last_newline_index = buffer.rfind("\n")
730 buffer = buffer[last_newline_index+1:]
731 else:
732 # No output is available right now; flush the buffer
733 if buffer:
734 print_line(buffer)
735 buffer = ""
736 # The process terminated; print any remaining output
737 if buffer:
738 print_line(buffer)
739 # Get the exit status, print it and send it to termination_func
740 status = self.get_status()
741 if status is None:
742 return
743 print_line("(Process terminated with status %s)" % status)
744 try:
745 params = self.termination_params + (status,)
746 self.termination_func(*params)
747 except TypeError:
748 pass
749 finally:
750 self.tail_thread = None
lmrbbc9dd52009-07-22 20:33:47 +0000751
752
lmrc07f3812009-10-14 10:27:04 +0000753 def _start_thread(self):
lmree4338e2010-07-08 23:40:10 +0000754 self.tail_thread = threading.Thread(target=self._tail,
755 name="tail_thread_%s" % self.id)
lmrc07f3812009-10-14 10:27:04 +0000756 self.tail_thread.start()
757
758
lmrbbc9dd52009-07-22 20:33:47 +0000759 def _join_thread(self):
760 # Wait for the tail thread to exit
lmree4338e2010-07-08 23:40:10 +0000761 # (it's done this way because self.tail_thread may become None at any
762 # time)
763 t = self.tail_thread
764 if t:
765 t.join()
lmrbbc9dd52009-07-22 20:33:47 +0000766
767
768class kvm_expect(kvm_tail):
769 """
770 This class runs a child process in the background and provides expect-like
771 services.
772
773 It also provides all of kvm_tail's functionality.
774 """
775
lmrcec66772010-06-22 01:55:50 +0000776 def __init__(self, command=None, id=None, auto_close=False, echo=False,
777 linesep="\n", termination_func=None, termination_params=(),
778 output_func=None, output_params=(), output_prefix=""):
lmrbbc9dd52009-07-22 20:33:47 +0000779 """
780 Initialize the class and run command as a child process.
781
782 @param command: Command to run, or None if accessing an already running
783 server.
784 @param id: ID of an already running server, if accessing a running
785 server, or None if starting a new one.
lmrcec66772010-06-22 01:55:50 +0000786 @param auto_close: If True, close() the instance automatically when its
787 reference count drops to zero (default False).
lmrbbc9dd52009-07-22 20:33:47 +0000788 @param echo: Boolean indicating whether echo should be initially
789 enabled for the pseudo terminal running the subprocess. This
790 parameter has an effect only when starting a new server.
791 @param linesep: Line separator to be appended to strings sent to the
792 child process by sendline().
793 @param termination_func: Function to call when the process exits. The
794 function must accept a single exit status parameter.
lmr4fe15ba2009-08-13 04:11:26 +0000795 @param termination_params: Parameters to send to termination_func
796 before the exit status.
lmrbbc9dd52009-07-22 20:33:47 +0000797 @param output_func: Function to call whenever a line of output is
798 available from the STDOUT or STDERR streams of the process.
799 The function must accept a single string parameter. The string
800 does not include the final newline.
lmr4fe15ba2009-08-13 04:11:26 +0000801 @param output_params: Parameters to send to output_func before the
802 output line.
lmrbbc9dd52009-07-22 20:33:47 +0000803 @param output_prefix: String to prepend to lines sent to output_func.
804 """
805 # Add a reader
806 self._add_reader("expect")
807
808 # Init the superclass
lmrcec66772010-06-22 01:55:50 +0000809 kvm_tail.__init__(self, command, id, auto_close, echo, linesep,
lmr4fe15ba2009-08-13 04:11:26 +0000810 termination_func, termination_params,
811 output_func, output_params, output_prefix)
lmrbbc9dd52009-07-22 20:33:47 +0000812
813
814 def __getinitargs__(self):
815 return kvm_tail.__getinitargs__(self)
816
817
818 def read_nonblocking(self, timeout=None):
819 """
820 Read from child until there is nothing to read for timeout seconds.
821
822 @param timeout: Time (seconds) to wait before we give up reading from
823 the child process, or None to use the default value.
824 """
825 if timeout is None:
826 timeout = 0.1
827 fd = self._get_fd("expect")
828 data = ""
829 while True:
830 try:
831 r, w, x = select.select([fd], [], [], timeout)
832 except:
833 return data
834 if fd in r:
835 new_data = os.read(fd, 1024)
836 if not new_data:
837 return data
838 data += new_data
839 else:
840 return data
841
842
843 def match_patterns(self, str, patterns):
844 """
845 Match str against a list of patterns.
846
847 Return the index of the first pattern that matches a substring of str.
848 None and empty strings in patterns are ignored.
849 If no match is found, return None.
850
851 @param patterns: List of strings (regular expression patterns).
852 """
853 for i in range(len(patterns)):
854 if not patterns[i]:
855 continue
856 if re.search(patterns[i], str):
857 return i
858
859
860 def read_until_output_matches(self, patterns, filter=lambda x: x,
861 timeout=30.0, internal_timeout=None,
862 print_func=None):
863 """
864 Read using read_nonblocking until a match is found using match_patterns,
865 or until timeout expires. Before attempting to search for a match, the
866 data is filtered using the filter function provided.
867
868 @brief: Read from child using read_nonblocking until a pattern
869 matches.
870 @param patterns: List of strings (regular expression patterns)
871 @param filter: Function to apply to the data read from the child before
872 attempting to match it against the patterns (should take and
873 return a string)
874 @param timeout: The duration (in seconds) to wait until a match is
875 found
876 @param internal_timeout: The timeout to pass to read_nonblocking
877 @param print_func: A function to be used to print the data being read
878 (should take a string parameter)
879 @return: Tuple containing the match index (or None if no match was
880 found) and the data read so far.
881 """
882 match = None
883 data = ""
884
lmrf48c5cc2009-10-05 19:22:49 +0000885 fd = self._get_fd("expect")
lmrbbc9dd52009-07-22 20:33:47 +0000886 end_time = time.time() + timeout
lmrf48c5cc2009-10-05 19:22:49 +0000887 while True:
lmr04d5b012009-11-10 16:28:22 +0000888 try:
889 r, w, x = select.select([fd], [], [],
890 max(0, end_time - time.time()))
891 except (select.error, TypeError):
892 break
893 if fd not in r:
894 break
lmrbbc9dd52009-07-22 20:33:47 +0000895 # Read data from child
896 newdata = self.read_nonblocking(internal_timeout)
897 # Print it if necessary
898 if print_func and newdata:
899 str = newdata
900 if str.endswith("\n"):
901 str = str[:-1]
902 for line in str.split("\n"):
lmrcf668fe2010-06-22 02:07:37 +0000903 print_func(line)
lmrbbc9dd52009-07-22 20:33:47 +0000904 data += newdata
905
906 done = False
907 # Look for patterns
908 match = self.match_patterns(filter(data), patterns)
909 if match is not None:
910 done = True
911 # Check if child has died
912 if not self.is_alive():
lmrf48c5cc2009-10-05 19:22:49 +0000913 logging.debug("Process terminated with status %s" %
914 self.get_status())
lmrbbc9dd52009-07-22 20:33:47 +0000915 done = True
916 # Are we done?
917 if done: break
918
919 # Print some debugging info
920 if match is None and (self.is_alive() or self.get_status() != 0):
921 logging.debug("Timeout elapsed or process terminated. Output:" +
922 kvm_utils.format_str_for_message(data.strip()))
923
924 return (match, data)
925
926
927 def read_until_last_word_matches(self, patterns, timeout=30.0,
928 internal_timeout=None, print_func=None):
929 """
930 Read using read_nonblocking until the last word of the output matches
931 one of the patterns (using match_patterns), or until timeout expires.
932
933 @param patterns: A list of strings (regular expression patterns)
934 @param timeout: The duration (in seconds) to wait until a match is
935 found
936 @param internal_timeout: The timeout to pass to read_nonblocking
937 @param print_func: A function to be used to print the data being read
938 (should take a string parameter)
939 @return: A tuple containing the match index (or None if no match was
940 found) and the data read so far.
941 """
942 def get_last_word(str):
943 if str:
944 return str.split()[-1]
945 else:
946 return ""
947
948 return self.read_until_output_matches(patterns, get_last_word,
949 timeout, internal_timeout,
950 print_func)
951
952
953 def read_until_last_line_matches(self, patterns, timeout=30.0,
954 internal_timeout=None, print_func=None):
955 """
956 Read using read_nonblocking until the last non-empty line of the output
957 matches one of the patterns (using match_patterns), or until timeout
958 expires. Return a tuple containing the match index (or None if no match
959 was found) and the data read so far.
960
961 @brief: Read using read_nonblocking until the last non-empty line
962 matches a pattern.
963
964 @param patterns: A list of strings (regular expression patterns)
965 @param timeout: The duration (in seconds) to wait until a match is
966 found
967 @param internal_timeout: The timeout to pass to read_nonblocking
968 @param print_func: A function to be used to print the data being read
969 (should take a string parameter)
970 """
971 def get_last_nonempty_line(str):
972 nonempty_lines = [l for l in str.splitlines() if l.strip()]
973 if nonempty_lines:
974 return nonempty_lines[-1]
975 else:
976 return ""
977
978 return self.read_until_output_matches(patterns, get_last_nonempty_line,
979 timeout, internal_timeout,
980 print_func)
981
982
983class kvm_shell_session(kvm_expect):
984 """
985 This class runs a child process in the background. It it suited for
986 processes that provide an interactive shell, such as SSH and Telnet.
987
988 It provides all services of kvm_expect and kvm_tail. In addition, it
989 provides command running services, and a utility function to test the
990 process for responsiveness.
991 """
992
lmrcec66772010-06-22 01:55:50 +0000993 def __init__(self, command=None, id=None, auto_close=True, echo=False,
994 linesep="\n", termination_func=None, termination_params=(),
995 output_func=None, output_params=(), output_prefix="",
lmrbbc9dd52009-07-22 20:33:47 +0000996 prompt=r"[\#\$]\s*$", status_test_command="echo $?"):
997 """
998 Initialize the class and run command as a child process.
999
1000 @param command: Command to run, or None if accessing an already running
1001 server.
1002 @param id: ID of an already running server, if accessing a running
1003 server, or None if starting a new one.
lmrcec66772010-06-22 01:55:50 +00001004 @param auto_close: If True, close() the instance automatically when its
1005 reference count drops to zero (default True).
lmrbbc9dd52009-07-22 20:33:47 +00001006 @param echo: Boolean indicating whether echo should be initially
1007 enabled for the pseudo terminal running the subprocess. This
1008 parameter has an effect only when starting a new server.
1009 @param linesep: Line separator to be appended to strings sent to the
1010 child process by sendline().
1011 @param termination_func: Function to call when the process exits. The
1012 function must accept a single exit status parameter.
lmr4fe15ba2009-08-13 04:11:26 +00001013 @param termination_params: Parameters to send to termination_func
1014 before the exit status.
lmrbbc9dd52009-07-22 20:33:47 +00001015 @param output_func: Function to call whenever a line of output is
1016 available from the STDOUT or STDERR streams of the process.
1017 The function must accept a single string parameter. The string
1018 does not include the final newline.
lmr4fe15ba2009-08-13 04:11:26 +00001019 @param output_params: Parameters to send to output_func before the
1020 output line.
lmrbbc9dd52009-07-22 20:33:47 +00001021 @param output_prefix: String to prepend to lines sent to output_func.
1022 @param prompt: Regular expression describing the shell's prompt line.
1023 @param status_test_command: Command to be used for getting the last
1024 exit status of commands run inside the shell (used by
1025 get_command_status_output() and friends).
1026 """
1027 # Init the superclass
lmrcec66772010-06-22 01:55:50 +00001028 kvm_expect.__init__(self, command, id, auto_close, echo, linesep,
lmr4fe15ba2009-08-13 04:11:26 +00001029 termination_func, termination_params,
1030 output_func, output_params, output_prefix)
lmrbbc9dd52009-07-22 20:33:47 +00001031
1032 # Remember some attributes
1033 self.prompt = prompt
1034 self.status_test_command = status_test_command
1035
1036
1037 def __getinitargs__(self):
1038 return kvm_expect.__getinitargs__(self) + (self.prompt,
1039 self.status_test_command)
1040
1041
1042 def set_prompt(self, prompt):
1043 """
1044 Set the prompt attribute for later use by read_up_to_prompt.
1045
1046 @param: String that describes the prompt contents.
1047 """
1048 self.prompt = prompt
1049
1050
1051 def set_status_test_command(self, status_test_command):
1052 """
1053 Set the command to be sent in order to get the last exit status.
1054
1055 @param status_test_command: Command that will be sent to get the last
1056 exit status.
1057 """
1058 self.status_test_command = status_test_command
1059
1060
1061 def is_responsive(self, timeout=5.0):
1062 """
1063 Return True if the process responds to STDIN/terminal input.
1064
1065 Send a newline to the child process (e.g. SSH or Telnet) and read some
1066 output using read_nonblocking().
1067 If all is OK, some output should be available (e.g. the shell prompt).
1068 In that case return True. Otherwise return False.
1069
1070 @param timeout: Time duration to wait before the process is considered
1071 unresponsive.
1072 """
1073 # Read all output that's waiting to be read, to make sure the output
1074 # we read next is in response to the newline sent
lmr59b98db2009-10-05 19:11:21 +00001075 self.read_nonblocking(timeout=0)
lmrbbc9dd52009-07-22 20:33:47 +00001076 # Send a newline
1077 self.sendline()
1078 # Wait up to timeout seconds for some output from the child
1079 end_time = time.time() + timeout
1080 while time.time() < end_time:
1081 time.sleep(0.5)
1082 if self.read_nonblocking(timeout=0).strip():
1083 return True
1084 # No output -- report unresponsive
1085 return False
1086
1087
1088 def read_up_to_prompt(self, timeout=30.0, internal_timeout=None,
1089 print_func=None):
1090 """
1091 Read using read_nonblocking until the last non-empty line of the output
1092 matches the prompt regular expression set by set_prompt, or until
1093 timeout expires.
1094
1095 @brief: Read using read_nonblocking until the last non-empty line
1096 matches the prompt.
1097
1098 @param timeout: The duration (in seconds) to wait until a match is
1099 found
1100 @param internal_timeout: The timeout to pass to read_nonblocking
1101 @param print_func: A function to be used to print the data being
1102 read (should take a string parameter)
1103
1104 @return: A tuple containing True/False indicating whether the prompt
1105 was found, and the data read so far.
1106 """
1107 (match, output) = self.read_until_last_line_matches([self.prompt],
1108 timeout,
1109 internal_timeout,
1110 print_func)
1111 return (match is not None, output)
1112
1113
1114 def get_command_status_output(self, command, timeout=30.0,
1115 internal_timeout=None, print_func=None):
1116 """
1117 Send a command and return its exit status and output.
1118
1119 @param command: Command to send (must not contain newline characters)
1120 @param timeout: The duration (in seconds) to wait until a match is
1121 found
1122 @param internal_timeout: The timeout to pass to read_nonblocking
1123 @param print_func: A function to be used to print the data being read
1124 (should take a string parameter)
1125
1126 @return: A tuple (status, output) where status is the exit status or
1127 None if no exit status is available (e.g. timeout elapsed), and
1128 output is the output of command.
1129 """
1130 def remove_command_echo(str, cmd):
1131 if str and str.splitlines()[0] == cmd:
1132 str = "".join(str.splitlines(True)[1:])
1133 return str
1134
1135 def remove_last_nonempty_line(str):
1136 return "".join(str.rstrip().splitlines(True)[:-1])
1137
1138 # Print some debugging info
1139 logging.debug("Sending command: %s" % command)
1140
1141 # Read everything that's waiting to be read
lmr59b98db2009-10-05 19:11:21 +00001142 self.read_nonblocking(timeout=0)
lmrbbc9dd52009-07-22 20:33:47 +00001143
1144 # Send the command and get its output
1145 self.sendline(command)
1146 (match, output) = self.read_up_to_prompt(timeout, internal_timeout,
1147 print_func)
1148 # Remove the echoed command from the output
1149 output = remove_command_echo(output, command)
1150 # If the prompt was not found, return the output so far
1151 if not match:
1152 return (None, output)
1153 # Remove the final shell prompt from the output
1154 output = remove_last_nonempty_line(output)
1155
1156 # Send the 'echo ...' command to get the last exit status
1157 self.sendline(self.status_test_command)
1158 (match, status) = self.read_up_to_prompt(10.0, internal_timeout)
1159 if not match:
1160 return (None, output)
1161 status = remove_command_echo(status, self.status_test_command)
1162 status = remove_last_nonempty_line(status)
1163 # Get the first line consisting of digits only
1164 digit_lines = [l for l in status.splitlines() if l.strip().isdigit()]
1165 if not digit_lines:
1166 return (None, output)
1167 status = int(digit_lines[0].strip())
1168
1169 # Print some debugging info
1170 if status != 0:
1171 logging.debug("Command failed; status: %d, output:%s", status,
1172 kvm_utils.format_str_for_message(output.strip()))
1173
1174 return (status, output)
1175
1176
1177 def get_command_status(self, command, timeout=30.0, internal_timeout=None,
1178 print_func=None):
1179 """
1180 Send a command and return its exit status.
1181
1182 @param command: Command to send
1183 @param timeout: The duration (in seconds) to wait until a match is
1184 found
1185 @param internal_timeout: The timeout to pass to read_nonblocking
1186 @param print_func: A function to be used to print the data being read
1187 (should take a string parameter)
1188
1189 @return: Exit status or None if no exit status is available (e.g.
1190 timeout elapsed).
1191 """
1192 (status, output) = self.get_command_status_output(command, timeout,
1193 internal_timeout,
1194 print_func)
1195 return status
1196
1197
1198 def get_command_output(self, command, timeout=30.0, internal_timeout=None,
1199 print_func=None):
1200 """
1201 Send a command and return its output.
1202
1203 @param command: Command to send
1204 @param timeout: The duration (in seconds) to wait until a match is
1205 found
1206 @param internal_timeout: The timeout to pass to read_nonblocking
1207 @param print_func: A function to be used to print the data being read
1208 (should take a string parameter)
1209 """
1210 (status, output) = self.get_command_status_output(command, timeout,
1211 internal_timeout,
1212 print_func)
1213 return output