Skip to contentSkip to conversation

KVM test: kvm_preprocessing.py: minor style corrections

PATCH Superseded Michael Goldish 1 participant 5 messages Mar 22, 2010 KVM

v1 of 2 Superseded Latest is v2 →

lore
Share & tools
lore
#0 lore raw

PATCH 1/5 KVM test: kvm_preprocessing.py: minor style corrections

Also, fetch the KVM version before setting up the VMs.

---
 client/tests/kvm/kvm_preprocessing.py |   58 +++++++++++++++-----------------
 1 files changed, 27 insertions(+), 31 deletions(-)
client/tests/kvm/kvm_preprocessing.py +27 -31
index e91d1da..e3a5501 100644
@@ -58,8 +58,8 @@ def preprocess_vm(test, params, env, name):
     for_migration = False
 
     if params.get("start_vm_for_migration") == "yes":
-        logging.debug("'start_vm_for_migration' specified; (re)starting VM with"
-                      " -incoming option...")
+        logging.debug("'start_vm_for_migration' specified; (re)starting VM "
+                      "with -incoming option...")
         start_vm = True
         for_migration = True
     elif params.get("restart_vm") == "yes":
@@ -187,12 +187,12 @@ def preprocess(test, params, env):
     @param env: The environment (a dict-like object).
     """
     # Start tcpdump if it isn't already running
-    if not env.has_key("address_cache"):
+    if "address_cache" not in env:
         env["address_cache"] = {}
-    if env.has_key("tcpdump") and not env["tcpdump"].is_alive():
+    if "tcpdump" in env and not env["tcpdump"].is_alive():
         env["tcpdump"].close()
         del env["tcpdump"]
-    if not env.has_key("tcpdump"):
+    if "tcpdump" not in env:
         command = "/usr/sbin/tcpdump -npvi any 'dst port 68'"
         logging.debug("Starting tcpdump (%s)...", command)
         env["tcpdump"] = kvm_subprocess.kvm_tail(
@@ -208,35 +208,23 @@ def preprocess(test, params, env):
 
     # Destroy and remove VMs that are no longer needed in the environment
     requested_vms = kvm_utils.get_sub_dict_names(params, "vms")
-    for key in env.keys():
+    for key in env:
         vm = env[key]
         if not kvm_utils.is_vm(vm):
             continue
         if not vm.name in requested_vms:
-            logging.debug("VM '%s' found in environment but not required for"
-                          " test; removing it..." % vm.name)
+            logging.debug("VM '%s' found in environment but not required for "
+                          "test; removing it..." % vm.name)
             vm.destroy()
             del env[key]
 
-    # Execute any pre_commands
-    if params.get("pre_command"):
-        process_command(test, params, env, params.get("pre_command"),
-                        int(params.get("pre_command_timeout", "600")),
-                        params.get("pre_command_noncritical") == "yes")
-
-    # Preprocess all VMs and images
-    process(test, params, env, preprocess_image, preprocess_vm)
-
     # Get the KVM kernel module version and write it as a keyval
     logging.debug("Fetching KVM module version...")
     if os.path.exists("/dev/kvm"):
-        kvm_version = os.uname()[2]
         try:
-            file = open("/sys/module/kvm/version", "r")
-            kvm_version = file.read().strip()
-            file.close()
+            kvm_version = open("/sys/module/kvm/version").read().strip()
         except:
-            pass
+            kvm_version = os.uname()[2]
     else:
         kvm_version = "Unknown"
         logging.debug("KVM module not loaded")
@@ -248,16 +236,24 @@ def preprocess(test, params, env):
     qemu_path = kvm_utils.get_path(test.bindir, params.get("qemu_binary",
                                                            "qemu"))
     version_line = commands.getoutput("%s -help | head -n 1" % qemu_path)
-    exp = re.compile("[Vv]ersion .*?,")
-    match = exp.search(version_line)
-    if match:
-        kvm_userspace_version = " ".join(match.group().split()[1:]).strip(",")
+    matches = re.findall("[Vv]ersion .*?,", version_line)
+    if matches:
+        kvm_userspace_version = " ".join(matches[0].split()[1:]).strip(",")
     else:
         kvm_userspace_version = "Unknown"
         logging.debug("Could not fetch KVM userspace version")
     logging.debug("KVM userspace version: %s" % kvm_userspace_version)
     test.write_test_keyval({"kvm_userspace_version": kvm_userspace_version})
 
+    # Execute any pre_commands
+    if params.get("pre_command"):
+        process_command(test, params, env, params.get("pre_command"),
+                        int(params.get("pre_command_timeout", "600")),
+                        params.get("pre_command_noncritical") == "yes")
+
+    # Preprocess all VMs and images
+    process(test, params, env, preprocess_image, preprocess_vm)
+
 
 def postprocess(test, params, env):
     """
