blob: a940a1683ec0ab3783359c0fa363b8f4d0ca79c6 [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
Tom Wai-Hong Tam22b77302011-11-03 13:03:48 +080017from autotest_lib.server.cros.servo_test import ServoTest
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +080018from autotest_lib.site_utils import lab_test
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080019
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +080020dirname = os.path.dirname(sys.modules[__name__].__file__)
21autotest_dir = os.path.abspath(os.path.join(dirname, "..", ".."))
22cros_dir = os.path.join(autotest_dir, "..", "..", "..", "..")
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080023
24class FAFTSequence(ServoTest):
25 """
26 The base class of Fully Automated Firmware Test Sequence.
27
28 Many firmware tests require several reboot cycles and verify the resulted
29 system states. To do that, an Autotest test case should detailly handle
30 every action on each step. It makes the test case hard to read and many
31 duplicated code. The base class FAFTSequence is to solve this problem.
32
33 The actions of one reboot cycle is defined in a dict, namely FAFT_STEP.
34 There are four functions in the FAFT_STEP dict:
35 state_checker: a function to check the current is valid or not,
36 returning True if valid, otherwise, False to break the whole
37 test sequence.
38 userspace_action: a function to describe the action ran in userspace.
Tom Wai-Hong Tamf1e34972011-11-02 17:07:04 +080039 reboot_action: a function to do reboot, default: sync_and_hw_reboot.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080040 firmware_action: a function to describe the action ran after reboot.
41
Tom Wai-Hong Tam7c17ff22011-10-26 09:44:09 +080042 And configurations:
43 install_deps_after_boot: if True, install the Autotest dependency after
44 boot; otherwise, do nothing. It is for the cases of recovery mode
45 test. The test boots a USB/SD image instead of an internal image.
46 The previous installed Autotest dependency on the internal image
47 is lost. So need to install it again.
48
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080049 The default FAFT_STEP checks nothing in state_checker and does nothing in
Tom Wai-Hong Tamf1e34972011-11-02 17:07:04 +080050 userspace_action and firmware_action. Its reboot_action is a hardware
51 reboot. You can change the default FAFT_STEP by calling
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080052 self.register_faft_template(FAFT_STEP).
53
54 A FAFT test case consists of several FAFT_STEP's, namely FAFT_SEQUENCE.
55 FAFT_SEQUENCE is an array of FAFT_STEP's. Any missing fields on FAFT_STEP
56 fall back to default.
57
58 In the run_once(), it should register and run FAFT_SEQUENCE like:
59 def run_once(self):
60 self.register_faft_sequence(FAFT_SEQUENCE)
61 self.run_faft_sequnce()
62
63 Note that in the last step, we only run state_checker. The
64 userspace_action, reboot_action, and firmware_action are not executed.
65
66 Attributes:
67 _faft_template: The default FAFT_STEP of each step. The actions would
68 be over-written if the registered FAFT_SEQUENCE is valid.
69 _faft_sequence: The registered FAFT_SEQUENCE.
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +080070 _customized_ctrl_d_key_command: The customized Ctrl-D key command
71 instead of sending key via servo board.
72 _customized_enter_key_command: The customized Enter key command instead
73 of sending key via servo board.
74 _install_image_path: The path of Chrome OS test image to be installed.
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +080075 _firmware_update: Boolean. True if firmware update needed after
76 installing the image.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080077 """
78 version = 1
79
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +080080
81 # Mapping of partition number of kernel and rootfs.
82 KERNEL_MAP = {'a':'2', 'b':'4', '2':'2', '4':'4', '3':'2', '5':'4'}
83 ROOTFS_MAP = {'a':'3', 'b':'5', '2':'3', '4':'5', '3':'3', '5':'5'}
84 OTHER_KERNEL_MAP = {'a':'4', 'b':'2', '2':'4', '4':'2', '3':'4', '5':'2'}
85 OTHER_ROOTFS_MAP = {'a':'5', 'b':'3', '2':'5', '4':'3', '3':'5', '5':'3'}
86
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +080087 # Delay between power-on and firmware screen.
Tom Wai-Hong Tam211ccba2012-01-13 15:35:53 +080088 FIRMWARE_SCREEN_DELAY = 2
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +080089 # Delay between passing firmware screen and text mode warning screen.
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +080090 TEXT_SCREEN_DELAY = 20
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +080091 # Delay of loading the USB kernel.
Tom Wai-Hong Tam07278c22012-02-08 16:53:00 +080092 USB_LOAD_DELAY = 10
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +080093 # Delay between USB plug-out and plug-in.
Tom Wai-Hong Tam9ca742a2011-12-05 15:48:57 +080094 USB_PLUG_DELAY = 10
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +080095 # Delay after running the 'sync' command.
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +080096 SYNC_DELAY = 5
Vic Yang59cac9c2012-05-21 15:28:42 +080097 # Delay for waiting client to return before EC reboot
98 EC_REBOOT_DELAY = 1
99 # Delay between EC reboot and pressing power button
100 POWER_BTN_DELAY = 0.5
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800101
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800102 CHROMEOS_MAGIC = "CHROMEOS"
103 CORRUPTED_MAGIC = "CORRUPTD"
104
Tom Wai-Hong Tamf954d172011-12-08 17:14:15 +0800105 # Recovery reason codes, copied from:
106 # vboot_reference/firmware/lib/vboot_nvstorage.h
107 # vboot_reference/firmware/lib/vboot_struct.h
108 RECOVERY_REASON = {
109 # Recovery not requested
110 'NOT_REQUESTED': '0', # 0x00
111 # Recovery requested from legacy utility
112 'LEGACY': '1', # 0x01
113 # User manually requested recovery via recovery button
114 'RO_MANUAL': '2', # 0x02
115 # RW firmware failed signature check
116 'RO_INVALID_RW': '3', # 0x03
117 # S3 resume failed
118 'RO_S3_RESUME': '4', # 0x04
119 # TPM error in read-only firmware
120 'RO_TPM_ERROR': '5', # 0x05
121 # Shared data error in read-only firmware
122 'RO_SHARED_DATA': '6', # 0x06
123 # Test error from S3Resume()
124 'RO_TEST_S3': '7', # 0x07
125 # Test error from LoadFirmwareSetup()
126 'RO_TEST_LFS': '8', # 0x08
127 # Test error from LoadFirmware()
128 'RO_TEST_LF': '9', # 0x09
129 # RW firmware failed signature check
130 'RW_NOT_DONE': '16', # 0x10
131 'RW_DEV_MISMATCH': '17', # 0x11
132 'RW_REC_MISMATCH': '18', # 0x12
133 'RW_VERIFY_KEYBLOCK': '19', # 0x13
134 'RW_KEY_ROLLBACK': '20', # 0x14
135 'RW_DATA_KEY_PARSE': '21', # 0x15
136 'RW_VERIFY_PREAMBLE': '22', # 0x16
137 'RW_FW_ROLLBACK': '23', # 0x17
138 'RW_HEADER_VALID': '24', # 0x18
139 'RW_GET_FW_BODY': '25', # 0x19
140 'RW_HASH_WRONG_SIZE': '26', # 0x1A
141 'RW_VERIFY_BODY': '27', # 0x1B
142 'RW_VALID': '28', # 0x1C
143 # Read-only normal path requested by firmware preamble, but
144 # unsupported by firmware.
145 'RW_NO_RO_NORMAL': '29', # 0x1D
146 # Firmware boot failure outside of verified boot
147 'RO_FIRMWARE': '32', # 0x20
148 # Recovery mode TPM initialization requires a system reboot.
149 # The system was already in recovery mode for some other reason
150 # when this happened.
151 'RO_TPM_REBOOT': '33', # 0x21
152 # Unspecified/unknown error in read-only firmware
153 'RO_UNSPECIFIED': '63', # 0x3F
154 # User manually requested recovery by pressing a key at developer
155 # warning screen.
156 'RW_DEV_SCREEN': '65', # 0x41
157 # No OS kernel detected
158 'RW_NO_OS': '66', # 0x42
159 # OS kernel failed signature check
160 'RW_INVALID_OS': '67', # 0x43
161 # TPM error in rewritable firmware
162 'RW_TPM_ERROR': '68', # 0x44
163 # RW firmware in dev mode, but dev switch is off.
164 'RW_DEV_MISMATCH': '69', # 0x45
165 # Shared data error in rewritable firmware
166 'RW_SHARED_DATA': '70', # 0x46
167 # Test error from LoadKernel()
168 'RW_TEST_LK': '71', # 0x47
169 # No bootable disk found
170 'RW_NO_DISK': '72', # 0x48
171 # Unspecified/unknown error in rewritable firmware
172 'RW_UNSPECIFIED': '127', # 0x7F
173 # DM-verity error
174 'KE_DM_VERITY': '129', # 0x81
175 # Unspecified/unknown error in kernel
176 'KE_UNSPECIFIED': '191', # 0xBF
177 # Recovery mode test from user-mode
178 'US_TEST': '193', # 0xC1
179 # Unspecified/unknown error in user-mode
180 'US_UNSPECIFIED': '255', # 0xFF
181 }
182
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +0800183 _faft_template = {}
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800184 _faft_sequence = ()
185
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800186 _customized_ctrl_d_key_command = None
187 _customized_enter_key_command = None
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800188 _install_image_path = None
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800189 _firmware_update = False
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800190
191
192 def initialize(self, host, cmdline_args, use_pyauto=False, use_faft=False):
193 # Parse arguments from command line
194 args = {}
195 for arg in cmdline_args:
196 match = re.search("^(\w+)=(.+)", arg)
197 if match:
198 args[match.group(1)] = match.group(2)
199
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800200 # Keep the arguments which will be used later.
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800201 if 'ctrl_d_cmd' in args:
202 self._customized_ctrl_d_key_command = args['ctrl_d_cmd']
203 logging.info('Customized Ctrl-D key command: %s' %
204 self._customized_ctrl_d_key_command)
205 if 'enter_cmd' in args:
206 self._customized_enter_key_command = args['enter_cmd']
207 logging.info('Customized Enter key command: %s' %
208 self._customized_enter_key_command)
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800209 if 'image' in args:
210 self._install_image_path = args['image']
211 logging.info('Install Chrome OS test image path: %s' %
212 self._install_image_path)
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800213 if 'firmware_update' in args and args['firmware_update'].lower() \
214 not in ('0', 'false', 'no'):
215 if self._install_image_path:
216 self._firmware_update = True
217 logging.info('Also update firmware after installing.')
218 else:
219 logging.warning('Firmware update will not not performed '
220 'since no image is specified.')
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800221
222 super(FAFTSequence, self).initialize(host, cmdline_args, use_pyauto,
223 use_faft)
224
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800225
226 def setup(self):
227 """Autotest setup function."""
228 super(FAFTSequence, self).setup()
229 if not self._remote_infos['faft']['used']:
230 raise error.TestError('The use_faft flag should be enabled.')
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800231
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800232 self.register_faft_template({
233 'state_checker': (None),
234 'userspace_action': (None),
Tom Wai-Hong Tamf1e34972011-11-02 17:07:04 +0800235 'reboot_action': (self.sync_and_hw_reboot),
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800236 'firmware_action': (None)
237 })
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800238 if self._install_image_path:
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800239 self.install_test_image(self._install_image_path,
240 self._firmware_update)
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800241
242
243 def cleanup(self):
244 """Autotest cleanup function."""
245 self._faft_sequence = ()
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +0800246 self._faft_template = {}
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800247 super(FAFTSequence, self).cleanup()
248
249
Tom Wai-Hong Tam91f49822011-12-28 15:44:15 +0800250 def assert_test_image_in_usb_disk(self, usb_dev=None):
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800251 """Assert an USB disk plugged-in on servo and a test image inside.
252
Tom Wai-Hong Tam91f49822011-12-28 15:44:15 +0800253 Args:
254 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
255 If None, it is detected automatically.
256
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800257 Raises:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800258 error.TestError: if USB disk not detected or not a test image.
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800259 """
Tom Wai-Hong Tam91f49822011-12-28 15:44:15 +0800260 if usb_dev:
261 assert self.servo.get('usb_mux_sel1') == 'servo_sees_usbkey'
262 else:
263 self.servo.set('usb_mux_sel1', 'servo_sees_usbkey')
264 usb_dev = self.servo.probe_host_usb_dev()
265 if not usb_dev:
266 raise error.TestError(
267 'An USB disk should be plugged in the servo board.')
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800268
269 tmp_dir = tempfile.mkdtemp()
Tom Wai-Hong Tamb0e80852011-12-07 16:15:06 +0800270 utils.system('sudo mount -r -t ext2 %s3 %s' % (usb_dev, tmp_dir))
Tom Wai-Hong Tame77459e2011-11-03 17:19:46 +0800271 code = utils.system(
272 'grep -qE "(Test Build|testimage-channel)" %s/etc/lsb-release' %
273 tmp_dir, ignore_status=True)
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800274 utils.system('sudo umount %s' % tmp_dir)
275 os.removedirs(tmp_dir)
276 if code != 0:
277 raise error.TestError(
278 'The image in the USB disk should be a test image.')
279
280
Simran Basi741b5d42012-05-18 11:27:15 -0700281 def install_test_image(self, image_path=None, firmware_update=False):
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800282 """Install the test image specied by the path onto the USB and DUT disk.
283
284 The method first copies the image to USB disk and reboots into it via
285 recovery mode. Then runs 'chromeos-install' to install it to DUT disk.
286
287 Args:
288 image_path: Path on the host to the test image.
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800289 firmware_update: Also update the firmware after installing.
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800290 """
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800291 install_cmd = 'chromeos-install --yes'
292 if firmware_update:
293 install_cmd += ' && chromeos-firmwareupdate --mode recovery'
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800294 build_ver, build_hash = lab_test.VerifyImageAndGetId(cros_dir,
295 image_path)
296 logging.info('Processing build: %s %s' % (build_ver, build_hash))
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800297
298 # Reuse the install_recovery_image method by using a test image.
299 # Don't wait for completion but run chromeos-install to install it.
Simran Basi741b5d42012-05-18 11:27:15 -0700300 self.servo.install_recovery_image(image_path)
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800301 self.wait_for_client(install_deps=True)
302 self.run_faft_step({
303 'userspace_action': (self.faft_client.run_shell_command,
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800304 install_cmd)
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800305 })
306
307
Vic Yangb4e3e742012-06-02 13:17:38 +0800308 def _open_uart_pty(self):
309 """Open UART pty and spawn pexpect object.
310
311 Returns:
312 Tuple (fd, child): fd is the file descriptor of opened UART pty, and
313 child is a fdpexpect object tied to it.
314 """
315 fd = os.open(self.servo.get("uart1_pty"), os.O_RDWR | os.O_NONBLOCK)
316 child = fdpexpect.fdspawn(fd)
317 return (fd, child)
318
319
320 def _flush_uart_pty(self, child):
321 """Flush UART output to prevent previous pending message interferring.
322
323 Args:
324 child: The fdpexpect object tied to UART pty.
325 """
326 child.sendline("")
327 while True:
328 try:
329 child.expect(".", timeout=0.01)
330 except pexpect.TIMEOUT:
331 break
332
333
334 def _uart_send(self, child, line):
335 """Flush and send command through UART.
336
337 Args:
338 child: The pexpect object tied to UART pty.
339 line: String to send through UART.
340
341 Raises:
342 error.TestFail: Raised when writing to UART fails.
343 """
344 logging.info("Sending UART command: %s" % line)
345 self._flush_uart_pty(child)
346 if child.sendline(line) != len(line) + 1:
347 raise error.TestFail("Failed to send UART command.")
348
349
350 def send_uart_command(self, command):
351 """Send command through UART.
352
353 This function open UART pty when called, and then command is sent
354 through UART.
355
356 Args:
357 command: The command string to send.
358
359 Raises:
360 error.TestFail: Raised when writing to UART fails.
361 """
362 (fd, child) = self._open_uart_pty()
363 try:
364 self._uart_send(child, command)
365 finally:
366 os.close(fd)
367
368
369 def send_uart_command_get_output(self, command, regex_list, timeout=1):
370 """Send command through UART and wait for response.
371
372 This function waits for response message matching regular expressions.
373
374 Args:
375 command: The command sent.
376 regex_list: List of regular expressions used to match response message.
377 Note, list must be ordered.
378
379 Returns:
380 List of match objects of response message.
381
382 Raises:
383 error.TestFail: If timed out waiting for EC response.
384 """
385 if not isinstance(regex_list, list):
386 regex_list = [regex_list]
387 result_list = []
388 (fd, child) = self._open_uart_pty()
389 try:
390 self._uart_send(child, command)
391 for regex in regex_list:
392 child.expect(regex, timeout=timeout)
393 result_list.append(child.match)
394 except pexpect.TIMEOUT:
395 raise error.TestFail("Timeout waiting for UART response.")
396 finally:
397 os.close(fd)
398 return result_list
399
400
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800401 def _parse_crossystem_output(self, lines):
402 """Parse the crossystem output into a dict.
403
404 Args:
405 lines: The list of crossystem output strings.
406
407 Returns:
408 A dict which contains the crossystem keys/values.
409
410 Raises:
411 error.TestError: If wrong format in crossystem output.
412
413 >>> seq = FAFTSequence()
414 >>> seq._parse_crossystem_output([ \
415 "arch = x86 # Platform architecture", \
416 "cros_debug = 1 # OS should allow debug", \
417 ])
418 {'cros_debug': '1', 'arch': 'x86'}
419 >>> seq._parse_crossystem_output([ \
420 "arch=x86", \
421 ])
422 Traceback (most recent call last):
423 ...
424 TestError: Failed to parse crossystem output: arch=x86
425 >>> seq._parse_crossystem_output([ \
426 "arch = x86 # Platform architecture", \
427 "arch = arm # Platform architecture", \
428 ])
429 Traceback (most recent call last):
430 ...
431 TestError: Duplicated crossystem key: arch
432 """
433 pattern = "^([^ =]*) *= *(.*[^ ]) *# [^#]*$"
434 parsed_list = {}
435 for line in lines:
436 matched = re.match(pattern, line.strip())
437 if not matched:
438 raise error.TestError("Failed to parse crossystem output: %s"
439 % line)
440 (name, value) = (matched.group(1), matched.group(2))
441 if name in parsed_list:
442 raise error.TestError("Duplicated crossystem key: %s" % name)
443 parsed_list[name] = value
444 return parsed_list
445
446
447 def crossystem_checker(self, expected_dict):
448 """Check the crossystem values matched.
449
450 Given an expect_dict which describes the expected crossystem values,
451 this function check the current crossystem values are matched or not.
452
453 Args:
454 expected_dict: A dict which contains the expected values.
455
456 Returns:
457 True if the crossystem value matched; otherwise, False.
458 """
459 lines = self.faft_client.run_shell_command_get_output('crossystem')
460 got_dict = self._parse_crossystem_output(lines)
461 for key in expected_dict:
462 if key not in got_dict:
463 logging.info('Expected key "%s" not in crossystem result' % key)
464 return False
465 if isinstance(expected_dict[key], str):
466 if got_dict[key] != expected_dict[key]:
467 logging.info("Expected '%s' value '%s' but got '%s'" %
468 (key, expected_dict[key], got_dict[key]))
469 return False
470 elif isinstance(expected_dict[key], tuple):
471 # Expected value is a tuple of possible actual values.
472 if got_dict[key] not in expected_dict[key]:
473 logging.info("Expected '%s' values %s but got '%s'" %
474 (key, str(expected_dict[key]), got_dict[key]))
475 return False
476 else:
477 logging.info("The expected_dict is neither a str nor a dict.")
478 return False
479 return True
480
481
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800482 def root_part_checker(self, expected_part):
483 """Check the partition number of the root device matched.
484
485 Args:
486 expected_part: A string containing the number of the expected root
487 partition.
488
489 Returns:
490 True if the currect root partition number matched; otherwise, False.
491 """
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +0800492 part = self.faft_client.get_root_part()[-1]
493 if self.ROOTFS_MAP[expected_part] != part:
494 logging.info("Expected root part %s but got %s" %
495 (self.ROOTFS_MAP[expected_part], part))
496 return False
497 return True
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800498
499
Vic Yang59cac9c2012-05-21 15:28:42 +0800500 def ec_act_copy_checker(self, expected_copy):
501 """Check the EC running firmware copy matches.
502
503 Args:
504 expected_copy: A string containing 'RO', 'A', or 'B' indicating
505 the expected copy of EC running firmware.
506
507 Returns:
508 True if the current EC running copy matches; otherwise, False.
509 """
510 lines = self.faft_client.run_shell_command_get_output('ectool version')
511 pattern = re.compile("Firmware copy: (.*)")
512 for line in lines:
513 matched = pattern.match(line)
514 if matched and matched.group(1) == expected_copy:
515 return True
516 return False
517
518
Tom Wai-Hong Tam07278c22012-02-08 16:53:00 +0800519 def check_root_part_on_non_recovery(self, part):
520 """Check the partition number of root device and on normal/dev boot.
521
522 Returns:
523 True if the root device matched and on normal/dev boot;
524 otherwise, False.
525 """
526 return self.root_part_checker(part) and \
527 self.crossystem_checker({
528 'mainfw_type': ('normal', 'developer'),
529 'recoverysw_boot': '0',
530 })
531
532
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800533 def _join_part(self, dev, part):
534 """Return a concatenated string of device and partition number.
535
536 Args:
537 dev: A string of device, e.g.'/dev/sda'.
538 part: A string of partition number, e.g.'3'.
539
540 Returns:
541 A concatenated string of device and partition number, e.g.'/dev/sda3'.
542
543 >>> seq = FAFTSequence()
544 >>> seq._join_part('/dev/sda', '3')
545 '/dev/sda3'
546 >>> seq._join_part('/dev/mmcblk0', '2')
547 '/dev/mmcblk0p2'
548 """
549 if 'mmcblk' in dev:
550 return dev + 'p' + part
551 else:
552 return dev + part
553
554
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800555 def copy_kernel_and_rootfs(self, from_part, to_part):
556 """Copy kernel and rootfs from from_part to to_part.
557
558 Args:
559 from_part: A string of partition number to be copied from.
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800560 to_part: A string of partition number to be copied to.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800561 """
562 root_dev = self.faft_client.get_root_dev()
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800563 logging.info('Copying kernel from %s to %s. Please wait...' %
564 (from_part, to_part))
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800565 self.faft_client.run_shell_command('dd if=%s of=%s bs=4M' %
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800566 (self._join_part(root_dev, self.KERNEL_MAP[from_part]),
567 self._join_part(root_dev, self.KERNEL_MAP[to_part])))
568 logging.info('Copying rootfs from %s to %s. Please wait...' %
569 (from_part, to_part))
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800570 self.faft_client.run_shell_command('dd if=%s of=%s bs=4M' %
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800571 (self._join_part(root_dev, self.ROOTFS_MAP[from_part]),
572 self._join_part(root_dev, self.ROOTFS_MAP[to_part])))
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800573
574
575 def ensure_kernel_boot(self, part):
576 """Ensure the request kernel boot.
577
578 If not, it duplicates the current kernel to the requested kernel
579 and sets the requested higher priority to ensure it boot.
580
581 Args:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800582 part: A string of kernel partition number or 'a'/'b'.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800583 """
584 if not self.root_part_checker(part):
585 self.copy_kernel_and_rootfs(from_part=self.OTHER_KERNEL_MAP[part],
586 to_part=part)
Tom Wai-Hong Tamc7ecfca2011-12-06 11:12:31 +0800587 self.run_faft_step({
588 'userspace_action': (self.reset_and_prioritize_kernel, part),
589 })
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800590
591
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800592 def send_ctrl_d_to_dut(self):
593 """Send Ctrl-D key to DUT."""
594 if self._customized_ctrl_d_key_command:
595 logging.info('running the customized Ctrl-D key command')
596 os.system(self._customized_ctrl_d_key_command)
597 else:
598 self.servo.ctrl_d()
599
600
601 def send_enter_to_dut(self):
602 """Send Enter key to DUT."""
603 if self._customized_enter_key_command:
604 logging.info('running the customized Enter key command')
605 os.system(self._customized_enter_key_command)
606 else:
607 self.servo.enter_key()
608
609
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800610 def wait_fw_screen_and_ctrl_d(self):
611 """Wait for firmware warning screen and press Ctrl-D."""
612 time.sleep(self.FIRMWARE_SCREEN_DELAY)
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800613 self.send_ctrl_d_to_dut()
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800614
615
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800616 def wait_fw_screen_and_trigger_recovery(self, need_dev_transition=False):
617 """Wait for firmware warning screen and trigger recovery boot."""
618 time.sleep(self.FIRMWARE_SCREEN_DELAY)
619 self.send_enter_to_dut()
620
621 # For Alex/ZGB, there is a dev warning screen in text mode.
622 # Skip it by pressing Ctrl-D.
623 if need_dev_transition:
624 time.sleep(self.TEXT_SCREEN_DELAY)
625 self.send_ctrl_d_to_dut()
626
627
Tom Wai-Hong Tam5d2f4702011-12-06 10:42:31 +0800628 def wait_fw_screen_and_plug_usb(self):
629 """Wait for firmware warning screen and then unplug and plug the USB."""
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +0800630 time.sleep(self.USB_LOAD_DELAY)
Tom Wai-Hong Tam5d2f4702011-12-06 10:42:31 +0800631 self.servo.set('usb_mux_sel1', 'servo_sees_usbkey')
632 time.sleep(self.USB_PLUG_DELAY)
633 self.servo.set('usb_mux_sel1', 'dut_sees_usbkey')
634
635
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800636 def wait_fw_screen_and_press_power(self):
637 """Wait for firmware warning screen and press power button."""
638 time.sleep(self.FIRMWARE_SCREEN_DELAY)
Tom Wai-Hong Tam610262a2012-01-12 14:16:53 +0800639 self.servo.power_short_press()
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800640
641
642 def wait_fw_screen_and_close_lid(self):
643 """Wait for firmware warning screen and close lid."""
644 time.sleep(self.FIRMWARE_SCREEN_DELAY)
645 self.servo.lid_close()
646
647
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800648 def setup_tried_fwb(self, tried_fwb):
649 """Setup for fw B tried state.
650
651 It makes sure the system in the requested fw B tried state. If not, it
652 tries to do so.
653
654 Args:
655 tried_fwb: True if requested in tried_fwb=1; False if tried_fwb=0.
656 """
657 if tried_fwb:
658 if not self.crossystem_checker({'tried_fwb': '1'}):
659 logging.info(
660 'Firmware is not booted with tried_fwb. Reboot into it.')
661 self.run_faft_step({
662 'userspace_action': self.faft_client.set_try_fw_b,
663 })
664 else:
665 if not self.crossystem_checker({'tried_fwb': '0'}):
666 logging.info(
667 'Firmware is booted with tried_fwb. Reboot to clear.')
668 self.run_faft_step({})
669
670
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800671 def enable_dev_mode_and_fw(self):
672 """Enable developer mode and use developer firmware."""
673 self.servo.enable_development_mode()
674 self.faft_client.run_shell_command(
675 'chromeos-firmwareupdate --mode todev && reboot')
676
677
678 def enable_normal_mode_and_fw(self):
679 """Enable normal mode and use normal firmware."""
680 self.servo.disable_development_mode()
681 self.faft_client.run_shell_command(
682 'chromeos-firmwareupdate --mode tonormal && reboot')
683
684
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800685 def setup_dev_mode(self, dev_mode):
686 """Setup for development mode.
687
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800688 It makes sure the system in the requested normal/dev mode. If not, it
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800689 tries to do so.
690
691 Args:
692 dev_mode: True if requested in dev mode; False if normal mode.
693 """
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800694 # Change the default firmware_action for dev mode passing the fw screen.
695 self.register_faft_template({
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800696 'firmware_action': (self.wait_fw_screen_and_ctrl_d if dev_mode
697 else None),
698 })
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800699 if dev_mode:
700 if not self.crossystem_checker({'devsw_cur': '1'}):
701 logging.info('Dev switch is not on. Now switch it on.')
702 self.servo.enable_development_mode()
703 if not self.crossystem_checker({'devsw_boot': '1',
704 'mainfw_type': 'developer'}):
705 logging.info('System is not in dev mode. Reboot into it.')
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800706 self.run_faft_step({
707 'userspace_action': (self.faft_client.run_shell_command,
Tom Wai-Hong Tamc7ecfca2011-12-06 11:12:31 +0800708 'chromeos-firmwareupdate --mode todev && reboot'),
709 'reboot_action': None,
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800710 })
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800711 else:
712 if not self.crossystem_checker({'devsw_cur': '0'}):
713 logging.info('Dev switch is not off. Now switch it off.')
714 self.servo.disable_development_mode()
715 if not self.crossystem_checker({'devsw_boot': '0',
716 'mainfw_type': 'normal'}):
717 logging.info('System is not in normal mode. Reboot into it.')
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800718 self.run_faft_step({
719 'userspace_action': (self.faft_client.run_shell_command,
Tom Wai-Hong Tamc7ecfca2011-12-06 11:12:31 +0800720 'chromeos-firmwareupdate --mode tonormal && reboot'),
721 'reboot_action': None,
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800722 })
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800723
724
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800725 def setup_kernel(self, part):
726 """Setup for kernel test.
727
728 It makes sure both kernel A and B bootable and the current boot is
729 the requested kernel part.
730
731 Args:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800732 part: A string of kernel partition number or 'a'/'b'.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800733 """
734 self.ensure_kernel_boot(part)
735 self.copy_kernel_and_rootfs(from_part=part,
736 to_part=self.OTHER_KERNEL_MAP[part])
737 self.reset_and_prioritize_kernel(part)
738
739
740 def reset_and_prioritize_kernel(self, part):
741 """Make the requested partition highest priority.
742
743 This function also reset kerenl A and B to bootable.
744
745 Args:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800746 part: A string of partition number to be prioritized.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800747 """
748 root_dev = self.faft_client.get_root_dev()
749 # Reset kernel A and B to bootable.
750 self.faft_client.run_shell_command('cgpt add -i%s -P1 -S1 -T0 %s' %
751 (self.KERNEL_MAP['a'], root_dev))
752 self.faft_client.run_shell_command('cgpt add -i%s -P1 -S1 -T0 %s' %
753 (self.KERNEL_MAP['b'], root_dev))
754 # Set kernel part highest priority.
755 self.faft_client.run_shell_command('cgpt prioritize -i%s %s' %
756 (self.KERNEL_MAP[part], root_dev))
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +0800757 # Safer to sync and wait until the cgpt status written to the disk.
758 self.faft_client.run_shell_command('sync')
759 time.sleep(self.SYNC_DELAY)
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800760
761
Tom Wai-Hong Tamf1e34972011-11-02 17:07:04 +0800762 def sync_and_hw_reboot(self):
763 """Request the client sync and do a warm reboot.
764
765 This is the default reboot action on FAFT.
766 """
767 self.faft_client.run_shell_command('sync')
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +0800768 time.sleep(self.SYNC_DELAY)
Tom Wai-Hong Tamf1e34972011-11-02 17:07:04 +0800769 self.servo.warm_reset()
770
771
Vic Yang59cac9c2012-05-21 15:28:42 +0800772 def sync_and_ec_reboot(self):
773 """Request the client sync and do a EC triggered reboot."""
774 self.faft_client.run_shell_command('sync')
775 time.sleep(self.SYNC_DELAY)
776 self.faft_client.run_shell_command('(sleep %d; ectool reboot_ec)&' %
777 self.EC_REBOOT_DELAY)
778 time.sleep(self.EC_REBOOT_DELAY + self.POWER_BTN_DELAY)
779 self.servo.power_normal_press()
780
781
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800782 def _modify_usb_kernel(self, usb_dev, from_magic, to_magic):
783 """Modify the kernel header magic in USB stick.
784
785 The kernel header magic is the first 8-byte of kernel partition.
786 We modify it to make it fail on kernel verification check.
787
788 Args:
789 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
790 from_magic: A string of magic which we change it from.
791 to_magic: A string of magic which we change it to.
792
793 Raises:
794 error.TestError: if failed to change magic.
795 """
796 assert len(from_magic) == 8
797 assert len(to_magic) == 8
Tom Wai-Hong Tama1d9a0f2011-12-23 09:13:33 +0800798 # USB image only contains one kernel.
799 kernel_part = self._join_part(usb_dev, self.KERNEL_MAP['a'])
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800800 read_cmd = "sudo dd if=%s bs=8 count=1 2>/dev/null" % kernel_part
801 current_magic = utils.system_output(read_cmd)
802 if current_magic == to_magic:
803 logging.info("The kernel magic is already %s." % current_magic)
804 return
805 if current_magic != from_magic:
806 raise error.TestError("Invalid kernel image on USB: wrong magic.")
807
808 logging.info('Modify the kernel magic in USB, from %s to %s.' %
809 (from_magic, to_magic))
810 write_cmd = ("echo -n '%s' | sudo dd of=%s oflag=sync conv=notrunc "
811 " 2>/dev/null" % (to_magic, kernel_part))
812 utils.system(write_cmd)
813
814 if utils.system_output(read_cmd) != to_magic:
815 raise error.TestError("Failed to write new magic.")
816
817
818 def corrupt_usb_kernel(self, usb_dev):
819 """Corrupt USB kernel by modifying its magic from CHROMEOS to CORRUPTD.
820
821 Args:
822 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
823 """
824 self._modify_usb_kernel(usb_dev, self.CHROMEOS_MAGIC,
825 self.CORRUPTED_MAGIC)
826
827
828 def restore_usb_kernel(self, usb_dev):
829 """Restore USB kernel by modifying its magic from CORRUPTD to CHROMEOS.
830
831 Args:
832 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
833 """
834 self._modify_usb_kernel(usb_dev, self.CORRUPTED_MAGIC,
835 self.CHROMEOS_MAGIC)
836
837
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800838 def _call_action(self, action_tuple):
839 """Call the action function with/without arguments.
840
841 Args:
842 action_tuple: A function, or a tuple which consisted of a function
843 and its arguments (if any).
844
845 Returns:
846 The result value of the action function.
847 """
848 if isinstance(action_tuple, tuple):
849 action = action_tuple[0]
850 args = action_tuple[1:]
851 if callable(action):
852 logging.info('calling %s with parameter %s' % (
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +0800853 str(action), str(action_tuple[1])))
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800854 return action(*args)
855 else:
856 logging.info('action is not callable!')
857 else:
858 action = action_tuple
859 if action is not None:
860 if callable(action):
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +0800861 logging.info('calling %s' % str(action))
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800862 return action()
863 else:
864 logging.info('action is not callable!')
865
866 return None
867
868
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800869 def run_shutdown_process(self, shutdown_action, pre_power_action=None,
870 post_power_action=None):
871 """Run shutdown_action(), which makes DUT shutdown, and power it on.
872
873 Args:
874 shutdown_action: a function which makes DUT shutdown, like pressing
875 power key.
876 pre_power_action: a function which is called before next power on.
877 post_power_action: a function which is called after next power on.
878
879 Raises:
880 error.TestFail: if the shutdown_action() failed to turn DUT off.
881 """
882 self._call_action(shutdown_action)
883 logging.info('Wait to ensure DUT shut down...')
884 try:
885 self.wait_for_client()
886 raise error.TestFail(
887 'Should shut the device down after calling %s.' %
888 str(shutdown_action))
889 except AssertionError:
890 logging.info(
891 'DUT is surely shutdown. We are going to power it on again...')
892
893 if pre_power_action:
894 self._call_action(pre_power_action)
Tom Wai-Hong Tam610262a2012-01-12 14:16:53 +0800895 self.servo.power_short_press()
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800896 if post_power_action:
897 self._call_action(post_power_action)
898
899
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800900 def register_faft_template(self, template):
901 """Register FAFT template, the default FAFT_STEP of each step.
902
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +0800903 Any missing field falls back to the original faft_template.
904
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800905 Args:
906 template: A FAFT_STEP dict.
907 """
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +0800908 self._faft_template.update(template)
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800909
910
911 def register_faft_sequence(self, sequence):
912 """Register FAFT sequence.
913
914 Args:
915 sequence: A FAFT_SEQUENCE array which consisted of FAFT_STEP dicts.
916 """
917 self._faft_sequence = sequence
918
919
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +0800920 def run_faft_step(self, step, no_reboot=False):
921 """Run a single FAFT step.
922
923 Any missing field falls back to faft_template. An empty step means
924 running the default faft_template.
925
926 Args:
927 step: A FAFT_STEP dict.
928 no_reboot: True to prevent running reboot_action and firmware_action.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800929
930 Raises:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800931 error.TestFail: An error when the test failed.
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +0800932 error.TestError: An error when the given step is not valid.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800933 """
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +0800934 FAFT_STEP_KEYS = ('state_checker', 'userspace_action', 'reboot_action',
935 'firmware_action', 'install_deps_after_boot')
936
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +0800937 test = {}
938 test.update(self._faft_template)
939 test.update(step)
940
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +0800941 for key in test:
942 if key not in FAFT_STEP_KEYS:
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800943 raise error.TestError('Invalid key in FAFT step: %s', key)
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +0800944
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +0800945 if test['state_checker']:
946 if not self._call_action(test['state_checker']):
947 raise error.TestFail('State checker failed!')
948
949 self._call_action(test['userspace_action'])
950
951 # Don't run reboot_action and firmware_action if no_reboot is True.
952 if not no_reboot:
953 self._call_action(test['reboot_action'])
954 self.wait_for_client_offline()
955 self._call_action(test['firmware_action'])
956
957 if 'install_deps_after_boot' in test:
958 self.wait_for_client(
959 install_deps=test['install_deps_after_boot'])
960 else:
961 self.wait_for_client()
962
963
964 def run_faft_sequence(self):
965 """Run FAFT sequence which was previously registered."""
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800966 sequence = self._faft_sequence
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +0800967 index = 1
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +0800968 for step in sequence:
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +0800969 logging.info('======== Running FAFT sequence step %d ========' %
970 index)
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +0800971 # Don't reboot in the last step.
972 self.run_faft_step(step, no_reboot=(step is sequence[-1]))
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +0800973 index += 1