blob: 76c826853690d3a55c57cf85880eb3c46524191b [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
lmr15c44862009-09-10 03:23:45 +00004import kvm_vm, kvm_utils, kvm_subprocess, 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
lmr0294de32009-09-09 22:44:28 +000082 if start_vm and not vm.create(name, params, test.bindir, for_migration):
83 raise error.TestError("Could not start VM")
lmr6f669ce2009-05-31 19:02:42 +000084
85 scrdump_filename = os.path.join(test.debugdir, "pre_%s.ppm" % name)
86 vm.send_monitor_cmd("screendump %s" % scrdump_filename)
87
88
89def postprocess_image(test, params):
90 """
91 Postprocess a single QEMU image according to the instructions in params.
92 Currently this function just removes an image if requested.
93
94 @param test: An Autotest test object.
95 @param params: A dict containing image postprocessing parameters.
96 """
lmr6f669ce2009-05-31 19:02:42 +000097 if params.get("remove_image") == "yes":
lmr90b9fd52009-08-17 20:48:18 +000098 kvm_vm.remove_image(params, test.bindir)
lmr6f669ce2009-05-31 19:02:42 +000099
100
101def postprocess_vm(test, params, env, name):
102 """
103 Postprocess a single VM object according to the instructions in params.
104 Kill the VM if requested and get a screendump.
105
106 @param test: An Autotest test object.
107 @param params: A dict containing VM postprocessing parameters.
108 @param env: The environment (a dict-like object).
109 @param name: The name of the VM object.
110 """
111 logging.debug("Postprocessing VM '%s'..." % name)
112 vm = kvm_utils.env_get_vm(env, name)
113 if vm:
114 logging.debug("VM object found in environment")
115 else:
116 logging.debug("VM object does not exist in environment")
117 return
118
119 scrdump_filename = os.path.join(test.debugdir, "post_%s.ppm" % name)
120 vm.send_monitor_cmd("screendump %s" % scrdump_filename)
121
122 if params.get("kill_vm") == "yes":
lmradbfb1a2009-10-13 13:44:14 +0000123 kill_vm_timeout = float(params.get("kill_vm_timeout", 0))
124 if kill_vm_timeout:
125 logging.debug("'kill_vm' specified; waiting for VM to shut down "
126 "before killing it...")
127 kvm_utils.wait_for(vm.is_dead, kill_vm_timeout, 0, 1)
128 else:
lmr6f669ce2009-05-31 19:02:42 +0000129 logging.debug("'kill_vm' specified; killing VM...")
130 vm.destroy(gracefully = params.get("kill_vm_gracefully") == "yes")
131
132
lmr12b98a72010-02-09 11:13:57 +0000133def process_command(test, params, env, command, command_timeout,
lmr86d1ea52009-06-15 20:34:39 +0000134 command_noncritical):
135 """
136 Pre- or post- custom commands to be executed before/after a test is run
137
138 @param test: An Autotest test object.
139 @param params: A dict containing all VM and image parameters.
140 @param env: The environment (a dict-like object).
lmr12b98a72010-02-09 11:13:57 +0000141 @param command: Command to be run.
lmr0bc6efc2009-07-27 13:27:42 +0000142 @param command_timeout: Timeout for command execution.
143 @param command_noncritical: If True test will not fail if command fails.
lmr86d1ea52009-06-15 20:34:39 +0000144 """
lmr0bc6efc2009-07-27 13:27:42 +0000145 # Export environment vars
lmr0ce407d2010-03-23 15:46:30 +0000146 for k in params:
lmr0bc6efc2009-07-27 13:27:42 +0000147 os.putenv("KVM_TEST_%s" % k, str(params[k]))
lmrb1ef8472010-02-05 11:21:13 +0000148 # Execute commands
lmr12b98a72010-02-09 11:13:57 +0000149 try:
150 utils.system("cd %s; %s" % (test.bindir, command))
151 except error.CmdError, e:
152 logging.warn("Custom processing command '%s' failed, output is: %s",
153 command, str(e))
154 if not command_noncritical:
155 raise error.TestError("Custom processing command failed: %s" %
156 str(e))
lmr86d1ea52009-06-15 20:34:39 +0000157
158
lmr6f669ce2009-05-31 19:02:42 +0000159def process(test, params, env, image_func, vm_func):
160 """
161 Pre- or post-process VMs and images according to the instructions in params.
162 Call image_func for each image listed in params and vm_func for each VM.
163
164 @param test: An Autotest test object.
165 @param params: A dict containing all VM and image parameters.
166 @param env: The environment (a dict-like object).
167 @param image_func: A function to call for each image.
168 @param vm_func: A function to call for each VM.
169 """
170 # Get list of VMs specified for this test
171 vm_names = kvm_utils.get_sub_dict_names(params, "vms")
172 for vm_name in vm_names:
173 vm_params = kvm_utils.get_sub_dict(params, vm_name)
174 # Get list of images specified for this VM
175 image_names = kvm_utils.get_sub_dict_names(vm_params, "images")
176 for image_name in image_names:
177 image_params = kvm_utils.get_sub_dict(vm_params, image_name)
178 # Call image_func for each image
179 image_func(test, image_params)
180 # Call vm_func for each vm
181 vm_func(test, vm_params, env, vm_name)
182
183
184def preprocess(test, params, env):
185 """
186 Preprocess all VMs and images according to the instructions in params.
187 Also, collect some host information, such as the KVM version.
188
189 @param test: An Autotest test object.
190 @param params: A dict containing all VM and image parameters.
191 @param env: The environment (a dict-like object).
192 """
lmr965bcd22009-08-13 04:12:19 +0000193 # Start tcpdump if it isn't already running
lmr8a47ce32010-03-23 15:27:12 +0000194 if "address_cache" not in env:
lmr965bcd22009-08-13 04:12:19 +0000195 env["address_cache"] = {}
lmr8a47ce32010-03-23 15:27:12 +0000196 if "tcpdump" in env and not env["tcpdump"].is_alive():
lmr965bcd22009-08-13 04:12:19 +0000197 env["tcpdump"].close()
198 del env["tcpdump"]
lmrb1f76462010-05-25 23:44:03 +0000199 if "tcpdump" not in env and params.get("run_tcpdump", "yes") == "yes":
lmr965bcd22009-08-13 04:12:19 +0000200 command = "/usr/sbin/tcpdump -npvi any 'dst port 68'"
201 logging.debug("Starting tcpdump (%s)...", command)
202 env["tcpdump"] = kvm_subprocess.kvm_tail(
203 command=command,
204 output_func=_update_address_cache,
205 output_params=(env["address_cache"],))
206 if kvm_utils.wait_for(lambda: not env["tcpdump"].is_alive(),
207 0.1, 0.1, 1.0):
208 logging.warn("Could not start tcpdump")
209 logging.warn("Status: %s" % env["tcpdump"].get_status())
210 logging.warn("Output:" + kvm_utils.format_str_for_message(
211 env["tcpdump"].get_output()))
212
lmr6f669ce2009-05-31 19:02:42 +0000213 # Destroy and remove VMs that are no longer needed in the environment
214 requested_vms = kvm_utils.get_sub_dict_names(params, "vms")
lmr0ce407d2010-03-23 15:46:30 +0000215 for key in env.keys():
lmr6f669ce2009-05-31 19:02:42 +0000216 vm = env[key]
217 if not kvm_utils.is_vm(vm):
218 continue
219 if not vm.name in requested_vms:
lmr8a47ce32010-03-23 15:27:12 +0000220 logging.debug("VM '%s' found in environment but not required for "
221 "test; removing it..." % vm.name)
lmr6f669ce2009-05-31 19:02:42 +0000222 vm.destroy()
223 del env[key]
224
lmr6f669ce2009-05-31 19:02:42 +0000225 # Get the KVM kernel module version and write it as a keyval
226 logging.debug("Fetching KVM module version...")
227 if os.path.exists("/dev/kvm"):
lmr6f669ce2009-05-31 19:02:42 +0000228 try:
lmr8a47ce32010-03-23 15:27:12 +0000229 kvm_version = open("/sys/module/kvm/version").read().strip()
lmr6f669ce2009-05-31 19:02:42 +0000230 except:
lmr8a47ce32010-03-23 15:27:12 +0000231 kvm_version = os.uname()[2]
lmr6f669ce2009-05-31 19:02:42 +0000232 else:
233 kvm_version = "Unknown"
234 logging.debug("KVM module not loaded")
235 logging.debug("KVM version: %s" % kvm_version)
236 test.write_test_keyval({"kvm_version": kvm_version})
237
238 # Get the KVM userspace version and write it as a keyval
239 logging.debug("Fetching KVM userspace version...")
lmr52800ba2009-08-17 20:49:58 +0000240 qemu_path = kvm_utils.get_path(test.bindir, params.get("qemu_binary",
241 "qemu"))
lmr6f669ce2009-05-31 19:02:42 +0000242 version_line = commands.getoutput("%s -help | head -n 1" % qemu_path)
lmr8a47ce32010-03-23 15:27:12 +0000243 matches = re.findall("[Vv]ersion .*?,", version_line)
244 if matches:
245 kvm_userspace_version = " ".join(matches[0].split()[1:]).strip(",")
lmr6f669ce2009-05-31 19:02:42 +0000246 else:
247 kvm_userspace_version = "Unknown"
248 logging.debug("Could not fetch KVM userspace version")
249 logging.debug("KVM userspace version: %s" % kvm_userspace_version)
250 test.write_test_keyval({"kvm_userspace_version": kvm_userspace_version})
251
lmr8a47ce32010-03-23 15:27:12 +0000252 # Execute any pre_commands
253 if params.get("pre_command"):
254 process_command(test, params, env, params.get("pre_command"),
255 int(params.get("pre_command_timeout", "600")),
256 params.get("pre_command_noncritical") == "yes")
257
258 # Preprocess all VMs and images
259 process(test, params, env, preprocess_image, preprocess_vm)
260
lmr0e4056d2010-04-01 02:58:01 +0000261 # Start the screendump thread
262 if params.get("take_regular_screendumps") == "yes":
263 logging.debug("Starting screendump thread")
264 global _screendump_thread, _screendump_thread_termination_event
265 _screendump_thread_termination_event = threading.Event()
266 _screendump_thread = threading.Thread(target=_take_screendumps,
267 args=(test, params, env))
268 _screendump_thread.start()
269
lmr6f669ce2009-05-31 19:02:42 +0000270
271def postprocess(test, params, env):
272 """
273 Postprocess all VMs and images according to the instructions in params.
274
275 @param test: An Autotest test object.
276 @param params: Dict containing all VM and image parameters.
277 @param env: The environment (a dict-like object).
278 """
lmr0e4056d2010-04-01 02:58:01 +0000279 # Postprocess all VMs and images
lmr6f669ce2009-05-31 19:02:42 +0000280 process(test, params, env, postprocess_image, postprocess_vm)
281
lmr0e4056d2010-04-01 02:58:01 +0000282 # Terminate the screendump thread
283 global _screendump_thread, _screendump_thread_termination_event
284 if _screendump_thread:
285 logging.debug("Terminating screendump thread...")
286 _screendump_thread_termination_event.set()
287 _screendump_thread.join(10)
lmr327729b2010-06-14 17:14:00 +0000288 _screendump_thread = None
289 _screendump_thread_termination_event = None
lmr0e4056d2010-04-01 02:58:01 +0000290
lmr665975c2009-12-27 20:01:41 +0000291 # Warn about corrupt PPM files
292 for f in glob.glob(os.path.join(test.debugdir, "*.ppm")):
293 if not ppm_utils.image_verify_ppm_file(f):
294 logging.warn("Found corrupt PPM file: %s", f)
295
lmr0ee0a9c2009-07-24 19:23:29 +0000296 # Should we convert PPM files to PNG format?
297 if params.get("convert_ppm_files_to_png") == "yes":
lmr8a47ce32010-03-23 15:27:12 +0000298 logging.debug("'convert_ppm_files_to_png' specified; converting PPM "
299 "files to PNG format...")
lmre9f528e2009-08-12 15:18:10 +0000300 try:
301 for f in glob.glob(os.path.join(test.debugdir, "*.ppm")):
lmr15c44862009-09-10 03:23:45 +0000302 if ppm_utils.image_verify_ppm_file(f):
303 new_path = f.replace(".ppm", ".png")
304 image = PIL.Image.open(f)
305 image.save(new_path, format='PNG')
lmre9f528e2009-08-12 15:18:10 +0000306 except NameError:
307 pass
lmr0ee0a9c2009-07-24 19:23:29 +0000308
309 # Should we keep the PPM files?
310 if params.get("keep_ppm_files") != "yes":
lmr8a47ce32010-03-23 15:27:12 +0000311 logging.debug("'keep_ppm_files' not specified; removing all PPM files "
312 "from debug dir...")
lmre9f528e2009-08-12 15:18:10 +0000313 for f in glob.glob(os.path.join(test.debugdir, '*.ppm')):
314 os.unlink(f)
lmr6f669ce2009-05-31 19:02:42 +0000315
lmr0e4056d2010-04-01 02:58:01 +0000316 # Should we keep the screendump dirs?
317 if params.get("keep_screendumps") != "yes":
318 logging.debug("'keep_screendumps' not specified; removing screendump "
319 "dirs...")
320 for d in glob.glob(os.path.join(test.debugdir, "screendumps_*")):
321 if os.path.isdir(d) and not os.path.islink(d):
322 shutil.rmtree(d, ignore_errors=True)
lmr86d1ea52009-06-15 20:34:39 +0000323
lmr588f4972009-10-13 13:43:10 +0000324 # Kill all unresponsive VMs
325 if params.get("kill_unresponsive_vms") == "yes":
326 logging.debug("'kill_unresponsive_vms' specified; killing all VMs "
327 "that fail to respond to a remote login request...")
328 for vm in kvm_utils.env_get_all_vms(env):
329 if vm.is_alive():
330 session = vm.remote_login()
331 if session:
332 session.close()
333 else:
334 vm.destroy(gracefully=False)
335
lmra4197002009-08-13 05:00:51 +0000336 # Kill the tailing threads of all VMs
337 for vm in kvm_utils.env_get_all_vms(env):
338 vm.kill_tail_thread()
339
lmr965bcd22009-08-13 04:12:19 +0000340 # Terminate tcpdump if no VMs are alive
341 living_vms = [vm for vm in kvm_utils.env_get_all_vms(env) if vm.is_alive()]
lmr8a47ce32010-03-23 15:27:12 +0000342 if not living_vms and "tcpdump" in env:
lmr965bcd22009-08-13 04:12:19 +0000343 env["tcpdump"].close()
344 del env["tcpdump"]
345
lmr0e4056d2010-04-01 02:58:01 +0000346 # Execute any post_commands
347 if params.get("post_command"):
348 process_command(test, params, env, params.get("post_command"),
349 int(params.get("post_command_timeout", "600")),
350 params.get("post_command_noncritical") == "yes")
351
lmrfef27e12010-04-01 02:59:31 +0000352 # Abort on error?
353 if params.get("abort") == "yes":
354 exc_string = str(sys.exc_info()[1])
355 logging.info("Aborting job (%s)", exc_string)
356 for vm in kvm_utils.env_get_all_vms(env):
357 if not vm.is_dead():
358 logging.info("VM '%s' is alive.", vm.name)
359 logging.info("The monitor unix socket of '%s' is: %s",
360 vm.name, vm.monitor_file_name)
361 logging.info("The command line used to start '%s' was:\n%s",
362 vm.name, vm.make_qemu_command())
363 raise error.JobError("Abort requested (%s)" % exc_string)
364
lmr6f669ce2009-05-31 19:02:42 +0000365
366def postprocess_on_error(test, params, env):
367 """
368 Perform postprocessing operations required only if the test failed.
369
370 @param test: An Autotest test object.
371 @param params: A dict containing all VM and image parameters.
372 @param env: The environment (a dict-like object).
373 """
374 params.update(kvm_utils.get_sub_dict(params, "on_error"))
lmr965bcd22009-08-13 04:12:19 +0000375
376
377def _update_address_cache(address_cache, line):
378 if re.search("Your.IP", line, re.IGNORECASE):
379 matches = re.findall(r"\d*\.\d*\.\d*\.\d*", line)
380 if matches:
381 address_cache["last_seen"] = matches[0]
382 if re.search("Client.Ethernet.Address", line, re.IGNORECASE):
383 matches = re.findall(r"\w*:\w*:\w*:\w*:\w*:\w*", line)
384 if matches and address_cache.get("last_seen"):
385 mac_address = matches[0].lower()
386 logging.debug("(address cache) Adding cache entry: %s ---> %s",
387 mac_address, address_cache.get("last_seen"))
388 address_cache[mac_address] = address_cache.get("last_seen")
389 del address_cache["last_seen"]
lmr0e4056d2010-04-01 02:58:01 +0000390
391
392def _take_screendumps(test, params, env):
393 global _screendump_thread_termination_event
394 temp_dir = test.debugdir
395 if params.get("screendump_temp_dir"):
396 temp_dir = kvm_utils.get_path(test.bindir,
397 params.get("screendump_temp_dir"))
398 try:
399 os.makedirs(temp_dir)
400 except OSError:
401 pass
402 temp_filename = os.path.join(temp_dir, "scrdump-%s.ppm" %
403 kvm_utils.generate_random_string(6))
404 delay = float(params.get("screendump_delay", 5))
405 quality = int(params.get("screendump_quality", 30))
lmr70c1c5b2010-04-17 18:05:29 +0000406 if params.get("screendump_verbose") == 'yes':
407 screendump_verbose = True
408 else:
409 screendump_verbose = False
lmr0e4056d2010-04-01 02:58:01 +0000410
411 cache = {}
412
413 while True:
414 for vm in kvm_utils.env_get_all_vms(env):
415 if vm.is_dead():
416 continue
lmr70c1c5b2010-04-17 18:05:29 +0000417 if screendump_verbose:
418 vm.send_monitor_cmd("screendump %s" % temp_filename)
419 else:
420 vm.send_monitor_cmd("screendump %s" % temp_filename,
421 verbose=False)
lmr0e4056d2010-04-01 02:58:01 +0000422 if not os.path.exists(temp_filename):
423 logging.warn("VM '%s' failed to produce a screendump", vm.name)
424 continue
425 if not ppm_utils.image_verify_ppm_file(temp_filename):
426 logging.warn("VM '%s' produced an invalid screendump", vm.name)
427 os.unlink(temp_filename)
428 continue
429 screendump_dir = os.path.join(test.debugdir,
430 "screendumps_%s" % vm.name)
431 try:
432 os.makedirs(screendump_dir)
433 except OSError:
434 pass
435 screendump_filename = os.path.join(screendump_dir,
436 "%s_%s.jpg" % (vm.name,
437 time.strftime("%Y-%m-%d_%H-%M-%S")))
438 hash = utils.hash_file(temp_filename)
439 if hash in cache:
440 try:
441 os.link(cache[hash], screendump_filename)
442 except OSError:
443 pass
444 else:
445 try:
446 image = PIL.Image.open(temp_filename)
447 image.save(screendump_filename, format="JPEG", quality=quality)
448 cache[hash] = screendump_filename
449 except NameError:
450 pass
451 os.unlink(temp_filename)
452 if _screendump_thread_termination_event.isSet():
453 break
454 _screendump_thread_termination_event.wait(delay)