blob: 2d32e8661fab54882235bd2903ddf537acdfb1ba [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 """
22 qemu_img_path = os.path.join(test.bindir, "qemu-img")
23 image_dir = os.path.join(test.bindir, "images")
24 image_filename = kvm_vm.get_image_filename(params, image_dir)
25
26 create_image = False
27
28 if params.get("force_create_image") == "yes":
29 logging.debug("'force_create_image' specified; creating image...")
30 create_image = True
31 elif params.get("create_image") == "yes" and not \
32 os.path.exists(image_filename):
33 logging.debug("Creating image...")
34 create_image = True
35
36 if create_image:
37 if not kvm_vm.create_image(params, qemu_img_path, image_dir):
38 message = "Could not create image"
39 logging.error(message)
40 raise error.TestError(message)
41
42
43def preprocess_vm(test, params, env, name):
44 """
45 Preprocess a single VM object according to the instructions in params.
46 Start the VM if requested and get a screendump.
47
48 @param test: An Autotest test object.
49 @param params: A dict containing VM preprocessing parameters.
50 @param env: The environment (a dict-like object).
51 @param name: The name of the VM object.
52 """
53 qemu_path = os.path.join(test.bindir, "qemu")
54 image_dir = os.path.join(test.bindir, "images")
55 iso_dir = os.path.join(test.bindir, "isos")
lmrf4696342009-08-13 04:06:33 +000056 script_dir = os.path.join(test.bindir, "scripts")
lmr6f669ce2009-05-31 19:02:42 +000057
58 logging.debug("Preprocessing VM '%s'..." % name)
59 vm = kvm_utils.env_get_vm(env, name)
60 if vm:
61 logging.debug("VM object found in environment")
62 else:
63 logging.debug("VM object does not exist; creating it")
lmree90dd92009-08-13 04:13:39 +000064 vm = kvm_vm.VM(name, params, qemu_path, image_dir, iso_dir, script_dir,
65 env.get("address_cache"))
lmr6f669ce2009-05-31 19:02:42 +000066 kvm_utils.env_register_vm(env, name, vm)
67
68 start_vm = False
69 for_migration = False
70
71 if params.get("start_vm_for_migration") == "yes":
72 logging.debug("'start_vm_for_migration' specified; (re)starting VM with"
73 " -incoming option...")
74 start_vm = True
75 for_migration = True
76 elif params.get("restart_vm") == "yes":
77 logging.debug("'restart_vm' specified; (re)starting VM...")
78 start_vm = True
79 elif params.get("start_vm") == "yes":
80 if not vm.is_alive():
81 logging.debug("VM is not alive; starting it...")
82 start_vm = True
83 elif vm.make_qemu_command() != vm.make_qemu_command(name, params,
84 qemu_path,
85 image_dir,
lmrf4696342009-08-13 04:06:33 +000086 iso_dir,
87 script_dir):
lmra4967622009-07-23 01:36:32 +000088 logging.debug("VM's qemu command differs from requested one; "
lmr6f669ce2009-05-31 19:02:42 +000089 "restarting it...")
90 start_vm = True
91
92 if start_vm:
lmr6f669ce2009-05-31 19:02:42 +000093 if not vm.create(name, params, qemu_path, image_dir, iso_dir,
lmrf4696342009-08-13 04:06:33 +000094 script_dir, for_migration):
lmr6f669ce2009-05-31 19:02:42 +000095 message = "Could not start VM"
96 logging.error(message)
97 raise error.TestError(message)
98
99 scrdump_filename = os.path.join(test.debugdir, "pre_%s.ppm" % name)
100 vm.send_monitor_cmd("screendump %s" % scrdump_filename)
101
102
103def postprocess_image(test, params):
104 """
105 Postprocess a single QEMU image according to the instructions in params.
106 Currently this function just removes an image if requested.
107
108 @param test: An Autotest test object.
109 @param params: A dict containing image postprocessing parameters.
110 """
111 image_dir = os.path.join(test.bindir, "images")
112
113 if params.get("remove_image") == "yes":
114 kvm_vm.remove_image(params, image_dir)
115
116
117def postprocess_vm(test, params, env, name):
118 """
119 Postprocess a single VM object according to the instructions in params.
120 Kill the VM if requested and get a screendump.
121
122 @param test: An Autotest test object.
123 @param params: A dict containing VM postprocessing parameters.
124 @param env: The environment (a dict-like object).
125 @param name: The name of the VM object.
126 """
127 logging.debug("Postprocessing VM '%s'..." % name)
128 vm = kvm_utils.env_get_vm(env, name)
129 if vm:
130 logging.debug("VM object found in environment")
131 else:
132 logging.debug("VM object does not exist in environment")
133 return
134
135 scrdump_filename = os.path.join(test.debugdir, "post_%s.ppm" % name)
136 vm.send_monitor_cmd("screendump %s" % scrdump_filename)
137
138 if params.get("kill_vm") == "yes":
139 if not kvm_utils.wait_for(vm.is_dead,
140 float(params.get("kill_vm_timeout", 0)), 0.0, 1.0,
141 "Waiting for VM to kill itself..."):
142 logging.debug("'kill_vm' specified; killing VM...")
143 vm.destroy(gracefully = params.get("kill_vm_gracefully") == "yes")
144
145
lmr86d1ea52009-06-15 20:34:39 +0000146def process_command(test, params, env, command, command_timeout,
147 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).
lmr0bc6efc2009-07-27 13:27:42 +0000154 @param command: Command to be run.
155 @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
lmr86d1ea52009-06-15 20:34:39 +0000159 for k in params.keys():
lmr0bc6efc2009-07-27 13:27:42 +0000160 os.putenv("KVM_TEST_%s" % k, str(params[k]))
161 # Execute command
lmr86d1ea52009-06-15 20:34:39 +0000162 logging.info("Executing command '%s'..." % command)
lmra4967622009-07-23 01:36:32 +0000163 (status, output) = kvm_subprocess.run_fg("cd %s; %s" % (test.bindir,
lmr86d1ea52009-06-15 20:34:39 +0000164 command),
lmra4967622009-07-23 01:36:32 +0000165 logging.debug, "(command) ",
lmr0bc6efc2009-07-27 13:27:42 +0000166 timeout=command_timeout)
lmr86d1ea52009-06-15 20:34:39 +0000167 if status != 0:
lmr0bc6efc2009-07-27 13:27:42 +0000168 logging.warn("Custom processing command failed: '%s'" % command)
169 if not command_noncritical:
lmr86d1ea52009-06-15 20:34:39 +0000170 raise error.TestError("Custom processing command failed")
171
172
lmr6f669ce2009-05-31 19:02:42 +0000173def process(test, params, env, image_func, vm_func):
174 """
175 Pre- or post-process VMs and images according to the instructions in params.
176 Call image_func for each image listed in params and vm_func for each VM.
177
178 @param test: An Autotest test object.
179 @param params: A dict containing all VM and image parameters.
180 @param env: The environment (a dict-like object).
181 @param image_func: A function to call for each image.
182 @param vm_func: A function to call for each VM.
183 """
184 # Get list of VMs specified for this test
185 vm_names = kvm_utils.get_sub_dict_names(params, "vms")
186 for vm_name in vm_names:
187 vm_params = kvm_utils.get_sub_dict(params, vm_name)
188 # Get list of images specified for this VM
189 image_names = kvm_utils.get_sub_dict_names(vm_params, "images")
190 for image_name in image_names:
191 image_params = kvm_utils.get_sub_dict(vm_params, image_name)
192 # Call image_func for each image
193 image_func(test, image_params)
194 # Call vm_func for each vm
195 vm_func(test, vm_params, env, vm_name)
196
197
198def preprocess(test, params, env):
199 """
200 Preprocess all VMs and images according to the instructions in params.
201 Also, collect some host information, such as the KVM version.
202
203 @param test: An Autotest test object.
204 @param params: A dict containing all VM and image parameters.
205 @param env: The environment (a dict-like object).
206 """
lmr965bcd22009-08-13 04:12:19 +0000207 # Start tcpdump if it isn't already running
208 if not env.has_key("address_cache"):
209 env["address_cache"] = {}
210 if env.has_key("tcpdump") and not env["tcpdump"].is_alive():
211 env["tcpdump"].close()
212 del env["tcpdump"]
213 if not env.has_key("tcpdump"):
214 command = "/usr/sbin/tcpdump -npvi any 'dst port 68'"
215 logging.debug("Starting tcpdump (%s)...", command)
216 env["tcpdump"] = kvm_subprocess.kvm_tail(
217 command=command,
218 output_func=_update_address_cache,
219 output_params=(env["address_cache"],))
220 if kvm_utils.wait_for(lambda: not env["tcpdump"].is_alive(),
221 0.1, 0.1, 1.0):
222 logging.warn("Could not start tcpdump")
223 logging.warn("Status: %s" % env["tcpdump"].get_status())
224 logging.warn("Output:" + kvm_utils.format_str_for_message(
225 env["tcpdump"].get_output()))
226
lmr6f669ce2009-05-31 19:02:42 +0000227 # Destroy and remove VMs that are no longer needed in the environment
228 requested_vms = kvm_utils.get_sub_dict_names(params, "vms")
229 for key in env.keys():
230 vm = env[key]
231 if not kvm_utils.is_vm(vm):
232 continue
233 if not vm.name in requested_vms:
234 logging.debug("VM '%s' found in environment but not required for"
235 " test; removing it..." % vm.name)
236 vm.destroy()
237 del env[key]
238
lmr0bc6efc2009-07-27 13:27:42 +0000239 # Execute any pre_commands
lmr86d1ea52009-06-15 20:34:39 +0000240 if params.get("pre_command"):
241 process_command(test, params, env, params.get("pre_command"),
lmr0bc6efc2009-07-27 13:27:42 +0000242 int(params.get("pre_command_timeout", "600")),
243 params.get("pre_command_noncritical") == "yes")
lmr86d1ea52009-06-15 20:34:39 +0000244
lmr6f669ce2009-05-31 19:02:42 +0000245 # Preprocess all VMs and images
246 process(test, params, env, preprocess_image, preprocess_vm)
247
248 # Get the KVM kernel module version and write it as a keyval
249 logging.debug("Fetching KVM module version...")
250 if os.path.exists("/dev/kvm"):
251 kvm_version = os.uname()[2]
252 try:
253 file = open("/sys/module/kvm/version", "r")
254 kvm_version = file.read().strip()
255 file.close()
256 except:
257 pass
258 else:
259 kvm_version = "Unknown"
260 logging.debug("KVM module not loaded")
261 logging.debug("KVM version: %s" % kvm_version)
262 test.write_test_keyval({"kvm_version": kvm_version})
263
264 # Get the KVM userspace version and write it as a keyval
265 logging.debug("Fetching KVM userspace version...")
266 qemu_path = os.path.join(test.bindir, "qemu")
267 version_line = commands.getoutput("%s -help | head -n 1" % qemu_path)
268 exp = re.compile("[Vv]ersion .*?,")
269 match = exp.search(version_line)
270 if match:
271 kvm_userspace_version = " ".join(match.group().split()[1:]).strip(",")
272 else:
273 kvm_userspace_version = "Unknown"
274 logging.debug("Could not fetch KVM userspace version")
275 logging.debug("KVM userspace version: %s" % kvm_userspace_version)
276 test.write_test_keyval({"kvm_userspace_version": kvm_userspace_version})
277
278
279def postprocess(test, params, env):
280 """
281 Postprocess all VMs and images according to the instructions in params.
282
283 @param test: An Autotest test object.
284 @param params: Dict containing all VM and image parameters.
285 @param env: The environment (a dict-like object).
286 """
287 process(test, params, env, postprocess_image, postprocess_vm)
288
lmr0ee0a9c2009-07-24 19:23:29 +0000289 # Should we convert PPM files to PNG format?
290 if params.get("convert_ppm_files_to_png") == "yes":
291 logging.debug("'convert_ppm_files_to_png' specified; converting PPM"
292 " files to PNG format...")
lmre9f528e2009-08-12 15:18:10 +0000293 try:
294 for f in glob.glob(os.path.join(test.debugdir, "*.ppm")):
lmr8e7929b2009-08-13 04:26:53 +0000295 new_path = f.replace(".ppm", ".png")
lmre9f528e2009-08-12 15:18:10 +0000296 image = PIL.Image.open(f)
lmr8e7929b2009-08-13 04:26:53 +0000297 image.save(new_path, format = 'PNG')
lmre9f528e2009-08-12 15:18:10 +0000298 except NameError:
299 pass
lmr0ee0a9c2009-07-24 19:23:29 +0000300
301 # Should we keep the PPM files?
302 if params.get("keep_ppm_files") != "yes":
lmr6f669ce2009-05-31 19:02:42 +0000303 logging.debug("'keep_ppm_files' not specified; removing all PPM files"
lmr0ee0a9c2009-07-24 19:23:29 +0000304 " from debug dir...")
lmre9f528e2009-08-12 15:18:10 +0000305 for f in glob.glob(os.path.join(test.debugdir, '*.ppm')):
306 os.unlink(f)
lmr6f669ce2009-05-31 19:02:42 +0000307
lmr0bc6efc2009-07-27 13:27:42 +0000308 # Execute any post_commands
lmr86d1ea52009-06-15 20:34:39 +0000309 if params.get("post_command"):
310 process_command(test, params, env, params.get("post_command"),
lmr0bc6efc2009-07-27 13:27:42 +0000311 int(params.get("post_command_timeout", "600")),
312 params.get("post_command_noncritical") == "yes")
lmr86d1ea52009-06-15 20:34:39 +0000313
lmra4197002009-08-13 05:00:51 +0000314 # Kill the tailing threads of all VMs
315 for vm in kvm_utils.env_get_all_vms(env):
316 vm.kill_tail_thread()
317
lmr965bcd22009-08-13 04:12:19 +0000318 # Terminate tcpdump if no VMs are alive
319 living_vms = [vm for vm in kvm_utils.env_get_all_vms(env) if vm.is_alive()]
320 if not living_vms and env.has_key("tcpdump"):
321 env["tcpdump"].close()
322 del env["tcpdump"]
323
lmr6f669ce2009-05-31 19:02:42 +0000324
325def postprocess_on_error(test, params, env):
326 """
327 Perform postprocessing operations required only if the test failed.
328
329 @param test: An Autotest test object.
330 @param params: A dict containing all VM and image parameters.
331 @param env: The environment (a dict-like object).
332 """
333 params.update(kvm_utils.get_sub_dict(params, "on_error"))
lmr965bcd22009-08-13 04:12:19 +0000334
335
336def _update_address_cache(address_cache, line):
337 if re.search("Your.IP", line, re.IGNORECASE):
338 matches = re.findall(r"\d*\.\d*\.\d*\.\d*", line)
339 if matches:
340 address_cache["last_seen"] = matches[0]
341 if re.search("Client.Ethernet.Address", line, re.IGNORECASE):
342 matches = re.findall(r"\w*:\w*:\w*:\w*:\w*:\w*", line)
343 if matches and address_cache.get("last_seen"):
344 mac_address = matches[0].lower()
345 logging.debug("(address cache) Adding cache entry: %s ---> %s",
346 mac_address, address_cache.get("last_seen"))
347 address_cache[mac_address] = address_cache.get("last_seen")
348 del address_cache["last_seen"]