Skip to contentSkip to conversation

KVM test: kvm_preprocessing.py: allow modifying VM params without restarting

PATCH New Michael Goldish 1 participant 18 messages Jun 18, 2010 KVM

lore
Share & tools
lore
#0 lore raw

PATCH 1/18 KVM test: kvm_preprocessing.py: allow modifying VM params without restarting

Currently a VM's params are changed before the test only if it's restarted. This patch allows VM params to be changed when it isn't restarted. This is useful for params that can have an effect without a restart, such as
main_monitor: monitors can be switched between tests without restarting, so that one test talks to the human monitor and the next test talks to the QMP monitor of the same VM.

---
 client/tests/kvm/kvm_preprocessing.py |    9 +++++++--
 1 files changed, 7 insertions(+), 2 deletions(-)
client/tests/kvm/kvm_preprocessing.py +7 -2
index ee3e9b2..17f3a29 100644
@@ -79,8 +79,13 @@ def preprocess_vm(test, params, env, name):
                           "restarting it...")
             start_vm = True
 
-    if start_vm and not vm.create(name, params, test.bindir, for_migration):
-        raise error.TestError("Could not start VM")
+    if start_vm:
+        # Start the VM (or restart it if it's already up)
+        if not vm.create(name, params, test.bindir, for_migration):
+            raise error.TestError("Could not start VM")
+    else:
+        # Don't start the VM, just update its params
+        vm.params = params
 
     scrdump_filename = os.path.join(test.debugdir, "pre_%s.ppm" % name)
     try:
Signature · 1 line
1.5.4.1
#1 lore raw

PATCH 2/18 KVM test: kvm.py: suppress exceptions during postprocessing if the test fails

We don't want an exception during postprocessing to mask the exception that caused the failure.

Also, move abort-on-error handling from kvm_preprocessing.py to kvm.py, and modify some debug messages.

---
 client/tests/kvm/kvm.py               |  100 +++++++++++++++++++++-----------
 client/tests/kvm/kvm_preprocessing.py |   14 -----
 2 files changed, 65 insertions(+), 49 deletions(-)
client/tests/kvm/kvm.py +65 -35
index c6e146d..bab1e6f 100644
@@ -32,49 +32,79 @@ class kvm(test.test):
             self.write_test_keyval({key: params[key]})
 
         # Open the environment file
+        logging.info("Unpickling env. You may see some harmless error "
+                     "messages.")
         env_filename = os.path.join(self.bindir, params.get("env", "env"))
         env = kvm_utils.load_env(env_filename, {})
-        logging.debug("Contents of environment: %s", str(env))
+        logging.debug("Contents of environment: %s", env)
+
+        test_passed = False
 
         try:
             try:
-                # Get the test routine corresponding to the specified test type
-                t_type = params.get("type")
-                # Verify if we have the correspondent source file for it
-                subtest_dir = os.path.join(self.bindir, "tests")
-                module_path = os.path.join(subtest_dir, "%s.py" % t_type)
-                if not os.path.isfile(module_path):
-                    raise error.TestError("No %s.py test file found" % t_type)
-                # Load the test module
-                f, p, d = imp.find_module(t_type, [subtest_dir])
-                test_module = imp.load_module(t_type, f, p, d)
-                f.close()
-
-                # Preprocess
                 try:
-                    kvm_preprocessing.preprocess(self, params, env)
-                finally:
-                    kvm_utils.dump_env(env, env_filename)
-                # Run the test function
-                run_func = getattr(test_module, "run_%s" % t_type)
-                try:
-                    run_func(self, params, env)
-                finally:
-                    kvm_utils.dump_env(env, env_filename)
+                    # Get the test routine corresponding to the specified
+                    # test type
+                    t_type = params.get("type")
+                    # Verify if we have the correspondent source file for it
+                    subtest_dir = os.path.join(self.bindir, "tests")
+                    module_path = os.path.join(subtest_dir, "%s.py" % t_type)
+                    if not os.path.isfile(module_path):
+                        raise error.TestError("No %s.py test file found" %
+                                              t_type)
+                    # Load the test module
+                    f, p, d = imp.find_module(t_type, [subtest_dir])
+                    test_module = imp.load_module(t_type, f, p, d)
+                    f.close()
 
-            except Exception, e:
-                logging.error("Test failed: %s", e)
-                logging.debug("Postprocessing on error...")
+                    # Preprocess
+                    try:
+                        kvm_preprocessing.preprocess(self, params, env)
+                    finally:
+                        kvm_utils.dump_env(env, env_filename)
+                    # Run the test function
+                    run_func = getattr(test_module, "run_%s" % t_type)
+                    try:
+                        run_func(self, params, env)
+                    finally:
+                        kvm_utils.dump_env(env, env_filename)
+                    test_passed = True
+
+                except Exception, e:
+                    logging.error("Test failed: %s", e)
+                    try:
+                        kvm_preprocessing.postprocess_on_error(
+                            self, params, env)
+                    finally:
+                        kvm_utils.dump_env(env, env_filename)
+                    raise
+
+            finally:
+                # Postprocess
                 try:
-                    kvm_preprocessing.postprocess_on_error(self, params, env)
+                    try:
+                        kvm_preprocessing.postprocess(self, params, env)
+                    except Exception, e:
+                        if test_passed:
+                            raise
+                        logging.error("Exception raised during "
+                                      "postprocessing: %s", e)
                 finally:
                     kvm_utils.dump_env(env, env_filename)
-                raise
+                    logging.debug("Contents of environment: %s", env)
 
-        finally:
-            # Postprocess
-            try:
-                kvm_preprocessing.postprocess(self, params, env)
-            finally:
-                kvm_utils.dump_env(env, env_filename)
-                logging.debug("Contents of environment: %s", str(env))
+        except Exception, e:
+            if params.get("abort_on_error") != "yes":
+                raise
+            # Abort on error
+            logging.info("Aborting job (%s)", e)
+            for vm in kvm_utils.env_get_all_vms(env):
+                if vm.is_dead():
+                    continue
+                logging.info("VM '%s' is alive.", vm.name)
+                for m in vm.monitors:
+                    logging.info("'%s' has a %s monitor unix socket at: %s",
+                                 vm.name, m.protocol, m.filename)
+                logging.info("The command line used to start '%s' was:\n%s",
+                             vm.name, vm.make_qemu_command())
+            raise error.JobError("Abort requested (%s)" % e)
client/tests/kvm/kvm_preprocessing.py +0 -14
index 17f3a29..84ad7c5 100644
@@ -362,20 +362,6 @@ def postprocess(test, params, env):
                         int(params.get("post_command_timeout", "600")),
                         params.get("post_command_noncritical") == "yes")
 
-    # Abort on error?
-    if params.get("abort") == "yes":
-        exc_string = str(sys.exc_info()[1])
-        logging.info("Aborting job (%s)", exc_string)
-        for vm in kvm_utils.env_get_all_vms(env):
-            if not vm.is_dead():
-                logging.info("VM '%s' is alive.", vm.name)
-                for m in vm.monitors:
-                    logging.info("'%s' has a %s monitor unix socket at: %s",
-                                 vm.name, m.protocol, m.filename)
-                logging.info("The command line used to start '%s' was:\n%s",
-                             vm.name, vm.make_qemu_command())
-        raise error.JobError("Abort requested (%s)" % exc_string)
-
 
 def postprocess_on_error(test, params, env):
     """
Signature · 1 line
1.5.4.1
#2 lore raw

PATCH 3/18 KVM test: kvm_monitor.py: add convenience method get_event()

get_event() looks for and returns a single event matching the given name, or None if none is found.

---
 client/tests/kvm/kvm_monitor.py |   12 ++++++++++++
 1 files changed, 12 insertions(+), 0 deletions(-)
client/tests/kvm/kvm_monitor.py +12 -0
index 12cf773..c2c6261 100644
@@ -566,6 +566,18 @@ class QMPMonitor(Monitor):
             self._lock.release()
 
 
+    def get_event(self, name):
+        """
+        Look for an event with the given name in the list of events.
+
+        @param name: The name of the event to look for (e.g. 'RESET')
+        @return: An event object or None if none is found
+        """
+        for e in self.get_events():
+            if e.get("event") == name:
+                return e
+
+
     def clear_events(self):
         """
         Clear the list of asynchronous events.
