• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Lint as: python2, python3
2# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
6import re
7import logging
8
9from autotest_lib.client.common_lib import error
10
11
12class FAFTCheckers(object):
13    """Class that contains FAFT checkers."""
14    version = 1
15
16    def __init__(self, faft_framework):
17        self.faft_framework = faft_framework
18        self.faft_client = faft_framework.faft_client
19        self.faft_config = faft_framework.faft_config
20        self.fw_vboot2 = self.faft_client.system.get_fw_vboot2()
21
22    def _parse_crossystem_output(self, lines):
23        """Parse the crossystem output into a dict.
24
25        @param lines: The list of crossystem output strings.
26        @return: A dict which contains the crossystem keys/values.
27        @raise TestError: If wrong format in crossystem output.
28
29        >>> seq = FAFTSequence()
30        >>> seq._parse_crossystem_output([ \
31                "arch          = x86    # Platform architecture", \
32                "cros_debug    = 1      # OS should allow debug", \
33            ])
34        {'cros_debug': '1', 'arch': 'x86'}
35        >>> seq._parse_crossystem_output([ \
36                "arch=x86", \
37            ])
38        Traceback (most recent call last):
39            ...
40        TestError: Failed to parse crossystem output: arch=x86
41        >>> seq._parse_crossystem_output([ \
42                "arch          = x86    # Platform architecture", \
43                "arch          = arm    # Platform architecture", \
44            ])
45        Traceback (most recent call last):
46            ...
47        TestError: Duplicated crossystem key: arch
48        """
49        pattern = "^([^ =]*) *= *(.*[^ ]) *# [^#]*$"
50        parsed_list = {}
51        for line in lines:
52            matched = re.match(pattern, line.strip())
53            if not matched:
54                raise error.TestError("Failed to parse crossystem output: %s"
55                                      % line)
56            (name, value) = (matched.group(1), matched.group(2))
57            if name in parsed_list:
58                raise error.TestError("Duplicated crossystem key: %s" % name)
59            parsed_list[name] = value
60        return parsed_list
61
62    def crossystem_checker(self, expected_dict, suppress_logging=False):
63        """Check the crossystem values matched.
64
65        Given an expect_dict which describes the expected crossystem values,
66        this function check the current crossystem values are matched or not.
67
68        @param expected_dict: A dict which contains the expected values.
69        @param suppress_logging: True to suppress any logging messages.
70        @return: True if the crossystem value matched; otherwise, False.
71        """
72        succeed = True
73        lines = self.faft_client.system.run_shell_command_get_output(
74                'crossystem')
75        got_dict = self._parse_crossystem_output(lines)
76        for key in expected_dict:
77            if key not in got_dict:
78                logging.warning('Expected key %r not in crossystem result', key)
79                succeed = False
80                continue
81            if isinstance(expected_dict[key], str):
82                if got_dict[key] != expected_dict[key]:
83                    message = ('Expected %r value %r but got %r' % (
84                               key, expected_dict[key], got_dict[key]))
85                    succeed = False
86                else:
87                    message = ('Expected %r value %r == real value %r' % (
88                               key, expected_dict[key], got_dict[key]))
89
90            elif isinstance(expected_dict[key], tuple):
91                # Expected value is a tuple of possible actual values.
92                if got_dict[key] not in expected_dict[key]:
93                    message = ('Expected %r values %r but got %r' % (
94                               key, expected_dict[key], got_dict[key]))
95                    succeed = False
96                else:
97                    message = ('Expected %r values %r == real value %r' % (
98                               key, expected_dict[key], got_dict[key]))
99            else:
100                logging.warning('The expected value of %r is neither a str nor a '
101                             'dict: %r', key, expected_dict[key])
102                succeed = False
103                continue
104            if not suppress_logging:
105                logging.info(message)
106        return succeed
107
108    def mode_checker(self, mode):
109        """Check whether the DUT is in the given firmware boot mode.
110
111        @param mode: A string of the expected boot mode: normal, rec, or dev.
112        @return: True if the system in the given mode; otherwise, False.
113        @raise ValueError: If the expected boot mode is not one of normal, rec,
114                           or dev.
115        """
116        if mode not in ('normal', 'rec', 'dev'):
117            raise ValueError(
118                    'Unexpected boot mode %s: want normal, rec, or dev' % mode)
119        return self.faft_client.system.get_boot_mode() == mode
120
121    def fw_tries_checker(self,
122                         expected_mainfw_act,
123                         expected_fw_tried=True,
124                         expected_try_count=0):
125        """Check the current FW booted and try_count
126
127        Mainly for dealing with the vboot1-specific flags fwb_tries and
128        tried_fwb fields in crossystem.  In vboot2, fwb_tries is meaningless and
129        is ignored while tried_fwb is translated into fw_try_count.
130
131        @param expected_mainfw_act: A string of expected firmware, 'A', 'B', or
132                       None if don't care.
133        @param expected_fw_tried: True if tried expected FW at last boot.
134                       This means that mainfw_act=A,tried_fwb=0 or
135                       mainfw_act=B,tried_fwb=1. Set to False if want to
136                       check the opposite case for the mainfw_act.  This
137                       check is only performed in vboot1 as tried_fwb is
138                       never set in vboot2.
139        @param expected_try_count: Number of times to try a FW slot.
140
141        @return: True if the correct boot firmware fields matched.  Otherwise,
142                       False.
143        """
144        crossystem_dict = {'mainfw_act': expected_mainfw_act.upper()}
145
146        if not self.fw_vboot2:
147            if expected_mainfw_act == 'B':
148                tried_fwb_val = True
149            else:
150                tried_fwb_val = False
151            if not expected_fw_tried:
152                tried_fwb_val = not tried_fwb_val
153            crossystem_dict['tried_fwb'] = '1' if tried_fwb_val else '0'
154
155            crossystem_dict['fwb_tries'] = str(expected_try_count)
156        else:
157            crossystem_dict['fw_try_count'] = str(expected_try_count)
158        return self.crossystem_checker(crossystem_dict)
159
160    def dev_boot_usb_checker(self, dev_boot_usb=True, kernel_key_hash=False):
161        """Check the current boot is from a developer USB (Ctrl-U trigger).
162
163        @param dev_boot_usb: True to expect an USB boot;
164                             False to expect an internal device boot.
165        @param kernel_key_hash: True to expect an USB boot with kernkey_vfy
166                                value as 'hash';
167                                False to expect kernkey_vfy value as 'sig'.
168        @return: True if the current boot device matched; otherwise, False.
169        """
170        assert (dev_boot_usb or not kernel_key_hash), ("Invalid condition "
171            "dev_boot_usb_checker(%s, %s). kernel_key_hash should not be "
172            "True in internal disk boot.") % (dev_boot_usb, kernel_key_hash)
173        # kernkey_vfy value will be 'sig', when device booted in internal
174        # disk or booted in USB image signed with SSD key(Ctrl-U trigger).
175        expected_kernkey_vfy = 'sig'
176        if kernel_key_hash:
177            expected_kernkey_vfy = 'hash'
178        return (self.crossystem_checker({'mainfw_type': 'developer',
179                                         'kernkey_vfy':
180                                             expected_kernkey_vfy}) and
181                self.faft_client.system.is_removable_device_boot() ==
182                dev_boot_usb)
183
184    def root_part_checker(self, expected_part):
185        """Check the partition number of the root device matched.
186
187        @param expected_part: A string containing the number of the expected
188                              root partition.
189        @return: True if the currect root  partition number matched;
190                 otherwise, False.
191        """
192        part = self.faft_client.system.get_root_part()[-1]
193        if self.faft_framework.ROOTFS_MAP[expected_part] != part:
194            logging.info("Expected root part %s but got %s",
195                         self.faft_framework.ROOTFS_MAP[expected_part], part)
196            return False
197        return True
198
199    def ec_act_copy_checker(self, expected_copy):
200        """Check the EC running firmware copy matches.
201
202        @param expected_copy: A string containing 'RO', 'A', or 'B' indicating
203                              the expected copy of EC running firmware.
204        @return: True if the current EC running copy matches; otherwise, False.
205        """
206        cmd = 'ectool version'
207        lines = self.faft_client.system.run_shell_command_get_output(cmd)
208        pattern = re.compile("Firmware copy: (.*)")
209        for line in lines:
210            matched = pattern.match(line)
211            if matched:
212                if matched.group(1) == expected_copy:
213                    return True
214                else:
215                    logging.info("Expected EC in %s but now in %s",
216                                 expected_copy, matched.group(1))
217                    return False
218        logging.info("Wrong output format of '%s':\n%s", cmd, '\n'.join(lines))
219        return False
220
221    def minios_checker(self):
222        """Check the current boot is a success MiniOS boot via SSH.
223
224        The DUT with test image should allow SSH connection, and we will use the
225        raw command, host.run_output(), to check since autotest client libraries
226        cannot be installed in MiniOS.
227
228        @return True if DUT booted to MiniOS; otherwise, False.
229        @raise TestError if DUT does not enable MiniOS.
230        """
231
232        if not self.faft_config.minios_enabled:
233            raise error.TestError('MiniOS is not enabled for this board')
234
235        cmdline = self.faft_client.host.run_output('cat /proc/cmdline')
236        return 'cros_minios' in cmdline.split()
237