@@ -276,8 +272,8 @@ def postprocess(test, params, env):
 
     # Should we convert PPM files to PNG format?
     if params.get("convert_ppm_files_to_png") == "yes":
-        logging.debug("'convert_ppm_files_to_png' specified; converting PPM"
-                      " files to PNG format...")
+        logging.debug("'convert_ppm_files_to_png' specified; converting PPM "
+                      "files to PNG format...")
         try:
             for f in glob.glob(os.path.join(test.debugdir, "*.ppm")):
                 if ppm_utils.image_verify_ppm_file(f):
@@ -289,8 +285,8 @@ def postprocess(test, params, env):
 
     # Should we keep the PPM files?
     if params.get("keep_ppm_files") != "yes":
-        logging.debug("'keep_ppm_files' not specified; removing all PPM files"
-                      " from debug dir...")
+        logging.debug("'keep_ppm_files' not specified; removing all PPM files "
+                      "from debug dir...")
         for f in glob.glob(os.path.join(test.debugdir, '*.ppm')):
             os.unlink(f)
 
@@ -318,7 +314,7 @@ def postprocess(test, params, env):
 
     # Terminate tcpdump if no VMs are alive
     living_vms = [vm for vm in kvm_utils.env_get_all_vms(env) if vm.is_alive()]
-    if not living_vms and env.has_key("tcpdump"):
+    if not living_vms and "tcpdump" in env:
         env["tcpdump"].close()
         del env["tcpdump"]
 
Signature · 1 line
1.5.4.1
#1 lore raw

PATCH 2/5 KVM test: kvm.py: make sure all dump_env() calls are inside 'finally' blocks

---
 client/tests/kvm/kvm.py |   29 +++++++++++++++++++----------
 1 files changed, 19 insertions(+), 10 deletions(-)
client/tests/kvm/kvm.py +19 -10
index 9b8a10c..c6e146d 100644
@@ -21,6 +21,7 @@ class kvm(test.test):
             (Online doc - Getting started with KVM testing)
     """
     version = 1
+
     def run_once(self, params):
         # Report the parameters we've received and write them as keyvals
         logging.debug("Test parameters:")
@@ -33,7 +34,7 @@ class kvm(test.test):
         # Open the environment file
         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", str(env))
 
         try:
             try:
@@ -50,22 +51,30 @@ class kvm(test.test):
                 f.close()
 
                 # Preprocess
-                kvm_preprocessing.preprocess(self, params, env)
-                kvm_utils.dump_env(env, env_filename)
+                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)
-                run_func(self, params, env)
-                kvm_utils.dump_env(env, env_filename)
+                try:
+                    run_func(self, params, env)
+                finally:
+                    kvm_utils.dump_env(env, env_filename)
 
             except Exception, e:
                 logging.error("Test failed: %s", e)
                 logging.debug("Postprocessing on error...")
-                kvm_preprocessing.postprocess_on_error(self, params, env)
-                kvm_utils.dump_env(env, env_filename)
+                try:
+                    kvm_preprocessing.postprocess_on_error(self, params, env)
+                finally:
+                    kvm_utils.dump_env(env, env_filename)
                 raise
 
         finally:
             # Postprocess
-            kvm_preprocessing.postprocess(self, params, env)
-            logging.debug("Contents of environment: %s", str(env))
-            kvm_utils.dump_env(env, env_filename)
+            try:
+                kvm_preprocessing.postprocess(self, params, env)
+            finally:
+                kvm_utils.dump_env(env, env_filename)
+                logging.debug("Contents of environment: %s", str(env))
Signature · 1 line
1.5.4.1
#2 lore raw

PATCH 3/5 KVM test: kvm_utils.load_env(): do not fail if env file is corrupted

- Include the unpickling code in the 'try' block, so that an exception raised during unpickling will not fail the test.
- Change the default env (returned by load_env() when the file is missing or corrupt) to {}.

---
 client/tests/kvm/kvm_utils.py |   10 ++++++----
 1 files changed, 6 insertions(+), 4 deletions(-)
client/tests/kvm/kvm_utils.py +6 -4
index d386456..cc39b5d 100644
@@ -22,7 +22,7 @@ def dump_env(obj, filename):
     file.close()
 
 
-def load_env(filename, default=None):
+def load_env(filename, default={}):
     """
     Load KVM test environment from an environment file.
 
