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