blob: 1055b2b78d4e1db2128786db7c69a245494b0c4a [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")
lmrf4696342009-08-13 04:06:33 +000064 vm = kvm_vm.VM(name, params, qemu_path, image_dir, iso_dir, script_dir)
lmr6f669ce2009-05-31 19:02:42 +000065 kvm_utils.env_register_vm(env, name, vm)
66
67 start_vm = False
68 for_migration = False
69
70 if params.get("start_vm_for_migration") == "yes":
71 logging.debug("'start_vm_for_migration' specified; (re)starting VM with"
72 " -incoming option...")
73 start_vm = True
74 for_migration = True
75 elif params.get("restart_vm") == "yes":
76 logging.debug("'restart_vm' specified; (re)starting VM...")
77 start_vm = True
78 elif params.get("start_vm") == "yes":
79 if not vm.is_alive():
80 logging.debug("VM is not alive; starting it...")
81 start_vm = True
82 elif vm.make_qemu_command() != vm.make_qemu_command(name, params,
83 qemu_path,
84 image_dir,
lmrf4696342009-08-13 04:06:33 +000085 iso_dir,
86 script_dir):
lmra4967622009-07-23 01:36:32 +000087 logging.debug("VM's qemu command differs from requested one; "
lmr6f669ce2009-05-31 19:02:42 +000088 "restarting it...")
89 start_vm = True
90
91 if start_vm:
lmr6f669ce2009-05-31 19:02:42 +000092 if not vm.create(name, params, qemu_path, image_dir, iso_dir,
lmrf4696342009-08-13 04:06:33 +000093 script_dir, for_migration):
lmr6f669ce2009-05-31 19:02:42 +000094 message = "Could not start VM"
95 logging.error(message)
96 raise error.TestError(message)
97
98 scrdump_filename = os.path.join(test.debugdir, "pre_%s.ppm" % name)
99 vm.send_monitor_cmd("screendump %s" % scrdump_filename)
100
101
102def postprocess_image(test, params):
103 """
104 Postprocess a single QEMU image according to the instructions in params.
105 Currently this function just removes an image if requested.
106
107 @param test: An Autotest test object.
108 @param params: A dict containing image postprocessing parameters.
109 """
110 image_dir = os.path.join(test.bindir, "images")
111
112 if params.get("remove_image") == "yes":
113 kvm_vm.remove_image(params, image_dir)
114
115
116def postprocess_vm(test, params, env, name):
117 """
118 Postprocess a single VM object according to the instructions in params.
119 Kill the VM if requested and get a screendump.
120
121 @param test: An Autotest test object.
122 @param params: A dict containing VM postprocessing parameters.
123 @param env: The environment (a dict-like object).
124 @param name: The name of the VM object.
125 """
126 logging.debug("Postprocessing VM '%s'..." % name)
127 vm = kvm_utils.env_get_vm(env, name)
128 if vm:
129 logging.debug("VM object found in environment")
130 else:
131 logging.debug("VM object does not exist in environment")
132 return
133
134 scrdump_filename = os.path.join(test.debugdir, "post_%s.ppm" % name)
135 vm.send_monitor_cmd("screendump %s" % scrdump_filename)
136
137 if params.get("kill_vm") == "yes":
138 if not kvm_utils.wait_for(vm.is_dead,
139 float(params.get("kill_vm_timeout", 0)), 0.0, 1.0,
140 "Waiting for VM to kill itself..."):
141 logging.debug("'kill_vm' specified; killing VM...")
142 vm.destroy(gracefully = params.get("kill_vm_gracefully") == "yes")
143
144
lmr86d1ea52009-06-15 20:34:39 +0000145def process_command(test, params, env, command, command_timeout,
146 command_noncritical):
147 """
148 Pre- or post- custom commands to be executed before/after a test is run
149
150 @param test: An Autotest test object.
151 @param params: A dict containing all VM and image parameters.
152 @param env: The environment (a dict-like object).
lmr0bc6efc2009-07-27 13:27:42 +0000153 @param command: Command to be run.
154 @param command_timeout: Timeout for command execution.
155 @param command_noncritical: If True test will not fail if command fails.
lmr86d1ea52009-06-15 20:34:39 +0000156 """
lmr0bc6efc2009-07-27 13:27:42 +0000157 # Export environment vars
lmr86d1ea52009-06-15 20:34:39 +0000158 for k in params.keys():
lmr0bc6efc2009-07-27 13:27:42 +0000159 os.putenv("KVM_TEST_%s" % k, str(params[k]))
160 # Execute command
lmr86d1ea52009-06-15 20:34:39 +0000161 logging.info("Executing command '%s'..." % command)
lmra4967622009-07-23 01:36:32 +0000162 (status, output) = kvm_subprocess.run_fg("cd %s; %s" % (test.bindir,
lmr86d1ea52009-06-15 20:34:39 +0000163 command),
lmra4967622009-07-23 01:36:32 +0000164 logging.debug, "(command) ",
lmr0bc6efc2009-07-27 13:27:42 +0000165 timeout=command_timeout)
lmr86d1ea52009-06-15 20:34:39 +0000166 if status != 0:
lmr0bc6efc2009-07-27 13:27:42 +0000167 logging.warn("Custom processing command failed: '%s'" % command)
168 if not command_noncritical:
lmr86d1ea52009-06-15 20:34:39 +0000169 raise error.TestError("Custom processing command failed")
170
171
lmr6f669ce2009-05-31 19:02:42 +0000172def process(test, params, env, image_func, vm_func):
173 """
174 Pre- or post-process VMs and images according to the instructions in params.
175 Call image_func for each image listed in params and vm_func for each VM.
176
177 @param test: An Autotest test object.
178 @param params: A dict containing all VM and image parameters.
179 @param env: The environment (a dict-like object).
180 @param image_func: A function to call for each image.
181 @param vm_func: A function to call for each VM.
182 """
183 # Get list of VMs specified for this test
184 vm_names = kvm_utils.get_sub_dict_names(params, "vms")
185 for vm_name in vm_names:
186 vm_params = kvm_utils.get_sub_dict(params, vm_name)
187 # Get list of images specified for this VM
188 image_names = kvm_utils.get_sub_dict_names(vm_params, "images")
189 for image_name in image_names:
190 image_params = kvm_utils.get_sub_dict(vm_params, image_name)
191 # Call image_func for each image
192 image_func(test, image_params)
193 # Call vm_func for each vm
194 vm_func(test, vm_params, env, vm_name)
195
196
197def preprocess(test, params, env):
198 """
199 Preprocess all VMs and images according to the instructions in params.
200 Also, collect some host information, such as the KVM version.
201
202 @param test: An Autotest test object.
203 @param params: A dict containing all VM and image parameters.
204 @param env: The environment (a dict-like object).
205 """
lmr965bcd22009-08-13 04:12:19 +0000206 # Start tcpdump if it isn't already running
207 if not env.has_key("address_cache"):
208 env["address_cache"] = {}
209 if env.has_key("tcpdump") and not env["tcpdump"].is_alive():
210 env["tcpdump"].close()
211 del env["tcpdump"]
212 if not env.has_key("tcpdump"):
213 command = "/usr/sbin/tcpdump -npvi any 'dst port 68'"
214 logging.debug("Starting tcpdump (%s)...", command)
215 env["tcpdump"] = kvm_subprocess.kvm_tail(
216 command=command,
217 output_func=_update_address_cache,
218 output_params=(env["address_cache"],))
219 if kvm_utils.wait_for(lambda: not env["tcpdump"].is_alive(),
220 0.1, 0.1, 1.0):
221 logging.warn("Could not start tcpdump")
222 logging.warn("Status: %s" % env["tcpdump"].get_status())
223 logging.warn("Output:" + kvm_utils.format_str_for_message(
224 env["tcpdump"].get_output()))
225
lmr6f669ce2009-05-31 19:02:42 +0000226 # Destroy and remove VMs that are no longer needed in the environment
227 requested_vms = kvm_utils.get_sub_dict_names(params, "vms")
228 for key in env.keys():
229 vm = env[key]
230 if not kvm_utils.is_vm(vm):
231 continue
232 if not vm.name in requested_vms:
233 logging.debug("VM '%s' found in environment but not required for"
234 " test; removing it..." % vm.name)
235 vm.destroy()
236 del env[key]
237
lmr0bc6efc2009-07-27 13:27:42 +0000238 # Execute any pre_commands
lmr86d1ea52009-06-15 20:34:39 +0000239 if params.get("pre_command"):
240 process_command(test, params, env, params.get("pre_command"),
lmr0bc6efc2009-07-27 13:27:42 +0000241 int(params.get("pre_command_timeout", "600")),
242 params.get("pre_command_noncritical") == "yes")
lmr86d1ea52009-06-15 20:34:39 +0000243
lmr6f669ce2009-05-31 19:02:42 +0000244 # Preprocess all VMs and images
245 process(test, params, env, preprocess_image, preprocess_vm)
246
247 # Get the KVM kernel module version and write it as a keyval
248 logging.debug("Fetching KVM module version...")
249 if os.path.exists("/dev/kvm"):
250 kvm_version = os.uname()[2]
251 try:
252 file = open("/sys/module/kvm/version", "r")
253 kvm_version = file.read().strip()
254 file.close()
255 except:
256 pass
257 else:
258 kvm_version = "Unknown"
259 logging.debug("KVM module not loaded")
260 logging.debug("KVM version: %s" % kvm_version)
261 test.write_test_keyval({"kvm_version": kvm_version})
262
263 # Get the KVM userspace version and write it as a keyval
264 logging.debug("Fetching KVM userspace version...")
265 qemu_path = os.path.join(test.bindir, "qemu")
266 version_line = commands.getoutput("%s -help | head -n 1" % qemu_path)
267 exp = re.compile("[Vv]ersion .*?,")
268 match = exp.search(version_line)
269 if match:
270 kvm_userspace_version = " ".join(match.group().split()[1:]).strip(",")
271 else:
272 kvm_userspace_version = "Unknown"
273 logging.debug("Could not fetch KVM userspace version")
274 logging.debug("KVM userspace version: %s" % kvm_userspace_version)
275 test.write_test_keyval({"kvm_userspace_version": kvm_userspace_version})
276
277
278def postprocess(test, params, env):
279 """
280 Postprocess all VMs and images according to the instructions in params.
281
282 @param test: An Autotest test object.
283 @param params: Dict containing all VM and image parameters.
284 @param env: The environment (a dict-like object).
285 """
286 process(test, params, env, postprocess_image, postprocess_vm)
287
lmr0ee0a9c2009-07-24 19:23:29 +0000288 # Should we convert PPM files to PNG format?
289 if params.get("convert_ppm_files_to_png") == "yes":
290 logging.debug("'convert_ppm_files_to_png' specified; converting PPM"
291 " files to PNG format...")
lmre9f528e2009-08-12 15:18:10 +0000292 try:
293 for f in glob.glob(os.path.join(test.debugdir, "*.ppm")):
294 image = PIL.Image.open(f)
295 image.save(history_scrdump_filename, format = 'PNG')
296 except NameError:
297 pass
lmr0ee0a9c2009-07-24 19:23:29 +0000298
299 # Should we keep the PPM files?
300 if params.get("keep_ppm_files") != "yes":
lmr6f669ce2009-05-31 19:02:42 +0000301 logging.debug("'keep_ppm_files' not specified; removing all PPM files"
lmr0ee0a9c2009-07-24 19:23:29 +0000302 " from debug dir...")
lmre9f528e2009-08-12 15:18:10 +0000303 for f in glob.glob(os.path.join(test.debugdir, '*.ppm')):
304 os.unlink(f)
lmr6f669ce2009-05-31 19:02:42 +0000305
lmr0bc6efc2009-07-27 13:27:42 +0000306 # Execute any post_commands
lmr86d1ea52009-06-15 20:34:39 +0000307 if params.get("post_command"):
308 process_command(test, params, env, params.get("post_command"),
lmr0bc6efc2009-07-27 13:27:42 +0000309 int(params.get("post_command_timeout", "600")),
310 params.get("post_command_noncritical") == "yes")
lmr86d1ea52009-06-15 20:34:39 +0000311
lmr965bcd22009-08-13 04:12:19 +0000312 # Terminate tcpdump if no VMs are alive
313 living_vms = [vm for vm in kvm_utils.env_get_all_vms(env) if vm.is_alive()]
314 if not living_vms and env.has_key("tcpdump"):
315 env["tcpdump"].close()
316 del env["tcpdump"]
317
lmr6f669ce2009-05-31 19:02:42 +0000318
319def postprocess_on_error(test, params, env):
320 """
321 Perform postprocessing operations required only if the test failed.
322
323 @param test: An Autotest test object.
324 @param params: A dict containing all VM and image parameters.
325 @param env: The environment (a dict-like object).
326 """
327 params.update(kvm_utils.get_sub_dict(params, "on_error"))
lmr965bcd22009-08-13 04:12:19 +0000328
329
330def _update_address_cache(address_cache, line):
331 if re.search("Your.IP", line, re.IGNORECASE):
332 matches = re.findall(r"\d*\.\d*\.\d*\.\d*", line)
333 if matches:
334 address_cache["last_seen"] = matches[0]
335 if re.search("Client.Ethernet.Address", line, re.IGNORECASE):
336 matches = re.findall(r"\w*:\w*:\w*:\w*:\w*:\w*", line)
337 if matches and address_cache.get("last_seen"):
338 mac_address = matches[0].lower()
339 logging.debug("(address cache) Adding cache entry: %s ---> %s",
340 mac_address, address_cache.get("last_seen"))
341 address_cache[mac_address] = address_cache.get("last_seen")
342 del address_cache["last_seen"]