Fix Unhandled* exceptions
PATCH v3 1/11 Fix Unhandled* exceptions
In recent Python versions, when exceptions are unpickled their __init__() method is called again. The parameters passed to __init__() upon unpickling are *self.args. Because the first execution of __init__() sets self.args to something different from the parameters passed to __init__() (by passing something to Exception.__init__()), upon unpickling __init__() is called with unexpected parameters.
For example, if a NameError is raised in a test, UnhandledTestFail.__init__() will callException.__init__(self, "Unhandled NameError: ...").
Upon unpickling, UnhandledTestFail.__init__() will be called with "Unhandled
NameError: ..." which is a string. It will then call Exception.__init__(self, "Unhandled str: Unhandled NameError: ...") because str is not an instance of TestFail. The resulting exception's __str__() method will return "Unhandled str: Unhandled NameError: ..." which isn't pretty.
To fix this, this patch makes the Unhandled* exceptions rely on __str__() and attributes (self.unhandled_exception and self.traceback) instead of __init__() and self.args.
--- client/bin/job.py | 6 ++-- client/common_lib/error.py | 51 ++++++++++++++++++++++++++++--------------- 2 files changed, 36 insertions(+), 21 deletions(-)
client/bin/job.py +3 -3
@@ -1182,13 +1182,13 @@ def runjob(control, drop_caches, options): sys.exit(1) except error.JobError, instance: - logging.error("JOB ERROR: " + instance.args[0]) + logging.error("JOB ERROR: " + str(instance)) if myjob: command = None if len(instance.args) > 1: command = instance.args[1] - myjob.record('ABORT', None, command, instance.args[0]) - myjob.record('END ABORT', None, None, instance.args[0]) + myjob.record('ABORT', None, command, str(instance)) + myjob.record('END ABORT', None, None, str(instance)) assert myjob._record_indent == 0 myjob.complete(1) else:
client/common_lib/error.py +33 -18
74 lines not on this page · raw message
Signature · 1 line
1.7.3.4
PATCH v3 2/11 CmdError: remove extra blank line between methods
For consistency with other exception classes, keep just a single blank line between __init__() and __str__().
--- client/common_lib/error.py | 1 - 1 files changed, 0 insertions(+), 1 deletions(-)
client/common_lib/error.py +0 -1
@@ -133,7 +133,6 @@ class CmdError(TestError): self.result_obj = result_obj self.additional_text = additional_text - def __str__(self): if self.result_obj.exit_status is None: msg = "Command <%s> failed and is not responding to signals"
Signature · 1 line
1.7.3.4
PATCH v3 3/11 Introduce exception context strings
In reply to Michael GoldishIn complex tests (KVM) an exception string is often not informative enough and the traceback and source code have to be examined in order to figure out what caused the exception. Context strings are a way for tests to provide information about what they're doing, so that when an exception is raised, this information will be embedded in the exception string. The result is a concise yet highly informative exception string, which should make it very easy to figure out where/when the exception was raised.
A typical example for a test where this may be useful is KVM's reboot test. Some exceptions can be raised either before or after the VM is rebooted (e.g. logging into the guest can fail) and whether they are raised before or after is critical to the understanding of the failure. Normally the traceback would have to be examined, but the proposed method makes it easy to know where the exception is raised without doing so. To achieve this, the reboot test should place calls to error.context() as follows:
error.context("before reboot")
<carry out pre-reboot actions>error.context("sending reboot command")
<send the reboot command>error.context("after reboot")
<carry out post-reboot actions>
If login fails in the pre-reboot section, the resulting exception string can can have something like "context: before reboot" embedded in it. (The actual embedding is done in the next patch in the series.)
Differences from previous version:
- Allow for 2 context levels per function using base_context(). This may be useful for some functions.
- Update the comment in error.py.
- Rename context_for_exception() to exception_context().
- Add set_exception_context().
- Add join_contexts().
--- client/common_lib/error.py | 139 +++++++++++++++++++++++++++++++++++++++++++- 1 files changed, 137 insertions(+), 2 deletions(-)
client/common_lib/error.py +137 -2
@@ -2,13 +2,14 @@ Internal global error types """ -import sys, traceback +import sys, traceback, threading, logging from traceback import format_exception # Add names you want to be imported by 'from errors import *' to this list. # This must be list not a tuple as we modify it to include all of our # the Exception classes we define below at the end of this file. -__all__ = ['format_error'] +__all__ = ['format_error', 'context_aware', 'context', 'get_context', + 'exception_context'] def format_error():
@@ -21,6 +22,140 @@ def format_error(): return ''.join(trace) +# Exception context information: +# ------------------------------ +# Every function can have some context string associated with it. +# The context string can be changed by calling context(str) and cleared by +# calling context() with no parameters. +# get_context() joins the current context strings of all functions in the +# provided traceback. The result is a brief description of what the test was +# doing in the provided traceback (which should be the traceback of a caught +# exception). +# +# For example: assume a() calls b() and b() calls c(). +# +# @error.context_aware +# def a(): +# error.context("hello") +# b() +# error.context("world") +# error.get_context() ----> 'world' +# +# @error.context_aware +# def b(): +# error.context("foo") +# c() +# +# @error.context_aware +# def c(): +# error.context("bar") +# error.get_context() ----> 'hello --> foo --> bar' +# +# The current context is automatically inserted into exceptions raised in +# context_aware functions, so usually test code doesn't need to call +# error.get_context(). + +ctx = threading.local() + + +def _new_context(s=""): + if not hasattr(ctx, "contexts"): + ctx.contexts = [] + ctx.contexts.append(s) + + +def _pop_context(): + ctx.contexts.pop() + + +def context(s="", log=None): + """ + Set the context for the currently executing function and optionally log it. + + @param s: A string. If not provided, the context for the current function + will be cleared. + @param log: A logging function to pass the context message to. If None, no + function will be called. + """ + ctx.contexts[-1] = s + if s and log: + log("Context: %s" % get_context()) + + +def base_context(s="", log=None): + """ + Set the base context for the currently executing function and optionally + log it. The base context is just another context level that is hidden by + default. Functions that require a single context level should not use + base_context(). + + @param s: A string. If not provided, the base context for the current + function will be cleared. + @param log: A logging function to pass the context message to. If None, no + function will be called. + """ + ctx.contexts[-2] = s + if s and log: + log("Context: %s" % get_context()) + + +def get_context(): + """Return the current context (or None if none is defined).""" + if hasattr(ctx, "contexts"): + return " --> ".join([s for s in ctx.contexts if s]) + + +def exception_context(e): + """Return the context of a given exception (or None if none is defined).""" + if hasattr(e, "_context"): + return e._context + + +def set_exception_context(e, s): + """Set the context of a given exception.""" + e._context = s + + +def join_contexts(s1, s2): + """Join two context strings.""" + if s1: + if s2: + return "%s --> %s" % (s1, s2) + else: + return s1 + else: + return s2 + + +def context_aware(fn): + """A decorator that must be applied to functions that call context().""" + def new_fn(*args, **kwargs): + _new_context() + _new_context("(%s)" % fn.__name__) + try: + try: + return fn(*args, **kwargs) + except Exception, e: + if not exception_context(e): + set_exception_context(e, get_context()) + raise + finally: + _pop_context() + _pop_context() + new_fn.__name__ = fn.__name__ + new_fn.__doc__ = fn.__doc__ + new_fn.__dict__.update(fn.__dict__) + return new_fn + + +def _context_message(e): + s = exception_context(e) + if s: + return " [context: %s]" % s + else: + return "" + + class JobContinue(SystemExit): """Allow us to bail out requesting continuance.""" pass
Signature · 1 line
1.7.3.4
PATCH v3 4/11 Embed context information in exception strings
In reply to Michael GoldishExceptions look for a ._context attribute and embed it in the string returned by __str__(). If the attribute isn't set (or if it's an empty string) nothing is embedded.
--- client/common_lib/error.py | 10 +++++++++- 1 files changed, 9 insertions(+), 1 deletions(-)
client/common_lib/error.py +9 -1
@@ -168,7 +168,8 @@ class JobComplete(SystemExit): class AutotestError(Exception): """The parent of all errors deliberatly thrown within the client code.""" - pass + def __str__(self): + return Exception.__str__(self) + _context_message(self) class JobError(AutotestError):
@@ -190,6 +191,8 @@ class UnhandledJobError(JobError): msg = "Unhandled %s: %s" msg %= (self.unhandled_exception.__class__.__name__, self.unhandled_exception) + if not isinstance(self.unhandled_exception, AutotestError): + msg += _context_message(self.unhandled_exception) msg += "\n" + self.traceback return msg
@@ -236,6 +239,8 @@ class UnhandledTestError(TestError): msg = "Unhandled %s: %s" msg %= (self.unhandled_exception.__class__.__name__, self.unhandled_exception) + if not isinstance(self.unhandled_exception, AutotestError): + msg += _context_message(self.unhandled_exception) msg += "\n" + self.traceback return msg
@@ -254,6 +259,8 @@ class UnhandledTestFail(TestFail): msg = "Unhandled %s: %s" msg %= (self.unhandled_exception.__class__.__name__, self.unhandled_exception) + if not isinstance(self.unhandled_exception, AutotestError): + msg += _context_message(self.unhandled_exception) msg += "\n" + self.traceback return msg
@@ -278,6 +285,7 @@ class CmdError(TestError): if self.additional_text: msg += ", " + self.additional_text + msg += _context_message(self) msg += '\n' + repr(self.result_obj) return msg
Signature · 1 line
1.7.3.4
PATCH v3 5/11 KVM test: Thread.join(): insert the current context into the thread's exception
In reply to Michael GoldishBecause contexts are thread specific, exceptions raised in another thread will not contain the context in which the thread was started/joined. This context should be explicitly inserted into any exception raised in the thread and re-raised in join().
--- client/tests/kvm/kvm_utils.py | 5 +++++ 1 files changed, 5 insertions(+), 0 deletions(-)
client/tests/kvm/kvm_utils.py +5 -0
@@ -1179,6 +1179,11 @@ class Thread(threading.Thread): threading.Thread.join(self, timeout) try: if self._e: + # Because the exception was raised in another thread, we need + # to explicitly insert the current context into it + s = error.exception_context(self._e[1]) + s = error.join_contexts(error.get_context(), s) + error.set_exception_context(self._e[1], s) raise self._e[0], self._e[1], self._e[2] else: return self._retval
Signature · 1 line
1.7.3.4
PATCH v3 6/11 KVM test: use error.context() in migration_with_file_transfer
In reply to Michael GoldishThis is an example of a case where context information is useful.
--- .../kvm/tests/migration_with_file_transfer.py | 12 +++++++++--- 1 files changed, 9 insertions(+), 3 deletions(-)
client/tests/kvm/tests/migration_with_file_transfer.py +9 -3
@@ -4,6 +4,7 @@ from autotest_lib.client.bin import utils as client_utils import kvm_subprocess, kvm_test_utils, kvm_utils [email protected]_aware def run_migration_with_file_transfer(test, params, env): """ KVM migration test:
@@ -47,24 +48,29 @@ def run_migration_with_file_transfer(test, params, env): finally: bg.join() - logging.info("Transferring file from host to guest") + error.context("transferring file to guest while migrating", + logging.info) bg = kvm_utils.Thread(vm.copy_files_to, (host_path, guest_path, 0, transfer_timeout)) run_and_migrate(bg) - logging.info("Transferring file back from guest to host") + error.context("transferring file back to host while migrating", + logging.info) bg = kvm_utils.Thread(vm.copy_files_from, (guest_path, host_path_returned, 0, transfer_timeout)) run_and_migrate(bg) - # Make sure the returned file is indentical to the original one + # Make sure the returned file is identical to the original one + error.context("comparing hashes", logging.info) orig_hash = client_utils.hash_file(host_path) returned_hash = client_utils.hash_file(host_path_returned) if orig_hash != returned_hash: raise error.TestFail("Returned file hash (%s) differs from " "original one (%s)" % (returned_hash, orig_hash)) + error.context() + finally: session.close() if os.path.isfile(host_path):
Signature · 1 line
1.7.3.4
PATCH v3 7/11 KVM test: use error.context() in kvm_preprocessing.py
In reply to Michael Goldish--- client/tests/kvm/kvm_preprocessing.py | 6 ++++++ 1 files changed, 6 insertions(+), 0 deletions(-)
client/tests/kvm/kvm_preprocessing.py +6 -0
@@ -187,6 +187,7 @@ def process(test, params, env, image_func, vm_func): vm_func(test, vm_params, env, vm_name) [email protected]_aware def preprocess(test, params, env): """ Preprocess all VMs and images according to the instructions in params.
@@ -196,6 +197,8 @@ def preprocess(test, params, env): @param params: A dict containing all VM and image parameters. @param env: The environment (a dict-like object). """ + error.context("preprocessing") + # Start tcpdump if it isn't already running if "address_cache" not in env: env["address_cache"] = {}
@@ -274,6 +277,7 @@ def preprocess(test, params, env): _screendump_thread.start() [email protected]_aware def postprocess(test, params, env): """ Postprocess all VMs and images according to the instructions in params.
@@ -282,6 +286,8 @@ def postprocess(test, params, env): @param params: Dict containing all VM and image parameters. @param env: The environment (a dict-like object). """ + error.context("postprocessing") + # Postprocess all VMs and images process(test, params, env, postprocess_image, postprocess_vm)
Signature · 1 line
1.7.3.4
PATCH v3 8/11 KVM test: use error.context() in VM.login() and VM.copy_files_*()
In reply to Michael Goldish--- client/tests/kvm/kvm_vm.py | 8 ++++++++ 1 files changed, 8 insertions(+), 0 deletions(-)
client/tests/kvm/kvm_vm.py +8 -0
@@ -1199,6 +1199,7 @@ class VM: return shm * 4.0 / 1024 + @error.context_aware def login(self, nic_index=0, timeout=10): """ Log into the guest via SSH/Telnet/Netcat.
@@ -1210,6 +1211,7 @@ class VM: guest. @return: A ShellSession object. """ + error.context("logging into '%s'" % self.name) username = self.params.get("username", "") password = self.params.get("password", "") prompt = self.params.get("shell_prompt", "[\#\$]")
@@ -1256,6 +1258,7 @@ class VM: return self.login(nic_index, internal_timeout) + @error.context_aware def copy_files_to(self, host_path, guest_path, nic_index=0, timeout=600): """ Transfer files to the remote host(guest).
@@ -1266,6 +1269,7 @@ class VM: @param timeout: Time (seconds) before giving up on doing the remote copy. """ + error.context("sending file(s) to '%s'" % self.name) username = self.params.get("username", "") password = self.params.get("password", "") client = self.params.get("file_transfer_client")
@@ -1278,6 +1282,7 @@ class VM: host_path, guest_path, log_filename, timeout) + @error.context_aware def copy_files_from(self, guest_path, host_path, nic_index=0, timeout=600): """ Transfer files from the guest.
@@ -1288,6 +1293,7 @@ class VM: @param timeout: Time (seconds) before giving up on doing the remote copy. """ + error.context("receiving file(s) from '%s'" % self.name) username = self.params.get("username", "") password = self.params.get("password", "") client = self.params.get("file_transfer_client")
@@ -1300,6 +1306,7 @@ class VM: guest_path, host_path, log_filename, timeout) + @error.context_aware def serial_login(self, timeout=10): """ Log into the guest via the serial console.
@@ -1309,6 +1316,7 @@ class VM: @param timeout: Time (seconds) before giving up logging into the guest. @return: ShellSession object on success and None on failure. """ + error.context("logging into '%s' via serial console" % self.name) username = self.params.get("username", "") password = self.params.get("password", "") prompt = self.params.get("shell_prompt", "[\#\$]")
Signature · 1 line
1.7.3.4
PATCH v3 9/11 KVM test: use error.context() in VM.create()
In reply to Michael Goldish--- client/tests/kvm/kvm_vm.py | 2 ++ 1 files changed, 2 insertions(+), 0 deletions(-)
client/tests/kvm/kvm_vm.py +2 -0
@@ -656,6 +656,7 @@ class VM: return qemu_cmd + @error.context_aware def create(self, name=None, params=None, root_dir=None, timeout=5.0, migration_mode=None, mac_source=None): """
@@ -683,6 +684,7 @@ class VM: requested @raise VMPAError: If no PCI assignable devices could be assigned """ + error.context("creating '%s'" % self.name) self.destroy() if name is not None:
Signature · 1 line
1.7.3.4
PATCH v3 10/11 KVM test: use error.context() in VM.migrate()
In reply to Michael Goldish--- client/tests/kvm/kvm_vm.py | 5 +++++ 1 files changed, 5 insertions(+), 0 deletions(-)
client/tests/kvm/kvm_vm.py +5 -0
@@ -1357,6 +1357,7 @@ class VM: return self.serial_login(internal_timeout) + @error.context_aware def migrate(self, timeout=3600, protocol="tcp", cancel_delay=None, offline=False, stable_check=False, clean=True, save_path="/tmp", dest_host="localhost", remote_port=None):
@@ -1381,6 +1382,8 @@ class VM: @param dest_host: Destination host (defaults to 'localhost'). @param remote_port: Port to use for remote migration. """ + error.base_context("migrating '%s'" % self.name) + def mig_finished(): o = self.monitor.info("migrate") if isinstance(o, str):
@@ -1421,11 +1424,13 @@ class VM: clone = self.clone() if local: + error.context("creating destination VM") if stable_check: # Pause the dest vm after creation extra_params = clone.params.get("extra_params", "") + " -S" clone.params["extra_params"] = extra_params clone.create(migration_mode=protocol, mac_source=self) + error.context() try: if protocol == "tcp":
Signature · 1 line
1.7.3.4
PATCH v3 11/11 KVM test: use error.context() in guest_s4
In reply to Michael Goldish--- client/tests/kvm/tests/guest_s4.py | 13 +++++++++++-- 1 files changed, 11 insertions(+), 2 deletions(-)
client/tests/kvm/tests/guest_s4.py +11 -2
@@ -3,6 +3,7 @@ from autotest_lib.client.common_lib import error import kvm_test_utils, kvm_utils [email protected]_aware def run_guest_s4(test, params, env): """ Suspend guest to disk, supports both Linux & Windows OSes.
@@ -11,13 +12,15 @@ def run_guest_s4(test, params, env): @param params: Dictionary with test parameters. @param env: Dictionary with the test environment. """ + error.base_context("before S4") vm = env.get_vm(params["main_vm"]) vm.verify_alive() timeout = int(params.get("login_timeout", 360)) session = vm.wait_for_login(timeout=timeout) - logging.info("Checking whether guest OS supports suspend to disk (S4)...") + error.context("checking whether guest OS supports S4", logging.info) session.cmd(params.get("check_s4_support_cmd")) + error.context() logging.info("Waiting until all guest OS services are fully started...") time.sleep(float(params.get("services_up_timeout", 30)))
@@ -32,15 +35,19 @@ def run_guest_s4(test, params, env): session2 = vm.wait_for_login(timeout=timeout) # Make sure the background program is running as expected + error.context("making sure background program is running") check_s4_cmd = params.get("check_s4_cmd") session2.cmd(check_s4_cmd) logging.info("Launched background command in guest: %s" % test_s4_cmd) + error.context() + error.base_context() # Suspend to disk logging.info("Starting suspend to disk now...") session2.sendline(params.get("set_s4_cmd")) # Make sure the VM goes down + error.base_context("after S4") suspend_timeout = 240 + int(params.get("smp")) * 60 if not kvm_utils.wait_for(vm.is_dead, suspend_timeout, 2, 2): raise error.TestFail("VM refuses to go down. Suspend failed.")
@@ -58,8 +65,10 @@ def run_guest_s4(test, params, env): session2 = vm.wait_for_login(timeout=relogin_timeout) # Check whether the test command is still alive - logging.info("Checking if background command is still alive...") + error.context("making sure background program is still running", + logging.info) session2.cmd(check_s4_cmd) + error.context() logging.info("VM resumed successfuly after suspend to disk") session2.cmd_output(params.get("kill_test_s4_cmd"))
Signature · 1 line
1.7.3.4