Signature · 1 line
1.5.4.1
#3 lore raw

PATCH 4/18 KVM test: kvm_monitor.py: verify correctness of QMP transaction id

In _get_command_output(), instead of just looking for an object with a 'return' or 'error' key, look for an object with the same unique transaction id given in the command. Also modify exception message accordingly.

---
 client/tests/kvm/kvm_monitor.py |   27 ++++++++++++++++-----------
 1 files changed, 16 insertions(+), 11 deletions(-)
client/tests/kvm/kvm_monitor.py +16 -11
index c2c6261..8d4a798 100644
@@ -427,10 +427,12 @@ class QMPMonitor(Monitor):
 
     # Private methods
 
-    def _build_cmd(self, cmd, args=None):
+    def _build_cmd(self, cmd, args=None, id=None):
         obj = {"execute": cmd}
-        if args:
+        if args is not None:
             obj["arguments"] = args
+        if id is not None:
+            obj["id"] = id
         return obj
 
 
@@ -467,7 +469,7 @@ class QMPMonitor(Monitor):
         return objs
 
 
-    def _send_command(self, cmd, args=None):
+    def _send_command(self, cmd, args=None, id=None):
         """
         Send command without waiting for response.
 
@@ -481,7 +483,7 @@ class QMPMonitor(Monitor):
                                    "QMP command '%s'" % cmd)
 
         try:
-            cmdobj = self._build_cmd(cmd, args)
+            cmdobj = self._build_cmd(cmd, args, id)
             try:
                 self._socket.sendall(json.dumps(cmdobj) + "\n")
             except socket.error:
@@ -514,20 +516,23 @@ class QMPMonitor(Monitor):
             # Read any data that might be available
             self._read_objects()
             # Send command
-            self._send_command(cmd, args)
+            id = kvm_utils.generate_random_string(8)
+            self._send_command(cmd, args, id)
             # Read response
             end_time = time.time() + timeout
             while time.time() < end_time:
                 for obj in self._read_objects():
-                    if "return" in obj:
-                        return obj["return"]
-                    elif "error" in obj:
-                        raise QMPCmdError("QMP command '%s' failed" % cmd,
-                                          obj["error"])
+                    if isinstance(obj, dict) and obj.get("id") == id:
+                        if "return" in obj:
+                            return obj["return"]
+                        elif "error" in obj:
+                            raise QMPCmdError("QMP command '%s' failed" % cmd,
+                                              obj["error"])
                 time.sleep(0.1)
             # No response found
             raise MonitorProtocolError("Received no response to QMP command "
-                                       "'%s'" % cmd)
+                                       "'%s', or received a response with an "
+                                       "incorrect id" % cmd)
 
         finally:
             self._lock.release()
Signature · 1 line
1.5.4.1
#4 lore raw

PATCH 5/18 KVM test: check for RESET QMP events in the system_reset test

If the VM has QMP monitors and no such events are found, fail.

---
 client/tests/kvm/kvm_test_utils.py |   14 +++++++++++++-
 1 files changed, 13 insertions(+), 1 deletions(-)
client/tests/kvm/kvm_test_utils.py +13 -1
index 9fdea87..7358589 100644
@@ -80,14 +80,26 @@ def reboot(vm, session, method="shell", sleep_before_reset=10, nic_index=0,
     if method == "shell":
         # Send a reboot command to the guest's shell
         session.sendline(vm.get_params().get("reboot_command"))
-        logging.info("Reboot command sent. Waiting for guest to go down")
+        logging.info("Reboot command sent. Waiting for guest to go down...")
     elif method == "system_reset":
         # Sleep for a while before sending the command
         time.sleep(sleep_before_reset)
+        # Clear the event list of all QMP monitors
+        monitors = [m for m in vm.monitors if m.protocol == "qmp"]
+        for m in monitors:
+            m.clear_events()
         # Send a system_reset monitor command
         vm.monitor.cmd("system_reset")
         logging.info("Monitor command system_reset sent. Waiting for guest to "
                      "go down...")
+        # Look for RESET QMP events
+        time.sleep(1)
+        for m in monitors:
+            if not m.get_event("RESET"):
+                raise error.TestFail("RESET QMP event not received after "
+                                     "system_reset (monitor '%s')" % m.name)
+            else:
+                logging.info("RESET QMP event received")
     else:
         logging.error("Unknown reboot method: %s", method)
 
Signature · 1 line
1.5.4.1
#5 lore raw

RFC PATCH 6/18 KVM test: tests_base.cfg.sample: remove noacpi, userirq variants

AFAIK there is very little interest in these variants, so make all tests use the default options (acpi enabled). Note that you shouldn't use 'only acpi' now because the acpi variant is no longer defined.

---
 client/tests/kvm/tests.cfg.sample      |    4 ----
 client/tests/kvm/tests_base.cfg.sample |   14 --------------
 2 files changed, 0 insertions(+), 18 deletions(-)
client/tests/kvm/tests.cfg.sample +0 -4
index e0d4271..a55a320 100644
@@ -34,8 +34,6 @@ variants:
         only rtl8139
         # Only ide hard drives
         only ide
-        # acpi means that acpi and kvm irq chip are enabled
-        only acpi
         # qemu-kvm will start only with -smp 2 (2 processors)
         only smp2
         # No PCI assignable devices
@@ -55,7 +53,6 @@ variants:
         # The default nw card for qemu is e1000
         only e1000
         only ide
-        only acpi
         # qemu using kvm doesn't support smp yet
         only up
         only no_pci_assignable
@@ -72,7 +69,6 @@ variants:
         only qcow2
         only rtl8139
         only ide
-        only acpi
         only smp2
         only no_pci_assignable
         only smallpages
client/tests/kvm/tests_base.cfg.sample +0 -14
index cabeb4a..ec61a5e 100644
@@ -1384,18 +1384,6 @@ variants:
 
 
 variants:
-    - @acpi:
-    - noacpi:
-        only Fedora Ubuntu Windows
-        no WinVista Win2008
-        no smp2.*Windows
-        extra_params += " -no-acpi"
-    - userirq:
-        only Fedora Ubuntu Windows
-        extra_params += " -no-kvm-irqchip -no-kvm-pit"
-
-
-variants:
     - @ide:
         drive_format=ide
     - scsi:
@@ -1422,14 +1410,12 @@ variants:
         only Fedora Ubuntu Windows
         only smp2
         only rtl8139
-        only acpi
         image_format = vmdk
     - raw:
         no ioquit
         only Fedora Ubuntu Windows
         only smp2
         only rtl8139
-        only acpi
         image_format = raw
 
 
Signature · 1 line
1.5.4.1
#6 lore raw

PATCH 7/18 KVM test: kvm_preprocessing.py: simplify pre/post_command error handling

Currently the error message appears twice: both in a logging.warn() statement and in an exception. Also the error.TestError raised adds unnecessary text to the exception message, which is informative enough as it is.

---
 client/tests/kvm/kvm_preprocessing.py |   10 ++++------
 1 files changed, 4 insertions(+), 6 deletions(-)
client/tests/kvm/kvm_preprocessing.py +4 -6
index 84ad7c5..1ed4ec2 100644
@@ -162,12 +162,10 @@ def process_command(test, params, env, command, command_timeout,
     try:
         utils.system("cd %s; %s" % (test.bindir, command))
     except error.CmdError, e:
-        logging.warn("Custom processing command '%s' failed, output is: %s",
-                     command, str(e))
-        if not command_noncritical:
-            raise error.TestError("Custom processing command failed: %s" %
-                                  str(e))
-
+        if command_noncritical:
+            logging.warn(e)
+        else:
+            raise
 
 def process(test, params, env, image_func, vm_func):
     """
