1# Copyright (c) 2017 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
5import datetime
6import logging
7import os
8import re
9import time
10
11from autotest_lib.client.bin import utils
12from autotest_lib.client.common_lib import error
13from autotest_lib.server.cros import stress
14from autotest_lib.server.cros.faft.firmware_test import FirmwareTest
15
16class firmware_EmmcWriteLoad(FirmwareTest):
17    """
18    Runs chromeos-install repeatedly while monitoring dmesg output for EMMC
19    timeout errors.
20
21    This test requires a USB disk plugged-in, which contains a Chrome OS test
22    image (built by "build_image test"). On runtime, this test first switches
23    DUT to developer mode. When dev_boot_usb=0, pressing Ctrl-U on developer
24    screen should not boot the USB disk. When dev_boot_usb=1, pressing Ctrl-U
25    should boot the USB disk.
26
27    The length of time in minutes should be specified by the parameter
28    -a 'minutes_to_run=240'
29    """
30    version = 1
31    NEEDS_SERVO_USB = True
32
33    INSTALL_COMMAND = '/usr/sbin/chromeos-install --yes'
34    ERROR_MESSAGE_REGEX = re.compile(
35            r'mmc[0-9]+: Timeout waiting for hardware interrupt', re.MULTILINE)
36
37    def initialize(self, host, cmdline_args, ec_wp=None):
38        """Initialize the test"""
39        dict_args = utils.args_to_dict(cmdline_args)
40        self.minutes_to_run = int(dict_args.get('minutes_to_run', 5))
41        super(firmware_EmmcWriteLoad, self).initialize(
42            host, cmdline_args, ec_wp=ec_wp)
43
44        self.switcher.setup_mode('dev')
45        # Use the USB key for Ctrl-U dev boot, not recovery.
46        self.setup_usbkey(usbkey=True, host=False, used_for_recovery=False)
47
48        self.original_dev_boot_usb = self.faft_client.system.get_dev_boot_usb()
49        logging.info('Original dev_boot_usb value: %s',
50                     str(self.original_dev_boot_usb))
51
52
53    def read_dmesg(self, filename):
54        """Put the contents of 'dmesg -cT' into the given file.
55
56        @param filename: The file to write 'dmesg -cT' into.
57        """
58        with open(filename, 'w') as f:
59            self._client.run('dmesg -cT', stdout_tee=f)
60
61        return utils.read_file(filename)
62
63    def check_for_emmc_error(self, dmesg):
64        """Check the current dmesg output for the specified error message regex.
65
66        @param dmesg: Contents of the dmesg buffer.
67
68        @return True if error found.
69        """
70        for line in dmesg.splitlines():
71            if self.ERROR_MESSAGE_REGEX.search(line):
72                return True
73
74        return False
75
76    def install_chrome_os(self):
77        """Runs the install command. """
78        self.faft_client.system.run_shell_command(self.INSTALL_COMMAND)
79
80    def poll_for_emmc_error(self, dmesg_file, poll_seconds=20):
81        """Continuously polls the contents of dmesg for the emmc failure message
82
83        @param dmesg_file: Contents of the dmesg buffer.
84        @param poll_seconds: Time to wait before checking dmesg again.
85
86        @return True if error found.
87        """
88        end_time = datetime.datetime.now() + \
89                   datetime.timedelta(minutes=self.minutes_to_run)
90
91        while datetime.datetime.now() <= end_time:
92            dmesg = self.read_dmesg(dmesg_file)
93            contains_error = self.check_for_emmc_error(dmesg)
94
95            if contains_error:
96                raise error.TestFail('eMMC error found. Dmesg output: %s' %
97                                     dmesg)
98            time.sleep(poll_seconds)
99
100    def cleanup(self):
101        """Cleanup the test"""
102        try:
103            self.ensure_dev_internal_boot(self.original_dev_boot_usb)
104        except Exception as e:
105            logging.error("Caught exception: %s", str(e))
106        super(firmware_EmmcWriteLoad, self).cleanup()
107
108    def run_once(self):
109        """Main test logic"""
110        self.faft_client.system.set_dev_boot_usb(1)
111        self.switcher.simple_reboot()
112        self.switcher.bypass_dev_boot_usb()
113        self.switcher.wait_for_client()
114
115        logging.info('Expected USB boot, set dev_boot_usb to the original.')
116        self.check_state((self.checkers.dev_boot_usb_checker, (True, True),
117                          'Device not booted from USB image properly.'))
118        stressor = stress.ControlledStressor(self.install_chrome_os)
119
120        dmesg_filename = os.path.join(self.resultsdir, 'dmesg')
121
122        logging.info('===== Starting OS install loop. =====')
123        logging.info('===== Running install for %s minutes. =====',
124                     self.minutes_to_run)
125        stressor.start()
126
127        self.poll_for_emmc_error(dmesg_file=dmesg_filename)
128
129        logging.info('Stopping install loop.')
130        # Usually takes a little over 3 minutes to install so make sure we
131        # wait long enough for a install iteration to complete.
132        stressor.stop(timeout=300)
133
134        logging.info("Installing OS one more time.")
135        # Installing OS one more time to ensure DUT is left in a good state
136        self.install_chrome_os()
137