blob: dcb20cc9f3f54fda252bc2e37436ec030fa24d7c [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 """
lmr5df99f32009-08-13 04:46:16 +0000367 return _locked(self.lock_server_running_filename)
lmrbbc9dd52009-07-22 20:33:47 +0000368
369
370 def close(self, sig=signal.SIGTERM):
371 """
372 Kill the child process if it's alive and remove temporary files.
373
374 @param sig: The signal to send the process when attempting to kill it.
375 """
376 # Kill it if it's alive
377 if self.is_alive():
378 try:
379 os.kill(self.get_shell_pid(), sig)
380 except:
381 pass
382 # Wait for the server to exit
383 _wait(self.lock_server_running_filename)
384 # Call all cleanup routines
385 for hook in self.close_hooks:
386 hook()
387 # Close reader file descriptors
388 for fd in self.reader_fds.values():
389 try:
390 os.close(fd)
391 except:
392 pass
393 # Remove all used files
394 for filename in (_get_filenames("/tmp/kvm_spawn", self.id) +
395 self.reader_filenames.values()):
396 try:
397 os.unlink(filename)
398 except OSError:
399 pass
400
401
402 def set_linesep(self, linesep):
403 """
404 Sets the line separator string (usually "\\n").
405
406 @param linesep: Line separator string.
407 """
408 self.linesep = linesep
409
410
411 def send(self, str=""):
412 """
413 Send a string to the child process.
414
415 @param str: String to send to the child process.
416 """
417 try:
418 fd = os.open(self.inpipe_filename, os.O_RDWR)
419 os.write(fd, str)
420 os.close(fd)
421 except:
422 pass
423
424
425 def sendline(self, str=""):
426 """
427 Send a string followed by a line separator to the child process.
428
429 @param str: String to send to the child process.
430 """
431 self.send(str + self.linesep)
432
433
434class kvm_tail(kvm_spawn):
435 """
436 This class runs a child process in the background and sends its output in
437 real time, line-by-line, to a callback function.
438
439 See kvm_spawn's docstring.
440
441 This class uses a single pipe reader to read data in real time from the
442 child process and report it to a given callback function.
443 When the child process exits, its exit status is reported to an additional
444 callback function.
445
446 When this class is unpickled, it automatically resumes reporting output.
447 """
448
449 def __init__(self, command=None, id=None, echo=False, linesep="\n",
lmr4fe15ba2009-08-13 04:11:26 +0000450 termination_func=None, termination_params=(),
451 output_func=None, output_params=(),
452 output_prefix=""):
lmrbbc9dd52009-07-22 20:33:47 +0000453 """
454 Initialize the class and run command as a child process.
455
456 @param command: Command to run, or None if accessing an already running
457 server.
458 @param id: ID of an already running server, if accessing a running
459 server, or None if starting a new one.
460 @param echo: Boolean indicating whether echo should be initially
461 enabled for the pseudo terminal running the subprocess. This
462 parameter has an effect only when starting a new server.
463 @param linesep: Line separator to be appended to strings sent to the
464 child process by sendline().
465 @param termination_func: Function to call when the process exits. The
466 function must accept a single exit status parameter.
lmr4fe15ba2009-08-13 04:11:26 +0000467 @param termination_params: Parameters to send to termination_func
468 before the exit status.
lmrbbc9dd52009-07-22 20:33:47 +0000469 @param output_func: Function to call whenever a line of output is
470 available from the STDOUT or STDERR streams of the process.
471 The function must accept a single string parameter. The string
472 does not include the final newline.
lmr4fe15ba2009-08-13 04:11:26 +0000473 @param output_params: Parameters to send to output_func before the
474 output line.
lmrbbc9dd52009-07-22 20:33:47 +0000475 @param output_prefix: String to prepend to lines sent to output_func.
476 """
477 # Add a reader and a close hook
478 self._add_reader("tail")
479 self._add_close_hook(self._join_thread)
480
481 # Init the superclass
482 kvm_spawn.__init__(self, command, id, echo, linesep)
483
484 # Remember some attributes
485 self.termination_func = termination_func
lmr4fe15ba2009-08-13 04:11:26 +0000486 self.termination_params = termination_params
lmrbbc9dd52009-07-22 20:33:47 +0000487 self.output_func = output_func
lmr4fe15ba2009-08-13 04:11:26 +0000488 self.output_params = output_params
lmrbbc9dd52009-07-22 20:33:47 +0000489 self.output_prefix = output_prefix
490
491 # Start the thread in the background
492 self.tail_thread = threading.Thread(None, self._tail)
493 self.tail_thread.start()
494
495
496 def __getinitargs__(self):
497 return kvm_spawn.__getinitargs__(self) + (self.termination_func,
lmr4fe15ba2009-08-13 04:11:26 +0000498 self.termination_params,
lmrbbc9dd52009-07-22 20:33:47 +0000499 self.output_func,
lmr4fe15ba2009-08-13 04:11:26 +0000500 self.output_params,
lmrbbc9dd52009-07-22 20:33:47 +0000501 self.output_prefix)
502
503
504 def set_termination_func(self, termination_func):
505 """
506 Set the termination_func attribute. See __init__() for details.
507
508 @param termination_func: Function to call when the process terminates.
509 Must take a single parameter -- the exit status.
510 """
511 self.termination_func = termination_func
512
513
lmr4fe15ba2009-08-13 04:11:26 +0000514 def set_termination_params(self, termination_params):
515 """
516 Set the termination_params attribute. See __init__() for details.
517
518 @param termination_params: Parameters to send to termination_func
519 before the exit status.
520 """
521 self.termination_params = termination_params
522
523
lmrbbc9dd52009-07-22 20:33:47 +0000524 def set_output_func(self, output_func):
525 """
526 Set the output_func attribute. See __init__() for details.
527
528 @param output_func: Function to call for each line of STDOUT/STDERR
529 output from the process. Must take a single string parameter.
530 """
531 self.output_func = output_func
532
533
lmr4fe15ba2009-08-13 04:11:26 +0000534 def set_output_params(self, output_params):
535 """
536 Set the output_params attribute. See __init__() for details.
537
538 @param output_params: Parameters to send to output_func before the
539 output line.
540 """
541 self.output_params = output_params
542
543
lmrbbc9dd52009-07-22 20:33:47 +0000544 def set_output_prefix(self, output_prefix):
545 """
546 Set the output_prefix attribute. See __init__() for details.
547
548 @param output_prefix: String to pre-pend to each line sent to
549 output_func (see set_output_callback()).
550 """
551 self.output_prefix = output_prefix
552
553
554 def _tail(self):
555 def print_line(text):
556 # Pre-pend prefix and remove trailing whitespace
557 text = self.output_prefix + text.rstrip()
558 # Sanitize text
559 text = text.decode("utf-8", "replace")
560 # Pass it to output_func
561 try:
lmr4fe15ba2009-08-13 04:11:26 +0000562 params = self.output_params + (text,)
563 self.output_func(*params)
lmrbbc9dd52009-07-22 20:33:47 +0000564 except TypeError:
565 pass
566
567 fd = self._get_fd("tail")
568 buffer = ""
569 while True:
570 try:
571 # See if there's any data to read from the pipe
572 r, w, x = select.select([fd], [], [], 0.05)
573 except:
574 break
575 if fd in r:
576 # Some data is available; read it
577 new_data = os.read(fd, 1024)
578 if not new_data:
579 break
580 buffer += new_data
581 # Send the output to output_func line by line
582 # (except for the last line)
583 if self.output_func:
584 lines = buffer.split("\n")
585 for line in lines[:-1]:
586 print_line(line)
587 # Leave only the last line
588 last_newline_index = buffer.rfind("\n")
589 buffer = buffer[last_newline_index+1:]
590 else:
591 # No output is available right now; flush the buffer
592 if buffer:
593 print_line(buffer)
594 buffer = ""
595 # The process terminated; print any remaining output
596 if buffer:
597 print_line(buffer)
598 # Get the exit status, print it and send it to termination_func
599 status = self.get_status()
600 if status is None:
601 return
602 print_line("(Process terminated with status %s)" % status)
603 try:
lmr4fe15ba2009-08-13 04:11:26 +0000604 params = self.termination_params + (status,)
605 self.termination_func(*params)
lmrbbc9dd52009-07-22 20:33:47 +0000606 except TypeError:
607 pass
608
609
610 def _join_thread(self):
611 # Wait for the tail thread to exit
612 if self.tail_thread:
613 self.tail_thread.join()
614
615
616class kvm_expect(kvm_tail):
617 """
618 This class runs a child process in the background and provides expect-like
619 services.
620
621 It also provides all of kvm_tail's functionality.
622 """
623
624 def __init__(self, command=None, id=None, echo=False, linesep="\n",
lmr4fe15ba2009-08-13 04:11:26 +0000625 termination_func=None, termination_params=(),
626 output_func=None, output_params=(),
627 output_prefix=""):
lmrbbc9dd52009-07-22 20:33:47 +0000628 """
629 Initialize the class and run command as a child process.
630
631 @param command: Command to run, or None if accessing an already running
632 server.
633 @param id: ID of an already running server, if accessing a running
634 server, or None if starting a new one.
635 @param echo: Boolean indicating whether echo should be initially
636 enabled for the pseudo terminal running the subprocess. This
637 parameter has an effect only when starting a new server.
638 @param linesep: Line separator to be appended to strings sent to the
639 child process by sendline().
640 @param termination_func: Function to call when the process exits. The
641 function must accept a single exit status parameter.
lmr4fe15ba2009-08-13 04:11:26 +0000642 @param termination_params: Parameters to send to termination_func
643 before the exit status.
lmrbbc9dd52009-07-22 20:33:47 +0000644 @param output_func: Function to call whenever a line of output is
645 available from the STDOUT or STDERR streams of the process.
646 The function must accept a single string parameter. The string
647 does not include the final newline.
lmr4fe15ba2009-08-13 04:11:26 +0000648 @param output_params: Parameters to send to output_func before the
649 output line.
lmrbbc9dd52009-07-22 20:33:47 +0000650 @param output_prefix: String to prepend to lines sent to output_func.
651 """
652 # Add a reader
653 self._add_reader("expect")
654
655 # Init the superclass
656 kvm_tail.__init__(self, command, id, echo, linesep,
lmr4fe15ba2009-08-13 04:11:26 +0000657 termination_func, termination_params,
658 output_func, output_params, output_prefix)
lmrbbc9dd52009-07-22 20:33:47 +0000659
660
661 def __getinitargs__(self):
662 return kvm_tail.__getinitargs__(self)
663
664
665 def read_nonblocking(self, timeout=None):
666 """
667 Read from child until there is nothing to read for timeout seconds.
668
669 @param timeout: Time (seconds) to wait before we give up reading from
670 the child process, or None to use the default value.
671 """
672 if timeout is None:
673 timeout = 0.1
674 fd = self._get_fd("expect")
675 data = ""
676 while True:
677 try:
678 r, w, x = select.select([fd], [], [], timeout)
679 except:
680 return data
681 if fd in r:
682 new_data = os.read(fd, 1024)
683 if not new_data:
684 return data
685 data += new_data
686 else:
687 return data
688
689
690 def match_patterns(self, str, patterns):
691 """
692 Match str against a list of patterns.
693
694 Return the index of the first pattern that matches a substring of str.
695 None and empty strings in patterns are ignored.
696 If no match is found, return None.
697
698 @param patterns: List of strings (regular expression patterns).
699 """
700 for i in range(len(patterns)):
701 if not patterns[i]:
702 continue
703 if re.search(patterns[i], str):
704 return i
705
706
707 def read_until_output_matches(self, patterns, filter=lambda x: x,
708 timeout=30.0, internal_timeout=None,
709 print_func=None):
710 """
711 Read using read_nonblocking until a match is found using match_patterns,
712 or until timeout expires. Before attempting to search for a match, the
713 data is filtered using the filter function provided.
714
715 @brief: Read from child using read_nonblocking until a pattern
716 matches.
717 @param patterns: List of strings (regular expression patterns)
718 @param filter: Function to apply to the data read from the child before
719 attempting to match it against the patterns (should take and
720 return a string)
721 @param timeout: The duration (in seconds) to wait until a match is
722 found
723 @param internal_timeout: The timeout to pass to read_nonblocking
724 @param print_func: A function to be used to print the data being read
725 (should take a string parameter)
726 @return: Tuple containing the match index (or None if no match was
727 found) and the data read so far.
728 """
729 match = None
730 data = ""
731
732 end_time = time.time() + timeout
733 while time.time() < end_time:
734 # Read data from child
735 newdata = self.read_nonblocking(internal_timeout)
736 # Print it if necessary
737 if print_func and newdata:
738 str = newdata
739 if str.endswith("\n"):
740 str = str[:-1]
741 for line in str.split("\n"):
742 print_func(line.decode("utf-8", "replace"))
743 data += newdata
744
745 done = False
746 # Look for patterns
747 match = self.match_patterns(filter(data), patterns)
748 if match is not None:
749 done = True
750 # Check if child has died
751 if not self.is_alive():
752 logging.debug("Process terminated with status %s" % self.get_status())
753 done = True
754 # Are we done?
755 if done: break
756
757 # Print some debugging info
758 if match is None and (self.is_alive() or self.get_status() != 0):
759 logging.debug("Timeout elapsed or process terminated. Output:" +
760 kvm_utils.format_str_for_message(data.strip()))
761
762 return (match, data)
763
764
765 def read_until_last_word_matches(self, patterns, timeout=30.0,
766 internal_timeout=None, print_func=None):
767 """
768 Read using read_nonblocking until the last word of the output matches
769 one of the patterns (using match_patterns), or until timeout expires.
770
771 @param patterns: A list of strings (regular expression patterns)
772 @param timeout: The duration (in seconds) to wait until a match is
773 found
774 @param internal_timeout: The timeout to pass to read_nonblocking
775 @param print_func: A function to be used to print the data being read
776 (should take a string parameter)
777 @return: A tuple containing the match index (or None if no match was
778 found) and the data read so far.
779 """
780 def get_last_word(str):
781 if str:
782 return str.split()[-1]
783 else:
784 return ""
785
786 return self.read_until_output_matches(patterns, get_last_word,
787 timeout, internal_timeout,
788 print_func)
789
790
791 def read_until_last_line_matches(self, patterns, timeout=30.0,
792 internal_timeout=None, print_func=None):
793 """
794 Read using read_nonblocking until the last non-empty line of the output
795 matches one of the patterns (using match_patterns), or until timeout
796 expires. Return a tuple containing the match index (or None if no match
797 was found) and the data read so far.
798
799 @brief: Read using read_nonblocking until the last non-empty line
800 matches a pattern.
801
802 @param patterns: A list of strings (regular expression patterns)
803 @param timeout: The duration (in seconds) to wait until a match is
804 found
805 @param internal_timeout: The timeout to pass to read_nonblocking
806 @param print_func: A function to be used to print the data being read
807 (should take a string parameter)
808 """
809 def get_last_nonempty_line(str):
810 nonempty_lines = [l for l in str.splitlines() if l.strip()]
811 if nonempty_lines:
812 return nonempty_lines[-1]
813 else:
814 return ""
815
816 return self.read_until_output_matches(patterns, get_last_nonempty_line,
817 timeout, internal_timeout,
818 print_func)
819
820
821class kvm_shell_session(kvm_expect):
822 """
823 This class runs a child process in the background. It it suited for
824 processes that provide an interactive shell, such as SSH and Telnet.
825
826 It provides all services of kvm_expect and kvm_tail. In addition, it
827 provides command running services, and a utility function to test the
828 process for responsiveness.
829 """
830
831 def __init__(self, command=None, id=None, echo=False, linesep="\n",
lmr4fe15ba2009-08-13 04:11:26 +0000832 termination_func=None, termination_params=(),
833 output_func=None, output_params=(),
834 output_prefix="",
lmrbbc9dd52009-07-22 20:33:47 +0000835 prompt=r"[\#\$]\s*$", status_test_command="echo $?"):
836 """
837 Initialize the class and run command as a child process.
838
839 @param command: Command to run, or None if accessing an already running
840 server.
841 @param id: ID of an already running server, if accessing a running
842 server, or None if starting a new one.
843 @param echo: Boolean indicating whether echo should be initially
844 enabled for the pseudo terminal running the subprocess. This
845 parameter has an effect only when starting a new server.
846 @param linesep: Line separator to be appended to strings sent to the
847 child process by sendline().
848 @param termination_func: Function to call when the process exits. The
849 function must accept a single exit status parameter.
lmr4fe15ba2009-08-13 04:11:26 +0000850 @param termination_params: Parameters to send to termination_func
851 before the exit status.
lmrbbc9dd52009-07-22 20:33:47 +0000852 @param output_func: Function to call whenever a line of output is
853 available from the STDOUT or STDERR streams of the process.
854 The function must accept a single string parameter. The string
855 does not include the final newline.
lmr4fe15ba2009-08-13 04:11:26 +0000856 @param output_params: Parameters to send to output_func before the
857 output line.
lmrbbc9dd52009-07-22 20:33:47 +0000858 @param output_prefix: String to prepend to lines sent to output_func.
859 @param prompt: Regular expression describing the shell's prompt line.
860 @param status_test_command: Command to be used for getting the last
861 exit status of commands run inside the shell (used by
862 get_command_status_output() and friends).
863 """
864 # Init the superclass
865 kvm_expect.__init__(self, command, id, echo, linesep,
lmr4fe15ba2009-08-13 04:11:26 +0000866 termination_func, termination_params,
867 output_func, output_params, output_prefix)
lmrbbc9dd52009-07-22 20:33:47 +0000868
869 # Remember some attributes
870 self.prompt = prompt
871 self.status_test_command = status_test_command
872
873
874 def __getinitargs__(self):
875 return kvm_expect.__getinitargs__(self) + (self.prompt,
876 self.status_test_command)
877
878
879 def set_prompt(self, prompt):
880 """
881 Set the prompt attribute for later use by read_up_to_prompt.
882
883 @param: String that describes the prompt contents.
884 """
885 self.prompt = prompt
886
887
888 def set_status_test_command(self, status_test_command):
889 """
890 Set the command to be sent in order to get the last exit status.
891
892 @param status_test_command: Command that will be sent to get the last
893 exit status.
894 """
895 self.status_test_command = status_test_command
896
897
898 def is_responsive(self, timeout=5.0):
899 """
900 Return True if the process responds to STDIN/terminal input.
901
902 Send a newline to the child process (e.g. SSH or Telnet) and read some
903 output using read_nonblocking().
904 If all is OK, some output should be available (e.g. the shell prompt).
905 In that case return True. Otherwise return False.
906
907 @param timeout: Time duration to wait before the process is considered
908 unresponsive.
909 """
910 # Read all output that's waiting to be read, to make sure the output
911 # we read next is in response to the newline sent
912 self.read_nonblocking(timeout=0.1)
913 # Send a newline
914 self.sendline()
915 # Wait up to timeout seconds for some output from the child
916 end_time = time.time() + timeout
917 while time.time() < end_time:
918 time.sleep(0.5)
919 if self.read_nonblocking(timeout=0).strip():
920 return True
921 # No output -- report unresponsive
922 return False
923
924
925 def read_up_to_prompt(self, timeout=30.0, internal_timeout=None,
926 print_func=None):
927 """
928 Read using read_nonblocking until the last non-empty line of the output
929 matches the prompt regular expression set by set_prompt, or until
930 timeout expires.
931
932 @brief: Read using read_nonblocking until the last non-empty line
933 matches the prompt.
934
935 @param timeout: The duration (in seconds) to wait until a match is
936 found
937 @param internal_timeout: The timeout to pass to read_nonblocking
938 @param print_func: A function to be used to print the data being
939 read (should take a string parameter)
940
941 @return: A tuple containing True/False indicating whether the prompt
942 was found, and the data read so far.
943 """
944 (match, output) = self.read_until_last_line_matches([self.prompt],
945 timeout,
946 internal_timeout,
947 print_func)
948 return (match is not None, output)
949
950
951 def get_command_status_output(self, command, timeout=30.0,
952 internal_timeout=None, print_func=None):
953 """
954 Send a command and return its exit status and output.
955
956 @param command: Command to send (must not contain newline characters)
957 @param timeout: The duration (in seconds) to wait until a match is
958 found
959 @param internal_timeout: The timeout to pass to read_nonblocking
960 @param print_func: A function to be used to print the data being read
961 (should take a string parameter)
962
963 @return: A tuple (status, output) where status is the exit status or
964 None if no exit status is available (e.g. timeout elapsed), and
965 output is the output of command.
966 """
967 def remove_command_echo(str, cmd):
968 if str and str.splitlines()[0] == cmd:
969 str = "".join(str.splitlines(True)[1:])
970 return str
971
972 def remove_last_nonempty_line(str):
973 return "".join(str.rstrip().splitlines(True)[:-1])
974
975 # Print some debugging info
976 logging.debug("Sending command: %s" % command)
977
978 # Read everything that's waiting to be read
979 self.read_nonblocking(0.1)
980
981 # Send the command and get its output
982 self.sendline(command)
983 (match, output) = self.read_up_to_prompt(timeout, internal_timeout,
984 print_func)
985 # Remove the echoed command from the output
986 output = remove_command_echo(output, command)
987 # If the prompt was not found, return the output so far
988 if not match:
989 return (None, output)
990 # Remove the final shell prompt from the output
991 output = remove_last_nonempty_line(output)
992
993 # Send the 'echo ...' command to get the last exit status
994 self.sendline(self.status_test_command)
995 (match, status) = self.read_up_to_prompt(10.0, internal_timeout)
996 if not match:
997 return (None, output)
998 status = remove_command_echo(status, self.status_test_command)
999 status = remove_last_nonempty_line(status)
1000 # Get the first line consisting of digits only
1001 digit_lines = [l for l in status.splitlines() if l.strip().isdigit()]
1002 if not digit_lines:
1003 return (None, output)
1004 status = int(digit_lines[0].strip())
1005
1006 # Print some debugging info
1007 if status != 0:
1008 logging.debug("Command failed; status: %d, output:%s", status,
1009 kvm_utils.format_str_for_message(output.strip()))
1010
1011 return (status, output)
1012
1013
1014 def get_command_status(self, command, timeout=30.0, internal_timeout=None,
1015 print_func=None):
1016 """
1017 Send a command and return its exit status.
1018
1019 @param command: Command to send
1020 @param timeout: The duration (in seconds) to wait until a match is
1021 found
1022 @param internal_timeout: The timeout to pass to read_nonblocking
1023 @param print_func: A function to be used to print the data being read
1024 (should take a string parameter)
1025
1026 @return: Exit status or None if no exit status is available (e.g.
1027 timeout elapsed).
1028 """
1029 (status, output) = self.get_command_status_output(command, timeout,
1030 internal_timeout,
1031 print_func)
1032 return status
1033
1034
1035 def get_command_output(self, command, timeout=30.0, internal_timeout=None,
1036 print_func=None):
1037 """
1038 Send a command and return its output.
1039
1040 @param command: Command to send
1041 @param timeout: The duration (in seconds) to wait until a match is
1042 found
1043 @param internal_timeout: The timeout to pass to read_nonblocking
1044 @param print_func: A function to be used to print the data being read
1045 (should take a string parameter)
1046 """
1047 (status, output) = self.get_command_status_output(command, timeout,
1048 internal_timeout,
1049 print_func)
1050 return output
1051
1052
1053# The following is the server part of the module.
1054
1055def _server_main():
1056 id = sys.stdin.readline().strip()
1057 echo = sys.stdin.readline().strip() == "True"
1058 readers = sys.stdin.readline().strip().split(",")
1059 command = sys.stdin.readline().strip() + " && echo %s > /dev/null" % id
1060
1061 # Define filenames to be used for communication
1062 base_dir = "/tmp/kvm_spawn"
1063 (shell_pid_filename,
1064 status_filename,
1065 output_filename,
1066 inpipe_filename,
1067 lock_server_running_filename,
1068 lock_client_starting_filename) = _get_filenames(base_dir, id)
1069
1070 # Populate the reader filenames list
1071 reader_filenames = [_get_reader_filename(base_dir, id, reader)
1072 for reader in readers]
1073
1074 # Set $TERM = dumb
1075 os.putenv("TERM", "dumb")
1076
1077 (shell_pid, shell_fd) = pty.fork()
1078 if shell_pid == 0:
1079 # Child process: run the command in a subshell
1080 os.execv("/bin/sh", ["/bin/sh", "-c", command])
1081 else:
1082 # Parent process
1083 lock_server_running = _lock(lock_server_running_filename)
1084
1085 # Set terminal echo on/off and disable pre- and post-processing
1086 attr = termios.tcgetattr(shell_fd)
1087 attr[0] &= ~termios.INLCR
1088 attr[0] &= ~termios.ICRNL
1089 attr[0] &= ~termios.IGNCR
1090 attr[1] &= ~termios.OPOST
1091 if echo:
1092 attr[3] |= termios.ECHO
1093 else:
1094 attr[3] &= ~termios.ECHO
1095 termios.tcsetattr(shell_fd, termios.TCSANOW, attr)
1096
1097 # Open output file
1098 output_file = open(output_filename, "w")
1099 # Open input pipe
1100 os.mkfifo(inpipe_filename)
1101 inpipe_fd = os.open(inpipe_filename, os.O_RDWR)
1102 # Open output pipes (readers)
1103 reader_fds = []
1104 for filename in reader_filenames:
1105 os.mkfifo(filename)
1106 reader_fds.append(os.open(filename, os.O_RDWR))
1107
1108 # Write shell PID to file
1109 file = open(shell_pid_filename, "w")
1110 file.write(str(shell_pid))
1111 file.close()
1112
1113 # Print something to stdout so the client can start working
lmrb8f53d62009-07-27 13:29:17 +00001114 print "Server %s ready" % id
lmrbbc9dd52009-07-22 20:33:47 +00001115 sys.stdout.flush()
1116
1117 # Initialize buffers
1118 buffers = ["" for reader in readers]
1119
1120 # Read from child and write to files/pipes
1121 while True:
1122 # Make a list of reader pipes whose buffers are not empty
1123 fds = [fd for (i, fd) in enumerate(reader_fds) if buffers[i]]
1124 # Wait until there's something to do
1125 r, w, x = select.select([shell_fd, inpipe_fd], fds, [])
1126 # If a reader pipe is ready for writing --
1127 for (i, fd) in enumerate(reader_fds):
1128 if fd in w:
1129 bytes_written = os.write(fd, buffers[i])
1130 buffers[i] = buffers[i][bytes_written:]
1131 # If there's data to read from the child process --
1132 if shell_fd in r:
1133 try:
1134 data = os.read(shell_fd, 16384)
1135 except OSError:
1136 break
1137 # Remove carriage returns from the data -- they often cause
1138 # trouble and are normally not needed
1139 data = data.replace("\r", "")
1140 output_file.write(data)
1141 output_file.flush()
1142 for i in range(len(readers)):
1143 buffers[i] += data
1144 # If there's data to read from the client --
1145 if inpipe_fd in r:
1146 data = os.read(inpipe_fd, 1024)
1147 os.write(shell_fd, data)
1148
1149 # Wait for the shell process to exit and get its exit status
1150 status = os.waitpid(shell_pid, 0)[1]
1151 status = os.WEXITSTATUS(status)
1152 file = open(status_filename, "w")
1153 file.write(str(status))
1154 file.close()
1155
1156 # Wait for the client to finish initializing
1157 _wait(lock_client_starting_filename)
1158
1159 # Delete FIFOs
1160 for filename in reader_filenames + [inpipe_filename]:
1161 try:
1162 os.unlink(filename)
1163 except OSError:
1164 pass
1165
1166 # Close all files and pipes
1167 output_file.close()
1168 os.close(inpipe_fd)
1169 for fd in reader_fds:
1170 os.close(fd)
1171
1172 _unlock(lock_server_running)
1173
1174
1175if __name__ == "__main__":
1176 _server_main()