blob: 93a842912ecbbd1847da601c2ecbe3388687b6f2 [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
551class kvm_tail(kvm_spawn):
552 """
553 This class runs a child process in the background and sends its output in
554 real time, line-by-line, to a callback function.
555
556 See kvm_spawn's docstring.
557
558 This class uses a single pipe reader to read data in real time from the
559 child process and report it to a given callback function.
560 When the child process exits, its exit status is reported to an additional
561 callback function.
562
563 When this class is unpickled, it automatically resumes reporting output.
564 """
565
lmrcec66772010-06-22 01:55:50 +0000566 def __init__(self, command=None, id=None, auto_close=False, echo=False,
567 linesep="\n", termination_func=None, termination_params=(),
568 output_func=None, output_params=(), output_prefix=""):
lmrbbc9dd52009-07-22 20:33:47 +0000569 """
570 Initialize the class and run command as a child process.
571
572 @param command: Command to run, or None if accessing an already running
573 server.
574 @param id: ID of an already running server, if accessing a running
575 server, or None if starting a new one.
lmrcec66772010-06-22 01:55:50 +0000576 @param auto_close: If True, close() the instance automatically when its
577 reference count drops to zero (default False).
lmrbbc9dd52009-07-22 20:33:47 +0000578 @param echo: Boolean indicating whether echo should be initially
579 enabled for the pseudo terminal running the subprocess. This
580 parameter has an effect only when starting a new server.
581 @param linesep: Line separator to be appended to strings sent to the
582 child process by sendline().
583 @param termination_func: Function to call when the process exits. The
584 function must accept a single exit status parameter.
lmr4fe15ba2009-08-13 04:11:26 +0000585 @param termination_params: Parameters to send to termination_func
586 before the exit status.
lmrbbc9dd52009-07-22 20:33:47 +0000587 @param output_func: Function to call whenever a line of output is
588 available from the STDOUT or STDERR streams of the process.
589 The function must accept a single string parameter. The string
590 does not include the final newline.
lmr4fe15ba2009-08-13 04:11:26 +0000591 @param output_params: Parameters to send to output_func before the
592 output line.
lmrbbc9dd52009-07-22 20:33:47 +0000593 @param output_prefix: String to prepend to lines sent to output_func.
594 """
595 # Add a reader and a close hook
596 self._add_reader("tail")
lmr16063962009-10-14 10:27:59 +0000597 self._add_close_hook(kvm_tail._join_thread)
lmrbbc9dd52009-07-22 20:33:47 +0000598
599 # Init the superclass
lmrcec66772010-06-22 01:55:50 +0000600 kvm_spawn.__init__(self, command, id, auto_close, echo, linesep)
lmrbbc9dd52009-07-22 20:33:47 +0000601
602 # Remember some attributes
603 self.termination_func = termination_func
lmr4fe15ba2009-08-13 04:11:26 +0000604 self.termination_params = termination_params
lmrbbc9dd52009-07-22 20:33:47 +0000605 self.output_func = output_func
lmr4fe15ba2009-08-13 04:11:26 +0000606 self.output_params = output_params
lmrbbc9dd52009-07-22 20:33:47 +0000607 self.output_prefix = output_prefix
608
609 # Start the thread in the background
lmrc07f3812009-10-14 10:27:04 +0000610 self.tail_thread = None
lmra4197002009-08-13 05:00:51 +0000611 self.__thread_kill_requested = False
lmrc07f3812009-10-14 10:27:04 +0000612 if termination_func or output_func:
613 self._start_thread()
lmrbbc9dd52009-07-22 20:33:47 +0000614
615
616 def __getinitargs__(self):
617 return kvm_spawn.__getinitargs__(self) + (self.termination_func,
lmr4fe15ba2009-08-13 04:11:26 +0000618 self.termination_params,
lmrbbc9dd52009-07-22 20:33:47 +0000619 self.output_func,
lmr4fe15ba2009-08-13 04:11:26 +0000620 self.output_params,
lmrbbc9dd52009-07-22 20:33:47 +0000621 self.output_prefix)
622
623
624 def set_termination_func(self, termination_func):
625 """
626 Set the termination_func attribute. See __init__() for details.
627
628 @param termination_func: Function to call when the process terminates.
629 Must take a single parameter -- the exit status.
630 """
631 self.termination_func = termination_func
lmrc07f3812009-10-14 10:27:04 +0000632 if termination_func and not self.tail_thread:
633 self._start_thread()
lmrbbc9dd52009-07-22 20:33:47 +0000634
635
lmr4fe15ba2009-08-13 04:11:26 +0000636 def set_termination_params(self, termination_params):
637 """
638 Set the termination_params attribute. See __init__() for details.
639
640 @param termination_params: Parameters to send to termination_func
641 before the exit status.
642 """
643 self.termination_params = termination_params
644
645
lmrbbc9dd52009-07-22 20:33:47 +0000646 def set_output_func(self, output_func):
647 """
648 Set the output_func attribute. See __init__() for details.
649
650 @param output_func: Function to call for each line of STDOUT/STDERR
651 output from the process. Must take a single string parameter.
652 """
653 self.output_func = output_func
lmrc07f3812009-10-14 10:27:04 +0000654 if output_func and not self.tail_thread:
655 self._start_thread()
lmrbbc9dd52009-07-22 20:33:47 +0000656
657
lmr4fe15ba2009-08-13 04:11:26 +0000658 def set_output_params(self, output_params):
659 """
660 Set the output_params attribute. See __init__() for details.
661
662 @param output_params: Parameters to send to output_func before the
663 output line.
664 """
665 self.output_params = output_params
666
667
lmrbbc9dd52009-07-22 20:33:47 +0000668 def set_output_prefix(self, output_prefix):
669 """
670 Set the output_prefix attribute. See __init__() for details.
671
672 @param output_prefix: String to pre-pend to each line sent to
673 output_func (see set_output_callback()).
674 """
675 self.output_prefix = output_prefix
676
677
lmra4197002009-08-13 05:00:51 +0000678 def kill_tail_thread(self):
679 """
680 Stop the tailing thread which calls output_func() and
681 termination_func().
682 """
683 self.__thread_kill_requested = True
684 self._join_thread()
685
686
lmrbbc9dd52009-07-22 20:33:47 +0000687 def _tail(self):
688 def print_line(text):
689 # Pre-pend prefix and remove trailing whitespace
690 text = self.output_prefix + text.rstrip()
lmrcf668fe2010-06-22 02:07:37 +0000691 # Pass text to output_func
lmrbbc9dd52009-07-22 20:33:47 +0000692 try:
lmr4fe15ba2009-08-13 04:11:26 +0000693 params = self.output_params + (text,)
694 self.output_func(*params)
lmrbbc9dd52009-07-22 20:33:47 +0000695 except TypeError:
696 pass
697
698 fd = self._get_fd("tail")
699 buffer = ""
700 while True:
lmra4197002009-08-13 05:00:51 +0000701 if self.__thread_kill_requested:
702 return
lmrbbc9dd52009-07-22 20:33:47 +0000703 try:
704 # See if there's any data to read from the pipe
705 r, w, x = select.select([fd], [], [], 0.05)
706 except:
707 break
708 if fd in r:
709 # Some data is available; read it
710 new_data = os.read(fd, 1024)
711 if not new_data:
712 break
713 buffer += new_data
714 # Send the output to output_func line by line
715 # (except for the last line)
716 if self.output_func:
717 lines = buffer.split("\n")
718 for line in lines[:-1]:
719 print_line(line)
720 # Leave only the last line
721 last_newline_index = buffer.rfind("\n")
722 buffer = buffer[last_newline_index+1:]
723 else:
724 # No output is available right now; flush the buffer
725 if buffer:
726 print_line(buffer)
727 buffer = ""
728 # The process terminated; print any remaining output
729 if buffer:
730 print_line(buffer)
731 # Get the exit status, print it and send it to termination_func
732 status = self.get_status()
733 if status is None:
734 return
735 print_line("(Process terminated with status %s)" % status)
736 try:
lmr4fe15ba2009-08-13 04:11:26 +0000737 params = self.termination_params + (status,)
738 self.termination_func(*params)
lmrbbc9dd52009-07-22 20:33:47 +0000739 except TypeError:
740 pass
741
742
lmrc07f3812009-10-14 10:27:04 +0000743 def _start_thread(self):
744 self.tail_thread = threading.Thread(None, self._tail)
745 self.tail_thread.start()
746
747
lmrbbc9dd52009-07-22 20:33:47 +0000748 def _join_thread(self):
749 # Wait for the tail thread to exit
750 if self.tail_thread:
751 self.tail_thread.join()
752
753
754class kvm_expect(kvm_tail):
755 """
756 This class runs a child process in the background and provides expect-like
757 services.
758
759 It also provides all of kvm_tail's functionality.
760 """
761
lmrcec66772010-06-22 01:55:50 +0000762 def __init__(self, command=None, id=None, auto_close=False, echo=False,
763 linesep="\n", termination_func=None, termination_params=(),
764 output_func=None, output_params=(), output_prefix=""):
lmrbbc9dd52009-07-22 20:33:47 +0000765 """
766 Initialize the class and run command as a child process.
767
768 @param command: Command to run, or None if accessing an already running
769 server.
770 @param id: ID of an already running server, if accessing a running
771 server, or None if starting a new one.
lmrcec66772010-06-22 01:55:50 +0000772 @param auto_close: If True, close() the instance automatically when its
773 reference count drops to zero (default False).
lmrbbc9dd52009-07-22 20:33:47 +0000774 @param echo: Boolean indicating whether echo should be initially
775 enabled for the pseudo terminal running the subprocess. This
776 parameter has an effect only when starting a new server.
777 @param linesep: Line separator to be appended to strings sent to the
778 child process by sendline().
779 @param termination_func: Function to call when the process exits. The
780 function must accept a single exit status parameter.
lmr4fe15ba2009-08-13 04:11:26 +0000781 @param termination_params: Parameters to send to termination_func
782 before the exit status.
lmrbbc9dd52009-07-22 20:33:47 +0000783 @param output_func: Function to call whenever a line of output is
784 available from the STDOUT or STDERR streams of the process.
785 The function must accept a single string parameter. The string
786 does not include the final newline.
lmr4fe15ba2009-08-13 04:11:26 +0000787 @param output_params: Parameters to send to output_func before the
788 output line.
lmrbbc9dd52009-07-22 20:33:47 +0000789 @param output_prefix: String to prepend to lines sent to output_func.
790 """
791 # Add a reader
792 self._add_reader("expect")
793
794 # Init the superclass
lmrcec66772010-06-22 01:55:50 +0000795 kvm_tail.__init__(self, command, id, auto_close, echo, linesep,
lmr4fe15ba2009-08-13 04:11:26 +0000796 termination_func, termination_params,
797 output_func, output_params, output_prefix)
lmrbbc9dd52009-07-22 20:33:47 +0000798
799
800 def __getinitargs__(self):
801 return kvm_tail.__getinitargs__(self)
802
803
804 def read_nonblocking(self, timeout=None):
805 """
806 Read from child until there is nothing to read for timeout seconds.
807
808 @param timeout: Time (seconds) to wait before we give up reading from
809 the child process, or None to use the default value.
810 """
811 if timeout is None:
812 timeout = 0.1
813 fd = self._get_fd("expect")
814 data = ""
815 while True:
816 try:
817 r, w, x = select.select([fd], [], [], timeout)
818 except:
819 return data
820 if fd in r:
821 new_data = os.read(fd, 1024)
822 if not new_data:
823 return data
824 data += new_data
825 else:
826 return data
827
828
829 def match_patterns(self, str, patterns):
830 """
831 Match str against a list of patterns.
832
833 Return the index of the first pattern that matches a substring of str.
834 None and empty strings in patterns are ignored.
835 If no match is found, return None.
836
837 @param patterns: List of strings (regular expression patterns).
838 """
839 for i in range(len(patterns)):
840 if not patterns[i]:
841 continue
842 if re.search(patterns[i], str):
843 return i
844
845
846 def read_until_output_matches(self, patterns, filter=lambda x: x,
847 timeout=30.0, internal_timeout=None,
848 print_func=None):
849 """
850 Read using read_nonblocking until a match is found using match_patterns,
851 or until timeout expires. Before attempting to search for a match, the
852 data is filtered using the filter function provided.
853
854 @brief: Read from child using read_nonblocking until a pattern
855 matches.
856 @param patterns: List of strings (regular expression patterns)
857 @param filter: Function to apply to the data read from the child before
858 attempting to match it against the patterns (should take and
859 return a string)
860 @param timeout: The duration (in seconds) to wait until a match is
861 found
862 @param internal_timeout: The timeout to pass to read_nonblocking
863 @param print_func: A function to be used to print the data being read
864 (should take a string parameter)
865 @return: Tuple containing the match index (or None if no match was
866 found) and the data read so far.
867 """
868 match = None
869 data = ""
870
lmrf48c5cc2009-10-05 19:22:49 +0000871 fd = self._get_fd("expect")
lmrbbc9dd52009-07-22 20:33:47 +0000872 end_time = time.time() + timeout
lmrf48c5cc2009-10-05 19:22:49 +0000873 while True:
lmr04d5b012009-11-10 16:28:22 +0000874 try:
875 r, w, x = select.select([fd], [], [],
876 max(0, end_time - time.time()))
877 except (select.error, TypeError):
878 break
879 if fd not in r:
880 break
lmrbbc9dd52009-07-22 20:33:47 +0000881 # Read data from child
882 newdata = self.read_nonblocking(internal_timeout)
883 # Print it if necessary
884 if print_func and newdata:
885 str = newdata
886 if str.endswith("\n"):
887 str = str[:-1]
888 for line in str.split("\n"):
lmrcf668fe2010-06-22 02:07:37 +0000889 print_func(line)
lmrbbc9dd52009-07-22 20:33:47 +0000890 data += newdata
891
892 done = False
893 # Look for patterns
894 match = self.match_patterns(filter(data), patterns)
895 if match is not None:
896 done = True
897 # Check if child has died
898 if not self.is_alive():
lmrf48c5cc2009-10-05 19:22:49 +0000899 logging.debug("Process terminated with status %s" %
900 self.get_status())
lmrbbc9dd52009-07-22 20:33:47 +0000901 done = True
902 # Are we done?
903 if done: break
904
905 # Print some debugging info
906 if match is None and (self.is_alive() or self.get_status() != 0):
907 logging.debug("Timeout elapsed or process terminated. Output:" +
908 kvm_utils.format_str_for_message(data.strip()))
909
910 return (match, data)
911
912
913 def read_until_last_word_matches(self, patterns, timeout=30.0,
914 internal_timeout=None, print_func=None):
915 """
916 Read using read_nonblocking until the last word of the output matches
917 one of the patterns (using match_patterns), or until timeout expires.
918
919 @param patterns: A list of strings (regular expression patterns)
920 @param timeout: The duration (in seconds) to wait until a match is
921 found
922 @param internal_timeout: The timeout to pass to read_nonblocking
923 @param print_func: A function to be used to print the data being read
924 (should take a string parameter)
925 @return: A tuple containing the match index (or None if no match was
926 found) and the data read so far.
927 """
928 def get_last_word(str):
929 if str:
930 return str.split()[-1]
931 else:
932 return ""
933
934 return self.read_until_output_matches(patterns, get_last_word,
935 timeout, internal_timeout,
936 print_func)
937
938
939 def read_until_last_line_matches(self, patterns, timeout=30.0,
940 internal_timeout=None, print_func=None):
941 """
942 Read using read_nonblocking until the last non-empty line of the output
943 matches one of the patterns (using match_patterns), or until timeout
944 expires. Return a tuple containing the match index (or None if no match
945 was found) and the data read so far.
946
947 @brief: Read using read_nonblocking until the last non-empty line
948 matches a pattern.
949
950 @param patterns: A list of strings (regular expression patterns)
951 @param timeout: The duration (in seconds) to wait until a match is
952 found
953 @param internal_timeout: The timeout to pass to read_nonblocking
954 @param print_func: A function to be used to print the data being read
955 (should take a string parameter)
956 """
957 def get_last_nonempty_line(str):
958 nonempty_lines = [l for l in str.splitlines() if l.strip()]
959 if nonempty_lines:
960 return nonempty_lines[-1]
961 else:
962 return ""
963
964 return self.read_until_output_matches(patterns, get_last_nonempty_line,
965 timeout, internal_timeout,
966 print_func)
967
968
969class kvm_shell_session(kvm_expect):
970 """
971 This class runs a child process in the background. It it suited for
972 processes that provide an interactive shell, such as SSH and Telnet.
973
974 It provides all services of kvm_expect and kvm_tail. In addition, it
975 provides command running services, and a utility function to test the
976 process for responsiveness.
977 """
978
lmrcec66772010-06-22 01:55:50 +0000979 def __init__(self, command=None, id=None, auto_close=True, echo=False,
980 linesep="\n", termination_func=None, termination_params=(),
981 output_func=None, output_params=(), output_prefix="",
lmrbbc9dd52009-07-22 20:33:47 +0000982 prompt=r"[\#\$]\s*$", status_test_command="echo $?"):
983 """
984 Initialize the class and run command as a child process.
985
986 @param command: Command to run, or None if accessing an already running
987 server.
988 @param id: ID of an already running server, if accessing a running
989 server, or None if starting a new one.
lmrcec66772010-06-22 01:55:50 +0000990 @param auto_close: If True, close() the instance automatically when its
991 reference count drops to zero (default True).
lmrbbc9dd52009-07-22 20:33:47 +0000992 @param echo: Boolean indicating whether echo should be initially
993 enabled for the pseudo terminal running the subprocess. This
994 parameter has an effect only when starting a new server.
995 @param linesep: Line separator to be appended to strings sent to the
996 child process by sendline().
997 @param termination_func: Function to call when the process exits. The
998 function must accept a single exit status parameter.
lmr4fe15ba2009-08-13 04:11:26 +0000999 @param termination_params: Parameters to send to termination_func
1000 before the exit status.
lmrbbc9dd52009-07-22 20:33:47 +00001001 @param output_func: Function to call whenever a line of output is
1002 available from the STDOUT or STDERR streams of the process.
1003 The function must accept a single string parameter. The string
1004 does not include the final newline.
lmr4fe15ba2009-08-13 04:11:26 +00001005 @param output_params: Parameters to send to output_func before the
1006 output line.
lmrbbc9dd52009-07-22 20:33:47 +00001007 @param output_prefix: String to prepend to lines sent to output_func.
1008 @param prompt: Regular expression describing the shell's prompt line.
1009 @param status_test_command: Command to be used for getting the last
1010 exit status of commands run inside the shell (used by
1011 get_command_status_output() and friends).
1012 """
1013 # Init the superclass
lmrcec66772010-06-22 01:55:50 +00001014 kvm_expect.__init__(self, command, id, auto_close, echo, linesep,
lmr4fe15ba2009-08-13 04:11:26 +00001015 termination_func, termination_params,
1016 output_func, output_params, output_prefix)
lmrbbc9dd52009-07-22 20:33:47 +00001017
1018 # Remember some attributes
1019 self.prompt = prompt
1020 self.status_test_command = status_test_command
1021
1022
1023 def __getinitargs__(self):
1024 return kvm_expect.__getinitargs__(self) + (self.prompt,
1025 self.status_test_command)
1026
1027
1028 def set_prompt(self, prompt):
1029 """
1030 Set the prompt attribute for later use by read_up_to_prompt.
1031
1032 @param: String that describes the prompt contents.
1033 """
1034 self.prompt = prompt
1035
1036
1037 def set_status_test_command(self, status_test_command):
1038 """
1039 Set the command to be sent in order to get the last exit status.
1040
1041 @param status_test_command: Command that will be sent to get the last
1042 exit status.
1043 """
1044 self.status_test_command = status_test_command
1045
1046
1047 def is_responsive(self, timeout=5.0):
1048 """
1049 Return True if the process responds to STDIN/terminal input.
1050
1051 Send a newline to the child process (e.g. SSH or Telnet) and read some
1052 output using read_nonblocking().
1053 If all is OK, some output should be available (e.g. the shell prompt).
1054 In that case return True. Otherwise return False.
1055
1056 @param timeout: Time duration to wait before the process is considered
1057 unresponsive.
1058 """
1059 # Read all output that's waiting to be read, to make sure the output
1060 # we read next is in response to the newline sent
lmr59b98db2009-10-05 19:11:21 +00001061 self.read_nonblocking(timeout=0)
lmrbbc9dd52009-07-22 20:33:47 +00001062 # Send a newline
1063 self.sendline()
1064 # Wait up to timeout seconds for some output from the child
1065 end_time = time.time() + timeout
1066 while time.time() < end_time:
1067 time.sleep(0.5)
1068 if self.read_nonblocking(timeout=0).strip():
1069 return True
1070 # No output -- report unresponsive
1071 return False
1072
1073
1074 def read_up_to_prompt(self, timeout=30.0, internal_timeout=None,
1075 print_func=None):
1076 """
1077 Read using read_nonblocking until the last non-empty line of the output
1078 matches the prompt regular expression set by set_prompt, or until
1079 timeout expires.
1080
1081 @brief: Read using read_nonblocking until the last non-empty line
1082 matches the prompt.
1083
1084 @param timeout: The duration (in seconds) to wait until a match is
1085 found
1086 @param internal_timeout: The timeout to pass to read_nonblocking
1087 @param print_func: A function to be used to print the data being
1088 read (should take a string parameter)
1089
1090 @return: A tuple containing True/False indicating whether the prompt
1091 was found, and the data read so far.
1092 """
1093 (match, output) = self.read_until_last_line_matches([self.prompt],
1094 timeout,
1095 internal_timeout,
1096 print_func)
1097 return (match is not None, output)
1098
1099
1100 def get_command_status_output(self, command, timeout=30.0,
1101 internal_timeout=None, print_func=None):
1102 """
1103 Send a command and return its exit status and output.
1104
1105 @param command: Command to send (must not contain newline characters)
1106 @param timeout: The duration (in seconds) to wait until a match is
1107 found
1108 @param internal_timeout: The timeout to pass to read_nonblocking
1109 @param print_func: A function to be used to print the data being read
1110 (should take a string parameter)
1111
1112 @return: A tuple (status, output) where status is the exit status or
1113 None if no exit status is available (e.g. timeout elapsed), and
1114 output is the output of command.
1115 """
1116 def remove_command_echo(str, cmd):
1117 if str and str.splitlines()[0] == cmd:
1118 str = "".join(str.splitlines(True)[1:])
1119 return str
1120
1121 def remove_last_nonempty_line(str):
1122 return "".join(str.rstrip().splitlines(True)[:-1])
1123
1124 # Print some debugging info
1125 logging.debug("Sending command: %s" % command)
1126
1127 # Read everything that's waiting to be read
lmr59b98db2009-10-05 19:11:21 +00001128 self.read_nonblocking(timeout=0)
lmrbbc9dd52009-07-22 20:33:47 +00001129
1130 # Send the command and get its output
1131 self.sendline(command)
1132 (match, output) = self.read_up_to_prompt(timeout, internal_timeout,
1133 print_func)
1134 # Remove the echoed command from the output
1135 output = remove_command_echo(output, command)
1136 # If the prompt was not found, return the output so far
1137 if not match:
1138 return (None, output)
1139 # Remove the final shell prompt from the output
1140 output = remove_last_nonempty_line(output)
1141
1142 # Send the 'echo ...' command to get the last exit status
1143 self.sendline(self.status_test_command)
1144 (match, status) = self.read_up_to_prompt(10.0, internal_timeout)
1145 if not match:
1146 return (None, output)
1147 status = remove_command_echo(status, self.status_test_command)
1148 status = remove_last_nonempty_line(status)
1149 # Get the first line consisting of digits only
1150 digit_lines = [l for l in status.splitlines() if l.strip().isdigit()]
1151 if not digit_lines:
1152 return (None, output)
1153 status = int(digit_lines[0].strip())
1154
1155 # Print some debugging info
1156 if status != 0:
1157 logging.debug("Command failed; status: %d, output:%s", status,
1158 kvm_utils.format_str_for_message(output.strip()))
1159
1160 return (status, output)
1161
1162
1163 def get_command_status(self, command, timeout=30.0, internal_timeout=None,
1164 print_func=None):
1165 """
1166 Send a command and return its exit status.
1167
1168 @param command: Command to send
1169 @param timeout: The duration (in seconds) to wait until a match is
1170 found
1171 @param internal_timeout: The timeout to pass to read_nonblocking
1172 @param print_func: A function to be used to print the data being read
1173 (should take a string parameter)
1174
1175 @return: Exit status or None if no exit status is available (e.g.
1176 timeout elapsed).
1177 """
1178 (status, output) = self.get_command_status_output(command, timeout,
1179 internal_timeout,
1180 print_func)
1181 return status
1182
1183
1184 def get_command_output(self, command, timeout=30.0, internal_timeout=None,
1185 print_func=None):
1186 """
1187 Send a command and return its output.
1188
1189 @param command: Command to send
1190 @param timeout: The duration (in seconds) to wait until a match is
1191 found
1192 @param internal_timeout: The timeout to pass to read_nonblocking
1193 @param print_func: A function to be used to print the data being read
1194 (should take a string parameter)
1195 """
1196 (status, output) = self.get_command_status_output(command, timeout,
1197 internal_timeout,
1198 print_func)
1199 return output