blob: 5c0efcc60efc1a0ccd009dafdf8d29500f25fc0b [file] [log] [blame]
J. Richard Barnette24adbf42012-04-11 15:04:53 -07001# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
Dale Curtisaa5eedb2011-08-23 16:18:52 -07002# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
Aviv Keshet74c89a92013-02-04 15:18:30 -08005import functools
Darren Krahn0bd18e82015-10-28 23:30:46 +00006import json
J. Richard Barnette1d78b012012-05-15 13:56:30 -07007import logging
Dan Shi0f466e82013-02-22 15:44:58 -08008import os
Simran Basid5e5e272012-09-24 15:23:59 -07009import re
J. Richard Barnette134ec2c2012-04-25 12:59:37 -070010import time
11
mussa584b4462014-06-20 15:13:28 -070012import common
J. Richard Barnette45e93de2012-04-11 17:24:15 -070013from autotest_lib.client.bin import utils
Dan Shi9cb0eec2014-06-03 09:04:50 -070014from autotest_lib.client.common_lib import autotemp
Richard Barnette0c73ffc2012-11-19 15:21:18 -080015from autotest_lib.client.common_lib import error
16from autotest_lib.client.common_lib import global_config
Dan Shi549fb822015-03-24 18:01:11 -070017from autotest_lib.client.common_lib import lsbrelease_utils
J. Richard Barnette45e93de2012-04-11 17:24:15 -070018from autotest_lib.client.common_lib.cros import autoupdater
Richard Barnette03a0c132012-11-05 12:40:35 -080019from autotest_lib.client.common_lib.cros import dev_server
Gabe Blackb72f4fb2015-01-20 16:47:13 -080020from autotest_lib.client.common_lib.cros.graphite import autotest_es
Gabe Black1e1c41b2015-02-04 23:55:15 -080021from autotest_lib.client.common_lib.cros.graphite import autotest_stats
Hsinyu Chaoe0b08e62015-08-11 10:50:37 +000022from autotest_lib.client.cros import constants as client_constants
J. Richard Barnette84890bd2014-02-21 11:05:47 -080023from autotest_lib.client.cros import cros_ui
Cheng-Yi Chiangf4104ff2014-12-23 19:39:01 +080024from autotest_lib.client.cros.audio import cras_utils
Katherine Threlkeldab83d392015-06-18 16:45:57 -070025from autotest_lib.client.cros.input_playback import input_playback
Mussa5b589052015-10-26 17:55:26 -070026from autotest_lib.client.cros.video import constants as video_test_constants
Simran Basi5ace6f22016-01-06 17:30:44 -080027from autotest_lib.server import afe_utils
MK Ryu35d661e2014-09-25 17:44:10 -070028from autotest_lib.server import autoserv_parser
29from autotest_lib.server import autotest
30from autotest_lib.server import constants
31from autotest_lib.server import crashcollect
Dan Shia1ecd5c2013-06-06 11:21:31 -070032from autotest_lib.server import utils as server_utils
Dan Shi9cb0eec2014-06-03 09:04:50 -070033from autotest_lib.server.cros import provision
Scott Zawalski89c44dd2013-02-26 09:28:02 -050034from autotest_lib.server.cros.dynamic_suite import constants as ds_constants
Simran Basi5e6339a2013-03-21 11:34:32 -070035from autotest_lib.server.cros.dynamic_suite import tools, frontend_wrappers
Dan Shi9cb0eec2014-06-03 09:04:50 -070036from autotest_lib.server.cros.faft.config.config import Config as FAFTConfig
Scottfe06ed82015-11-05 17:15:01 -080037from autotest_lib.server.cros.servo import plankton
Fang Deng96667ca2013-08-01 17:46:18 -070038from autotest_lib.server.hosts import abstract_ssh
Tom Wai-Hong Tamefe1c7f2014-01-02 14:00:11 +080039from autotest_lib.server.hosts import chameleon_host
J. Richard Barnettea7e7fdc2016-02-12 12:35:36 -080040from autotest_lib.server.hosts import cros_repair
Scottfe06ed82015-11-05 17:15:01 -080041from autotest_lib.server.hosts import plankton_host
Fang Deng5d518f42013-08-02 14:04:32 -070042from autotest_lib.server.hosts import servo_host
Simran Basidcff4252012-11-20 16:13:20 -080043from autotest_lib.site_utils.rpm_control_system import rpm_client
Simran Basid5e5e272012-09-24 15:23:59 -070044
45
Dan Shib8540a52015-07-16 14:18:23 -070046CONFIG = global_config.global_config
47
Eric Carusoee673ac2015-08-05 17:03:04 -070048LUCID_SLEEP_BOARDS = ['samus', 'lulu']
49
Dan Shid07ee2e2015-09-24 14:49:25 -070050# A file to indicate provision failure and require Repair job to powerwash the
51# dut.
52PROVISION_FAILED = '/var/tmp/provision_failed'
53
beepsc87ff602013-07-31 21:53:00 -070054class FactoryImageCheckerException(error.AutoservError):
55 """Exception raised when an image is a factory image."""
56 pass
57
58
Fang Deng0ca40e22013-08-27 17:47:44 -070059class CrosHost(abstract_ssh.AbstractSSHHost):
J. Richard Barnette45e93de2012-04-11 17:24:15 -070060 """Chromium OS specific subclass of Host."""
61
Simran Basi5ace6f22016-01-06 17:30:44 -080062 VERSION_PREFIX = provision.CROS_VERSION_PREFIX
63
J. Richard Barnette45e93de2012-04-11 17:24:15 -070064 _parser = autoserv_parser.autoserv_parser
Scott Zawalski62bacae2013-03-05 10:40:32 -050065 _AFE = frontend_wrappers.RetryingAFE(timeout_min=5, delay_sec=10)
J. Richard Barnette45e93de2012-04-11 17:24:15 -070066
Richard Barnette03a0c132012-11-05 12:40:35 -080067 # Timeout values (in seconds) associated with various Chrome OS
68 # state changes.
J. Richard Barnette134ec2c2012-04-25 12:59:37 -070069 #
Richard Barnette0c73ffc2012-11-19 15:21:18 -080070 # In general, a good rule of thumb is that the timeout can be up
71 # to twice the typical measured value on the slowest platform.
72 # The times here have not necessarily been empirically tested to
73 # meet this criterion.
J. Richard Barnetteeb69d722012-06-18 17:29:44 -070074 #
75 # SLEEP_TIMEOUT: Time to allow for suspend to memory.
Richard Barnette0c73ffc2012-11-19 15:21:18 -080076 # RESUME_TIMEOUT: Time to allow for resume after suspend, plus
77 # time to restart the netwowrk.
J. Richard Barnette84890bd2014-02-21 11:05:47 -080078 # SHUTDOWN_TIMEOUT: Time to allow for shut down.
J. Richard Barnetteeb69d722012-06-18 17:29:44 -070079 # BOOT_TIMEOUT: Time to allow for boot from power off. Among
Richard Barnette0c73ffc2012-11-19 15:21:18 -080080 # other things, this must account for the 30 second dev-mode
J. Richard Barnette417cc792015-10-01 09:56:36 -070081 # screen delay, time to start the network on the DUT, and the
82 # ssh timeout of 120 seconds.
J. Richard Barnetteeb69d722012-06-18 17:29:44 -070083 # USB_BOOT_TIMEOUT: Time to allow for boot from a USB device,
Richard Barnette0c73ffc2012-11-19 15:21:18 -080084 # including the 30 second dev-mode delay and time to start the
J. Richard Barnetted4649c62013-03-06 17:42:27 -080085 # network.
beepsf079cfb2013-09-18 17:49:51 -070086 # INSTALL_TIMEOUT: Time to allow for chromeos-install.
J. Richard Barnette84890bd2014-02-21 11:05:47 -080087 # POWERWASH_BOOT_TIMEOUT: Time to allow for a reboot that
88 # includes powerwash.
J. Richard Barnetteeb69d722012-06-18 17:29:44 -070089
90 SLEEP_TIMEOUT = 2
J. Richard Barnetted4649c62013-03-06 17:42:27 -080091 RESUME_TIMEOUT = 10
Tom Wai-Hong Tamfe005c22014-12-03 09:25:44 +080092 SHUTDOWN_TIMEOUT = 10
J. Richard Barnette417cc792015-10-01 09:56:36 -070093 BOOT_TIMEOUT = 150
J. Richard Barnette5bab5f52015-08-03 13:14:38 -070094 USB_BOOT_TIMEOUT = 300
J. Richard Barnette7817b052014-08-28 09:47:29 -070095 INSTALL_TIMEOUT = 480
Dan Shi2c88eed2013-11-12 10:18:38 -080096 POWERWASH_BOOT_TIMEOUT = 60
Chris Sosab76e0ee2013-05-22 16:55:41 -070097
Dan Shica503482015-03-30 17:23:25 -070098 # Minimum OS version that supports server side packaging. Older builds may
99 # not have server side package built or with Autotest code change to support
100 # server-side packaging.
Dan Shib8540a52015-07-16 14:18:23 -0700101 MIN_VERSION_SUPPORT_SSP = CONFIG.get_config_value(
Dan Shiced09e42015-04-17 16:09:34 -0700102 'AUTOSERV', 'min_version_support_ssp', type=int)
Dan Shica503482015-03-30 17:23:25 -0700103
J. Richard Barnette84890bd2014-02-21 11:05:47 -0800104 # REBOOT_TIMEOUT: How long to wait for a reboot.
105 #
Chris Sosab76e0ee2013-05-22 16:55:41 -0700106 # We have a long timeout to ensure we don't flakily fail due to other
107 # issues. Shorter timeouts are vetted in platform_RebootAfterUpdate.
Simran Basi1160e2c2013-10-04 16:00:24 -0700108 # TODO(sbasi - crbug.com/276094) Restore to 5 mins once the 'host did not
109 # return from reboot' bug is solved.
110 REBOOT_TIMEOUT = 480
Chris Sosab76e0ee2013-05-22 16:55:41 -0700111
Ismail Noorbasha07fdb612013-02-14 14:13:31 -0800112 # _USB_POWER_TIMEOUT: Time to allow for USB to power toggle ON and OFF.
113 # _POWER_CYCLE_TIMEOUT: Time to allow for manual power cycle.
114 _USB_POWER_TIMEOUT = 5
115 _POWER_CYCLE_TIMEOUT = 10
116
Dan Shib8540a52015-07-16 14:18:23 -0700117 _RPM_RECOVERY_BOARDS = CONFIG.get_config_value('CROS',
Richard Barnette82c35912012-11-20 10:09:10 -0800118 'rpm_recovery_boards', type=str).split(',')
119
120 _MAX_POWER_CYCLE_ATTEMPTS = 6
121 _LAB_MACHINE_FILE = '/mnt/stateful_partition/.labmachine'
Fang Dengdeba14f2014-11-14 11:54:09 -0800122 _RPM_HOSTNAME_REGEX = ('chromeos(\d+)(-row(\d+))?-rack(\d+[a-z]*)'
123 '-host(\d+)')
Katherine Threlkeldab83d392015-06-18 16:45:57 -0700124 _LIGHTSENSOR_FILES = [ "in_illuminance0_input",
125 "in_illuminance_input",
126 "in_illuminance0_raw",
127 "in_illuminance_raw",
128 "illuminance0_input"]
Richard Barnette82c35912012-11-20 10:09:10 -0800129 _LIGHTSENSOR_SEARCH_DIR = '/sys/bus/iio/devices'
130 _LABEL_FUNCTIONS = []
Aviv Keshet74c89a92013-02-04 15:18:30 -0800131 _DETECTABLE_LABELS = []
Kevin Cheng3a4a57a2015-09-30 12:09:50 -0700132 label_decorator = functools.partial(server_utils.add_label_detector,
133 _LABEL_FUNCTIONS,
Aviv Keshet74c89a92013-02-04 15:18:30 -0800134 _DETECTABLE_LABELS)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -0700135
J. Richard Barnetteb6de7e32013-02-14 13:28:04 -0800136 # Constants used in ping_wait_up() and ping_wait_down().
137 #
138 # _PING_WAIT_COUNT is the approximate number of polling
139 # cycles to use when waiting for a host state change.
140 #
141 # _PING_STATUS_DOWN and _PING_STATUS_UP are names used
142 # for arguments to the internal _ping_wait_for_status()
143 # method.
144 _PING_WAIT_COUNT = 40
145 _PING_STATUS_DOWN = False
146 _PING_STATUS_UP = True
147
Ismail Noorbasha07fdb612013-02-14 14:13:31 -0800148 # Allowed values for the power_method argument.
149
150 # POWER_CONTROL_RPM: Passed as default arg for power_off/on/cycle() methods.
151 # POWER_CONTROL_SERVO: Used in set_power() and power_cycle() methods.
152 # POWER_CONTROL_MANUAL: Used in set_power() and power_cycle() methods.
153 POWER_CONTROL_RPM = 'RPM'
154 POWER_CONTROL_SERVO = 'servoj10'
155 POWER_CONTROL_MANUAL = 'manual'
156
157 POWER_CONTROL_VALID_ARGS = (POWER_CONTROL_RPM,
158 POWER_CONTROL_SERVO,
159 POWER_CONTROL_MANUAL)
Richard Barnette0c73ffc2012-11-19 15:21:18 -0800160
Simran Basi5e6339a2013-03-21 11:34:32 -0700161 _RPM_OUTLET_CHANGED = 'outlet_changed'
162
Dan Shi9cb0eec2014-06-03 09:04:50 -0700163 # URL pattern to download firmware image.
Dan Shib8540a52015-07-16 14:18:23 -0700164 _FW_IMAGE_URL_PATTERN = CONFIG.get_config_value(
Dan Shi9cb0eec2014-06-03 09:04:50 -0700165 'CROS', 'firmware_url_pattern', type=str)
beeps687243d2013-07-18 15:29:27 -0700166
MK Ryu35d661e2014-09-25 17:44:10 -0700167 # File that has a list of directories to be collected
168 _LOGS_TO_COLLECT_FILE = os.path.join(
169 common.client_dir, 'common_lib', 'logs_to_collect')
170
171 # Prefix of logging message w.r.t. crash collection
172 _CRASHLOGS_PREFIX = 'collect_crashlogs'
173
174 # Time duration waiting for host up/down check
175 _CHECK_HOST_UP_TIMEOUT_SECS = 15
176
177 # A command that interacts with kernel and hardware (e.g., rm, mkdir, etc)
178 # might not be completely done deep through the hardware when the machine
179 # is powered down right after the command returns.
180 # We should wait for a few seconds to make them done. Finger crossed.
181 _SAFE_WAIT_SECS = 10
182
183
J. Richard Barnette964fba02012-10-24 17:34:29 -0700184 @staticmethod
beeps46dadc92013-11-07 14:07:10 -0800185 def check_host(host, timeout=10):
186 """
187 Check if the given host is a chrome-os host.
188
189 @param host: An ssh host representing a device.
190 @param timeout: The timeout for the run command.
191
192 @return: True if the host device is chromeos.
193
beeps46dadc92013-11-07 14:07:10 -0800194 """
195 try:
Simran Basi933c8af2015-04-29 14:05:07 -0700196 result = host.run(
197 'grep -q CHROMEOS /etc/lsb-release && '
198 '! test -f /mnt/stateful_partition/.android_tester && '
199 '! grep -q moblab /etc/lsb-release',
200 ignore_status=True, timeout=timeout)
beeps46dadc92013-11-07 14:07:10 -0800201 except (error.AutoservRunError, error.AutoservSSHTimeout):
202 return False
203 return result.exit_status == 0
204
205
206 @staticmethod
Tom Wai-Hong Tamefe1c7f2014-01-02 14:00:11 +0800207 def _extract_arguments(args_dict, key_subset):
208 """Extract options from `args_dict` and return a subset result.
J. Richard Barnette7214e0b2013-02-06 15:20:49 -0800209
210 Take the provided dictionary of argument options and return
Tom Wai-Hong Tamefe1c7f2014-01-02 14:00:11 +0800211 a subset that represent standard arguments needed to construct
212 a test-assistant object (chameleon or servo) for a host. The
213 intent is to provide standard argument processing from
Christopher Wiley644ef3e2015-05-15 13:14:14 -0700214 CrosHost for tests that require a test-assistant board
Tom Wai-Hong Tamefe1c7f2014-01-02 14:00:11 +0800215 to operate.
216
217 @param args_dict Dictionary from which to extract the arguments.
218 @param key_subset Tuple of keys to extract from the args_dict, e.g.
219 ('servo_host', 'servo_port').
220 """
221 result = {}
222 for arg in key_subset:
223 if arg in args_dict:
224 result[arg] = args_dict[arg]
225 return result
226
227
228 @staticmethod
229 def get_chameleon_arguments(args_dict):
230 """Extract chameleon options from `args_dict` and return the result.
231
232 Recommended usage:
233 ~~~~~~~~
234 args_dict = utils.args_to_dict(args)
235 chameleon_args = hosts.CrosHost.get_chameleon_arguments(args_dict)
236 host = hosts.create_host(machine, chameleon_args=chameleon_args)
237 ~~~~~~~~
238
239 @param args_dict Dictionary from which to extract the chameleon
240 arguments.
241 """
242 return CrosHost._extract_arguments(
243 args_dict, ('chameleon_host', 'chameleon_port'))
244
245
246 @staticmethod
Scottfe06ed82015-11-05 17:15:01 -0800247 def get_plankton_arguments(args_dict):
248 """Extract chameleon options from `args_dict` and return the result.
249
250 Recommended usage:
251 ~~~~~~~~
252 args_dict = utils.args_to_dict(args)
253 plankon_args = hosts.CrosHost.get_plankton_arguments(args_dict)
254 host = hosts.create_host(machine, plankton_args=polankton_args)
255 ~~~~~~~~
256
257 @param args_dict Dictionary from which to extract the plankton
258 arguments.
259 """
260 args = CrosHost._extract_arguments(
261 args_dict, ('plankton_host', 'plankton_port'))
262 return args
263
264
265 @staticmethod
Tom Wai-Hong Tamefe1c7f2014-01-02 14:00:11 +0800266 def get_servo_arguments(args_dict):
267 """Extract servo options from `args_dict` and return the result.
J. Richard Barnette7214e0b2013-02-06 15:20:49 -0800268
269 Recommended usage:
270 ~~~~~~~~
271 args_dict = utils.args_to_dict(args)
Fang Deng0ca40e22013-08-27 17:47:44 -0700272 servo_args = hosts.CrosHost.get_servo_arguments(args_dict)
J. Richard Barnette7214e0b2013-02-06 15:20:49 -0800273 host = hosts.create_host(machine, servo_args=servo_args)
274 ~~~~~~~~
275
276 @param args_dict Dictionary from which to extract the servo
277 arguments.
278 """
Tom Wai-Hong Tamefe1c7f2014-01-02 14:00:11 +0800279 return CrosHost._extract_arguments(
280 args_dict, ('servo_host', 'servo_port'))
J. Richard Barnette134ec2c2012-04-25 12:59:37 -0700281
J. Richard Barnette964fba02012-10-24 17:34:29 -0700282
Scottfe06ed82015-11-05 17:15:01 -0800283 def _initialize(self, hostname, chameleon_args=None, servo_args=None, plankton_args=None,
Fang Denge545abb2014-12-30 18:43:47 -0800284 try_lab_servo=False, ssh_verbosity_flag='', ssh_options='',
Fang Dengd1c2b732013-08-20 12:59:46 -0700285 *args, **dargs):
Tom Wai-Hong Tamefe1c7f2014-01-02 14:00:11 +0800286 """Initialize superclasses, |self.chameleon|, and |self.servo|.
J. Richard Barnette67ccb872012-04-19 16:34:56 -0700287
Fang Denge545abb2014-12-30 18:43:47 -0800288 This method will attempt to create the test-assistant object
289 (chameleon/servo) when it is needed by the test. Check
290 the docstring of chameleon_host.create_chameleon_host and
291 servo_host.create_servo_host for how this is determined.
Fang Deng5d518f42013-08-02 14:04:32 -0700292
Fang Denge545abb2014-12-30 18:43:47 -0800293 @param hostname: Hostname of the dut.
294 @param chameleon_args: A dictionary that contains args for creating
295 a ChameleonHost. See chameleon_host for details.
296 @param servo_args: A dictionary that contains args for creating
297 a ServoHost object. See servo_host for details.
298 @param try_lab_servo: Boolean, False indicates that ServoHost should
299 not be created for a device in Cros test lab.
300 See servo_host for details.
301 @param ssh_verbosity_flag: String, to pass to the ssh command to control
302 verbosity.
303 @param ssh_options: String, other ssh options to pass to the ssh
304 command.
J. Richard Barnette67ccb872012-04-19 16:34:56 -0700305 """
Fang Deng0ca40e22013-08-27 17:47:44 -0700306 super(CrosHost, self)._initialize(hostname=hostname,
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700307 *args, **dargs)
J. Richard Barnettea7e7fdc2016-02-12 12:35:36 -0800308 self._repair_strategy = cros_repair.create_repair_strategy()
J. Richard Barnettef0859852012-08-20 14:55:50 -0700309 # self.env is a dictionary of environment variable settings
310 # to be exported for commands run on the host.
311 # LIBC_FATAL_STDERR_ can be useful for diagnosing certain
312 # errors that might happen.
313 self.env['LIBC_FATAL_STDERR_'] = '1'
Fang Dengd1c2b732013-08-20 12:59:46 -0700314 self._ssh_verbosity_flag = ssh_verbosity_flag
Aviv Keshetc5947fa2013-09-04 14:06:29 -0700315 self._ssh_options = ssh_options
Fang Deng5d518f42013-08-02 14:04:32 -0700316 # TODO(fdeng): We need to simplify the
317 # process of servo and servo_host initialization.
318 # crbug.com/298432
Fang Denge545abb2014-12-30 18:43:47 -0800319 self._servo_host = servo_host.create_servo_host(
320 dut=self.hostname, servo_args=servo_args,
321 try_lab_servo=try_lab_servo)
Tom Wai-Hong Tamefe1c7f2014-01-02 14:00:11 +0800322 # TODO(waihong): Do the simplication on Chameleon too.
Tom Wai-Hong Tam3d6790d2014-04-14 16:15:47 +0800323 self._chameleon_host = chameleon_host.create_chameleon_host(
324 dut=self.hostname, chameleon_args=chameleon_args)
Scottfe06ed82015-11-05 17:15:01 -0800325 # Add plankton host if plankton args were added on command line
326 self._plankton_host = plankton_host.create_plankton_host(plankton_args)
Tom Wai-Hong Tam3d6790d2014-04-14 16:15:47 +0800327
Dan Shi4d478522014-02-14 13:46:32 -0800328 if self._servo_host is not None:
329 self.servo = self._servo_host.get_servo()
330 else:
331 self.servo = None
332
Tom Wai-Hong Tam3d6790d2014-04-14 16:15:47 +0800333 if self._chameleon_host:
Tom Wai-Hong Tameaee3402014-01-22 08:52:10 +0800334 self.chameleon = self._chameleon_host.create_chameleon_board()
Tom Wai-Hong Tamefe1c7f2014-01-02 14:00:11 +0800335 else:
Tom Wai-Hong Tam3d6790d2014-04-14 16:15:47 +0800336 self.chameleon = None
Fang Deng5d518f42013-08-02 14:04:32 -0700337
Scottfe06ed82015-11-05 17:15:01 -0800338 if self._plankton_host:
339 self.plankton_servo = self._plankton_host.get_servo()
340 logging.info('plankton_servo: %r', self.plankton_servo)
341 # Create the plankton object used to access the ec uart
Scott07a848f2016-01-12 15:04:52 -0800342 self.plankton = plankton.Plankton(self.plankton_servo,
343 self._plankton_host.get_servod_server_proxy())
Scottfe06ed82015-11-05 17:15:01 -0800344 else:
Scott07a848f2016-01-12 15:04:52 -0800345 self.plankton = None
Scottfe06ed82015-11-05 17:15:01 -0800346
Fang Deng5d518f42013-08-02 14:04:32 -0700347
Dan Shi3d7a0e12015-10-12 11:55:45 -0700348 def get_repair_image_name(self, image_type='cros'):
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500349 """Generate a image_name from variables in the global config.
350
Dan Shi3d7a0e12015-10-12 11:55:45 -0700351 image_type is used to differentiate different images. Default is CrOS,
352 in which case, repair image's name follows the naming convention defined
353 in global setting CROS/stable_build_pattern.
354 If the image_type is not `cros`, the repair image will be looked up
355 using key `board_name/image_type`, e.g., daisy_spring/firmware.
356
357 @param image_type: Type of the image. Default is `cros`.
358
Dan Shi08173202015-11-12 13:08:45 -0800359 @returns a str of $board-version/$BUILD. Returns None if stable version
360 for the board and the default are both not set, e.g., stable
361 firmware version for a new board.
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500362
363 """
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500364 board = self._get_board_from_afe()
365 if board is None:
366 raise error.AutoservError('DUT has no board attribute, '
367 'cannot be repaired.')
Dan Shi3d7a0e12015-10-12 11:55:45 -0700368 if image_type != 'cros':
369 board = '%s/%s' % (board, image_type)
Simran Basibeb2bb22016-02-03 15:25:48 -0800370 stable_version = afe_utils.get_stable_version(board=board)
Dan Shi3d7a0e12015-10-12 11:55:45 -0700371 if image_type == 'cros':
372 build_pattern = CONFIG.get_config_value(
373 'CROS', 'stable_build_pattern')
374 stable_version = build_pattern % (board, stable_version)
Dan Shi08173202015-11-12 13:08:45 -0800375 elif image_type == 'firmware':
376 # If firmware stable version is not specified, `stable_version`
377 # from the RPC is the default stable version for CrOS image.
378 # firmware stable version must be from firmware branch, thus its
379 # value must be like board-firmware/R31-1234.0.0. Check if
380 # firmware exists in the stable version, if not, return None.
381 if 'firmware' not in stable_version:
382 return None
Dan Shi3d7a0e12015-10-12 11:55:45 -0700383 return stable_version
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500384
385
Chris Sosab76e0ee2013-05-22 16:55:41 -0700386 def lookup_job_repo_url(self):
387 """Looks up the job_repo_url for the host.
388
Dan Shi8190eb82016-02-11 17:15:58 -0800389 This is kept for backwards compatibility as AU test code in older
390 branch does not use server-side packaging and calls this method through
391 the host object.
392
393 TODO(dshi): Once R50 falls off the stable branch, we should remove this
394 method.
395
Chris Sosab76e0ee2013-05-22 16:55:41 -0700396 @returns job_repo_url from AFE or None if not found.
397
398 @raises KeyError if the host does not have a job_repo_url
399 """
Dan Shibe3636a2016-02-14 22:48:01 -0800400 return afe_utils.get_host_attribute(self, ds_constants.JOB_REPO_URL)
beepscb6f1e22013-06-28 19:14:10 -0700401
402
beepsdae65fd2013-07-26 16:24:41 -0700403 def verify_job_repo_url(self, tag=''):
beepscb6f1e22013-06-28 19:14:10 -0700404 """
405 Make sure job_repo_url of this host is valid.
406
joychen03eaad92013-06-26 09:55:21 -0700407 Eg: The job_repo_url "http://lmn.cd.ab.xyx:8080/static/\
beepscb6f1e22013-06-28 19:14:10 -0700408 lumpy-release/R29-4279.0.0/autotest/packages" claims to have the
409 autotest package for lumpy-release/R29-4279.0.0. If this isn't the case,
410 download and extract it. If the devserver embedded in the url is
411 unresponsive, update the job_repo_url of the host after staging it on
412 another devserver.
413
414 @param job_repo_url: A url pointing to the devserver where the autotest
415 package for this build should be staged.
beepsdae65fd2013-07-26 16:24:41 -0700416 @param tag: The tag from the server job, in the format
417 <job_id>-<user>/<hostname>, or <hostless> for a server job.
beepscb6f1e22013-06-28 19:14:10 -0700418
419 @raises DevServerException: If we could not resolve a devserver.
420 @raises AutoservError: If we're unable to save the new job_repo_url as
421 a result of choosing a new devserver because the old one failed to
422 respond to a health check.
beeps0c865032013-07-30 11:37:06 -0700423 @raises urllib2.URLError: If the devserver embedded in job_repo_url
424 doesn't respond within the timeout.
beepscb6f1e22013-06-28 19:14:10 -0700425 """
Dan Shibe3636a2016-02-14 22:48:01 -0800426 job_repo_url = afe_utils.get_host_attribute(self,
427 ds_constants.JOB_REPO_URL)
beepscb6f1e22013-06-28 19:14:10 -0700428 if not job_repo_url:
429 logging.warning('No job repo url set on host %s', self.hostname)
430 return
431
432 logging.info('Verifying job repo url %s', job_repo_url)
433 devserver_url, image_name = tools.get_devserver_build_from_package_url(
434 job_repo_url)
435
beeps0c865032013-07-30 11:37:06 -0700436 ds = dev_server.ImageServer(devserver_url)
beepscb6f1e22013-06-28 19:14:10 -0700437
438 logging.info('Staging autotest artifacts for %s on devserver %s',
439 image_name, ds.url())
beeps687243d2013-07-18 15:29:27 -0700440
441 start_time = time.time()
Simran Basi25e7a922014-10-31 11:56:10 -0700442 ds.stage_artifacts(image_name, ['autotest_packages'])
beeps687243d2013-07-18 15:29:27 -0700443 stage_time = time.time() - start_time
444
445 # Record how much of the verification time comes from a devserver
446 # restage. If we're doing things right we should not see multiple
447 # devservers for a given board/build/branch path.
448 try:
J. Richard Barnette3cbd76b2013-11-27 12:11:25 -0800449 board, build_type, branch = server_utils.ParseBuildName(
beeps687243d2013-07-18 15:29:27 -0700450 image_name)[:3]
J. Richard Barnette3cbd76b2013-11-27 12:11:25 -0800451 except server_utils.ParseBuildNameException:
beeps687243d2013-07-18 15:29:27 -0700452 pass
453 else:
beeps0c865032013-07-30 11:37:06 -0700454 devserver = devserver_url[
Chris Sosa65425082013-10-16 13:26:22 -0700455 devserver_url.find('/') + 2:devserver_url.rfind(':')]
beeps687243d2013-07-18 15:29:27 -0700456 stats_key = {
457 'board': board,
458 'build_type': build_type,
459 'branch': branch,
beeps0c865032013-07-30 11:37:06 -0700460 'devserver': devserver.replace('.', '_'),
beeps687243d2013-07-18 15:29:27 -0700461 }
Gabe Black1e1c41b2015-02-04 23:55:15 -0800462 autotest_stats.Gauge('verify_job_repo_url').send(
beeps687243d2013-07-18 15:29:27 -0700463 '%(board)s.%(build_type)s.%(branch)s.%(devserver)s' % stats_key,
464 stage_time)
beepscb6f1e22013-06-28 19:14:10 -0700465
Scott Zawalskieadbf702013-03-14 09:23:06 -0400466
Dan Shicf4d2032015-03-12 15:04:21 -0700467 def stage_server_side_package(self, image=None):
468 """Stage autotest server-side package on devserver.
469
470 @param image: Full path of an OS image to install or a build name.
471
472 @return: A url to the autotest server-side package.
473 """
474 if image:
475 image_name = tools.get_build_from_image(image)
476 if not image_name:
477 raise error.AutoservError(
478 'Failed to parse build name from %s' % image)
479 ds = dev_server.ImageServer.resolve(image_name)
480 else:
Dan Shibe3636a2016-02-14 22:48:01 -0800481 job_repo_url = afe_utils.get_host_attribute(
482 self, ds_constants.JOB_REPO_URL)
Dan Shicf4d2032015-03-12 15:04:21 -0700483 if job_repo_url:
484 devserver_url, image_name = (
485 tools.get_devserver_build_from_package_url(job_repo_url))
486 ds = dev_server.ImageServer(devserver_url)
487 else:
488 labels = self._AFE.get_labels(
489 name__startswith=ds_constants.VERSION_PREFIX,
490 host__hostname=self.hostname)
491 if not labels:
492 raise error.AutoservError(
493 'Failed to stage server-side package. The host has '
494 'no job_report_url attribute or version label.')
495 image_name = labels[0].name[len(ds_constants.VERSION_PREFIX):]
496 ds = dev_server.ImageServer.resolve(image_name)
Dan Shica503482015-03-30 17:23:25 -0700497
498 # Get the OS version of the build, for any build older than
499 # MIN_VERSION_SUPPORT_SSP, server side packaging is not supported.
500 match = re.match('.*/R\d+-(\d+)\.', image_name)
501 if match and int(match.group(1)) < self.MIN_VERSION_SUPPORT_SSP:
502 logging.warn('Build %s is older than %s. Server side packaging is '
503 'disabled.', image_name, self.MIN_VERSION_SUPPORT_SSP)
504 return None
505
Dan Shicf4d2032015-03-12 15:04:21 -0700506 ds.stage_artifacts(image_name, ['autotest_server_package'])
507 return '%s/static/%s/%s' % (ds.url(), image_name,
508 'autotest_server_package.tar.bz2')
509
510
Dan Shi0f466e82013-02-22 15:44:58 -0800511 def _try_stateful_update(self, update_url, force_update, updater):
512 """Try to use stateful update to initialize DUT.
513
514 When DUT is already running the same version that machine_install
515 tries to install, stateful update is a much faster way to clean up
516 the DUT for testing, compared to a full reimage. It is implemeted
517 by calling autoupdater.run_update, but skipping updating root, as
518 updating the kernel is time consuming and not necessary.
519
520 @param update_url: url of the image.
521 @param force_update: Set to True to update the image even if the DUT
522 is running the same version.
523 @param updater: ChromiumOSUpdater instance used to update the DUT.
524 @returns: True if the DUT was updated with stateful update.
525
526 """
Dan Shi10b98482016-02-02 14:38:50 -0800527 # Stop service ap-update-manager to prevent rebooting during autoupdate.
528 # The service is used in jetstream boards, but not other CrOS devices.
529 self.run('sudo stop ap-update-manager', ignore_status=True)
530
J. Richard Barnette3f731032014-04-07 17:42:59 -0700531 # TODO(jrbarnette): Yes, I hate this re.match() test case.
532 # It's better than the alternative: see crbug.com/360944.
533 image_name = autoupdater.url_to_image_name(update_url)
534 release_pattern = r'^.*-release/R[0-9]+-[0-9]+\.[0-9]+\.0$'
535 if not re.match(release_pattern, image_name):
536 return False
Dan Shi0f466e82013-02-22 15:44:58 -0800537 if not updater.check_version():
538 return False
539 if not force_update:
540 logging.info('Canceling stateful update because the new and '
541 'old versions are the same.')
542 return False
543 # Following folders should be rebuilt after stateful update.
544 # A test file is used to confirm each folder gets rebuilt after
545 # the stateful update.
546 folders_to_check = ['/var', '/home', '/mnt/stateful_partition']
547 test_file = '.test_file_to_be_deleted'
548 for folder in folders_to_check:
549 touch_path = os.path.join(folder, test_file)
550 self.run('touch %s' % touch_path)
551
Chris Sosae92399e2015-04-24 11:32:59 -0700552 updater.run_update(update_root=False)
Dan Shi0f466e82013-02-22 15:44:58 -0800553
554 # Reboot to complete stateful update.
Chris Sosab76e0ee2013-05-22 16:55:41 -0700555 self.reboot(timeout=self.REBOOT_TIMEOUT, wait=True)
Dan Shi0f466e82013-02-22 15:44:58 -0800556 check_file_cmd = 'test -f %s; echo $?'
557 for folder in folders_to_check:
558 test_file_path = os.path.join(folder, test_file)
559 result = self.run(check_file_cmd % test_file_path,
560 ignore_status=True)
561 if result.exit_status == 1:
562 return False
563 return True
564
565
J. Richard Barnette7275b612013-06-04 18:13:11 -0700566 def _post_update_processing(self, updater, expected_kernel=None):
Dan Shi0f466e82013-02-22 15:44:58 -0800567 """After the DUT is updated, confirm machine_install succeeded.
568
569 @param updater: ChromiumOSUpdater instance used to update the DUT.
J. Richard Barnette7275b612013-06-04 18:13:11 -0700570 @param expected_kernel: kernel expected to be active after reboot,
571 or `None` to skip rollback checking.
Dan Shi0f466e82013-02-22 15:44:58 -0800572
573 """
J. Richard Barnette7275b612013-06-04 18:13:11 -0700574 # Touch the lab machine file to leave a marker that
575 # distinguishes this image from other test images.
576 # Afterwards, we must re-run the autoreboot script because
577 # it depends on the _LAB_MACHINE_FILE.
J. Richard Barnette71cc1862015-12-02 10:32:38 -0800578 autoreboot_cmd = ('FILE="%s" ; [ -f "$FILE" ] || '
579 '( touch "$FILE" ; start autoreboot )')
580 self.run(autoreboot_cmd % self._LAB_MACHINE_FILE)
Chris Sosa65425082013-10-16 13:26:22 -0700581 updater.verify_boot_expectations(
582 expected_kernel, rollback_message=
Gilad Arnoldc26ae1f2015-10-22 16:09:41 -0700583 'Build %s failed to boot on %s; system rolled back to previous '
Chris Sosa65425082013-10-16 13:26:22 -0700584 'build' % (updater.update_version, self.hostname))
J. Richard Barnette7275b612013-06-04 18:13:11 -0700585 # Check that we've got the build we meant to install.
586 if not updater.check_version_to_confirm_install():
587 raise autoupdater.ChromiumOSError(
588 'Failed to update %s to build %s; found build '
589 '%s instead' % (self.hostname,
Chris Sosa65425082013-10-16 13:26:22 -0700590 updater.update_version,
Dan Shi0942b1d2015-03-31 11:07:00 -0700591 self.get_release_version()))
Dan Shi0f466e82013-02-22 15:44:58 -0800592
Chris Sosae92399e2015-04-24 11:32:59 -0700593 logging.debug('Cleaning up old autotest directories.')
594 try:
595 installed_autodir = autotest.Autotest.get_installed_autodir(self)
596 self.run('rm -rf ' + installed_autodir)
597 except autotest.AutodirNotFoundError:
598 logging.debug('No autotest installed directory found.')
599
Dan Shi0f466e82013-02-22 15:44:58 -0800600
J. Richard Barnettee4af8b92013-05-01 13:16:12 -0700601 def _stage_image_for_update(self, image_name=None):
Chris Sosae92399e2015-04-24 11:32:59 -0700602 """Stage a build on a devserver and return the update_url and devserver.
Scott Zawalskieadbf702013-03-14 09:23:06 -0400603
604 @param image_name: a name like lumpy-release/R27-3837.0.0
Chris Sosae92399e2015-04-24 11:32:59 -0700605 @returns a tuple with an update URL like:
Scott Zawalskieadbf702013-03-14 09:23:06 -0400606 http://172.22.50.205:8082/update/lumpy-release/R27-3837.0.0
Chris Sosae92399e2015-04-24 11:32:59 -0700607 and the devserver instance.
Scott Zawalskieadbf702013-03-14 09:23:06 -0400608 """
J. Richard Barnettee4af8b92013-05-01 13:16:12 -0700609 if not image_name:
610 image_name = self.get_repair_image_name()
Chris Sosae92399e2015-04-24 11:32:59 -0700611
J. Richard Barnettee4af8b92013-05-01 13:16:12 -0700612 logging.info('Staging build for AU: %s', image_name)
Dan Shi216389c2015-12-22 11:03:06 -0800613 devserver = dev_server.ImageServer.resolve(image_name, self.hostname)
Scott Zawalskieadbf702013-03-14 09:23:06 -0400614 devserver.trigger_download(image_name, synchronous=False)
Chris Sosae92399e2015-04-24 11:32:59 -0700615 return (tools.image_url_pattern() % (devserver.url(), image_name),
616 devserver)
Scott Zawalskieadbf702013-03-14 09:23:06 -0400617
618
J. Richard Barnettee4af8b92013-05-01 13:16:12 -0700619 def stage_image_for_servo(self, image_name=None):
620 """Stage a build on a devserver and return the update_url.
621
622 @param image_name: a name like lumpy-release/R27-3837.0.0
623 @returns an update URL like:
624 http://172.22.50.205:8082/update/lumpy-release/R27-3837.0.0
625 """
626 if not image_name:
627 image_name = self.get_repair_image_name()
628 logging.info('Staging build for servo install: %s', image_name)
Dan Shi216389c2015-12-22 11:03:06 -0800629 devserver = dev_server.ImageServer.resolve(image_name, self.hostname)
J. Richard Barnettee4af8b92013-05-01 13:16:12 -0700630 devserver.stage_artifacts(image_name, ['test_image'])
631 return devserver.get_test_image_url(image_name)
632
633
beepse539be02013-07-31 21:57:39 -0700634 def stage_factory_image_for_servo(self, image_name):
635 """Stage a build on a devserver and return the update_url.
636
637 @param image_name: a name like <baord>/4262.204.0
beeps12c0a3c2013-09-03 11:58:27 -0700638
beepse539be02013-07-31 21:57:39 -0700639 @return: An update URL, eg:
640 http://<devserver>/static/canary-channel/\
641 <board>/4262.204.0/factory_test/chromiumos_factory_image.bin
beeps12c0a3c2013-09-03 11:58:27 -0700642
643 @raises: ValueError if the factory artifact name is missing from
644 the config.
645
beepse539be02013-07-31 21:57:39 -0700646 """
647 if not image_name:
648 logging.error('Need an image_name to stage a factory image.')
649 return
650
Dan Shib8540a52015-07-16 14:18:23 -0700651 factory_artifact = CONFIG.get_config_value(
beeps12c0a3c2013-09-03 11:58:27 -0700652 'CROS', 'factory_artifact', type=str, default='')
653 if not factory_artifact:
654 raise ValueError('Cannot retrieve the factory artifact name from '
655 'autotest config, and hence cannot stage factory '
656 'artifacts.')
657
beepse539be02013-07-31 21:57:39 -0700658 logging.info('Staging build for servo install: %s', image_name)
Dan Shi216389c2015-12-22 11:03:06 -0800659 devserver = dev_server.ImageServer.resolve(image_name, self.hostname)
beepse539be02013-07-31 21:57:39 -0700660 devserver.stage_artifacts(
661 image_name,
beeps12c0a3c2013-09-03 11:58:27 -0700662 [factory_artifact],
663 archive_url=None)
beepse539be02013-07-31 21:57:39 -0700664
665 return tools.factory_image_url_pattern() % (devserver.url(), image_name)
666
667
Chris Sosaa3ac2152012-05-23 22:23:13 -0700668 def machine_install(self, update_url=None, force_update=False,
Richard Barnette0b023a72015-04-24 16:07:30 +0000669 local_devserver=False, repair=False,
670 force_full_update=False):
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500671 """Install the DUT.
672
Dan Shi0f466e82013-02-22 15:44:58 -0800673 Use stateful update if the DUT is already running the same build.
674 Stateful update does not update kernel and tends to run much faster
675 than a full reimage. If the DUT is running a different build, or it
676 failed to do a stateful update, full update, including kernel update,
677 will be applied to the DUT.
678
Simran Basi5ace6f22016-01-06 17:30:44 -0800679 Once a host enters machine_install its host attribute job_repo_url
680 (used for package install) will be removed and then updated.
Scott Zawalskieadbf702013-03-14 09:23:06 -0400681
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500682 @param update_url: The url to use for the update
683 pattern: http://$devserver:###/update/$build
684 If update_url is None and repair is True we will install the
Dan Shi6964fa52014-12-18 11:04:27 -0800685 stable image listed in afe_stable_versions table. If the table
686 is not setup, global_config value under CROS.stable_cros_version
687 will be used instead.
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500688 @param force_update: Force an update even if the version installed
689 is the same. Default:False
Christopher Wiley6a4ff932015-05-15 14:00:47 -0700690 @param local_devserver: Used by test_that to allow people to
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500691 use their local devserver. Default: False
Chris Sosae92399e2015-04-24 11:32:59 -0700692 @param repair: Forces update to repair image. Implies force_update.
Fang Deng3d3b9272014-12-22 12:20:28 -0800693 @param force_full_update: If True, do not attempt to run stateful
694 update, force a full reimage. If False, try stateful update
695 first when the dut is already installed with the same version.
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500696 @raises autoupdater.ChromiumOSError
697
Dan Shibe3636a2016-02-14 22:48:01 -0800698 @returns A tuple of (image_name, host_attributes).
699 image_name is the name of image installed, e.g.,
700 veyron_jerry-release/R50-7871.0.0
701 host_attributes is a dictionary of (attribute, value), which
702 can be saved to afe_host_attributes table in database. This
703 method returns a dictionary with a single entry of
704 `job_repo_url`: repo_url, where repo_url is a devserver url to
705 autotest packages.
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500706 """
Chris Sosae92399e2015-04-24 11:32:59 -0700707 devserver = None
Richard Barnette0b023a72015-04-24 16:07:30 +0000708 if repair:
Chris Sosae92399e2015-04-24 11:32:59 -0700709 update_url, devserver = self._stage_image_for_update()
Richard Barnette0b023a72015-04-24 16:07:30 +0000710 force_update = True
Dan Shi0f466e82013-02-22 15:44:58 -0800711
Chris Sosae92399e2015-04-24 11:32:59 -0700712 if not update_url and not self._parser.options.image:
713 raise error.AutoservError(
Dan Shid07ee2e2015-09-24 14:49:25 -0700714 'There is no update URL, nor a method to get one.')
Chris Sosae92399e2015-04-24 11:32:59 -0700715
716 if not update_url and self._parser.options.image:
717 # This is the base case where we have no given update URL i.e.
718 # dynamic suites logic etc. This is the most flexible case where we
719 # can serve an update from any of our fleet of devservers.
720 requested_build = self._parser.options.image
721 if not requested_build.startswith('http://'):
722 logging.debug('Update will be staged for this installation')
723 update_url, devserver = self._stage_image_for_update(
Dan Shid07ee2e2015-09-24 14:49:25 -0700724 requested_build)
Chris Sosae92399e2015-04-24 11:32:59 -0700725 else:
726 update_url = requested_build
727
728 logging.debug('Update URL is %s', update_url)
729
Dan Shif48f8132016-02-18 10:34:30 -0800730 # Report provision stats.
xixuan9e2c98d2016-02-26 19:04:53 -0800731 server_name = dev_server.ImageServer.get_server_name(update_url)
Dan Shif48f8132016-02-18 10:34:30 -0800732 server_name = server_name.replace('.', '_')
733 autotest_stats.Counter('cros_host_provision.' + server_name).increment()
734 autotest_stats.Counter('cros_host_provision.total').increment()
735
Dan Shid07ee2e2015-09-24 14:49:25 -0700736 # Create a file to indicate if provision fails. The file will be removed
737 # by stateful update or full install.
738 self.run('touch %s' % PROVISION_FAILED)
739
Chris Sosae92399e2015-04-24 11:32:59 -0700740 update_complete = False
741 updater = autoupdater.ChromiumOSUpdater(
742 update_url, host=self, local_devserver=local_devserver)
Fang Deng3d3b9272014-12-22 12:20:28 -0800743 if not force_full_update:
744 try:
Chris Sosae92399e2015-04-24 11:32:59 -0700745 # If the DUT is already running the same build, try stateful
746 # update first as it's much quicker than a full re-image.
747 update_complete = self._try_stateful_update(
Dan Shid07ee2e2015-09-24 14:49:25 -0700748 update_url, force_update, updater)
Fang Deng3d3b9272014-12-22 12:20:28 -0800749 except Exception as e:
750 logging.exception(e)
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700751
Dan Shi0f466e82013-02-22 15:44:58 -0800752 inactive_kernel = None
Chris Sosae92399e2015-04-24 11:32:59 -0700753 if update_complete or (not force_update and updater.check_version()):
754 logging.info('Install complete without full update')
755 else:
756 logging.info('DUT requires full update.')
757 self.reboot(timeout=self.REBOOT_TIMEOUT, wait=True)
Dan Shi10b98482016-02-02 14:38:50 -0800758 # Stop service ap-update-manager to prevent rebooting during
759 # autoupdate. The service is used in jetstream boards, but not other
760 # CrOS devices.
761 self.run('sudo stop ap-update-manager', ignore_status=True)
762
Chris Sosae92399e2015-04-24 11:32:59 -0700763 num_of_attempts = provision.FLAKY_DEVSERVER_ATTEMPTS
Chris Sosab7612bc2013-03-21 10:32:37 -0700764
Chris Sosae92399e2015-04-24 11:32:59 -0700765 while num_of_attempts > 0:
766 num_of_attempts -= 1
767 try:
768 updater.run_update()
769 except Exception:
770 logging.warn('Autoupdate did not complete.')
771 # Do additional check for the devserver health. Ideally,
772 # the autoupdater.py could raise an exception when it
773 # detected network flake but that would require
774 # instrumenting the update engine and parsing it log.
775 if (num_of_attempts <= 0 or
776 devserver is None or
xixuan9e2c98d2016-02-26 19:04:53 -0800777 dev_server.ImageServer.devserver_healthy(
Chris Sosae92399e2015-04-24 11:32:59 -0700778 devserver.url())):
Dan Shid07ee2e2015-09-24 14:49:25 -0700779 raise
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700780
Chris Sosae92399e2015-04-24 11:32:59 -0700781 logging.warn('Devserver looks unhealthy. Trying another')
782 update_url, devserver = self._stage_image_for_update(
783 requested_build)
784 logging.debug('New Update URL is %s', update_url)
785 updater = autoupdater.ChromiumOSUpdater(
786 update_url, host=self,
787 local_devserver=local_devserver)
788 else:
789 break
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700790
Chris Sosae92399e2015-04-24 11:32:59 -0700791 # Give it some time in case of IO issues.
792 time.sleep(10)
Dan Shi5699ac22014-12-19 10:55:49 -0800793
Chris Sosae92399e2015-04-24 11:32:59 -0700794 # Figure out active and inactive kernel.
795 active_kernel, inactive_kernel = updater.get_kernel_state()
Simran Basi13fa1ba2013-03-04 10:56:47 -0800796
Chris Sosae92399e2015-04-24 11:32:59 -0700797 # Ensure inactive kernel has higher priority than active.
798 if (updater.get_kernel_priority(inactive_kernel)
799 < updater.get_kernel_priority(active_kernel)):
800 raise autoupdater.ChromiumOSError(
801 'Update failed. The priority of the inactive kernel'
802 ' partition is less than that of the active kernel'
803 ' partition.')
804
805 # Updater has returned successfully; reboot the host.
806 self.reboot(timeout=self.REBOOT_TIMEOUT, wait=True)
807
808 self._post_update_processing(updater, inactive_kernel)
Simran Basi5ace6f22016-01-06 17:30:44 -0800809 image_name = autoupdater.url_to_image_name(update_url)
Dan Shibe3636a2016-02-14 22:48:01 -0800810 # update_url is different from devserver url needed to stage autotest
811 # packages, therefore, resolve a new devserver url here.
812 devserver_url = dev_server.ImageServer.resolve(image_name,
813 self.hostname).url()
814 repo_url = tools.get_package_url(devserver_url, image_name)
Simran Basi9cbdbc32016-02-11 18:15:46 -0800815 self.verify_software()
Dan Shibe3636a2016-02-14 22:48:01 -0800816 return image_name, {ds_constants.JOB_REPO_URL: repo_url}
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700817
818
Tom Wai-Hong Tam2d00cb22016-01-08 06:40:50 +0800819 def _clear_fw_version_labels(self, rw_only):
820 """Clear firmware version labels from the machine.
821
822 @param rw_only: True to only clear fwrw_version; otherewise, clear
823 both fwro_version and fwrw_version.
824 """
Dan Shi9cb0eec2014-06-03 09:04:50 -0700825 labels = self._AFE.get_labels(
Dan Shi0723bf52015-06-24 10:52:38 -0700826 name__startswith=provision.FW_RW_VERSION_PREFIX,
Dan Shi9cb0eec2014-06-03 09:04:50 -0700827 host__hostname=self.hostname)
Tom Wai-Hong Tam2d00cb22016-01-08 06:40:50 +0800828 if not rw_only:
829 labels = labels + self._AFE.get_labels(
830 name__startswith=provision.FW_RO_VERSION_PREFIX,
831 host__hostname=self.hostname)
Dan Shi9cb0eec2014-06-03 09:04:50 -0700832 for label in labels:
833 label.remove_hosts(hosts=[self.hostname])
834
835
Tom Wai-Hong Tam2d00cb22016-01-08 06:40:50 +0800836 def _add_fw_version_label(self, build, rw_only):
Dan Shi9cb0eec2014-06-03 09:04:50 -0700837 """Add firmware version label to the machine.
838
839 @param build: Build of firmware.
Tom Wai-Hong Tam2d00cb22016-01-08 06:40:50 +0800840 @param rw_only: True to only add fwrw_version; otherwise, add both
841 fwro_version and fwrw_version.
Dan Shi9cb0eec2014-06-03 09:04:50 -0700842
843 """
Tom Wai-Hong Tam2d00cb22016-01-08 06:40:50 +0800844 fw_label = provision.fwrw_version_to_label(build)
MK Ryu73be9862015-07-06 12:25:00 -0700845 self._AFE.run('label_add_hosts', id=fw_label, hosts=[self.hostname])
Tom Wai-Hong Tam2d00cb22016-01-08 06:40:50 +0800846 if not rw_only:
847 fw_label = provision.fwro_version_to_label(build)
848 self._AFE.run('label_add_hosts', id=fw_label, hosts=[self.hostname])
Dan Shi9cb0eec2014-06-03 09:04:50 -0700849
850
Tom Wai-Hong Tam4ac78982016-01-08 02:34:37 +0800851 def firmware_install(self, build=None, rw_only=False):
Dan Shi9cb0eec2014-06-03 09:04:50 -0700852 """Install firmware to the DUT.
853
854 Use stateful update if the DUT is already running the same build.
855 Stateful update does not update kernel and tends to run much faster
856 than a full reimage. If the DUT is running a different build, or it
857 failed to do a stateful update, full update, including kernel update,
858 will be applied to the DUT.
859
Tom Wai-Hong Tam2d00cb22016-01-08 06:40:50 +0800860 Once a host enters firmware_install its fw[ro|rw]_version label will
861 be removed. After the firmware is updated successfully, a new
862 fw[ro|rw]_version label will be added to the host.
Dan Shi9cb0eec2014-06-03 09:04:50 -0700863
864 @param build: The build version to which we want to provision the
865 firmware of the machine,
866 e.g. 'link-firmware/R22-2695.1.144'.
Tom Wai-Hong Tam4ac78982016-01-08 02:34:37 +0800867 @param rw_only: True to only install firmware to its RW portions. Keep
868 the RO portions unchanged.
Dan Shi9cb0eec2014-06-03 09:04:50 -0700869
870 TODO(dshi): After bug 381718 is fixed, update here with corresponding
871 exceptions that could be raised.
872
873 """
874 if not self.servo:
875 raise error.TestError('Host %s does not have servo.' %
876 self.hostname)
877
878 # TODO(fdeng): use host.get_board() after
879 # crbug.com/271834 is fixed.
880 board = self._get_board_from_afe()
881
Chris Sosae92399e2015-04-24 11:32:59 -0700882 # If build is not set, try to install firmware from stable CrOS.
Dan Shi9cb0eec2014-06-03 09:04:50 -0700883 if not build:
Dan Shi3d7a0e12015-10-12 11:55:45 -0700884 build = self.get_repair_image_name(image_type='firmware')
885 if not build:
886 raise error.TestError(
887 'Failed to find stable firmware build for %s.',
888 self.hostname)
889 logging.info('Will install firmware from build %s.', build)
Dan Shi9cb0eec2014-06-03 09:04:50 -0700890
891 config = FAFTConfig(board)
892 if config.use_u_boot:
893 ap_image = 'image-%s.bin' % board
894 else: # Depthcharge platform
895 ap_image = 'image.bin'
896 ec_image = 'ec.bin'
Dan Shi216389c2015-12-22 11:03:06 -0800897 ds = dev_server.ImageServer.resolve(build, self.hostname)
Dan Shi9cb0eec2014-06-03 09:04:50 -0700898 ds.stage_artifacts(build, ['firmware'])
899
900 tmpd = autotemp.tempdir(unique_id='fwimage')
901 try:
902 fwurl = self._FW_IMAGE_URL_PATTERN % (ds.url(), build)
903 local_tarball = os.path.join(tmpd.name, os.path.basename(fwurl))
904 server_utils.system('wget -O %s %s' % (local_tarball, fwurl),
905 timeout=60)
Dan Shi9cb0eec2014-06-03 09:04:50 -0700906
Tom Wai-Hong Tam2d00cb22016-01-08 06:40:50 +0800907 self._clear_fw_version_labels(rw_only)
Tom Wai-Hong Tamf9db57a2016-03-17 05:32:22 +0800908 if self.get_ec():
909 logging.info('Will re-program EC %snow', 'RW ' if rw_only else '')
910 server_utils.system('tar xf %s -C %s %s' %
911 (local_tarball, tmpd.name, ec_image),
912 timeout=60)
913 self.servo.program_ec(os.path.join(tmpd.name, ec_image), rw_only)
914 else:
915 logging.info('Not a Chrome EC, ignore re-programing it')
Tom Wai-Hong Tam4ac78982016-01-08 02:34:37 +0800916 logging.info('Will re-program BIOS %snow', 'RW ' if rw_only else '')
Tom Wai-Hong Tamf9db57a2016-03-17 05:32:22 +0800917 server_utils.system('tar xf %s -C %s %s' %
918 (local_tarball, tmpd.name, ap_image),
919 timeout=60)
Tom Wai-Hong Tam4ac78982016-01-08 02:34:37 +0800920 self.servo.program_bios(os.path.join(tmpd.name, ap_image), rw_only)
Dan Shi9cb0eec2014-06-03 09:04:50 -0700921 self.servo.get_power_state_controller().reset()
922 time.sleep(self.servo.BOOT_DELAY)
Tom Wai-Hong Tam2d00cb22016-01-08 06:40:50 +0800923 self._add_fw_version_label(build, rw_only)
Dan Shi9cb0eec2014-06-03 09:04:50 -0700924 finally:
925 tmpd.clean()
926
927
Dan Shi10e992b2013-08-30 11:02:59 -0700928 def show_update_engine_log(self):
929 """Output update engine log."""
MK Ryu35d661e2014-09-25 17:44:10 -0700930 logging.debug('Dumping %s', client_constants.UPDATE_ENGINE_LOG)
931 self.run('cat %s' % client_constants.UPDATE_ENGINE_LOG)
Dan Shi10e992b2013-08-30 11:02:59 -0700932
933
Richard Barnette82c35912012-11-20 10:09:10 -0800934 def _get_board_from_afe(self):
935 """Retrieve this host's board from its labels in the AFE.
936
937 Looks for a host label of the form "board:<board>", and
938 returns the "<board>" part of the label. `None` is returned
939 if there is not a single, unique label matching the pattern.
940
941 @returns board from label, or `None`.
942 """
Dan Shia1ecd5c2013-06-06 11:21:31 -0700943 return server_utils.get_board_from_afe(self.hostname, self._AFE)
Simran Basi833814b2013-01-29 13:13:43 -0800944
945
Dan Shib3b6db32016-02-03 14:54:05 -0800946 def get_build(self):
947 """Retrieve the current build for this Host from the AFE.
948
949 Looks through this host's labels in the AFE to determine its build.
950 This method is replaced by afe_utils.get_build. It's kept here to
951 maintain backwards compatibility for test control files in older CrOS
952 builds (R48, R49 etc.) still call host.get_build, e.g.,
953 `provision_AutoUpdate.double`.
954 TODO(sbasi): Once R50 falls into release branch, this method can be
955 removed.
956
957 @returns The current build or None if it could not find it or if there
958 were multiple build labels assigned to this host.
959 """
960 return afe_utils.get_build(self)
961
962
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500963 def _install_repair(self):
Chris Sosae92399e2015-04-24 11:32:59 -0700964 """Attempt to repair this host using the update-engine.
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500965
966 If the host is up, try installing the DUT with a stable
Dan Shi6964fa52014-12-18 11:04:27 -0800967 "repair" version of Chrome OS as defined in afe_stable_versions table.
968 If the table is not setup, global_config value under
969 CROS.stable_cros_version will be used instead.
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500970
Scott Zawalski62bacae2013-03-05 10:40:32 -0500971 @raises AutoservRepairMethodNA if the DUT is not reachable.
972 @raises ChromiumOSError if the install failed for some reason.
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500973
974 """
975 if not self.is_up():
Scott Zawalski62bacae2013-03-05 10:40:32 -0500976 raise error.AutoservRepairMethodNA('DUT unreachable for install.')
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500977 logging.info('Attempting to reimage machine to repair image.')
978 try:
Simran Basi5ace6f22016-01-06 17:30:44 -0800979 afe_utils.machine_install_and_update_labels(self, repair=True)
Fang Dengd0672f32013-03-18 17:18:09 -0700980 except autoupdater.ChromiumOSError as e:
981 logging.exception(e)
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500982 logging.info('Repair via install failed.')
Scott Zawalski62bacae2013-03-05 10:40:32 -0500983 raise
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500984
985
Dan Shi2c88eed2013-11-12 10:18:38 -0800986 def _install_repair_with_powerwash(self):
Dan Shi9cc48452013-11-12 12:39:26 -0800987 """Attempt to powerwash first then repair this host using update-engine.
Dan Shi2c88eed2013-11-12 10:18:38 -0800988
Dan Shi9cc48452013-11-12 12:39:26 -0800989 update-engine may fail due to a bad image. In such case, powerwash
990 may help to cleanup the DUT for update-engine to work again.
Dan Shi2c88eed2013-11-12 10:18:38 -0800991
992 @raises AutoservRepairMethodNA if the DUT is not reachable.
993 @raises ChromiumOSError if the install failed for some reason.
994
995 """
996 if not self.is_up():
997 raise error.AutoservRepairMethodNA('DUT unreachable for install.')
998
999 logging.info('Attempting to powerwash the DUT.')
1000 self.run('echo "fast safe" > '
1001 '/mnt/stateful_partition/factory_install_reset')
1002 self.reboot(timeout=self.POWERWASH_BOOT_TIMEOUT, wait=True)
1003 if not self.is_up():
Dan Shi9cc48452013-11-12 12:39:26 -08001004 logging.error('Powerwash failed. DUT did not come back after '
Dan Shi2c88eed2013-11-12 10:18:38 -08001005 'reboot.')
1006 raise error.AutoservRepairFailure(
1007 'DUT failed to boot from powerwash after %d seconds' %
1008 self.POWERWASH_BOOT_TIMEOUT)
1009
1010 logging.info('Powerwash succeeded.')
1011 self._install_repair()
1012
1013
beepsf079cfb2013-09-18 17:49:51 -07001014 def servo_install(self, image_url=None, usb_boot_timeout=USB_BOOT_TIMEOUT,
1015 install_timeout=INSTALL_TIMEOUT):
Scott Zawalski62bacae2013-03-05 10:40:32 -05001016 """
1017 Re-install the OS on the DUT by:
1018 1) installing a test image on a USB storage device attached to the Servo
1019 board,
Richard Barnette03a0c132012-11-05 12:40:35 -08001020 2) booting that image in recovery mode, and then
J. Richard Barnette31b2e312013-04-04 16:05:22 -07001021 3) installing the image with chromeos-install.
1022
Scott Zawalski62bacae2013-03-05 10:40:32 -05001023 @param image_url: If specified use as the url to install on the DUT.
1024 otherwise boot the currently staged image on the USB stick.
beepsf079cfb2013-09-18 17:49:51 -07001025 @param usb_boot_timeout: The usb_boot_timeout to use during reimage.
1026 Factory images need a longer usb_boot_timeout than regular
1027 cros images.
1028 @param install_timeout: The timeout to use when installing the chromeos
1029 image. Factory images need a longer install_timeout.
Richard Barnette03a0c132012-11-05 12:40:35 -08001030
Scott Zawalski62bacae2013-03-05 10:40:32 -05001031 @raises AutoservError if the image fails to boot.
beepsf079cfb2013-09-18 17:49:51 -07001032
J. Richard Barnette0199cc82014-12-05 17:08:40 -08001033 """
beepsf079cfb2013-09-18 17:49:51 -07001034 usb_boot_timer_key = ('servo_install.usb_boot_timeout_%s'
1035 % usb_boot_timeout)
1036 logging.info('Downloading image to USB, then booting from it. Usb boot '
1037 'timeout = %s', usb_boot_timeout)
Gabe Black1e1c41b2015-02-04 23:55:15 -08001038 timer = autotest_stats.Timer(usb_boot_timer_key)
beepsf079cfb2013-09-18 17:49:51 -07001039 timer.start()
J. Richard Barnette31b2e312013-04-04 16:05:22 -07001040 self.servo.install_recovery_image(image_url)
beepsf079cfb2013-09-18 17:49:51 -07001041 if not self.wait_up(timeout=usb_boot_timeout):
Scott Zawalski62bacae2013-03-05 10:40:32 -05001042 raise error.AutoservRepairFailure(
1043 'DUT failed to boot from USB after %d seconds' %
beepsf079cfb2013-09-18 17:49:51 -07001044 usb_boot_timeout)
1045 timer.stop()
Scott Zawalski62bacae2013-03-05 10:40:32 -05001046
Tom Wai-Hong Tamf6b4f812015-08-08 04:14:59 +08001047 # The new chromeos-tpm-recovery has been merged since R44-7073.0.0.
1048 # In old CrOS images, this command fails. Skip the error.
Tom Wai-Hong Tam27af7332015-07-25 06:09:39 +08001049 logging.info('Resetting the TPM status')
Tom Wai-Hong Tamf6b4f812015-08-08 04:14:59 +08001050 try:
1051 self.run('chromeos-tpm-recovery')
1052 except error.AutoservRunError:
1053 logging.warn('chromeos-tpm-recovery is too old.')
1054
Tom Wai-Hong Tam27af7332015-07-25 06:09:39 +08001055
beepsf079cfb2013-09-18 17:49:51 -07001056 install_timer_key = ('servo_install.install_timeout_%s'
1057 % install_timeout)
Gabe Black1e1c41b2015-02-04 23:55:15 -08001058 timer = autotest_stats.Timer(install_timer_key)
beepsf079cfb2013-09-18 17:49:51 -07001059 timer.start()
1060 logging.info('Installing image through chromeos-install.')
J. Richard Barnette9af19632015-09-25 12:18:03 -07001061 self.run('chromeos-install --yes', timeout=install_timeout)
1062 self.halt()
beepsf079cfb2013-09-18 17:49:51 -07001063 timer.stop()
1064
1065 logging.info('Power cycling DUT through servo.')
J. Richard Barnette0199cc82014-12-05 17:08:40 -08001066 self.servo.get_power_state_controller().power_off()
Fang Dengafb88142013-05-30 17:44:31 -07001067 self.servo.switch_usbkey('off')
J. Richard Barnette0199cc82014-12-05 17:08:40 -08001068 # N.B. The Servo API requires that we use power_on() here
1069 # for two reasons:
1070 # 1) After turning on a DUT in recovery mode, you must turn
1071 # it off and then on with power_on() once more to
1072 # disable recovery mode (this is a Parrot specific
1073 # requirement).
1074 # 2) After power_off(), the only way to turn on is with
1075 # power_on() (this is a Storm specific requirement).
J. Richard Barnettefbcc7122013-07-24 18:24:59 -07001076 self.servo.get_power_state_controller().power_on()
beepsf079cfb2013-09-18 17:49:51 -07001077
1078 logging.info('Waiting for DUT to come back up.')
Richard Barnette03a0c132012-11-05 12:40:35 -08001079 if not self.wait_up(timeout=self.BOOT_TIMEOUT):
1080 raise error.AutoservError('DUT failed to reboot installed '
1081 'test image after %d seconds' %
Scott Zawalski62bacae2013-03-05 10:40:32 -05001082 self.BOOT_TIMEOUT)
1083
1084
Dan Shic1b8bdd2015-09-14 23:11:24 -07001085 def _setup_servo(self):
1086 """Try to force to create servo object if it's not set up yet.
1087 """
1088 if self.servo:
1089 return
1090
1091 try:
1092 # Setting servo_args to {} will force it to create the servo_host
1093 # object if possible.
1094 self._servo_host = servo_host.create_servo_host(
1095 dut=self.hostname, servo_args={})
1096 if self._servo_host:
1097 self.servo = self._servo_host.get_servo()
1098 else:
1099 logging.error('Failed to create servo_host object.')
1100 except Exception as e:
1101 logging.error('Failed to create servo object: %s', e)
1102
1103
J. Richard Barnettee4af8b92013-05-01 13:16:12 -07001104 def _servo_repair_reinstall(self):
Scott Zawalski62bacae2013-03-05 10:40:32 -05001105 """Reinstall the DUT utilizing servo and a test image.
1106
1107 Re-install the OS on the DUT by:
1108 1) installing a test image on a USB storage device attached to the Servo
1109 board,
Tom Wai-Hong Tam27af7332015-07-25 06:09:39 +08001110 2) booting that image in recovery mode,
1111 3) resetting the TPM status, and then
1112 4) installing the image with chromeos-install.
Scott Zawalski62bacae2013-03-05 10:40:32 -05001113
Scott Zawalski62bacae2013-03-05 10:40:32 -05001114 @raises AutoservRepairMethodNA if the device does not have servo
1115 support.
1116
1117 """
1118 if not self.servo:
1119 raise error.AutoservRepairMethodNA('Repair Reinstall NA: '
1120 'DUT has no servo support.')
1121
1122 logging.info('Attempting to recovery servo enabled device with '
1123 'servo_repair_reinstall')
1124
J. Richard Barnettee4af8b92013-05-01 13:16:12 -07001125 image_url = self.stage_image_for_servo()
Scott Zawalski62bacae2013-03-05 10:40:32 -05001126 self.servo_install(image_url)
1127
1128
Tom Wai-Hong Tambea741c2016-01-21 07:20:14 +08001129 def _is_firmware_repair_supported(self):
1130 """Check if the firmware repair is supported.
Dan Shi3d7a0e12015-10-12 11:55:45 -07001131
Tom Wai-Hong Tambea741c2016-01-21 07:20:14 +08001132 The firmware repair is only applicable to DUTs in pools listed in
1133 global config CROS/pools_support_firmware_repair.
Dan Shi3d7a0e12015-10-12 11:55:45 -07001134
Tom Wai-Hong Tambea741c2016-01-21 07:20:14 +08001135 @return: True if it is supported; otherwise False.
Dan Shi3d7a0e12015-10-12 11:55:45 -07001136 """
1137 logging.info('Checking if host %s can be repaired with firmware '
1138 'repair.', self.hostname)
1139 pools = server_utils.get_labels_from_afe(self.hostname, 'pool:',
1140 self._AFE)
1141 pools_support_firmware_repair = CONFIG.get_config_value('CROS',
1142 'pools_support_firmware_repair', type=str).split(',')
Tom Wai-Hong Tambea741c2016-01-21 07:20:14 +08001143
1144 return (pools and pools_support_firmware_repair and
1145 set(pools).intersection(set(pools_support_firmware_repair)))
1146
1147
1148 def _firmware_repair(self):
1149 """Reinstall the firmware image using servo.
1150
1151 This repair function attempts to install the stable firmware specified
1152 by the stable firmware version.
1153 Then reset the DUT and try to verify it. If verify fails, it will try to
1154 install the CrOS image using servo.
1155 """
1156 if not self._is_firmware_repair_supported():
1157 logging.info('Host is not in pools that support firmware repair.')
Dan Shi3d7a0e12015-10-12 11:55:45 -07001158 raise error.AutoservRepairMethodNA(
1159 'Firmware repair is not applicable to host %s.' %
1160 self.hostname)
1161
1162 # To repair a DUT connected to a moblab, try to create a servo object if
1163 # it was failed to be created earlier as there may be a servo_host host
1164 # attribute for this host.
1165 if utils.is_moblab():
1166 self._setup_servo()
1167
1168 if not self.servo:
1169 raise error.AutoservRepairMethodNA('Repair Reinstall NA: '
1170 'DUT has no servo support.')
1171
1172 logging.info('Attempting to recovery servo enabled device with '
1173 'firmware_repair.')
1174 self.firmware_install()
1175
1176 logging.info('Firmware repaired. Check if the DUT can boot. If not, '
1177 'reinstall the CrOS using servo.')
1178 try:
Dan Shi3d7a0e12015-10-12 11:55:45 -07001179 self.verify()
1180 except Exception as e:
1181 logging.warn('Failed to verify DUT, error: %s. Will try to repair '
1182 'the DUT with servo_repair_reinstall.', e)
1183 self._servo_repair_reinstall()
1184
1185
Scott Zawalski62bacae2013-03-05 10:40:32 -05001186 def _servo_repair_power(self):
1187 """Attempt to repair DUT using an attached Servo.
1188
J. Richard Barnette13165972016-01-13 10:53:09 -08001189 Attempt to power cycle the DUT via cold_reset.
Scott Zawalski62bacae2013-03-05 10:40:32 -05001190
1191 @raises AutoservRepairMethodNA if the device does not have servo
1192 support.
1193 @raises AutoservRepairFailure if the repair fails for any reason.
1194 """
1195 if not self.servo:
1196 raise error.AutoservRepairMethodNA('Repair Power NA: '
1197 'DUT has no servo support.')
1198
1199 logging.info('Attempting to recover servo enabled device by '
J. Richard Barnette13165972016-01-13 10:53:09 -08001200 'powering cycling with cold reset.')
1201 self.servo.get_power_state_controller().reset()
Scott Zawalski62bacae2013-03-05 10:40:32 -05001202 if self.wait_up(self.BOOT_TIMEOUT):
1203 return
1204
1205 raise error.AutoservRepairFailure('DUT did not boot after long_press.')
Richard Barnette03a0c132012-11-05 12:40:35 -08001206
1207
Richard Barnette82c35912012-11-20 10:09:10 -08001208 def _powercycle_to_repair(self):
1209 """Utilize the RPM Infrastructure to bring the host back up.
1210
1211 If the host is not up/repaired after the first powercycle we utilize
1212 auto fallback to the last good install by powercycling and rebooting the
1213 host 6 times.
Scott Zawalski62bacae2013-03-05 10:40:32 -05001214
1215 @raises AutoservRepairMethodNA if the device does not support remote
1216 power.
1217 @raises AutoservRepairFailure if the repair fails for any reason.
1218
Richard Barnette82c35912012-11-20 10:09:10 -08001219 """
Scott Zawalski62bacae2013-03-05 10:40:32 -05001220 if not self.has_power():
1221 raise error.AutoservRepairMethodNA('Device does not support power.')
1222
Richard Barnette82c35912012-11-20 10:09:10 -08001223 logging.info('Attempting repair via RPM powercycle.')
1224 failed_cycles = 0
1225 self.power_cycle()
1226 while not self.wait_up(timeout=self.BOOT_TIMEOUT):
1227 failed_cycles += 1
1228 if failed_cycles >= self._MAX_POWER_CYCLE_ATTEMPTS:
Scott Zawalski62bacae2013-03-05 10:40:32 -05001229 raise error.AutoservRepairFailure(
1230 'Powercycled host %s %d times; device did not come back'
1231 ' online.' % (self.hostname, failed_cycles))
Richard Barnette82c35912012-11-20 10:09:10 -08001232 self.power_cycle()
1233 if failed_cycles == 0:
1234 logging.info('Powercycling was successful first time.')
1235 else:
1236 logging.info('Powercycling was successful after %d failures.',
1237 failed_cycles)
1238
1239
MK Ryu35d661e2014-09-25 17:44:10 -07001240 def _reboot_repair(self):
1241 """SSH to this host and reboot."""
1242 if not self.is_up(self._CHECK_HOST_UP_TIMEOUT_SECS):
1243 raise error.AutoservRepairMethodNA('DUT unreachable for reboot.')
1244 logging.info('Attempting repair via SSH reboot.')
1245 self.reboot(timeout=self.BOOT_TIMEOUT, wait=True)
1246
1247
Prashanth B4d8184f2014-05-05 12:22:02 -07001248 def check_device(self):
1249 """Check if a device is ssh-able, and if so, clean and verify it.
1250
1251 @raise AutoservSSHTimeout: If the ssh ping times out.
1252 @raise AutoservSshPermissionDeniedError: If ssh ping fails due to
1253 permissions.
1254 @raise AutoservSshPingHostError: For other AutoservRunErrors during
1255 ssh_ping.
1256 @raises AutoservError: As appropriate, during cleanup and verify.
1257 """
1258 self.ssh_ping()
1259 self.cleanup()
1260 self.verify()
1261
1262
Dan Shi90466352015-09-22 15:01:05 -07001263 def confirm_servo(self):
1264 """Confirm servo is initialized and verified.
1265
1266 @raise AutoservError: If servo is not initialized and verified.
1267 """
Tom Wai-Hong Tam244acc22016-01-09 07:04:21 +08001268 if self.servo and self._servo_host.required_by_test:
Dan Shi90466352015-09-22 15:01:05 -07001269 return
1270
1271 # Force to re-create the servo object to make sure servo is verified.
1272 logging.debug('Rebuilding the servo object.')
1273 self.servo = None
1274 self._servo_host = None
1275 self._setup_servo()
1276 if not self.servo:
1277 raise error.AutoservError('Failed to create servo object.')
1278
1279
Dan Shid07ee2e2015-09-24 14:49:25 -07001280 def _is_last_provision_failed(self):
1281 """Checks if the last provision job failed.
1282
1283 @return: True if there exists file /var/tmp/provision_failed, which
1284 indicates the last provision job failed.
1285 False if the file does not exist or the dut can't be reached.
1286 """
1287 try:
1288 result = self.run('test -f %s' % PROVISION_FAILED,
1289 ignore_status=True, timeout=5)
1290 return result.exit_status == 0
1291 except (error.AutoservRunError, error.AutoservSSHTimeout):
1292 # Default to False, for repair to try all repair method if the dut
1293 # can't be reached.
1294 return False
1295
1296
J. Richard Barnettec2d99cf2015-11-18 12:46:15 -08001297 def repair(self):
1298 """Attempt to get the DUT to pass `self.verify()`.
Richard Barnette82c35912012-11-20 10:09:10 -08001299
1300 This overrides the base class function for repair; it does
1301 not call back to the parent class, but instead offers a
1302 simplified implementation based on the capabilities in the
1303 Chrome OS test lab.
1304
Fang Deng5d518f42013-08-02 14:04:32 -07001305 It first verifies and repairs servo if it is a DUT in CrOS
Fang Deng03590af2013-10-07 17:34:20 -07001306 lab and a servo is attached.
Fang Deng5d518f42013-08-02 14:04:32 -07001307
Jakob Juelich82b7d1c2014-09-15 16:10:57 -07001308 This escalates in order through the following procedures and verifies
1309 the status using `self.check_device()` after each of them. This is done
1310 until both the repair and the veryfing step succeed.
1311
MK Ryu35d661e2014-09-25 17:44:10 -07001312 Escalation order of repair procedures from less intrusive to
1313 more intrusive repairs:
1314 1. SSH to the DUT and reboot.
Scott Zawalski62bacae2013-03-05 10:40:32 -05001315 2. If there's a servo for the DUT, try to power the DUT off and
1316 on.
MK Ryu35d661e2014-09-25 17:44:10 -07001317 3. If the DUT can be power-cycled via RPM, try to repair
Richard Barnette82c35912012-11-20 10:09:10 -08001318 by power-cycling.
MK Ryu35d661e2014-09-25 17:44:10 -07001319 4. Try to re-install to a known stable image using
1320 auto-update.
1321 5. If there's a servo for the DUT, try to re-install via
1322 the servo.
Richard Barnette82c35912012-11-20 10:09:10 -08001323
1324 As with the parent method, the last operation performed on
Prashanth B4d8184f2014-05-05 12:22:02 -07001325 the DUT must be to call `self.check_device()`; If that call fails the
1326 exception it raises is passed back to the caller.
J. Richard Barnettefde55fc2013-03-15 17:47:01 -07001327
Scott Zawalski62bacae2013-03-05 10:40:32 -05001328 @raises AutoservRepairTotalFailure if the repair process fails to
1329 fix the DUT.
Fang Deng5d518f42013-08-02 14:04:32 -07001330 @raises ServoHostRepairTotalFailure if the repair process fails to
1331 fix the servo host if one is attached to the DUT.
1332 @raises AutoservSshPermissionDeniedError if it is unable
1333 to ssh to the servo host due to permission error.
1334
Richard Barnette82c35912012-11-20 10:09:10 -08001335 """
Jakob Juelich82b7d1c2014-09-15 16:10:57 -07001336 # Caution: Deleting shards relies on repair to always reboot the DUT.
1337
Nicolas Boichate30c7e12015-11-05 11:12:50 +08001338 # To repair a DUT connected to a moblab, try to create a servo object if
1339 # it was failed to be created earlier as there may be a servo_host host
1340 # attribute for this host.
1341 if utils.is_moblab():
1342 self._setup_servo()
1343
Dan Shi4d478522014-02-14 13:46:32 -08001344 if self._servo_host and not self.servo:
Fang Deng03590af2013-10-07 17:34:20 -07001345 try:
J. Richard Barnette4fc59c42015-12-15 16:58:50 -08001346 self._servo_host.repair()
Fang Deng03590af2013-10-07 17:34:20 -07001347 except Exception as e:
Fang Deng03590af2013-10-07 17:34:20 -07001348 logging.error('Could not create a healthy servo: %s', e)
Dan Shi4d478522014-02-14 13:46:32 -08001349 self.servo = self._servo_host.get_servo()
Fang Deng5d518f42013-08-02 14:04:32 -07001350
MK Ryu35d661e2014-09-25 17:44:10 -07001351 self.try_collect_crashlogs()
1352
Scott Zawalski62bacae2013-03-05 10:40:32 -05001353 # TODO(scottz): This should use something similar to label_decorator,
1354 # but needs to be populated in order so DUTs are repaired with the
1355 # least amount of effort.
Dan Shid07ee2e2015-09-24 14:49:25 -07001356 force_powerwash = self._is_last_provision_failed()
1357 if force_powerwash:
1358 logging.info('Last provision failed, try powerwash first.')
1359 autotest_stats.Counter(
1360 'repair_force_powerwash.TOTAL').increment()
Tom Wai-Hong Tamb284ce42016-01-15 08:11:38 +08001361 repair_funcs = [self._firmware_repair,
1362 self._install_repair_with_powerwash,
1363 self._servo_repair_reinstall]
Dan Shid07ee2e2015-09-24 14:49:25 -07001364 else:
1365 repair_funcs = [self._reboot_repair,
1366 self._servo_repair_power,
Tom Wai-Hong Tamb284ce42016-01-15 08:11:38 +08001367 self._firmware_repair,
Dan Shid07ee2e2015-09-24 14:49:25 -07001368 self._powercycle_to_repair,
1369 self._install_repair,
1370 self._install_repair_with_powerwash,
Tom Wai-Hong Tamb284ce42016-01-15 08:11:38 +08001371 self._servo_repair_reinstall]
Scott Zawalski62bacae2013-03-05 10:40:32 -05001372 errors = []
Simran Basie6130932013-10-01 14:07:52 -07001373 board = self._get_board_from_afe()
Scott Zawalski62bacae2013-03-05 10:40:32 -05001374 for repair_func in repair_funcs:
1375 try:
1376 repair_func()
MK Ryu35d661e2014-09-25 17:44:10 -07001377 self.try_collect_crashlogs()
Prashanth B4d8184f2014-05-05 12:22:02 -07001378 self.check_device()
Gabe Black1e1c41b2015-02-04 23:55:15 -08001379 autotest_stats.Counter(
Simran Basie6130932013-10-01 14:07:52 -07001380 '%s.SUCCEEDED' % repair_func.__name__).increment()
1381 if board:
Gabe Black1e1c41b2015-02-04 23:55:15 -08001382 autotest_stats.Counter(
Dan Shid07ee2e2015-09-24 14:49:25 -07001383 '%s.%s.SUCCEEDED' % (repair_func.__name__,
Simran Basie6130932013-10-01 14:07:52 -07001384 board)).increment()
Dan Shid07ee2e2015-09-24 14:49:25 -07001385 if force_powerwash:
1386 autotest_stats.Counter(
1387 'repair_force_powerwash.SUCCEEDED').increment()
Scott Zawalski62bacae2013-03-05 10:40:32 -05001388 return
Simran Basie6130932013-10-01 14:07:52 -07001389 except error.AutoservRepairMethodNA as e:
Gabe Black1e1c41b2015-02-04 23:55:15 -08001390 autotest_stats.Counter(
Simran Basie6130932013-10-01 14:07:52 -07001391 '%s.RepairNA' % repair_func.__name__).increment()
1392 if board:
Gabe Black1e1c41b2015-02-04 23:55:15 -08001393 autotest_stats.Counter(
Dan Shid07ee2e2015-09-24 14:49:25 -07001394 '%s.%s.RepairNA' % (repair_func.__name__,
1395 board)).increment()
Ilja H. Friedel04be2bd2014-05-07 21:29:59 -07001396 logging.warning('Repair function NA: %s', e)
Simran Basie6130932013-10-01 14:07:52 -07001397 errors.append(str(e))
Scott Zawalski62bacae2013-03-05 10:40:32 -05001398 except Exception as e:
Gabe Black1e1c41b2015-02-04 23:55:15 -08001399 autotest_stats.Counter(
Simran Basie6130932013-10-01 14:07:52 -07001400 '%s.FAILED' % repair_func.__name__).increment()
1401 if board:
Gabe Black1e1c41b2015-02-04 23:55:15 -08001402 autotest_stats.Counter(
Dan Shid07ee2e2015-09-24 14:49:25 -07001403 '%s.%s.FAILED' % (repair_func.__name__,
1404 board)).increment()
Ilja H. Friedel04be2bd2014-05-07 21:29:59 -07001405 logging.warning('Failed to repair device: %s', e)
Scott Zawalski62bacae2013-03-05 10:40:32 -05001406 errors.append(str(e))
Scott Zawalski89c44dd2013-02-26 09:28:02 -05001407
Dan Shid07ee2e2015-09-24 14:49:25 -07001408 if force_powerwash:
1409 autotest_stats.Counter(
1410 'repair_force_powerwash.FAILED').increment()
Gabe Black1e1c41b2015-02-04 23:55:15 -08001411 autotest_stats.Counter('Full_Repair_Failed').increment()
Simran Basie6130932013-10-01 14:07:52 -07001412 if board:
Gabe Black1e1c41b2015-02-04 23:55:15 -08001413 autotest_stats.Counter(
Dan Shid07ee2e2015-09-24 14:49:25 -07001414 'Full_Repair_Failed.%s' % board).increment()
Scott Zawalski62bacae2013-03-05 10:40:32 -05001415 raise error.AutoservRepairTotalFailure(
1416 'All attempts at repairing the device failed:\n%s' %
1417 '\n'.join(errors))
Richard Barnette82c35912012-11-20 10:09:10 -08001418
1419
MK Ryu35d661e2014-09-25 17:44:10 -07001420 def try_collect_crashlogs(self, check_host_up=True):
1421 """
1422 Check if a host is up and logs need to be collected from the host,
1423 if yes, collect them.
1424
1425 @param check_host_up: Flag for checking host is up. Default is True.
1426 """
1427 try:
1428 crash_job = self._need_crash_logs()
1429 if crash_job:
1430 logging.debug('%s: Job %s was crashed', self._CRASHLOGS_PREFIX,
1431 crash_job)
1432 if not check_host_up or self.is_up(
1433 self._CHECK_HOST_UP_TIMEOUT_SECS):
1434 self._collect_crashlogs(crash_job)
1435 logging.debug('%s: Completed collecting logs for the '
1436 'crashed job %s', self._CRASHLOGS_PREFIX,
1437 crash_job)
1438 except Exception as e:
1439 # Exception should not result in repair failure.
1440 # Therefore, suppress all exceptions here.
1441 logging.error('%s: Failed while trying to collect crash-logs: %s',
1442 self._CRASHLOGS_PREFIX, e)
1443
1444
1445 def _need_crash_logs(self):
1446 """Get the value of need_crash_logs attribute of this host.
1447
1448 @return: Value string of need_crash_logs attribute
1449 None if there is no need_crash_logs attribute
1450 """
1451 attrs = self._AFE.get_host_attribute(constants.CRASHLOGS_HOST_ATTRIBUTE,
1452 hostname=self.hostname)
1453 assert len(attrs) < 2
1454 return attrs[0].value if attrs else None
1455
1456
1457 def _collect_crashlogs(self, job_id):
1458 """Grab logs from the host where a job was crashed.
1459
1460 First, check if PRIOR_LOGS_DIR exists in the host.
1461 If yes, collect them.
1462 Otherwise, check if a lab-machine marker (_LAB_MACHINE_FILE) exists
1463 in the host.
1464 If yes, the host was repaired automatically, and we collect normal
1465 system logs.
1466
1467 @param job_id: Id of the job that was crashed.
1468 """
1469 crashlogs_dir = crashcollect.get_crashinfo_dir(self,
1470 constants.CRASHLOGS_DEST_DIR_PREFIX)
1471 flag_prior_logs = False
1472
1473 if self.path_exists(client_constants.PRIOR_LOGS_DIR):
1474 flag_prior_logs = True
1475 self._collect_prior_logs(crashlogs_dir)
1476 elif self.path_exists(self._LAB_MACHINE_FILE):
1477 self._collect_system_logs(crashlogs_dir)
1478 else:
1479 logging.warning('%s: Host was manually re-installed without '
1480 '--lab_preserve_log option. Skip collecting '
1481 'crash-logs.', self._CRASHLOGS_PREFIX)
1482
1483 # We make crash collection be one-time effort.
1484 # _collect_prior_logs() and _collect_system_logs() will not throw
1485 # any exception, and following codes will be executed even when
1486 # those methods fail.
1487 # _collect_crashlogs() is called only when the host is up (refer
1488 # to try_collect_crashlogs()). We assume _collect_prior_logs() and
1489 # _collect_system_logs() fail rarely when the host is up.
1490 # In addition, it is not clear how many times we should try crash
1491 # collection again while not triggering next repair unnecessarily.
1492 # Threfore, we try crash collection one time.
1493
1494 # Create a marker file as soon as log collection is done.
1495 # Leave the job id to this marker for gs_offloader to consume.
1496 marker_file = os.path.join(crashlogs_dir, constants.CRASHLOGS_MARKER)
1497 with open(marker_file, 'a') as f:
1498 f.write('%s\n' % job_id)
1499
1500 # Remove need_crash_logs attribute
1501 logging.debug('%s: Remove attribute need_crash_logs from host %s',
1502 self._CRASHLOGS_PREFIX, self.hostname)
1503 self._AFE.set_host_attribute(constants.CRASHLOGS_HOST_ATTRIBUTE,
1504 None, hostname=self.hostname)
1505
1506 if flag_prior_logs:
1507 logging.debug('%s: Remove %s from host %s', self._CRASHLOGS_PREFIX,
1508 client_constants.PRIOR_LOGS_DIR, self.hostname)
1509 self.run('rm -rf %s; sync' % client_constants.PRIOR_LOGS_DIR)
1510 # Wait for a few seconds to make sure the prior command is
1511 # done deep through storage.
1512 time.sleep(self._SAFE_WAIT_SECS)
1513
1514
1515 def _collect_prior_logs(self, crashlogs_dir):
1516 """Grab prior logs that were stashed before re-installing a host.
1517
1518 @param crashlogs_dir: Directory path where crash-logs are stored.
1519 """
1520 logging.debug('%s: Found %s, collecting them...',
1521 self._CRASHLOGS_PREFIX, client_constants.PRIOR_LOGS_DIR)
1522 try:
1523 self.collect_logs(client_constants.PRIOR_LOGS_DIR,
1524 crashlogs_dir, False)
1525 logging.debug('%s: %s is collected',
1526 self._CRASHLOGS_PREFIX, client_constants.PRIOR_LOGS_DIR)
1527 except Exception as e:
1528 logging.error('%s: Failed to collect %s: %s',
1529 self._CRASHLOGS_PREFIX, client_constants.PRIOR_LOGS_DIR,
1530 e)
1531
1532
1533 def _collect_system_logs(self, crashlogs_dir):
1534 """Grab normal system logs from a host.
1535
1536 @param crashlogs_dir: Directory path where crash-logs are stored.
1537 """
1538 logging.debug('%s: Found %s, collecting system logs...',
1539 self._CRASHLOGS_PREFIX, self._LAB_MACHINE_FILE)
1540 sources = server_utils.parse_simple_config(self._LOGS_TO_COLLECT_FILE)
1541 for src in sources:
1542 try:
1543 if self.path_exists(src):
1544 logging.debug('%s: Collecting %s...',
1545 self._CRASHLOGS_PREFIX, src)
1546 dest = server_utils.concat_path_except_last(
1547 crashlogs_dir, src)
1548 self.collect_logs(src, dest, False)
1549 logging.debug('%s: %s is collected',
1550 self._CRASHLOGS_PREFIX, src)
1551 except Exception as e:
1552 logging.error('%s: Failed to collect %s: %s',
1553 self._CRASHLOGS_PREFIX, src, e)
1554
1555
J. Richard Barnette1d78b012012-05-15 13:56:30 -07001556 def close(self):
Fang Deng0ca40e22013-08-27 17:47:44 -07001557 super(CrosHost, self).close()
J. Richard Barnette1d78b012012-05-15 13:56:30 -07001558
1559
Dan Shi49ca0932014-11-14 11:22:27 -08001560 def get_power_supply_info(self):
1561 """Get the output of power_supply_info.
1562
1563 power_supply_info outputs the info of each power supply, e.g.,
1564 Device: Line Power
1565 online: no
1566 type: Mains
1567 voltage (V): 0
1568 current (A): 0
1569 Device: Battery
1570 state: Discharging
1571 percentage: 95.9276
1572 technology: Li-ion
1573
1574 Above output shows two devices, Line Power and Battery, with details of
1575 each device listed. This function parses the output into a dictionary,
1576 with key being the device name, and value being a dictionary of details
1577 of the device info.
1578
1579 @return: The dictionary of power_supply_info, e.g.,
1580 {'Line Power': {'online': 'yes', 'type': 'main'},
1581 'Battery': {'vendor': 'xyz', 'percentage': '100'}}
Dan Shie9b765d2014-12-29 16:59:49 -08001582 @raise error.AutoservRunError if power_supply_info tool is not found in
1583 the DUT. Caller should handle this error to avoid false failure
1584 on verification.
Dan Shi49ca0932014-11-14 11:22:27 -08001585 """
1586 result = self.run('power_supply_info').stdout.strip()
1587 info = {}
1588 device_name = None
1589 device_info = {}
1590 for line in result.split('\n'):
1591 pair = [v.strip() for v in line.split(':')]
1592 if len(pair) != 2:
1593 continue
1594 if pair[0] == 'Device':
1595 if device_name:
1596 info[device_name] = device_info
1597 device_name = pair[1]
1598 device_info = {}
1599 else:
1600 device_info[pair[0]] = pair[1]
1601 if device_name and not device_name in info:
1602 info[device_name] = device_info
1603 return info
1604
1605
1606 def get_battery_percentage(self):
1607 """Get the battery percentage.
1608
1609 @return: The percentage of battery level, value range from 0-100. Return
1610 None if the battery info cannot be retrieved.
1611 """
1612 try:
1613 info = self.get_power_supply_info()
1614 logging.info(info)
1615 return float(info['Battery']['percentage'])
Dan Shie9b765d2014-12-29 16:59:49 -08001616 except (KeyError, ValueError, error.AutoservRunError):
Dan Shi49ca0932014-11-14 11:22:27 -08001617 return None
1618
1619
1620 def is_ac_connected(self):
1621 """Check if the dut has power adapter connected and charging.
1622
1623 @return: True if power adapter is connected and charging.
1624 """
1625 try:
1626 info = self.get_power_supply_info()
1627 return info['Line Power']['online'] == 'yes'
Dan Shie9b765d2014-12-29 16:59:49 -08001628 except (KeyError, error.AutoservRunError):
1629 return None
Dan Shi49ca0932014-11-14 11:22:27 -08001630
1631
Simran Basi5e6339a2013-03-21 11:34:32 -07001632 def _cleanup_poweron(self):
1633 """Special cleanup method to make sure hosts always get power back."""
1634 afe = frontend_wrappers.RetryingAFE(timeout_min=5, delay_sec=10)
1635 hosts = afe.get_hosts(hostname=self.hostname)
1636 if not hosts or not (self._RPM_OUTLET_CHANGED in
1637 hosts[0].attributes):
1638 return
1639 logging.debug('This host has recently interacted with the RPM'
1640 ' Infrastructure. Ensuring power is on.')
1641 try:
1642 self.power_on()
Dan Shi7dca56e2014-11-11 17:07:56 -08001643 afe.set_host_attribute(self._RPM_OUTLET_CHANGED, None,
1644 hostname=self.hostname)
Simran Basi5e6339a2013-03-21 11:34:32 -07001645 except rpm_client.RemotePowerException:
Simran Basi5e6339a2013-03-21 11:34:32 -07001646 logging.error('Failed to turn Power On for this host after '
1647 'cleanup through the RPM Infrastructure.')
Gabe Blackb72f4fb2015-01-20 16:47:13 -08001648 autotest_es.post(
Dan Shi7dca56e2014-11-11 17:07:56 -08001649 type_str='RPM_poweron_failure',
1650 metadata={'hostname': self.hostname})
Dan Shi49ca0932014-11-14 11:22:27 -08001651
1652 battery_percentage = self.get_battery_percentage()
Dan Shif01ebe22014-12-05 13:10:57 -08001653 if battery_percentage and battery_percentage < 50:
Dan Shi49ca0932014-11-14 11:22:27 -08001654 raise
1655 elif self.is_ac_connected():
1656 logging.info('The device has power adapter connected and '
1657 'charging. No need to try to turn RPM on '
1658 'again.')
1659 afe.set_host_attribute(self._RPM_OUTLET_CHANGED, None,
1660 hostname=self.hostname)
1661 logging.info('Battery level is now at %s%%. The device may '
1662 'still have enough power to run test, so no '
1663 'exception will be raised.', battery_percentage)
1664
Simran Basi5e6339a2013-03-21 11:34:32 -07001665
beepsc87ff602013-07-31 21:53:00 -07001666 def _is_factory_image(self):
1667 """Checks if the image on the DUT is a factory image.
1668
1669 @return: True if the image on the DUT is a factory image.
1670 False otherwise.
1671 """
1672 result = self.run('[ -f /root/.factory_test ]', ignore_status=True)
1673 return result.exit_status == 0
1674
1675
1676 def _restart_ui(self):
J. Richard Barnette84890bd2014-02-21 11:05:47 -08001677 """Restart the Chrome UI.
beepsc87ff602013-07-31 21:53:00 -07001678
1679 @raises: FactoryImageCheckerException for factory images, since
1680 we cannot attempt to restart ui on them.
1681 error.AutoservRunError for any other type of error that
1682 occurs while restarting ui.
1683 """
1684 if self._is_factory_image():
Dan Shi549fb822015-03-24 18:01:11 -07001685 raise FactoryImageCheckerException('Cannot restart ui on factory '
1686 'images')
beepsc87ff602013-07-31 21:53:00 -07001687
J. Richard Barnette84890bd2014-02-21 11:05:47 -08001688 # TODO(jrbarnette): The command to stop/start the ui job
1689 # should live inside cros_ui, too. However that would seem
1690 # to imply interface changes to the existing start()/restart()
1691 # functions, which is a bridge too far (for now).
J. Richard Barnette6069aa12015-06-08 09:10:24 -07001692 prompt = cros_ui.get_chrome_session_ident(self)
J. Richard Barnette84890bd2014-02-21 11:05:47 -08001693 self.run('stop ui; start ui')
1694 cros_ui.wait_for_chrome_ready(prompt, self)
beepsc87ff602013-07-31 21:53:00 -07001695
1696
Dan Shi549fb822015-03-24 18:01:11 -07001697 def get_release_version(self):
1698 """Get the value of attribute CHROMEOS_RELEASE_VERSION from lsb-release.
1699
1700 @returns The version string in lsb-release, under attribute
1701 CHROMEOS_RELEASE_VERSION.
1702 """
1703 lsb_release_content = self.run(
1704 'cat "%s"' % client_constants.LSB_RELEASE).stdout.strip()
1705 return lsbrelease_utils.get_chromeos_release_version(
1706 lsb_release_content=lsb_release_content)
1707
1708
1709 def verify_cros_version_label(self):
1710 """ Make sure host's cros-version label match the actual image in dut.
1711
1712 Remove any cros-version: label that doesn't match that installed in
1713 the dut.
1714
1715 @param raise_error: Set to True to raise exception if any mismatch found
1716
1717 @raise error.AutoservError: If any mismatch between cros-version label
1718 and the build installed in dut is found.
1719 """
1720 labels = self._AFE.get_labels(
1721 name__startswith=ds_constants.VERSION_PREFIX,
1722 host__hostname=self.hostname)
1723 mismatch_found = False
1724 if labels:
1725 # Get CHROMEOS_RELEASE_VERSION from lsb-release, e.g., 6908.0.0.
1726 # Note that it's different from cros-version label, which has
1727 # builder and branch info, e.g.,
1728 # cros-version:peppy-release/R43-6908.0.0
1729 release_version = self.get_release_version()
1730 host_list = [self.hostname]
1731 for label in labels:
1732 # Remove any cros-version label that does not match
1733 # release_version.
1734 build_version = label.name[len(ds_constants.VERSION_PREFIX):]
1735 if not utils.version_match(build_version, release_version):
1736 logging.warn('cros-version label "%s" does not match '
1737 'release version %s. Removing the label.',
1738 label.name, release_version)
1739 label.remove_hosts(hosts=host_list)
1740 mismatch_found = True
1741 if mismatch_found:
Dan Shi1057bae2015-03-30 11:35:09 -07001742 autotest_es.post(use_http=True,
1743 type_str='cros_version_label_mismatch',
1744 metadata={'hostname': self.hostname})
Dan Shi549fb822015-03-24 18:01:11 -07001745 raise error.AutoservError('The host has wrong cros-version label.')
1746
1747
Darren Krahn0bd18e82015-10-28 23:30:46 +00001748 def verify_tpm_status(self):
1749 """ Verify the host's TPM is in a good state.
1750
1751 @raise error.AutoservError: If state is not good.
1752 """
1753 # This cryptohome command emits status information in JSON format. It
1754 # looks something like this:
1755 # {
1756 # "installattrs": {
1757 # "first_install": false,
1758 # "initialized": true,
1759 # "invalid": false,
1760 # "lockbox_index": 536870916,
1761 # "lockbox_nvram_version": 2,
1762 # "secure": true,
1763 # "size": 0,
1764 # "version": 1
1765 # },
1766 # "mounts": [ {
1767 # "enterprise": false,
1768 # "keysets": [ {
1769 # "current": true,
1770 # "index": 0,
1771 # "last_activity": 1330111359,
1772 # "ok": true,
1773 # "scrypt": true,
1774 # "tpm": false
1775 # } ],
1776 # "mounted": true,
1777 # "owner": "dbb3dd34edb181245130e136be51fa08478d3909"
1778 # } ],
1779 # "tpm": {
1780 # "being_owned": false,
1781 # "can_connect": true,
1782 # "can_decrypt": false,
1783 # "can_encrypt": false,
1784 # "can_load_srk": true,
1785 # "can_load_srk_pubkey": true,
1786 # "enabled": true,
1787 # "has_context": true,
1788 # "has_cryptohome_key": false,
1789 # "has_key_handle": false,
1790 # "last_error": 0,
1791 # "owned": true
1792 # }
1793 # }
1794 output = self.run('cryptohome --action=status').stdout.strip()
1795 try:
1796 status = json.loads(output)
1797 except ValueError:
1798 logging.error('TPM_VERIFY: Cryptohome did not return valid status.')
1799 return
1800 try:
1801 tpm = status['tpm']
1802 if (not tpm['enabled'] or not tpm['can_connect'] or
1803 (tpm['owned'] and not tpm['can_load_srk']) or
1804 (tpm['can_load_srk'] and not tpm['can_load_srk_pubkey'])):
1805 logging.error('TPM_VERIFY: The host TPM is in a bad state.')
1806 raise error.AutoservError('The host TPM is in a bad state.')
1807 else:
1808 logging.debug('TPM_VERIFY: The host TPM is in a good state.')
1809 except KeyError:
1810 logging.error('TPM_VERIFY: Cryptohome did not return valid status.')
1811
1812
Tom Wai-Hong Tambea741c2016-01-21 07:20:14 +08001813 def verify_firmware_status(self):
1814 """Verify the host's firmware is in a good state.
1815
1816 @raise error.AutoservError: If state is not good.
1817 """
1818 if self._is_firmware_repair_supported():
Tom Wai-Hong Tam93a29562016-01-23 04:16:53 +08001819 try:
1820 # Read the AP firmware and dump the sections we are interested.
1821 cmd = ('mkdir /tmp/verify_firmware; '
1822 'cd /tmp/verify_firmware; '
1823 'for section in VBLOCK_A VBLOCK_B FW_MAIN_A FW_MAIN_B; '
1824 'do flashrom -r image.bin -i $section:$section; '
1825 'done')
1826 self.run(cmd)
1827
1828 # Verify the firmware blocks A and B.
1829 cmd = ('vbutil_firmware --verify /tmp/verify_firmware/VBLOCK_%c'
1830 ' --signpubkey /usr/share/vboot/devkeys/root_key.vbpubk'
1831 ' --fv /tmp/verify_firmware/FW_MAIN_%c')
1832 for c in ('A', 'B'):
1833 rv = self.run(cmd % (c, c), ignore_status=True)
1834 if rv.exit_status:
1835 raise error.AutoservError(
1836 'Firmware %c is in a bad state.' % c)
1837 finally:
1838 # Remove the tempoary files.
1839 self.run('rm -rf /tmp/verify_firmware')
Tom Wai-Hong Tambea741c2016-01-21 07:20:14 +08001840 else:
1841 logging.info('Do not care about firmware status when the host '
1842 'is not in pools that support firmware repair.')
1843
1844
Shelley Chena11b9e72016-01-21 15:15:18 -08001845 def verify_filesystem_write_status(self):
1846 """Verify the DUT's filesystem is read/writable
1847
1848 @raise error.AutoservError: if filesystem is not writable.
1849 """
1850 # try to create & delete a file
1851 filename = "/mnt/stateful_partition/test.txt"
1852 cmd = 'touch %s && rm %s' % (filename, filename)
1853 rv = self.run(command=cmd, ignore_status=True)
1854
1855 if rv.exit_status == 1:
1856 raise error.AutoservError('DUT filesystem is read-only.')
1857
1858
beepsc87ff602013-07-31 21:53:00 -07001859 def cleanup(self):
MK Ryu35d661e2014-09-25 17:44:10 -07001860 self.run('rm -f %s' % client_constants.CLEANUP_LOGS_PAUSED_FILE)
Scott Zawalskiddbc31e2012-11-15 11:29:01 -05001861 try:
beepsc87ff602013-07-31 21:53:00 -07001862 self._restart_ui()
1863 except (error.AutotestRunError, error.AutoservRunError,
1864 FactoryImageCheckerException):
Ilja H. Friedel04be2bd2014-05-07 21:29:59 -07001865 logging.warning('Unable to restart ui, rebooting device.')
Scott Zawalskiddbc31e2012-11-15 11:29:01 -05001866 # Since restarting the UI fails fall back to normal Autotest
1867 # cleanup routines, i.e. reboot the machine.
Fang Deng0ca40e22013-08-27 17:47:44 -07001868 super(CrosHost, self).cleanup()
Simran Basi5e6339a2013-03-21 11:34:32 -07001869 # Check if the rpm outlet was manipulated.
Simran Basid5e5e272012-09-24 15:23:59 -07001870 if self.has_power():
Simran Basi5e6339a2013-03-21 11:34:32 -07001871 self._cleanup_poweron()
Dan Shi549fb822015-03-24 18:01:11 -07001872 self.verify_cros_version_label()
J. Richard Barnette45e93de2012-04-11 17:24:15 -07001873
1874
Yu-Ju Honga2be94a2012-07-31 09:48:52 -07001875 def reboot(self, **dargs):
1876 """
1877 This function reboots the site host. The more generic
1878 RemoteHost.reboot() performs sync and sleeps for 5
1879 seconds. This is not necessary for Chrome OS devices as the
1880 sync should be finished in a short time during the reboot
1881 command.
1882 """
Tom Wai-Hong Tamf5cd1d42012-08-13 12:04:08 +08001883 if 'reboot_cmd' not in dargs:
Doug Anderson7d5aeb22014-02-27 15:12:17 -08001884 reboot_timeout = dargs.get('reboot_timeout', 10)
J. Richard Barnette9af19632015-09-25 12:18:03 -07001885 dargs['reboot_cmd'] = ('sleep 1; '
1886 'reboot & sleep %d; '
1887 'reboot -f' % reboot_timeout)
Yu-Ju Honga2be94a2012-07-31 09:48:52 -07001888 # Enable fastsync to avoid running extra sync commands before reboot.
Tom Wai-Hong Tamf5cd1d42012-08-13 12:04:08 +08001889 if 'fastsync' not in dargs:
1890 dargs['fastsync'] = True
Michael Liangda8c60a2014-06-03 13:24:51 -07001891
Charlie Mooneya8e6dab2014-05-29 14:37:55 -07001892 # For purposes of logging reboot times:
1893 # Get the board name i.e. 'daisy_spring'
Michael Liangca4f5a62014-07-10 15:45:13 -07001894 board_fullname = self.get_board()
1895
1896 # Strip the prefix and add it to dargs.
1897 dargs['board'] = board_fullname[board_fullname.find(':')+1:]
Fang Deng0ca40e22013-08-27 17:47:44 -07001898 super(CrosHost, self).reboot(**dargs)
Yu-Ju Honga2be94a2012-07-31 09:48:52 -07001899
1900
Gwendal Grignou7a61d2f2014-05-23 11:05:51 -07001901 def suspend(self, **dargs):
1902 """
1903 This function suspends the site host.
1904 """
1905 suspend_time = dargs.get('suspend_time', 60)
1906 dargs['timeout'] = suspend_time
1907 if 'suspend_cmd' not in dargs:
J. Richard Barnette9af19632015-09-25 12:18:03 -07001908 dargs['suspend_cmd'] = ' && '.join([
1909 'echo 0 > /sys/class/rtc/rtc0/wakealarm',
Gwendal Grignou7a61d2f2014-05-23 11:05:51 -07001910 'echo +%d > /sys/class/rtc/rtc0/wakealarm' % suspend_time,
J. Richard Barnette9af19632015-09-25 12:18:03 -07001911 'powerd_dbus_suspend --delay=0'])
Gwendal Grignou7a61d2f2014-05-23 11:05:51 -07001912 super(CrosHost, self).suspend(**dargs)
1913
1914
Simran Basiec564392014-08-25 16:48:09 -07001915 def upstart_status(self, service_name):
1916 """Check the status of an upstart init script.
1917
1918 @param service_name: Service to look up.
1919
1920 @returns True if the service is running, False otherwise.
1921 """
1922 return self.run('status %s | grep start/running' %
1923 service_name).stdout.strip() != ''
1924
1925
J. Richard Barnette45e93de2012-04-11 17:24:15 -07001926 def verify_software(self):
Richard Barnetteb2bc13c2013-01-08 17:32:51 -08001927 """Verify working software on a Chrome OS system.
J. Richard Barnette45e93de2012-04-11 17:24:15 -07001928
Richard Barnetteb2bc13c2013-01-08 17:32:51 -08001929 Tests for the following conditions:
1930 1. All conditions tested by the parent version of this
1931 function.
1932 2. Sufficient space in /mnt/stateful_partition.
Fang Deng6b05f5b2013-03-20 13:42:11 -07001933 3. Sufficient space in /mnt/stateful_partition/encrypted.
1934 4. update_engine answers a simple status request over DBus.
J. Richard Barnette45e93de2012-04-11 17:24:15 -07001935
J. Richard Barnette45e93de2012-04-11 17:24:15 -07001936 """
MK Ryu35d661e2014-09-25 17:44:10 -07001937 # Check if a job was crashed on this host.
1938 # If yes, avoid verification until crash-logs are collected.
1939 if self._need_crash_logs():
1940 raise error.AutoservCrashLogCollectRequired(
1941 'Need to collect crash-logs before verification')
1942
Fang Deng0ca40e22013-08-27 17:47:44 -07001943 super(CrosHost, self).verify_software()
Dan Shib8540a52015-07-16 14:18:23 -07001944 default_kilo_inodes_required = CONFIG.get_config_value(
1945 'SERVER', 'kilo_inodes_required', type=int, default=100)
1946 board = self.get_board().replace(ds_constants.BOARD_PREFIX, '')
1947 kilo_inodes_required = CONFIG.get_config_value(
1948 'SERVER', 'kilo_inodes_required_%s' % board,
1949 type=int, default=default_kilo_inodes_required)
1950 self.check_inodes('/mnt/stateful_partition', kilo_inodes_required)
J. Richard Barnette45e93de2012-04-11 17:24:15 -07001951 self.check_diskspace(
1952 '/mnt/stateful_partition',
Dan Shib8540a52015-07-16 14:18:23 -07001953 CONFIG.get_config_value(
Fang Deng6b05f5b2013-03-20 13:42:11 -07001954 'SERVER', 'gb_diskspace_required', type=float,
1955 default=20.0))
Gaurav Shahe448af82014-06-19 15:18:59 -07001956 encrypted_stateful_path = '/mnt/stateful_partition/encrypted'
1957 # Not all targets build with encrypted stateful support.
1958 if self.path_exists(encrypted_stateful_path):
1959 self.check_diskspace(
1960 encrypted_stateful_path,
Dan Shib8540a52015-07-16 14:18:23 -07001961 CONFIG.get_config_value(
Gaurav Shahe448af82014-06-19 15:18:59 -07001962 'SERVER', 'gb_encrypted_diskspace_required', type=float,
1963 default=0.1))
beepsc87ff602013-07-31 21:53:00 -07001964
Simran Basiec564392014-08-25 16:48:09 -07001965 if not self.upstart_status('system-services'):
Prashanth B5d0a0512014-04-25 12:26:08 -07001966 raise error.AutoservError('Chrome failed to reach login. '
1967 'System services not running.')
1968
beepsc87ff602013-07-31 21:53:00 -07001969 # Factory images don't run update engine,
1970 # goofy controls dbus on these DUTs.
1971 if not self._is_factory_image():
1972 self.run('update_engine_client --status')
Scott Zawalskifbca4a92013-03-04 15:56:42 -05001973 # Makes sure python is present, loads and can use built in functions.
1974 # We have seen cases where importing cPickle fails with undefined
1975 # symbols in cPickle.so.
1976 self.run('python -c "import cPickle"')
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001977
Dan Shi549fb822015-03-24 18:01:11 -07001978 self.verify_cros_version_label()
1979
Darren Krahn0bd18e82015-10-28 23:30:46 +00001980 self.verify_tpm_status()
1981
Tom Wai-Hong Tambea741c2016-01-21 07:20:14 +08001982 self.verify_firmware_status()
1983
Shelley Chena11b9e72016-01-21 15:15:18 -08001984 self.verify_filesystem_write_status()
1985
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001986
J. Richard Barnettea7e7fdc2016-02-12 12:35:36 -08001987 def verify(self):
1988 self._repair_strategy.verify(self)
1989
1990
Fang Deng96667ca2013-08-01 17:46:18 -07001991 def make_ssh_command(self, user='root', port=22, opts='', hosts_file=None,
1992 connect_timeout=None, alive_interval=None):
1993 """Override default make_ssh_command to use options tuned for Chrome OS.
1994
1995 Tuning changes:
1996 - ConnectTimeout=30; maximum of 30 seconds allowed for an SSH
1997 connection failure. Consistency with remote_access.sh.
1998
Samuel Tan2ce155b2015-06-23 18:24:38 -07001999 - ServerAliveInterval=900; which causes SSH to ping connection every
2000 900 seconds. In conjunction with ServerAliveCountMax ensures
2001 that if the connection dies, Autotest will bail out.
Fang Deng96667ca2013-08-01 17:46:18 -07002002 Originally tried 60 secs, but saw frequent job ABORTS where
Samuel Tan2ce155b2015-06-23 18:24:38 -07002003 the test completed successfully. Later increased from 180 seconds to
2004 900 seconds to account for tests where the DUT is suspended for
2005 longer periods of time.
Fang Deng96667ca2013-08-01 17:46:18 -07002006
2007 - ServerAliveCountMax=3; consistency with remote_access.sh.
2008
2009 - ConnectAttempts=4; reduce flakiness in connection errors;
2010 consistency with remote_access.sh.
2011
2012 - UserKnownHostsFile=/dev/null; we don't care about the keys.
2013 Host keys change with every new installation, don't waste
2014 memory/space saving them.
2015
2016 - SSH protocol forced to 2; needed for ServerAliveInterval.
2017
2018 @param user User name to use for the ssh connection.
2019 @param port Port on the target host to use for ssh connection.
2020 @param opts Additional options to the ssh command.
2021 @param hosts_file Ignored.
2022 @param connect_timeout Ignored.
2023 @param alive_interval Ignored.
2024 """
Aviv Keshetc5947fa2013-09-04 14:06:29 -07002025 base_command = ('/usr/bin/ssh -a -x %s %s %s'
2026 ' -o StrictHostKeyChecking=no'
Fang Deng96667ca2013-08-01 17:46:18 -07002027 ' -o UserKnownHostsFile=/dev/null -o BatchMode=yes'
Samuel Tan2ce155b2015-06-23 18:24:38 -07002028 ' -o ConnectTimeout=30 -o ServerAliveInterval=900'
Fang Deng96667ca2013-08-01 17:46:18 -07002029 ' -o ServerAliveCountMax=3 -o ConnectionAttempts=4'
2030 ' -o Protocol=2 -l %s -p %d')
Aviv Keshetc5947fa2013-09-04 14:06:29 -07002031 return base_command % (self._ssh_verbosity_flag, self._ssh_options,
2032 opts, user, port)
Jason Abeleb6f924f2013-11-13 16:01:54 -08002033 def syslog(self, message, tag='autotest'):
2034 """Logs a message to syslog on host.
2035
2036 @param message String message to log into syslog
2037 @param tag String tag prefix for syslog
2038
2039 """
2040 self.run('logger -t "%s" "%s"' % (tag, message))
2041
2042
J. Richard Barnetteb6de7e32013-02-14 13:28:04 -08002043 def _ping_check_status(self, status):
2044 """Ping the host once, and return whether it has a given status.
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002045
J. Richard Barnetteb6de7e32013-02-14 13:28:04 -08002046 @param status Check the ping status against this value.
2047 @return True iff `status` and the result of ping are the same
2048 (i.e. both True or both False).
2049
2050 """
2051 ping_val = utils.ping(self.hostname, tries=1, deadline=1)
2052 return not (status ^ (ping_val == 0))
2053
2054 def _ping_wait_for_status(self, status, timeout):
2055 """Wait for the host to have a given status (UP or DOWN).
2056
2057 Status is checked by polling. Polling will not last longer
2058 than the number of seconds in `timeout`. The polling
2059 interval will be long enough that only approximately
2060 _PING_WAIT_COUNT polling cycles will be executed, subject
2061 to a maximum interval of about one minute.
2062
2063 @param status Waiting will stop immediately if `ping` of the
2064 host returns this status.
2065 @param timeout Poll for at most this many seconds.
2066 @return True iff the host status from `ping` matched the
2067 requested status at the time of return.
2068
2069 """
2070 # _ping_check_status() takes about 1 second, hence the
2071 # "- 1" in the formula below.
2072 poll_interval = min(int(timeout / self._PING_WAIT_COUNT), 60) - 1
2073 end_time = time.time() + timeout
2074 while time.time() <= end_time:
2075 if self._ping_check_status(status):
2076 return True
2077 if poll_interval > 0:
2078 time.sleep(poll_interval)
2079
2080 # The last thing we did was sleep(poll_interval), so it may
2081 # have been too long since the last `ping`. Check one more
2082 # time, just to be sure.
2083 return self._ping_check_status(status)
2084
2085 def ping_wait_up(self, timeout):
2086 """Wait for the host to respond to `ping`.
2087
2088 N.B. This method is not a reliable substitute for
2089 `wait_up()`, because a host that responds to ping will not
2090 necessarily respond to ssh. This method should only be used
2091 if the target DUT can be considered functional even if it
2092 can't be reached via ssh.
2093
2094 @param timeout Minimum time to allow before declaring the
2095 host to be non-responsive.
2096 @return True iff the host answered to ping before the timeout.
2097
2098 """
2099 return self._ping_wait_for_status(self._PING_STATUS_UP, timeout)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002100
Andrew Bresticker678c0c72013-01-22 10:44:09 -08002101 def ping_wait_down(self, timeout):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002102 """Wait until the host no longer responds to `ping`.
2103
J. Richard Barnetteb6de7e32013-02-14 13:28:04 -08002104 This function can be used as a slightly faster version of
2105 `wait_down()`, by avoiding potentially long ssh timeouts.
2106
2107 @param timeout Minimum time to allow for the host to become
2108 non-responsive.
2109 @return True iff the host quit answering ping before the
2110 timeout.
2111
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002112 """
J. Richard Barnetteb6de7e32013-02-14 13:28:04 -08002113 return self._ping_wait_for_status(self._PING_STATUS_DOWN, timeout)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002114
Tom Wai-Hong Tamfced4f62014-04-17 10:56:30 +08002115 def test_wait_for_sleep(self, sleep_timeout=None):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002116 """Wait for the client to enter low-power sleep mode.
2117
2118 The test for "is asleep" can't distinguish a system that is
2119 powered off; to confirm that the unit was asleep, it is
2120 necessary to force resume, and then call
2121 `test_wait_for_resume()`.
2122
2123 This function is expected to be called from a test as part
2124 of a sequence like the following:
2125
2126 ~~~~~~~~
2127 boot_id = host.get_boot_id()
2128 # trigger sleep on the host
2129 host.test_wait_for_sleep()
2130 # trigger resume on the host
2131 host.test_wait_for_resume(boot_id)
2132 ~~~~~~~~
2133
Tom Wai-Hong Tamfced4f62014-04-17 10:56:30 +08002134 @param sleep_timeout time limit in seconds to allow the host sleep.
2135
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002136 @exception TestFail The host did not go to sleep within
2137 the allowed time.
2138 """
Tom Wai-Hong Tamfced4f62014-04-17 10:56:30 +08002139 if sleep_timeout is None:
2140 sleep_timeout = self.SLEEP_TIMEOUT
2141
2142 if not self.ping_wait_down(timeout=sleep_timeout):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002143 raise error.TestFail(
Tom Wai-Hong Tamfced4f62014-04-17 10:56:30 +08002144 'client failed to sleep after %d seconds' % sleep_timeout)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002145
2146
Tom Wai-Hong Tamfced4f62014-04-17 10:56:30 +08002147 def test_wait_for_resume(self, old_boot_id, resume_timeout=None):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002148 """Wait for the client to resume from low-power sleep mode.
2149
2150 The `old_boot_id` parameter should be the value from
2151 `get_boot_id()` obtained prior to entering sleep mode. A
2152 `TestFail` exception is raised if the boot id changes.
2153
2154 See @ref test_wait_for_sleep for more on this function's
2155 usage.
2156
J. Richard Barnette7214e0b2013-02-06 15:20:49 -08002157 @param old_boot_id A boot id value obtained before the
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002158 target host went to sleep.
Tom Wai-Hong Tamfced4f62014-04-17 10:56:30 +08002159 @param resume_timeout time limit in seconds to allow the host up.
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002160
2161 @exception TestFail The host did not respond within the
2162 allowed time.
2163 @exception TestFail The host responded, but the boot id test
2164 indicated a reboot rather than a sleep
2165 cycle.
2166 """
Tom Wai-Hong Tamfced4f62014-04-17 10:56:30 +08002167 if resume_timeout is None:
2168 resume_timeout = self.RESUME_TIMEOUT
2169
2170 if not self.wait_up(timeout=resume_timeout):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002171 raise error.TestFail(
2172 'client failed to resume from sleep after %d seconds' %
Tom Wai-Hong Tamfced4f62014-04-17 10:56:30 +08002173 resume_timeout)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002174 else:
2175 new_boot_id = self.get_boot_id()
2176 if new_boot_id != old_boot_id:
Tom Wai-Hong Tam01792682015-01-06 08:00:46 +08002177 logging.error('client rebooted (old boot %s, new boot %s)',
2178 old_boot_id, new_boot_id)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002179 raise error.TestFail(
Tom Wai-Hong Tam01792682015-01-06 08:00:46 +08002180 'client rebooted, but sleep was expected')
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002181
2182
Tom Wai-Hong Tamfe005c22014-12-03 09:25:44 +08002183 def test_wait_for_shutdown(self, shutdown_timeout=None):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002184 """Wait for the client to shut down.
2185
2186 The test for "has shut down" can't distinguish a system that
2187 is merely asleep; to confirm that the unit was down, it is
2188 necessary to force boot, and then call test_wait_for_boot().
2189
2190 This function is expected to be called from a test as part
2191 of a sequence like the following:
2192
2193 ~~~~~~~~
2194 boot_id = host.get_boot_id()
2195 # trigger shutdown on the host
2196 host.test_wait_for_shutdown()
2197 # trigger boot on the host
2198 host.test_wait_for_boot(boot_id)
2199 ~~~~~~~~
2200
Tom Wai-Hong Tamfe005c22014-12-03 09:25:44 +08002201 @param shutdown_timeout time limit in seconds to allow the host down.
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002202 @exception TestFail The host did not shut down within the
2203 allowed time.
2204 """
Tom Wai-Hong Tamfe005c22014-12-03 09:25:44 +08002205 if shutdown_timeout is None:
2206 shutdown_timeout = self.SHUTDOWN_TIMEOUT
2207
2208 if not self.ping_wait_down(timeout=shutdown_timeout):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002209 raise error.TestFail(
2210 'client failed to shut down after %d seconds' %
Tom Wai-Hong Tamfe005c22014-12-03 09:25:44 +08002211 shutdown_timeout)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002212
2213
2214 def test_wait_for_boot(self, old_boot_id=None):
2215 """Wait for the client to boot from cold power.
2216
2217 The `old_boot_id` parameter should be the value from
2218 `get_boot_id()` obtained prior to shutting down. A
2219 `TestFail` exception is raised if the boot id does not
2220 change. The boot id test is omitted if `old_boot_id` is not
2221 specified.
2222
2223 See @ref test_wait_for_shutdown for more on this function's
2224 usage.
2225
J. Richard Barnette7214e0b2013-02-06 15:20:49 -08002226 @param old_boot_id A boot id value obtained before the
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002227 shut down.
2228
2229 @exception TestFail The host did not respond within the
2230 allowed time.
2231 @exception TestFail The host responded, but the boot id test
2232 indicated that there was no reboot.
2233 """
J. Richard Barnetteeb69d722012-06-18 17:29:44 -07002234 if not self.wait_up(timeout=self.REBOOT_TIMEOUT):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002235 raise error.TestFail(
2236 'client failed to reboot after %d seconds' %
J. Richard Barnetteeb69d722012-06-18 17:29:44 -07002237 self.REBOOT_TIMEOUT)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002238 elif old_boot_id:
2239 if self.get_boot_id() == old_boot_id:
Tom Wai-Hong Tam01792682015-01-06 08:00:46 +08002240 logging.error('client not rebooted (boot %s)',
2241 old_boot_id)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002242 raise error.TestFail(
Tom Wai-Hong Tam01792682015-01-06 08:00:46 +08002243 'client is back up, but did not reboot')
Simran Basid5e5e272012-09-24 15:23:59 -07002244
2245
2246 @staticmethod
2247 def check_for_rpm_support(hostname):
2248 """For a given hostname, return whether or not it is powered by an RPM.
2249
Simran Basi1df55112013-09-06 11:25:09 -07002250 @param hostname: hostname to check for rpm support.
2251
Simran Basid5e5e272012-09-24 15:23:59 -07002252 @return None if this host does not follows the defined naming format
2253 for RPM powered DUT's in the lab. If it does follow the format,
2254 it returns a regular expression MatchObject instead.
2255 """
Fang Dengbaff9082015-01-06 13:46:15 -08002256 return re.match(CrosHost._RPM_HOSTNAME_REGEX, hostname)
Simran Basid5e5e272012-09-24 15:23:59 -07002257
2258
2259 def has_power(self):
2260 """For this host, return whether or not it is powered by an RPM.
2261
2262 @return True if this host is in the CROS lab and follows the defined
2263 naming format.
2264 """
Fang Deng0ca40e22013-08-27 17:47:44 -07002265 return CrosHost.check_for_rpm_support(self.hostname)
Simran Basid5e5e272012-09-24 15:23:59 -07002266
2267
Ismail Noorbasha07fdb612013-02-14 14:13:31 -08002268 def _set_power(self, state, power_method):
2269 """Sets the power to the host via RPM, Servo or manual.
2270
2271 @param state Specifies which power state to set to DUT
2272 @param power_method Specifies which method of power control to
2273 use. By default "RPM" will be used. Valid values
2274 are the strings "RPM", "manual", "servoj10".
2275
2276 """
2277 ACCEPTABLE_STATES = ['ON', 'OFF']
2278
2279 if state.upper() not in ACCEPTABLE_STATES:
2280 raise error.TestError('State must be one of: %s.'
2281 % (ACCEPTABLE_STATES,))
2282
2283 if power_method == self.POWER_CONTROL_SERVO:
2284 logging.info('Setting servo port J10 to %s', state)
2285 self.servo.set('prtctl3_pwren', state.lower())
2286 time.sleep(self._USB_POWER_TIMEOUT)
2287 elif power_method == self.POWER_CONTROL_MANUAL:
2288 logging.info('You have %d seconds to set the AC power to %s.',
2289 self._POWER_CYCLE_TIMEOUT, state)
2290 time.sleep(self._POWER_CYCLE_TIMEOUT)
2291 else:
2292 if not self.has_power():
2293 raise error.TestFail('DUT does not have RPM connected.')
Simran Basi5e6339a2013-03-21 11:34:32 -07002294 afe = frontend_wrappers.RetryingAFE(timeout_min=5, delay_sec=10)
2295 afe.set_host_attribute(self._RPM_OUTLET_CHANGED, True,
2296 hostname=self.hostname)
Simran Basi1df55112013-09-06 11:25:09 -07002297 rpm_client.set_power(self.hostname, state.upper(), timeout_mins=5)
Simran Basid5e5e272012-09-24 15:23:59 -07002298
2299
Ismail Noorbasha07fdb612013-02-14 14:13:31 -08002300 def power_off(self, power_method=POWER_CONTROL_RPM):
2301 """Turn off power to this host via RPM, Servo or manual.
2302
2303 @param power_method Specifies which method of power control to
2304 use. By default "RPM" will be used. Valid values
2305 are the strings "RPM", "manual", "servoj10".
2306
2307 """
2308 self._set_power('OFF', power_method)
Simran Basid5e5e272012-09-24 15:23:59 -07002309
2310
Ismail Noorbasha07fdb612013-02-14 14:13:31 -08002311 def power_on(self, power_method=POWER_CONTROL_RPM):
2312 """Turn on power to this host via RPM, Servo or manual.
2313
2314 @param power_method Specifies which method of power control to
2315 use. By default "RPM" will be used. Valid values
2316 are the strings "RPM", "manual", "servoj10".
2317
2318 """
2319 self._set_power('ON', power_method)
2320
2321
2322 def power_cycle(self, power_method=POWER_CONTROL_RPM):
2323 """Cycle power to this host by turning it OFF, then ON.
2324
2325 @param power_method Specifies which method of power control to
2326 use. By default "RPM" will be used. Valid values
2327 are the strings "RPM", "manual", "servoj10".
2328
2329 """
2330 if power_method in (self.POWER_CONTROL_SERVO,
2331 self.POWER_CONTROL_MANUAL):
2332 self.power_off(power_method=power_method)
2333 time.sleep(self._POWER_CYCLE_TIMEOUT)
2334 self.power_on(power_method=power_method)
2335 else:
2336 rpm_client.set_power(self.hostname, 'CYCLE')
Simran Basic6f1f7a2012-10-16 10:47:46 -07002337
2338
2339 def get_platform(self):
2340 """Determine the correct platform label for this host.
2341
2342 @returns a string representing this host's platform.
2343 """
2344 crossystem = utils.Crossystem(self)
2345 crossystem.init()
2346 # Extract fwid value and use the leading part as the platform id.
2347 # fwid generally follow the format of {platform}.{firmware version}
2348 # Example: Alex.X.YYY.Z or Google_Alex.X.YYY.Z
2349 platform = crossystem.fwid().split('.')[0].lower()
2350 # Newer platforms start with 'Google_' while the older ones do not.
2351 return platform.replace('google_', '')
2352
2353
Hung-ying Tyanb1328032014-04-01 14:18:54 +08002354 def get_architecture(self):
2355 """Determine the correct architecture label for this host.
2356
2357 @returns a string representing this host's architecture.
2358 """
2359 crossystem = utils.Crossystem(self)
2360 crossystem.init()
2361 return crossystem.arch()
2362
2363
Luis Lozano40b7d0d2014-01-17 15:12:06 -08002364 def get_chrome_version(self):
2365 """Gets the Chrome version number and milestone as strings.
2366
2367 Invokes "chrome --version" to get the version number and milestone.
2368
2369 @return A tuple (chrome_ver, milestone) where "chrome_ver" is the
2370 current Chrome version number as a string (in the form "W.X.Y.Z")
2371 and "milestone" is the first component of the version number
2372 (the "W" from "W.X.Y.Z"). If the version number cannot be parsed
2373 in the "W.X.Y.Z" format, the "chrome_ver" will be the full output
2374 of "chrome --version" and the milestone will be the empty string.
2375
2376 """
MK Ryu35d661e2014-09-25 17:44:10 -07002377 version_string = self.run(client_constants.CHROME_VERSION_COMMAND).stdout
Luis Lozano40b7d0d2014-01-17 15:12:06 -08002378 return utils.parse_chrome_version(version_string)
2379
J. Richard Barnetted2af5852016-02-05 15:03:10 -08002380
Aviv Keshet74c89a92013-02-04 15:18:30 -08002381 @label_decorator()
Simran Basic6f1f7a2012-10-16 10:47:46 -07002382 def get_board(self):
2383 """Determine the correct board label for this host.
2384
2385 @returns a string representing this host's board.
2386 """
2387 release_info = utils.parse_cmd_output('cat /etc/lsb-release',
2388 run_method=self.run)
J. Richard Barnetted2af5852016-02-05 15:03:10 -08002389 return (ds_constants.BOARD_PREFIX +
2390 release_info['CHROMEOS_RELEASE_BOARD'])
Simran Basic6f1f7a2012-10-16 10:47:46 -07002391
2392
Aviv Keshet74c89a92013-02-04 15:18:30 -08002393 @label_decorator('lightsensor')
Simran Basic6f1f7a2012-10-16 10:47:46 -07002394 def has_lightsensor(self):
2395 """Determine the correct board label for this host.
2396
2397 @returns the string 'lightsensor' if this host has a lightsensor or
2398 None if it does not.
2399 """
2400 search_cmd = "find -L %s -maxdepth 4 | egrep '%s'" % (
Richard Barnette82c35912012-11-20 10:09:10 -08002401 self._LIGHTSENSOR_SEARCH_DIR, '|'.join(self._LIGHTSENSOR_FILES))
Simran Basic6f1f7a2012-10-16 10:47:46 -07002402 try:
2403 # Run the search cmd following the symlinks. Stderr_tee is set to
2404 # None as there can be a symlink loop, but the command will still
2405 # execute correctly with a few messages printed to stderr.
2406 self.run(search_cmd, stdout_tee=None, stderr_tee=None)
2407 return 'lightsensor'
2408 except error.AutoservRunError:
2409 # egrep exited with a return code of 1 meaning none of the possible
2410 # lightsensor files existed.
2411 return None
2412
2413
Aviv Keshet74c89a92013-02-04 15:18:30 -08002414 @label_decorator('bluetooth')
Simran Basic6f1f7a2012-10-16 10:47:46 -07002415 def has_bluetooth(self):
2416 """Determine the correct board label for this host.
2417
2418 @returns the string 'bluetooth' if this host has bluetooth or
2419 None if it does not.
2420 """
2421 try:
2422 self.run('test -d /sys/class/bluetooth/hci0')
2423 # test exited with a return code of 0.
2424 return 'bluetooth'
2425 except error.AutoservRunError:
2426 # test exited with a return code 1 meaning the directory did not
2427 # exist.
2428 return None
2429
2430
Bill Richardson4f595f52014-02-13 16:20:26 -08002431 @label_decorator('ec')
2432 def get_ec(self):
2433 """
2434 Determine the type of EC on this host.
2435
2436 @returns a string representing this host's embedded controller type.
2437 At present, it only returns "ec:cros", for Chrome OS ECs. Other types
2438 of EC (or none) don't return any strings, since no tests depend on
2439 those.
2440 """
2441 cmd = 'mosys ec info'
2442 # The output should look like these, so that the last field should
2443 # match our EC version scheme:
2444 #
2445 # stm | stm32f100 | snow_v1.3.139-375eb9f
2446 # ti | Unknown-10de | peppy_v1.5.114-5d52788
2447 #
2448 # Non-Chrome OS ECs will look like these:
2449 #
2450 # ENE | KB932 | 00BE107A00
2451 # ite | it8518 | 3.08
2452 #
2453 # And some systems don't have ECs at all (Lumpy, for example).
2454 regexp = r'^.*\|\s*(\S+_v\d+\.\d+\.\d+-[0-9a-f]+)\s*$'
2455
2456 ecinfo = self.run(command=cmd, ignore_status=True)
2457 if ecinfo.exit_status == 0:
2458 res = re.search(regexp, ecinfo.stdout)
2459 if res:
2460 logging.info("EC version is %s", res.groups()[0])
2461 return 'ec:cros'
2462 logging.info("%s got: %s", cmd, ecinfo.stdout)
2463 # Has an EC, but it's not a Chrome OS EC
2464 return None
2465 logging.info("%s exited with status %d", cmd, ecinfo.exit_status)
2466 # No EC present
2467 return None
2468
2469
Alec Berg31b932b2014-04-04 16:09:11 -07002470 @label_decorator('accels')
2471 def get_accels(self):
2472 """
2473 Determine the type of accelerometers on this host.
2474
2475 @returns a string representing this host's accelerometer type.
2476 At present, it only returns "accel:cros-ec", for accelerometers
2477 attached to a Chrome OS EC, or none, if no accelerometers.
2478 """
2479 # Check to make sure we have ectool
2480 rv = self.run('which ectool', ignore_status=True)
2481 if rv.exit_status:
2482 logging.info("No ectool cmd found, assuming no EC accelerometers")
2483 return None
2484
2485 # Check that the EC supports the motionsense command
2486 rv = self.run('ectool motionsense', ignore_status=True)
2487 if rv.exit_status:
2488 logging.info("EC does not support motionsense command "
2489 "assuming no EC accelerometers")
2490 return None
2491
2492 # Check that EC motion sensors are active
2493 active = self.run('ectool motionsense active').stdout.split('\n')
2494 if active[0] == "0":
2495 logging.info("Motion sense inactive, assuming no EC accelerometers")
2496 return None
2497
2498 logging.info("EC accelerometers found")
2499 return 'accel:cros-ec'
2500
2501
Tom Wai-Hong Tam3d6790d2014-04-14 16:15:47 +08002502 @label_decorator('chameleon')
2503 def has_chameleon(self):
2504 """Determine if a Chameleon connected to this host.
2505
Tom Wai-Hong Tambadbb332014-10-10 02:59:41 +08002506 @returns a list containing two strings ('chameleon' and
2507 'chameleon:' + label, e.g. 'chameleon:hdmi') if this host
2508 has a Chameleon or None if it has not.
Tom Wai-Hong Tam3d6790d2014-04-14 16:15:47 +08002509 """
2510 if self._chameleon_host:
Tom Wai-Hong Tambadbb332014-10-10 02:59:41 +08002511 return ['chameleon', 'chameleon:' + self.chameleon.get_label()]
Tom Wai-Hong Tam3d6790d2014-04-14 16:15:47 +08002512 else:
2513 return None
2514
2515
Cheng-Yi Chiangf4104ff2014-12-23 19:39:01 +08002516 @label_decorator('audio_loopback_dongle')
2517 def has_loopback_dongle(self):
2518 """Determine if an audio loopback dongle is plugged to this host.
2519
2520 @returns 'audio_loopback_dongle' when there is an audio loopback dongle
2521 plugged to this host.
2522 None when there is no audio loopback dongle
2523 plugged to this host.
2524 """
Cheng-Yi Chiang8de78112015-05-27 14:47:08 +08002525 nodes_info = self.run(command=cras_utils.get_cras_nodes_cmd(),
2526 ignore_status=True).stdout
2527 if (cras_utils.node_type_is_plugged('HEADPHONE', nodes_info) and
2528 cras_utils.node_type_is_plugged('MIC', nodes_info)):
Cheng-Yi Chiangf4104ff2014-12-23 19:39:01 +08002529 return 'audio_loopback_dongle'
2530 else:
2531 return None
2532
2533
Derek Basehorec71ff622014-07-07 15:18:40 -07002534 @label_decorator('power_supply')
2535 def get_power_supply(self):
2536 """
2537 Determine what type of power supply the host has
2538
2539 @returns a string representing this host's power supply.
2540 'power:battery' when the device has a battery intended for
2541 extended use
2542 'power:AC_primary' when the device has a battery not intended
2543 for extended use (for moving the machine, etc)
2544 'power:AC_only' when the device has no battery at all.
2545 """
2546 psu = self.run(command='mosys psu type', ignore_status=True)
2547 if psu.exit_status:
2548 # The psu command for mosys is not included for all platforms. The
2549 # assumption is that the device will have a battery if the command
2550 # is not found.
2551 return 'power:battery'
2552
2553 psu_str = psu.stdout.strip()
2554 if psu_str == 'unknown':
2555 return None
2556
2557 return 'power:%s' % psu_str
2558
2559
Puthikorn Voravootivatfa011242014-03-14 18:45:11 -07002560 @label_decorator('storage')
2561 def get_storage(self):
2562 """
2563 Determine the type of boot device for this host.
2564
2565 Determine if the internal device is SCSI or dw_mmc device.
2566 Then check that it is SSD or HDD or eMMC or something else.
2567
2568 @returns a string representing this host's internal device type.
2569 'storage:ssd' when internal device is solid state drive
2570 'storage:hdd' when internal device is hard disk drive
2571 'storage:mmc' when internal device is mmc drive
2572 None When internal device is something else or
2573 when we are unable to determine the type
2574 """
2575 # The output should be /dev/mmcblk* for SD/eMMC or /dev/sd* for scsi
2576 rootdev_cmd = ' '.join(['. /usr/sbin/write_gpt.sh;',
2577 '. /usr/share/misc/chromeos-common.sh;',
2578 'load_base_vars;',
2579 'get_fixed_dst_drive'])
Puthikorn Voravootivat03c51682014-04-24 13:52:12 -07002580 rootdev = self.run(command=rootdev_cmd, ignore_status=True)
2581 if rootdev.exit_status:
2582 logging.info("Fail to run %s", rootdev_cmd)
2583 return None
Puthikorn Voravootivatfa011242014-03-14 18:45:11 -07002584 rootdev_str = rootdev.stdout.strip()
2585
2586 if not rootdev_str:
2587 return None
2588
2589 rootdev_base = os.path.basename(rootdev_str)
2590
2591 mmc_pattern = '/dev/mmcblk[0-9]'
2592 if re.match(mmc_pattern, rootdev_str):
2593 # Use type to determine if the internal device is eMMC or somthing
2594 # else. We can assume that MMC is always an internal device.
2595 type_cmd = 'cat /sys/block/%s/device/type' % rootdev_base
Puthikorn Voravootivat03c51682014-04-24 13:52:12 -07002596 type = self.run(command=type_cmd, ignore_status=True)
2597 if type.exit_status:
2598 logging.info("Fail to run %s", type_cmd)
2599 return None
Puthikorn Voravootivatfa011242014-03-14 18:45:11 -07002600 type_str = type.stdout.strip()
2601
2602 if type_str == 'MMC':
2603 return 'storage:mmc'
2604
2605 scsi_pattern = '/dev/sd[a-z]+'
2606 if re.match(scsi_pattern, rootdev.stdout):
2607 # Read symlink for /sys/block/sd* to determine if the internal
2608 # device is connected via ata or usb.
2609 link_cmd = 'readlink /sys/block/%s' % rootdev_base
Puthikorn Voravootivat03c51682014-04-24 13:52:12 -07002610 link = self.run(command=link_cmd, ignore_status=True)
2611 if link.exit_status:
2612 logging.info("Fail to run %s", link_cmd)
2613 return None
Puthikorn Voravootivatfa011242014-03-14 18:45:11 -07002614 link_str = link.stdout.strip()
2615 if 'usb' in link_str:
2616 return None
2617
2618 # Read rotation to determine if the internal device is ssd or hdd.
2619 rotate_cmd = str('cat /sys/block/%s/queue/rotational'
2620 % rootdev_base)
Puthikorn Voravootivat03c51682014-04-24 13:52:12 -07002621 rotate = self.run(command=rotate_cmd, ignore_status=True)
2622 if rotate.exit_status:
2623 logging.info("Fail to run %s", rotate_cmd)
2624 return None
Puthikorn Voravootivatfa011242014-03-14 18:45:11 -07002625 rotate_str = rotate.stdout.strip()
2626
2627 rotate_dict = {'0':'storage:ssd', '1':'storage:hdd'}
2628 return rotate_dict.get(rotate_str)
2629
2630 # All other internal device / error case will always fall here
2631 return None
2632
2633
Dan Shi4e9a2aa2014-03-24 14:28:42 -07002634 @label_decorator('servo')
2635 def get_servo(self):
2636 """Determine if the host has a servo attached.
2637
2638 If the host has a working servo attached, it should have a servo label.
2639
2640 @return: string 'servo' if the host has servo attached. Otherwise,
2641 returns None.
2642 """
2643 return 'servo' if self._servo_host else None
2644
2645
Dan Shi5beba472014-05-28 22:46:07 -07002646 @label_decorator('video_labels')
2647 def get_video_labels(self):
2648 """Run /usr/local/bin/avtest_label_detect to get a list of video labels.
2649
2650 Sample output of avtest_label_detect:
2651 Detected label: hw_video_acc_vp8
2652 Detected label: webcam
2653
2654 @return: A list of labels detected by tool avtest_label_detect.
2655 """
2656 try:
2657 result = self.run('/usr/local/bin/avtest_label_detect').stdout
2658 return re.findall('^Detected label: (\w+)$', result, re.M)
2659 except error.AutoservRunError:
2660 # The tool is not installed.
2661 return []
2662
2663
mussa584b4462014-06-20 15:13:28 -07002664 @label_decorator('video_glitch_detection')
2665 def is_video_glitch_detection_supported(self):
2666 """ Determine if a board under test is supported for video glitch
2667 detection tests.
2668
2669 @return: 'video_glitch_detection' if board is supported, None otherwise.
2670 """
Mussa5b589052015-10-26 17:55:26 -07002671 board = self.get_board().replace(ds_constants.BOARD_PREFIX, '')
mussa584b4462014-06-20 15:13:28 -07002672
Mussa5b589052015-10-26 17:55:26 -07002673 if board in video_test_constants.SUPPORTED_BOARDS:
2674 return 'video_glitch_detection'
mussa584b4462014-06-20 15:13:28 -07002675
Mussa5b589052015-10-26 17:55:26 -07002676 return None
mussa584b4462014-06-20 15:13:28 -07002677
mussa584b4462014-06-20 15:13:28 -07002678
Katherine Threlkeld7b97a9f2014-06-24 13:47:14 -07002679 @label_decorator('touch_labels')
2680 def get_touch(self):
2681 """
2682 Determine whether board under test has a touchpad or touchscreen.
2683
2684 @return: A list of some combination of 'touchscreen' and 'touchpad',
2685 depending on what is present on the device.
Katherine Threlkeldab83d392015-06-18 16:45:57 -07002686
Katherine Threlkeld7b97a9f2014-06-24 13:47:14 -07002687 """
2688 labels = []
Katherine Threlkeldab83d392015-06-18 16:45:57 -07002689 looking_for = ['touchpad', 'touchscreen']
2690 player = input_playback.InputPlayback()
2691 input_events = self.run('ls /dev/input/event*').stdout.strip().split()
2692 filename = '/tmp/touch_labels'
2693 for event in input_events:
2694 self.run('evtest %s > %s' % (event, filename), timeout=1,
2695 ignore_timeout=True)
2696 properties = self.run('cat %s' % filename).stdout
2697 input_type = player._determine_input_type(properties)
2698 if input_type in looking_for:
2699 labels.append(input_type)
2700 looking_for.remove(input_type)
2701 if len(looking_for) == 0:
2702 break
2703 self.run('rm %s' % filename)
2704
Katherine Threlkeld7b97a9f2014-06-24 13:47:14 -07002705 return labels
2706
Hung-ying Tyana39b0542015-06-30 10:36:42 +08002707
2708 @label_decorator('internal_display')
2709 def has_internal_display(self):
2710 """Determine if the device under test is equipped with an internal
2711 display.
2712
2713 @return: 'internal_display' if one is present; None otherwise.
2714 """
2715 from autotest_lib.client.cros.graphics import graphics_utils
2716 from autotest_lib.client.common_lib import utils as common_utils
2717
2718 def __system_output(cmd):
2719 return self.run(cmd).stdout
2720
2721 def __read_file(remote_path):
2722 return self.run('cat %s' % remote_path).stdout
2723
2724 # Hijack the necessary client functions so that we can take advantage
2725 # of the client lib here.
2726 # FIXME: find a less hacky way than this
2727 original_system_output = utils.system_output
2728 original_read_file = common_utils.read_file
2729 utils.system_output = __system_output
2730 common_utils.read_file = __read_file
2731 try:
2732 return ('internal_display' if graphics_utils.has_internal_display()
2733 else None)
2734 finally:
2735 utils.system_output = original_system_output
2736 common_utils.read_file = original_read_file
2737
2738
Eric Carusoee673ac2015-08-05 17:03:04 -07002739 @label_decorator('lucidsleep')
2740 def has_lucid_sleep_support(self):
2741 """Determine if the device under test has support for lucid sleep.
2742
2743 @return 'lucidsleep' if this board supports lucid sleep; None otherwise
2744 """
2745 board = self.get_board().replace(ds_constants.BOARD_PREFIX, '')
2746 return 'lucidsleep' if board in LUCID_SLEEP_BOARDS else None
2747
2748
Dan Shi85276d42014-04-08 22:11:45 -07002749 def is_boot_from_usb(self):
2750 """Check if DUT is boot from USB.
2751
2752 @return: True if DUT is boot from usb.
2753 """
2754 device = self.run('rootdev -s -d').stdout.strip()
2755 removable = int(self.run('cat /sys/block/%s/removable' %
2756 os.path.basename(device)).stdout.strip())
2757 return removable == 1
Helen Zhang17dae2b2014-11-11 09:25:52 -08002758
2759
2760 def read_from_meminfo(self, key):
Dan Shi49ca0932014-11-14 11:22:27 -08002761 """Return the memory info from /proc/meminfo
Helen Zhang17dae2b2014-11-11 09:25:52 -08002762
2763 @param key: meminfo requested
2764
2765 @return the memory value as a string
2766
2767 """
Helen Zhang17dae2b2014-11-11 09:25:52 -08002768 meminfo = self.run('grep %s /proc/meminfo' % key).stdout.strip()
2769 logging.debug('%s', meminfo)
2770 return int(re.search(r'\d+', meminfo).group(0))
Rohit Makasana8a4923c2015-08-13 17:04:26 -07002771
2772
2773 def get_board_type(self):
2774 """
2775 Get the DUT's device type from /etc/lsb-release.
Danny Chan471a8d12015-08-18 14:57:41 -07002776 DEVICETYPE can be one of CHROMEBOX, CHROMEBASE, CHROMEBOOK or more.
2777
2778 @return value of DEVICETYPE param from lsb-release.
Rohit Makasana8a4923c2015-08-13 17:04:26 -07002779 """
Danny Chan471a8d12015-08-18 14:57:41 -07002780 device_type = self.run('grep DEVICETYPE /etc/lsb-release',
2781 ignore_status=True).stdout
2782 if device_type:
Kalin Stoyanov524310b2015-08-21 16:24:04 -07002783 return device_type.split('=')[-1].strip()
Danny Chan471a8d12015-08-18 14:57:41 -07002784 return ''
Gilad Arnolda76bef02015-09-29 13:55:15 -07002785
2786
2787 def get_os_type(self):
2788 return 'cros'
Simran Basia5522a32015-10-06 11:01:24 -07002789
2790
2791 def enable_adb_testing(self):
2792 """Mark this host as an adb tester."""
Dan Shia2872172015-10-31 01:16:51 -07002793 self.run('touch %s' % constants.ANDROID_TESTER_FILEFLAG)