blob: f815069c36ea2232f100870b45c97c824e4158cd [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)
564
565
lmrbbc9dd52009-07-22 20:33:47 +0000566class kvm_tail(kvm_spawn):
567 """
568 This class runs a child process in the background and sends its output in
569 real time, line-by-line, to a callback function.
570
571 See kvm_spawn's docstring.
572
573 This class uses a single pipe reader to read data in real time from the
574 child process and report it to a given callback function.
575 When the child process exits, its exit status is reported to an additional
576 callback function.
577
578 When this class is unpickled, it automatically resumes reporting output.
579 """
580
lmrcec66772010-06-22 01:55:50 +0000581 def __init__(self, command=None, id=None, auto_close=False, echo=False,
582 linesep="\n", termination_func=None, termination_params=(),
583 output_func=None, output_params=(), output_prefix=""):
lmrbbc9dd52009-07-22 20:33:47 +0000584 """
585 Initialize the class and run command as a child process.
586
587 @param command: Command to run, or None if accessing an already running
588 server.
589 @param id: ID of an already running server, if accessing a running
590 server, or None if starting a new one.
lmrcec66772010-06-22 01:55:50 +0000591 @param auto_close: If True, close() the instance automatically when its
592 reference count drops to zero (default False).
lmrbbc9dd52009-07-22 20:33:47 +0000593 @param echo: Boolean indicating whether echo should be initially
594 enabled for the pseudo terminal running the subprocess. This
595 parameter has an effect only when starting a new server.
596 @param linesep: Line separator to be appended to strings sent to the
597 child process by sendline().
598 @param termination_func: Function to call when the process exits. The
599 function must accept a single exit status parameter.
lmr4fe15ba2009-08-13 04:11:26 +0000600 @param termination_params: Parameters to send to termination_func
601 before the exit status.
lmrbbc9dd52009-07-22 20:33:47 +0000602 @param output_func: Function to call whenever a line of output is
603 available from the STDOUT or STDERR streams of the process.
604 The function must accept a single string parameter. The string
605 does not include the final newline.
lmr4fe15ba2009-08-13 04:11:26 +0000606 @param output_params: Parameters to send to output_func before the
607 output line.
lmrbbc9dd52009-07-22 20:33:47 +0000608 @param output_prefix: String to prepend to lines sent to output_func.
609 """
610 # Add a reader and a close hook
611 self._add_reader("tail")
lmr16063962009-10-14 10:27:59 +0000612 self._add_close_hook(kvm_tail._join_thread)
lmrbbc9dd52009-07-22 20:33:47 +0000613
614 # Init the superclass
lmrcec66772010-06-22 01:55:50 +0000615 kvm_spawn.__init__(self, command, id, auto_close, echo, linesep)
lmrbbc9dd52009-07-22 20:33:47 +0000616
617 # Remember some attributes
618 self.termination_func = termination_func
lmr4fe15ba2009-08-13 04:11:26 +0000619 self.termination_params = termination_params
lmrbbc9dd52009-07-22 20:33:47 +0000620 self.output_func = output_func
lmr4fe15ba2009-08-13 04:11:26 +0000621 self.output_params = output_params
lmrbbc9dd52009-07-22 20:33:47 +0000622 self.output_prefix = output_prefix
623
624 # Start the thread in the background
lmrc07f3812009-10-14 10:27:04 +0000625 self.tail_thread = None
lmrc07f3812009-10-14 10:27:04 +0000626 if termination_func or output_func:
627 self._start_thread()
lmrbbc9dd52009-07-22 20:33:47 +0000628
629
630 def __getinitargs__(self):
631 return kvm_spawn.__getinitargs__(self) + (self.termination_func,
lmr4fe15ba2009-08-13 04:11:26 +0000632 self.termination_params,
lmrbbc9dd52009-07-22 20:33:47 +0000633 self.output_func,
lmr4fe15ba2009-08-13 04:11:26 +0000634 self.output_params,
lmrbbc9dd52009-07-22 20:33:47 +0000635 self.output_prefix)
636
637
638 def set_termination_func(self, termination_func):
639 """
640 Set the termination_func attribute. See __init__() for details.
641
642 @param termination_func: Function to call when the process terminates.
643 Must take a single parameter -- the exit status.
644 """
645 self.termination_func = termination_func
lmrc07f3812009-10-14 10:27:04 +0000646 if termination_func and not self.tail_thread:
647 self._start_thread()
lmrbbc9dd52009-07-22 20:33:47 +0000648
649
lmr4fe15ba2009-08-13 04:11:26 +0000650 def set_termination_params(self, termination_params):
651 """
652 Set the termination_params attribute. See __init__() for details.
653
654 @param termination_params: Parameters to send to termination_func
655 before the exit status.
656 """
657 self.termination_params = termination_params
658
659
lmrbbc9dd52009-07-22 20:33:47 +0000660 def set_output_func(self, output_func):
661 """
662 Set the output_func attribute. See __init__() for details.
663
664 @param output_func: Function to call for each line of STDOUT/STDERR
665 output from the process. Must take a single string parameter.
666 """
667 self.output_func = output_func
lmrc07f3812009-10-14 10:27:04 +0000668 if output_func and not self.tail_thread:
669 self._start_thread()
lmrbbc9dd52009-07-22 20:33:47 +0000670
671
lmr4fe15ba2009-08-13 04:11:26 +0000672 def set_output_params(self, output_params):
673 """
674 Set the output_params attribute. See __init__() for details.
675
676 @param output_params: Parameters to send to output_func before the
677 output line.
678 """
679 self.output_params = output_params
680
681
lmrbbc9dd52009-07-22 20:33:47 +0000682 def set_output_prefix(self, output_prefix):
683 """
684 Set the output_prefix attribute. See __init__() for details.
685
686 @param output_prefix: String to pre-pend to each line sent to
687 output_func (see set_output_callback()).
688 """
689 self.output_prefix = output_prefix
690
691
692 def _tail(self):
693 def print_line(text):
694 # Pre-pend prefix and remove trailing whitespace
695 text = self.output_prefix + text.rstrip()
lmrcf668fe2010-06-22 02:07:37 +0000696 # Pass text to output_func
lmrbbc9dd52009-07-22 20:33:47 +0000697 try:
lmr4fe15ba2009-08-13 04:11:26 +0000698 params = self.output_params + (text,)
699 self.output_func(*params)
lmrbbc9dd52009-07-22 20:33:47 +0000700 except TypeError:
701 pass
702
lmrbbc9dd52009-07-22 20:33:47 +0000703 try:
lmree4338e2010-07-08 23:40:10 +0000704 fd = self._get_fd("tail")
705 buffer = ""
706 while True:
707 global _thread_kill_requested
708 if _thread_kill_requested:
709 return
710 try:
711 # See if there's any data to read from the pipe
712 r, w, x = select.select([fd], [], [], 0.05)
713 except:
714 break
715 if fd in r:
716 # Some data is available; read it
717 new_data = os.read(fd, 1024)
718 if not new_data:
719 break
720 buffer += new_data
721 # Send the output to output_func line by line
722 # (except for the last line)
723 if self.output_func:
724 lines = buffer.split("\n")
725 for line in lines[:-1]:
726 print_line(line)
727 # Leave only the last line
728 last_newline_index = buffer.rfind("\n")
729 buffer = buffer[last_newline_index+1:]
730 else:
731 # No output is available right now; flush the buffer
732 if buffer:
733 print_line(buffer)
734 buffer = ""
735 # The process terminated; print any remaining output
736 if buffer:
737 print_line(buffer)
738 # Get the exit status, print it and send it to termination_func
739 status = self.get_status()
740 if status is None:
741 return
742 print_line("(Process terminated with status %s)" % status)
743 try:
744 params = self.termination_params + (status,)
745 self.termination_func(*params)
746 except TypeError:
747 pass
748 finally:
749 self.tail_thread = None
lmrbbc9dd52009-07-22 20:33:47 +0000750
751
lmrc07f3812009-10-14 10:27:04 +0000752 def _start_thread(self):
lmree4338e2010-07-08 23:40:10 +0000753 self.tail_thread = threading.Thread(target=self._tail,
754 name="tail_thread_%s" % self.id)
lmrc07f3812009-10-14 10:27:04 +0000755 self.tail_thread.start()
756
757
lmrbbc9dd52009-07-22 20:33:47 +0000758 def _join_thread(self):
759 # Wait for the tail thread to exit
lmree4338e2010-07-08 23:40:10 +0000760 # (it's done this way because self.tail_thread may become None at any
761 # time)
762 t = self.tail_thread
763 if t:
764 t.join()
lmrbbc9dd52009-07-22 20:33:47 +0000765
766
767class kvm_expect(kvm_tail):
768 """
769 This class runs a child process in the background and provides expect-like
770 services.
771
772 It also provides all of kvm_tail's functionality.
773 """
774
lmrcec66772010-06-22 01:55:50 +0000775 def __init__(self, command=None, id=None, auto_close=False, echo=False,
776 linesep="\n", termination_func=None, termination_params=(),
777 output_func=None, output_params=(), output_prefix=""):
lmrbbc9dd52009-07-22 20:33:47 +0000778 """
779 Initialize the class and run command as a child process.
780
781 @param command: Command to run, or None if accessing an already running
782 server.
783 @param id: ID of an already running server, if accessing a running
784 server, or None if starting a new one.
lmrcec66772010-06-22 01:55:50 +0000785 @param auto_close: If True, close() the instance automatically when its
786 reference count drops to zero (default False).
lmrbbc9dd52009-07-22 20:33:47 +0000787 @param echo: Boolean indicating whether echo should be initially
788 enabled for the pseudo terminal running the subprocess. This
789 parameter has an effect only when starting a new server.
790 @param linesep: Line separator to be appended to strings sent to the
791 child process by sendline().
792 @param termination_func: Function to call when the process exits. The
793 function must accept a single exit status parameter.
lmr4fe15ba2009-08-13 04:11:26 +0000794 @param termination_params: Parameters to send to termination_func
795 before the exit status.
lmrbbc9dd52009-07-22 20:33:47 +0000796 @param output_func: Function to call whenever a line of output is
797 available from the STDOUT or STDERR streams of the process.
798 The function must accept a single string parameter. The string
799 does not include the final newline.
lmr4fe15ba2009-08-13 04:11:26 +0000800 @param output_params: Parameters to send to output_func before the
801 output line.
lmrbbc9dd52009-07-22 20:33:47 +0000802 @param output_prefix: String to prepend to lines sent to output_func.
803 """
804 # Add a reader
805 self._add_reader("expect")
806
807 # Init the superclass
lmrcec66772010-06-22 01:55:50 +0000808 kvm_tail.__init__(self, command, id, auto_close, echo, linesep,
lmr4fe15ba2009-08-13 04:11:26 +0000809 termination_func, termination_params,
810 output_func, output_params, output_prefix)
lmrbbc9dd52009-07-22 20:33:47 +0000811
812
813 def __getinitargs__(self):
814 return kvm_tail.__getinitargs__(self)
815
816
817 def read_nonblocking(self, timeout=None):
818 """
819 Read from child until there is nothing to read for timeout seconds.
820
821 @param timeout: Time (seconds) to wait before we give up reading from
822 the child process, or None to use the default value.
823 """
824 if timeout is None:
825 timeout = 0.1
826 fd = self._get_fd("expect")
827 data = ""
828 while True:
829 try:
830 r, w, x = select.select([fd], [], [], timeout)
831 except:
832 return data
833 if fd in r:
834 new_data = os.read(fd, 1024)
835 if not new_data:
836 return data
837 data += new_data
838 else:
839 return data
840
841
842 def match_patterns(self, str, patterns):
843 """
844 Match str against a list of patterns.
845
846 Return the index of the first pattern that matches a substring of str.
847 None and empty strings in patterns are ignored.
848 If no match is found, return None.
849
850 @param patterns: List of strings (regular expression patterns).
851 """
852 for i in range(len(patterns)):
853 if not patterns[i]:
854 continue
855 if re.search(patterns[i], str):
856 return i
857
858
859 def read_until_output_matches(self, patterns, filter=lambda x: x,
860 timeout=30.0, internal_timeout=None,
861 print_func=None):
862 """
863 Read using read_nonblocking until a match is found using match_patterns,
864 or until timeout expires. Before attempting to search for a match, the
865 data is filtered using the filter function provided.
866
867 @brief: Read from child using read_nonblocking until a pattern
868 matches.
869 @param patterns: List of strings (regular expression patterns)
870 @param filter: Function to apply to the data read from the child before
871 attempting to match it against the patterns (should take and
872 return a string)
873 @param timeout: The duration (in seconds) to wait until a match is
874 found
875 @param internal_timeout: The timeout to pass to read_nonblocking
876 @param print_func: A function to be used to print the data being read
877 (should take a string parameter)
878 @return: Tuple containing the match index (or None if no match was
879 found) and the data read so far.
880 """
881 match = None
882 data = ""
883
lmrf48c5cc2009-10-05 19:22:49 +0000884 fd = self._get_fd("expect")
lmrbbc9dd52009-07-22 20:33:47 +0000885 end_time = time.time() + timeout
lmrf48c5cc2009-10-05 19:22:49 +0000886 while True:
lmr04d5b012009-11-10 16:28:22 +0000887 try:
888 r, w, x = select.select([fd], [], [],
889 max(0, end_time - time.time()))
890 except (select.error, TypeError):
891 break
892 if fd not in r:
893 break
lmrbbc9dd52009-07-22 20:33:47 +0000894 # Read data from child
895 newdata = self.read_nonblocking(internal_timeout)
896 # Print it if necessary
897 if print_func and newdata:
898 str = newdata
899 if str.endswith("\n"):
900 str = str[:-1]
901 for line in str.split("\n"):
lmrcf668fe2010-06-22 02:07:37 +0000902 print_func(line)
lmrbbc9dd52009-07-22 20:33:47 +0000903 data += newdata
904
905 done = False
906 # Look for patterns
907 match = self.match_patterns(filter(data), patterns)
908 if match is not None:
909 done = True
910 # Check if child has died
911 if not self.is_alive():
lmrf48c5cc2009-10-05 19:22:49 +0000912 logging.debug("Process terminated with status %s" %
913 self.get_status())
lmrbbc9dd52009-07-22 20:33:47 +0000914 done = True
915 # Are we done?
916 if done: break
917
918 # Print some debugging info
919 if match is None and (self.is_alive() or self.get_status() != 0):
920 logging.debug("Timeout elapsed or process terminated. Output:" +
921 kvm_utils.format_str_for_message(data.strip()))
922
923 return (match, data)
924
925
926 def read_until_last_word_matches(self, patterns, timeout=30.0,
927 internal_timeout=None, print_func=None):
928 """
929 Read using read_nonblocking until the last word of the output matches
930 one of the patterns (using match_patterns), or until timeout expires.
931
932 @param patterns: A list of strings (regular expression patterns)
933 @param timeout: The duration (in seconds) to wait until a match is
934 found
935 @param internal_timeout: The timeout to pass to read_nonblocking
936 @param print_func: A function to be used to print the data being read
937 (should take a string parameter)
938 @return: A tuple containing the match index (or None if no match was
939 found) and the data read so far.
940 """
941 def get_last_word(str):
942 if str:
943 return str.split()[-1]
944 else:
945 return ""
946
947 return self.read_until_output_matches(patterns, get_last_word,
948 timeout, internal_timeout,
949 print_func)
950
951
952 def read_until_last_line_matches(self, patterns, timeout=30.0,
953 internal_timeout=None, print_func=None):
954 """
955 Read using read_nonblocking until the last non-empty line of the output
956 matches one of the patterns (using match_patterns), or until timeout
957 expires. Return a tuple containing the match index (or None if no match
958 was found) and the data read so far.
959
960 @brief: Read using read_nonblocking until the last non-empty line
961 matches a pattern.
962
963 @param patterns: A list of strings (regular expression patterns)
964 @param timeout: The duration (in seconds) to wait until a match is
965 found
966 @param internal_timeout: The timeout to pass to read_nonblocking
967 @param print_func: A function to be used to print the data being read
968 (should take a string parameter)
969 """
970 def get_last_nonempty_line(str):
971 nonempty_lines = [l for l in str.splitlines() if l.strip()]
972 if nonempty_lines:
973 return nonempty_lines[-1]
974 else:
975 return ""
976
977 return self.read_until_output_matches(patterns, get_last_nonempty_line,
978 timeout, internal_timeout,
979 print_func)
980
981
982class kvm_shell_session(kvm_expect):
983 """
984 This class runs a child process in the background. It it suited for
985 processes that provide an interactive shell, such as SSH and Telnet.
986
987 It provides all services of kvm_expect and kvm_tail. In addition, it
988 provides command running services, and a utility function to test the
989 process for responsiveness.
990 """
991
lmrcec66772010-06-22 01:55:50 +0000992 def __init__(self, command=None, id=None, auto_close=True, echo=False,
993 linesep="\n", termination_func=None, termination_params=(),
994 output_func=None, output_params=(), output_prefix="",
lmrbbc9dd52009-07-22 20:33:47 +0000995 prompt=r"[\#\$]\s*$", status_test_command="echo $?"):
996 """
997 Initialize the class and run command as a child process.
998
999 @param command: Command to run, or None if accessing an already running
1000 server.
1001 @param id: ID of an already running server, if accessing a running
1002 server, or None if starting a new one.
lmrcec66772010-06-22 01:55:50 +00001003 @param auto_close: If True, close() the instance automatically when its
1004 reference count drops to zero (default True).
lmrbbc9dd52009-07-22 20:33:47 +00001005 @param echo: Boolean indicating whether echo should be initially
1006 enabled for the pseudo terminal running the subprocess. This
1007 parameter has an effect only when starting a new server.
1008 @param linesep: Line separator to be appended to strings sent to the
1009 child process by sendline().
1010 @param termination_func: Function to call when the process exits. The
1011 function must accept a single exit status parameter.
lmr4fe15ba2009-08-13 04:11:26 +00001012 @param termination_params: Parameters to send to termination_func
1013 before the exit status.
lmrbbc9dd52009-07-22 20:33:47 +00001014 @param output_func: Function to call whenever a line of output is
1015 available from the STDOUT or STDERR streams of the process.
1016 The function must accept a single string parameter. The string
1017 does not include the final newline.
lmr4fe15ba2009-08-13 04:11:26 +00001018 @param output_params: Parameters to send to output_func before the
1019 output line.
lmrbbc9dd52009-07-22 20:33:47 +00001020 @param output_prefix: String to prepend to lines sent to output_func.
1021 @param prompt: Regular expression describing the shell's prompt line.
1022 @param status_test_command: Command to be used for getting the last
1023 exit status of commands run inside the shell (used by
1024 get_command_status_output() and friends).
1025 """
1026 # Init the superclass
lmrcec66772010-06-22 01:55:50 +00001027 kvm_expect.__init__(self, command, id, auto_close, echo, linesep,
lmr4fe15ba2009-08-13 04:11:26 +00001028 termination_func, termination_params,
1029 output_func, output_params, output_prefix)
lmrbbc9dd52009-07-22 20:33:47 +00001030
1031 # Remember some attributes
1032 self.prompt = prompt
1033 self.status_test_command = status_test_command
1034
1035
1036 def __getinitargs__(self):
1037 return kvm_expect.__getinitargs__(self) + (self.prompt,
1038 self.status_test_command)
1039
1040
1041 def set_prompt(self, prompt):
1042 """
1043 Set the prompt attribute for later use by read_up_to_prompt.
1044
1045 @param: String that describes the prompt contents.
1046 """
1047 self.prompt = prompt
1048
1049
1050 def set_status_test_command(self, status_test_command):
1051 """
1052 Set the command to be sent in order to get the last exit status.
1053
1054 @param status_test_command: Command that will be sent to get the last
1055 exit status.
1056 """
1057 self.status_test_command = status_test_command
1058
1059
1060 def is_responsive(self, timeout=5.0):
1061 """
1062 Return True if the process responds to STDIN/terminal input.
1063
1064 Send a newline to the child process (e.g. SSH or Telnet) and read some
1065 output using read_nonblocking().
1066 If all is OK, some output should be available (e.g. the shell prompt).
1067 In that case return True. Otherwise return False.
1068
1069 @param timeout: Time duration to wait before the process is considered
1070 unresponsive.
1071 """
1072 # Read all output that's waiting to be read, to make sure the output
1073 # we read next is in response to the newline sent
lmr59b98db2009-10-05 19:11:21 +00001074 self.read_nonblocking(timeout=0)
lmrbbc9dd52009-07-22 20:33:47 +00001075 # Send a newline
1076 self.sendline()
1077 # Wait up to timeout seconds for some output from the child
1078 end_time = time.time() + timeout
1079 while time.time() < end_time:
1080 time.sleep(0.5)
1081 if self.read_nonblocking(timeout=0).strip():
1082 return True
1083 # No output -- report unresponsive
1084 return False
1085
1086
1087 def read_up_to_prompt(self, timeout=30.0, internal_timeout=None,
1088 print_func=None):
1089 """
1090 Read using read_nonblocking until the last non-empty line of the output
1091 matches the prompt regular expression set by set_prompt, or until
1092 timeout expires.
1093
1094 @brief: Read using read_nonblocking until the last non-empty line
1095 matches the prompt.
1096
1097 @param timeout: The duration (in seconds) to wait until a match is
1098 found
1099 @param internal_timeout: The timeout to pass to read_nonblocking
1100 @param print_func: A function to be used to print the data being
1101 read (should take a string parameter)
1102
1103 @return: A tuple containing True/False indicating whether the prompt
1104 was found, and the data read so far.
1105 """
1106 (match, output) = self.read_until_last_line_matches([self.prompt],
1107 timeout,
1108 internal_timeout,
1109 print_func)
1110 return (match is not None, output)
1111
1112
1113 def get_command_status_output(self, command, timeout=30.0,
1114 internal_timeout=None, print_func=None):
1115 """
1116 Send a command and return its exit status and output.
1117
1118 @param command: Command to send (must not contain newline characters)
1119 @param timeout: The duration (in seconds) to wait until a match is
1120 found
1121 @param internal_timeout: The timeout to pass to read_nonblocking
1122 @param print_func: A function to be used to print the data being read
1123 (should take a string parameter)
1124
1125 @return: A tuple (status, output) where status is the exit status or
1126 None if no exit status is available (e.g. timeout elapsed), and
1127 output is the output of command.
1128 """
1129 def remove_command_echo(str, cmd):
1130 if str and str.splitlines()[0] == cmd:
1131 str = "".join(str.splitlines(True)[1:])
1132 return str
1133
1134 def remove_last_nonempty_line(str):
1135 return "".join(str.rstrip().splitlines(True)[:-1])
1136
1137 # Print some debugging info
1138 logging.debug("Sending command: %s" % command)
1139
1140 # Read everything that's waiting to be read
lmr59b98db2009-10-05 19:11:21 +00001141 self.read_nonblocking(timeout=0)
lmrbbc9dd52009-07-22 20:33:47 +00001142
1143 # Send the command and get its output
1144 self.sendline(command)
1145 (match, output) = self.read_up_to_prompt(timeout, internal_timeout,
1146 print_func)
1147 # Remove the echoed command from the output
1148 output = remove_command_echo(output, command)
1149 # If the prompt was not found, return the output so far
1150 if not match:
1151 return (None, output)
1152 # Remove the final shell prompt from the output
1153 output = remove_last_nonempty_line(output)
1154
1155 # Send the 'echo ...' command to get the last exit status
1156 self.sendline(self.status_test_command)
1157 (match, status) = self.read_up_to_prompt(10.0, internal_timeout)
1158 if not match:
1159 return (None, output)
1160 status = remove_command_echo(status, self.status_test_command)
1161 status = remove_last_nonempty_line(status)
1162 # Get the first line consisting of digits only
1163 digit_lines = [l for l in status.splitlines() if l.strip().isdigit()]
1164 if not digit_lines:
1165 return (None, output)
1166 status = int(digit_lines[0].strip())
1167
1168 # Print some debugging info
1169 if status != 0:
1170 logging.debug("Command failed; status: %d, output:%s", status,
1171 kvm_utils.format_str_for_message(output.strip()))
1172
1173 return (status, output)
1174
1175
1176 def get_command_status(self, command, timeout=30.0, internal_timeout=None,
1177 print_func=None):
1178 """
1179 Send a command and return its exit status.
1180
1181 @param command: Command to send
1182 @param timeout: The duration (in seconds) to wait until a match is
1183 found
1184 @param internal_timeout: The timeout to pass to read_nonblocking
1185 @param print_func: A function to be used to print the data being read
1186 (should take a string parameter)
1187
1188 @return: Exit status or None if no exit status is available (e.g.
1189 timeout elapsed).
1190 """
1191 (status, output) = self.get_command_status_output(command, timeout,
1192 internal_timeout,
1193 print_func)
1194 return status
1195
1196
1197 def get_command_output(self, command, timeout=30.0, internal_timeout=None,
1198 print_func=None):
1199 """
1200 Send a command and return its output.
1201
1202 @param command: Command to send
1203 @param timeout: The duration (in seconds) to wait until a match is
1204 found
1205 @param internal_timeout: The timeout to pass to read_nonblocking
1206 @param print_func: A function to be used to print the data being read
1207 (should take a string parameter)
1208 """
1209 (status, output) = self.get_command_status_output(command, timeout,
1210 internal_timeout,
1211 print_func)
1212 return output