blob: e3de0b358a6c51d654118be333b42d678833ff71 [file] [log] [blame]
lmr0e4056d2010-04-01 02:58:01 +00001import sys, os, time, commands, re, logging, signal, glob, threading, shutil
lmr47a853b2010-02-04 13:56:48 +00002from autotest_lib.client.bin import test, utils
lmr6f669ce2009-05-31 19:02:42 +00003from autotest_lib.client.common_lib import error
lmr9e964a02010-06-18 03:46:21 +00004import kvm_vm, kvm_utils, kvm_subprocess, kvm_monitor, ppm_utils
lmre9f528e2009-08-12 15:18:10 +00005try:
6 import PIL.Image
7except ImportError:
8 logging.warning('No python imaging library installed. PPM image '
9 'conversion to JPEG disabled. In order to enable it, '
10 'please install python-imaging or the equivalent for your '
11 'distro.')
lmr6f669ce2009-05-31 19:02:42 +000012
13
lmr0e4056d2010-04-01 02:58:01 +000014_screendump_thread = None
15_screendump_thread_termination_event = None
16
17
lmr6f669ce2009-05-31 19:02:42 +000018def preprocess_image(test, params):
19 """
20 Preprocess a single QEMU image according to the instructions in params.
21
22 @param test: Autotest test object.
23 @param params: A dict containing image preprocessing parameters.
24 @note: Currently this function just creates an image if requested.
25 """
lmr90b9fd52009-08-17 20:48:18 +000026 image_filename = kvm_vm.get_image_filename(params, test.bindir)
lmr6f669ce2009-05-31 19:02:42 +000027
28 create_image = False
29
30 if params.get("force_create_image") == "yes":
31 logging.debug("'force_create_image' specified; creating image...")
32 create_image = True
lmr52800ba2009-08-17 20:49:58 +000033 elif (params.get("create_image") == "yes" and not
34 os.path.exists(image_filename)):
lmr6f669ce2009-05-31 19:02:42 +000035 logging.debug("Creating image...")
36 create_image = True
37
lmr0294de32009-09-09 22:44:28 +000038 if create_image and not kvm_vm.create_image(params, test.bindir):
39 raise error.TestError("Could not create image")
lmr6f669ce2009-05-31 19:02:42 +000040
41
42def preprocess_vm(test, params, env, name):
43 """
44 Preprocess a single VM object according to the instructions in params.
45 Start the VM if requested and get a screendump.
46
47 @param test: An Autotest test object.
48 @param params: A dict containing VM preprocessing parameters.
49 @param env: The environment (a dict-like object).
50 @param name: The name of the VM object.
51 """
lmr6f669ce2009-05-31 19:02:42 +000052 logging.debug("Preprocessing VM '%s'..." % name)
53 vm = kvm_utils.env_get_vm(env, name)
54 if vm:
55 logging.debug("VM object found in environment")
56 else:
57 logging.debug("VM object does not exist; creating it")
lmr52800ba2009-08-17 20:49:58 +000058 vm = kvm_vm.VM(name, params, test.bindir, env.get("address_cache"))
lmr6f669ce2009-05-31 19:02:42 +000059 kvm_utils.env_register_vm(env, name, vm)
60
61 start_vm = False
62 for_migration = False
63
64 if params.get("start_vm_for_migration") == "yes":
lmr8a47ce32010-03-23 15:27:12 +000065 logging.debug("'start_vm_for_migration' specified; (re)starting VM "
66 "with -incoming option...")
lmr6f669ce2009-05-31 19:02:42 +000067 start_vm = True
68 for_migration = True
69 elif params.get("restart_vm") == "yes":
70 logging.debug("'restart_vm' specified; (re)starting VM...")
71 start_vm = True
72 elif params.get("start_vm") == "yes":
73 if not vm.is_alive():
74 logging.debug("VM is not alive; starting it...")
75 start_vm = True
76 elif vm.make_qemu_command() != vm.make_qemu_command(name, params,
lmr90b9fd52009-08-17 20:48:18 +000077 test.bindir):
lmra4967622009-07-23 01:36:32 +000078 logging.debug("VM's qemu command differs from requested one; "
lmr6f669ce2009-05-31 19:02:42 +000079 "restarting it...")
80 start_vm = True
81
lmre9a9cf32010-06-18 12:15:25 +000082 if start_vm:
83 # Start the VM (or restart it if it's already up)
84 if not vm.create(name, params, test.bindir, for_migration):
85 raise error.TestError("Could not start VM")
86 else:
87 # Don't start the VM, just update its params
88 vm.params = params
lmr6f669ce2009-05-31 19:02:42 +000089
90 scrdump_filename = os.path.join(test.debugdir, "pre_%s.ppm" % name)
lmr9e964a02010-06-18 03:46:21 +000091 try:
92 if vm.monitor:
93 vm.monitor.screendump(scrdump_filename)
94 except kvm_monitor.MonitorError, e:
95 logging.warn(e)
lmr6f669ce2009-05-31 19:02:42 +000096
97
98def postprocess_image(test, params):
99 """
100 Postprocess a single QEMU image according to the instructions in params.
101 Currently this function just removes an image if requested.
102
103 @param test: An Autotest test object.
104 @param params: A dict containing image postprocessing parameters.
105 """
lmr6f669ce2009-05-31 19:02:42 +0000106 if params.get("remove_image") == "yes":
lmr90b9fd52009-08-17 20:48:18 +0000107 kvm_vm.remove_image(params, test.bindir)
lmr6f669ce2009-05-31 19:02:42 +0000108
109
110def postprocess_vm(test, params, env, name):
111 """
112 Postprocess a single VM object according to the instructions in params.
113 Kill the VM if requested and get a screendump.
114
115 @param test: An Autotest test object.
116 @param params: A dict containing VM postprocessing parameters.
117 @param env: The environment (a dict-like object).
118 @param name: The name of the VM object.
119 """
120 logging.debug("Postprocessing VM '%s'..." % name)
121 vm = kvm_utils.env_get_vm(env, name)
122 if vm:
123 logging.debug("VM object found in environment")
124 else:
125 logging.debug("VM object does not exist in environment")
126 return
127
128 scrdump_filename = os.path.join(test.debugdir, "post_%s.ppm" % name)
lmr9e964a02010-06-18 03:46:21 +0000129 try:
130 if vm.monitor:
131 vm.monitor.screendump(scrdump_filename)
132 except kvm_monitor.MonitorError, e:
133 logging.warn(e)
lmr6f669ce2009-05-31 19:02:42 +0000134
135 if params.get("kill_vm") == "yes":
lmradbfb1a2009-10-13 13:44:14 +0000136 kill_vm_timeout = float(params.get("kill_vm_timeout", 0))
137 if kill_vm_timeout:
138 logging.debug("'kill_vm' specified; waiting for VM to shut down "
139 "before killing it...")
140 kvm_utils.wait_for(vm.is_dead, kill_vm_timeout, 0, 1)
141 else:
lmr6f669ce2009-05-31 19:02:42 +0000142 logging.debug("'kill_vm' specified; killing VM...")
143 vm.destroy(gracefully = params.get("kill_vm_gracefully") == "yes")
144
145
lmr12b98a72010-02-09 11:13:57 +0000146def process_command(test, params, env, command, command_timeout,
lmr86d1ea52009-06-15 20:34:39 +0000147 command_noncritical):
148 """
149 Pre- or post- custom commands to be executed before/after a test is run
150
151 @param test: An Autotest test object.
152 @param params: A dict containing all VM and image parameters.
153 @param env: The environment (a dict-like object).
lmr12b98a72010-02-09 11:13:57 +0000154 @param command: Command to be run.
lmr0bc6efc2009-07-27 13:27:42 +0000155 @param command_timeout: Timeout for command execution.
156 @param command_noncritical: If True test will not fail if command fails.
lmr86d1ea52009-06-15 20:34:39 +0000157 """
lmr0bc6efc2009-07-27 13:27:42 +0000158 # Export environment vars
lmr0ce407d2010-03-23 15:46:30 +0000159 for k in params:
lmr0bc6efc2009-07-27 13:27:42 +0000160 os.putenv("KVM_TEST_%s" % k, str(params[k]))
lmrb1ef8472010-02-05 11:21:13 +0000161 # Execute commands
lmr12b98a72010-02-09 11:13:57 +0000162 try:
163 utils.system("cd %s; %s" % (test.bindir, command))
164 except error.CmdError, e:
lmr10845532010-06-18 12:54:46 +0000165 if command_noncritical:
166 logging.warn(e)
167 else:
168 raise
lmr86d1ea52009-06-15 20:34:39 +0000169
lmr6f669ce2009-05-31 19:02:42 +0000170def process(test, params, env, image_func, vm_func):
171 """
172 Pre- or post-process VMs and images according to the instructions in params.
173 Call image_func for each image listed in params and vm_func for each VM.
174
175 @param test: An Autotest test object.
176 @param params: A dict containing all VM and image parameters.
177 @param env: The environment (a dict-like object).
178 @param image_func: A function to call for each image.
179 @param vm_func: A function to call for each VM.
180 """
181 # Get list of VMs specified for this test
182 vm_names = kvm_utils.get_sub_dict_names(params, "vms")
183 for vm_name in vm_names:
184 vm_params = kvm_utils.get_sub_dict(params, vm_name)
185 # Get list of images specified for this VM
186 image_names = kvm_utils.get_sub_dict_names(vm_params, "images")
187 for image_name in image_names:
188 image_params = kvm_utils.get_sub_dict(vm_params, image_name)
189 # Call image_func for each image
190 image_func(test, image_params)
191 # Call vm_func for each vm
192 vm_func(test, vm_params, env, vm_name)
193
194
195def preprocess(test, params, env):
196 """
197 Preprocess all VMs and images according to the instructions in params.
198 Also, collect some host information, such as the KVM version.
199
200 @param test: An Autotest test object.
201 @param params: A dict containing all VM and image parameters.
202 @param env: The environment (a dict-like object).
203 """
lmr965bcd22009-08-13 04:12:19 +0000204 # Start tcpdump if it isn't already running
lmr8a47ce32010-03-23 15:27:12 +0000205 if "address_cache" not in env:
lmr965bcd22009-08-13 04:12:19 +0000206 env["address_cache"] = {}
lmr8a47ce32010-03-23 15:27:12 +0000207 if "tcpdump" in env and not env["tcpdump"].is_alive():
lmr965bcd22009-08-13 04:12:19 +0000208 env["tcpdump"].close()
209 del env["tcpdump"]
lmrb1f76462010-05-25 23:44:03 +0000210 if "tcpdump" not in env and params.get("run_tcpdump", "yes") == "yes":
lmr3eb39c72010-07-08 23:34:05 +0000211 cmd = "%s -npvi any 'dst port 68'" % kvm_utils.find_command("tcpdump")
212 logging.debug("Starting tcpdump (%s)...", cmd)
lmr965bcd22009-08-13 04:12:19 +0000213 env["tcpdump"] = kvm_subprocess.kvm_tail(
lmr3eb39c72010-07-08 23:34:05 +0000214 command=cmd,
lmr965bcd22009-08-13 04:12:19 +0000215 output_func=_update_address_cache,
216 output_params=(env["address_cache"],))
217 if kvm_utils.wait_for(lambda: not env["tcpdump"].is_alive(),
218 0.1, 0.1, 1.0):
219 logging.warn("Could not start tcpdump")
220 logging.warn("Status: %s" % env["tcpdump"].get_status())
221 logging.warn("Output:" + kvm_utils.format_str_for_message(
222 env["tcpdump"].get_output()))
223
lmr6f669ce2009-05-31 19:02:42 +0000224 # Destroy and remove VMs that are no longer needed in the environment
225 requested_vms = kvm_utils.get_sub_dict_names(params, "vms")
lmr0ce407d2010-03-23 15:46:30 +0000226 for key in env.keys():
lmr6f669ce2009-05-31 19:02:42 +0000227 vm = env[key]
228 if not kvm_utils.is_vm(vm):
229 continue
230 if not vm.name in requested_vms:
lmr8a47ce32010-03-23 15:27:12 +0000231 logging.debug("VM '%s' found in environment but not required for "
232 "test; removing it..." % vm.name)
lmr6f669ce2009-05-31 19:02:42 +0000233 vm.destroy()
234 del env[key]
235
lmr6f669ce2009-05-31 19:02:42 +0000236 # Get the KVM kernel module version and write it as a keyval
237 logging.debug("Fetching KVM module version...")
238 if os.path.exists("/dev/kvm"):
lmr6f669ce2009-05-31 19:02:42 +0000239 try:
lmr8a47ce32010-03-23 15:27:12 +0000240 kvm_version = open("/sys/module/kvm/version").read().strip()
lmr6f669ce2009-05-31 19:02:42 +0000241 except:
lmr8a47ce32010-03-23 15:27:12 +0000242 kvm_version = os.uname()[2]
lmr6f669ce2009-05-31 19:02:42 +0000243 else:
244 kvm_version = "Unknown"
245 logging.debug("KVM module not loaded")
246 logging.debug("KVM version: %s" % kvm_version)
247 test.write_test_keyval({"kvm_version": kvm_version})
248
249 # Get the KVM userspace version and write it as a keyval
250 logging.debug("Fetching KVM userspace version...")
lmr52800ba2009-08-17 20:49:58 +0000251 qemu_path = kvm_utils.get_path(test.bindir, params.get("qemu_binary",
252 "qemu"))
lmr6f669ce2009-05-31 19:02:42 +0000253 version_line = commands.getoutput("%s -help | head -n 1" % qemu_path)
lmr8a47ce32010-03-23 15:27:12 +0000254 matches = re.findall("[Vv]ersion .*?,", version_line)
255 if matches:
256 kvm_userspace_version = " ".join(matches[0].split()[1:]).strip(",")
lmr6f669ce2009-05-31 19:02:42 +0000257 else:
258 kvm_userspace_version = "Unknown"
259 logging.debug("Could not fetch KVM userspace version")
260 logging.debug("KVM userspace version: %s" % kvm_userspace_version)
261 test.write_test_keyval({"kvm_userspace_version": kvm_userspace_version})
262
lmr8a47ce32010-03-23 15:27:12 +0000263 # Execute any pre_commands
264 if params.get("pre_command"):
265 process_command(test, params, env, params.get("pre_command"),
266 int(params.get("pre_command_timeout", "600")),
267 params.get("pre_command_noncritical") == "yes")
268
269 # Preprocess all VMs and images
270 process(test, params, env, preprocess_image, preprocess_vm)
271
lmr0e4056d2010-04-01 02:58:01 +0000272 # Start the screendump thread
273 if params.get("take_regular_screendumps") == "yes":
274 logging.debug("Starting screendump thread")
275 global _screendump_thread, _screendump_thread_termination_event
276 _screendump_thread_termination_event = threading.Event()
277 _screendump_thread = threading.Thread(target=_take_screendumps,
278 args=(test, params, env))
279 _screendump_thread.start()
280
lmr6f669ce2009-05-31 19:02:42 +0000281
282def postprocess(test, params, env):
283 """
284 Postprocess all VMs and images according to the instructions in params.
285
286 @param test: An Autotest test object.
287 @param params: Dict containing all VM and image parameters.
288 @param env: The environment (a dict-like object).
289 """
lmr0e4056d2010-04-01 02:58:01 +0000290 # Postprocess all VMs and images
lmr6f669ce2009-05-31 19:02:42 +0000291 process(test, params, env, postprocess_image, postprocess_vm)
292
lmr0e4056d2010-04-01 02:58:01 +0000293 # Terminate the screendump thread
294 global _screendump_thread, _screendump_thread_termination_event
295 if _screendump_thread:
296 logging.debug("Terminating screendump thread...")
297 _screendump_thread_termination_event.set()
298 _screendump_thread.join(10)
lmr327729b2010-06-14 17:14:00 +0000299 _screendump_thread = None
300 _screendump_thread_termination_event = None
lmr0e4056d2010-04-01 02:58:01 +0000301
lmr665975c2009-12-27 20:01:41 +0000302 # Warn about corrupt PPM files
303 for f in glob.glob(os.path.join(test.debugdir, "*.ppm")):
304 if not ppm_utils.image_verify_ppm_file(f):
305 logging.warn("Found corrupt PPM file: %s", f)
306
lmr0ee0a9c2009-07-24 19:23:29 +0000307 # Should we convert PPM files to PNG format?
308 if params.get("convert_ppm_files_to_png") == "yes":
lmr8a47ce32010-03-23 15:27:12 +0000309 logging.debug("'convert_ppm_files_to_png' specified; converting PPM "
310 "files to PNG format...")
lmre9f528e2009-08-12 15:18:10 +0000311 try:
312 for f in glob.glob(os.path.join(test.debugdir, "*.ppm")):
lmr15c44862009-09-10 03:23:45 +0000313 if ppm_utils.image_verify_ppm_file(f):
314 new_path = f.replace(".ppm", ".png")
315 image = PIL.Image.open(f)
316 image.save(new_path, format='PNG')
lmre9f528e2009-08-12 15:18:10 +0000317 except NameError:
318 pass
lmr0ee0a9c2009-07-24 19:23:29 +0000319
320 # Should we keep the PPM files?
321 if params.get("keep_ppm_files") != "yes":
lmr8a47ce32010-03-23 15:27:12 +0000322 logging.debug("'keep_ppm_files' not specified; removing all PPM files "
323 "from debug dir...")
lmre9f528e2009-08-12 15:18:10 +0000324 for f in glob.glob(os.path.join(test.debugdir, '*.ppm')):
325 os.unlink(f)
lmr6f669ce2009-05-31 19:02:42 +0000326
lmr0e4056d2010-04-01 02:58:01 +0000327 # Should we keep the screendump dirs?
328 if params.get("keep_screendumps") != "yes":
329 logging.debug("'keep_screendumps' not specified; removing screendump "
330 "dirs...")
331 for d in glob.glob(os.path.join(test.debugdir, "screendumps_*")):
332 if os.path.isdir(d) and not os.path.islink(d):
333 shutil.rmtree(d, ignore_errors=True)
lmr86d1ea52009-06-15 20:34:39 +0000334
lmr588f4972009-10-13 13:43:10 +0000335 # Kill all unresponsive VMs
336 if params.get("kill_unresponsive_vms") == "yes":
337 logging.debug("'kill_unresponsive_vms' specified; killing all VMs "
338 "that fail to respond to a remote login request...")
339 for vm in kvm_utils.env_get_all_vms(env):
340 if vm.is_alive():
341 session = vm.remote_login()
342 if session:
343 session.close()
344 else:
345 vm.destroy(gracefully=False)
346
lmree4338e2010-07-08 23:40:10 +0000347 # Kill all kvm_subprocess tail threads
348 kvm_subprocess.kill_tail_threads()
lmra4197002009-08-13 05:00:51 +0000349
lmr965bcd22009-08-13 04:12:19 +0000350 # Terminate tcpdump if no VMs are alive
351 living_vms = [vm for vm in kvm_utils.env_get_all_vms(env) if vm.is_alive()]
lmr8a47ce32010-03-23 15:27:12 +0000352 if not living_vms and "tcpdump" in env:
lmr965bcd22009-08-13 04:12:19 +0000353 env["tcpdump"].close()
354 del env["tcpdump"]
355
lmr0e4056d2010-04-01 02:58:01 +0000356 # Execute any post_commands
357 if params.get("post_command"):
358 process_command(test, params, env, params.get("post_command"),
359 int(params.get("post_command_timeout", "600")),
360 params.get("post_command_noncritical") == "yes")
361
lmr6f669ce2009-05-31 19:02:42 +0000362
363def postprocess_on_error(test, params, env):
364 """
365 Perform postprocessing operations required only if the test failed.
366
367 @param test: An Autotest test object.
368 @param params: A dict containing all VM and image parameters.
369 @param env: The environment (a dict-like object).
370 """
371 params.update(kvm_utils.get_sub_dict(params, "on_error"))
lmr965bcd22009-08-13 04:12:19 +0000372
373
374def _update_address_cache(address_cache, line):
375 if re.search("Your.IP", line, re.IGNORECASE):
376 matches = re.findall(r"\d*\.\d*\.\d*\.\d*", line)
377 if matches:
378 address_cache["last_seen"] = matches[0]
379 if re.search("Client.Ethernet.Address", line, re.IGNORECASE):
380 matches = re.findall(r"\w*:\w*:\w*:\w*:\w*:\w*", line)
381 if matches and address_cache.get("last_seen"):
382 mac_address = matches[0].lower()
383 logging.debug("(address cache) Adding cache entry: %s ---> %s",
384 mac_address, address_cache.get("last_seen"))
385 address_cache[mac_address] = address_cache.get("last_seen")
386 del address_cache["last_seen"]
lmr0e4056d2010-04-01 02:58:01 +0000387
388
389def _take_screendumps(test, params, env):
390 global _screendump_thread_termination_event
391 temp_dir = test.debugdir
392 if params.get("screendump_temp_dir"):
393 temp_dir = kvm_utils.get_path(test.bindir,
394 params.get("screendump_temp_dir"))
395 try:
396 os.makedirs(temp_dir)
397 except OSError:
398 pass
399 temp_filename = os.path.join(temp_dir, "scrdump-%s.ppm" %
400 kvm_utils.generate_random_string(6))
401 delay = float(params.get("screendump_delay", 5))
402 quality = int(params.get("screendump_quality", 30))
403
404 cache = {}
405
406 while True:
407 for vm in kvm_utils.env_get_all_vms(env):
lmr7fa9fe72010-06-22 01:46:47 +0000408 if not vm.is_alive():
lmr0e4056d2010-04-01 02:58:01 +0000409 continue
lmr9e964a02010-06-18 03:46:21 +0000410 try:
411 vm.monitor.screendump(temp_filename)
412 except kvm_monitor.MonitorError, e:
413 logging.warn(e)
414 continue
lmr0e4056d2010-04-01 02:58:01 +0000415 if not os.path.exists(temp_filename):
416 logging.warn("VM '%s' failed to produce a screendump", vm.name)
417 continue
418 if not ppm_utils.image_verify_ppm_file(temp_filename):
419 logging.warn("VM '%s' produced an invalid screendump", vm.name)
420 os.unlink(temp_filename)
421 continue
422 screendump_dir = os.path.join(test.debugdir,
423 "screendumps_%s" % vm.name)
424 try:
425 os.makedirs(screendump_dir)
426 except OSError:
427 pass
428 screendump_filename = os.path.join(screendump_dir,
429 "%s_%s.jpg" % (vm.name,
430 time.strftime("%Y-%m-%d_%H-%M-%S")))
431 hash = utils.hash_file(temp_filename)
432 if hash in cache:
433 try:
434 os.link(cache[hash], screendump_filename)
435 except OSError:
436 pass
437 else:
438 try:
439 image = PIL.Image.open(temp_filename)
440 image.save(screendump_filename, format="JPEG", quality=quality)
441 cache[hash] = screendump_filename
442 except NameError:
443 pass
444 os.unlink(temp_filename)
445 if _screendump_thread_termination_event.isSet():
446 break
447 _screendump_thread_termination_event.wait(delay)