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