blob: 80d7be8e614d38180a04a7fbc572c9e2a0cb3e36 [file] [log] [blame]
lmr86d1ea52009-06-15 20:34:39 +00001import sys, os, time, commands, re, logging, signal
lmr6f669ce2009-05-31 19:02:42 +00002from autotest_lib.client.bin import test
3from autotest_lib.client.common_lib import error
4import kvm_vm, kvm_utils
5
6
7def preprocess_image(test, params):
8 """
9 Preprocess a single QEMU image according to the instructions in params.
10
11 @param test: Autotest test object.
12 @param params: A dict containing image preprocessing parameters.
13 @note: Currently this function just creates an image if requested.
14 """
15 qemu_img_path = os.path.join(test.bindir, "qemu-img")
16 image_dir = os.path.join(test.bindir, "images")
17 image_filename = kvm_vm.get_image_filename(params, image_dir)
18
19 create_image = False
20
21 if params.get("force_create_image") == "yes":
22 logging.debug("'force_create_image' specified; creating image...")
23 create_image = True
24 elif params.get("create_image") == "yes" and not \
25 os.path.exists(image_filename):
26 logging.debug("Creating image...")
27 create_image = True
28
29 if create_image:
30 if not kvm_vm.create_image(params, qemu_img_path, image_dir):
31 message = "Could not create image"
32 logging.error(message)
33 raise error.TestError(message)
34
35
36def preprocess_vm(test, params, env, name):
37 """
38 Preprocess a single VM object according to the instructions in params.
39 Start the VM if requested and get a screendump.
40
41 @param test: An Autotest test object.
42 @param params: A dict containing VM preprocessing parameters.
43 @param env: The environment (a dict-like object).
44 @param name: The name of the VM object.
45 """
46 qemu_path = os.path.join(test.bindir, "qemu")
47 image_dir = os.path.join(test.bindir, "images")
48 iso_dir = os.path.join(test.bindir, "isos")
49
50 logging.debug("Preprocessing VM '%s'..." % name)
51 vm = kvm_utils.env_get_vm(env, name)
52 if vm:
53 logging.debug("VM object found in environment")
54 else:
55 logging.debug("VM object does not exist; creating it")
56 vm = kvm_vm.VM(name, params, qemu_path, image_dir, iso_dir)
57 kvm_utils.env_register_vm(env, name, vm)
58
59 start_vm = False
60 for_migration = False
61
62 if params.get("start_vm_for_migration") == "yes":
63 logging.debug("'start_vm_for_migration' specified; (re)starting VM with"
64 " -incoming option...")
65 start_vm = True
66 for_migration = True
67 elif params.get("restart_vm") == "yes":
68 logging.debug("'restart_vm' specified; (re)starting VM...")
69 start_vm = True
70 elif params.get("start_vm") == "yes":
71 if not vm.is_alive():
72 logging.debug("VM is not alive; starting it...")
73 start_vm = True
74 elif vm.make_qemu_command() != vm.make_qemu_command(name, params,
75 qemu_path,
76 image_dir,
77 iso_dir):
78 logging.debug("VM's qemu command differs from requested one;"
79 "restarting it...")
80 start_vm = True
81
82 if start_vm:
lmr6f669ce2009-05-31 19:02:42 +000083 if not vm.create(name, params, qemu_path, image_dir, iso_dir,
84 for_migration):
85 message = "Could not start VM"
86 logging.error(message)
87 raise error.TestError(message)
88
89 scrdump_filename = os.path.join(test.debugdir, "pre_%s.ppm" % name)
90 vm.send_monitor_cmd("screendump %s" % scrdump_filename)
91
92
93def postprocess_image(test, params):
94 """
95 Postprocess a single QEMU image according to the instructions in params.
96 Currently this function just removes an image if requested.
97
98 @param test: An Autotest test object.
99 @param params: A dict containing image postprocessing parameters.
100 """
101 image_dir = os.path.join(test.bindir, "images")
102
103 if params.get("remove_image") == "yes":
104 kvm_vm.remove_image(params, image_dir)
105
106
107def postprocess_vm(test, params, env, name):
108 """
109 Postprocess a single VM object according to the instructions in params.
110 Kill the VM if requested and get a screendump.
111
112 @param test: An Autotest test object.
113 @param params: A dict containing VM postprocessing parameters.
114 @param env: The environment (a dict-like object).
115 @param name: The name of the VM object.
116 """
117 logging.debug("Postprocessing VM '%s'..." % name)
118 vm = kvm_utils.env_get_vm(env, name)
119 if vm:
120 logging.debug("VM object found in environment")
121 else:
122 logging.debug("VM object does not exist in environment")
123 return
124
125 scrdump_filename = os.path.join(test.debugdir, "post_%s.ppm" % name)
126 vm.send_monitor_cmd("screendump %s" % scrdump_filename)
127
128 if params.get("kill_vm") == "yes":
129 if not kvm_utils.wait_for(vm.is_dead,
130 float(params.get("kill_vm_timeout", 0)), 0.0, 1.0,
131 "Waiting for VM to kill itself..."):
132 logging.debug("'kill_vm' specified; killing VM...")
133 vm.destroy(gracefully = params.get("kill_vm_gracefully") == "yes")
134
135
lmr86d1ea52009-06-15 20:34:39 +0000136def process_command(test, params, env, command, command_timeout,
137 command_noncritical):
138 """
139 Pre- or post- custom commands to be executed before/after a test is run
140
141 @param test: An Autotest test object.
142 @param params: A dict containing all VM and image parameters.
143 @param env: The environment (a dict-like object).
144 @param command: Script containing the command to be run.
145 @param commmand_timeout: Timeout for command execution.
146 @param command_noncritical: if 'yes' test will not fail if command fails.
147 """
148 if command_timeout is None:
149 command_timeout = "600"
150
151 if command_noncritical is None:
152 command_noncritical = "no"
153
154 # export environment vars
155 for k in params.keys():
156 logging.info("Adding KVM_TEST_%s to Environment" % (k))
157 os.putenv("KVM_TEST_%s" % (k), str(params[k]))
158 # execute command
159 logging.info("Executing command '%s'..." % command)
160 timeout = int(command_timeout)
161 (status, pid, output) = kvm_utils.run_bg("cd %s; %s" % (test.bindir,
162 command),
163 None, logging.debug,
164 "(command) ",
165 timeout = timeout)
166 if status != 0:
167 kvm_utils.safe_kill(pid, signal.SIGTERM)
168 logging.warn("Custom processing command failed: '%s'..." % command)
169 if command_noncritical != "yes":
170 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 """
207 # Verify the identities of all living VMs
208 for vm in env.values():
209 if not kvm_utils.is_vm(vm):
210 continue
211 if vm.is_dead():
212 continue
213 if not vm.verify_process_identity():
214 logging.debug("VM '%s' seems to have been replaced by another"
215 " process" % vm.name)
216 vm.pid = None
217
218 # Destroy and remove VMs that are no longer needed in the environment
219 requested_vms = kvm_utils.get_sub_dict_names(params, "vms")
220 for key in env.keys():
221 vm = env[key]
222 if not kvm_utils.is_vm(vm):
223 continue
224 if not vm.name in requested_vms:
225 logging.debug("VM '%s' found in environment but not required for"
226 " test; removing it..." % vm.name)
227 vm.destroy()
228 del env[key]
229
lmr86d1ea52009-06-15 20:34:39 +0000230 #execute any pre_commands
231 if params.get("pre_command"):
232 process_command(test, params, env, params.get("pre_command"),
233 params.get("pre_command_timeout"),
234 params.get("pre_command_noncritical"))
235
lmr6f669ce2009-05-31 19:02:42 +0000236 # Preprocess all VMs and images
237 process(test, params, env, preprocess_image, preprocess_vm)
238
239 # Get the KVM kernel module version and write it as a keyval
240 logging.debug("Fetching KVM module version...")
241 if os.path.exists("/dev/kvm"):
242 kvm_version = os.uname()[2]
243 try:
244 file = open("/sys/module/kvm/version", "r")
245 kvm_version = file.read().strip()
246 file.close()
247 except:
248 pass
249 else:
250 kvm_version = "Unknown"
251 logging.debug("KVM module not loaded")
252 logging.debug("KVM version: %s" % kvm_version)
253 test.write_test_keyval({"kvm_version": kvm_version})
254
255 # Get the KVM userspace version and write it as a keyval
256 logging.debug("Fetching KVM userspace version...")
257 qemu_path = os.path.join(test.bindir, "qemu")
258 version_line = commands.getoutput("%s -help | head -n 1" % qemu_path)
259 exp = re.compile("[Vv]ersion .*?,")
260 match = exp.search(version_line)
261 if match:
262 kvm_userspace_version = " ".join(match.group().split()[1:]).strip(",")
263 else:
264 kvm_userspace_version = "Unknown"
265 logging.debug("Could not fetch KVM userspace version")
266 logging.debug("KVM userspace version: %s" % kvm_userspace_version)
267 test.write_test_keyval({"kvm_userspace_version": kvm_userspace_version})
268
269
270def postprocess(test, params, env):
271 """
272 Postprocess all VMs and images according to the instructions in params.
273
274 @param test: An Autotest test object.
275 @param params: Dict containing all VM and image parameters.
276 @param env: The environment (a dict-like object).
277 """
278 process(test, params, env, postprocess_image, postprocess_vm)
279
280 # See if we should get rid of all PPM files
281 if not params.get("keep_ppm_files") == "yes":
282 # Remove them all
283 logging.debug("'keep_ppm_files' not specified; removing all PPM files"
284 " from results dir...")
285 kvm_utils.run_bg("rm -vf %s" % os.path.join(test.debugdir, "*.ppm"),
286 None, logging.debug, "(rm) ", timeout=5.0)
287
lmr86d1ea52009-06-15 20:34:39 +0000288 #execute any post_commands
289 if params.get("post_command"):
290 process_command(test, params, env, params.get("post_command"),
291 params.get("post_command_timeout"),
292 params.get("post_command_noncritical"))
293
lmr6f669ce2009-05-31 19:02:42 +0000294
295def postprocess_on_error(test, params, env):
296 """
297 Perform postprocessing operations required only if the test failed.
298
299 @param test: An Autotest test object.
300 @param params: A dict containing all VM and image parameters.
301 @param env: The environment (a dict-like object).
302 """
303 params.update(kvm_utils.get_sub_dict(params, "on_error"))