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