blob: 2e35d9f3e05026336fafcf17d3b1875aca4e209d [file] [log] [blame]
lmre9f528e2009-08-12 15:18:10 +00001import sys, os, time, commands, re, logging, signal, glob
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
14def preprocess_image(test, params):
15 """
16 Preprocess a single QEMU image according to the instructions in params.
17
18 @param test: Autotest test object.
19 @param params: A dict containing image preprocessing parameters.
20 @note: Currently this function just creates an image if requested.
21 """
lmr90b9fd52009-08-17 20:48:18 +000022 image_filename = kvm_vm.get_image_filename(params, test.bindir)
lmr6f669ce2009-05-31 19:02:42 +000023
24 create_image = False
25
26 if params.get("force_create_image") == "yes":
27 logging.debug("'force_create_image' specified; creating image...")
28 create_image = True
lmr52800ba2009-08-17 20:49:58 +000029 elif (params.get("create_image") == "yes" and not
30 os.path.exists(image_filename)):
lmr6f669ce2009-05-31 19:02:42 +000031 logging.debug("Creating image...")
32 create_image = True
33
lmr0294de32009-09-09 22:44:28 +000034 if create_image and not kvm_vm.create_image(params, test.bindir):
35 raise error.TestError("Could not create image")
lmr6f669ce2009-05-31 19:02:42 +000036
37
38def preprocess_vm(test, params, env, name):
39 """
40 Preprocess a single VM object according to the instructions in params.
41 Start the VM if requested and get a screendump.
42
43 @param test: An Autotest test object.
44 @param params: A dict containing VM preprocessing parameters.
45 @param env: The environment (a dict-like object).
46 @param name: The name of the VM object.
47 """
lmr6f669ce2009-05-31 19:02:42 +000048 logging.debug("Preprocessing VM '%s'..." % name)
49 vm = kvm_utils.env_get_vm(env, name)
50 if vm:
51 logging.debug("VM object found in environment")
52 else:
53 logging.debug("VM object does not exist; creating it")
lmr52800ba2009-08-17 20:49:58 +000054 vm = kvm_vm.VM(name, params, test.bindir, env.get("address_cache"))
lmr6f669ce2009-05-31 19:02:42 +000055 kvm_utils.env_register_vm(env, name, vm)
56
57 start_vm = False
58 for_migration = False
59
60 if params.get("start_vm_for_migration") == "yes":
61 logging.debug("'start_vm_for_migration' specified; (re)starting VM with"
62 " -incoming option...")
63 start_vm = True
64 for_migration = True
65 elif params.get("restart_vm") == "yes":
66 logging.debug("'restart_vm' specified; (re)starting VM...")
67 start_vm = True
68 elif params.get("start_vm") == "yes":
69 if not vm.is_alive():
70 logging.debug("VM is not alive; starting it...")
71 start_vm = True
72 elif vm.make_qemu_command() != vm.make_qemu_command(name, params,
lmr90b9fd52009-08-17 20:48:18 +000073 test.bindir):
lmra4967622009-07-23 01:36:32 +000074 logging.debug("VM's qemu command differs from requested one; "
lmr6f669ce2009-05-31 19:02:42 +000075 "restarting it...")
76 start_vm = True
77
lmr0294de32009-09-09 22:44:28 +000078 if start_vm and not vm.create(name, params, test.bindir, for_migration):
79 raise error.TestError("Could not start VM")
lmr6f669ce2009-05-31 19:02:42 +000080
81 scrdump_filename = os.path.join(test.debugdir, "pre_%s.ppm" % name)
82 vm.send_monitor_cmd("screendump %s" % scrdump_filename)
83
84
85def postprocess_image(test, params):
86 """
87 Postprocess a single QEMU image according to the instructions in params.
88 Currently this function just removes an image if requested.
89
90 @param test: An Autotest test object.
91 @param params: A dict containing image postprocessing parameters.
92 """
lmr6f669ce2009-05-31 19:02:42 +000093 if params.get("remove_image") == "yes":
lmr90b9fd52009-08-17 20:48:18 +000094 kvm_vm.remove_image(params, test.bindir)
lmr6f669ce2009-05-31 19:02:42 +000095
96
97def postprocess_vm(test, params, env, name):
98 """
99 Postprocess a single VM object according to the instructions in params.
100 Kill the VM if requested and get a screendump.
101
102 @param test: An Autotest test object.
103 @param params: A dict containing VM postprocessing parameters.
104 @param env: The environment (a dict-like object).
105 @param name: The name of the VM object.
106 """
107 logging.debug("Postprocessing VM '%s'..." % name)
108 vm = kvm_utils.env_get_vm(env, name)
109 if vm:
110 logging.debug("VM object found in environment")
111 else:
112 logging.debug("VM object does not exist in environment")
113 return
114
115 scrdump_filename = os.path.join(test.debugdir, "post_%s.ppm" % name)
116 vm.send_monitor_cmd("screendump %s" % scrdump_filename)
117
118 if params.get("kill_vm") == "yes":
lmradbfb1a2009-10-13 13:44:14 +0000119 kill_vm_timeout = float(params.get("kill_vm_timeout", 0))
120 if kill_vm_timeout:
121 logging.debug("'kill_vm' specified; waiting for VM to shut down "
122 "before killing it...")
123 kvm_utils.wait_for(vm.is_dead, kill_vm_timeout, 0, 1)
124 else:
lmr6f669ce2009-05-31 19:02:42 +0000125 logging.debug("'kill_vm' specified; killing VM...")
126 vm.destroy(gracefully = params.get("kill_vm_gracefully") == "yes")
127
128
lmrb1ef8472010-02-05 11:21:13 +0000129def process_command(test, params, env, commands, command_timeout,
lmr86d1ea52009-06-15 20:34:39 +0000130 command_noncritical):
131 """
132 Pre- or post- custom commands to be executed before/after a test is run
133
134 @param test: An Autotest test object.
135 @param params: A dict containing all VM and image parameters.
136 @param env: The environment (a dict-like object).
lmrb1ef8472010-02-05 11:21:13 +0000137 @param commands: List of commands to be run.
lmr0bc6efc2009-07-27 13:27:42 +0000138 @param command_timeout: Timeout for command execution.
139 @param command_noncritical: If True test will not fail if command fails.
lmr86d1ea52009-06-15 20:34:39 +0000140 """
lmr0bc6efc2009-07-27 13:27:42 +0000141 # Export environment vars
lmr86d1ea52009-06-15 20:34:39 +0000142 for k in params.keys():
lmr0bc6efc2009-07-27 13:27:42 +0000143 os.putenv("KVM_TEST_%s" % k, str(params[k]))
lmrb1ef8472010-02-05 11:21:13 +0000144 # Execute commands
145 for command in commands:
146 try:
147 utils.system("cd %s; %s" % (test.bindir, command))
148 except error.CmdError, e:
149 logging.warn("Custom processing command '%s' failed, output is: %s",
150 command, str(e))
151 if not command_noncritical:
152 raise error.TestError("Custom processing command failed: %s" %
153 str(e))
lmr86d1ea52009-06-15 20:34:39 +0000154
155
lmr6f669ce2009-05-31 19:02:42 +0000156def process(test, params, env, image_func, vm_func):
157 """
158 Pre- or post-process VMs and images according to the instructions in params.
159 Call image_func for each image listed in params and vm_func for each VM.
160
161 @param test: An Autotest test object.
162 @param params: A dict containing all VM and image parameters.
163 @param env: The environment (a dict-like object).
164 @param image_func: A function to call for each image.
165 @param vm_func: A function to call for each VM.
166 """
167 # Get list of VMs specified for this test
168 vm_names = kvm_utils.get_sub_dict_names(params, "vms")
169 for vm_name in vm_names:
170 vm_params = kvm_utils.get_sub_dict(params, vm_name)
171 # Get list of images specified for this VM
172 image_names = kvm_utils.get_sub_dict_names(vm_params, "images")
173 for image_name in image_names:
174 image_params = kvm_utils.get_sub_dict(vm_params, image_name)
175 # Call image_func for each image
176 image_func(test, image_params)
177 # Call vm_func for each vm
178 vm_func(test, vm_params, env, vm_name)
179
180
181def preprocess(test, params, env):
182 """
183 Preprocess all VMs and images according to the instructions in params.
184 Also, collect some host information, such as the KVM version.
185
186 @param test: An Autotest test object.
187 @param params: A dict containing all VM and image parameters.
188 @param env: The environment (a dict-like object).
189 """
lmr965bcd22009-08-13 04:12:19 +0000190 # Start tcpdump if it isn't already running
191 if not env.has_key("address_cache"):
192 env["address_cache"] = {}
193 if env.has_key("tcpdump") and not env["tcpdump"].is_alive():
194 env["tcpdump"].close()
195 del env["tcpdump"]
196 if not env.has_key("tcpdump"):
197 command = "/usr/sbin/tcpdump -npvi any 'dst port 68'"
198 logging.debug("Starting tcpdump (%s)...", command)
199 env["tcpdump"] = kvm_subprocess.kvm_tail(
200 command=command,
201 output_func=_update_address_cache,
202 output_params=(env["address_cache"],))
203 if kvm_utils.wait_for(lambda: not env["tcpdump"].is_alive(),
204 0.1, 0.1, 1.0):
205 logging.warn("Could not start tcpdump")
206 logging.warn("Status: %s" % env["tcpdump"].get_status())
207 logging.warn("Output:" + kvm_utils.format_str_for_message(
208 env["tcpdump"].get_output()))
209
lmr6f669ce2009-05-31 19:02:42 +0000210 # Destroy and remove VMs that are no longer needed in the environment
211 requested_vms = kvm_utils.get_sub_dict_names(params, "vms")
212 for key in env.keys():
213 vm = env[key]
214 if not kvm_utils.is_vm(vm):
215 continue
216 if not vm.name in requested_vms:
217 logging.debug("VM '%s' found in environment but not required for"
218 " test; removing it..." % vm.name)
219 vm.destroy()
220 del env[key]
221
lmr0bc6efc2009-07-27 13:27:42 +0000222 # Execute any pre_commands
lmr86d1ea52009-06-15 20:34:39 +0000223 if params.get("pre_command"):
lmrb1ef8472010-02-05 11:21:13 +0000224 pre_commands = params.get("pre_command").spit()
225 process_command(test, params, env, pre_commands,
lmr0bc6efc2009-07-27 13:27:42 +0000226 int(params.get("pre_command_timeout", "600")),
227 params.get("pre_command_noncritical") == "yes")
lmr86d1ea52009-06-15 20:34:39 +0000228
lmr6f669ce2009-05-31 19:02:42 +0000229 # Preprocess all VMs and images
230 process(test, params, env, preprocess_image, preprocess_vm)
231
232 # Get the KVM kernel module version and write it as a keyval
233 logging.debug("Fetching KVM module version...")
234 if os.path.exists("/dev/kvm"):
235 kvm_version = os.uname()[2]
236 try:
237 file = open("/sys/module/kvm/version", "r")
238 kvm_version = file.read().strip()
239 file.close()
240 except:
241 pass
242 else:
243 kvm_version = "Unknown"
244 logging.debug("KVM module not loaded")
245 logging.debug("KVM version: %s" % kvm_version)
246 test.write_test_keyval({"kvm_version": kvm_version})
247
248 # Get the KVM userspace version and write it as a keyval
249 logging.debug("Fetching KVM userspace version...")
lmr52800ba2009-08-17 20:49:58 +0000250 qemu_path = kvm_utils.get_path(test.bindir, params.get("qemu_binary",
251 "qemu"))
lmr6f669ce2009-05-31 19:02:42 +0000252 version_line = commands.getoutput("%s -help | head -n 1" % qemu_path)
253 exp = re.compile("[Vv]ersion .*?,")
254 match = exp.search(version_line)
255 if match:
256 kvm_userspace_version = " ".join(match.group().split()[1:]).strip(",")
257 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
263
264def postprocess(test, params, env):
265 """
266 Postprocess all VMs and images according to the instructions in params.
267
268 @param test: An Autotest test object.
269 @param params: Dict containing all VM and image parameters.
270 @param env: The environment (a dict-like object).
271 """
272 process(test, params, env, postprocess_image, postprocess_vm)
273
lmr665975c2009-12-27 20:01:41 +0000274 # Warn about corrupt PPM files
275 for f in glob.glob(os.path.join(test.debugdir, "*.ppm")):
276 if not ppm_utils.image_verify_ppm_file(f):
277 logging.warn("Found corrupt PPM file: %s", f)
278
lmr0ee0a9c2009-07-24 19:23:29 +0000279 # Should we convert PPM files to PNG format?
280 if params.get("convert_ppm_files_to_png") == "yes":
281 logging.debug("'convert_ppm_files_to_png' specified; converting PPM"
282 " files to PNG format...")
lmre9f528e2009-08-12 15:18:10 +0000283 try:
284 for f in glob.glob(os.path.join(test.debugdir, "*.ppm")):
lmr15c44862009-09-10 03:23:45 +0000285 if ppm_utils.image_verify_ppm_file(f):
286 new_path = f.replace(".ppm", ".png")
287 image = PIL.Image.open(f)
288 image.save(new_path, format='PNG')
lmre9f528e2009-08-12 15:18:10 +0000289 except NameError:
290 pass
lmr0ee0a9c2009-07-24 19:23:29 +0000291
292 # Should we keep the PPM files?
293 if params.get("keep_ppm_files") != "yes":
lmr6f669ce2009-05-31 19:02:42 +0000294 logging.debug("'keep_ppm_files' not specified; removing all PPM files"
lmr0ee0a9c2009-07-24 19:23:29 +0000295 " from debug dir...")
lmre9f528e2009-08-12 15:18:10 +0000296 for f in glob.glob(os.path.join(test.debugdir, '*.ppm')):
297 os.unlink(f)
lmr6f669ce2009-05-31 19:02:42 +0000298
lmr0bc6efc2009-07-27 13:27:42 +0000299 # Execute any post_commands
lmr86d1ea52009-06-15 20:34:39 +0000300 if params.get("post_command"):
lmrb1ef8472010-02-05 11:21:13 +0000301 post_commands = params.get("post_command").split()
302 process_command(test, params, env, post_commands,
lmr0bc6efc2009-07-27 13:27:42 +0000303 int(params.get("post_command_timeout", "600")),
304 params.get("post_command_noncritical") == "yes")
lmr86d1ea52009-06-15 20:34:39 +0000305
lmr588f4972009-10-13 13:43:10 +0000306 # Kill all unresponsive VMs
307 if params.get("kill_unresponsive_vms") == "yes":
308 logging.debug("'kill_unresponsive_vms' specified; killing all VMs "
309 "that fail to respond to a remote login request...")
310 for vm in kvm_utils.env_get_all_vms(env):
311 if vm.is_alive():
312 session = vm.remote_login()
313 if session:
314 session.close()
315 else:
316 vm.destroy(gracefully=False)
317
lmra4197002009-08-13 05:00:51 +0000318 # Kill the tailing threads of all VMs
319 for vm in kvm_utils.env_get_all_vms(env):
320 vm.kill_tail_thread()
321
lmr965bcd22009-08-13 04:12:19 +0000322 # Terminate tcpdump if no VMs are alive
323 living_vms = [vm for vm in kvm_utils.env_get_all_vms(env) if vm.is_alive()]
324 if not living_vms and env.has_key("tcpdump"):
325 env["tcpdump"].close()
326 del env["tcpdump"]
327
lmr6f669ce2009-05-31 19:02:42 +0000328
329def postprocess_on_error(test, params, env):
330 """
331 Perform postprocessing operations required only if the test failed.
332
333 @param test: An Autotest test object.
334 @param params: A dict containing all VM and image parameters.
335 @param env: The environment (a dict-like object).
336 """
337 params.update(kvm_utils.get_sub_dict(params, "on_error"))
lmr965bcd22009-08-13 04:12:19 +0000338
339
340def _update_address_cache(address_cache, line):
341 if re.search("Your.IP", line, re.IGNORECASE):
342 matches = re.findall(r"\d*\.\d*\.\d*\.\d*", line)
343 if matches:
344 address_cache["last_seen"] = matches[0]
345 if re.search("Client.Ethernet.Address", line, re.IGNORECASE):
346 matches = re.findall(r"\w*:\w*:\w*:\w*:\w*:\w*", line)
347 if matches and address_cache.get("last_seen"):
348 mac_address = matches[0].lower()
349 logging.debug("(address cache) Adding cache entry: %s ---> %s",
350 mac_address, address_cache.get("last_seen"))
351 address_cache[mac_address] = address_cache.get("last_seen")
352 del address_cache["last_seen"]