Signature · 1 line
1.5.4.1
#7 lore raw

PATCH 8/18 KVM test: simplify remote_scp()

No need to use the redundant timeout check (end_time <= time.time()). This is taken care of by read_until_last_line_matches(). The same goes for the exit status check.

Also, rename timeout to transfer_timeout and timeout_ to timeout.

---
 client/tests/kvm/kvm_utils.py |   56 +++++++++++++++-------------------------
 1 files changed, 21 insertions(+), 35 deletions(-)
client/tests/kvm/kvm_utils.py +21 -35
index 0ea5a8a..1399892 100644
@@ -524,20 +524,20 @@ def remote_login(command, password, prompt, linesep="\n", timeout=10):
             return None
 
 
-def remote_scp(command, password, timeout=600, login_timeout=10):
+def remote_scp(command, password, transfer_timeout=600, login_timeout=10):
     """
     Run the given command using kvm_spawn and provide answers to the questions
-    asked. If timeout expires while waiting for the transfer to complete ,
-    fail. If login_timeout expires while waiting for output from the child
-    (e.g. a password prompt), fail.
+    asked. If transfer_timeout expires while waiting for the transfer to
+    complete, fail. If login_timeout expires while waiting for output from the
+    child (e.g. a password prompt), fail.
 
     @brief: Transfer files using SCP, given a command line.
 
     @param command: The command to execute
         (e.g. "scp -r foobar root@localhost:/tmp/").
     @param password: The password to send in reply to a password prompt.
-    @param timeout: The time duration (in seconds) to wait for the transfer
-        to complete.
+    @param transfer_timeout: The time duration (in seconds) to wait for the
+        transfer to complete.
     @param login_timeout: The maximal time duration (in seconds) to wait for
         each step of the login procedure (i.e. the "Are you sure" prompt or the
         password prompt)
@@ -547,20 +547,15 @@ def remote_scp(command, password, timeout=600, login_timeout=10):
     sub = kvm_subprocess.kvm_expect(command)
 
     password_prompt_count = 0
-    _timeout = login_timeout
-    end_time = time.time() + timeout
-    logging.debug("Trying to SCP with command '%s', timeout %ss", command,
-                  timeout)
+    timeout = login_timeout
+
+    logging.debug("Trying to SCP with command '%s', timeout %ss",
+                  command, timeout)
 
     while True:
-        if end_time <= time.time():
-            logging.debug("SCP transfer timed out")
-            sub.close()
-            return False
         (match, text) = sub.read_until_last_line_matches(
-                [r"[Aa]re you sure", r"[Pp]assword:\s*$", r"lost connection",
-                 r"Exit status", r"stalled"],
-                timeout=_timeout, internal_timeout=0.5)
+                [r"[Aa]re you sure", r"[Pp]assword:\s*$", r"lost connection"],
+                timeout=timeout, internal_timeout=0.5)
         if match == 0:  # "Are you sure you want to continue connecting"
             logging.debug("Got 'Are you sure...'; sending 'yes'")
             sub.sendline("yes")
@@ -570,7 +565,7 @@ def remote_scp(command, password, timeout=600, login_timeout=10):
                 logging.debug("Got password prompt; sending '%s'" % password)
                 sub.sendline(password)
                 password_prompt_count += 1
-                _timeout = timeout
+                timeout = transfer_timeout
                 continue
             else:
                 logging.debug("Got password prompt again")
@@ -580,25 +575,16 @@ def remote_scp(command, password, timeout=600, login_timeout=10):
             logging.debug("Got 'lost connection'")
             sub.close()
             return False
-        elif match == 3: # "Exit status"
-            sub.close()
-            if "Exit status 0" in text:
-                logging.debug("SCP command completed successfully")
-                return True
-            else:
-                logging.debug("SCP command fail with exit status %s" % text)
-                return False
-        elif match == 4: # "stalled"
-            logging.debug("SCP connection is stalled")
-            continue
-
         else:  # match == None
             if sub.is_alive():
-                continue
-            logging.debug("SCP process terminated")
-            status = sub.get_status()
-            sub.close()
-            return status == 0
+                logging.debug("Timeout expired")
+                sub.close()
+                return False
+            else:
+                status = sub.get_status()
+                sub.close()
+                logging.debug("SCP process terminated with status %s", status)
+                return status == 0
 
 
 def scp_to_remote(host, port, username, password, local_path, remote_path,
Signature · 1 line
1.5.4.1
#8 lore raw

PATCH 9/18 KVM test: kvm_utils.py: add a primitive logging mechanism for kvm_subprocess

Add log_line() which logs a single line to a given file. The file's path is given relative to a certain base dir.
Add set_log_dir() which sets the base dir.

This is useful for logging the output of kvm_subprocess. kvm_subprocess can take a callback function, which it calls with each line of output it gets from the running subprocess. Redirecting kvm_subprocess's output to the regular log files is done by passing it logging.debug or logging.info. However, in order to log to other files, we'd have to pass kvm_subprocess a custom logger method, e.g. our_custom_logger.debug. Unfortunately, such methods (called instancemethods) cannot be pickled, and kvm_subprocess relies on pickling. This patch offers an easy yet somewhat dirty solution to the problem.

---
 client/tests/kvm/kvm_utils.py |   37 +++++++++++++++++++++++++++++++++++++
 1 files changed, 37 insertions(+), 0 deletions(-)
client/tests/kvm/kvm_utils.py +37 -0
index 1399892..8569ac3 100644
@@ -732,6 +732,43 @@ def find_free_ports(start_port, end_port, count):
     return ports
 
 
+# An easy way to log lines to files when the logging system can't be used
+
+_open_log_files = {}
+_log_file_dir = "/tmp"
+
+
+def log_line(filename, line):
+    """
+    Write a line to a file.  '\n' is appended to the line.
+
+    @param filename: Path of file to write to, either absolute or relative to
+            the dir set by set_log_file_dir().
+    @param line: Line to write.
+    """
+    global _open_log_files, _log_file_dir
+    if filename not in _open_log_files:
+        path = get_path(_log_file_dir, filename)
+        try:
+            os.makedirs(os.path.dirname(path))
+        except OSError:
+            pass
+        _open_log_files[filename] = open(path, "w")
+    timestr = time.strftime("%Y-%m-%d %H:%M:%S")
+    _open_log_files[filename].write("%s: %s\n" % (timestr, line))
+    _open_log_files[filename].flush()
+
+
+def set_log_file_dir(dir):
+    """
+    Set the base directory for log files created by log_line().
+
+    @param dir: Directory for log files.
+    """
+    global _log_file_dir
+    _log_file_dir = dir
+
+
 # The following are miscellaneous utility functions.
 
 def get_path(base_path, user_path):
Signature · 1 line
1.5.4.1
#9 lore raw

PATCH 10/18 KVM test: add the auto_close option to all kvm_subprocess classes

Allow all kvm_subprocess classes (kvm_spawn, kvm_tail, kvm_expect, kvm_shell_session) to close automatically if auto_close is given and True. By default auto_close if False for all classes except kvm_shell_session, for which it is True by default.

---
 client/tests/kvm/kvm_subprocess.py |   50 +++++++++++++++++++++---------------
 1 files changed, 29 insertions(+), 21 deletions(-)
client/tests/kvm/kvm_subprocess.py +29 -21
index 2d70146..73edc5d 100755
@@ -285,7 +285,8 @@ class kvm_spawn:
     resumes _tail() if needed.
     """
 
