Skip to contentSkip to conversation

KVM test: kvm_preprocessing.py: minor style corrections

PATCH New Michael Goldish 1 participant 2 messages Mar 22, 2010 KVM

lore
Share & tools
lore
#0 lore raw

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

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

Changes from v1:
Change 'for key in env' back to 'for key in env.keys()', because that loop may remove entries from the env dictionary, therefore causing an exception to be raised ("RuntimeError: dictionary changed size during iteration"). Also, change 'for k in params.keys()' to 'for k in params' in process_command().

---
 client/tests/kvm/kvm_preprocessing.py |   58 +++++++++++++++-----------------
 1 files changed, 27 insertions(+), 31 deletions(-)
client/tests/kvm/kvm_preprocessing.py +27 -31
index e91d1da..a92282a 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":
@@ -139,7 +139,7 @@ def process_command(test, params, env, command, command_timeout,
     @param command_noncritical: If True test will not fail if command fails.
     """
     # Export environment vars
-    for k in params.keys():
+    for k in params:
         os.putenv("KVM_TEST_%s" % k, str(params[k]))
     # Execute commands
     try:
@@ -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(
@@ -213,30 +213,18 @@ def preprocess(test, params, env):
         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 v2 1/1 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.)

Changes from v1:
Print debug messages when starting or terminating the screendump thread.

---
 client/tests/kvm/kvm_preprocessing.py  |   87 +++++++++++++++++++++++++++++--
 client/tests/kvm/tests_base.cfg.sample |   13 ++++-
 2 files changed, 91 insertions(+), 9 deletions(-)
client/tests/kvm/kvm_preprocessing.py +81 -6
index a92282a..774de3f 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,15 @@ 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":
+        logging.debug("Starting screendump thread")
+        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 +276,16 @@ 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:
+        logging.debug("Terminating 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 +311,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 +341,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 +372,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