blob: eae1d0c826e34df252b6228ef59e3c396541b287 [file] [log] [blame]
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001# Copyright (c) 2011 The Chromium OS Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
Vic Yangb4e3e742012-06-02 13:17:38 +08005import fdpexpect
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08006import logging
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +08007import os
Vic Yangb4e3e742012-06-02 13:17:38 +08008import pexpect
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08009import re
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +080010import sys
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +080011import tempfile
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080012import time
13import xmlrpclib
14
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +080015from autotest_lib.client.bin import utils
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080016from autotest_lib.client.common_lib import error
Vic Yangebd6de62012-06-26 14:25:57 +080017from autotest_lib.server.cros.faft_client_attribute import FAFTClientAttribute
Tom Wai-Hong Tam22b77302011-11-03 13:03:48 +080018from autotest_lib.server.cros.servo_test import ServoTest
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +080019from autotest_lib.site_utils import lab_test
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080020
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +080021dirname = os.path.dirname(sys.modules[__name__].__file__)
22autotest_dir = os.path.abspath(os.path.join(dirname, "..", ".."))
23cros_dir = os.path.join(autotest_dir, "..", "..", "..", "..")
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080024
25class FAFTSequence(ServoTest):
26 """
27 The base class of Fully Automated Firmware Test Sequence.
28
29 Many firmware tests require several reboot cycles and verify the resulted
30 system states. To do that, an Autotest test case should detailly handle
31 every action on each step. It makes the test case hard to read and many
32 duplicated code. The base class FAFTSequence is to solve this problem.
33
34 The actions of one reboot cycle is defined in a dict, namely FAFT_STEP.
35 There are four functions in the FAFT_STEP dict:
36 state_checker: a function to check the current is valid or not,
37 returning True if valid, otherwise, False to break the whole
38 test sequence.
39 userspace_action: a function to describe the action ran in userspace.
Tom Wai-Hong Tamf1e34972011-11-02 17:07:04 +080040 reboot_action: a function to do reboot, default: sync_and_hw_reboot.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080041 firmware_action: a function to describe the action ran after reboot.
42
Tom Wai-Hong Tam7c17ff22011-10-26 09:44:09 +080043 And configurations:
44 install_deps_after_boot: if True, install the Autotest dependency after
45 boot; otherwise, do nothing. It is for the cases of recovery mode
46 test. The test boots a USB/SD image instead of an internal image.
47 The previous installed Autotest dependency on the internal image
48 is lost. So need to install it again.
49
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080050 The default FAFT_STEP checks nothing in state_checker and does nothing in
Tom Wai-Hong Tamf1e34972011-11-02 17:07:04 +080051 userspace_action and firmware_action. Its reboot_action is a hardware
52 reboot. You can change the default FAFT_STEP by calling
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080053 self.register_faft_template(FAFT_STEP).
54
55 A FAFT test case consists of several FAFT_STEP's, namely FAFT_SEQUENCE.
56 FAFT_SEQUENCE is an array of FAFT_STEP's. Any missing fields on FAFT_STEP
57 fall back to default.
58
59 In the run_once(), it should register and run FAFT_SEQUENCE like:
60 def run_once(self):
61 self.register_faft_sequence(FAFT_SEQUENCE)
62 self.run_faft_sequnce()
63
64 Note that in the last step, we only run state_checker. The
65 userspace_action, reboot_action, and firmware_action are not executed.
66
67 Attributes:
68 _faft_template: The default FAFT_STEP of each step. The actions would
69 be over-written if the registered FAFT_SEQUENCE is valid.
70 _faft_sequence: The registered FAFT_SEQUENCE.
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +080071 _customized_ctrl_d_key_command: The customized Ctrl-D key command
72 instead of sending key via servo board.
73 _customized_enter_key_command: The customized Enter key command instead
74 of sending key via servo board.
75 _install_image_path: The path of Chrome OS test image to be installed.
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +080076 _firmware_update: Boolean. True if firmware update needed after
77 installing the image.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080078 """
79 version = 1
80
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +080081
82 # Mapping of partition number of kernel and rootfs.
83 KERNEL_MAP = {'a':'2', 'b':'4', '2':'2', '4':'4', '3':'2', '5':'4'}
84 ROOTFS_MAP = {'a':'3', 'b':'5', '2':'3', '4':'5', '3':'3', '5':'5'}
85 OTHER_KERNEL_MAP = {'a':'4', 'b':'2', '2':'4', '4':'2', '3':'4', '5':'2'}
86 OTHER_ROOTFS_MAP = {'a':'5', 'b':'3', '2':'5', '4':'3', '3':'5', '5':'3'}
87
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +080088 # Delay between power-on and firmware screen.
Tom Wai-Hong Tam211ccba2012-01-13 15:35:53 +080089 FIRMWARE_SCREEN_DELAY = 2
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +080090 # Delay between passing firmware screen and text mode warning screen.
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +080091 TEXT_SCREEN_DELAY = 20
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +080092 # Delay of loading the USB kernel.
Tom Wai-Hong Tam07278c22012-02-08 16:53:00 +080093 USB_LOAD_DELAY = 10
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +080094 # Delay between USB plug-out and plug-in.
Tom Wai-Hong Tam9ca742a2011-12-05 15:48:57 +080095 USB_PLUG_DELAY = 10
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +080096 # Delay after running the 'sync' command.
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +080097 SYNC_DELAY = 5
Vic Yang59cac9c2012-05-21 15:28:42 +080098 # Delay for waiting client to return before EC reboot
99 EC_REBOOT_DELAY = 1
100 # Delay between EC reboot and pressing power button
101 POWER_BTN_DELAY = 0.5
Vic Yange7553162012-06-20 16:20:47 +0800102 # Delay between sending keystroke to firmware
103 FIRMWARE_KEY_DELAY = 0.5
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800104
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800105 CHROMEOS_MAGIC = "CHROMEOS"
106 CORRUPTED_MAGIC = "CORRUPTD"
107
Tom Wai-Hong Tamf954d172011-12-08 17:14:15 +0800108 # Recovery reason codes, copied from:
109 # vboot_reference/firmware/lib/vboot_nvstorage.h
110 # vboot_reference/firmware/lib/vboot_struct.h
111 RECOVERY_REASON = {
112 # Recovery not requested
113 'NOT_REQUESTED': '0', # 0x00
114 # Recovery requested from legacy utility
115 'LEGACY': '1', # 0x01
116 # User manually requested recovery via recovery button
117 'RO_MANUAL': '2', # 0x02
118 # RW firmware failed signature check
119 'RO_INVALID_RW': '3', # 0x03
120 # S3 resume failed
121 'RO_S3_RESUME': '4', # 0x04
122 # TPM error in read-only firmware
123 'RO_TPM_ERROR': '5', # 0x05
124 # Shared data error in read-only firmware
125 'RO_SHARED_DATA': '6', # 0x06
126 # Test error from S3Resume()
127 'RO_TEST_S3': '7', # 0x07
128 # Test error from LoadFirmwareSetup()
129 'RO_TEST_LFS': '8', # 0x08
130 # Test error from LoadFirmware()
131 'RO_TEST_LF': '9', # 0x09
132 # RW firmware failed signature check
133 'RW_NOT_DONE': '16', # 0x10
134 'RW_DEV_MISMATCH': '17', # 0x11
135 'RW_REC_MISMATCH': '18', # 0x12
136 'RW_VERIFY_KEYBLOCK': '19', # 0x13
137 'RW_KEY_ROLLBACK': '20', # 0x14
138 'RW_DATA_KEY_PARSE': '21', # 0x15
139 'RW_VERIFY_PREAMBLE': '22', # 0x16
140 'RW_FW_ROLLBACK': '23', # 0x17
141 'RW_HEADER_VALID': '24', # 0x18
142 'RW_GET_FW_BODY': '25', # 0x19
143 'RW_HASH_WRONG_SIZE': '26', # 0x1A
144 'RW_VERIFY_BODY': '27', # 0x1B
145 'RW_VALID': '28', # 0x1C
146 # Read-only normal path requested by firmware preamble, but
147 # unsupported by firmware.
148 'RW_NO_RO_NORMAL': '29', # 0x1D
149 # Firmware boot failure outside of verified boot
150 'RO_FIRMWARE': '32', # 0x20
151 # Recovery mode TPM initialization requires a system reboot.
152 # The system was already in recovery mode for some other reason
153 # when this happened.
154 'RO_TPM_REBOOT': '33', # 0x21
155 # Unspecified/unknown error in read-only firmware
156 'RO_UNSPECIFIED': '63', # 0x3F
157 # User manually requested recovery by pressing a key at developer
158 # warning screen.
159 'RW_DEV_SCREEN': '65', # 0x41
160 # No OS kernel detected
161 'RW_NO_OS': '66', # 0x42
162 # OS kernel failed signature check
163 'RW_INVALID_OS': '67', # 0x43
164 # TPM error in rewritable firmware
165 'RW_TPM_ERROR': '68', # 0x44
166 # RW firmware in dev mode, but dev switch is off.
167 'RW_DEV_MISMATCH': '69', # 0x45
168 # Shared data error in rewritable firmware
169 'RW_SHARED_DATA': '70', # 0x46
170 # Test error from LoadKernel()
171 'RW_TEST_LK': '71', # 0x47
172 # No bootable disk found
173 'RW_NO_DISK': '72', # 0x48
174 # Unspecified/unknown error in rewritable firmware
175 'RW_UNSPECIFIED': '127', # 0x7F
176 # DM-verity error
177 'KE_DM_VERITY': '129', # 0x81
178 # Unspecified/unknown error in kernel
179 'KE_UNSPECIFIED': '191', # 0xBF
180 # Recovery mode test from user-mode
181 'US_TEST': '193', # 0xC1
182 # Unspecified/unknown error in user-mode
183 'US_UNSPECIFIED': '255', # 0xFF
184 }
185
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +0800186 _faft_template = {}
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800187 _faft_sequence = ()
188
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800189 _customized_ctrl_d_key_command = None
190 _customized_enter_key_command = None
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800191 _install_image_path = None
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800192 _firmware_update = False
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800193
194
195 def initialize(self, host, cmdline_args, use_pyauto=False, use_faft=False):
196 # Parse arguments from command line
197 args = {}
198 for arg in cmdline_args:
199 match = re.search("^(\w+)=(.+)", arg)
200 if match:
201 args[match.group(1)] = match.group(2)
202
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800203 # Keep the arguments which will be used later.
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800204 if 'ctrl_d_cmd' in args:
205 self._customized_ctrl_d_key_command = args['ctrl_d_cmd']
206 logging.info('Customized Ctrl-D key command: %s' %
207 self._customized_ctrl_d_key_command)
208 if 'enter_cmd' in args:
209 self._customized_enter_key_command = args['enter_cmd']
210 logging.info('Customized Enter key command: %s' %
211 self._customized_enter_key_command)
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800212 if 'image' in args:
213 self._install_image_path = args['image']
214 logging.info('Install Chrome OS test image path: %s' %
215 self._install_image_path)
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800216 if 'firmware_update' in args and args['firmware_update'].lower() \
217 not in ('0', 'false', 'no'):
218 if self._install_image_path:
219 self._firmware_update = True
220 logging.info('Also update firmware after installing.')
221 else:
222 logging.warning('Firmware update will not not performed '
223 'since no image is specified.')
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800224
225 super(FAFTSequence, self).initialize(host, cmdline_args, use_pyauto,
226 use_faft)
Vic Yangebd6de62012-06-26 14:25:57 +0800227 if use_faft:
228 self.client_attr = FAFTClientAttribute(
229 self.faft_client.get_platform_name())
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800230
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800231
232 def setup(self):
233 """Autotest setup function."""
234 super(FAFTSequence, self).setup()
235 if not self._remote_infos['faft']['used']:
236 raise error.TestError('The use_faft flag should be enabled.')
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800237
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800238 self.register_faft_template({
239 'state_checker': (None),
240 'userspace_action': (None),
Tom Wai-Hong Tamf1e34972011-11-02 17:07:04 +0800241 'reboot_action': (self.sync_and_hw_reboot),
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800242 'firmware_action': (None)
243 })
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800244 if self._install_image_path:
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800245 self.install_test_image(self._install_image_path,
246 self._firmware_update)
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800247
248
249 def cleanup(self):
250 """Autotest cleanup function."""
251 self._faft_sequence = ()
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +0800252 self._faft_template = {}
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800253 super(FAFTSequence, self).cleanup()
254
255
Tom Wai-Hong Tam91f49822011-12-28 15:44:15 +0800256 def assert_test_image_in_usb_disk(self, usb_dev=None):
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800257 """Assert an USB disk plugged-in on servo and a test image inside.
258
Tom Wai-Hong Tam91f49822011-12-28 15:44:15 +0800259 Args:
260 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
261 If None, it is detected automatically.
262
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800263 Raises:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800264 error.TestError: if USB disk not detected or not a test image.
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800265 """
Tom Wai-Hong Tam91f49822011-12-28 15:44:15 +0800266 if usb_dev:
267 assert self.servo.get('usb_mux_sel1') == 'servo_sees_usbkey'
268 else:
269 self.servo.set('usb_mux_sel1', 'servo_sees_usbkey')
270 usb_dev = self.servo.probe_host_usb_dev()
271 if not usb_dev:
272 raise error.TestError(
273 'An USB disk should be plugged in the servo board.')
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800274
275 tmp_dir = tempfile.mkdtemp()
Tom Wai-Hong Tamb0e80852011-12-07 16:15:06 +0800276 utils.system('sudo mount -r -t ext2 %s3 %s' % (usb_dev, tmp_dir))
Tom Wai-Hong Tame77459e2011-11-03 17:19:46 +0800277 code = utils.system(
278 'grep -qE "(Test Build|testimage-channel)" %s/etc/lsb-release' %
279 tmp_dir, ignore_status=True)
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800280 utils.system('sudo umount %s' % tmp_dir)
281 os.removedirs(tmp_dir)
282 if code != 0:
283 raise error.TestError(
284 'The image in the USB disk should be a test image.')
285
286
Simran Basi741b5d42012-05-18 11:27:15 -0700287 def install_test_image(self, image_path=None, firmware_update=False):
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800288 """Install the test image specied by the path onto the USB and DUT disk.
289
290 The method first copies the image to USB disk and reboots into it via
291 recovery mode. Then runs 'chromeos-install' to install it to DUT disk.
292
293 Args:
294 image_path: Path on the host to the test image.
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800295 firmware_update: Also update the firmware after installing.
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800296 """
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800297 install_cmd = 'chromeos-install --yes'
298 if firmware_update:
299 install_cmd += ' && chromeos-firmwareupdate --mode recovery'
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800300 build_ver, build_hash = lab_test.VerifyImageAndGetId(cros_dir,
301 image_path)
302 logging.info('Processing build: %s %s' % (build_ver, build_hash))
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800303
304 # Reuse the install_recovery_image method by using a test image.
305 # Don't wait for completion but run chromeos-install to install it.
Simran Basi741b5d42012-05-18 11:27:15 -0700306 self.servo.install_recovery_image(image_path)
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800307 self.wait_for_client(install_deps=True)
308 self.run_faft_step({
309 'userspace_action': (self.faft_client.run_shell_command,
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800310 install_cmd)
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800311 })
312
313
Vic Yangb4e3e742012-06-02 13:17:38 +0800314 def _open_uart_pty(self):
315 """Open UART pty and spawn pexpect object.
316
317 Returns:
318 Tuple (fd, child): fd is the file descriptor of opened UART pty, and
319 child is a fdpexpect object tied to it.
320 """
321 fd = os.open(self.servo.get("uart1_pty"), os.O_RDWR | os.O_NONBLOCK)
322 child = fdpexpect.fdspawn(fd)
323 return (fd, child)
324
325
326 def _flush_uart_pty(self, child):
327 """Flush UART output to prevent previous pending message interferring.
328
329 Args:
330 child: The fdpexpect object tied to UART pty.
331 """
332 child.sendline("")
333 while True:
334 try:
335 child.expect(".", timeout=0.01)
336 except pexpect.TIMEOUT:
337 break
338
339
340 def _uart_send(self, child, line):
341 """Flush and send command through UART.
342
343 Args:
344 child: The pexpect object tied to UART pty.
345 line: String to send through UART.
346
347 Raises:
348 error.TestFail: Raised when writing to UART fails.
349 """
350 logging.info("Sending UART command: %s" % line)
351 self._flush_uart_pty(child)
352 if child.sendline(line) != len(line) + 1:
353 raise error.TestFail("Failed to send UART command.")
354
355
356 def send_uart_command(self, command):
357 """Send command through UART.
358
359 This function open UART pty when called, and then command is sent
360 through UART.
361
362 Args:
363 command: The command string to send.
364
365 Raises:
366 error.TestFail: Raised when writing to UART fails.
367 """
368 (fd, child) = self._open_uart_pty()
369 try:
370 self._uart_send(child, command)
371 finally:
372 os.close(fd)
373
374
375 def send_uart_command_get_output(self, command, regex_list, timeout=1):
376 """Send command through UART and wait for response.
377
378 This function waits for response message matching regular expressions.
379
380 Args:
381 command: The command sent.
382 regex_list: List of regular expressions used to match response message.
383 Note, list must be ordered.
384
385 Returns:
386 List of match objects of response message.
387
388 Raises:
389 error.TestFail: If timed out waiting for EC response.
390 """
391 if not isinstance(regex_list, list):
392 regex_list = [regex_list]
393 result_list = []
394 (fd, child) = self._open_uart_pty()
395 try:
396 self._uart_send(child, command)
397 for regex in regex_list:
398 child.expect(regex, timeout=timeout)
399 result_list.append(child.match)
400 except pexpect.TIMEOUT:
401 raise error.TestFail("Timeout waiting for UART response.")
402 finally:
403 os.close(fd)
404 return result_list
405
406
Vic Yang4d72cb62012-07-24 11:51:09 +0800407 def check_ec_capability(self, required_cap=[]):
408 """Check if current platform has required EC capabilities.
409
410 Args:
411 required_cap: A list containing required EC capabilities. Pass in
412 None to only check for presence of Chrome EC.
413
414 Returns:
415 True if requirements are met. Otherwise, False.
416 """
417 if not self.client_attr.chrome_ec:
418 logging.warn('Requires Chrome EC to run this test.')
419 return False
420
421 for cap in required_cap:
422 if cap not in self.client_attr.ec_capability:
423 logging.warn('Requires EC capability "%s" to run this test.' %
424 cap)
425 return False
426
427 return True
428
429
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800430 def _parse_crossystem_output(self, lines):
431 """Parse the crossystem output into a dict.
432
433 Args:
434 lines: The list of crossystem output strings.
435
436 Returns:
437 A dict which contains the crossystem keys/values.
438
439 Raises:
440 error.TestError: If wrong format in crossystem output.
441
442 >>> seq = FAFTSequence()
443 >>> seq._parse_crossystem_output([ \
444 "arch = x86 # Platform architecture", \
445 "cros_debug = 1 # OS should allow debug", \
446 ])
447 {'cros_debug': '1', 'arch': 'x86'}
448 >>> seq._parse_crossystem_output([ \
449 "arch=x86", \
450 ])
451 Traceback (most recent call last):
452 ...
453 TestError: Failed to parse crossystem output: arch=x86
454 >>> seq._parse_crossystem_output([ \
455 "arch = x86 # Platform architecture", \
456 "arch = arm # Platform architecture", \
457 ])
458 Traceback (most recent call last):
459 ...
460 TestError: Duplicated crossystem key: arch
461 """
462 pattern = "^([^ =]*) *= *(.*[^ ]) *# [^#]*$"
463 parsed_list = {}
464 for line in lines:
465 matched = re.match(pattern, line.strip())
466 if not matched:
467 raise error.TestError("Failed to parse crossystem output: %s"
468 % line)
469 (name, value) = (matched.group(1), matched.group(2))
470 if name in parsed_list:
471 raise error.TestError("Duplicated crossystem key: %s" % name)
472 parsed_list[name] = value
473 return parsed_list
474
475
476 def crossystem_checker(self, expected_dict):
477 """Check the crossystem values matched.
478
479 Given an expect_dict which describes the expected crossystem values,
480 this function check the current crossystem values are matched or not.
481
482 Args:
483 expected_dict: A dict which contains the expected values.
484
485 Returns:
486 True if the crossystem value matched; otherwise, False.
487 """
488 lines = self.faft_client.run_shell_command_get_output('crossystem')
489 got_dict = self._parse_crossystem_output(lines)
490 for key in expected_dict:
491 if key not in got_dict:
492 logging.info('Expected key "%s" not in crossystem result' % key)
493 return False
494 if isinstance(expected_dict[key], str):
495 if got_dict[key] != expected_dict[key]:
496 logging.info("Expected '%s' value '%s' but got '%s'" %
497 (key, expected_dict[key], got_dict[key]))
498 return False
499 elif isinstance(expected_dict[key], tuple):
500 # Expected value is a tuple of possible actual values.
501 if got_dict[key] not in expected_dict[key]:
502 logging.info("Expected '%s' values %s but got '%s'" %
503 (key, str(expected_dict[key]), got_dict[key]))
504 return False
505 else:
506 logging.info("The expected_dict is neither a str nor a dict.")
507 return False
508 return True
509
510
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800511 def root_part_checker(self, expected_part):
512 """Check the partition number of the root device matched.
513
514 Args:
515 expected_part: A string containing the number of the expected root
516 partition.
517
518 Returns:
519 True if the currect root partition number matched; otherwise, False.
520 """
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +0800521 part = self.faft_client.get_root_part()[-1]
522 if self.ROOTFS_MAP[expected_part] != part:
523 logging.info("Expected root part %s but got %s" %
524 (self.ROOTFS_MAP[expected_part], part))
525 return False
526 return True
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800527
528
Vic Yang59cac9c2012-05-21 15:28:42 +0800529 def ec_act_copy_checker(self, expected_copy):
530 """Check the EC running firmware copy matches.
531
532 Args:
533 expected_copy: A string containing 'RO', 'A', or 'B' indicating
534 the expected copy of EC running firmware.
535
536 Returns:
537 True if the current EC running copy matches; otherwise, False.
538 """
539 lines = self.faft_client.run_shell_command_get_output('ectool version')
540 pattern = re.compile("Firmware copy: (.*)")
541 for line in lines:
542 matched = pattern.match(line)
543 if matched and matched.group(1) == expected_copy:
544 return True
545 return False
546
547
Tom Wai-Hong Tam07278c22012-02-08 16:53:00 +0800548 def check_root_part_on_non_recovery(self, part):
549 """Check the partition number of root device and on normal/dev boot.
550
551 Returns:
552 True if the root device matched and on normal/dev boot;
553 otherwise, False.
554 """
555 return self.root_part_checker(part) and \
556 self.crossystem_checker({
557 'mainfw_type': ('normal', 'developer'),
558 'recoverysw_boot': '0',
559 })
560
561
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800562 def _join_part(self, dev, part):
563 """Return a concatenated string of device and partition number.
564
565 Args:
566 dev: A string of device, e.g.'/dev/sda'.
567 part: A string of partition number, e.g.'3'.
568
569 Returns:
570 A concatenated string of device and partition number, e.g.'/dev/sda3'.
571
572 >>> seq = FAFTSequence()
573 >>> seq._join_part('/dev/sda', '3')
574 '/dev/sda3'
575 >>> seq._join_part('/dev/mmcblk0', '2')
576 '/dev/mmcblk0p2'
577 """
578 if 'mmcblk' in dev:
579 return dev + 'p' + part
580 else:
581 return dev + part
582
583
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800584 def copy_kernel_and_rootfs(self, from_part, to_part):
585 """Copy kernel and rootfs from from_part to to_part.
586
587 Args:
588 from_part: A string of partition number to be copied from.
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800589 to_part: A string of partition number to be copied to.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800590 """
591 root_dev = self.faft_client.get_root_dev()
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800592 logging.info('Copying kernel from %s to %s. Please wait...' %
593 (from_part, to_part))
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800594 self.faft_client.run_shell_command('dd if=%s of=%s bs=4M' %
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800595 (self._join_part(root_dev, self.KERNEL_MAP[from_part]),
596 self._join_part(root_dev, self.KERNEL_MAP[to_part])))
597 logging.info('Copying rootfs from %s to %s. Please wait...' %
598 (from_part, to_part))
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800599 self.faft_client.run_shell_command('dd if=%s of=%s bs=4M' %
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800600 (self._join_part(root_dev, self.ROOTFS_MAP[from_part]),
601 self._join_part(root_dev, self.ROOTFS_MAP[to_part])))
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800602
603
604 def ensure_kernel_boot(self, part):
605 """Ensure the request kernel boot.
606
607 If not, it duplicates the current kernel to the requested kernel
608 and sets the requested higher priority to ensure it boot.
609
610 Args:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800611 part: A string of kernel partition number or 'a'/'b'.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800612 """
613 if not self.root_part_checker(part):
614 self.copy_kernel_and_rootfs(from_part=self.OTHER_KERNEL_MAP[part],
615 to_part=part)
Tom Wai-Hong Tamc7ecfca2011-12-06 11:12:31 +0800616 self.run_faft_step({
617 'userspace_action': (self.reset_and_prioritize_kernel, part),
618 })
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800619
620
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800621 def send_ctrl_d_to_dut(self):
622 """Send Ctrl-D key to DUT."""
623 if self._customized_ctrl_d_key_command:
624 logging.info('running the customized Ctrl-D key command')
625 os.system(self._customized_ctrl_d_key_command)
626 else:
627 self.servo.ctrl_d()
628
629
630 def send_enter_to_dut(self):
631 """Send Enter key to DUT."""
632 if self._customized_enter_key_command:
633 logging.info('running the customized Enter key command')
634 os.system(self._customized_enter_key_command)
635 else:
636 self.servo.enter_key()
637
638
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800639 def wait_fw_screen_and_ctrl_d(self):
640 """Wait for firmware warning screen and press Ctrl-D."""
641 time.sleep(self.FIRMWARE_SCREEN_DELAY)
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800642 self.send_ctrl_d_to_dut()
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800643
644
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800645 def wait_fw_screen_and_trigger_recovery(self, need_dev_transition=False):
646 """Wait for firmware warning screen and trigger recovery boot."""
647 time.sleep(self.FIRMWARE_SCREEN_DELAY)
648 self.send_enter_to_dut()
649
650 # For Alex/ZGB, there is a dev warning screen in text mode.
651 # Skip it by pressing Ctrl-D.
652 if need_dev_transition:
653 time.sleep(self.TEXT_SCREEN_DELAY)
654 self.send_ctrl_d_to_dut()
655
656
Tom Wai-Hong Tam5d2f4702011-12-06 10:42:31 +0800657 def wait_fw_screen_and_plug_usb(self):
658 """Wait for firmware warning screen and then unplug and plug the USB."""
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +0800659 time.sleep(self.USB_LOAD_DELAY)
Tom Wai-Hong Tam5d2f4702011-12-06 10:42:31 +0800660 self.servo.set('usb_mux_sel1', 'servo_sees_usbkey')
661 time.sleep(self.USB_PLUG_DELAY)
662 self.servo.set('usb_mux_sel1', 'dut_sees_usbkey')
663
664
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800665 def wait_fw_screen_and_press_power(self):
666 """Wait for firmware warning screen and press power button."""
667 time.sleep(self.FIRMWARE_SCREEN_DELAY)
Tom Wai-Hong Tam610262a2012-01-12 14:16:53 +0800668 self.servo.power_short_press()
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800669
670
671 def wait_fw_screen_and_close_lid(self):
672 """Wait for firmware warning screen and close lid."""
673 time.sleep(self.FIRMWARE_SCREEN_DELAY)
674 self.servo.lid_close()
675
676
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800677 def setup_tried_fwb(self, tried_fwb):
678 """Setup for fw B tried state.
679
680 It makes sure the system in the requested fw B tried state. If not, it
681 tries to do so.
682
683 Args:
684 tried_fwb: True if requested in tried_fwb=1; False if tried_fwb=0.
685 """
686 if tried_fwb:
687 if not self.crossystem_checker({'tried_fwb': '1'}):
688 logging.info(
689 'Firmware is not booted with tried_fwb. Reboot into it.')
690 self.run_faft_step({
691 'userspace_action': self.faft_client.set_try_fw_b,
692 })
693 else:
694 if not self.crossystem_checker({'tried_fwb': '0'}):
695 logging.info(
696 'Firmware is booted with tried_fwb. Reboot to clear.')
697 self.run_faft_step({})
698
699
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800700 def enable_dev_mode_and_fw(self):
701 """Enable developer mode and use developer firmware."""
Vic Yange7553162012-06-20 16:20:47 +0800702 if self.client_attr.keyboard_dev:
703 self.enable_keyboard_dev_mode()
704 else:
705 self.servo.enable_development_mode()
706 self.faft_client.run_shell_command(
707 'chromeos-firmwareupdate --mode todev && reboot')
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800708
709
710 def enable_normal_mode_and_fw(self):
711 """Enable normal mode and use normal firmware."""
Vic Yange7553162012-06-20 16:20:47 +0800712 if self.client_attr.keyboard_dev:
713 self.disable_keyboard_dev_mode()
714 else:
715 self.servo.disable_development_mode()
716 self.faft_client.run_shell_command(
717 'chromeos-firmwareupdate --mode tonormal && reboot')
718
719
720 def wait_fw_screen_and_switch_keyboard_dev_mode(self, dev):
721 """Wait for firmware screen and then switch into or out of dev mode.
722
723 Args:
724 dev: True if switching into dev mode. Otherwise, False.
725 """
726 time.sleep(self.FIRMWARE_SCREEN_DELAY)
727 if dev:
728 self.servo.ctrl_d()
729 else:
730 self.servo.enter_key()
731 time.sleep(self.FIRMWARE_KEY_DELAY)
732 self.servo.enter_key()
733
734
735 def enable_keyboard_dev_mode(self):
736 logging.info("Enabling keyboard controlled developer mode")
737 # Rebooting EC with rec mode on. Should power on AP.
738 self.servo.enable_recovery_mode()
739 self.servo.cold_reset()
740 self.wait_fw_screen_and_switch_keyboard_dev_mode(dev=True)
741 self.servo.disable_recovery_mode()
742
743
744 def disable_keyboard_dev_mode(self):
745 logging.info("Disabling keyboard controlled developer mode")
746 self.servo.disable_recovery_mode()
747 self.servo.cold_reset()
748 # Rebooting EC with rec mode off. Software sync should power on AP,
749 # and then shut down AP after a while.
750 # TODO(victoryang): Figure out the proper delay period before pressing
751 # power button after software sync is done.
752 time.sleep(self.POWER_BTN_DELAY)
753 self.servo.power_short_press()
754 self.wait_fw_screen_and_switch_keyboard_dev_mode(dev=False)
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800755
756
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800757 def setup_dev_mode(self, dev_mode):
758 """Setup for development mode.
759
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800760 It makes sure the system in the requested normal/dev mode. If not, it
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800761 tries to do so.
762
763 Args:
764 dev_mode: True if requested in dev mode; False if normal mode.
765 """
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800766 # Change the default firmware_action for dev mode passing the fw screen.
767 self.register_faft_template({
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800768 'firmware_action': (self.wait_fw_screen_and_ctrl_d if dev_mode
769 else None),
770 })
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800771 if dev_mode:
Vic Yange7553162012-06-20 16:20:47 +0800772 if (not self.client_attr.keyboard_dev and
773 not self.crossystem_checker({'devsw_cur': '1'})):
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800774 logging.info('Dev switch is not on. Now switch it on.')
775 self.servo.enable_development_mode()
776 if not self.crossystem_checker({'devsw_boot': '1',
777 'mainfw_type': 'developer'}):
778 logging.info('System is not in dev mode. Reboot into it.')
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800779 self.run_faft_step({
Vic Yange7553162012-06-20 16:20:47 +0800780 'userspace_action': None if self.client_attr.keyboard_dev
781 else (self.faft_client.run_shell_command,
Tom Wai-Hong Tamc7ecfca2011-12-06 11:12:31 +0800782 'chromeos-firmwareupdate --mode todev && reboot'),
Vic Yange7553162012-06-20 16:20:47 +0800783 'reboot_action': self.enable_keyboard_dev_mode if
784 self.client_attr.keyboard_dev else None,
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800785 })
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800786 else:
Vic Yange7553162012-06-20 16:20:47 +0800787 if (not self.client_attr.keyboard_dev and
788 not self.crossystem_checker({'devsw_cur': '0'})):
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800789 logging.info('Dev switch is not off. Now switch it off.')
790 self.servo.disable_development_mode()
791 if not self.crossystem_checker({'devsw_boot': '0',
792 'mainfw_type': 'normal'}):
793 logging.info('System is not in normal mode. Reboot into it.')
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800794 self.run_faft_step({
Vic Yange7553162012-06-20 16:20:47 +0800795 'userspace_action': None if self.client_attr.keyboard_dev
796 else (self.faft_client.run_shell_command,
Tom Wai-Hong Tamc7ecfca2011-12-06 11:12:31 +0800797 'chromeos-firmwareupdate --mode tonormal && reboot'),
Vic Yange7553162012-06-20 16:20:47 +0800798 'reboot_action': self.disable_keyboard_dev_mode if
799 self.client_attr.keyboard_dev else None,
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800800 })
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800801
802
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800803 def setup_kernel(self, part):
804 """Setup for kernel test.
805
806 It makes sure both kernel A and B bootable and the current boot is
807 the requested kernel part.
808
809 Args:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800810 part: A string of kernel partition number or 'a'/'b'.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800811 """
812 self.ensure_kernel_boot(part)
813 self.copy_kernel_and_rootfs(from_part=part,
814 to_part=self.OTHER_KERNEL_MAP[part])
815 self.reset_and_prioritize_kernel(part)
816
817
818 def reset_and_prioritize_kernel(self, part):
819 """Make the requested partition highest priority.
820
821 This function also reset kerenl A and B to bootable.
822
823 Args:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800824 part: A string of partition number to be prioritized.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800825 """
826 root_dev = self.faft_client.get_root_dev()
827 # Reset kernel A and B to bootable.
828 self.faft_client.run_shell_command('cgpt add -i%s -P1 -S1 -T0 %s' %
829 (self.KERNEL_MAP['a'], root_dev))
830 self.faft_client.run_shell_command('cgpt add -i%s -P1 -S1 -T0 %s' %
831 (self.KERNEL_MAP['b'], root_dev))
832 # Set kernel part highest priority.
833 self.faft_client.run_shell_command('cgpt prioritize -i%s %s' %
834 (self.KERNEL_MAP[part], root_dev))
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +0800835 # Safer to sync and wait until the cgpt status written to the disk.
836 self.faft_client.run_shell_command('sync')
837 time.sleep(self.SYNC_DELAY)
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800838
839
Tom Wai-Hong Tamf1e34972011-11-02 17:07:04 +0800840 def sync_and_hw_reboot(self):
841 """Request the client sync and do a warm reboot.
842
843 This is the default reboot action on FAFT.
844 """
845 self.faft_client.run_shell_command('sync')
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +0800846 time.sleep(self.SYNC_DELAY)
Tom Wai-Hong Tamf1e34972011-11-02 17:07:04 +0800847 self.servo.warm_reset()
848
849
Vic Yang59cac9c2012-05-21 15:28:42 +0800850 def sync_and_ec_reboot(self):
851 """Request the client sync and do a EC triggered reboot."""
852 self.faft_client.run_shell_command('sync')
853 time.sleep(self.SYNC_DELAY)
854 self.faft_client.run_shell_command('(sleep %d; ectool reboot_ec)&' %
855 self.EC_REBOOT_DELAY)
856 time.sleep(self.EC_REBOOT_DELAY + self.POWER_BTN_DELAY)
857 self.servo.power_normal_press()
858
859
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800860 def _modify_usb_kernel(self, usb_dev, from_magic, to_magic):
861 """Modify the kernel header magic in USB stick.
862
863 The kernel header magic is the first 8-byte of kernel partition.
864 We modify it to make it fail on kernel verification check.
865
866 Args:
867 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
868 from_magic: A string of magic which we change it from.
869 to_magic: A string of magic which we change it to.
870
871 Raises:
872 error.TestError: if failed to change magic.
873 """
874 assert len(from_magic) == 8
875 assert len(to_magic) == 8
Tom Wai-Hong Tama1d9a0f2011-12-23 09:13:33 +0800876 # USB image only contains one kernel.
877 kernel_part = self._join_part(usb_dev, self.KERNEL_MAP['a'])
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800878 read_cmd = "sudo dd if=%s bs=8 count=1 2>/dev/null" % kernel_part
879 current_magic = utils.system_output(read_cmd)
880 if current_magic == to_magic:
881 logging.info("The kernel magic is already %s." % current_magic)
882 return
883 if current_magic != from_magic:
884 raise error.TestError("Invalid kernel image on USB: wrong magic.")
885
886 logging.info('Modify the kernel magic in USB, from %s to %s.' %
887 (from_magic, to_magic))
888 write_cmd = ("echo -n '%s' | sudo dd of=%s oflag=sync conv=notrunc "
889 " 2>/dev/null" % (to_magic, kernel_part))
890 utils.system(write_cmd)
891
892 if utils.system_output(read_cmd) != to_magic:
893 raise error.TestError("Failed to write new magic.")
894
895
896 def corrupt_usb_kernel(self, usb_dev):
897 """Corrupt USB kernel by modifying its magic from CHROMEOS to CORRUPTD.
898
899 Args:
900 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
901 """
902 self._modify_usb_kernel(usb_dev, self.CHROMEOS_MAGIC,
903 self.CORRUPTED_MAGIC)
904
905
906 def restore_usb_kernel(self, usb_dev):
907 """Restore USB kernel by modifying its magic from CORRUPTD to CHROMEOS.
908
909 Args:
910 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
911 """
912 self._modify_usb_kernel(usb_dev, self.CORRUPTED_MAGIC,
913 self.CHROMEOS_MAGIC)
914
915
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800916 def _call_action(self, action_tuple):
917 """Call the action function with/without arguments.
918
919 Args:
920 action_tuple: A function, or a tuple which consisted of a function
921 and its arguments (if any).
922
923 Returns:
924 The result value of the action function.
925 """
926 if isinstance(action_tuple, tuple):
927 action = action_tuple[0]
928 args = action_tuple[1:]
929 if callable(action):
930 logging.info('calling %s with parameter %s' % (
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +0800931 str(action), str(action_tuple[1])))
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800932 return action(*args)
933 else:
934 logging.info('action is not callable!')
935 else:
936 action = action_tuple
937 if action is not None:
938 if callable(action):
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +0800939 logging.info('calling %s' % str(action))
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800940 return action()
941 else:
942 logging.info('action is not callable!')
943
944 return None
945
946
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800947 def run_shutdown_process(self, shutdown_action, pre_power_action=None,
948 post_power_action=None):
949 """Run shutdown_action(), which makes DUT shutdown, and power it on.
950
951 Args:
952 shutdown_action: a function which makes DUT shutdown, like pressing
953 power key.
954 pre_power_action: a function which is called before next power on.
955 post_power_action: a function which is called after next power on.
956
957 Raises:
958 error.TestFail: if the shutdown_action() failed to turn DUT off.
959 """
960 self._call_action(shutdown_action)
961 logging.info('Wait to ensure DUT shut down...')
962 try:
963 self.wait_for_client()
964 raise error.TestFail(
965 'Should shut the device down after calling %s.' %
966 str(shutdown_action))
967 except AssertionError:
968 logging.info(
969 'DUT is surely shutdown. We are going to power it on again...')
970
971 if pre_power_action:
972 self._call_action(pre_power_action)
Tom Wai-Hong Tam610262a2012-01-12 14:16:53 +0800973 self.servo.power_short_press()
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800974 if post_power_action:
975 self._call_action(post_power_action)
976
977
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800978 def register_faft_template(self, template):
979 """Register FAFT template, the default FAFT_STEP of each step.
980
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +0800981 Any missing field falls back to the original faft_template.
982
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800983 Args:
984 template: A FAFT_STEP dict.
985 """
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +0800986 self._faft_template.update(template)
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800987
988
989 def register_faft_sequence(self, sequence):
990 """Register FAFT sequence.
991
992 Args:
993 sequence: A FAFT_SEQUENCE array which consisted of FAFT_STEP dicts.
994 """
995 self._faft_sequence = sequence
996
997
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +0800998 def run_faft_step(self, step, no_reboot=False):
999 """Run a single FAFT step.
1000
1001 Any missing field falls back to faft_template. An empty step means
1002 running the default faft_template.
1003
1004 Args:
1005 step: A FAFT_STEP dict.
1006 no_reboot: True to prevent running reboot_action and firmware_action.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001007
1008 Raises:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001009 error.TestFail: An error when the test failed.
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +08001010 error.TestError: An error when the given step is not valid.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001011 """
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +08001012 FAFT_STEP_KEYS = ('state_checker', 'userspace_action', 'reboot_action',
1013 'firmware_action', 'install_deps_after_boot')
1014
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001015 test = {}
1016 test.update(self._faft_template)
1017 test.update(step)
1018
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +08001019 for key in test:
1020 if key not in FAFT_STEP_KEYS:
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001021 raise error.TestError('Invalid key in FAFT step: %s', key)
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +08001022
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001023 if test['state_checker']:
1024 if not self._call_action(test['state_checker']):
1025 raise error.TestFail('State checker failed!')
1026
1027 self._call_action(test['userspace_action'])
1028
1029 # Don't run reboot_action and firmware_action if no_reboot is True.
1030 if not no_reboot:
1031 self._call_action(test['reboot_action'])
1032 self.wait_for_client_offline()
1033 self._call_action(test['firmware_action'])
1034
1035 if 'install_deps_after_boot' in test:
1036 self.wait_for_client(
1037 install_deps=test['install_deps_after_boot'])
1038 else:
1039 self.wait_for_client()
1040
1041
1042 def run_faft_sequence(self):
1043 """Run FAFT sequence which was previously registered."""
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001044 sequence = self._faft_sequence
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +08001045 index = 1
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001046 for step in sequence:
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +08001047 logging.info('======== Running FAFT sequence step %d ========' %
1048 index)
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001049 # Don't reboot in the last step.
1050 self.run_faft_step(step, no_reboot=(step is sequence[-1]))
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +08001051 index += 1