-    def __init__(self, command=None, id=None, echo=False, linesep="\n"):
+    def __init__(self, command=None, id=None, auto_close=False, echo=False,
+                 linesep="\n"):
         """
         Initialize the class and run command as a child process.
 
@@ -293,6 +294,8 @@ class kvm_spawn:
                 server.
         @param id: ID of an already running server, if accessing a running
                 server, or None if starting a new one.
+        @param auto_close: If True, close() the instance automatically when its
+                reference count drops to zero (default False).
         @param echo: Boolean indicating whether echo should be initially
                 enabled for the pseudo terminal running the subprocess.  This
                 parameter has an effect only when starting a new server.
@@ -316,6 +319,7 @@ class kvm_spawn:
                                                               self.id)
 
         # Remember some attributes
+        self.auto_close = auto_close
         self.echo = echo
         self.linesep = linesep
 
@@ -378,7 +382,12 @@ class kvm_spawn:
     def __getinitargs__(self):
         # Save some information when pickling -- will be passed to the
         # constructor upon unpickling
-        return (None, self.id, self.echo, self.linesep)
+        return (None, self.id, self.auto_close, self.echo, self.linesep)
+
+
+    def __del__(self):
+        if self.auto_close:
+            self.close()
 
 
     def _add_reader(self, reader):
@@ -554,10 +563,9 @@ class kvm_tail(kvm_spawn):
     When this class is unpickled, it automatically resumes reporting output.
     """
 
-    def __init__(self, command=None, id=None, echo=False, linesep="\n",
-                 termination_func=None, termination_params=(),
-                 output_func=None, output_params=(),
-                 output_prefix=""):
+    def __init__(self, command=None, id=None, auto_close=False, echo=False,
+                 linesep="\n", termination_func=None, termination_params=(),
+                 output_func=None, output_params=(), output_prefix=""):
         """
         Initialize the class and run command as a child process.
 
@@ -565,6 +573,8 @@ class kvm_tail(kvm_spawn):
                 server.
         @param id: ID of an already running server, if accessing a running
                 server, or None if starting a new one.
+        @param auto_close: If True, close() the instance automatically when its
+                reference count drops to zero (default False).
         @param echo: Boolean indicating whether echo should be initially
                 enabled for the pseudo terminal running the subprocess.  This
                 parameter has an effect only when starting a new server.
@@ -587,7 +597,7 @@ class kvm_tail(kvm_spawn):
         self._add_close_hook(kvm_tail._join_thread)
 
         # Init the superclass
-        kvm_spawn.__init__(self, command, id, echo, linesep)
+        kvm_spawn.__init__(self, command, id, auto_close, echo, linesep)
 
         # Remember some attributes
         self.termination_func = termination_func
@@ -751,10 +761,9 @@ class kvm_expect(kvm_tail):
     It also provides all of kvm_tail's functionality.
     """
 
-    def __init__(self, command=None, id=None, echo=False, linesep="\n",
-                 termination_func=None, termination_params=(),
-                 output_func=None, output_params=(),
-                 output_prefix=""):
+    def __init__(self, command=None, id=None, auto_close=False, echo=False,
+                 linesep="\n", termination_func=None, termination_params=(),
+                 output_func=None, output_params=(), output_prefix=""):
         """
         Initialize the class and run command as a child process.
 
@@ -762,6 +771,8 @@ class kvm_expect(kvm_tail):
                 server.
         @param id: ID of an already running server, if accessing a running
                 server, or None if starting a new one.
+        @param auto_close: If True, close() the instance automatically when its
+                reference count drops to zero (default False).
         @param echo: Boolean indicating whether echo should be initially
                 enabled for the pseudo terminal running the subprocess.  This
                 parameter has an effect only when starting a new server.
@@ -783,7 +794,7 @@ class kvm_expect(kvm_tail):
         self._add_reader("expect")
 
         # Init the superclass
-        kvm_tail.__init__(self, command, id, echo, linesep,
+        kvm_tail.__init__(self, command, id, auto_close, echo, linesep,
                           termination_func, termination_params,
                           output_func, output_params, output_prefix)
 
@@ -967,10 +978,9 @@ class kvm_shell_session(kvm_expect):
     process for responsiveness.
     """
 
