blob: 8fa74cfe057a78b4ea74ab1561c2edb25a72dc0c [file] [log] [blame]
lmre9f528e2009-08-12 15:18:10 +00001import sys, os, time, commands, re, logging, signal, glob
lmr6f669ce2009-05-31 19:02:42 +00002from autotest_lib.client.bin import test
3from autotest_lib.client.common_lib import error
lmra4967622009-07-23 01:36:32 +00004import kvm_vm, kvm_utils, kvm_subprocess
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
34 if create_image:
lmr52800ba2009-08-17 20:49:58 +000035 if not kvm_vm.create_image(params, test.bindir):
lmr6f669ce2009-05-31 19:02:42 +000036 message = "Could not create image"
37 logging.error(message)
38 raise error.TestError(message)
39
40
41def preprocess_vm(test, params, env, name):
42 """
43 Preprocess a single VM object according to the instructions in params.
44 Start the VM if requested and get a screendump.
45
46 @param test: An Autotest test object.
47 @param params: A dict containing VM preprocessing parameters.
48 @param env: The environment (a dict-like object).
49 @param name: The name of the VM object.
50 """
lmr6f669ce2009-05-31 19:02:42 +000051 logging.debug("Preprocessing VM '%s'..." % name)
52 vm = kvm_utils.env_get_vm(env, name)
53 if vm:
54 logging.debug("VM object found in environment")
55 else:
56 logging.debug("VM object does not exist; creating it")
lmr52800ba2009-08-17 20:49:58 +000057 vm = kvm_vm.VM(name, params, test.bindir, env.get("address_cache"))
lmr6f669ce2009-05-31 19:02:42 +000058 kvm_utils.env_register_vm(env, name, vm)
59
60 start_vm = False
61 for_migration = False
62
63 if params.get("start_vm_for_migration") == "yes":
64 logging.debug("'start_vm_for_migration' specified; (re)starting VM with"
65 " -incoming option...")
66 start_vm = True
67 for_migration = True
68 elif params.get("restart_vm") == "yes":
69 logging.debug("'restart_vm' specified; (re)starting VM...")
70 start_vm = True
71 elif params.get("start_vm") == "yes":
72 if not vm.is_alive():
73 logging.debug("VM is not alive; starting it...")
74 start_vm = True
75 elif vm.make_qemu_command() != vm.make_qemu_command(name, params,
lmr90b9fd52009-08-17 20:48:18 +000076 test.bindir):
lmra4967622009-07-23 01:36:32 +000077 logging.debug("VM's qemu command differs from requested one; "
lmr6f669ce2009-05-31 19:02:42 +000078 "restarting it...")
79 start_vm = True
80
81 if start_vm:
lmr52800ba2009-08-17 20:49:58 +000082 if not vm.create(name, params, test.bindir, for_migration):
lmr6f669ce2009-05-31 19:02:42 +000083 message = "Could not start VM"
84 logging.error(message)
85 raise error.TestError(message)
86
87 scrdump_filename = os.path.join(test.debugdir, "pre_%s.ppm" % name)
88 vm.send_monitor_cmd("screendump %s" % scrdump_filename)
89
90
91def postprocess_image(test, params):
92 """
93 Postprocess a single QEMU image according to the instructions in params.
94 Currently this function just removes an image if requested.
95
96 @param test: An Autotest test object.
97 @param params: A dict containing image postprocessing parameters.
98 """
lmr6f669ce2009-05-31 19:02:42 +000099 if params.get("remove_image") == "yes":
lmr90b9fd52009-08-17 20:48:18 +0000100 kvm_vm.remove_image(params, test.bindir)
lmr6f669ce2009-05-31 19:02:42 +0000101
102
103def postprocess_vm(test, params, env, name):
104 """
105 Postprocess a single VM object according to the instructions in params.
106 Kill the VM if requested and get a screendump.
107
108 @param test: An Autotest test object.
109 @param params: A dict containing VM postprocessing parameters.
110 @param env: The environment (a dict-like object).
111 @param name: The name of the VM object.
112 """
113 logging.debug("Postprocessing VM '%s'..." % name)
114 vm = kvm_utils.env_get_vm(env, name)
115 if vm:
116 logging.debug("VM object found in environment")
117 else:
118 logging.debug("VM object does not exist in environment")
119 return
120
121 scrdump_filename = os.path.join(test.debugdir, "post_%s.ppm" % name)
122 vm.send_monitor_cmd("screendump %s" % scrdump_filename)
123
124 if params.get("kill_vm") == "yes":
125 if not kvm_utils.wait_for(vm.is_dead,
126 float(params.get("kill_vm_timeout", 0)), 0.0, 1.0,
127 "Waiting for VM to kill itself..."):
128 logging.debug("'kill_vm' specified; killing VM...")
129 vm.destroy(gracefully = params.get("kill_vm_gracefully") == "yes")
130
131
lmr86d1ea52009-06-15 20:34:39 +0000132def process_command(test, params, env, command, command_timeout,
133 command_noncritical):
134 """
135 Pre- or post- custom commands to be executed before/after a test is run
136
137 @param test: An Autotest test object.
138 @param params: A dict containing all VM and image parameters.
139 @param env: The environment (a dict-like object).
lmr0bc6efc2009-07-27 13:27:42 +0000140 @param command: Command to be run.
141 @param command_timeout: Timeout for command execution.
142 @param command_noncritical: If True test will not fail if command fails.
lmr86d1ea52009-06-15 20:34:39 +0000143 """
lmr0bc6efc2009-07-27 13:27:42 +0000144 # Export environment vars
lmr86d1ea52009-06-15 20:34:39 +0000145 for k in params.keys():
lmr0bc6efc2009-07-27 13:27:42 +0000146 os.putenv("KVM_TEST_%s" % k, str(params[k]))
147 # Execute command
lmr86d1ea52009-06-15 20:34:39 +0000148 logging.info("Executing command '%s'..." % command)
lmra4967622009-07-23 01:36:32 +0000149 (status, output) = kvm_subprocess.run_fg("cd %s; %s" % (test.bindir,
lmr86d1ea52009-06-15 20:34:39 +0000150 command),
lmra4967622009-07-23 01:36:32 +0000151 logging.debug, "(command) ",
lmr0bc6efc2009-07-27 13:27:42 +0000152 timeout=command_timeout)
lmr86d1ea52009-06-15 20:34:39 +0000153 if status != 0:
lmr0bc6efc2009-07-27 13:27:42 +0000154 logging.warn("Custom processing command failed: '%s'" % command)
155 if not command_noncritical:
lmr86d1ea52009-06-15 20:34:39 +0000156 raise error.TestError("Custom processing command failed")
157
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
194 if not env.has_key("address_cache"):
195 env["address_cache"] = {}
196 if env.has_key("tcpdump") and not env["tcpdump"].is_alive():
197 env["tcpdump"].close()
198 del env["tcpdump"]
199 if not env.has_key("tcpdump"):
200 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")
215 for key in env.keys():
216 vm = env[key]
217 if not kvm_utils.is_vm(vm):
218 continue
219 if not vm.name in requested_vms:
220 logging.debug("VM '%s' found in environment but not required for"
221 " test; removing it..." % vm.name)
222 vm.destroy()
223 del env[key]
224
lmr0bc6efc2009-07-27 13:27:42 +0000225 # Execute any pre_commands
lmr86d1ea52009-06-15 20:34:39 +0000226 if params.get("pre_command"):
227 process_command(test, params, env, params.get("pre_command"),
lmr0bc6efc2009-07-27 13:27:42 +0000228 int(params.get("pre_command_timeout", "600")),
229 params.get("pre_command_noncritical") == "yes")
lmr86d1ea52009-06-15 20:34:39 +0000230
lmr6f669ce2009-05-31 19:02:42 +0000231 # Preprocess all VMs and images
232 process(test, params, env, preprocess_image, preprocess_vm)
233
234 # Get the KVM kernel module version and write it as a keyval
235 logging.debug("Fetching KVM module version...")
236 if os.path.exists("/dev/kvm"):
237 kvm_version = os.uname()[2]
238 try:
239 file = open("/sys/module/kvm/version", "r")
240 kvm_version = file.read().strip()
241 file.close()
242 except:
243 pass
244 else:
245 kvm_version = "Unknown"
246 logging.debug("KVM module not loaded")
247 logging.debug("KVM version: %s" % kvm_version)
248 test.write_test_keyval({"kvm_version": kvm_version})
249
250 # Get the KVM userspace version and write it as a keyval
251 logging.debug("Fetching KVM userspace version...")
lmr52800ba2009-08-17 20:49:58 +0000252 qemu_path = kvm_utils.get_path(test.bindir, params.get("qemu_binary",
253 "qemu"))
lmr6f669ce2009-05-31 19:02:42 +0000254 version_line = commands.getoutput("%s -help | head -n 1" % qemu_path)
255 exp = re.compile("[Vv]ersion .*?,")
256 match = exp.search(version_line)
257 if match:
258 kvm_userspace_version = " ".join(match.group().split()[1:]).strip(",")
259 else:
260 kvm_userspace_version = "Unknown"
261 logging.debug("Could not fetch KVM userspace version")
262 logging.debug("KVM userspace version: %s" % kvm_userspace_version)
263 test.write_test_keyval({"kvm_userspace_version": kvm_userspace_version})
264
265
266def postprocess(test, params, env):
267 """
268 Postprocess all VMs and images according to the instructions in params.
269
270 @param test: An Autotest test object.
271 @param params: Dict containing all VM and image parameters.
272 @param env: The environment (a dict-like object).
273 """
274 process(test, params, env, postprocess_image, postprocess_vm)
275
lmr0ee0a9c2009-07-24 19:23:29 +0000276 # Should we convert PPM files to PNG format?
277 if params.get("convert_ppm_files_to_png") == "yes":
278 logging.debug("'convert_ppm_files_to_png' specified; converting PPM"
279 " files to PNG format...")
lmre9f528e2009-08-12 15:18:10 +0000280 try:
281 for f in glob.glob(os.path.join(test.debugdir, "*.ppm")):
lmr8e7929b2009-08-13 04:26:53 +0000282 new_path = f.replace(".ppm", ".png")
lmre9f528e2009-08-12 15:18:10 +0000283 image = PIL.Image.open(f)
lmr8e7929b2009-08-13 04:26:53 +0000284 image.save(new_path, format = 'PNG')
lmre9f528e2009-08-12 15:18:10 +0000285 except NameError:
286 pass
lmr0ee0a9c2009-07-24 19:23:29 +0000287
288 # Should we keep the PPM files?
289 if params.get("keep_ppm_files") != "yes":
lmr6f669ce2009-05-31 19:02:42 +0000290 logging.debug("'keep_ppm_files' not specified; removing all PPM files"
lmr0ee0a9c2009-07-24 19:23:29 +0000291 " from debug dir...")
lmre9f528e2009-08-12 15:18:10 +0000292 for f in glob.glob(os.path.join(test.debugdir, '*.ppm')):
293 os.unlink(f)
lmr6f669ce2009-05-31 19:02:42 +0000294
lmr0bc6efc2009-07-27 13:27:42 +0000295 # Execute any post_commands
lmr86d1ea52009-06-15 20:34:39 +0000296 if params.get("post_command"):
297 process_command(test, params, env, params.get("post_command"),
lmr0bc6efc2009-07-27 13:27:42 +0000298 int(params.get("post_command_timeout", "600")),
299 params.get("post_command_noncritical") == "yes")
lmr86d1ea52009-06-15 20:34:39 +0000300
lmra4197002009-08-13 05:00:51 +0000301 # Kill the tailing threads of all VMs
302 for vm in kvm_utils.env_get_all_vms(env):
303 vm.kill_tail_thread()
304
lmr965bcd22009-08-13 04:12:19 +0000305 # Terminate tcpdump if no VMs are alive
306 living_vms = [vm for vm in kvm_utils.env_get_all_vms(env) if vm.is_alive()]
307 if not living_vms and env.has_key("tcpdump"):
308 env["tcpdump"].close()
309 del env["tcpdump"]
310
lmr6f669ce2009-05-31 19:02:42 +0000311
312def postprocess_on_error(test, params, env):
313 """
314 Perform postprocessing operations required only if the test failed.
315
316 @param test: An Autotest test object.
317 @param params: A dict containing all VM and image parameters.
318 @param env: The environment (a dict-like object).
319 """
320 params.update(kvm_utils.get_sub_dict(params, "on_error"))
lmr965bcd22009-08-13 04:12:19 +0000321
322
323def _update_address_cache(address_cache, line):
324 if re.search("Your.IP", line, re.IGNORECASE):
325 matches = re.findall(r"\d*\.\d*\.\d*\.\d*", line)
326 if matches:
327 address_cache["last_seen"] = matches[0]
328 if re.search("Client.Ethernet.Address", line, re.IGNORECASE):
329 matches = re.findall(r"\w*:\w*:\w*:\w*:\w*:\w*", line)
330 if matches and address_cache.get("last_seen"):
331 mac_address = matches[0].lower()
332 logging.debug("(address cache) Adding cache entry: %s ---> %s",
333 mac_address, address_cache.get("last_seen"))
334 address_cache[mac_address] = address_cache.get("last_seen")
335 del address_cache["last_seen"]