@@ -30,11 +30,13 @@ def load_env(filename, default=None):
     """
     try:
         file = open(filename, "r")
+        obj = cPickle.load(file)
+        file.close()
+        return obj
+    # Almost any exception can be raised during unpickling, so let's catch
+    # them all
     except:
         return default
-    obj = cPickle.load(file)
-    file.close()
-    return obj
 
 
 def get_sub_dict(dict, name):
Signature · 1 line
1.5.4.1
#3 lore raw

PATCH 4/5 KVM test: make kvm_stat usage optional

Relying on the test tag is not cool. Use a dedicated parameter instead. By default, all tests except build tests will use kvm_stat.

---
 client/tests/kvm/kvm_utils.py          |    8 ++++----
 client/tests/kvm/tests_base.cfg.sample |    3 +++
 2 files changed, 7 insertions(+), 4 deletions(-)
client/tests/kvm/kvm_utils.py +4 -4
index cc39b5d..5834539 100644
@@ -845,8 +845,8 @@ def run_tests(test_list, job):
     @return: True, if all tests ran passed, False if any of them failed.
     """
     status_dict = {}
-
     failed = False
+
     for dict in test_list:
         if dict.get("skip") == "yes":
             continue
@@ -863,12 +863,12 @@ def run_tests(test_list, job):
             test_tag = dict.get("shortname")
             # Setting up kvm_stat profiling during test execution.
             # We don't need kvm_stat profiling on the build tests.
-            if "build" in test_tag:
+            if dict.get("run_kvm_stat") == "yes":
+                profile = True
+            else:
                 # None because it's the default value on the base_test class
                 # and the value None is specifically checked there.
                 profile = None
-            else:
-                profile = True
 
             if profile:
                 job.profilers.add('kvm_stat')
client/tests/kvm/tests_base.cfg.sample +3 -0
index 9963a44..b13aec4 100644
@@ -40,6 +40,9 @@ nic_mode = user
 nic_script = scripts/qemu-ifup
 address_index = 0
 
+# Misc
+run_kvm_stat = yes
+
 
 # Tests
 variants:
Signature · 1 line
1.5.4.1
#4 lore raw

PATCH 5/5 KVM test: take frequent screendumps during all tests

Screendumps are taken regularly and converted to JPEG format. They are stored in .../debug/screendumps_<VMname>/. Requires python-imaging.

- Enabled by 'take_regular_screendumps = yes' (naming suggestions welcome).
- Delay between screendumps is controlled by 'screendump_delay' (default 5).
- Compression quality is controlled by 'screendump_quality' (default 30).
- It's probably a good idea to dump them to /dev/shm before converting them in order to minimize disk use. This can be enabled by 'screendump_temp_dir = /dev/shm' (commented out by default because I'm not sure /dev/shm is available on all machines.)
- Screendumps are removed unless 'keep_screendumps'['_on_error'] is 'yes'. The recommended setting when submitting jobs from autoserv is 'keep_screendumps_on_error = yes', which means screendumps are kept only if the test fails. Keeping all screendumps may use up all of the server's storage space.

This patch sets reasonable defaults in tests_base.cfg.sample.

(It also makes sure post_command is executed last in the postprocessing procedure -- otherwise post_command failure can prevent other postprocessing steps (like removing the screendump dirs) from taking place.)

---
 client/tests/kvm/kvm_preprocessing.py  |   85 +++++++++++++++++++++++++++++--
 client/tests/kvm/tests_base.cfg.sample |   13 ++++-
 2 files changed, 89 insertions(+), 9 deletions(-)
client/tests/kvm/kvm_preprocessing.py +79 -6
index e3a5501..0e4ce87 100644
@@ -1,4 +1,4 @@
-import sys, os, time, commands, re, logging, signal, glob
+import sys, os, time, commands, re, logging, signal, glob, threading, shutil
 from autotest_lib.client.bin import test, utils
 from autotest_lib.client.common_lib import error
 import kvm_vm, kvm_utils, kvm_subprocess, ppm_utils
@@ -11,6 +11,10 @@ except ImportError:
                     'distro.')
 
 
+_screendump_thread = None
+_screendump_thread_termination_event = None
+
+
 def preprocess_image(test, params):
     """
     Preprocess a single QEMU image according to the instructions in params.
@@ -254,6 +258,14 @@ def preprocess(test, params, env):
     # Preprocess all VMs and images
     process(test, params, env, preprocess_image, preprocess_vm)
 
+    # Start the screendump thread
+    if params.get("take_regular_screendumps") == "yes":
+        global _screendump_thread, _screendump_thread_termination_event
+        _screendump_thread_termination_event = threading.Event()
+        _screendump_thread = threading.Thread(target=_take_screendumps,
+                                              args=(test, params, env))
+        _screendump_thread.start()
+
 
 def postprocess(test, params, env):
     """
