blob: 1bb9d24465dc06723b4f7ddac5d0c993eeaab51c [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
J. Richard Barnette1d78b012012-05-15 13:56:30 -07005import logging
Dan Shi0f466e82013-02-22 15:44:58 -08006import os
Simran Basid5e5e272012-09-24 15:23:59 -07007import re
Vincent Palatindf2372c2016-10-07 17:03:00 +02008import sys
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07009import time
10
mussa584b4462014-06-20 15:13:28 -070011import common
J. Richard Barnette45e93de2012-04-11 17:24:15 -070012from autotest_lib.client.bin import utils
Dan Shi9cb0eec2014-06-03 09:04:50 -070013from autotest_lib.client.common_lib import autotemp
Richard Barnette0c73ffc2012-11-19 15:21:18 -080014from autotest_lib.client.common_lib import error
15from autotest_lib.client.common_lib import global_config
J. Richard Barnette91137f02016-03-10 16:52:26 -080016from autotest_lib.client.common_lib import hosts
Dan Shi549fb822015-03-24 18:01:11 -070017from autotest_lib.client.common_lib import lsbrelease_utils
Richard Barnette03a0c132012-11-05 12:40:35 -080018from autotest_lib.client.common_lib.cros import dev_server
Justin TerAvest3b0c5ba2017-11-07 09:59:11 -070019from autotest_lib.client.common_lib.cros import retry
Hsinyu Chaoe0b08e62015-08-11 10:50:37 +000020from autotest_lib.client.cros import constants as client_constants
J. Richard Barnette84890bd2014-02-21 11:05:47 -080021from autotest_lib.client.cros import cros_ui
Simran Basi5ace6f22016-01-06 17:30:44 -080022from autotest_lib.server import afe_utils
Dan Shia1ecd5c2013-06-06 11:21:31 -070023from autotest_lib.server import utils as server_utils
Dan Shi9cb0eec2014-06-03 09:04:50 -070024from autotest_lib.server.cros import provision
Scott Zawalski89c44dd2013-02-26 09:28:02 -050025from autotest_lib.server.cros.dynamic_suite import constants as ds_constants
Simran Basi5e6339a2013-03-21 11:34:32 -070026from autotest_lib.server.cros.dynamic_suite import tools, frontend_wrappers
Wai-Hong Tam0ed9fe12019-05-23 11:00:58 -070027from autotest_lib.server.cros.servo import pdtester
Fang Deng96667ca2013-08-01 17:46:18 -070028from autotest_lib.server.hosts import abstract_ssh
Kevin Chenga2619dc2016-03-28 11:42:08 -070029from autotest_lib.server.hosts import base_label
Tom Wai-Hong Tamefe1c7f2014-01-02 14:00:11 +080030from autotest_lib.server.hosts import chameleon_host
Richard Barnetted31580e2018-05-14 19:58:00 +000031from autotest_lib.server.hosts import cros_label
J. Richard Barnettea7e7fdc2016-02-12 12:35:36 -080032from autotest_lib.server.hosts import cros_repair
Wai-Hong Tam0ed9fe12019-05-23 11:00:58 -070033from autotest_lib.server.hosts import pdtester_host
Fang Deng5d518f42013-08-02 14:04:32 -070034from autotest_lib.server.hosts import servo_host
Simran Basidcff4252012-11-20 16:13:20 -080035from autotest_lib.site_utils.rpm_control_system import rpm_client
Simran Basid5e5e272012-09-24 15:23:59 -070036
Simran Basi382506b2016-09-13 14:58:15 -070037# In case cros_host is being ran via SSP on an older Moblab version with an
38# older chromite version.
39try:
40 from chromite.lib import metrics
Dan Shi5e2efb72017-02-07 11:40:23 -080041except ImportError:
Congbin Guo42427612019-02-12 10:22:06 -080042 metrics = utils.metrics_mock
Dan Shi5e2efb72017-02-07 11:40:23 -080043
Simran Basid5e5e272012-09-24 15:23:59 -070044
Dan Shib8540a52015-07-16 14:18:23 -070045CONFIG = global_config.global_config
46
Dan Shid07ee2e2015-09-24 14:49:25 -070047
beepsc87ff602013-07-31 21:53:00 -070048class FactoryImageCheckerException(error.AutoservError):
49 """Exception raised when an image is a factory image."""
50 pass
51
52
Fang Deng0ca40e22013-08-27 17:47:44 -070053class CrosHost(abstract_ssh.AbstractSSHHost):
J. Richard Barnette45e93de2012-04-11 17:24:15 -070054 """Chromium OS specific subclass of Host."""
55
Simran Basi5ace6f22016-01-06 17:30:44 -080056 VERSION_PREFIX = provision.CROS_VERSION_PREFIX
57
Scott Zawalski62bacae2013-03-05 10:40:32 -050058 _AFE = frontend_wrappers.RetryingAFE(timeout_min=5, delay_sec=10)
J. Richard Barnette45e93de2012-04-11 17:24:15 -070059
Richard Barnette03a0c132012-11-05 12:40:35 -080060 # Timeout values (in seconds) associated with various Chrome OS
61 # state changes.
J. Richard Barnette134ec2c2012-04-25 12:59:37 -070062 #
Richard Barnette0c73ffc2012-11-19 15:21:18 -080063 # In general, a good rule of thumb is that the timeout can be up
64 # to twice the typical measured value on the slowest platform.
65 # The times here have not necessarily been empirically tested to
66 # meet this criterion.
J. Richard Barnetteeb69d722012-06-18 17:29:44 -070067 #
68 # SLEEP_TIMEOUT: Time to allow for suspend to memory.
Richard Barnette0c73ffc2012-11-19 15:21:18 -080069 # RESUME_TIMEOUT: Time to allow for resume after suspend, plus
70 # time to restart the netwowrk.
J. Richard Barnette84890bd2014-02-21 11:05:47 -080071 # SHUTDOWN_TIMEOUT: Time to allow for shut down.
J. Richard Barnetteeb69d722012-06-18 17:29:44 -070072 # BOOT_TIMEOUT: Time to allow for boot from power off. Among
Richard Barnette0c73ffc2012-11-19 15:21:18 -080073 # other things, this must account for the 30 second dev-mode
J. Richard Barnette417cc792015-10-01 09:56:36 -070074 # screen delay, time to start the network on the DUT, and the
75 # ssh timeout of 120 seconds.
J. Richard Barnetteeb69d722012-06-18 17:29:44 -070076 # USB_BOOT_TIMEOUT: Time to allow for boot from a USB device,
Richard Barnette0c73ffc2012-11-19 15:21:18 -080077 # including the 30 second dev-mode delay and time to start the
J. Richard Barnetted4649c62013-03-06 17:42:27 -080078 # network.
beepsf079cfb2013-09-18 17:49:51 -070079 # INSTALL_TIMEOUT: Time to allow for chromeos-install.
J. Richard Barnette84890bd2014-02-21 11:05:47 -080080 # POWERWASH_BOOT_TIMEOUT: Time to allow for a reboot that
81 # includes powerwash.
J. Richard Barnetteeb69d722012-06-18 17:29:44 -070082
83 SLEEP_TIMEOUT = 2
J. Richard Barnetted4649c62013-03-06 17:42:27 -080084 RESUME_TIMEOUT = 10
Tom Wai-Hong Tamfe005c22014-12-03 09:25:44 +080085 SHUTDOWN_TIMEOUT = 10
J. Richard Barnette417cc792015-10-01 09:56:36 -070086 BOOT_TIMEOUT = 150
J. Richard Barnette5bab5f52015-08-03 13:14:38 -070087 USB_BOOT_TIMEOUT = 300
J. Richard Barnette7817b052014-08-28 09:47:29 -070088 INSTALL_TIMEOUT = 480
Dan Shi2c88eed2013-11-12 10:18:38 -080089 POWERWASH_BOOT_TIMEOUT = 60
Chris Sosab76e0ee2013-05-22 16:55:41 -070090
Dan Shica503482015-03-30 17:23:25 -070091 # Minimum OS version that supports server side packaging. Older builds may
92 # not have server side package built or with Autotest code change to support
93 # server-side packaging.
Dan Shib8540a52015-07-16 14:18:23 -070094 MIN_VERSION_SUPPORT_SSP = CONFIG.get_config_value(
Dan Shiced09e42015-04-17 16:09:34 -070095 'AUTOSERV', 'min_version_support_ssp', type=int)
Dan Shica503482015-03-30 17:23:25 -070096
J. Richard Barnette84890bd2014-02-21 11:05:47 -080097 # REBOOT_TIMEOUT: How long to wait for a reboot.
98 #
Chris Sosab76e0ee2013-05-22 16:55:41 -070099 # We have a long timeout to ensure we don't flakily fail due to other
100 # issues. Shorter timeouts are vetted in platform_RebootAfterUpdate.
Simran Basi1160e2c2013-10-04 16:00:24 -0700101 # TODO(sbasi - crbug.com/276094) Restore to 5 mins once the 'host did not
102 # return from reboot' bug is solved.
103 REBOOT_TIMEOUT = 480
Chris Sosab76e0ee2013-05-22 16:55:41 -0700104
Ismail Noorbasha07fdb612013-02-14 14:13:31 -0800105 # _USB_POWER_TIMEOUT: Time to allow for USB to power toggle ON and OFF.
106 # _POWER_CYCLE_TIMEOUT: Time to allow for manual power cycle.
Garry Wang5e5538a2019-04-08 15:36:18 -0700107 # _CHANGE_SERVO_ROLE_TIMEOUT: Time to allow DUT regain network connection
108 # since changing servo role will reset USB state
109 # and causes temporary ethernet drop.
Ismail Noorbasha07fdb612013-02-14 14:13:31 -0800110 _USB_POWER_TIMEOUT = 5
111 _POWER_CYCLE_TIMEOUT = 10
Garry Wang5e5538a2019-04-08 15:36:18 -0700112 _CHANGE_SERVO_ROLE_TIMEOUT = 180
Ismail Noorbasha07fdb612013-02-14 14:13:31 -0800113
Fang Dengdeba14f2014-11-14 11:54:09 -0800114 _RPM_HOSTNAME_REGEX = ('chromeos(\d+)(-row(\d+))?-rack(\d+[a-z]*)'
115 '-host(\d+)')
J. Richard Barnette134ec2c2012-04-25 12:59:37 -0700116
J. Richard Barnetteb6de7e32013-02-14 13:28:04 -0800117 # Constants used in ping_wait_up() and ping_wait_down().
118 #
119 # _PING_WAIT_COUNT is the approximate number of polling
120 # cycles to use when waiting for a host state change.
121 #
122 # _PING_STATUS_DOWN and _PING_STATUS_UP are names used
123 # for arguments to the internal _ping_wait_for_status()
124 # method.
125 _PING_WAIT_COUNT = 40
126 _PING_STATUS_DOWN = False
127 _PING_STATUS_UP = True
128
Ismail Noorbasha07fdb612013-02-14 14:13:31 -0800129 # Allowed values for the power_method argument.
130
Garry Wang5e5538a2019-04-08 15:36:18 -0700131 # POWER_CONTROL_RPM: Used in power_off/on/cycle() methods, default for all
132 # DUTs except those with servo_v4 CCD.
133 # POWER_CONTROL_CCD: Used in power_off/on/cycle() methods, default for all
134 # DUTs with servo_v4 CCD.
Ismail Noorbasha07fdb612013-02-14 14:13:31 -0800135 # POWER_CONTROL_SERVO: Used in set_power() and power_cycle() methods.
136 # POWER_CONTROL_MANUAL: Used in set_power() and power_cycle() methods.
137 POWER_CONTROL_RPM = 'RPM'
Garry Wang5e5538a2019-04-08 15:36:18 -0700138 POWER_CONTROL_CCD = 'CCD'
Ismail Noorbasha07fdb612013-02-14 14:13:31 -0800139 POWER_CONTROL_SERVO = 'servoj10'
140 POWER_CONTROL_MANUAL = 'manual'
141
142 POWER_CONTROL_VALID_ARGS = (POWER_CONTROL_RPM,
Garry Wang5e5538a2019-04-08 15:36:18 -0700143 POWER_CONTROL_CCD,
Ismail Noorbasha07fdb612013-02-14 14:13:31 -0800144 POWER_CONTROL_SERVO,
145 POWER_CONTROL_MANUAL)
Richard Barnette0c73ffc2012-11-19 15:21:18 -0800146
Simran Basi5e6339a2013-03-21 11:34:32 -0700147 _RPM_OUTLET_CHANGED = 'outlet_changed'
148
Dan Shi9cb0eec2014-06-03 09:04:50 -0700149 # URL pattern to download firmware image.
Dan Shib8540a52015-07-16 14:18:23 -0700150 _FW_IMAGE_URL_PATTERN = CONFIG.get_config_value(
Dan Shi9cb0eec2014-06-03 09:04:50 -0700151 'CROS', 'firmware_url_pattern', type=str)
beeps687243d2013-07-18 15:29:27 -0700152
Brent Peterson1cb623a2020-01-09 13:14:28 -0800153 # Regular expression for extracting EC version string
154 _EC_REGEX = '(%s_\w*[-\.]\w*[-\.]\w*[-\.]\w*)'
155
156 # Regular expression for extracting BIOS version string
157 _BIOS_REGEX = '(%s\.\w*\.\w*\.\w*)'
158
Brent Petersonc70a1832020-01-24 15:54:35 -0800159 # Command to update firmware located on DUT
Brent Peterson669edf42020-02-07 15:07:54 -0800160 _FW_UPDATE_CMD = 'chromeos-firmwareupdate --mode=recovery -i %s %s'
Brent Petersonc70a1832020-01-24 15:54:35 -0800161
J. Richard Barnette964fba02012-10-24 17:34:29 -0700162 @staticmethod
beeps46dadc92013-11-07 14:07:10 -0800163 def check_host(host, timeout=10):
164 """
165 Check if the given host is a chrome-os host.
166
167 @param host: An ssh host representing a device.
168 @param timeout: The timeout for the run command.
169
170 @return: True if the host device is chromeos.
171
beeps46dadc92013-11-07 14:07:10 -0800172 """
173 try:
Allen Liad719c12017-06-27 23:48:04 +0000174 result = host.run(
Simran Basi933c8af2015-04-29 14:05:07 -0700175 'grep -q CHROMEOS /etc/lsb-release && '
Garry Wange4b6d6e2019-06-17 17:08:46 -0700176 '! grep -q moblab /etc/lsb-release && '
177 '! grep -q labstation /etc/lsb-release',
Simran Basi933c8af2015-04-29 14:05:07 -0700178 ignore_status=True, timeout=timeout)
Laurence Goodby468de252017-06-08 17:22:53 -0700179 if result.exit_status == 0:
Allen Liad719c12017-06-27 23:48:04 +0000180 lsb_release_content = host.run(
Laurence Goodby468de252017-06-08 17:22:53 -0700181 'grep CHROMEOS_RELEASE_BOARD /etc/lsb-release',
182 timeout=timeout).stdout
Pradeep Sawlaniaa013fa2017-11-09 06:34:18 -0800183 return not (
184 lsbrelease_utils.is_jetstream(
185 lsb_release_content=lsb_release_content) or
186 lsbrelease_utils.is_gce_board(
187 lsb_release_content=lsb_release_content))
188
beeps46dadc92013-11-07 14:07:10 -0800189 except (error.AutoservRunError, error.AutoservSSHTimeout):
190 return False
Laurence Goodby468de252017-06-08 17:22:53 -0700191
192 return False
beeps46dadc92013-11-07 14:07:10 -0800193
194
195 @staticmethod
Tom Wai-Hong Tamefe1c7f2014-01-02 14:00:11 +0800196 def get_chameleon_arguments(args_dict):
197 """Extract chameleon options from `args_dict` and return the result.
198
199 Recommended usage:
200 ~~~~~~~~
201 args_dict = utils.args_to_dict(args)
202 chameleon_args = hosts.CrosHost.get_chameleon_arguments(args_dict)
203 host = hosts.create_host(machine, chameleon_args=chameleon_args)
204 ~~~~~~~~
205
206 @param args_dict Dictionary from which to extract the chameleon
207 arguments.
208 """
Shijin Abraham783a7dd2020-02-14 15:36:11 -0800209 return {key: args_dict[key]
Allen Li083866b2016-08-18 10:07:10 -0700210 for key in ('chameleon_host', 'chameleon_port')
211 if key in args_dict}
Tom Wai-Hong Tamefe1c7f2014-01-02 14:00:11 +0800212
Shijin Abrahamc09587d2020-02-14 20:46:55 -0800213 @staticmethod
214 def get_btpeer_arguments(args_dict):
215 """Extract btpeer options from `args_dict` and return the result.
216
217 This is used to parse details of Bluetooth peer.
218 Recommended usage:
219 ~~~~~~~~
220 args_dict = utils.args_to_dict(args)
221 btpeer_args = hosts.CrosHost.get_btpeer_arguments(args_dict)
222 host = hosts.create_host(machine)
223 host.initialize_btpeer(btpeer_args)
224 ~~~~~~~~
225
226 @param args_dict: Dictionary from which to extract the btpeer
227 arguments.
228 """
229 if 'btpeer_host_list' in args_dict:
230 result = []
231 for btpeer in args_dict['btpeer_host_list'].split(','):
232 result.append({key: value for key,value in
233 zip(('btpeer_host','btpeer_port'),
234 btpeer.split(':'))})
235 return result
236 else:
237 return {key: args_dict[key]
238 for key in ('btpeer_host', 'btpeer_port')
239 if key in args_dict}
240
Tom Wai-Hong Tamefe1c7f2014-01-02 14:00:11 +0800241
242 @staticmethod
Wai-Hong Tam0ed9fe12019-05-23 11:00:58 -0700243 def get_pdtester_arguments(args_dict):
Scottfe06ed82015-11-05 17:15:01 -0800244 """Extract chameleon options from `args_dict` and return the result.
245
246 Recommended usage:
247 ~~~~~~~~
248 args_dict = utils.args_to_dict(args)
Wai-Hong Tam0ed9fe12019-05-23 11:00:58 -0700249 pdtester_args = hosts.CrosHost.get_pdtester_arguments(args_dict)
250 host = hosts.create_host(machine, pdtester_args=pdtester_args)
Scottfe06ed82015-11-05 17:15:01 -0800251 ~~~~~~~~
252
Wai-Hong Tam0ed9fe12019-05-23 11:00:58 -0700253 @param args_dict Dictionary from which to extract the pdtester
Scottfe06ed82015-11-05 17:15:01 -0800254 arguments.
255 """
Allen Li083866b2016-08-18 10:07:10 -0700256 return {key: args_dict[key]
Wai-Hong Tam0ed9fe12019-05-23 11:00:58 -0700257 for key in ('pdtester_host', 'pdtester_port')
Allen Li083866b2016-08-18 10:07:10 -0700258 if key in args_dict}
Scottfe06ed82015-11-05 17:15:01 -0800259
260
261 @staticmethod
Tom Wai-Hong Tamefe1c7f2014-01-02 14:00:11 +0800262 def get_servo_arguments(args_dict):
263 """Extract servo options from `args_dict` and return the result.
J. Richard Barnette7214e0b2013-02-06 15:20:49 -0800264
265 Recommended usage:
266 ~~~~~~~~
267 args_dict = utils.args_to_dict(args)
Fang Deng0ca40e22013-08-27 17:47:44 -0700268 servo_args = hosts.CrosHost.get_servo_arguments(args_dict)
J. Richard Barnette7214e0b2013-02-06 15:20:49 -0800269 host = hosts.create_host(machine, servo_args=servo_args)
270 ~~~~~~~~
271
272 @param args_dict Dictionary from which to extract the servo
273 arguments.
274 """
Richard Barnettee519dcd2016-08-15 17:37:17 -0700275 servo_attrs = (servo_host.SERVO_HOST_ATTR,
276 servo_host.SERVO_PORT_ATTR,
Nick Sanders2f3c9852018-10-24 12:10:24 -0700277 servo_host.SERVO_BOARD_ATTR,
278 servo_host.SERVO_MODEL_ATTR)
Armando Miraglia2ac802e2017-08-15 14:54:47 +0200279 servo_args = {key: args_dict[key]
280 for key in servo_attrs
281 if key in args_dict}
282 return (
283 None
284 if servo_host.SERVO_HOST_ATTR in servo_args
285 and not servo_args[servo_host.SERVO_HOST_ATTR]
286 else servo_args)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -0700287
J. Richard Barnette964fba02012-10-24 17:34:29 -0700288
J. Richard Barnette91137f02016-03-10 16:52:26 -0800289 def _initialize(self, hostname, chameleon_args=None, servo_args=None,
Wai-Hong Tam0ed9fe12019-05-23 11:00:58 -0700290 pdtester_args=None, try_lab_servo=False,
Richard Barnette9a26ad62016-06-10 12:03:08 -0700291 try_servo_repair=False,
J. Richard Barnette91137f02016-03-10 16:52:26 -0800292 ssh_verbosity_flag='', ssh_options='',
Fang Dengd1c2b732013-08-20 12:59:46 -0700293 *args, **dargs):
Tom Wai-Hong Tamefe1c7f2014-01-02 14:00:11 +0800294 """Initialize superclasses, |self.chameleon|, and |self.servo|.
J. Richard Barnette67ccb872012-04-19 16:34:56 -0700295
Fang Denge545abb2014-12-30 18:43:47 -0800296 This method will attempt to create the test-assistant object
297 (chameleon/servo) when it is needed by the test. Check
298 the docstring of chameleon_host.create_chameleon_host and
299 servo_host.create_servo_host for how this is determined.
Fang Deng5d518f42013-08-02 14:04:32 -0700300
Fang Denge545abb2014-12-30 18:43:47 -0800301 @param hostname: Hostname of the dut.
302 @param chameleon_args: A dictionary that contains args for creating
303 a ChameleonHost. See chameleon_host for details.
304 @param servo_args: A dictionary that contains args for creating
305 a ServoHost object. See servo_host for details.
Richard Barnette9a26ad62016-06-10 12:03:08 -0700306 @param try_lab_servo: When true, indicates that an attempt should
307 be made to create a ServoHost for a DUT in
308 the test lab, even if not required by
309 `servo_args`. See servo_host for details.
310 @param try_servo_repair: If a servo host is created, check it
311 with `repair()` rather than `verify()`.
Fang Denge545abb2014-12-30 18:43:47 -0800312 See servo_host for details.
313 @param ssh_verbosity_flag: String, to pass to the ssh command to control
314 verbosity.
315 @param ssh_options: String, other ssh options to pass to the ssh
316 command.
J. Richard Barnette67ccb872012-04-19 16:34:56 -0700317 """
Fang Deng0ca40e22013-08-27 17:47:44 -0700318 super(CrosHost, self)._initialize(hostname=hostname,
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700319 *args, **dargs)
J. Richard Barnette91137f02016-03-10 16:52:26 -0800320 self._repair_strategy = cros_repair.create_cros_repair_strategy()
Kevin Chenga2619dc2016-03-28 11:42:08 -0700321 self.labels = base_label.LabelRetriever(cros_label.CROS_LABELS)
J. Richard Barnettef0859852012-08-20 14:55:50 -0700322 # self.env is a dictionary of environment variable settings
323 # to be exported for commands run on the host.
324 # LIBC_FATAL_STDERR_ can be useful for diagnosing certain
325 # errors that might happen.
326 self.env['LIBC_FATAL_STDERR_'] = '1'
Fang Dengd1c2b732013-08-20 12:59:46 -0700327 self._ssh_verbosity_flag = ssh_verbosity_flag
Aviv Keshetc5947fa2013-09-04 14:06:29 -0700328 self._ssh_options = ssh_options
Shelley Chen905f1272020-03-06 20:52:07 +0000329 self.set_servo_host(
330 servo_host.create_servo_host(
331 dut=self, servo_args=servo_args,
332 try_lab_servo=try_lab_servo,
333 try_servo_repair=try_servo_repair,
334 dut_host_info=self.host_info_store.get()))
Garry Wang5e5538a2019-04-08 15:36:18 -0700335 self._default_power_method = None
Richard Barnettee519dcd2016-08-15 17:37:17 -0700336
Tom Wai-Hong Tamefe1c7f2014-01-02 14:00:11 +0800337 # TODO(waihong): Do the simplication on Chameleon too.
Shijin Abraham783a7dd2020-02-14 15:36:11 -0800338 self._chameleon_host = chameleon_host.create_chameleon_host(
Shelley Chen905f1272020-03-06 20:52:07 +0000339 dut=self.hostname, chameleon_args=chameleon_args)
Shijin Abraham783a7dd2020-02-14 15:36:11 -0800340 if self._chameleon_host:
341 self.chameleon = self._chameleon_host.create_chameleon_board()
Tom Wai-Hong Tamefe1c7f2014-01-02 14:00:11 +0800342 else:
Tom Wai-Hong Tam3d6790d2014-04-14 16:15:47 +0800343 self.chameleon = None
Fang Deng5d518f42013-08-02 14:04:32 -0700344
Shijin Abrahamc09587d2020-02-14 20:46:55 -0800345 # Bluetooth peers. These will be initialized by test if required.
346 self._btpeer_host_list = []
347 self.btpeer_list = []
348 self.btpeer = None
349
howardchung83e55272019-08-08 14:08:05 +0800350 # Add pdtester host if pdtester args were added on command line
Wai-Hong Tam16e5edb2019-09-17 16:10:07 -0700351 self._pdtester_host = pdtester_host.create_pdtester_host(
Wai-Hong Tam90b164d2019-10-25 13:15:39 -0700352 pdtester_args, self._servo_host)
howardchung83e55272019-08-08 14:08:05 +0800353
Wai-Hong Tam0ed9fe12019-05-23 11:00:58 -0700354 if self._pdtester_host:
355 self.pdtester_servo = self._pdtester_host.get_servo()
356 logging.info('pdtester_servo: %r', self.pdtester_servo)
357 # Create the pdtester object used to access the ec uart
358 self.pdtester = pdtester.PDTester(self.pdtester_servo,
359 self._pdtester_host.get_servod_server_proxy())
Scottfe06ed82015-11-05 17:15:01 -0800360 else:
Wai-Hong Tam0ed9fe12019-05-23 11:00:58 -0700361 self.pdtester = None
Scottfe06ed82015-11-05 17:15:01 -0800362
Fang Deng5d518f42013-08-02 14:04:32 -0700363
Shijin Abrahamc09587d2020-02-14 20:46:55 -0800364 def initialize_btpeer(self, btpeer_args):
365 """ Initialize the Bluetooth peers
366
367 Initialize Bluetooth peer devices given in the arguments. Bluetooth peer
368 is chameleon host on Raspberry Pi.
369 @param btpeer_args: A dictionary that contains args for creating
370 a ChameleonHost. See chameleon_host for details.
371
372 """
373
374 if type(btpeer_args) is list:
375 btpeer_args_list = btpeer_args
376 else:
377 btpeer_args_list = [btpeer_args]
378
379 self._btpeer_host_list = chameleon_host.create_btpeer_host(
380 dut=self.hostname, btpeer_args_list=btpeer_args_list)
381 logging.debug('Bluetooth peer hosts are %s', self._btpeer_host_list)
382 self.btpeer_list = [_host.create_chameleon_board() for _host in
383 self._btpeer_host_list if _host is not None]
384
385 if len(self.btpeer_list) > 0:
386 self.btpeer = self.btpeer_list[0]
387 else:
388 self.btpeer = None
389
390 logging.debug('After initialize_btpeer btpeer_list %s btpeer_host_list'
391 'is %s and btpeer is %s',self.btpeer_list,
392 self._btpeer_host_list, self.btpeer)
393
394
Richard Barnetteb4b4d6f2018-05-05 01:47:41 +0000395 def get_cros_repair_image_name(self):
Ruben Rodriguez Buchilloncee72f72019-05-01 13:20:58 -0700396 """Get latest stable cros image name from AFE.
397
398 Use the board name from the info store. Should that fail, try to
399 retrieve the board name from the host's installed image itself.
400
401 @returns: current stable cros image name for this host.
402 """
403 board = self.host_info_store.get().board
404 if not board:
405 logging.warn('No board label value found. Trying to infer '
406 'from the host itself.')
407 try:
408 board = self.get_board().split(':')[1]
409 except (error.AutoservRunError, error.AutoservSSHTimeout) as e:
410 logging.error('Also failed to get the board name from the DUT '
411 'itself. %s.', str(e))
412 raise error.AutoservError('Cannot obtain repair image name.')
Gregory Nisbet7fe11c22019-11-22 11:06:06 -0800413 return afe_utils.get_stable_cros_image_name_v2(self.host_info_store.get())
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500414
415
Rohit Makasanadf0a3a32017-06-30 13:55:18 -0700416 def host_version_prefix(self, image):
417 """Return version label prefix.
418
419 In case the CrOS provisioning version is something other than the
420 standard CrOS version e.g. CrOS TH version, this function will
421 find the prefix from provision.py.
422
423 @param image: The image name to find its version prefix.
424 @returns: A prefix string for the image type.
425 """
426 return provision.get_version_label_prefix(image)
427
428
beepsdae65fd2013-07-26 16:24:41 -0700429 def verify_job_repo_url(self, tag=''):
beepscb6f1e22013-06-28 19:14:10 -0700430 """
431 Make sure job_repo_url of this host is valid.
432
joychen03eaad92013-06-26 09:55:21 -0700433 Eg: The job_repo_url "http://lmn.cd.ab.xyx:8080/static/\
beepscb6f1e22013-06-28 19:14:10 -0700434 lumpy-release/R29-4279.0.0/autotest/packages" claims to have the
435 autotest package for lumpy-release/R29-4279.0.0. If this isn't the case,
436 download and extract it. If the devserver embedded in the url is
437 unresponsive, update the job_repo_url of the host after staging it on
438 another devserver.
439
440 @param job_repo_url: A url pointing to the devserver where the autotest
441 package for this build should be staged.
beepsdae65fd2013-07-26 16:24:41 -0700442 @param tag: The tag from the server job, in the format
443 <job_id>-<user>/<hostname>, or <hostless> for a server job.
beepscb6f1e22013-06-28 19:14:10 -0700444
445 @raises DevServerException: If we could not resolve a devserver.
446 @raises AutoservError: If we're unable to save the new job_repo_url as
447 a result of choosing a new devserver because the old one failed to
448 respond to a health check.
beeps0c865032013-07-30 11:37:06 -0700449 @raises urllib2.URLError: If the devserver embedded in job_repo_url
450 doesn't respond within the timeout.
beepscb6f1e22013-06-28 19:14:10 -0700451 """
Prathmesh Prabhu368abdf2017-02-14 11:23:47 -0800452 info = self.host_info_store.get()
453 job_repo_url = info.attributes.get(ds_constants.JOB_REPO_URL, '')
beepscb6f1e22013-06-28 19:14:10 -0700454 if not job_repo_url:
455 logging.warning('No job repo url set on host %s', self.hostname)
456 return
457
458 logging.info('Verifying job repo url %s', job_repo_url)
459 devserver_url, image_name = tools.get_devserver_build_from_package_url(
460 job_repo_url)
461
beeps0c865032013-07-30 11:37:06 -0700462 ds = dev_server.ImageServer(devserver_url)
beepscb6f1e22013-06-28 19:14:10 -0700463
464 logging.info('Staging autotest artifacts for %s on devserver %s',
465 image_name, ds.url())
beeps687243d2013-07-18 15:29:27 -0700466
467 start_time = time.time()
Simran Basi25e7a922014-10-31 11:56:10 -0700468 ds.stage_artifacts(image_name, ['autotest_packages'])
beeps687243d2013-07-18 15:29:27 -0700469 stage_time = time.time() - start_time
470
471 # Record how much of the verification time comes from a devserver
472 # restage. If we're doing things right we should not see multiple
473 # devservers for a given board/build/branch path.
474 try:
J. Richard Barnette3cbd76b2013-11-27 12:11:25 -0800475 board, build_type, branch = server_utils.ParseBuildName(
beeps687243d2013-07-18 15:29:27 -0700476 image_name)[:3]
J. Richard Barnette3cbd76b2013-11-27 12:11:25 -0800477 except server_utils.ParseBuildNameException:
beeps687243d2013-07-18 15:29:27 -0700478 pass
479 else:
beeps0c865032013-07-30 11:37:06 -0700480 devserver = devserver_url[
Chris Sosa65425082013-10-16 13:26:22 -0700481 devserver_url.find('/') + 2:devserver_url.rfind(':')]
beeps687243d2013-07-18 15:29:27 -0700482 stats_key = {
483 'board': board,
484 'build_type': build_type,
485 'branch': branch,
beeps0c865032013-07-30 11:37:06 -0700486 'devserver': devserver.replace('.', '_'),
beeps687243d2013-07-18 15:29:27 -0700487 }
Dan Shi5e2efb72017-02-07 11:40:23 -0800488
489 monarch_fields = {
490 'board': board,
491 'build_type': build_type,
Dan Shi5e2efb72017-02-07 11:40:23 -0800492 'branch': branch,
493 'dev_server': devserver,
494 }
495 metrics.Counter(
496 'chromeos/autotest/provision/verify_url'
497 ).increment(fields=monarch_fields)
498 metrics.SecondsDistribution(
499 'chromeos/autotest/provision/verify_url_duration'
500 ).add(stage_time, fields=monarch_fields)
501
502
Dan Shicf4d2032015-03-12 15:04:21 -0700503 def stage_server_side_package(self, image=None):
504 """Stage autotest server-side package on devserver.
505
506 @param image: Full path of an OS image to install or a build name.
507
508 @return: A url to the autotest server-side package.
Dan Shi14de7622016-08-22 11:09:06 -0700509
510 @raise: error.AutoservError if fail to locate the build to test with, or
511 fail to stage server-side package.
Dan Shicf4d2032015-03-12 15:04:21 -0700512 """
Dan Shid37736b2016-07-06 15:10:29 -0700513 # If enable_drone_in_restricted_subnet is False, do not set hostname
514 # in devserver.resolve call, so a devserver in non-restricted subnet
515 # is picked to stage autotest server package for drone to download.
516 hostname = self.hostname
517 if not server_utils.ENABLE_DRONE_IN_RESTRICTED_SUBNET:
518 hostname = None
Dan Shicf4d2032015-03-12 15:04:21 -0700519 if image:
520 image_name = tools.get_build_from_image(image)
521 if not image_name:
522 raise error.AutoservError(
523 'Failed to parse build name from %s' % image)
Dan Shid37736b2016-07-06 15:10:29 -0700524 ds = dev_server.ImageServer.resolve(image_name, hostname)
Dan Shicf4d2032015-03-12 15:04:21 -0700525 else:
Prathmesh Prabhu9235e4c2017-03-28 13:16:06 -0700526 info = self.host_info_store.get()
Prathmesh Prabhu368abdf2017-02-14 11:23:47 -0800527 job_repo_url = info.attributes.get(ds_constants.JOB_REPO_URL, '')
Dan Shicf4d2032015-03-12 15:04:21 -0700528 if job_repo_url:
529 devserver_url, image_name = (
530 tools.get_devserver_build_from_package_url(job_repo_url))
Dan Shid37736b2016-07-06 15:10:29 -0700531 # If enable_drone_in_restricted_subnet is True, use the
532 # existing devserver. Otherwise, resolve a new one in
533 # non-restricted subnet.
534 if server_utils.ENABLE_DRONE_IN_RESTRICTED_SUBNET:
535 ds = dev_server.ImageServer(devserver_url)
536 else:
537 ds = dev_server.ImageServer.resolve(image_name)
Prathmesh Prabhub6cea612017-02-09 15:41:19 -0800538 elif info.build is not None:
539 ds = dev_server.ImageServer.resolve(info.build, hostname)
Prathmesh Prabhu0c1dd4d2017-06-07 13:01:53 -0700540 image_name = info.build
Dan Shicf4d2032015-03-12 15:04:21 -0700541 else:
Prathmesh Prabhub6cea612017-02-09 15:41:19 -0800542 raise error.AutoservError(
543 'Failed to stage server-side package. The host has '
Garry Wang12b9baf2019-06-24 18:58:54 -0700544 'no job_repo_url attribute or cros-version label.')
Dan Shica503482015-03-30 17:23:25 -0700545
546 # Get the OS version of the build, for any build older than
547 # MIN_VERSION_SUPPORT_SSP, server side packaging is not supported.
548 match = re.match('.*/R\d+-(\d+)\.', image_name)
549 if match and int(match.group(1)) < self.MIN_VERSION_SUPPORT_SSP:
Dan Shi14de7622016-08-22 11:09:06 -0700550 raise error.AutoservError(
551 'Build %s is older than %s. Server side packaging is '
552 'disabled.' % (image_name, self.MIN_VERSION_SUPPORT_SSP))
Dan Shica503482015-03-30 17:23:25 -0700553
Dan Shicf4d2032015-03-12 15:04:21 -0700554 ds.stage_artifacts(image_name, ['autotest_server_package'])
555 return '%s/static/%s/%s' % (ds.url(), image_name,
556 'autotest_server_package.tar.bz2')
557
558
Kalin Stoyanovb3c11f32018-05-11 09:02:00 -0700559 def stage_image_for_servo(self, image_name=None, artifact='test_image'):
J. Richard Barnettee4af8b92013-05-01 13:16:12 -0700560 """Stage a build on a devserver and return the update_url.
561
562 @param image_name: a name like lumpy-release/R27-3837.0.0
Kalin Stoyanovb3c11f32018-05-11 09:02:00 -0700563 @param artifact: a string like 'test_image'. Requests
564 appropriate image to be staged.
Xixuan Wufee57542019-10-15 11:50:27 -0700565 @returns a tuple of (image_name, URL) like
566 (lumpy-release/R27-3837.0.0,
567 http://172.22.50.205:8082/update/lumpy-release/R27-3837.0.0)
J. Richard Barnettee4af8b92013-05-01 13:16:12 -0700568 """
569 if not image_name:
Richard Barnetteb4b4d6f2018-05-05 01:47:41 +0000570 image_name = self.get_cros_repair_image_name()
J. Richard Barnettee4af8b92013-05-01 13:16:12 -0700571 logging.info('Staging build for servo install: %s', image_name)
Dan Shi216389c2015-12-22 11:03:06 -0800572 devserver = dev_server.ImageServer.resolve(image_name, self.hostname)
Kalin Stoyanovb3c11f32018-05-11 09:02:00 -0700573 devserver.stage_artifacts(image_name, [artifact])
574 if artifact == 'test_image':
Xixuan Wufee57542019-10-15 11:50:27 -0700575 return image_name, devserver.get_test_image_url(image_name)
Kalin Stoyanovb3c11f32018-05-11 09:02:00 -0700576 elif artifact == 'recovery_image':
Xixuan Wufee57542019-10-15 11:50:27 -0700577 return image_name, devserver.get_recovery_image_url(image_name)
Kalin Stoyanovb3c11f32018-05-11 09:02:00 -0700578 else:
579 raise error.AutoservError("Bad artifact!")
J. Richard Barnettee4af8b92013-05-01 13:16:12 -0700580
581
beepse539be02013-07-31 21:57:39 -0700582 def stage_factory_image_for_servo(self, image_name):
583 """Stage a build on a devserver and return the update_url.
584
585 @param image_name: a name like <baord>/4262.204.0
beeps12c0a3c2013-09-03 11:58:27 -0700586
beepse539be02013-07-31 21:57:39 -0700587 @return: An update URL, eg:
588 http://<devserver>/static/canary-channel/\
589 <board>/4262.204.0/factory_test/chromiumos_factory_image.bin
beeps12c0a3c2013-09-03 11:58:27 -0700590
591 @raises: ValueError if the factory artifact name is missing from
592 the config.
593
beepse539be02013-07-31 21:57:39 -0700594 """
595 if not image_name:
596 logging.error('Need an image_name to stage a factory image.')
597 return
598
Dan Shib8540a52015-07-16 14:18:23 -0700599 factory_artifact = CONFIG.get_config_value(
beeps12c0a3c2013-09-03 11:58:27 -0700600 'CROS', 'factory_artifact', type=str, default='')
601 if not factory_artifact:
602 raise ValueError('Cannot retrieve the factory artifact name from '
603 'autotest config, and hence cannot stage factory '
604 'artifacts.')
605
beepse539be02013-07-31 21:57:39 -0700606 logging.info('Staging build for servo install: %s', image_name)
Dan Shi216389c2015-12-22 11:03:06 -0800607 devserver = dev_server.ImageServer.resolve(image_name, self.hostname)
beepse539be02013-07-31 21:57:39 -0700608 devserver.stage_artifacts(
609 image_name,
beeps12c0a3c2013-09-03 11:58:27 -0700610 [factory_artifact],
611 archive_url=None)
beepse539be02013-07-31 21:57:39 -0700612
613 return tools.factory_image_url_pattern() % (devserver.url(), image_name)
614
615
Laurence Goodby778c9a42017-05-24 19:24:07 -0700616 def prepare_for_update(self):
617 """Prepares the DUT for an update.
618
619 Subclasses may override this to perform any special actions
620 required before updating.
621 """
Laurence Goodby468de252017-06-08 17:22:53 -0700622 pass
Laurence Goodby778c9a42017-05-24 19:24:07 -0700623
624
Tom Wai-Hong Tam2d00cb22016-01-08 06:40:50 +0800625 def _clear_fw_version_labels(self, rw_only):
626 """Clear firmware version labels from the machine.
627
628 @param rw_only: True to only clear fwrw_version; otherewise, clear
629 both fwro_version and fwrw_version.
630 """
Prathmesh Prabhuf8ae9a82019-10-04 15:34:13 -0700631 info = self.host_info_store.get()
632 info.clear_version_labels(provision.FW_RW_VERSION_PREFIX)
Tom Wai-Hong Tam2d00cb22016-01-08 06:40:50 +0800633 if not rw_only:
Prathmesh Prabhuf8ae9a82019-10-04 15:34:13 -0700634 info.clear_version_labels(provision.FW_RO_VERSION_PREFIX)
635 self.host_info_store.commit(info)
Dan Shi9cb0eec2014-06-03 09:04:50 -0700636
637
Tom Wai-Hong Tam2d00cb22016-01-08 06:40:50 +0800638 def _add_fw_version_label(self, build, rw_only):
Dan Shi9cb0eec2014-06-03 09:04:50 -0700639 """Add firmware version label to the machine.
640
641 @param build: Build of firmware.
Tom Wai-Hong Tam2d00cb22016-01-08 06:40:50 +0800642 @param rw_only: True to only add fwrw_version; otherwise, add both
643 fwro_version and fwrw_version.
Dan Shi9cb0eec2014-06-03 09:04:50 -0700644
645 """
Prathmesh Prabhuf8ae9a82019-10-04 15:34:13 -0700646 info = self.host_info_store.get()
647 info.set_version_label(provision.FW_RW_VERSION_PREFIX, build)
Tom Wai-Hong Tam2d00cb22016-01-08 06:40:50 +0800648 if not rw_only:
Prathmesh Prabhuf8ae9a82019-10-04 15:34:13 -0700649 info.set_version_label(provision.FW_RO_VERSION_PREFIX, build)
650 self.host_info_store.commit(info)
Dan Shi9cb0eec2014-06-03 09:04:50 -0700651
652
Namyoon Woo5f894662019-11-15 15:23:23 -0800653 def get_latest_release_version(self, board):
654 """Search for the latest package release version from the image archive,
655 and return it.
656
657 @param board: board name
658
659 @return 'firmware-{board}-{branch}-firmwarebranch/{release-version}'
660 or None if LATEST release file does not exist.
661 """
662
663 # This might be in the format of 'baseboard_model',
664 # e.g. octopus_fleex. In that case, board should be just
665 # 'baseboard' to use in search for image package, e.g. octopus.
666 board = board.split('_')[0]
667
668 # Read 'LATEST-1.0.0' file
669 branch_dir = provision.FW_BRANCH_GLOB % board
670 latest_file = os.path.join(provision.CROS_IMAGE_ARCHIVE, branch_dir,
671 'LATEST-1.0.0')
Namyoon Woo5f894662019-11-15 15:23:23 -0800672
Namyoon Woo406c7d42020-01-24 15:57:11 -0800673 try:
674 # The result could be one or more.
675 result = utils.system_output('gsutil ls -d ' + latest_file)
676
677 candidates = re.findall('gs://.*', result)
Namyoon Woo5f894662019-11-15 15:23:23 -0800678 except error.CmdError:
679 logging.error('No LATEST release info is available.')
680 return None
681
Namyoon Woo406c7d42020-01-24 15:57:11 -0800682 for cand_dir in candidates:
683 result = utils.system_output('gsutil cat ' + cand_dir)
Namyoon Woo5f894662019-11-15 15:23:23 -0800684
Namyoon Woo406c7d42020-01-24 15:57:11 -0800685 release_path = cand_dir.replace('LATEST-1.0.0', result)
686 release_path = os.path.join(release_path, board)
687 try:
688 # Check if release_path does exist.
689 release = utils.system_output('gsutil ls -d ' + release_path)
690 # Now 'release' has a full directory path: e.g.
691 # gs://chromeos-image-archive/firmware-octopus-11297.B-
692 # firmwarebranch/RNone-1.0.0-b4395530/octopus/
693
694 # Remove "gs://chromeos-image-archive".
695 release = release.replace(provision.CROS_IMAGE_ARCHIVE, '')
696
697 # Remove CROS_IMAGE_ARCHIVE and any surrounding '/'s.
698 return release.strip('/')
699 except error.CmdError:
700 # The directory might not exist. Let's try next candidate.
701 pass
702 else:
703 raise error.AutoservError('Cannot find the latest firmware')
Namyoon Woo5f894662019-11-15 15:23:23 -0800704
Brent Peterson1cb623a2020-01-09 13:14:28 -0800705 @staticmethod
706 def get_version_from_image(image, version_regex):
Brent Peterson8039b472020-02-14 10:51:23 -0800707 """Get version string from binary image using regular expression.
708
709 @param image: Binary image to search
710 @param version_regex: Regular expression to search for
711
712 @return Version string
713
714 @raises TestFail if no version string is found in image
715 """
Brent Peterson1cb623a2020-01-09 13:14:28 -0800716 with open(image, 'rb') as f:
717 image_data = f.read()
718 match = re.findall(version_regex, image_data)
719 if match:
720 return match[0]
721 else:
722 raise error.TestFail('Failed to read version from %s.' % image)
723
724
Brent Peterson5b7c5b12020-01-09 13:14:28 -0800725 def firmware_install(self, build=None, rw_only=False, dest=None,
Brent Petersonc70a1832020-01-24 15:54:35 -0800726 local_tarball=None, verify_version=False,
727 try_scp=False):
Dan Shi9cb0eec2014-06-03 09:04:50 -0700728 """Install firmware to the DUT.
729
730 Use stateful update if the DUT is already running the same build.
731 Stateful update does not update kernel and tends to run much faster
732 than a full reimage. If the DUT is running a different build, or it
733 failed to do a stateful update, full update, including kernel update,
734 will be applied to the DUT.
735
Tom Wai-Hong Tam2d00cb22016-01-08 06:40:50 +0800736 Once a host enters firmware_install its fw[ro|rw]_version label will
737 be removed. After the firmware is updated successfully, a new
738 fw[ro|rw]_version label will be added to the host.
Dan Shi9cb0eec2014-06-03 09:04:50 -0700739
740 @param build: The build version to which we want to provision the
741 firmware of the machine,
742 e.g. 'link-firmware/R22-2695.1.144'.
Tom Wai-Hong Tam4ac78982016-01-08 02:34:37 +0800743 @param rw_only: True to only install firmware to its RW portions. Keep
744 the RO portions unchanged.
Mary Ruthven6481a9f2019-08-23 12:46:05 -0700745 @param dest: Directory to store the firmware in.
Brent Peterson5b7c5b12020-01-09 13:14:28 -0800746 @param local_tarball: Path to local firmware image for installing
747 without devserver.
Brent Peterson1cb623a2020-01-09 13:14:28 -0800748 @param verify_version: True to verify EC and BIOS versions after
749 programming firmware, default is False.
Brent Petersonc70a1832020-01-24 15:54:35 -0800750 @param try_scp: False to always program using servo, true to try copying
751 the firmware and programming from the DUT.
Dan Shi9cb0eec2014-06-03 09:04:50 -0700752
753 TODO(dshi): After bug 381718 is fixed, update here with corresponding
754 exceptions that could be raised.
755
756 """
757 if not self.servo:
758 raise error.TestError('Host %s does not have servo.' %
759 self.hostname)
760
Wai-Hong Tam3fa455a2018-07-18 14:40:43 -0700761 # Get the DUT board name from AFE.
762 info = self.host_info_store.get()
763 board = info.board
Shelley Chenac61d5a2019-06-24 15:35:46 -0700764 model = info.model
Namyoon Woo8dbfcf92019-01-15 18:37:12 -0800765
766 if board is None or board == '':
767 board = self.servo.get_board()
Dan Shi9cb0eec2014-06-03 09:04:50 -0700768
Mary Ruthvende14a8b2019-08-23 12:43:52 -0700769 if model is None or model == '':
770 model = self.get_platform_from_fwid()
771
Brent Peterson5b7c5b12020-01-09 13:14:28 -0800772 # If local firmware path not provided fetch it from the dev server
Mary Ruthven6481a9f2019-08-23 12:46:05 -0700773 tmpd = None
Brent Peterson5b7c5b12020-01-09 13:14:28 -0800774 if not local_tarball:
775 # If build is not set, try to install firmware from stable CrOS.
776 if not build:
777 build = afe_utils.get_stable_faft_version_v2(info)
778 if not build:
779 raise error.TestError(
780 'Failed to find stable firmware build for %s.',
781 self.hostname)
782 logging.info('Will install firmware from build %s.', build)
783
784 ds = dev_server.ImageServer.resolve(build, self.hostname)
785 ds.stage_artifacts(build, ['firmware'])
786
787 if not dest:
788 tmpd = autotemp.tempdir(unique_id='fwimage')
789 dest = tmpd.name
790
791 # Download firmware image
Dan Shi9cb0eec2014-06-03 09:04:50 -0700792 fwurl = self._FW_IMAGE_URL_PATTERN % (ds.url(), build)
Mary Ruthven6481a9f2019-08-23 12:46:05 -0700793 local_tarball = os.path.join(dest, os.path.basename(fwurl))
xixuan4e116822016-11-17 15:32:10 -0800794 ds.download_file(fwurl, local_tarball)
Dan Shi9cb0eec2014-06-03 09:04:50 -0700795
Brent Peterson1cb623a2020-01-09 13:14:28 -0800796 # Extract EC image from tarball
797 logging.info('Extracting EC image.')
798 ec_image = self.servo.extract_ec_image(board, model, local_tarball)
799
800 # Extract BIOS image from tarball
801 logging.info('Extracting BIOS image.')
802 bios_image = self.servo.extract_bios_image(board, model, local_tarball)
803
Brent Petersonc70a1832020-01-24 15:54:35 -0800804 # Clear firmware version labels
805 self._clear_fw_version_labels(rw_only)
806
807 # Install firmware from local tarball
Brent Peterson5b7c5b12020-01-09 13:14:28 -0800808 try:
Brent Petersonc70a1832020-01-24 15:54:35 -0800809 # Check if DUT is available and copying to DUT is enabled
810 if self.is_up() and try_scp:
811 # DUT is available, make temp firmware directory to store images
812 logging.info('Making temp folder.')
813 dest_folder = '/tmp/firmware'
814 self.run('mkdir -p ' + dest_folder)
815
Brent Petersonc70a1832020-01-24 15:54:35 -0800816 # Send BIOS firmware image to DUT
817 logging.info('Sending BIOS firmware.')
818 dest_bios_path = os.path.join(dest_folder,
819 os.path.basename(bios_image))
820 self.send_file(bios_image, dest_bios_path)
821
Brent Peterson669edf42020-02-07 15:07:54 -0800822 # Initialize firmware update command for BIOS image
823 fw_cmd = self._FW_UPDATE_CMD % (dest_bios_path,
Brent Petersonc70a1832020-01-24 15:54:35 -0800824 '--wp=1' if rw_only else '')
Brent Peterson669edf42020-02-07 15:07:54 -0800825
826 # Send EC firmware image to DUT when EC image was found
827 if ec_image:
828 logging.info('Sending EC firmware.')
829 dest_ec_path = os.path.join(dest_folder,
830 os.path.basename(ec_image))
831 self.send_file(ec_image, dest_ec_path)
832
833 # Add EC image to firmware update command
834 fw_cmd += ' -e %s' % dest_ec_path
835
836 # Update firmware on DUT
837 logging.info('Updating firmware.')
Brent Petersonc70a1832020-01-24 15:54:35 -0800838 self.run(fw_cmd)
839 else:
840 # Host is not available, program firmware using servo
Brent Peterson669edf42020-02-07 15:07:54 -0800841 if ec_image:
842 self.servo.program_ec(ec_image, rw_only)
Brent Petersonc70a1832020-01-24 15:54:35 -0800843 self.servo.program_bios(bios_image, rw_only)
844 if utils.host_is_in_lab_zone(self.hostname):
845 self._add_fw_version_label(build, rw_only)
Brent Peterson1cb623a2020-01-09 13:14:28 -0800846
847 # Reboot and wait for DUT after installing firmware
848 logging.info('Rebooting DUT.')
849 self.servo.get_power_state_controller().reset()
850 time.sleep(self.servo.BOOT_DELAY)
851 self.test_wait_for_boot()
852
853 # When enabled verify EC and BIOS firmware version after programming
854 if verify_version:
Brent Peterson669edf42020-02-07 15:07:54 -0800855 # Check programmed EC firmware when EC image was found
856 if ec_image:
857 logging.info('Checking EC firmware version.')
858 dest_ec_version = self.get_ec_version()
Brent Peterson8039b472020-02-14 10:51:23 -0800859 ec_version_prefix = dest_ec_version.split('_', 1)[0]
860 ec_regex = self._EC_REGEX % ec_version_prefix
Brent Peterson669edf42020-02-07 15:07:54 -0800861 image_ec_version = self.get_version_from_image(ec_image,
Brent Peterson8039b472020-02-14 10:51:23 -0800862 ec_regex)
Brent Peterson669edf42020-02-07 15:07:54 -0800863 if dest_ec_version != image_ec_version:
864 raise error.TestFail(
865 'Failed to update EC RO, version %s (expected %s)' %
866 (dest_ec_version, image_ec_version))
Brent Peterson1cb623a2020-01-09 13:14:28 -0800867
868 # Check programmed BIOS firmware against expected version
869 logging.info('Checking BIOS firmware version.')
870 dest_bios_version = self.get_firmware_version()
871 bios_version_prefix = dest_bios_version.split('.', 1)[0]
872 bios_regex = self._BIOS_REGEX % bios_version_prefix
873 image_bios_version = self.get_version_from_image(bios_image,
874 bios_regex)
875 if dest_bios_version != image_bios_version:
876 raise error.TestFail(
877 'Failed to update BIOS RO, version %s (expected %s)' %
878 (dest_bios_version, image_bios_version))
Dan Shi9cb0eec2014-06-03 09:04:50 -0700879 finally:
Mary Ruthven6481a9f2019-08-23 12:46:05 -0700880 if tmpd:
881 tmpd.clean()
Dan Shi9cb0eec2014-06-03 09:04:50 -0700882
883
beepsf079cfb2013-09-18 17:49:51 -0700884 def servo_install(self, image_url=None, usb_boot_timeout=USB_BOOT_TIMEOUT,
885 install_timeout=INSTALL_TIMEOUT):
Scott Zawalski62bacae2013-03-05 10:40:32 -0500886 """
887 Re-install the OS on the DUT by:
888 1) installing a test image on a USB storage device attached to the Servo
889 board,
Richard Barnette03a0c132012-11-05 12:40:35 -0800890 2) booting that image in recovery mode, and then
J. Richard Barnette31b2e312013-04-04 16:05:22 -0700891 3) installing the image with chromeos-install.
892
Scott Zawalski62bacae2013-03-05 10:40:32 -0500893 @param image_url: If specified use as the url to install on the DUT.
894 otherwise boot the currently staged image on the USB stick.
beepsf079cfb2013-09-18 17:49:51 -0700895 @param usb_boot_timeout: The usb_boot_timeout to use during reimage.
896 Factory images need a longer usb_boot_timeout than regular
897 cros images.
898 @param install_timeout: The timeout to use when installing the chromeos
899 image. Factory images need a longer install_timeout.
Richard Barnette03a0c132012-11-05 12:40:35 -0800900
Scott Zawalski62bacae2013-03-05 10:40:32 -0500901 @raises AutoservError if the image fails to boot.
beepsf079cfb2013-09-18 17:49:51 -0700902
J. Richard Barnette0199cc82014-12-05 17:08:40 -0800903 """
beepsf079cfb2013-09-18 17:49:51 -0700904 logging.info('Downloading image to USB, then booting from it. Usb boot '
905 'timeout = %s', usb_boot_timeout)
Allen Li48a13fe2016-11-22 14:10:40 -0800906 with metrics.SecondsTimer(
907 'chromeos/autotest/provision/servo_install/boot_duration'):
908 self.servo.install_recovery_image(image_url)
909 if not self.wait_up(timeout=usb_boot_timeout):
910 raise hosts.AutoservRepairError(
911 'DUT failed to boot from USB after %d seconds' %
Garry Wang954f8382019-01-23 13:49:29 -0800912 usb_boot_timeout, 'failed_to_reboot')
Scott Zawalski62bacae2013-03-05 10:40:32 -0500913
Tom Wai-Hong Tamf6b4f812015-08-08 04:14:59 +0800914 # The new chromeos-tpm-recovery has been merged since R44-7073.0.0.
915 # In old CrOS images, this command fails. Skip the error.
Tom Wai-Hong Tam27af7332015-07-25 06:09:39 +0800916 logging.info('Resetting the TPM status')
Tom Wai-Hong Tamf6b4f812015-08-08 04:14:59 +0800917 try:
918 self.run('chromeos-tpm-recovery')
919 except error.AutoservRunError:
920 logging.warn('chromeos-tpm-recovery is too old.')
921
Tom Wai-Hong Tam27af7332015-07-25 06:09:39 +0800922
Allen Li48a13fe2016-11-22 14:10:40 -0800923 with metrics.SecondsTimer(
924 'chromeos/autotest/provision/servo_install/install_duration'):
925 logging.info('Installing image through chromeos-install.')
Garry Wang83fb5b32019-09-27 13:16:00 -0700926 self.run('chromeos-install --yes',timeout=install_timeout)
Anh Lee21e4032019-07-11 15:01:06 -0700927
Allen Li48a13fe2016-11-22 14:10:40 -0800928 self.halt()
beepsf079cfb2013-09-18 17:49:51 -0700929
930 logging.info('Power cycling DUT through servo.')
J. Richard Barnette0199cc82014-12-05 17:08:40 -0800931 self.servo.get_power_state_controller().power_off()
Fang Dengafb88142013-05-30 17:44:31 -0700932 self.servo.switch_usbkey('off')
J. Richard Barnette0199cc82014-12-05 17:08:40 -0800933 # N.B. The Servo API requires that we use power_on() here
934 # for two reasons:
935 # 1) After turning on a DUT in recovery mode, you must turn
936 # it off and then on with power_on() once more to
937 # disable recovery mode (this is a Parrot specific
938 # requirement).
939 # 2) After power_off(), the only way to turn on is with
940 # power_on() (this is a Storm specific requirement).
J. Richard Barnettefbcc7122013-07-24 18:24:59 -0700941 self.servo.get_power_state_controller().power_on()
beepsf079cfb2013-09-18 17:49:51 -0700942
943 logging.info('Waiting for DUT to come back up.')
Richard Barnette03a0c132012-11-05 12:40:35 -0800944 if not self.wait_up(timeout=self.BOOT_TIMEOUT):
945 raise error.AutoservError('DUT failed to reboot installed '
946 'test image after %d seconds' %
Scott Zawalski62bacae2013-03-05 10:40:32 -0500947 self.BOOT_TIMEOUT)
948
949
Shelley Chen905f1272020-03-06 20:52:07 +0000950 def set_servo_host(self, host):
Richard Barnette4aeb01c2018-09-20 09:36:12 -0700951 """Set our servo host member, and associated servo.
952
953 @param host Our new `ServoHost`.
954 """
955 self._servo_host = host
956 if self._servo_host is not None:
957 self.servo = self._servo_host.get_servo()
Shelley Chen905f1272020-03-06 20:52:07 +0000958 self._update_servo_labels()
Richard Barnette4aeb01c2018-09-20 09:36:12 -0700959 else:
960 self.servo = None
961
962
Richard Barnette9a26ad62016-06-10 12:03:08 -0700963 def repair_servo(self):
Dan Shi90466352015-09-22 15:01:05 -0700964 """
Richard Barnette9a26ad62016-06-10 12:03:08 -0700965 Confirm that servo is initialized and verified.
Dan Shi90466352015-09-22 15:01:05 -0700966
Richard Barnette9a26ad62016-06-10 12:03:08 -0700967 If the servo object is missing, attempt to repair the servo
968 host. Repair failures are passed back to the caller.
969
970 @raise AutoservError: If there is no servo host for this CrOS
971 host.
972 """
973 if self.servo:
974 return
975 if not self._servo_host:
976 raise error.AutoservError('No servo host for %s.' %
977 self.hostname)
Otabek Kasimovcc9738e2020-02-14 16:17:15 -0800978 try:
979 self._servo_host.repair()
980 except:
981 raise
982 finally:
983 self.set_servo_host(self._servo_host)
984
985
Shelley Chen905f1272020-03-06 20:52:07 +0000986 def _update_servo_labels(self):
Otabek Kasimovcc9738e2020-02-14 16:17:15 -0800987 """Set servo info labels to dut host_info"""
Shelley Chen905f1272020-03-06 20:52:07 +0000988 if self._servo_host:
Otabek Kasimovcc9738e2020-02-14 16:17:15 -0800989 host_info = self.host_info_store.get()
Shelley Chen905f1272020-03-06 20:52:07 +0000990
991 servo_state = self._servo_host.get_servo_state()
992 host_info.set_version_label(servo_host.SERVO_STATE_LABEL_PREFIX, servo_state)
993
Otabek Kasimovcc9738e2020-02-14 16:17:15 -0800994 self.host_info_store.commit(host_info)
Dan Shi90466352015-09-22 15:01:05 -0700995
996
J. Richard Barnettec2d99cf2015-11-18 12:46:15 -0800997 def repair(self):
998 """Attempt to get the DUT to pass `self.verify()`.
Richard Barnette82c35912012-11-20 10:09:10 -0800999
1000 This overrides the base class function for repair; it does
J. Richard Barnette91137f02016-03-10 16:52:26 -08001001 not call back to the parent class, but instead relies on
1002 `self._repair_strategy` to coordinate the verification and
1003 repair steps needed to get the DUT working.
Richard Barnette82c35912012-11-20 10:09:10 -08001004 """
Richard Barnetteabbdc252018-07-26 16:57:42 -07001005 message = 'Beginning repair for host %s board %s model %s'
1006 info = self.host_info_store.get()
1007 message %= (self.hostname, info.board, info.model)
1008 self.record('INFO', None, None, message)
J. Richard Barnette91137f02016-03-10 16:52:26 -08001009 self._repair_strategy.repair(self)
Scott Zawalski89c44dd2013-02-26 09:28:02 -05001010
Richard Barnette82c35912012-11-20 10:09:10 -08001011
J. Richard Barnette1d78b012012-05-15 13:56:30 -07001012 def close(self):
David Rileye2c6be12017-12-11 10:20:57 -08001013 """Close connection."""
Fang Deng0ca40e22013-08-27 17:47:44 -07001014 super(CrosHost, self).close()
howardchung83e55272019-08-08 14:08:05 +08001015
Shijin Abraham783a7dd2020-02-14 15:36:11 -08001016 if self._chameleon_host:
1017 self._chameleon_host.close()
xixuand6011f12016-12-08 15:01:58 -08001018
1019 if self._servo_host:
1020 self._servo_host.close()
J. Richard Barnette1d78b012012-05-15 13:56:30 -07001021
1022
Dan Shi49ca0932014-11-14 11:22:27 -08001023 def get_power_supply_info(self):
1024 """Get the output of power_supply_info.
1025
1026 power_supply_info outputs the info of each power supply, e.g.,
1027 Device: Line Power
1028 online: no
1029 type: Mains
1030 voltage (V): 0
1031 current (A): 0
1032 Device: Battery
1033 state: Discharging
1034 percentage: 95.9276
1035 technology: Li-ion
1036
1037 Above output shows two devices, Line Power and Battery, with details of
1038 each device listed. This function parses the output into a dictionary,
1039 with key being the device name, and value being a dictionary of details
1040 of the device info.
1041
1042 @return: The dictionary of power_supply_info, e.g.,
1043 {'Line Power': {'online': 'yes', 'type': 'main'},
1044 'Battery': {'vendor': 'xyz', 'percentage': '100'}}
Dan Shie9b765d2014-12-29 16:59:49 -08001045 @raise error.AutoservRunError if power_supply_info tool is not found in
1046 the DUT. Caller should handle this error to avoid false failure
1047 on verification.
Dan Shi49ca0932014-11-14 11:22:27 -08001048 """
1049 result = self.run('power_supply_info').stdout.strip()
1050 info = {}
1051 device_name = None
1052 device_info = {}
1053 for line in result.split('\n'):
1054 pair = [v.strip() for v in line.split(':')]
1055 if len(pair) != 2:
1056 continue
1057 if pair[0] == 'Device':
1058 if device_name:
1059 info[device_name] = device_info
1060 device_name = pair[1]
1061 device_info = {}
1062 else:
1063 device_info[pair[0]] = pair[1]
1064 if device_name and not device_name in info:
1065 info[device_name] = device_info
1066 return info
1067
1068
1069 def get_battery_percentage(self):
1070 """Get the battery percentage.
1071
1072 @return: The percentage of battery level, value range from 0-100. Return
1073 None if the battery info cannot be retrieved.
1074 """
1075 try:
1076 info = self.get_power_supply_info()
1077 logging.info(info)
1078 return float(info['Battery']['percentage'])
Dan Shie9b765d2014-12-29 16:59:49 -08001079 except (KeyError, ValueError, error.AutoservRunError):
Dan Shi49ca0932014-11-14 11:22:27 -08001080 return None
1081
1082
Daniel Campello8ca25c22019-12-13 16:48:26 -07001083 def get_battery_display_percentage(self):
1084 """Get the battery display percentage.
1085
1086 @return: The display percentage of battery level, value range from
1087 0-100. Return None if the battery info cannot be retrieved.
1088 """
1089 try:
1090 info = self.get_power_supply_info()
1091 logging.info(info)
1092 return float(info['Battery']['display percentage'])
1093 except (KeyError, ValueError, error.AutoservRunError):
1094 return None
1095
1096
Dan Shi49ca0932014-11-14 11:22:27 -08001097 def is_ac_connected(self):
1098 """Check if the dut has power adapter connected and charging.
1099
1100 @return: True if power adapter is connected and charging.
1101 """
1102 try:
1103 info = self.get_power_supply_info()
1104 return info['Line Power']['online'] == 'yes'
Dan Shie9b765d2014-12-29 16:59:49 -08001105 except (KeyError, error.AutoservRunError):
1106 return None
Dan Shi49ca0932014-11-14 11:22:27 -08001107
1108
Simran Basi5e6339a2013-03-21 11:34:32 -07001109 def _cleanup_poweron(self):
1110 """Special cleanup method to make sure hosts always get power back."""
Garry Wangad4d4fd2019-01-30 17:00:38 -08001111 info = self.host_info_store.get()
1112 if self._RPM_OUTLET_CHANGED not in info.attributes:
Simran Basi5e6339a2013-03-21 11:34:32 -07001113 return
1114 logging.debug('This host has recently interacted with the RPM'
1115 ' Infrastructure. Ensuring power is on.')
1116 try:
1117 self.power_on()
Garry Wangad4d4fd2019-01-30 17:00:38 -08001118 self._remove_rpm_changed_tag()
Simran Basi5e6339a2013-03-21 11:34:32 -07001119 except rpm_client.RemotePowerException:
Simran Basi5e6339a2013-03-21 11:34:32 -07001120 logging.error('Failed to turn Power On for this host after '
1121 'cleanup through the RPM Infrastructure.')
Dan Shi49ca0932014-11-14 11:22:27 -08001122
1123 battery_percentage = self.get_battery_percentage()
Dan Shif01ebe22014-12-05 13:10:57 -08001124 if battery_percentage and battery_percentage < 50:
Dan Shi49ca0932014-11-14 11:22:27 -08001125 raise
1126 elif self.is_ac_connected():
1127 logging.info('The device has power adapter connected and '
1128 'charging. No need to try to turn RPM on '
1129 'again.')
Garry Wangad4d4fd2019-01-30 17:00:38 -08001130 self._remove_rpm_changed_tag()
Dan Shi49ca0932014-11-14 11:22:27 -08001131 logging.info('Battery level is now at %s%%. The device may '
1132 'still have enough power to run test, so no '
1133 'exception will be raised.', battery_percentage)
1134
Simran Basi5e6339a2013-03-21 11:34:32 -07001135
Garry Wangad4d4fd2019-01-30 17:00:38 -08001136 def _remove_rpm_changed_tag(self):
1137 info = self.host_info_store.get()
1138 del info.attributes[self._RPM_OUTLET_CHANGED]
1139 self.host_info_store.commit(info)
1140
1141
1142 def _add_rpm_changed_tag(self):
1143 info = self.host_info_store.get()
Garry Wang518831d2019-02-21 15:15:36 -08001144 info.attributes[self._RPM_OUTLET_CHANGED] = 'true'
Garry Wangad4d4fd2019-01-30 17:00:38 -08001145 self.host_info_store.commit(info)
1146
1147
1148
beepsc87ff602013-07-31 21:53:00 -07001149 def _is_factory_image(self):
1150 """Checks if the image on the DUT is a factory image.
1151
1152 @return: True if the image on the DUT is a factory image.
1153 False otherwise.
1154 """
1155 result = self.run('[ -f /root/.factory_test ]', ignore_status=True)
1156 return result.exit_status == 0
1157
1158
1159 def _restart_ui(self):
J. Richard Barnette84890bd2014-02-21 11:05:47 -08001160 """Restart the Chrome UI.
beepsc87ff602013-07-31 21:53:00 -07001161
1162 @raises: FactoryImageCheckerException for factory images, since
1163 we cannot attempt to restart ui on them.
1164 error.AutoservRunError for any other type of error that
1165 occurs while restarting ui.
1166 """
1167 if self._is_factory_image():
Dan Shi549fb822015-03-24 18:01:11 -07001168 raise FactoryImageCheckerException('Cannot restart ui on factory '
1169 'images')
beepsc87ff602013-07-31 21:53:00 -07001170
J. Richard Barnette84890bd2014-02-21 11:05:47 -08001171 # TODO(jrbarnette): The command to stop/start the ui job
1172 # should live inside cros_ui, too. However that would seem
1173 # to imply interface changes to the existing start()/restart()
1174 # functions, which is a bridge too far (for now).
J. Richard Barnette6069aa12015-06-08 09:10:24 -07001175 prompt = cros_ui.get_chrome_session_ident(self)
J. Richard Barnette84890bd2014-02-21 11:05:47 -08001176 self.run('stop ui; start ui')
1177 cros_ui.wait_for_chrome_ready(prompt, self)
beepsc87ff602013-07-31 21:53:00 -07001178
1179
Daniel Erat4b5f7e02018-07-04 22:05:30 -07001180 def _start_powerd_if_needed(self):
1181 """Start powerd if it isn't already running."""
1182 self.run('start powerd', ignore_status=True)
1183
1184
xixuana3bbc422017-05-04 15:57:21 -07001185 def _get_lsb_release_content(self):
1186 """Return the content of lsb-release file of host."""
1187 return self.run(
1188 'cat "%s"' % client_constants.LSB_RELEASE).stdout.strip()
1189
1190
Dan Shi549fb822015-03-24 18:01:11 -07001191 def get_release_version(self):
1192 """Get the value of attribute CHROMEOS_RELEASE_VERSION from lsb-release.
1193
1194 @returns The version string in lsb-release, under attribute
1195 CHROMEOS_RELEASE_VERSION.
1196 """
Dan Shi549fb822015-03-24 18:01:11 -07001197 return lsbrelease_utils.get_chromeos_release_version(
xixuana3bbc422017-05-04 15:57:21 -07001198 lsb_release_content=self._get_lsb_release_content())
1199
1200
Don Garrettb9f35802018-01-22 18:25:40 -08001201 def get_release_builder_path(self):
1202 """Get the value of CHROMEOS_RELEASE_BUILDER_PATH from lsb-release.
1203
1204 @returns The version string in lsb-release, under attribute
1205 CHROMEOS_RELEASE_BUILDER_PATH.
1206 """
1207 return lsbrelease_utils.get_chromeos_release_builder_path(
1208 lsb_release_content=self._get_lsb_release_content())
1209
1210
xixuana3bbc422017-05-04 15:57:21 -07001211 def get_chromeos_release_milestone(self):
1212 """Get the value of attribute CHROMEOS_RELEASE_BUILD_TYPE
1213 from lsb-release.
1214
1215 @returns The version string in lsb-release, under attribute
1216 CHROMEOS_RELEASE_BUILD_TYPE.
1217 """
1218 return lsbrelease_utils.get_chromeos_release_milestone(
1219 lsb_release_content=self._get_lsb_release_content())
Dan Shi549fb822015-03-24 18:01:11 -07001220
1221
1222 def verify_cros_version_label(self):
1223 """ Make sure host's cros-version label match the actual image in dut.
1224
1225 Remove any cros-version: label that doesn't match that installed in
1226 the dut.
1227
1228 @param raise_error: Set to True to raise exception if any mismatch found
1229
1230 @raise error.AutoservError: If any mismatch between cros-version label
1231 and the build installed in dut is found.
1232 """
Prathmesh Prabhuce2da3a2019-10-04 11:54:51 -07001233 # crbug.com/1007333: This check is being removed.
1234 return True
Dan Shi549fb822015-03-24 18:01:11 -07001235
1236
Laurence Goodby778c9a42017-05-24 19:24:07 -07001237 def cleanup_services(self):
1238 """Reinitializes the device for cleanup.
1239
1240 Subclasses may override this to customize the cleanup method.
1241
1242 To indicate failure of the reset, the implementation may raise
1243 any of:
1244 error.AutoservRunError
1245 error.AutotestRunError
1246 FactoryImageCheckerException
1247
1248 @raises error.AutoservRunError
1249 @raises error.AutotestRunError
1250 @raises error.FactoryImageCheckerException
1251 """
1252 self._restart_ui()
Daniel Erat4b5f7e02018-07-04 22:05:30 -07001253 self._start_powerd_if_needed()
Laurence Goodby778c9a42017-05-24 19:24:07 -07001254
1255
beepsc87ff602013-07-31 21:53:00 -07001256 def cleanup(self):
Pradeep Sawlaniaa013fa2017-11-09 06:34:18 -08001257 """Cleanup state on device."""
MK Ryu35d661e2014-09-25 17:44:10 -07001258 self.run('rm -f %s' % client_constants.CLEANUP_LOGS_PAUSED_FILE)
Scott Zawalskiddbc31e2012-11-15 11:29:01 -05001259 try:
Laurence Goodby778c9a42017-05-24 19:24:07 -07001260 self.cleanup_services()
beepsc87ff602013-07-31 21:53:00 -07001261 except (error.AutotestRunError, error.AutoservRunError,
1262 FactoryImageCheckerException):
Ilja H. Friedel04be2bd2014-05-07 21:29:59 -07001263 logging.warning('Unable to restart ui, rebooting device.')
Scott Zawalskiddbc31e2012-11-15 11:29:01 -05001264 # Since restarting the UI fails fall back to normal Autotest
1265 # cleanup routines, i.e. reboot the machine.
Fang Deng0ca40e22013-08-27 17:47:44 -07001266 super(CrosHost, self).cleanup()
Simran Basi5e6339a2013-03-21 11:34:32 -07001267 # Check if the rpm outlet was manipulated.
Simran Basid5e5e272012-09-24 15:23:59 -07001268 if self.has_power():
Simran Basi5e6339a2013-03-21 11:34:32 -07001269 self._cleanup_poweron()
Dan Shi549fb822015-03-24 18:01:11 -07001270 self.verify_cros_version_label()
J. Richard Barnette45e93de2012-04-11 17:24:15 -07001271
1272
Yu-Ju Honga2be94a2012-07-31 09:48:52 -07001273 def reboot(self, **dargs):
1274 """
1275 This function reboots the site host. The more generic
1276 RemoteHost.reboot() performs sync and sleeps for 5
1277 seconds. This is not necessary for Chrome OS devices as the
1278 sync should be finished in a short time during the reboot
1279 command.
1280 """
Tom Wai-Hong Tamf5cd1d42012-08-13 12:04:08 +08001281 if 'reboot_cmd' not in dargs:
Doug Anderson7d5aeb22014-02-27 15:12:17 -08001282 reboot_timeout = dargs.get('reboot_timeout', 10)
J. Richard Barnette9af19632015-09-25 12:18:03 -07001283 dargs['reboot_cmd'] = ('sleep 1; '
1284 'reboot & sleep %d; '
1285 'reboot -f' % reboot_timeout)
Yu-Ju Honga2be94a2012-07-31 09:48:52 -07001286 # Enable fastsync to avoid running extra sync commands before reboot.
Tom Wai-Hong Tamf5cd1d42012-08-13 12:04:08 +08001287 if 'fastsync' not in dargs:
1288 dargs['fastsync'] = True
Michael Liangda8c60a2014-06-03 13:24:51 -07001289
Prathmesh Prabhu53a4c1c2018-09-14 16:36:27 -07001290 dargs['board'] = self.host_info_store.get().board
Vincent Palatindf2372c2016-10-07 17:03:00 +02001291 # Record who called us
1292 orig = sys._getframe(1).f_code
Vincent Palatin80780b22016-07-27 16:02:37 +02001293 metric_fields = {'board' : dargs['board'],
Vincent Palatindf2372c2016-10-07 17:03:00 +02001294 'dut_host_name' : self.hostname,
1295 'success' : True}
1296 metric_debug_fields = {'board' : dargs['board'],
Prathmesh Prabhu53a4c1c2018-09-14 16:36:27 -07001297 'caller' : "%s:%s" % (orig.co_filename,
1298 orig.co_name),
Vincent Palatindf2372c2016-10-07 17:03:00 +02001299 'success' : True,
1300 'error' : ''}
1301
Vincent Palatin80780b22016-07-27 16:02:37 +02001302 t0 = time.time()
1303 try:
1304 super(CrosHost, self).reboot(**dargs)
1305 except Exception as e:
1306 metric_fields['success'] = False
Vincent Palatindf2372c2016-10-07 17:03:00 +02001307 metric_debug_fields['success'] = False
1308 metric_debug_fields['error'] = type(e).__name__
Vincent Palatin80780b22016-07-27 16:02:37 +02001309 raise
1310 finally:
1311 duration = int(time.time() - t0)
Dan Shi5e2efb72017-02-07 11:40:23 -08001312 metrics.Counter(
1313 'chromeos/autotest/autoserv/reboot_count').increment(
1314 fields=metric_fields)
1315 metrics.Counter(
1316 'chromeos/autotest/autoserv/reboot_debug').increment(
1317 fields=metric_debug_fields)
1318 metrics.SecondsDistribution(
1319 'chromeos/autotest/autoserv/reboot_duration').add(
1320 duration, fields=metric_fields)
Yu-Ju Honga2be94a2012-07-31 09:48:52 -07001321
1322
Kalin Stoyanov83d9caa2020-01-31 16:58:27 -08001323 def suspend(self, suspend_time=60, delay_seconds=0,
Ravi Chandra Sadineni812e61b2018-07-09 11:16:50 -07001324 suspend_cmd=None, allow_early_resume=False):
Gwendal Grignou7a61d2f2014-05-23 11:05:51 -07001325 """
1326 This function suspends the site host.
Ravi Chandra Sadineni812e61b2018-07-09 11:16:50 -07001327
1328 @param suspend_time: How long to suspend as integer seconds.
1329 @param suspend_cmd: Suspend command to execute.
1330 @param allow_early_resume: If False and if device resumes before
1331 |suspend_time|, throw an error.
1332
1333 @exception AutoservSuspendError Host resumed earlier than
1334 |suspend_time|.
Gwendal Grignou7a61d2f2014-05-23 11:05:51 -07001335 """
Ravi Chandra Sadineni812e61b2018-07-09 11:16:50 -07001336
1337 if suspend_cmd is None:
1338 suspend_cmd = ' && '.join([
J. Richard Barnette9af19632015-09-25 12:18:03 -07001339 'echo 0 > /sys/class/rtc/rtc0/wakealarm',
Gwendal Grignou7a61d2f2014-05-23 11:05:51 -07001340 'echo +%d > /sys/class/rtc/rtc0/wakealarm' % suspend_time,
Kalin Stoyanov83d9caa2020-01-31 16:58:27 -08001341 'powerd_dbus_suspend --delay=%d' % delay_seconds])
Ravi Chandra Sadineni812e61b2018-07-09 11:16:50 -07001342 super(CrosHost, self).suspend(suspend_time, suspend_cmd,
1343 allow_early_resume);
Gwendal Grignou7a61d2f2014-05-23 11:05:51 -07001344
1345
Simran Basiec564392014-08-25 16:48:09 -07001346 def upstart_status(self, service_name):
1347 """Check the status of an upstart init script.
1348
1349 @param service_name: Service to look up.
1350
1351 @returns True if the service is running, False otherwise.
1352 """
Richard Barnettee204dc52017-09-26 11:02:25 -07001353 return 'start/running' in self.run('status %s' % service_name,
1354 ignore_status=True).stdout
Simran Basiec564392014-08-25 16:48:09 -07001355
Tom Hughese9552342018-12-18 14:29:25 -08001356 def upstart_stop(self, service_name):
1357 """Stops an upstart job if it's running.
1358
1359 @param service_name: Service to stop
1360
1361 @returns True if service has been stopped or was already stopped
1362 False otherwise.
1363 """
1364 if not self.upstart_status(service_name):
1365 return True
1366
1367 result = self.run('stop %s' % service_name, ignore_status=True)
1368 if result.exit_status != 0:
1369 return False
1370 return True
1371
1372 def upstart_restart(self, service_name):
1373 """Restarts (or starts) an upstart job.
1374
1375 @param service_name: Service to start/restart
1376
1377 @returns True if service has been started/restarted, False otherwise.
1378 """
1379 cmd = 'start'
1380 if self.upstart_status(service_name):
1381 cmd = 'restart'
1382 cmd = cmd + ' %s' % service_name
1383 result = self.run(cmd)
1384 if result.exit_status != 0:
1385 return False
1386 return True
Simran Basiec564392014-08-25 16:48:09 -07001387
J. Richard Barnette45e93de2012-04-11 17:24:15 -07001388 def verify_software(self):
Richard Barnetteb2bc13c2013-01-08 17:32:51 -08001389 """Verify working software on a Chrome OS system.
J. Richard Barnette45e93de2012-04-11 17:24:15 -07001390
Richard Barnetteb2bc13c2013-01-08 17:32:51 -08001391 Tests for the following conditions:
1392 1. All conditions tested by the parent version of this
1393 function.
1394 2. Sufficient space in /mnt/stateful_partition.
Fang Deng6b05f5b2013-03-20 13:42:11 -07001395 3. Sufficient space in /mnt/stateful_partition/encrypted.
1396 4. update_engine answers a simple status request over DBus.
J. Richard Barnette45e93de2012-04-11 17:24:15 -07001397
J. Richard Barnette45e93de2012-04-11 17:24:15 -07001398 """
Fang Deng0ca40e22013-08-27 17:47:44 -07001399 super(CrosHost, self).verify_software()
Dan Shib8540a52015-07-16 14:18:23 -07001400 default_kilo_inodes_required = CONFIG.get_config_value(
1401 'SERVER', 'kilo_inodes_required', type=int, default=100)
1402 board = self.get_board().replace(ds_constants.BOARD_PREFIX, '')
1403 kilo_inodes_required = CONFIG.get_config_value(
1404 'SERVER', 'kilo_inodes_required_%s' % board,
1405 type=int, default=default_kilo_inodes_required)
1406 self.check_inodes('/mnt/stateful_partition', kilo_inodes_required)
J. Richard Barnette45e93de2012-04-11 17:24:15 -07001407 self.check_diskspace(
1408 '/mnt/stateful_partition',
Dan Shib8540a52015-07-16 14:18:23 -07001409 CONFIG.get_config_value(
Fang Deng6b05f5b2013-03-20 13:42:11 -07001410 'SERVER', 'gb_diskspace_required', type=float,
1411 default=20.0))
Gaurav Shahe448af82014-06-19 15:18:59 -07001412 encrypted_stateful_path = '/mnt/stateful_partition/encrypted'
1413 # Not all targets build with encrypted stateful support.
1414 if self.path_exists(encrypted_stateful_path):
1415 self.check_diskspace(
1416 encrypted_stateful_path,
Dan Shib8540a52015-07-16 14:18:23 -07001417 CONFIG.get_config_value(
Gaurav Shahe448af82014-06-19 15:18:59 -07001418 'SERVER', 'gb_encrypted_diskspace_required', type=float,
1419 default=0.1))
beepsc87ff602013-07-31 21:53:00 -07001420
Justin TerAvest3b0c5ba2017-11-07 09:59:11 -07001421 self.wait_for_system_services()
Prashanth B5d0a0512014-04-25 12:26:08 -07001422
beepsc87ff602013-07-31 21:53:00 -07001423 # Factory images don't run update engine,
1424 # goofy controls dbus on these DUTs.
1425 if not self._is_factory_image():
1426 self.run('update_engine_client --status')
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001427
Dan Shi549fb822015-03-24 18:01:11 -07001428 self.verify_cros_version_label()
1429
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001430
Justin TerAvest3b0c5ba2017-11-07 09:59:11 -07001431 @retry.retry(error.AutoservError, timeout_min=5, delay_sec=10)
1432 def wait_for_system_services(self):
1433 """Waits for system-services to be running.
1434
1435 Sometimes, update_engine will take a while to update firmware, so we
1436 should give this some time to finish. See crbug.com/765686#c38 for
1437 details.
1438 """
1439 if not self.upstart_status('system-services'):
1440 raise error.AutoservError('Chrome failed to reach login. '
1441 'System services not running.')
1442
1443
J. Richard Barnettea7e7fdc2016-02-12 12:35:36 -08001444 def verify(self):
Pradeep Sawlaniaa013fa2017-11-09 06:34:18 -08001445 """Verify Chrome OS system is in good state."""
Richard Barnetteabbdc252018-07-26 16:57:42 -07001446 message = 'Beginning verify for host %s board %s model %s'
1447 info = self.host_info_store.get()
1448 message %= (self.hostname, info.board, info.model)
1449 self.record('INFO', None, None, message)
J. Richard Barnettea7e7fdc2016-02-12 12:35:36 -08001450 self._repair_strategy.verify(self)
1451
1452
Fang Deng96667ca2013-08-01 17:46:18 -07001453 def make_ssh_command(self, user='root', port=22, opts='', hosts_file=None,
Dean Liaoe3e75f62017-11-14 10:36:43 +08001454 connect_timeout=None, alive_interval=None,
1455 alive_count_max=None, connection_attempts=None):
Fang Deng96667ca2013-08-01 17:46:18 -07001456 """Override default make_ssh_command to use options tuned for Chrome OS.
1457
1458 Tuning changes:
1459 - ConnectTimeout=30; maximum of 30 seconds allowed for an SSH
1460 connection failure. Consistency with remote_access.sh.
1461
Samuel Tan2ce155b2015-06-23 18:24:38 -07001462 - ServerAliveInterval=900; which causes SSH to ping connection every
1463 900 seconds. In conjunction with ServerAliveCountMax ensures
1464 that if the connection dies, Autotest will bail out.
Fang Deng96667ca2013-08-01 17:46:18 -07001465 Originally tried 60 secs, but saw frequent job ABORTS where
Samuel Tan2ce155b2015-06-23 18:24:38 -07001466 the test completed successfully. Later increased from 180 seconds to
1467 900 seconds to account for tests where the DUT is suspended for
1468 longer periods of time.
Fang Deng96667ca2013-08-01 17:46:18 -07001469
1470 - ServerAliveCountMax=3; consistency with remote_access.sh.
1471
1472 - ConnectAttempts=4; reduce flakiness in connection errors;
1473 consistency with remote_access.sh.
1474
1475 - UserKnownHostsFile=/dev/null; we don't care about the keys.
1476 Host keys change with every new installation, don't waste
1477 memory/space saving them.
1478
1479 - SSH protocol forced to 2; needed for ServerAliveInterval.
1480
1481 @param user User name to use for the ssh connection.
1482 @param port Port on the target host to use for ssh connection.
1483 @param opts Additional options to the ssh command.
1484 @param hosts_file Ignored.
1485 @param connect_timeout Ignored.
1486 @param alive_interval Ignored.
Dean Liaoe3e75f62017-11-14 10:36:43 +08001487 @param alive_count_max Ignored.
1488 @param connection_attempts Ignored.
Fang Deng96667ca2013-08-01 17:46:18 -07001489 """
Dean Liaoe3e75f62017-11-14 10:36:43 +08001490 options = ' '.join([opts, '-o Protocol=2'])
1491 return super(CrosHost, self).make_ssh_command(
1492 user=user, port=port, opts=options, hosts_file='/dev/null',
1493 connect_timeout=30, alive_interval=900, alive_count_max=3,
1494 connection_attempts=4)
1495
1496
Jason Abeleb6f924f2013-11-13 16:01:54 -08001497 def syslog(self, message, tag='autotest'):
1498 """Logs a message to syslog on host.
1499
1500 @param message String message to log into syslog
1501 @param tag String tag prefix for syslog
1502
1503 """
1504 self.run('logger -t "%s" "%s"' % (tag, message))
1505
1506
J. Richard Barnetteb6de7e32013-02-14 13:28:04 -08001507 def _ping_check_status(self, status):
1508 """Ping the host once, and return whether it has a given status.
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001509
J. Richard Barnetteb6de7e32013-02-14 13:28:04 -08001510 @param status Check the ping status against this value.
1511 @return True iff `status` and the result of ping are the same
1512 (i.e. both True or both False).
1513
1514 """
1515 ping_val = utils.ping(self.hostname, tries=1, deadline=1)
1516 return not (status ^ (ping_val == 0))
1517
1518 def _ping_wait_for_status(self, status, timeout):
1519 """Wait for the host to have a given status (UP or DOWN).
1520
1521 Status is checked by polling. Polling will not last longer
1522 than the number of seconds in `timeout`. The polling
1523 interval will be long enough that only approximately
1524 _PING_WAIT_COUNT polling cycles will be executed, subject
1525 to a maximum interval of about one minute.
1526
1527 @param status Waiting will stop immediately if `ping` of the
1528 host returns this status.
1529 @param timeout Poll for at most this many seconds.
1530 @return True iff the host status from `ping` matched the
1531 requested status at the time of return.
1532
1533 """
1534 # _ping_check_status() takes about 1 second, hence the
1535 # "- 1" in the formula below.
Nathan Ciobanu38480a32016-10-25 15:26:45 -07001536 # FIXME: if the ping command errors then _ping_check_status()
1537 # returns instantly. If timeout is also smaller than twice
1538 # _PING_WAIT_COUNT then the while loop below forks many
1539 # thousands of ping commands (see /tmp/test_that_results_XXXXX/
1540 # /results-1-logging_YYY.ZZZ/debug/autoserv.DEBUG) and hogs one
1541 # CPU core for 60 seconds.
J. Richard Barnetteb6de7e32013-02-14 13:28:04 -08001542 poll_interval = min(int(timeout / self._PING_WAIT_COUNT), 60) - 1
1543 end_time = time.time() + timeout
1544 while time.time() <= end_time:
1545 if self._ping_check_status(status):
1546 return True
1547 if poll_interval > 0:
1548 time.sleep(poll_interval)
1549
1550 # The last thing we did was sleep(poll_interval), so it may
1551 # have been too long since the last `ping`. Check one more
1552 # time, just to be sure.
1553 return self._ping_check_status(status)
1554
1555 def ping_wait_up(self, timeout):
1556 """Wait for the host to respond to `ping`.
1557
1558 N.B. This method is not a reliable substitute for
1559 `wait_up()`, because a host that responds to ping will not
1560 necessarily respond to ssh. This method should only be used
1561 if the target DUT can be considered functional even if it
1562 can't be reached via ssh.
1563
1564 @param timeout Minimum time to allow before declaring the
1565 host to be non-responsive.
1566 @return True iff the host answered to ping before the timeout.
1567
1568 """
1569 return self._ping_wait_for_status(self._PING_STATUS_UP, timeout)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001570
Andrew Bresticker678c0c72013-01-22 10:44:09 -08001571 def ping_wait_down(self, timeout):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001572 """Wait until the host no longer responds to `ping`.
1573
J. Richard Barnetteb6de7e32013-02-14 13:28:04 -08001574 This function can be used as a slightly faster version of
1575 `wait_down()`, by avoiding potentially long ssh timeouts.
1576
1577 @param timeout Minimum time to allow for the host to become
1578 non-responsive.
1579 @return True iff the host quit answering ping before the
1580 timeout.
1581
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001582 """
J. Richard Barnetteb6de7e32013-02-14 13:28:04 -08001583 return self._ping_wait_for_status(self._PING_STATUS_DOWN, timeout)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001584
Tom Wai-Hong Tamfced4f62014-04-17 10:56:30 +08001585 def test_wait_for_sleep(self, sleep_timeout=None):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001586 """Wait for the client to enter low-power sleep mode.
1587
1588 The test for "is asleep" can't distinguish a system that is
1589 powered off; to confirm that the unit was asleep, it is
1590 necessary to force resume, and then call
1591 `test_wait_for_resume()`.
1592
1593 This function is expected to be called from a test as part
1594 of a sequence like the following:
1595
1596 ~~~~~~~~
1597 boot_id = host.get_boot_id()
1598 # trigger sleep on the host
1599 host.test_wait_for_sleep()
1600 # trigger resume on the host
1601 host.test_wait_for_resume(boot_id)
1602 ~~~~~~~~
1603
Tom Wai-Hong Tamfced4f62014-04-17 10:56:30 +08001604 @param sleep_timeout time limit in seconds to allow the host sleep.
1605
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001606 @exception TestFail The host did not go to sleep within
1607 the allowed time.
1608 """
Tom Wai-Hong Tamfced4f62014-04-17 10:56:30 +08001609 if sleep_timeout is None:
1610 sleep_timeout = self.SLEEP_TIMEOUT
1611
1612 if not self.ping_wait_down(timeout=sleep_timeout):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001613 raise error.TestFail(
Tom Wai-Hong Tamfced4f62014-04-17 10:56:30 +08001614 'client failed to sleep after %d seconds' % sleep_timeout)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001615
1616
Tom Wai-Hong Tamfced4f62014-04-17 10:56:30 +08001617 def test_wait_for_resume(self, old_boot_id, resume_timeout=None):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001618 """Wait for the client to resume from low-power sleep mode.
1619
1620 The `old_boot_id` parameter should be the value from
1621 `get_boot_id()` obtained prior to entering sleep mode. A
1622 `TestFail` exception is raised if the boot id changes.
1623
1624 See @ref test_wait_for_sleep for more on this function's
1625 usage.
1626
J. Richard Barnette7214e0b2013-02-06 15:20:49 -08001627 @param old_boot_id A boot id value obtained before the
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001628 target host went to sleep.
Tom Wai-Hong Tamfced4f62014-04-17 10:56:30 +08001629 @param resume_timeout time limit in seconds to allow the host up.
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001630
1631 @exception TestFail The host did not respond within the
1632 allowed time.
1633 @exception TestFail The host responded, but the boot id test
1634 indicated a reboot rather than a sleep
1635 cycle.
1636 """
Tom Wai-Hong Tamfced4f62014-04-17 10:56:30 +08001637 if resume_timeout is None:
1638 resume_timeout = self.RESUME_TIMEOUT
1639
1640 if not self.wait_up(timeout=resume_timeout):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001641 raise error.TestFail(
1642 'client failed to resume from sleep after %d seconds' %
Tom Wai-Hong Tamfced4f62014-04-17 10:56:30 +08001643 resume_timeout)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001644 else:
1645 new_boot_id = self.get_boot_id()
1646 if new_boot_id != old_boot_id:
Tom Wai-Hong Tam01792682015-01-06 08:00:46 +08001647 logging.error('client rebooted (old boot %s, new boot %s)',
1648 old_boot_id, new_boot_id)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001649 raise error.TestFail(
Tom Wai-Hong Tam01792682015-01-06 08:00:46 +08001650 'client rebooted, but sleep was expected')
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001651
1652
Tom Wai-Hong Tamfe005c22014-12-03 09:25:44 +08001653 def test_wait_for_shutdown(self, shutdown_timeout=None):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001654 """Wait for the client to shut down.
1655
1656 The test for "has shut down" can't distinguish a system that
1657 is merely asleep; to confirm that the unit was down, it is
1658 necessary to force boot, and then call test_wait_for_boot().
1659
1660 This function is expected to be called from a test as part
1661 of a sequence like the following:
1662
1663 ~~~~~~~~
1664 boot_id = host.get_boot_id()
1665 # trigger shutdown on the host
1666 host.test_wait_for_shutdown()
1667 # trigger boot on the host
1668 host.test_wait_for_boot(boot_id)
1669 ~~~~~~~~
1670
Tom Wai-Hong Tamfe005c22014-12-03 09:25:44 +08001671 @param shutdown_timeout time limit in seconds to allow the host down.
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001672 @exception TestFail The host did not shut down within the
1673 allowed time.
1674 """
Tom Wai-Hong Tamfe005c22014-12-03 09:25:44 +08001675 if shutdown_timeout is None:
1676 shutdown_timeout = self.SHUTDOWN_TIMEOUT
1677
1678 if not self.ping_wait_down(timeout=shutdown_timeout):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001679 raise error.TestFail(
1680 'client failed to shut down after %d seconds' %
Tom Wai-Hong Tamfe005c22014-12-03 09:25:44 +08001681 shutdown_timeout)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001682
1683
1684 def test_wait_for_boot(self, old_boot_id=None):
1685 """Wait for the client to boot from cold power.
1686
1687 The `old_boot_id` parameter should be the value from
1688 `get_boot_id()` obtained prior to shutting down. A
1689 `TestFail` exception is raised if the boot id does not
1690 change. The boot id test is omitted if `old_boot_id` is not
1691 specified.
1692
1693 See @ref test_wait_for_shutdown for more on this function's
1694 usage.
1695
J. Richard Barnette7214e0b2013-02-06 15:20:49 -08001696 @param old_boot_id A boot id value obtained before the
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001697 shut down.
1698
1699 @exception TestFail The host did not respond within the
1700 allowed time.
1701 @exception TestFail The host responded, but the boot id test
1702 indicated that there was no reboot.
1703 """
J. Richard Barnetteeb69d722012-06-18 17:29:44 -07001704 if not self.wait_up(timeout=self.REBOOT_TIMEOUT):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001705 raise error.TestFail(
1706 'client failed to reboot after %d seconds' %
J. Richard Barnetteeb69d722012-06-18 17:29:44 -07001707 self.REBOOT_TIMEOUT)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001708 elif old_boot_id:
1709 if self.get_boot_id() == old_boot_id:
Tom Wai-Hong Tam01792682015-01-06 08:00:46 +08001710 logging.error('client not rebooted (boot %s)',
1711 old_boot_id)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001712 raise error.TestFail(
Tom Wai-Hong Tam01792682015-01-06 08:00:46 +08001713 'client is back up, but did not reboot')
Simran Basid5e5e272012-09-24 15:23:59 -07001714
1715
1716 @staticmethod
1717 def check_for_rpm_support(hostname):
1718 """For a given hostname, return whether or not it is powered by an RPM.
1719
Simran Basi1df55112013-09-06 11:25:09 -07001720 @param hostname: hostname to check for rpm support.
1721
Simran Basid5e5e272012-09-24 15:23:59 -07001722 @return None if this host does not follows the defined naming format
1723 for RPM powered DUT's in the lab. If it does follow the format,
1724 it returns a regular expression MatchObject instead.
1725 """
Fang Dengbaff9082015-01-06 13:46:15 -08001726 return re.match(CrosHost._RPM_HOSTNAME_REGEX, hostname)
Simran Basid5e5e272012-09-24 15:23:59 -07001727
1728
1729 def has_power(self):
1730 """For this host, return whether or not it is powered by an RPM.
1731
1732 @return True if this host is in the CROS lab and follows the defined
1733 naming format.
1734 """
Fang Deng0ca40e22013-08-27 17:47:44 -07001735 return CrosHost.check_for_rpm_support(self.hostname)
Simran Basid5e5e272012-09-24 15:23:59 -07001736
1737
Ismail Noorbasha07fdb612013-02-14 14:13:31 -08001738 def _set_power(self, state, power_method):
Garry Wang5e5538a2019-04-08 15:36:18 -07001739 """Sets the power to the host via RPM, CCD, Servo or manual.
Ismail Noorbasha07fdb612013-02-14 14:13:31 -08001740
1741 @param state Specifies which power state to set to DUT
1742 @param power_method Specifies which method of power control to
Garry Wang5e5538a2019-04-08 15:36:18 -07001743 use. By default "RPM" or "CCD" will be used based
1744 on servo type. Valid values from
1745 POWER_CONTROL_VALID_ARGS, or None to use default.
Ismail Noorbasha07fdb612013-02-14 14:13:31 -08001746
1747 """
1748 ACCEPTABLE_STATES = ['ON', 'OFF']
1749
Garry Wang5e5538a2019-04-08 15:36:18 -07001750 if not power_method:
1751 power_method = self.get_default_power_method()
1752
1753 state = state.upper()
1754 if state not in ACCEPTABLE_STATES:
Ismail Noorbasha07fdb612013-02-14 14:13:31 -08001755 raise error.TestError('State must be one of: %s.'
1756 % (ACCEPTABLE_STATES,))
1757
1758 if power_method == self.POWER_CONTROL_SERVO:
1759 logging.info('Setting servo port J10 to %s', state)
1760 self.servo.set('prtctl3_pwren', state.lower())
1761 time.sleep(self._USB_POWER_TIMEOUT)
1762 elif power_method == self.POWER_CONTROL_MANUAL:
1763 logging.info('You have %d seconds to set the AC power to %s.',
1764 self._POWER_CYCLE_TIMEOUT, state)
1765 time.sleep(self._POWER_CYCLE_TIMEOUT)
Garry Wang5e5538a2019-04-08 15:36:18 -07001766 elif power_method == self.POWER_CONTROL_CCD:
1767 servo_role = 'src' if state == 'ON' else 'snk'
1768 logging.info('servo ccd power pass through detected,'
1769 ' changing servo_role to %s.', servo_role)
1770 self.servo.set_servo_v4_role(servo_role)
1771 if not self.ping_wait_up(timeout=self._CHANGE_SERVO_ROLE_TIMEOUT):
Garry Wang94bf9de2019-06-10 17:23:37 -07001772 # Make sure we don't leave DUT with no power(servo_role=snk)
1773 # when DUT is not pingable, as we raise a exception here
1774 # that may break a power cycle in the middle.
1775 self.servo.set_servo_v4_role('src')
Garry Wang5e5538a2019-04-08 15:36:18 -07001776 raise error.AutoservError(
1777 'DUT failed to regain network connection after %d seconds.'
1778 % self._CHANGE_SERVO_ROLE_TIMEOUT)
Ismail Noorbasha07fdb612013-02-14 14:13:31 -08001779 else:
1780 if not self.has_power():
1781 raise error.TestFail('DUT does not have RPM connected.')
Garry Wangad4d4fd2019-01-30 17:00:38 -08001782 self._add_rpm_changed_tag()
Garry Wang5e5538a2019-04-08 15:36:18 -07001783 rpm_client.set_power(self, state, timeout_mins=5)
Simran Basid5e5e272012-09-24 15:23:59 -07001784
1785
Garry Wang5e5538a2019-04-08 15:36:18 -07001786 def power_off(self, power_method=None):
1787 """Turn off power to this host via RPM, CCD, Servo or manual.
Ismail Noorbasha07fdb612013-02-14 14:13:31 -08001788
1789 @param power_method Specifies which method of power control to
Garry Wang5e5538a2019-04-08 15:36:18 -07001790 use. By default "RPM" or "CCD" will be used based
1791 on servo type. Valid values from
1792 POWER_CONTROL_VALID_ARGS, or None to use default.
Ismail Noorbasha07fdb612013-02-14 14:13:31 -08001793
1794 """
1795 self._set_power('OFF', power_method)
Simran Basid5e5e272012-09-24 15:23:59 -07001796
1797
Garry Wang5e5538a2019-04-08 15:36:18 -07001798 def power_on(self, power_method=None):
1799 """Turn on power to this host via RPM, CCD, Servo or manual.
Ismail Noorbasha07fdb612013-02-14 14:13:31 -08001800
1801 @param power_method Specifies which method of power control to
Garry Wang5e5538a2019-04-08 15:36:18 -07001802 use. By default "RPM" or "CCD" will be used based
1803 on servo type. Valid values from
1804 POWER_CONTROL_VALID_ARGS, or None to use default.
Ismail Noorbasha07fdb612013-02-14 14:13:31 -08001805
1806 """
1807 self._set_power('ON', power_method)
1808
1809
Garry Wang5e5538a2019-04-08 15:36:18 -07001810 def power_cycle(self, power_method=None):
Ismail Noorbasha07fdb612013-02-14 14:13:31 -08001811 """Cycle power to this host by turning it OFF, then ON.
1812
1813 @param power_method Specifies which method of power control to
Garry Wang5e5538a2019-04-08 15:36:18 -07001814 use. By default "RPM" or "CCD" will be used based
1815 on servo type. Valid values from
1816 POWER_CONTROL_VALID_ARGS, or None to use default.
Ismail Noorbasha07fdb612013-02-14 14:13:31 -08001817
1818 """
Garry Wang5e5538a2019-04-08 15:36:18 -07001819 if not power_method:
1820 power_method = self.get_default_power_method()
1821
Ismail Noorbasha07fdb612013-02-14 14:13:31 -08001822 if power_method in (self.POWER_CONTROL_SERVO,
Garry Wang5e5538a2019-04-08 15:36:18 -07001823 self.POWER_CONTROL_MANUAL,
1824 self.POWER_CONTROL_CCD):
Ismail Noorbasha07fdb612013-02-14 14:13:31 -08001825 self.power_off(power_method=power_method)
1826 time.sleep(self._POWER_CYCLE_TIMEOUT)
1827 self.power_on(power_method=power_method)
1828 else:
Garry Wangad4d4fd2019-01-30 17:00:38 -08001829 self._add_rpm_changed_tag()
1830 rpm_client.set_power(self, 'CYCLE')
Simran Basic6f1f7a2012-10-16 10:47:46 -07001831
1832
Mary Ruthvende14a8b2019-08-23 12:43:52 -07001833 def get_platform_from_fwid(self):
1834 """Determine the platform from the crossystem fwid.
1835
1836 @returns a string representing this host's platform.
1837 """
1838 # Look at the firmware for non-unibuild cases or if mosys fails.
1839 crossystem = utils.Crossystem(self)
1840 crossystem.init()
1841 # Extract fwid value and use the leading part as the platform id.
1842 # fwid generally follow the format of {platform}.{firmware version}
1843 # Example: Alex.X.YYY.Z or Google_Alex.X.YYY.Z
1844 platform = crossystem.fwid().split('.')[0].lower()
1845 # Newer platforms start with 'Google_' while the older ones do not.
1846 return platform.replace('google_', '')
1847
Puthikorn Voravootivat0f7c3d82019-11-27 13:48:39 -08001848
Simran Basic6f1f7a2012-10-16 10:47:46 -07001849 def get_platform(self):
1850 """Determine the correct platform label for this host.
1851
1852 @returns a string representing this host's platform.
1853 """
C Shapiroed87c6f2018-04-19 09:13:58 -06001854 release_info = utils.parse_cmd_output('cat /etc/lsb-release',
1855 run_method=self.run)
C Shapiroed87c6f2018-04-19 09:13:58 -06001856 platform = ''
Puthikorn Voravootivat0f7c3d82019-11-27 13:48:39 -08001857 if release_info.get('CHROMEOS_RELEASE_UNIBUILD') == '1':
1858 platform = self.get_platform_from_mosys()
Mary Ruthvende14a8b2019-08-23 12:43:52 -07001859 return platform if platform else self.get_platform_from_fwid()
Simran Basic6f1f7a2012-10-16 10:47:46 -07001860
1861
Puthikorn Voravootivat0f7c3d82019-11-27 13:48:39 -08001862 def get_platform_from_mosys(self):
1863 """Get the host platform from mosys command.
1864
1865 @returns a string representing this host's platform.
1866 """
1867 cmd = 'mosys platform model'
1868 result = self.run(command=cmd, ignore_status=True)
1869 return result.stdout.strip() if result.exit_status == 0 else ''
1870
1871
Hung-ying Tyanb1328032014-04-01 14:18:54 +08001872 def get_architecture(self):
1873 """Determine the correct architecture label for this host.
1874
1875 @returns a string representing this host's architecture.
1876 """
1877 crossystem = utils.Crossystem(self)
1878 crossystem.init()
1879 return crossystem.arch()
1880
1881
Luis Lozano40b7d0d2014-01-17 15:12:06 -08001882 def get_chrome_version(self):
1883 """Gets the Chrome version number and milestone as strings.
1884
1885 Invokes "chrome --version" to get the version number and milestone.
1886
1887 @return A tuple (chrome_ver, milestone) where "chrome_ver" is the
1888 current Chrome version number as a string (in the form "W.X.Y.Z")
1889 and "milestone" is the first component of the version number
1890 (the "W" from "W.X.Y.Z"). If the version number cannot be parsed
1891 in the "W.X.Y.Z" format, the "chrome_ver" will be the full output
1892 of "chrome --version" and the milestone will be the empty string.
1893
1894 """
MK Ryu35d661e2014-09-25 17:44:10 -07001895 version_string = self.run(client_constants.CHROME_VERSION_COMMAND).stdout
Luis Lozano40b7d0d2014-01-17 15:12:06 -08001896 return utils.parse_chrome_version(version_string)
1897
J. Richard Barnetted2af5852016-02-05 15:03:10 -08001898
Puthikorn Voravootivatfd132172017-11-16 18:24:38 -08001899 def get_ec_version(self):
1900 """Get the ec version as strings.
1901
1902 @returns a string representing this host's ec version.
1903 """
Puthikorn Voravootivat65ad7672018-01-30 14:00:01 -08001904 command = 'mosys ec info -s fw_version'
Puthikorn Voravootivat720640d2018-02-16 17:32:38 -08001905 result = self.run(command, ignore_status=True)
1906 if result.exit_status != 0:
1907 return ''
1908 return result.stdout.strip()
Puthikorn Voravootivatfd132172017-11-16 18:24:38 -08001909
1910
1911 def get_firmware_version(self):
1912 """Get the firmware version as strings.
1913
1914 @returns a string representing this host's firmware version.
1915 """
1916 crossystem = utils.Crossystem(self)
1917 crossystem.init()
1918 return crossystem.fwid()
1919
1920
1921 def get_hardware_revision(self):
1922 """Get the hardware revision as strings.
1923
1924 @returns a string representing this host's hardware revision.
1925 """
Puthikorn Voravootivat65ad7672018-01-30 14:00:01 -08001926 command = 'mosys platform version'
Puthikorn Voravootivat720640d2018-02-16 17:32:38 -08001927 result = self.run(command, ignore_status=True)
1928 if result.exit_status != 0:
1929 return ''
1930 return result.stdout.strip()
Puthikorn Voravootivatfd132172017-11-16 18:24:38 -08001931
1932
1933 def get_kernel_version(self):
1934 """Get the kernel version as strings.
1935
1936 @returns a string representing this host's kernel version.
1937 """
1938 return self.run('uname -r').stdout.strip()
1939
1940
Puthikorn Voravootivat54aa53c2018-03-01 19:00:25 -08001941 def get_cpu_name(self):
1942 """Get the cpu name as strings.
1943
1944 @returns a string representing this host's cpu name.
1945 """
1946
1947 # Try get cpu name from device tree first
1948 if self.path_exists('/proc/device-tree/compatible'):
1949 command = ' | '.join(
1950 ["sed -e 's/\\x0/\\n/g' /proc/device-tree/compatible",
1951 'tail -1'])
1952 return self.run(command).stdout.strip().replace(',', ' ')
1953
1954 # Get cpu name from uname -p
1955 command = 'uname -p'
1956 ret = self.run(command).stdout.strip()
1957
1958 # 'uname -p' return variant of unknown or amd64 or x86_64 or i686
1959 # Try get cpu name from /proc/cpuinfo instead
1960 if re.match("unknown|amd64|[ix][0-9]?86(_64)?", ret, re.IGNORECASE):
1961 command = "grep model.name /proc/cpuinfo | cut -f 2 -d: | head -1"
1962 self = self.run(command).stdout.strip()
1963
1964 # Remove bloat from CPU name, for example
1965 # Intel(R) Core(TM) i5-7Y57 CPU @ 1.20GHz -> Intel Core i5-7Y57
1966 # Intel(R) Xeon(R) CPU E5-2690 v4 @ 2.60GHz -> Intel Xeon E5-2690 v4
1967 # AMD A10-7850K APU with Radeon(TM) R7 Graphics -> AMD A10-7850K
1968 # AMD GX-212JC SOC with Radeon(TM) R2E Graphics -> AMD GX-212JC
1969 trim_re = r' (@|processor|apu|soc|radeon).*|\(.*?\)| cpu'
1970 return re.sub(trim_re, '', ret, flags=re.IGNORECASE)
1971
1972
1973 def get_screen_resolution(self):
1974 """Get the screen(s) resolution as strings.
1975 In case of more than 1 monitor, return resolution for each monitor
1976 separate with plus sign.
1977
1978 @returns a string representing this host's screen(s) resolution.
1979 """
1980 command = 'for f in /sys/class/drm/*/*/modes; do head -1 $f; done'
1981 ret = self.run(command, ignore_status=True)
1982 # We might have Chromebox without a screen
1983 if ret.exit_status != 0:
1984 return ''
1985 return ret.stdout.strip().replace('\n', '+')
1986
1987
1988 def get_mem_total_gb(self):
1989 """Get total memory available in the system in GiB (2^20).
1990
1991 @returns an integer representing total memory
1992 """
1993 mem_total_kb = self.read_from_meminfo('MemTotal')
1994 kb_in_gb = float(2 ** 20)
1995 return int(round(mem_total_kb / kb_in_gb))
1996
1997
1998 def get_disk_size_gb(self):
1999 """Get size of disk in GB (10^9)
2000
2001 @returns an integer representing size of disk, 0 in Error Case
2002 """
2003 command = 'grep $(rootdev -s -d | cut -f3 -d/)$ /proc/partitions'
2004 result = self.run(command, ignore_status=True)
2005 if result.exit_status != 0:
2006 return 0
2007 _, _, block, _ = re.split(r' +', result.stdout.strip())
2008 byte_per_block = 1024.0
2009 disk_kb_in_gb = 1e9
2010 return int(int(block) * byte_per_block / disk_kb_in_gb + 0.5)
2011
2012
2013 def get_battery_size(self):
2014 """Get size of battery in Watt-hour via sysfs
2015
2016 This method assumes that battery support voltage_min_design and
2017 charge_full_design sysfs.
2018
2019 @returns a float representing Battery size, 0 if error.
2020 """
2021 # sysfs report data in micro scale
2022 battery_scale = 1e6
2023
2024 command = 'cat /sys/class/power_supply/*/voltage_min_design'
2025 result = self.run(command, ignore_status=True)
2026 if result.exit_status != 0:
2027 return 0
2028 voltage = float(result.stdout.strip()) / battery_scale
2029
2030 command = 'cat /sys/class/power_supply/*/charge_full_design'
2031 result = self.run(command, ignore_status=True)
2032 if result.exit_status != 0:
2033 return 0
2034 amphereHour = float(result.stdout.strip()) / battery_scale
2035
2036 return voltage * amphereHour
2037
2038
2039 def get_low_battery_shutdown_percent(self):
2040 """Get the percent-based low-battery shutdown threshold.
2041
2042 @returns a float representing low-battery shutdown percent, 0 if error.
2043 """
2044 ret = 0.0
2045 try:
2046 command = 'check_powerd_config --low_battery_shutdown_percent'
2047 ret = float(self.run(command).stdout)
2048 except error.CmdError:
2049 logging.debug("Can't run %s", command)
2050 except ValueError:
2051 logging.debug("Didn't get number from %s", command)
2052
2053 return ret
2054
2055
Puthikorn Voravootivat09c83d72018-08-10 15:58:32 -07002056 def has_hammer(self):
2057 """Check whether DUT has hammer device or not.
2058
2059 @returns boolean whether device has hammer or not
2060 """
2061 command = 'grep Hammer /sys/bus/usb/devices/*/product'
2062 return self.run(command, ignore_status=True).exit_status == 0
2063
2064
Niranjan Kumar34618872017-05-31 12:57:09 -07002065 def is_chrome_switch_present(self, switch):
David Haddock3ce538e2017-06-22 13:37:05 -07002066 """Returns True if the specified switch was provided to Chrome.
2067
2068 @param switch The chrome switch to search for.
2069 """
Niranjan Kumar34618872017-05-31 12:57:09 -07002070
Niranjan Kumar5f23fe92017-06-22 15:18:55 -07002071 command = 'pgrep -x -f -c "/opt/google/chrome/chrome.*%s.*"' % switch
2072 return self.run(command, ignore_status=True).exit_status == 0
Niranjan Kumar34618872017-05-31 12:57:09 -07002073
2074
2075 def oobe_triggers_update(self):
2076 """Returns True if this host has an OOBE flow during which
2077 it will perform an update check and perhaps an update.
2078 One example of such a flow is Hands-Off Zero-Touch Enrollment.
2079 As more such flows are developed, code handling them needs
2080 to be added here.
2081
2082 @return Boolean indicating whether this host's OOBE triggers an update.
2083 """
2084 return self.is_chrome_switch_present(
2085 '--enterprise-enable-zero-touch-enrollment=hands-off')
2086
2087
Kevin Chenga2619dc2016-03-28 11:42:08 -07002088 # TODO(kevcheng): change this to just return the board without the
2089 # 'board:' prefix and fix up all the callers. Also look into removing the
2090 # need for this method.
Simran Basic6f1f7a2012-10-16 10:47:46 -07002091 def get_board(self):
2092 """Determine the correct board label for this host.
2093
2094 @returns a string representing this host's board.
2095 """
2096 release_info = utils.parse_cmd_output('cat /etc/lsb-release',
2097 run_method=self.run)
J. Richard Barnetted2af5852016-02-05 15:03:10 -08002098 return (ds_constants.BOARD_PREFIX +
2099 release_info['CHROMEOS_RELEASE_BOARD'])
Simran Basic6f1f7a2012-10-16 10:47:46 -07002100
Po-Hsien Wang4618adf2017-10-10 14:40:21 -07002101 def get_channel(self):
2102 """Determine the correct channel label for this host.
Simran Basic6f1f7a2012-10-16 10:47:46 -07002103
Po-Hsien Wang4618adf2017-10-10 14:40:21 -07002104 @returns: a string represeting this host's build channel.
2105 (stable, dev, beta). None on fail.
2106 """
2107 return lsbrelease_utils.get_chromeos_channel(
2108 lsb_release_content=self._get_lsb_release_content())
Kevin Chenga328da62016-03-31 10:49:04 -07002109
Kevin Chenga328da62016-03-31 10:49:04 -07002110 def get_power_supply(self):
2111 """
2112 Determine what type of power supply the host has
2113
2114 @returns a string representing this host's power supply.
2115 'power:battery' when the device has a battery intended for
2116 extended use
2117 'power:AC_primary' when the device has a battery not intended
2118 for extended use (for moving the machine, etc)
2119 'power:AC_only' when the device has no battery at all.
2120 """
2121 psu = self.run(command='mosys psu type', ignore_status=True)
2122 if psu.exit_status:
2123 # The psu command for mosys is not included for all platforms. The
2124 # assumption is that the device will have a battery if the command
2125 # is not found.
2126 return 'power:battery'
2127
2128 psu_str = psu.stdout.strip()
2129 if psu_str == 'unknown':
2130 return None
2131
2132 return 'power:%s' % psu_str
2133
2134
Puthikorn Voravootivat54aa53c2018-03-01 19:00:25 -08002135 def has_battery(self):
2136 """Determine if DUT has a battery.
2137
2138 Returns:
2139 Boolean, False if known not to have battery, True otherwise.
2140 """
2141 rv = True
2142 power_supply = self.get_power_supply()
2143 if power_supply == 'power:battery':
2144 _NO_BATTERY_BOARD_TYPE = ['CHROMEBOX', 'CHROMEBIT', 'CHROMEBASE']
2145 board_type = self.get_board_type()
2146 if board_type in _NO_BATTERY_BOARD_TYPE:
2147 logging.warn('Do NOT believe type %s has battery. '
2148 'See debug for mosys details', board_type)
2149 psu = self.system_output('mosys -vvvv psu type',
2150 ignore_status=True)
2151 logging.debug(psu)
2152 rv = False
2153 elif power_supply == 'power:AC_only':
2154 rv = False
2155
2156 return rv
2157
2158
Kevin Chenga328da62016-03-31 10:49:04 -07002159 def get_servo(self):
2160 """Determine if the host has a servo attached.
2161
2162 If the host has a working servo attached, it should have a servo label.
2163
2164 @return: string 'servo' if the host has servo attached. Otherwise,
2165 returns None.
2166 """
2167 return 'servo' if self._servo_host else None
2168
2169
Kevin Chenga328da62016-03-31 10:49:04 -07002170 def has_internal_display(self):
2171 """Determine if the device under test is equipped with an internal
2172 display.
2173
2174 @return: 'internal_display' if one is present; None otherwise.
2175 """
2176 from autotest_lib.client.cros.graphics import graphics_utils
2177 from autotest_lib.client.common_lib import utils as common_utils
2178
2179 def __system_output(cmd):
2180 return self.run(cmd).stdout
2181
2182 def __read_file(remote_path):
2183 return self.run('cat %s' % remote_path).stdout
2184
2185 # Hijack the necessary client functions so that we can take advantage
2186 # of the client lib here.
2187 # FIXME: find a less hacky way than this
2188 original_system_output = utils.system_output
2189 original_read_file = common_utils.read_file
2190 utils.system_output = __system_output
2191 common_utils.read_file = __read_file
2192 try:
2193 return ('internal_display' if graphics_utils.has_internal_display()
2194 else None)
2195 finally:
2196 utils.system_output = original_system_output
2197 common_utils.read_file = original_read_file
2198
2199
Dan Shi85276d42014-04-08 22:11:45 -07002200 def is_boot_from_usb(self):
2201 """Check if DUT is boot from USB.
2202
2203 @return: True if DUT is boot from usb.
2204 """
2205 device = self.run('rootdev -s -d').stdout.strip()
2206 removable = int(self.run('cat /sys/block/%s/removable' %
2207 os.path.basename(device)).stdout.strip())
2208 return removable == 1
Helen Zhang17dae2b2014-11-11 09:25:52 -08002209
2210
2211 def read_from_meminfo(self, key):
Dan Shi49ca0932014-11-14 11:22:27 -08002212 """Return the memory info from /proc/meminfo
Helen Zhang17dae2b2014-11-11 09:25:52 -08002213
2214 @param key: meminfo requested
2215
2216 @return the memory value as a string
2217
2218 """
Helen Zhang17dae2b2014-11-11 09:25:52 -08002219 meminfo = self.run('grep %s /proc/meminfo' % key).stdout.strip()
2220 logging.debug('%s', meminfo)
2221 return int(re.search(r'\d+', meminfo).group(0))
Rohit Makasana8a4923c2015-08-13 17:04:26 -07002222
2223
Rohit Makasana98e696f2016-06-03 18:48:10 -07002224 def get_cpu_arch(self):
2225 """Returns CPU arch of the device.
2226
2227 @return CPU architecture of the DUT.
2228 """
Allen Li2c32d6b2017-02-03 15:28:10 -08002229 # Add CPUs by following logic in client/bin/utils.py.
Rohit Makasana98e696f2016-06-03 18:48:10 -07002230 if self.run("grep '^flags.*:.* lm .*' /proc/cpuinfo",
2231 ignore_status=True).stdout:
2232 return 'x86_64'
2233 if self.run("grep -Ei 'ARM|CPU implementer' /proc/cpuinfo",
2234 ignore_status=True).stdout:
2235 return 'arm'
2236 return 'i386'
2237
2238
Rohit Makasana8a4923c2015-08-13 17:04:26 -07002239 def get_board_type(self):
2240 """
2241 Get the DUT's device type from /etc/lsb-release.
Danny Chan471a8d12015-08-18 14:57:41 -07002242 DEVICETYPE can be one of CHROMEBOX, CHROMEBASE, CHROMEBOOK or more.
2243
2244 @return value of DEVICETYPE param from lsb-release.
Rohit Makasana8a4923c2015-08-13 17:04:26 -07002245 """
Danny Chan471a8d12015-08-18 14:57:41 -07002246 device_type = self.run('grep DEVICETYPE /etc/lsb-release',
2247 ignore_status=True).stdout
2248 if device_type:
Kalin Stoyanov524310b2015-08-21 16:24:04 -07002249 return device_type.split('=')[-1].strip()
Danny Chan471a8d12015-08-18 14:57:41 -07002250 return ''
Gilad Arnolda76bef02015-09-29 13:55:15 -07002251
2252
Rohit Makasanadf0a3a32017-06-30 13:55:18 -07002253 def get_arc_version(self):
2254 """Return ARC version installed on the DUT.
2255
2256 @returns ARC version as string if the CrOS build has ARC, else None.
2257 """
2258 arc_version = self.run('grep CHROMEOS_ARC_VERSION /etc/lsb-release',
2259 ignore_status=True).stdout
2260 if arc_version:
2261 return arc_version.split('=')[-1].strip()
2262 return None
2263
2264
Gilad Arnolda76bef02015-09-29 13:55:15 -07002265 def get_os_type(self):
2266 return 'cros'
Simran Basia5522a32015-10-06 11:01:24 -07002267
2268
Kevin Chenga2619dc2016-03-28 11:42:08 -07002269 def get_labels(self):
Kevin Chengf8660142016-08-12 10:17:41 -07002270 """Return the detected labels on the host."""
Kevin Chenga2619dc2016-03-28 11:42:08 -07002271 return self.labels.get_labels(self)
Garry Wang5e5538a2019-04-08 15:36:18 -07002272
2273
2274 def get_default_power_method(self):
2275 """
2276 Get the default power method for power_on/off/cycle() methods.
2277 @return POWER_CONTROL_RPM or POWER_CONTROL_CCD
2278 """
2279 if not self._default_power_method:
Garry Wang1a004aa2019-05-16 22:56:51 -07002280 self._default_power_method = self.POWER_CONTROL_RPM
Ruben Rodriguez Buchillon3eeeab32019-10-02 15:29:58 -07002281 if self.servo and self.servo.supports_built_in_pd_control():
2282 self._default_power_method = self.POWER_CONTROL_CCD
2283 else:
2284 logging.debug('Either servo is unitialized or the servo '
2285 'setup does not support pd controls. Falling '
2286 'back to default RPM method.')
Garry Wang5e5538a2019-04-08 15:36:18 -07002287 return self._default_power_method
Puthikorn Voravootivat4a054792019-12-13 16:44:17 -08002288
2289
2290 def find_usb_devices(self, idVendor, idProduct):
2291 """
2292 Get usb device sysfs name for specific device.
2293
2294 @param idVendor Vendor ID to search in sysfs directory.
2295 @param idProduct Product ID to search in sysfs directory.
2296
2297 @return Usb node names in /sys/bus/usb/drivers/usb/ that match.
2298 """
2299 # Look for matching file and cut at position 7 to get dir name.
2300 grep_cmd = 'grep {} /sys/bus/usb/drivers/usb/*/{} | cut -f 7 -d /'
2301
2302 vendor_cmd = grep_cmd.format(idVendor, 'idVendor')
2303 product_cmd = grep_cmd.format(idProduct, 'idProduct')
2304
2305 # Use uniq -d to print duplicate line from both command
2306 cmd = 'sort <({}) <({}) | uniq -d'.format(vendor_cmd, product_cmd)
2307
2308 return self.run(cmd, ignore_status=True).stdout.strip().split('\n')
2309
2310
2311 def bind_usb_device(self, usb_node):
2312 """
2313 Bind usb device
2314
2315 @param usb_node Node name in /sys/bus/usb/drivers/usb/
2316 """
2317 cmd = 'echo {} > /sys/bus/usb/drivers/usb/bind'.format(usb_node)
2318 self.run(cmd, ignore_status=True)
2319
2320
2321 def unbind_usb_device(self, usb_node):
2322 """
2323 Unbind usb device
2324
2325 @param usb_node Node name in /sys/bus/usb/drivers/usb/
2326 """
2327 cmd = 'echo {} > /sys/bus/usb/drivers/usb/unbind'.format(usb_node)
2328 self.run(cmd, ignore_status=True)
2329
2330
2331 def get_wlan_ip(self):
2332 """
2333 Get ip address of wlan interface.
2334
2335 @return ip address of wlan or empty string if wlan is not connected.
2336 """
2337 cmds = [
2338 'iw dev', # List wlan physical device
2339 'grep Interface', # Grep only interface name
2340 'cut -f 2 -d" "', # Cut the name part
2341 'xargs ifconfig', # Feed it to ifconfig to get ip
2342 'grep -oE "inet [0-9.]+"', # Grep only ipv4
2343 'cut -f 2 -d " "' # Cut the ip part
2344 ]
2345 return self.run(' | '.join(cmds), ignore_status=True).stdout.strip()
Puthikorn Voravootivatcd0dc9e2020-01-22 14:22:22 -08002346
2347 def connect_to_wifi(self, ssid, passphrase=None, security=None):
2348 """
2349 Connect to wifi network
2350
2351 @param ssid SSID of the wifi network.
2352 @param passphrase Passphrase of the wifi network. None if not existed.
2353 @param security Security of the wifi network. Default to "psk" if
2354 passphase is given without security. Possible values
2355 are "none", "psk", "802_1x".
2356
2357 @return True if succeed, False if not.
2358 """
2359 cmd = '/usr/local/autotest/cros/scripts/wifi connect ' + ssid
2360 if passphrase:
2361 cmd += ' ' + passphrase
2362 if security:
2363 cmd += ' ' + security
2364 return self.run(cmd, ignore_status=True).exit_status == 0