blob: 413bdaa5927011de5202e6b532f0b5c38da8a96b [file] [log] [blame]
lmrbbc9dd52009-07-22 20:33:47 +00001#!/usr/bin/python
2import sys, subprocess, pty, select, os, time, signal, re, termios, fcntl
3import threading, logging, commands
4import common, kvm_utils
5
6"""
7A class and functions used for running and controlling child processes.
8
9@copyright: 2008-2009 Red Hat Inc.
10"""
11
12
13def run_bg(command, termination_func=None, output_func=None, output_prefix="",
14 timeout=1.0):
15 """
16 Run command as a subprocess. Call output_func with each line of output
17 from the subprocess (prefixed by output_prefix). Call termination_func
18 when the subprocess terminates. Return when timeout expires or when the
19 subprocess exits -- whichever occurs first.
20
21 @brief: Run a subprocess in the background and collect its output and
22 exit status.
23
24 @param command: The shell command to execute
25 @param termination_func: A function to call when the process terminates
26 (should take an integer exit status parameter)
27 @param output_func: A function to call with each line of output from
28 the subprocess (should take a string parameter)
29 @param output_prefix: A string to pre-pend to each line of the output,
30 before passing it to stdout_func
31 @param timeout: Time duration (in seconds) to wait for the subprocess to
32 terminate before returning
33
34 @return: A kvm_tail object.
35 """
36 process = kvm_tail(command=command,
37 termination_func=termination_func,
38 output_func=output_func,
39 output_prefix=output_prefix)
40
41 end_time = time.time() + timeout
42 while time.time() < end_time and process.is_alive():
43 time.sleep(0.1)
44
45 return process
46
47
48def run_fg(command, output_func=None, output_prefix="", timeout=1.0):
49 """
50 Run command as a subprocess. Call output_func with each line of output
51 from the subprocess (prefixed by prefix). Return when timeout expires or
52 when the subprocess exits -- whichever occurs first. If timeout expires
53 and the subprocess is still running, kill it before returning.
54
55 @brief: Run a subprocess in the foreground and collect its output and
56 exit status.
57
58 @param command: The shell command to execute
59 @param output_func: A function to call with each line of output from
60 the subprocess (should take a string parameter)
61 @param output_prefix: A string to pre-pend to each line of the output,
62 before passing it to stdout_func
63 @param timeout: Time duration (in seconds) to wait for the subprocess to
64 terminate before killing it and returning
65
66 @return: A 2-tuple containing the exit status of the process and its
67 STDOUT/STDERR output. If timeout expires before the process
68 terminates, the returned status is None.
69 """
70 process = run_bg(command, None, output_func, output_prefix, timeout)
71 output = process.get_output()
72 if process.is_alive():
73 status = None
74 else:
75 status = process.get_status()
76 process.close()
77 return (status, output)
78
79
80def _lock(filename):
81 if not os.path.exists(filename):
82 open(filename, "w").close()
83 fd = os.open(filename, os.O_RDWR)
84 fcntl.lockf(fd, fcntl.LOCK_EX)
85 return fd
86
87
88def _unlock(fd):
89 fcntl.lockf(fd, fcntl.LOCK_UN)
90 os.close(fd)
91
92
93def _locked(filename):
94 try:
95 fd = os.open(filename, os.O_RDWR)
96 except:
97 return False
98 try:
99 fcntl.lockf(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
100 except:
101 os.close(fd)
102 return True
103 fcntl.lockf(fd, fcntl.LOCK_UN)
104 os.close(fd)
105 return False
106
107
108def _wait(filename):
109 fd = _lock(filename)
110 _unlock(fd)
111
112
113def _get_filenames(base_dir, id):
114 return [os.path.join(base_dir, s + id) for s in
115 "shell-pid-", "status-", "output-", "inpipe-",
116 "lock-server-running-", "lock-client-starting-"]
117
118
119def _get_reader_filename(base_dir, id, reader):
120 return os.path.join(base_dir, "outpipe-%s-%s" % (reader, id))
121
122
123class kvm_spawn:
124 """
125 This class is used for spawning and controlling a child process.
126
127 A new instance of this class can either run a new server (a small Python
128 program that reads output from the child process and reports it to the
129 client and to a text file) or attach to an already running server.
130 When a server is started it runs the child process.
131 The server writes output from the child's STDOUT and STDERR to a text file.
132 The text file can be accessed at any time using get_output().
133 In addition, the server opens as many pipes as requested by the client and
134 writes the output to them.
135 The pipes are requested and accessed by classes derived from kvm_spawn.
136 These pipes are referred to as "readers".
137 The server also receives input from the client and sends it to the child
138 process.
139 An instance of this class can be pickled. Every derived class is
140 responsible for restoring its own state by properly defining
141 __getinitargs__().
142
143 The first named pipe is used by _tail(), a function that runs in the
144 background and reports new output from the child as it is produced.
145 The second named pipe is used by a set of functions that read and parse
146 output as requested by the user in an interactive manner, similar to
147 pexpect.
148 When unpickled it automatically
149 resumes _tail() if needed.
150 """
151
152 def __init__(self, command=None, id=None, echo=False, linesep="\n"):
153 """
154 Initialize the class and run command as a child process.
155
156 @param command: Command to run, or None if accessing an already running
157 server.
158 @param id: ID of an already running server, if accessing a running
159 server, or None if starting a new one.
160 @param echo: Boolean indicating whether echo should be initially
161 enabled for the pseudo terminal running the subprocess. This
162 parameter has an effect only when starting a new server.
163 @param linesep: Line separator to be appended to strings sent to the
164 child process by sendline().
165 """
166 self.id = id or kvm_utils.generate_random_string(8)
167
168 # Define filenames for communication with server
169 base_dir = "/tmp/kvm_spawn"
170 try:
171 os.makedirs(base_dir)
172 except:
173 pass
174 (self.shell_pid_filename,
175 self.status_filename,
176 self.output_filename,
177 self.inpipe_filename,
178 self.lock_server_running_filename,
179 self.lock_client_starting_filename) = _get_filenames(base_dir,
180 self.id)
181
182 # Remember some attributes
183 self.echo = echo
184 self.linesep = linesep
185
186 # Make sure the 'readers' and 'close_hooks' attributes exist
187 if not hasattr(self, "readers"):
188 self.readers = []
189 if not hasattr(self, "close_hooks"):
190 self.close_hooks = []
191
192 # Define the reader filenames
193 self.reader_filenames = dict(
194 (reader, _get_reader_filename(base_dir, self.id, reader))
195 for reader in self.readers)
196
197 # Let the server know a client intends to open some pipes;
198 # if the executed command terminates quickly, the server will wait for
199 # the client to release the lock before exiting
200 lock_client_starting = _lock(self.lock_client_starting_filename)
201
202 # Start the server (which runs the command)
203 if command:
204 sub = subprocess.Popen("python %s" % __file__,
205 shell=True,
206 stdin=subprocess.PIPE,
207 stdout=subprocess.PIPE,
208 stderr=subprocess.STDOUT)
209 # Send parameters to the server
210 sub.stdin.write("%s\n" % self.id)
211 sub.stdin.write("%s\n" % echo)
212 sub.stdin.write("%s\n" % ",".join(self.readers))
213 sub.stdin.write("%s\n" % command)
214 # Wait for the server to complete its initialization
215 sub.stdout.readline()
216
217 # Open the reading pipes
218 self.reader_fds = {}
219 try:
220 assert(_locked(self.lock_server_running_filename))
221 for reader, filename in self.reader_filenames.items():
222 self.reader_fds[reader] = os.open(filename, os.O_RDONLY)
223 except:
224 pass
225
226 # Allow the server to continue
227 _unlock(lock_client_starting)
228
229
230 # The following two functions are defined to make sure the state is set
231 # exclusively by the constructor call as specified in __getinitargs__().
232
233 def __getstate__(self):
234 pass
235
236
237 def __setstate__(self, state):
238 pass
239
240
241 def __getinitargs__(self):
242 # Save some information when pickling -- will be passed to the
243 # constructor upon unpickling
244 return (None, self.id, self.echo, self.linesep)
245
246
247 def _add_reader(self, reader):
248 """
249 Add a reader whose file descriptor can be obtained with _get_fd().
250 Should be called before __init__(). Intended for use by derived
251 classes.
252
253 @param reader: The name of the reader.
254 """
255 if not hasattr(self, "readers"):
256 self.readers = []
257 self.readers.append(reader)
258
259
260 def _add_close_hook(self, hook):
261 """
262 Add a close hook function to be called when close() is called.
263 The function will be called after the process terminates but before
264 final cleanup. Intended for use by derived classes.
265
266 @param hook: The hook function.
267 """
268 if not hasattr(self, "close_hooks"):
269 self.close_hooks = []
270 self.close_hooks.append(hook)
271
272
273 def _get_fd(self, reader):
274 """
275 Return an open file descriptor corresponding to the specified reader
276 pipe. If no such reader exists, or the pipe could not be opened,
277 return None. Intended for use by derived classes.
278
279 @param reader: The name of the reader.
280 """
281 return self.reader_fds.get(reader)
282
283
284 def get_id(self):
285 """
286 Return the instance's id attribute, which may be used to access the
287 process in the future.
288 """
289 return self.id
290
291
292 def get_shell_pid(self):
293 """
294 Return the PID of the subshell process, or None if not available.
295 The subshell is the shell that runs the command.
296 """
297 try:
298 file = open(self.shell_pid_filename, "r")
299 pid = int(file.read())
300 file.close()
301 return pid
302 except:
303 return None
304
305
306 def get_pid(self, index=0):
307 """
308 Try to get and return the PID of a child process of the subshell.
309 This is usually the PID of the process executed in the subshell.
310 There are 3 exceptions:
311 - If the subshell couldn't start the process for some reason, no
312 PID can be returned.
313 - If the subshell is running several processes in parallel,
314 multiple PIDs can be returned. Use the index parameter in this
315 case.
316 - Before starting the process, after the process has terminated,
317 or while running shell code that doesn't start any processes --
318 no PID can be returned.
319
320 @param index: The index of the child process whose PID is requested.
321 Normally this should remain 0.
322 @return: The PID of the child process, or None if none could be found.
323 """
324 parent_pid = self.get_shell_pid()
325 if not parent_pid:
326 return None
327 pids = commands.getoutput("ps --ppid %d -o pid=" % parent_pid).split()
328 try:
329 return int(pids[index])
330 except:
331 return None
332
333
334 def get_status(self):
335 """
336 Wait for the process to exit and return its exit status, or None
337 if the exit status is not available.
338 """
339 _wait(self.lock_server_running_filename)
340 try:
341 file = open(self.status_filename, "r")
342 status = int(file.read())
343 file.close()
344 return status
345 except:
346 return None
347
348
349 def get_output(self):
350 """
351 Return the STDOUT and STDERR output of the process so far.
352 """
353 try:
354 file = open(self.output_filename, "r")
355 output = file.read()
356 file.close()
357 return output
358 except:
359 return ""
360
361
362 def is_alive(self):
363 """
364 Return True if the process is running.
365 """
366 pid = self.get_shell_pid()
367 # See if the PID exists
368 try:
369 os.kill(pid, 0)
370 except:
371 return False
372 # Make sure the PID belongs to the original process
373 filename = "/proc/%d/cmdline" % pid
374 try:
375 file = open(filename, "r")
376 cmdline = file.read()
377 file.close()
378 except:
379 # If we couldn't find the file for some reason, skip the check
380 return True
381 if self.id in cmdline:
382 return True
383 return False
384
385
386 def close(self, sig=signal.SIGTERM):
387 """
388 Kill the child process if it's alive and remove temporary files.
389
390 @param sig: The signal to send the process when attempting to kill it.
391 """
392 # Kill it if it's alive
393 if self.is_alive():
394 try:
395 os.kill(self.get_shell_pid(), sig)
396 except:
397 pass
398 # Wait for the server to exit
399 _wait(self.lock_server_running_filename)
400 # Call all cleanup routines
401 for hook in self.close_hooks:
402 hook()
403 # Close reader file descriptors
404 for fd in self.reader_fds.values():
405 try:
406 os.close(fd)
407 except:
408 pass
409 # Remove all used files
410 for filename in (_get_filenames("/tmp/kvm_spawn", self.id) +
411 self.reader_filenames.values()):
412 try:
413 os.unlink(filename)
414 except OSError:
415 pass
416
417
418 def set_linesep(self, linesep):
419 """
420 Sets the line separator string (usually "\\n").
421
422 @param linesep: Line separator string.
423 """
424 self.linesep = linesep
425
426
427 def send(self, str=""):
428 """
429 Send a string to the child process.
430
431 @param str: String to send to the child process.
432 """
433 try:
434 fd = os.open(self.inpipe_filename, os.O_RDWR)
435 os.write(fd, str)
436 os.close(fd)
437 except:
438 pass
439
440
441 def sendline(self, str=""):
442 """
443 Send a string followed by a line separator to the child process.
444
445 @param str: String to send to the child process.
446 """
447 self.send(str + self.linesep)
448
449
450class kvm_tail(kvm_spawn):
451 """
452 This class runs a child process in the background and sends its output in
453 real time, line-by-line, to a callback function.
454
455 See kvm_spawn's docstring.
456
457 This class uses a single pipe reader to read data in real time from the
458 child process and report it to a given callback function.
459 When the child process exits, its exit status is reported to an additional
460 callback function.
461
462 When this class is unpickled, it automatically resumes reporting output.
463 """
464
465 def __init__(self, command=None, id=None, echo=False, linesep="\n",
466 termination_func=None, output_func=None, output_prefix=""):
467 """
468 Initialize the class and run command as a child process.
469
470 @param command: Command to run, or None if accessing an already running
471 server.
472 @param id: ID of an already running server, if accessing a running
473 server, or None if starting a new one.
474 @param echo: Boolean indicating whether echo should be initially
475 enabled for the pseudo terminal running the subprocess. This
476 parameter has an effect only when starting a new server.
477 @param linesep: Line separator to be appended to strings sent to the
478 child process by sendline().
479 @param termination_func: Function to call when the process exits. The
480 function must accept a single exit status parameter.
481 @param output_func: Function to call whenever a line of output is
482 available from the STDOUT or STDERR streams of the process.
483 The function must accept a single string parameter. The string
484 does not include the final newline.
485 @param output_prefix: String to prepend to lines sent to output_func.
486 """
487 # Add a reader and a close hook
488 self._add_reader("tail")
489 self._add_close_hook(self._join_thread)
490
491 # Init the superclass
492 kvm_spawn.__init__(self, command, id, echo, linesep)
493
494 # Remember some attributes
495 self.termination_func = termination_func
496 self.output_func = output_func
497 self.output_prefix = output_prefix
498
499 # Start the thread in the background
500 self.tail_thread = threading.Thread(None, self._tail)
501 self.tail_thread.start()
502
503
504 def __getinitargs__(self):
505 return kvm_spawn.__getinitargs__(self) + (self.termination_func,
506 self.output_func,
507 self.output_prefix)
508
509
510 def set_termination_func(self, termination_func):
511 """
512 Set the termination_func attribute. See __init__() for details.
513
514 @param termination_func: Function to call when the process terminates.
515 Must take a single parameter -- the exit status.
516 """
517 self.termination_func = termination_func
518
519
520 def set_output_func(self, output_func):
521 """
522 Set the output_func attribute. See __init__() for details.
523
524 @param output_func: Function to call for each line of STDOUT/STDERR
525 output from the process. Must take a single string parameter.
526 """
527 self.output_func = output_func
528
529
530 def set_output_prefix(self, output_prefix):
531 """
532 Set the output_prefix attribute. See __init__() for details.
533
534 @param output_prefix: String to pre-pend to each line sent to
535 output_func (see set_output_callback()).
536 """
537 self.output_prefix = output_prefix
538
539
540 def _tail(self):
541 def print_line(text):
542 # Pre-pend prefix and remove trailing whitespace
543 text = self.output_prefix + text.rstrip()
544 # Sanitize text
545 text = text.decode("utf-8", "replace")
546 # Pass it to output_func
547 try:
548 self.output_func(text)
549 except TypeError:
550 pass
551
552 fd = self._get_fd("tail")
553 buffer = ""
554 while True:
555 try:
556 # See if there's any data to read from the pipe
557 r, w, x = select.select([fd], [], [], 0.05)
558 except:
559 break
560 if fd in r:
561 # Some data is available; read it
562 new_data = os.read(fd, 1024)
563 if not new_data:
564 break
565 buffer += new_data
566 # Send the output to output_func line by line
567 # (except for the last line)
568 if self.output_func:
569 lines = buffer.split("\n")
570 for line in lines[:-1]:
571 print_line(line)
572 # Leave only the last line
573 last_newline_index = buffer.rfind("\n")
574 buffer = buffer[last_newline_index+1:]
575 else:
576 # No output is available right now; flush the buffer
577 if buffer:
578 print_line(buffer)
579 buffer = ""
580 # The process terminated; print any remaining output
581 if buffer:
582 print_line(buffer)
583 # Get the exit status, print it and send it to termination_func
584 status = self.get_status()
585 if status is None:
586 return
587 print_line("(Process terminated with status %s)" % status)
588 try:
589 self.termination_func(status)
590 except TypeError:
591 pass
592
593
594 def _join_thread(self):
595 # Wait for the tail thread to exit
596 if self.tail_thread:
597 self.tail_thread.join()
598
599
600class kvm_expect(kvm_tail):
601 """
602 This class runs a child process in the background and provides expect-like
603 services.
604
605 It also provides all of kvm_tail's functionality.
606 """
607
608 def __init__(self, command=None, id=None, echo=False, linesep="\n",
609 termination_func=None, output_func=None, output_prefix=""):
610 """
611 Initialize the class and run command as a child process.
612
613 @param command: Command to run, or None if accessing an already running
614 server.
615 @param id: ID of an already running server, if accessing a running
616 server, or None if starting a new one.
617 @param echo: Boolean indicating whether echo should be initially
618 enabled for the pseudo terminal running the subprocess. This
619 parameter has an effect only when starting a new server.
620 @param linesep: Line separator to be appended to strings sent to the
621 child process by sendline().
622 @param termination_func: Function to call when the process exits. The
623 function must accept a single exit status parameter.
624 @param output_func: Function to call whenever a line of output is
625 available from the STDOUT or STDERR streams of the process.
626 The function must accept a single string parameter. The string
627 does not include the final newline.
628 @param output_prefix: String to prepend to lines sent to output_func.
629 """
630 # Add a reader
631 self._add_reader("expect")
632
633 # Init the superclass
634 kvm_tail.__init__(self, command, id, echo, linesep,
635 termination_func, output_func, output_prefix)
636
637
638 def __getinitargs__(self):
639 return kvm_tail.__getinitargs__(self)
640
641
642 def read_nonblocking(self, timeout=None):
643 """
644 Read from child until there is nothing to read for timeout seconds.
645
646 @param timeout: Time (seconds) to wait before we give up reading from
647 the child process, or None to use the default value.
648 """
649 if timeout is None:
650 timeout = 0.1
651 fd = self._get_fd("expect")
652 data = ""
653 while True:
654 try:
655 r, w, x = select.select([fd], [], [], timeout)
656 except:
657 return data
658 if fd in r:
659 new_data = os.read(fd, 1024)
660 if not new_data:
661 return data
662 data += new_data
663 else:
664 return data
665
666
667 def match_patterns(self, str, patterns):
668 """
669 Match str against a list of patterns.
670
671 Return the index of the first pattern that matches a substring of str.
672 None and empty strings in patterns are ignored.
673 If no match is found, return None.
674
675 @param patterns: List of strings (regular expression patterns).
676 """
677 for i in range(len(patterns)):
678 if not patterns[i]:
679 continue
680 if re.search(patterns[i], str):
681 return i
682
683
684 def read_until_output_matches(self, patterns, filter=lambda x: x,
685 timeout=30.0, internal_timeout=None,
686 print_func=None):
687 """
688 Read using read_nonblocking until a match is found using match_patterns,
689 or until timeout expires. Before attempting to search for a match, the
690 data is filtered using the filter function provided.
691
692 @brief: Read from child using read_nonblocking until a pattern
693 matches.
694 @param patterns: List of strings (regular expression patterns)
695 @param filter: Function to apply to the data read from the child before
696 attempting to match it against the patterns (should take and
697 return a string)
698 @param timeout: The duration (in seconds) to wait until a match is
699 found
700 @param internal_timeout: The timeout to pass to read_nonblocking
701 @param print_func: A function to be used to print the data being read
702 (should take a string parameter)
703 @return: Tuple containing the match index (or None if no match was
704 found) and the data read so far.
705 """
706 match = None
707 data = ""
708
709 end_time = time.time() + timeout
710 while time.time() < end_time:
711 # Read data from child
712 newdata = self.read_nonblocking(internal_timeout)
713 # Print it if necessary
714 if print_func and newdata:
715 str = newdata
716 if str.endswith("\n"):
717 str = str[:-1]
718 for line in str.split("\n"):
719 print_func(line.decode("utf-8", "replace"))
720 data += newdata
721
722 done = False
723 # Look for patterns
724 match = self.match_patterns(filter(data), patterns)
725 if match is not None:
726 done = True
727 # Check if child has died
728 if not self.is_alive():
729 logging.debug("Process terminated with status %s" % self.get_status())
730 done = True
731 # Are we done?
732 if done: break
733
734 # Print some debugging info
735 if match is None and (self.is_alive() or self.get_status() != 0):
736 logging.debug("Timeout elapsed or process terminated. Output:" +
737 kvm_utils.format_str_for_message(data.strip()))
738
739 return (match, data)
740
741
742 def read_until_last_word_matches(self, patterns, timeout=30.0,
743 internal_timeout=None, print_func=None):
744 """
745 Read using read_nonblocking until the last word of the output matches
746 one of the patterns (using match_patterns), or until timeout expires.
747
748 @param patterns: A list of strings (regular expression patterns)
749 @param timeout: The duration (in seconds) to wait until a match is
750 found
751 @param internal_timeout: The timeout to pass to read_nonblocking
752 @param print_func: A function to be used to print the data being read
753 (should take a string parameter)
754 @return: A tuple containing the match index (or None if no match was
755 found) and the data read so far.
756 """
757 def get_last_word(str):
758 if str:
759 return str.split()[-1]
760 else:
761 return ""
762
763 return self.read_until_output_matches(patterns, get_last_word,
764 timeout, internal_timeout,
765 print_func)
766
767
768 def read_until_last_line_matches(self, patterns, timeout=30.0,
769 internal_timeout=None, print_func=None):
770 """
771 Read using read_nonblocking until the last non-empty line of the output
772 matches one of the patterns (using match_patterns), or until timeout
773 expires. Return a tuple containing the match index (or None if no match
774 was found) and the data read so far.
775
776 @brief: Read using read_nonblocking until the last non-empty line
777 matches a pattern.
778
779 @param patterns: A list of strings (regular expression patterns)
780 @param timeout: The duration (in seconds) to wait until a match is
781 found
782 @param internal_timeout: The timeout to pass to read_nonblocking
783 @param print_func: A function to be used to print the data being read
784 (should take a string parameter)
785 """
786 def get_last_nonempty_line(str):
787 nonempty_lines = [l for l in str.splitlines() if l.strip()]
788 if nonempty_lines:
789 return nonempty_lines[-1]
790 else:
791 return ""
792
793 return self.read_until_output_matches(patterns, get_last_nonempty_line,
794 timeout, internal_timeout,
795 print_func)
796
797
798class kvm_shell_session(kvm_expect):
799 """
800 This class runs a child process in the background. It it suited for
801 processes that provide an interactive shell, such as SSH and Telnet.
802
803 It provides all services of kvm_expect and kvm_tail. In addition, it
804 provides command running services, and a utility function to test the
805 process for responsiveness.
806 """
807
808 def __init__(self, command=None, id=None, echo=False, linesep="\n",
809 termination_func=None, output_func=None, output_prefix="",
810 prompt=r"[\#\$]\s*$", status_test_command="echo $?"):
811 """
812 Initialize the class and run command as a child process.
813
814 @param command: Command to run, or None if accessing an already running
815 server.
816 @param id: ID of an already running server, if accessing a running
817 server, or None if starting a new one.
818 @param echo: Boolean indicating whether echo should be initially
819 enabled for the pseudo terminal running the subprocess. This
820 parameter has an effect only when starting a new server.
821 @param linesep: Line separator to be appended to strings sent to the
822 child process by sendline().
823 @param termination_func: Function to call when the process exits. The
824 function must accept a single exit status parameter.
825 @param output_func: Function to call whenever a line of output is
826 available from the STDOUT or STDERR streams of the process.
827 The function must accept a single string parameter. The string
828 does not include the final newline.
829 @param output_prefix: String to prepend to lines sent to output_func.
830 @param prompt: Regular expression describing the shell's prompt line.
831 @param status_test_command: Command to be used for getting the last
832 exit status of commands run inside the shell (used by
833 get_command_status_output() and friends).
834 """
835 # Init the superclass
836 kvm_expect.__init__(self, command, id, echo, linesep,
837 termination_func, output_func, output_prefix)
838
839 # Remember some attributes
840 self.prompt = prompt
841 self.status_test_command = status_test_command
842
843
844 def __getinitargs__(self):
845 return kvm_expect.__getinitargs__(self) + (self.prompt,
846 self.status_test_command)
847
848
849 def set_prompt(self, prompt):
850 """
851 Set the prompt attribute for later use by read_up_to_prompt.
852
853 @param: String that describes the prompt contents.
854 """
855 self.prompt = prompt
856
857
858 def set_status_test_command(self, status_test_command):
859 """
860 Set the command to be sent in order to get the last exit status.
861
862 @param status_test_command: Command that will be sent to get the last
863 exit status.
864 """
865 self.status_test_command = status_test_command
866
867
868 def is_responsive(self, timeout=5.0):
869 """
870 Return True if the process responds to STDIN/terminal input.
871
872 Send a newline to the child process (e.g. SSH or Telnet) and read some
873 output using read_nonblocking().
874 If all is OK, some output should be available (e.g. the shell prompt).
875 In that case return True. Otherwise return False.
876
877 @param timeout: Time duration to wait before the process is considered
878 unresponsive.
879 """
880 # Read all output that's waiting to be read, to make sure the output
881 # we read next is in response to the newline sent
882 self.read_nonblocking(timeout=0.1)
883 # Send a newline
884 self.sendline()
885 # Wait up to timeout seconds for some output from the child
886 end_time = time.time() + timeout
887 while time.time() < end_time:
888 time.sleep(0.5)
889 if self.read_nonblocking(timeout=0).strip():
890 return True
891 # No output -- report unresponsive
892 return False
893
894
895 def read_up_to_prompt(self, timeout=30.0, internal_timeout=None,
896 print_func=None):
897 """
898 Read using read_nonblocking until the last non-empty line of the output
899 matches the prompt regular expression set by set_prompt, or until
900 timeout expires.
901
902 @brief: Read using read_nonblocking until the last non-empty line
903 matches the prompt.
904
905 @param timeout: The duration (in seconds) to wait until a match is
906 found
907 @param internal_timeout: The timeout to pass to read_nonblocking
908 @param print_func: A function to be used to print the data being
909 read (should take a string parameter)
910
911 @return: A tuple containing True/False indicating whether the prompt
912 was found, and the data read so far.
913 """
914 (match, output) = self.read_until_last_line_matches([self.prompt],
915 timeout,
916 internal_timeout,
917 print_func)
918 return (match is not None, output)
919
920
921 def get_command_status_output(self, command, timeout=30.0,
922 internal_timeout=None, print_func=None):
923 """
924 Send a command and return its exit status and output.
925
926 @param command: Command to send (must not contain newline characters)
927 @param timeout: The duration (in seconds) to wait until a match is
928 found
929 @param internal_timeout: The timeout to pass to read_nonblocking
930 @param print_func: A function to be used to print the data being read
931 (should take a string parameter)
932
933 @return: A tuple (status, output) where status is the exit status or
934 None if no exit status is available (e.g. timeout elapsed), and
935 output is the output of command.
936 """
937 def remove_command_echo(str, cmd):
938 if str and str.splitlines()[0] == cmd:
939 str = "".join(str.splitlines(True)[1:])
940 return str
941
942 def remove_last_nonempty_line(str):
943 return "".join(str.rstrip().splitlines(True)[:-1])
944
945 # Print some debugging info
946 logging.debug("Sending command: %s" % command)
947
948 # Read everything that's waiting to be read
949 self.read_nonblocking(0.1)
950
951 # Send the command and get its output
952 self.sendline(command)
953 (match, output) = self.read_up_to_prompt(timeout, internal_timeout,
954 print_func)
955 # Remove the echoed command from the output
956 output = remove_command_echo(output, command)
957 # If the prompt was not found, return the output so far
958 if not match:
959 return (None, output)
960 # Remove the final shell prompt from the output
961 output = remove_last_nonempty_line(output)
962
963 # Send the 'echo ...' command to get the last exit status
964 self.sendline(self.status_test_command)
965 (match, status) = self.read_up_to_prompt(10.0, internal_timeout)
966 if not match:
967 return (None, output)
968 status = remove_command_echo(status, self.status_test_command)
969 status = remove_last_nonempty_line(status)
970 # Get the first line consisting of digits only
971 digit_lines = [l for l in status.splitlines() if l.strip().isdigit()]
972 if not digit_lines:
973 return (None, output)
974 status = int(digit_lines[0].strip())
975
976 # Print some debugging info
977 if status != 0:
978 logging.debug("Command failed; status: %d, output:%s", status,
979 kvm_utils.format_str_for_message(output.strip()))
980
981 return (status, output)
982
983
984 def get_command_status(self, command, timeout=30.0, internal_timeout=None,
985 print_func=None):
986 """
987 Send a command and return its exit status.
988
989 @param command: Command to send
990 @param timeout: The duration (in seconds) to wait until a match is
991 found
992 @param internal_timeout: The timeout to pass to read_nonblocking
993 @param print_func: A function to be used to print the data being read
994 (should take a string parameter)
995
996 @return: Exit status or None if no exit status is available (e.g.
997 timeout elapsed).
998 """
999 (status, output) = self.get_command_status_output(command, timeout,
1000 internal_timeout,
1001 print_func)
1002 return status
1003
1004
1005 def get_command_output(self, command, timeout=30.0, internal_timeout=None,
1006 print_func=None):
1007 """
1008 Send a command and return its output.
1009
1010 @param command: Command to send
1011 @param timeout: The duration (in seconds) to wait until a match is
1012 found
1013 @param internal_timeout: The timeout to pass to read_nonblocking
1014 @param print_func: A function to be used to print the data being read
1015 (should take a string parameter)
1016 """
1017 (status, output) = self.get_command_status_output(command, timeout,
1018 internal_timeout,
1019 print_func)
1020 return output
1021
1022
1023# The following is the server part of the module.
1024
1025def _server_main():
1026 id = sys.stdin.readline().strip()
1027 echo = sys.stdin.readline().strip() == "True"
1028 readers = sys.stdin.readline().strip().split(",")
1029 command = sys.stdin.readline().strip() + " && echo %s > /dev/null" % id
1030
1031 # Define filenames to be used for communication
1032 base_dir = "/tmp/kvm_spawn"
1033 (shell_pid_filename,
1034 status_filename,
1035 output_filename,
1036 inpipe_filename,
1037 lock_server_running_filename,
1038 lock_client_starting_filename) = _get_filenames(base_dir, id)
1039
1040 # Populate the reader filenames list
1041 reader_filenames = [_get_reader_filename(base_dir, id, reader)
1042 for reader in readers]
1043
1044 # Set $TERM = dumb
1045 os.putenv("TERM", "dumb")
1046
1047 (shell_pid, shell_fd) = pty.fork()
1048 if shell_pid == 0:
1049 # Child process: run the command in a subshell
1050 os.execv("/bin/sh", ["/bin/sh", "-c", command])
1051 else:
1052 # Parent process
1053 lock_server_running = _lock(lock_server_running_filename)
1054
1055 # Set terminal echo on/off and disable pre- and post-processing
1056 attr = termios.tcgetattr(shell_fd)
1057 attr[0] &= ~termios.INLCR
1058 attr[0] &= ~termios.ICRNL
1059 attr[0] &= ~termios.IGNCR
1060 attr[1] &= ~termios.OPOST
1061 if echo:
1062 attr[3] |= termios.ECHO
1063 else:
1064 attr[3] &= ~termios.ECHO
1065 termios.tcsetattr(shell_fd, termios.TCSANOW, attr)
1066
1067 # Open output file
1068 output_file = open(output_filename, "w")
1069 # Open input pipe
1070 os.mkfifo(inpipe_filename)
1071 inpipe_fd = os.open(inpipe_filename, os.O_RDWR)
1072 # Open output pipes (readers)
1073 reader_fds = []
1074 for filename in reader_filenames:
1075 os.mkfifo(filename)
1076 reader_fds.append(os.open(filename, os.O_RDWR))
1077
1078 # Write shell PID to file
1079 file = open(shell_pid_filename, "w")
1080 file.write(str(shell_pid))
1081 file.close()
1082
1083 # Print something to stdout so the client can start working
1084 print "hello"
1085 sys.stdout.flush()
1086
1087 # Initialize buffers
1088 buffers = ["" for reader in readers]
1089
1090 # Read from child and write to files/pipes
1091 while True:
1092 # Make a list of reader pipes whose buffers are not empty
1093 fds = [fd for (i, fd) in enumerate(reader_fds) if buffers[i]]
1094 # Wait until there's something to do
1095 r, w, x = select.select([shell_fd, inpipe_fd], fds, [])
1096 # If a reader pipe is ready for writing --
1097 for (i, fd) in enumerate(reader_fds):
1098 if fd in w:
1099 bytes_written = os.write(fd, buffers[i])
1100 buffers[i] = buffers[i][bytes_written:]
1101 # If there's data to read from the child process --
1102 if shell_fd in r:
1103 try:
1104 data = os.read(shell_fd, 16384)
1105 except OSError:
1106 break
1107 # Remove carriage returns from the data -- they often cause
1108 # trouble and are normally not needed
1109 data = data.replace("\r", "")
1110 output_file.write(data)
1111 output_file.flush()
1112 for i in range(len(readers)):
1113 buffers[i] += data
1114 # If there's data to read from the client --
1115 if inpipe_fd in r:
1116 data = os.read(inpipe_fd, 1024)
1117 os.write(shell_fd, data)
1118
1119 # Wait for the shell process to exit and get its exit status
1120 status = os.waitpid(shell_pid, 0)[1]
1121 status = os.WEXITSTATUS(status)
1122 file = open(status_filename, "w")
1123 file.write(str(status))
1124 file.close()
1125
1126 # Wait for the client to finish initializing
1127 _wait(lock_client_starting_filename)
1128
1129 # Delete FIFOs
1130 for filename in reader_filenames + [inpipe_filename]:
1131 try:
1132 os.unlink(filename)
1133 except OSError:
1134 pass
1135
1136 # Close all files and pipes
1137 output_file.close()
1138 os.close(inpipe_fd)
1139 for fd in reader_fds:
1140 os.close(fd)
1141
1142 _unlock(lock_server_running)
1143
1144
1145if __name__ == "__main__":
1146 _server_main()