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