-    def __init__(self, command=None, id=None, echo=False, linesep="\n",
-                 termination_func=None, termination_params=(),
-                 output_func=None, output_params=(),
-                 output_prefix="",
+    def __init__(self, command=None, id=None, auto_close=True, echo=False,
+                 linesep="\n", termination_func=None, termination_params=(),
+                 output_func=None, output_params=(), output_prefix="",
                  prompt=r"[\#\$]\s*$", status_test_command="echo $?"):
         """
         Initialize the class and run command as a child process.
@@ -979,6 +989,8 @@ class kvm_shell_session(kvm_expect):
                 server.
         @param id: ID of an already running server, if accessing a running
                 server, or None if starting a new one.
+        @param auto_close: If True, close() the instance automatically when its
+                reference count drops to zero (default True).
         @param echo: Boolean indicating whether echo should be initially
                 enabled for the pseudo terminal running the subprocess.  This
                 parameter has an effect only when starting a new server.
@@ -1001,7 +1013,7 @@ class kvm_shell_session(kvm_expect):
                 get_command_status_output() and friends).
         """
         # Init the superclass
-        kvm_expect.__init__(self, command, id, echo, linesep,
+        kvm_expect.__init__(self, command, id, auto_close, echo, linesep,
                             termination_func, termination_params,
                             output_func, output_params, output_prefix)
 
@@ -1015,10 +1027,6 @@ class kvm_shell_session(kvm_expect):
                                                    self.status_test_command)
 
 
-    def __del__(self):
-        self.close()
-
-
     def set_prompt(self, prompt):
         """
         Set the prompt attribute for later use by read_up_to_prompt.
Signature · 1 line
1.5.4.1
#10 lore raw

PATCH 11/18 KVM test: restructure remote_login() and remote_scp()

- Add _remote_login() and _remote_scp() which, instead of taking a command line, take an existing session and operate on it. This is useful for logging into existing always-open sessions, such as serial console sessions.

- Merge ssh/telnet/netcat into remote_login().

---
 client/tests/kvm/kvm_utils.py |  208 +++++++++++++++++++----------------------
 client/tests/kvm/kvm_vm.py    |   11 +--
 2 files changed, 100 insertions(+), 119 deletions(-)
client/tests/kvm/kvm_utils.py +98 -110
index 8569ac3..468e7a8 100644
@@ -451,142 +451,183 @@ def check_kvm_source_dir(source_dir):
 # The following are functions used for SSH, SCP and Telnet communication with
 # guests.
 
-def remote_login(command, password, prompt, linesep="\n", timeout=10):
+def _remote_login(session, password, prompt, timeout=10):
     """
-    Log into a remote host (guest) using SSH or Telnet. Run the given command
-    using kvm_spawn and provide answers to the questions asked. If timeout
-    expires while waiting for output from the child (e.g. a password prompt
-    or a shell prompt) -- fail.
+    Log into a remote host (guest) using SSH or Telnet.  Wait for questions
+    and provide answers.  If timeout expires while waiting for output from the
+    child (e.g. a password prompt or a shell prompt) -- fail.
 
     @brief: Log into a remote host (guest) using SSH or Telnet.
 
-    @param command: The command to execute (e.g. "ssh root@localhost")
+    @param session: A kvm_expect or kvm_shell_session instance to operate on
     @param password: The password to send in reply to a password prompt
     @param prompt: The shell prompt that indicates a successful login
-    @param linesep: The line separator to send instead of "\\n"
-            (sometimes "\\r\\n" is required)
     @param timeout: The maximal time duration (in seconds) to wait for each
             step of the login procedure (i.e. the "Are you sure" prompt, the
             password prompt, the shell prompt, etc)
 
-    @return Return the kvm_spawn object on success and None on failure.
+    @return: True on success and False otherwise.
     """
-    sub = kvm_subprocess.kvm_shell_session(command,
-                                           linesep=linesep,
-                                           prompt=prompt)
-
     password_prompt_count = 0
 
-    logging.debug("Trying to login with command '%s'" % command)
-
     while True:
-        (match, text) = sub.read_until_last_line_matches(
+        (match, text) = session.read_until_last_line_matches(
                 [r"[Aa]re you sure", r"[Pp]assword:\s*$", r"^\s*[Ll]ogin:\s*$",
                  r"[Cc]onnection.*closed", r"[Cc]onnection.*refused",
                  r"[Pp]lease wait", prompt],
                  timeout=timeout, internal_timeout=0.5)
         if match == 0:  # "Are you sure you want to continue connecting"
             logging.debug("Got 'Are you sure...'; sending 'yes'")
-            sub.sendline("yes")
+            session.sendline("yes")
             continue
         elif match == 1:  # "password:"
             if password_prompt_count == 0:
                 logging.debug("Got password prompt; sending '%s'" % password)
-                sub.sendline(password)
+                session.sendline(password)
                 password_prompt_count += 1
                 continue
             else:
                 logging.debug("Got password prompt again")
-                sub.close()
-                return None
+                return False
         elif match == 2:  # "login:"
             logging.debug("Got unexpected login prompt")
-            sub.close()
-            return None
+            return False
         elif match == 3:  # "Connection closed"
             logging.debug("Got 'Connection closed'")
-            sub.close()
-            return None
+            return False
         elif match == 4:  # "Connection refused"
             logging.debug("Got 'Connection refused'")
-            sub.close()
-            return None
+            return False
         elif match == 5:  # "Please wait"
             logging.debug("Got 'Please wait'")
             timeout = 30
             continue
         elif match == 6:  # prompt
             logging.debug("Got shell prompt -- logged in")
-            return sub
+            return session
         else:  # match == None
             logging.debug("Timeout elapsed or process terminated")
-            sub.close()
-            return None
+            return False
 
 
-def remote_scp(command, password, transfer_timeout=600, login_timeout=10):
+def _remote_scp(session, password, transfer_timeout=600, login_timeout=10):
     """
-    Run the given command using kvm_spawn and provide answers to the questions
-    asked. If transfer_timeout expires while waiting for the transfer to
-    complete, fail. If login_timeout expires while waiting for output from the
-    child (e.g. a password prompt), fail.
+    Transfer file(s) to a remote host (guest) using SCP.  Wait for questions
+    and provide answers.  If login_timeout expires while waiting for output
+    from the child (e.g. a password prompt), fail.  If transfer_timeout expires
+    while waiting for the transfer to complete, fail.
 
     @brief: Transfer files using SCP, given a command line.
 
-    @param command: The command to execute
-        (e.g. "scp -r foobar root@localhost:/tmp/").
+    @param session: A kvm_expect or kvm_shell_session instance to operate on
     @param password: The password to send in reply to a password prompt.
     @param transfer_timeout: The time duration (in seconds) to wait for the
-        transfer to complete.
+            transfer to complete.
     @param login_timeout: The maximal time duration (in seconds) to wait for
-        each step of the login procedure (i.e. the "Are you sure" prompt or the
-        password prompt)
+            each step of the login procedure (i.e. the "Are you sure" prompt
+            or the password prompt)
 
     @return: True if the transfer succeeds and False on failure.
     """
-    sub = kvm_subprocess.kvm_expect(command)
-
     password_prompt_count = 0
     timeout = login_timeout
 
-    logging.debug("Trying to SCP with command '%s', timeout %ss",
-                  command, timeout)
-
     while True:
-        (match, text) = sub.read_until_last_line_matches(
+        (match, text) = session.read_until_last_line_matches(
                 [r"[Aa]re you sure", r"[Pp]assword:\s*$", r"lost connection"],
                 timeout=timeout, internal_timeout=0.5)
         if match == 0:  # "Are you sure you want to continue connecting"
             logging.debug("Got 'Are you sure...'; sending 'yes'")
-            sub.sendline("yes")
+            session.sendline("yes")
             continue
         elif match == 1:  # "password:"
             if password_prompt_count == 0:
                 logging.debug("Got password prompt; sending '%s'" % password)
-                sub.sendline(password)
+                session.sendline(password)
                 password_prompt_count += 1
                 timeout = transfer_timeout
                 continue
             else:
                 logging.debug("Got password prompt again")
-                sub.close()
                 return False
         elif match == 2:  # "lost connection"
             logging.debug("Got 'lost connection'")
-            sub.close()
             return False
         else:  # match == None
-            if sub.is_alive():
+            if session.is_alive():
                 logging.debug("Timeout expired")
-                sub.close()
                 return False
             else:
-                status = sub.get_status()
-                sub.close()
+                status = session.get_status()
                 logging.debug("SCP process terminated with status %s", status)
                 return status == 0
 
 
+def remote_login(client, host, port, username, password, prompt, linesep="\n",
+                 timeout=10):
+    """
+    Log into a remote host (guest) using SSH/Telnet/Netcat.
+
+    @param client: The client to use ('ssh', 'telnet' or 'nc')
+    @param host: Hostname or IP address
+    @param port: Port to connect to
+    @param username: Username (if required)
+    @param password: Password (if required)
+    @param prompt: Shell prompt (regular expression)
+    @param linesep: The line separator to use when sending lines
+            (e.g. '\\n' or '\\r\\n')
+    @param timeout: The maximal time duration (in seconds) to wait for
+            each step of the login procedure (i.e. the "Are you sure" prompt
+            or the password prompt)
+
+    @return: kvm_shell_session object on success and None on failure.
+    """
+    if client == "ssh":
+        cmd = ("ssh -o UserKnownHostsFile=/dev/null "
+               "-o PreferredAuthentications=password -p %s %s@%s" %
+               (port, username, host))
+    elif client == "telnet":
+        cmd = "telnet -l %s %s %s" % (username, host, port)
+    elif client == "nc":
+        cmd = "nc %s %s" % (host, port)
+    else:
+        logging.error("Unknown remote shell client: %s" % client)
+        return
+    logging.debug("Trying to login with command '%s'" % cmd)
+    session = kvm_subprocess.kvm_shell_session(cmd, linesep=linesep,
+                                               prompt=prompt)
+    if _remote_login(session, password, prompt, timeout):
+        return session
+    else:
+        session.close()
+
+
+def remote_scp(command, password, transfer_timeout=600, login_timeout=10):
+    """
+    Transfer file(s) to a remote host (guest) using SCP.
+
+    @brief: Transfer files using SCP, given a command line.
+
+    @param command: The command to execute
+        (e.g. "scp -r foobar root@localhost:/tmp/").
+    @param password: The password to send in reply to a password prompt.
+    @param transfer_timeout: The time duration (in seconds) to wait for the
+            transfer to complete.
+    @param login_timeout: The maximal time duration (in seconds) to wait for
+            each step of the login procedure (i.e. the "Are you sure" prompt
+            or the password prompt)
+
+    @return: True if the transfer succeeds and False on failure.
+    """
+    logging.debug("Trying to SCP with command '%s', timeout %ss",
+                  command, transfer_timeout)
+    session = kvm_subprocess.kvm_expect(command)
+    try:
+        return _remote_scp(session, password, transfer_timeout, login_timeout)
+    finally:
+        session.close()
+
+
 def scp_to_remote(host, port, username, password, local_path, remote_path,
                   timeout=600):
     """
@@ -597,8 +638,8 @@ def scp_to_remote(host, port, username, password, local_path, remote_path,
     @param password: Password (if required)
     @param local_path: Path on the local machine where we are copying from
     @param remote_path: Path on the remote machine where we are copying to
-    @param timeout: Time in seconds that we will wait before giving up to
-            copy the files.
+    @param timeout: The time duration (in seconds) to wait for the transfer
+            to complete.
 
     @return: True on success and False on failure.
     """
@@ -618,8 +659,8 @@ def scp_from_remote(host, port, username, password, remote_path, local_path,
     @param password: Password (if required)
     @param local_path: Path on the local machine where we are copying from
     @param remote_path: Path on the remote machine where we are copying to
-    @param timeout: Time in seconds that we will wait before giving up to copy
-            the files.
+    @param timeout: The time duration (in seconds) to wait for the transfer
+            to complete.
 
     @return: True on success and False on failure.
     """
@@ -629,59 +670,6 @@ def scp_from_remote(host, port, username, password, remote_path, local_path,
     return remote_scp(command, password, timeout)
 
 
-def ssh(host, port, username, password, prompt, linesep="\n", timeout=10):
-    """
-    Log into a remote host (guest) using SSH.
-
-    @param host: Hostname or IP address
-    @param username: Username (if required)
-    @param password: Password (if required)
-    @param prompt: Shell prompt (regular expression)
-    @timeout: Time in seconds that we will wait before giving up on logging
-            into the host.
-
-    @return: kvm_spawn object on success and None on failure.
-    """
-    command = ("ssh -o UserKnownHostsFile=/dev/null "
-               "-o PreferredAuthentications=password -p %s %s@%s" %
-               (port, username, host))
-    return remote_login(command, password, prompt, linesep, timeout)
-
-
-def telnet(host, port, username, password, prompt, linesep="\n", timeout=10):
-    """
-    Log into a remote host (guest) using Telnet.
-
-    @param host: Hostname or IP address
-    @param username: Username (if required)
-    @param password: Password (if required)
-    @param prompt: Shell prompt (regular expression)
-    @timeout: Time in seconds that we will wait before giving up on logging
-            into the host.
-
-    @return: kvm_spawn object on success and None on failure.
-    """
-    command = "telnet -l %s %s %s" % (username, host, port)
-    return remote_login(command, password, prompt, linesep, timeout)
-
-
-def netcat(host, port, username, password, prompt, linesep="\n", timeout=10):
-    """
-    Log into a remote host (guest) using Netcat.
-
-    @param host: Hostname or IP address
-    @param username: Username (if required)
-    @param password: Password (if required)
-    @param prompt: Shell prompt (regular expression)
-    @timeout: Time in seconds that we will wait before giving up on logging
-            into the host.
-
-    @return: kvm_spawn object on success and None on failure.
-    """
-    command = "nc %s %s" % (host, port)
-    return remote_login(command, password, prompt, linesep, timeout)
-
-
 # The following are utility functions related to ports.
 
 def is_port_free(port):
client/tests/kvm/kvm_vm.py +2 -9
index 8113a45..c82226d 100755
@@ -901,15 +901,8 @@ class VM:
             logging.debug("IP address or port unavailable")
             return None
 
-        if client == "ssh":
-            session = kvm_utils.ssh(address, port, username, password,
-                                    prompt, linesep, timeout)
-        elif client == "telnet":
-            session = kvm_utils.telnet(address, port, username, password,
-                                       prompt, linesep, timeout)
-        elif client == "nc":
-            session = kvm_utils.netcat(address, port, username, password,
-                                       prompt, linesep, timeout)
+        session = kvm_utils.remote_login(client, address, port, username,
+                                         password, prompt, linesep, timeout)
 
         if session:
             session.set_status_test_command(self.params.get("status_test_"
Signature · 1 line
1.5.4.1
#11 lore raw

PATCH 12/18 KVM test: send username in remote_login()

In order to let the serial console work, we must let the remote_login() send the username when met the username prompt. This patch fails the progress if if it met the username prompt twice.

---
 client/tests/kvm/kvm_utils.py |   16 ++++++++++++----
 1 files changed, 12 insertions(+), 4 deletions(-)
client/tests/kvm/kvm_utils.py +12 -4
index 468e7a8..6750d15 100644
@@ -451,7 +451,7 @@ def check_kvm_source_dir(source_dir):
 # The following are functions used for SSH, SCP and Telnet communication with
 # guests.
 
-def _remote_login(session, password, prompt, timeout=10):
+def _remote_login(session, username, password, prompt, timeout=10):
     """
     Log into a remote host (guest) using SSH or Telnet.  Wait for questions
     and provide answers.  If timeout expires while waiting for output from the
@@ -460,6 +460,7 @@ def _remote_login(session, password, prompt, timeout=10):
     @brief: Log into a remote host (guest) using SSH or Telnet.
 
     @param session: A kvm_expect or kvm_shell_session instance to operate on
+    @param username: The username to send in reply to a login prompt
     @param password: The password to send in reply to a password prompt
     @param prompt: The shell prompt that indicates a successful login
     @param timeout: The maximal time duration (in seconds) to wait for each
@@ -469,6 +470,7 @@ def _remote_login(session, password, prompt, timeout=10):
     @return: True on success and False otherwise.
     """
     password_prompt_count = 0
+    login_prompt_count = 0
 
     while True:
         (match, text) = session.read_until_last_line_matches(
@@ -490,8 +492,14 @@ def _remote_login(session, password, prompt, timeout=10):
                 logging.debug("Got password prompt again")
                 return False
         elif match == 2:  # "login:"
-            logging.debug("Got unexpected login prompt")
-            return False
+            if login_prompt_count == 0:
+                logging.debug("Got username prompt; sending '%s'" % username)
+                session.sendline(username)
+                login_prompt_count += 1
+                continue
+            else:
+                logging.debug("Got username prompt again")
+                return False
         elif match == 3:  # "Connection closed"
             logging.debug("Got 'Connection closed'")
             return False
@@ -596,7 +604,7 @@ def remote_login(client, host, port, username, password, prompt, linesep="\n",
     logging.debug("Trying to login with command '%s'" % cmd)
     session = kvm_subprocess.kvm_shell_session(cmd, linesep=linesep,
                                                prompt=prompt)
-    if _remote_login(session, password, prompt, timeout):
+    if _remote_login(session, username, password, prompt, timeout):
         return session
     else:
         session.close()
Signature · 1 line
1.5.4.1
#12 lore raw

PATCH 13/18 KVM test: remote_login(): make the login re suitable for serial console

Current matching re ^\s*[Ll]ogin:\s*$ is not suitable for the serial console, so change it to [Ll]ogin:\s*$.

---
 client/tests/kvm/kvm_utils.py |    2 +-
 1 files changed, 1 insertions(+), 1 deletions(-)
client/tests/kvm/kvm_utils.py +1 -1
index 6750d15..074fa2c 100644
@@ -474,7 +474,7 @@ def _remote_login(session, username, password, prompt, timeout=10):
 
     while True:
         (match, text) = session.read_until_last_line_matches(
-                [r"[Aa]re you sure", r"[Pp]assword:\s*$", r"^\s*[Ll]ogin:\s*$",
+                [r"[Aa]re you sure", r"[Pp]assword:\s*$", r"[Ll]ogin:\s*$",
                  r"[Cc]onnection.*closed", r"[Cc]onnection.*refused",
                  r"[Pp]lease wait", prompt],
                  timeout=timeout, internal_timeout=0.5)
Signature · 1 line
1.5.4.1
#13 lore raw

PATCH 14/18 KVM test: kvm_vm.py: redirect the serial console to a unix socket

Based on Jason Wang's patch.

---
 client/tests/kvm/kvm_vm.py |   13 +++++++++++++
 1 files changed, 13 insertions(+), 0 deletions(-)
client/tests/kvm/kvm_vm.py +13 -0
index c82226d..5012d66 100755
@@ -203,6 +203,9 @@ class VM:
         def add_qmp_monitor(help, filename):
             return " -qmp unix:'%s',server,nowait" % filename
 
+        def add_serial(help, filename):
+            return " -serial unix:'%s',server,nowait" % filename
+
         def add_mem(help, mem):
             return " -m %s" % mem
 
@@ -313,6 +316,9 @@ class VM:
             else:
                 qemu_cmd += add_human_monitor(help, monitor_filename)
 
+        # Add serial console redirection
+        qemu_cmd += add_serial(help, self.get_serial_console_filename())
+
         for image_name in kvm_utils.get_sub_dict_names(params, "images"):
             image_params = kvm_utils.get_sub_dict(params, image_name)
             if image_params.get("boot_drive") == "no":
@@ -772,6 +778,13 @@ class VM:
                 kvm_utils.get_sub_dict_names(self.params, "monitors")]
 
 
+    def get_serial_console_filename(self):
+        """
+        Return the serial console filename.
+        """
+        return "/tmp/serial-%s" % self.instance
+
+
     def get_testlog_filename(self):
         """
         Return the testlog filename.
Signature · 1 line
1.5.4.1
#14 lore raw

PATCH 15/18 KVM test: kvm_vm.py: log serial console output and allow serial login

Log serial console output to files in the debug dir.

Also, add VM.serial_login() which attempts to log in via the serial console.

Note:

- Tests must NOT close() a serial console session, because it needs to remain open for the following tests to use.

- Instead, tests must use session.sendline("exit") for serial console sessions:

session = vm.serial_login()
try:
...
finally:
session.sendline("exit")

- Only one serial console session per VM is available at a time. Calling serial_login() twice for the same VM, without an "exit" between the calls, will probably fail and/or do bad stuff.

---
 client/tests/kvm/kvm_vm.py |   41 +++++++++++++++++++++++++++++++++++++++++
 1 files changed, 41 insertions(+), 0 deletions(-)
client/tests/kvm/kvm_vm.py +41 -0
index 5012d66..c8a282d 100755
@@ -106,6 +106,7 @@ class VM:
         @param address_cache: A dict that maps MAC addresses to IP addresses
         """
         self.process = None
+        self.serial_console = None
         self.redirs = {}
         self.vnc_port = 5900
         self.uuid = None
@@ -632,6 +633,15 @@ class VM:
                 return False
 
             logging.debug("VM appears to be alive with PID %s", self.get_pid())
+
+            # Establish a session with the serial console -- requires a version
+            # of netcat that supports -U
+            self.serial_console = kvm_subprocess.kvm_shell_session(
+                "nc -U %s" % self.get_serial_console_filename(),
+                auto_close=False,
+                output_func=kvm_utils.log_line,
+                output_params=("serial-%s.log" % name,))
+
             return True
 
         finally:
@@ -705,6 +715,8 @@ class VM:
                 self.pci_assignable.release_devs()
             if self.process:
                 self.process.close()
+            if self.serial_console:
+                self.serial_console.close()
             for f in ([self.get_testlog_filename()] +
                       self.get_monitor_filenames()):
                 try:
@@ -973,6 +985,35 @@ class VM:
                                              remote_path, local_path, timeout)
 
 
+    def serial_login(self, timeout=10):
+        """
+        Log into the guest via the serial console.
+        If timeout expires while waiting for output from the guest (e.g. a
+        password prompt or a shell prompt) -- fail.
+
+        @param timeout: Time (seconds) before giving up logging into the guest.
+        @return: kvm_spawn object on success and None on failure.
+        """
+        username = self.params.get("username", "")
+        password = self.params.get("password", "")
+        prompt = self.params.get("shell_prompt", "[\#\$]")
+        linesep = eval("'%s'" % self.params.get("shell_linesep", r"\n"))
+        status_test_command = self.params.get("status_test_command", "")
+
+        if self.serial_console:
+            self.serial_console.set_linesep(linesep)
+            self.serial_console.set_status_test_command(status_test_command)
+        else:
+            return None
+
+        # Make sure we get a login prompt
+        self.serial_console.sendline()
+
+        if kvm_utils._remote_login(self.serial_console, username, password,
+                                   prompt, timeout):
+            return self.serial_console
+
+
     def send_key(self, keystr):
         """
         Send a key event to the VM.
Signature · 1 line
1.5.4.1
#15 lore raw

PATCH 16/18 KVM test: kvm.py: set log file dir for kvm_subprocess logging

---
 client/tests/kvm/kvm.py |    4 ++++
 1 files changed, 4 insertions(+), 0 deletions(-)
client/tests/kvm/kvm.py +4 -0
index bab1e6f..0799cff 100644
@@ -31,6 +31,10 @@ class kvm(test.test):
             logging.debug("    %s = %s", key, params[key])
             self.write_test_keyval({key: params[key]})
 
+        # Set the log file dir for the logging mechanism used by kvm_subprocess
+        # (this must be done before unpickling env)
+        kvm_utils.set_log_file_dir(self.debugdir)
+
         # Open the environment file
         logging.info("Unpickling env. You may see some harmless error "
                      "messages.")
Signature · 1 line
1.5.4.1
#16 lore raw

PATCH 17/18 KVM test: kvm_subprocess.py: don't sanitize text before passing it to callbacks

Converting the text to utf-8 seems to cause trouble when converting back (e.g. when writing to files). The logging system seems to be fine with unsanitized text, so let's not sanitize it.

---
 client/tests/kvm/kvm_subprocess.py |    6 ++----
 1 files changed, 2 insertions(+), 4 deletions(-)
client/tests/kvm/kvm_subprocess.py +2 -4
index 73edc5d..93a8429 100755
@@ -688,9 +688,7 @@ class kvm_tail(kvm_spawn):
         def print_line(text):
             # Pre-pend prefix and remove trailing whitespace
             text = self.output_prefix + text.rstrip()
-            # Sanitize text
-            text = text.decode("utf-8", "replace")
-            # Pass it to output_func
+            # Pass text to output_func
             try:
                 params = self.output_params + (text,)
                 self.output_func(*params)
@@ -888,7 +886,7 @@ class kvm_expect(kvm_tail):
                 if str.endswith("\n"):
                     str = str[:-1]
                 for line in str.split("\n"):
-                    print_func(line.decode("utf-8", "replace"))
+                    print_func(line)
             data += newdata
 
             done = False
Signature · 1 line
1.5.4.1
#17 lore raw

PATCH 18/18 KVM test: log output of all shell sessions and SCP transfers

Use kvm_utils.log_line() to log the output of all shell sessions and SCP transfers.

---
 client/tests/kvm/kvm_utils.py |   33 ++++++++++++++++++++++++++-------
 client/tests/kvm/kvm_vm.py    |   15 ++++++++++++---
 2 files changed, 38 insertions(+), 10 deletions(-)
client/tests/kvm/kvm_utils.py +26 -7
index 074fa2c..409804a 100644
@@ -572,7 +572,7 @@ def _remote_scp(session, password, transfer_timeout=600, login_timeout=10):
 
 
 def remote_login(client, host, port, username, password, prompt, linesep="\n",
-                 timeout=10):
+                 log_filename=None, timeout=10):
     """
     Log into a remote host (guest) using SSH/Telnet/Netcat.
 
@@ -584,6 +584,7 @@ def remote_login(client, host, port, username, password, prompt, linesep="\n",
     @param prompt: Shell prompt (regular expression)
     @param linesep: The line separator to use when sending lines
             (e.g. '\\n' or '\\r\\n')
+    @param log_filename: If specified, log all output to this file
     @param timeout: The maximal time duration (in seconds) to wait for
             each step of the login procedure (i.e. the "Are you sure" prompt
             or the password prompt)
@@ -601,16 +602,21 @@ def remote_login(client, host, port, username, password, prompt, linesep="\n",
     else:
         logging.error("Unknown remote shell client: %s" % client)
         return
+
     logging.debug("Trying to login with command '%s'" % cmd)
     session = kvm_subprocess.kvm_shell_session(cmd, linesep=linesep,
                                                prompt=prompt)
     if _remote_login(session, username, password, prompt, timeout):
+        if log_filename:
+            session.set_output_func(log_line)
+            session.set_output_params((log_filename,))
         return session
     else:
         session.close()
 
 
-def remote_scp(command, password, transfer_timeout=600, login_timeout=10):
+def remote_scp(command, password, log_filename=None, transfer_timeout=600,
+               login_timeout=10):
     """
     Transfer file(s) to a remote host (guest) using SCP.
 
@@ -619,6 +625,7 @@ def remote_scp(command, password, transfer_timeout=600, login_timeout=10):
     @param command: The command to execute
         (e.g. "scp -r foobar root@localhost:/tmp/").
     @param password: The password to send in reply to a password prompt.
+    @param log_filename: If specified, log all output to this file
     @param transfer_timeout: The time duration (in seconds) to wait for the
             transfer to complete.
     @param login_timeout: The maximal time duration (in seconds) to wait for
@@ -629,7 +636,17 @@ def remote_scp(command, password, transfer_timeout=600, login_timeout=10):
     """
     logging.debug("Trying to SCP with command '%s', timeout %ss",
                   command, transfer_timeout)
-    session = kvm_subprocess.kvm_expect(command)
+
+    if log_filename:
+        output_func = log_line
+        output_params = (log_filename,)
+    else:
+        output_func = None
+        output_params = ()
+
+    session = kvm_subprocess.kvm_expect(command,
+                                        output_func=output_func,
+                                        output_params=output_params)
     try:
         return _remote_scp(session, password, transfer_timeout, login_timeout)
     finally:
@@ -637,7 +654,7 @@ def remote_scp(command, password, transfer_timeout=600, login_timeout=10):
 
 
 def scp_to_remote(host, port, username, password, local_path, remote_path,
-                  timeout=600):
+                  log_filename=None, timeout=600):
     """
     Copy files to a remote host (guest).
 
@@ -646,6 +663,7 @@ def scp_to_remote(host, port, username, password, local_path, remote_path,
     @param password: Password (if required)
     @param local_path: Path on the local machine where we are copying from
     @param remote_path: Path on the remote machine where we are copying to
+    @param log_filename: If specified, log all output to this file
     @param timeout: The time duration (in seconds) to wait for the transfer
             to complete.
 
@@ -654,11 +672,11 @@ def scp_to_remote(host, port, username, password, local_path, remote_path,
     command = ("scp -v -o UserKnownHostsFile=/dev/null "
                "-o PreferredAuthentications=password -r -P %s %s %s@%s:%s" %
                (port, local_path, username, host, remote_path))
-    return remote_scp(command, password, timeout)
+    return remote_scp(command, password, log_filename, timeout)
 
 
 def scp_from_remote(host, port, username, password, remote_path, local_path,
-                    timeout=600):
+                    log_filename=None, timeout=600):
     """
     Copy files from a remote host (guest).
 
@@ -667,6 +685,7 @@ def scp_from_remote(host, port, username, password, remote_path, local_path,
     @param password: Password (if required)
     @param local_path: Path on the local machine where we are copying from
     @param remote_path: Path on the remote machine where we are copying to
+    @param log_filename: If specified, log all output to this file
     @param timeout: The time duration (in seconds) to wait for the transfer
             to complete.
 
@@ -675,7 +694,7 @@ def scp_from_remote(host, port, username, password, remote_path, local_path,
     command = ("scp -v -o UserKnownHostsFile=/dev/null "
                "-o PreferredAuthentications=password -r -P %s %s@%s:%s %s" %
                (port, username, host, remote_path, local_path))
-    return remote_scp(command, password, timeout)
+    return remote_scp(command, password, log_filename, timeout)
 
 
 # The following are utility functions related to ports.
client/tests/kvm/kvm_vm.py +12 -3
index c8a282d..c5234c8 100755
@@ -921,13 +921,16 @@ class VM:
         client = self.params.get("shell_client")
         address = self.get_address(nic_index)
         port = self.get_port(int(self.params.get("shell_port")))
+        log_filename = ("session-%s-%s.log" %
+                        (self.name, kvm_utils.generate_random_string(4)))
 
         if not address or not port:
             logging.debug("IP address or port unavailable")
             return None
 
         session = kvm_utils.remote_login(client, address, port, username,
-                                         password, prompt, linesep, timeout)
+                                         password, prompt, linesep,
+                                         log_filename, timeout)
 
         if session:
             session.set_status_test_command(self.params.get("status_test_"
@@ -950,6 +953,8 @@ class VM:
         client = self.params.get("file_transfer_client")
         address = self.get_address(nic_index)
         port = self.get_port(int(self.params.get("file_transfer_port")))
+        log_filename = ("scp-%s-%s.log" %
+                        (self.name, kvm_utils.generate_random_string(4)))
 
         if not address or not port:
             logging.debug("IP address or port unavailable")
@@ -957,7 +962,8 @@ class VM:
 
         if client == "scp":
             return kvm_utils.scp_to_remote(address, port, username, password,
-                                           local_path, remote_path, timeout)
+                                           local_path, remote_path,
+                                           log_filename, timeout)
 
 
     def copy_files_from(self, remote_path, local_path, nic_index=0, timeout=600):
@@ -975,6 +981,8 @@ class VM:
         client = self.params.get("file_transfer_client")
         address = self.get_address(nic_index)
         port = self.get_port(int(self.params.get("file_transfer_port")))
+        log_filename = ("scp-%s-%s.log" %
+                        (self.name, kvm_utils.generate_random_string(4)))
 
         if not address or not port:
             logging.debug("IP address or port unavailable")
@@ -982,7 +990,8 @@ class VM:
 
         if client == "scp":
             return kvm_utils.scp_from_remote(address, port, username, password,
-                                             remote_path, local_path, timeout)
+                                             remote_path, local_path,
+                                             log_filename, timeout)
 
 
     def serial_login(self, timeout=10):
Signature · 1 line
1.5.4.1