@@ -263,8 +275,15 @@ def postprocess(test, params, env):
     @param params: Dict containing all VM and image parameters.
     @param env: The environment (a dict-like object).
     """
+    # Postprocess all VMs and images
     process(test, params, env, postprocess_image, postprocess_vm)
 
+    # Terminate the screendump thread
+    global _screendump_thread, _screendump_thread_termination_event
+    if _screendump_thread:
+        _screendump_thread_termination_event.set()
+        _screendump_thread.join(10)
+
     # Warn about corrupt PPM files
     for f in glob.glob(os.path.join(test.debugdir, "*.ppm")):
         if not ppm_utils.image_verify_ppm_file(f):
@@ -290,11 +309,13 @@ def postprocess(test, params, env):
         for f in glob.glob(os.path.join(test.debugdir, '*.ppm')):
             os.unlink(f)
 
-    # Execute any post_commands
-    if params.get("post_command"):
-        process_command(test, params, env, params.get("post_command"),
-                        int(params.get("post_command_timeout", "600")),
-                        params.get("post_command_noncritical") == "yes")
+    # Should we keep the screendump dirs?
+    if params.get("keep_screendumps") != "yes":
+        logging.debug("'keep_screendumps' not specified; removing screendump "
+                      "dirs...")
+        for d in glob.glob(os.path.join(test.debugdir, "screendumps_*")):
+            if os.path.isdir(d) and not os.path.islink(d):
+                shutil.rmtree(d, ignore_errors=True)
 
     # Kill all unresponsive VMs
     if params.get("kill_unresponsive_vms") == "yes":
@@ -318,6 +339,12 @@ def postprocess(test, params, env):
         env["tcpdump"].close()
         del env["tcpdump"]
 
+    # Execute any post_commands
+    if params.get("post_command"):
+        process_command(test, params, env, params.get("post_command"),
+                        int(params.get("post_command_timeout", "600")),
+                        params.get("post_command_noncritical") == "yes")
+
 
 def postprocess_on_error(test, params, env):
     """
@@ -343,3 +370,49 @@ def _update_address_cache(address_cache, line):
                           mac_address, address_cache.get("last_seen"))
             address_cache[mac_address] = address_cache.get("last_seen")
             del address_cache["last_seen"]
+
+
+def _take_screendumps(test, params, env):
+    global _screendump_thread_termination_event
+    temp_dir = test.debugdir
+    if params.get("screendump_temp_dir"):
+        temp_dir = kvm_utils.get_path(test.bindir,
+                                      params.get("screendump_temp_dir"))
+        try:
+            os.makedirs(temp_dir)
+        except OSError:
+            pass
+    temp_filename = os.path.join(temp_dir, "scrdump-%s.ppm" %
+                                 kvm_utils.generate_random_string(6))
+    delay = float(params.get("screendump_delay", 5))
+    quality = int(params.get("screendump_quality", 30))
+
+    while True:
+        for vm in kvm_utils.env_get_all_vms(env):
+            if vm.is_dead():
+                continue
+            vm.send_monitor_cmd("screendump %s" % temp_filename)
+            if not os.path.exists(temp_filename):
+                logging.warn("VM '%s' failed to produce a screendump", vm.name)
+                continue
+            if not ppm_utils.image_verify_ppm_file(temp_filename):
+                logging.warn("VM '%s' produced an invalid screendump", vm.name)
+                os.unlink(temp_filename)
+                continue
+            screendump_dir = os.path.join(test.debugdir,
+                                          "screendumps_%s" % vm.name)
+            try:
+                os.makedirs(screendump_dir)
+            except OSError:
+                pass
+            screendump_filename = os.path.join(screendump_dir,
+                    "%s-%s.jpg" % (vm.name, time.strftime("%Y%m%d-%H%M%S")))
+            try:
+                image = PIL.Image.open(temp_filename)
+                image.save(screendump_filename, format="JPEG", quality=quality)
+            except NameError:
+                pass
+            os.unlink(temp_filename)
+        if _screendump_thread_termination_event.isSet():
+            break
+        _screendump_thread_termination_event.wait(delay)
client/tests/kvm/tests_base.cfg.sample +10 -3
index b13aec4..1fd5b39 100644
@@ -10,13 +10,20 @@ main_vm = vm1
 
 # Some preprocessor/postprocessor params
 start_vm = yes
-convert_ppm_files_to_png_on_error = yes
-#keep_ppm_files = yes
-#keep_ppm_files_on_error = yes
 kill_vm = no
 kill_vm_gracefully = yes
 kill_unresponsive_vms = yes
 
+# Screendump specific stuff
+convert_ppm_files_to_png_on_error = yes
+#keep_ppm_files = yes
+#keep_ppm_files_on_error = yes
+take_regular_screendumps = yes
+keep_screendumps_on_error = yes
+screendump_delay = 5
+screendump_quality = 30
+#screendump_temp_dir = /dev/shm
+
 # Some default VM params
 qemu_binary = qemu
 qemu_img_binary = qemu-img
Signature · 1 line
1.5.4.1