blob: fe55e5f4cc6095e58f20c93fef8fa335d2ba88e7 [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
J. Richard Barnette964fba02012-10-24 17:34:29 -0700153 @staticmethod
beeps46dadc92013-11-07 14:07:10 -0800154 def check_host(host, timeout=10):
155 """
156 Check if the given host is a chrome-os host.
157
158 @param host: An ssh host representing a device.
159 @param timeout: The timeout for the run command.
160
161 @return: True if the host device is chromeos.
162
beeps46dadc92013-11-07 14:07:10 -0800163 """
164 try:
Allen Liad719c12017-06-27 23:48:04 +0000165 result = host.run(
Simran Basi933c8af2015-04-29 14:05:07 -0700166 'grep -q CHROMEOS /etc/lsb-release && '
Garry Wange4b6d6e2019-06-17 17:08:46 -0700167 '! grep -q moblab /etc/lsb-release && '
168 '! grep -q labstation /etc/lsb-release',
Simran Basi933c8af2015-04-29 14:05:07 -0700169 ignore_status=True, timeout=timeout)
Laurence Goodby468de252017-06-08 17:22:53 -0700170 if result.exit_status == 0:
Allen Liad719c12017-06-27 23:48:04 +0000171 lsb_release_content = host.run(
Laurence Goodby468de252017-06-08 17:22:53 -0700172 'grep CHROMEOS_RELEASE_BOARD /etc/lsb-release',
173 timeout=timeout).stdout
Pradeep Sawlaniaa013fa2017-11-09 06:34:18 -0800174 return not (
175 lsbrelease_utils.is_jetstream(
176 lsb_release_content=lsb_release_content) or
177 lsbrelease_utils.is_gce_board(
178 lsb_release_content=lsb_release_content))
179
beeps46dadc92013-11-07 14:07:10 -0800180 except (error.AutoservRunError, error.AutoservSSHTimeout):
181 return False
Laurence Goodby468de252017-06-08 17:22:53 -0700182
183 return False
beeps46dadc92013-11-07 14:07:10 -0800184
185
186 @staticmethod
Tom Wai-Hong Tamefe1c7f2014-01-02 14:00:11 +0800187 def get_chameleon_arguments(args_dict):
188 """Extract chameleon options from `args_dict` and return the result.
189
190 Recommended usage:
191 ~~~~~~~~
192 args_dict = utils.args_to_dict(args)
193 chameleon_args = hosts.CrosHost.get_chameleon_arguments(args_dict)
194 host = hosts.create_host(machine, chameleon_args=chameleon_args)
195 ~~~~~~~~
196
197 @param args_dict Dictionary from which to extract the chameleon
198 arguments.
199 """
howardchung83e55272019-08-08 14:08:05 +0800200 if 'chameleon_host_list' in args_dict:
201 result = []
202 for chameleon in args_dict['chameleon_host_list'].split(','):
203 result.append({key: value for key,value in
204 zip(('chameleon_host','chameleon_port'),
205 chameleon.split(':'))})
206
207 logging.info(result)
208 return result
209 else:
210 return {key: args_dict[key]
Allen Li083866b2016-08-18 10:07:10 -0700211 for key in ('chameleon_host', 'chameleon_port')
212 if key in args_dict}
Tom Wai-Hong Tamefe1c7f2014-01-02 14:00:11 +0800213
214
215 @staticmethod
Wai-Hong Tam0ed9fe12019-05-23 11:00:58 -0700216 def get_pdtester_arguments(args_dict):
Scottfe06ed82015-11-05 17:15:01 -0800217 """Extract chameleon options from `args_dict` and return the result.
218
219 Recommended usage:
220 ~~~~~~~~
221 args_dict = utils.args_to_dict(args)
Wai-Hong Tam0ed9fe12019-05-23 11:00:58 -0700222 pdtester_args = hosts.CrosHost.get_pdtester_arguments(args_dict)
223 host = hosts.create_host(machine, pdtester_args=pdtester_args)
Scottfe06ed82015-11-05 17:15:01 -0800224 ~~~~~~~~
225
Wai-Hong Tam0ed9fe12019-05-23 11:00:58 -0700226 @param args_dict Dictionary from which to extract the pdtester
Scottfe06ed82015-11-05 17:15:01 -0800227 arguments.
228 """
Allen Li083866b2016-08-18 10:07:10 -0700229 return {key: args_dict[key]
Wai-Hong Tam0ed9fe12019-05-23 11:00:58 -0700230 for key in ('pdtester_host', 'pdtester_port')
Allen Li083866b2016-08-18 10:07:10 -0700231 if key in args_dict}
Scottfe06ed82015-11-05 17:15:01 -0800232
233
234 @staticmethod
Tom Wai-Hong Tamefe1c7f2014-01-02 14:00:11 +0800235 def get_servo_arguments(args_dict):
236 """Extract servo options from `args_dict` and return the result.
J. Richard Barnette7214e0b2013-02-06 15:20:49 -0800237
238 Recommended usage:
239 ~~~~~~~~
240 args_dict = utils.args_to_dict(args)
Fang Deng0ca40e22013-08-27 17:47:44 -0700241 servo_args = hosts.CrosHost.get_servo_arguments(args_dict)
J. Richard Barnette7214e0b2013-02-06 15:20:49 -0800242 host = hosts.create_host(machine, servo_args=servo_args)
243 ~~~~~~~~
244
245 @param args_dict Dictionary from which to extract the servo
246 arguments.
247 """
Richard Barnettee519dcd2016-08-15 17:37:17 -0700248 servo_attrs = (servo_host.SERVO_HOST_ATTR,
249 servo_host.SERVO_PORT_ATTR,
Nick Sanders2f3c9852018-10-24 12:10:24 -0700250 servo_host.SERVO_BOARD_ATTR,
251 servo_host.SERVO_MODEL_ATTR)
Armando Miraglia2ac802e2017-08-15 14:54:47 +0200252 servo_args = {key: args_dict[key]
253 for key in servo_attrs
254 if key in args_dict}
255 return (
256 None
257 if servo_host.SERVO_HOST_ATTR in servo_args
258 and not servo_args[servo_host.SERVO_HOST_ATTR]
259 else servo_args)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -0700260
J. Richard Barnette964fba02012-10-24 17:34:29 -0700261
J. Richard Barnette91137f02016-03-10 16:52:26 -0800262 def _initialize(self, hostname, chameleon_args=None, servo_args=None,
Wai-Hong Tam0ed9fe12019-05-23 11:00:58 -0700263 pdtester_args=None, try_lab_servo=False,
Richard Barnette9a26ad62016-06-10 12:03:08 -0700264 try_servo_repair=False,
J. Richard Barnette91137f02016-03-10 16:52:26 -0800265 ssh_verbosity_flag='', ssh_options='',
Fang Dengd1c2b732013-08-20 12:59:46 -0700266 *args, **dargs):
Tom Wai-Hong Tamefe1c7f2014-01-02 14:00:11 +0800267 """Initialize superclasses, |self.chameleon|, and |self.servo|.
J. Richard Barnette67ccb872012-04-19 16:34:56 -0700268
Fang Denge545abb2014-12-30 18:43:47 -0800269 This method will attempt to create the test-assistant object
270 (chameleon/servo) when it is needed by the test. Check
271 the docstring of chameleon_host.create_chameleon_host and
272 servo_host.create_servo_host for how this is determined.
Fang Deng5d518f42013-08-02 14:04:32 -0700273
Fang Denge545abb2014-12-30 18:43:47 -0800274 @param hostname: Hostname of the dut.
275 @param chameleon_args: A dictionary that contains args for creating
276 a ChameleonHost. See chameleon_host for details.
277 @param servo_args: A dictionary that contains args for creating
278 a ServoHost object. See servo_host for details.
Richard Barnette9a26ad62016-06-10 12:03:08 -0700279 @param try_lab_servo: When true, indicates that an attempt should
280 be made to create a ServoHost for a DUT in
281 the test lab, even if not required by
282 `servo_args`. See servo_host for details.
283 @param try_servo_repair: If a servo host is created, check it
284 with `repair()` rather than `verify()`.
Fang Denge545abb2014-12-30 18:43:47 -0800285 See servo_host for details.
286 @param ssh_verbosity_flag: String, to pass to the ssh command to control
287 verbosity.
288 @param ssh_options: String, other ssh options to pass to the ssh
289 command.
J. Richard Barnette67ccb872012-04-19 16:34:56 -0700290 """
Fang Deng0ca40e22013-08-27 17:47:44 -0700291 super(CrosHost, self)._initialize(hostname=hostname,
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700292 *args, **dargs)
J. Richard Barnette91137f02016-03-10 16:52:26 -0800293 self._repair_strategy = cros_repair.create_cros_repair_strategy()
Kevin Chenga2619dc2016-03-28 11:42:08 -0700294 self.labels = base_label.LabelRetriever(cros_label.CROS_LABELS)
J. Richard Barnettef0859852012-08-20 14:55:50 -0700295 # self.env is a dictionary of environment variable settings
296 # to be exported for commands run on the host.
297 # LIBC_FATAL_STDERR_ can be useful for diagnosing certain
298 # errors that might happen.
299 self.env['LIBC_FATAL_STDERR_'] = '1'
Fang Dengd1c2b732013-08-20 12:59:46 -0700300 self._ssh_verbosity_flag = ssh_verbosity_flag
Aviv Keshetc5947fa2013-09-04 14:06:29 -0700301 self._ssh_options = ssh_options
Richard Barnette4aeb01c2018-09-20 09:36:12 -0700302 self.set_servo_host(
303 servo_host.create_servo_host(
Richard Barnetteea3e4602016-06-10 12:36:41 -0700304 dut=self, servo_args=servo_args,
Richard Barnette9a26ad62016-06-10 12:03:08 -0700305 try_lab_servo=try_lab_servo,
Richard Barnette4aeb01c2018-09-20 09:36:12 -0700306 try_servo_repair=try_servo_repair))
Garry Wang5e5538a2019-04-08 15:36:18 -0700307 self._default_power_method = None
Richard Barnettee519dcd2016-08-15 17:37:17 -0700308
Tom Wai-Hong Tamefe1c7f2014-01-02 14:00:11 +0800309 # TODO(waihong): Do the simplication on Chameleon too.
howardchung83e55272019-08-08 14:08:05 +0800310 if type(chameleon_args) is list:
311 self.multi_chameleon = True
312 chameleon_args_list = chameleon_args
313 else:
314 self.multi_chameleon = False
315 chameleon_args_list = [chameleon_args]
Tom Wai-Hong Tam3d6790d2014-04-14 16:15:47 +0800316
howardchung83e55272019-08-08 14:08:05 +0800317 self._chameleon_host_list = [
318 chameleon_host.create_chameleon_host(
319 dut=self.hostname, chameleon_args=_args)
320 for _args in chameleon_args_list]
321
322 self.chameleon_list = [_host.create_chameleon_board() for _host in
323 self._chameleon_host_list if _host is not None]
324 if len(self.chameleon_list) > 0:
325 self.chameleon = self.chameleon_list[0]
Tom Wai-Hong Tamefe1c7f2014-01-02 14:00:11 +0800326 else:
Tom Wai-Hong Tam3d6790d2014-04-14 16:15:47 +0800327 self.chameleon = None
Fang Deng5d518f42013-08-02 14:04:32 -0700328
howardchung83e55272019-08-08 14:08:05 +0800329 # Add pdtester host if pdtester args were added on command line
Wai-Hong Tam16e5edb2019-09-17 16:10:07 -0700330 self._pdtester_host = pdtester_host.create_pdtester_host(
Wai-Hong Tam90b164d2019-10-25 13:15:39 -0700331 pdtester_args, self._servo_host)
howardchung83e55272019-08-08 14:08:05 +0800332
Wai-Hong Tam0ed9fe12019-05-23 11:00:58 -0700333 if self._pdtester_host:
334 self.pdtester_servo = self._pdtester_host.get_servo()
335 logging.info('pdtester_servo: %r', self.pdtester_servo)
336 # Create the pdtester object used to access the ec uart
337 self.pdtester = pdtester.PDTester(self.pdtester_servo,
338 self._pdtester_host.get_servod_server_proxy())
Scottfe06ed82015-11-05 17:15:01 -0800339 else:
Wai-Hong Tam0ed9fe12019-05-23 11:00:58 -0700340 self.pdtester = None
Scottfe06ed82015-11-05 17:15:01 -0800341
Fang Deng5d518f42013-08-02 14:04:32 -0700342
Richard Barnetteb4b4d6f2018-05-05 01:47:41 +0000343 def get_cros_repair_image_name(self):
Ruben Rodriguez Buchilloncee72f72019-05-01 13:20:58 -0700344 """Get latest stable cros image name from AFE.
345
346 Use the board name from the info store. Should that fail, try to
347 retrieve the board name from the host's installed image itself.
348
349 @returns: current stable cros image name for this host.
350 """
351 board = self.host_info_store.get().board
352 if not board:
353 logging.warn('No board label value found. Trying to infer '
354 'from the host itself.')
355 try:
356 board = self.get_board().split(':')[1]
357 except (error.AutoservRunError, error.AutoservSSHTimeout) as e:
358 logging.error('Also failed to get the board name from the DUT '
359 'itself. %s.', str(e))
360 raise error.AutoservError('Cannot obtain repair image name.')
361 return afe_utils.get_stable_cros_image_name(board)
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500362
363
Rohit Makasanadf0a3a32017-06-30 13:55:18 -0700364 def host_version_prefix(self, image):
365 """Return version label prefix.
366
367 In case the CrOS provisioning version is something other than the
368 standard CrOS version e.g. CrOS TH version, this function will
369 find the prefix from provision.py.
370
371 @param image: The image name to find its version prefix.
372 @returns: A prefix string for the image type.
373 """
374 return provision.get_version_label_prefix(image)
375
376
beepsdae65fd2013-07-26 16:24:41 -0700377 def verify_job_repo_url(self, tag=''):
beepscb6f1e22013-06-28 19:14:10 -0700378 """
379 Make sure job_repo_url of this host is valid.
380
joychen03eaad92013-06-26 09:55:21 -0700381 Eg: The job_repo_url "http://lmn.cd.ab.xyx:8080/static/\
beepscb6f1e22013-06-28 19:14:10 -0700382 lumpy-release/R29-4279.0.0/autotest/packages" claims to have the
383 autotest package for lumpy-release/R29-4279.0.0. If this isn't the case,
384 download and extract it. If the devserver embedded in the url is
385 unresponsive, update the job_repo_url of the host after staging it on
386 another devserver.
387
388 @param job_repo_url: A url pointing to the devserver where the autotest
389 package for this build should be staged.
beepsdae65fd2013-07-26 16:24:41 -0700390 @param tag: The tag from the server job, in the format
391 <job_id>-<user>/<hostname>, or <hostless> for a server job.
beepscb6f1e22013-06-28 19:14:10 -0700392
393 @raises DevServerException: If we could not resolve a devserver.
394 @raises AutoservError: If we're unable to save the new job_repo_url as
395 a result of choosing a new devserver because the old one failed to
396 respond to a health check.
beeps0c865032013-07-30 11:37:06 -0700397 @raises urllib2.URLError: If the devserver embedded in job_repo_url
398 doesn't respond within the timeout.
beepscb6f1e22013-06-28 19:14:10 -0700399 """
Prathmesh Prabhu368abdf2017-02-14 11:23:47 -0800400 info = self.host_info_store.get()
401 job_repo_url = info.attributes.get(ds_constants.JOB_REPO_URL, '')
beepscb6f1e22013-06-28 19:14:10 -0700402 if not job_repo_url:
403 logging.warning('No job repo url set on host %s', self.hostname)
404 return
405
406 logging.info('Verifying job repo url %s', job_repo_url)
407 devserver_url, image_name = tools.get_devserver_build_from_package_url(
408 job_repo_url)
409
beeps0c865032013-07-30 11:37:06 -0700410 ds = dev_server.ImageServer(devserver_url)
beepscb6f1e22013-06-28 19:14:10 -0700411
412 logging.info('Staging autotest artifacts for %s on devserver %s',
413 image_name, ds.url())
beeps687243d2013-07-18 15:29:27 -0700414
415 start_time = time.time()
Simran Basi25e7a922014-10-31 11:56:10 -0700416 ds.stage_artifacts(image_name, ['autotest_packages'])
beeps687243d2013-07-18 15:29:27 -0700417 stage_time = time.time() - start_time
418
419 # Record how much of the verification time comes from a devserver
420 # restage. If we're doing things right we should not see multiple
421 # devservers for a given board/build/branch path.
422 try:
J. Richard Barnette3cbd76b2013-11-27 12:11:25 -0800423 board, build_type, branch = server_utils.ParseBuildName(
beeps687243d2013-07-18 15:29:27 -0700424 image_name)[:3]
J. Richard Barnette3cbd76b2013-11-27 12:11:25 -0800425 except server_utils.ParseBuildNameException:
beeps687243d2013-07-18 15:29:27 -0700426 pass
427 else:
beeps0c865032013-07-30 11:37:06 -0700428 devserver = devserver_url[
Chris Sosa65425082013-10-16 13:26:22 -0700429 devserver_url.find('/') + 2:devserver_url.rfind(':')]
beeps687243d2013-07-18 15:29:27 -0700430 stats_key = {
431 'board': board,
432 'build_type': build_type,
433 'branch': branch,
beeps0c865032013-07-30 11:37:06 -0700434 'devserver': devserver.replace('.', '_'),
beeps687243d2013-07-18 15:29:27 -0700435 }
Dan Shi5e2efb72017-02-07 11:40:23 -0800436
437 monarch_fields = {
438 'board': board,
439 'build_type': build_type,
Dan Shi5e2efb72017-02-07 11:40:23 -0800440 'branch': branch,
441 'dev_server': devserver,
442 }
443 metrics.Counter(
444 'chromeos/autotest/provision/verify_url'
445 ).increment(fields=monarch_fields)
446 metrics.SecondsDistribution(
447 'chromeos/autotest/provision/verify_url_duration'
448 ).add(stage_time, fields=monarch_fields)
449
450
Dan Shicf4d2032015-03-12 15:04:21 -0700451 def stage_server_side_package(self, image=None):
452 """Stage autotest server-side package on devserver.
453
454 @param image: Full path of an OS image to install or a build name.
455
456 @return: A url to the autotest server-side package.
Dan Shi14de7622016-08-22 11:09:06 -0700457
458 @raise: error.AutoservError if fail to locate the build to test with, or
459 fail to stage server-side package.
Dan Shicf4d2032015-03-12 15:04:21 -0700460 """
Dan Shid37736b2016-07-06 15:10:29 -0700461 # If enable_drone_in_restricted_subnet is False, do not set hostname
462 # in devserver.resolve call, so a devserver in non-restricted subnet
463 # is picked to stage autotest server package for drone to download.
464 hostname = self.hostname
465 if not server_utils.ENABLE_DRONE_IN_RESTRICTED_SUBNET:
466 hostname = None
Dan Shicf4d2032015-03-12 15:04:21 -0700467 if image:
468 image_name = tools.get_build_from_image(image)
469 if not image_name:
470 raise error.AutoservError(
471 'Failed to parse build name from %s' % image)
Dan Shid37736b2016-07-06 15:10:29 -0700472 ds = dev_server.ImageServer.resolve(image_name, hostname)
Dan Shicf4d2032015-03-12 15:04:21 -0700473 else:
Prathmesh Prabhu9235e4c2017-03-28 13:16:06 -0700474 info = self.host_info_store.get()
Prathmesh Prabhu368abdf2017-02-14 11:23:47 -0800475 job_repo_url = info.attributes.get(ds_constants.JOB_REPO_URL, '')
Dan Shicf4d2032015-03-12 15:04:21 -0700476 if job_repo_url:
477 devserver_url, image_name = (
478 tools.get_devserver_build_from_package_url(job_repo_url))
Dan Shid37736b2016-07-06 15:10:29 -0700479 # If enable_drone_in_restricted_subnet is True, use the
480 # existing devserver. Otherwise, resolve a new one in
481 # non-restricted subnet.
482 if server_utils.ENABLE_DRONE_IN_RESTRICTED_SUBNET:
483 ds = dev_server.ImageServer(devserver_url)
484 else:
485 ds = dev_server.ImageServer.resolve(image_name)
Prathmesh Prabhub6cea612017-02-09 15:41:19 -0800486 elif info.build is not None:
487 ds = dev_server.ImageServer.resolve(info.build, hostname)
Prathmesh Prabhu0c1dd4d2017-06-07 13:01:53 -0700488 image_name = info.build
Dan Shicf4d2032015-03-12 15:04:21 -0700489 else:
Prathmesh Prabhub6cea612017-02-09 15:41:19 -0800490 raise error.AutoservError(
491 'Failed to stage server-side package. The host has '
Garry Wang12b9baf2019-06-24 18:58:54 -0700492 'no job_repo_url attribute or cros-version label.')
Dan Shica503482015-03-30 17:23:25 -0700493
494 # Get the OS version of the build, for any build older than
495 # MIN_VERSION_SUPPORT_SSP, server side packaging is not supported.
496 match = re.match('.*/R\d+-(\d+)\.', image_name)
497 if match and int(match.group(1)) < self.MIN_VERSION_SUPPORT_SSP:
Dan Shi14de7622016-08-22 11:09:06 -0700498 raise error.AutoservError(
499 'Build %s is older than %s. Server side packaging is '
500 'disabled.' % (image_name, self.MIN_VERSION_SUPPORT_SSP))
Dan Shica503482015-03-30 17:23:25 -0700501
Dan Shicf4d2032015-03-12 15:04:21 -0700502 ds.stage_artifacts(image_name, ['autotest_server_package'])
503 return '%s/static/%s/%s' % (ds.url(), image_name,
504 'autotest_server_package.tar.bz2')
505
506
Kalin Stoyanovb3c11f32018-05-11 09:02:00 -0700507 def stage_image_for_servo(self, image_name=None, artifact='test_image'):
J. Richard Barnettee4af8b92013-05-01 13:16:12 -0700508 """Stage a build on a devserver and return the update_url.
509
510 @param image_name: a name like lumpy-release/R27-3837.0.0
Kalin Stoyanovb3c11f32018-05-11 09:02:00 -0700511 @param artifact: a string like 'test_image'. Requests
512 appropriate image to be staged.
Xixuan Wufee57542019-10-15 11:50:27 -0700513 @returns a tuple of (image_name, URL) like
514 (lumpy-release/R27-3837.0.0,
515 http://172.22.50.205:8082/update/lumpy-release/R27-3837.0.0)
J. Richard Barnettee4af8b92013-05-01 13:16:12 -0700516 """
517 if not image_name:
Richard Barnetteb4b4d6f2018-05-05 01:47:41 +0000518 image_name = self.get_cros_repair_image_name()
J. Richard Barnettee4af8b92013-05-01 13:16:12 -0700519 logging.info('Staging build for servo install: %s', image_name)
Dan Shi216389c2015-12-22 11:03:06 -0800520 devserver = dev_server.ImageServer.resolve(image_name, self.hostname)
Kalin Stoyanovb3c11f32018-05-11 09:02:00 -0700521 devserver.stage_artifacts(image_name, [artifact])
522 if artifact == 'test_image':
Xixuan Wufee57542019-10-15 11:50:27 -0700523 return image_name, devserver.get_test_image_url(image_name)
Kalin Stoyanovb3c11f32018-05-11 09:02:00 -0700524 elif artifact == 'recovery_image':
Xixuan Wufee57542019-10-15 11:50:27 -0700525 return image_name, devserver.get_recovery_image_url(image_name)
Kalin Stoyanovb3c11f32018-05-11 09:02:00 -0700526 else:
527 raise error.AutoservError("Bad artifact!")
J. Richard Barnettee4af8b92013-05-01 13:16:12 -0700528
529
beepse539be02013-07-31 21:57:39 -0700530 def stage_factory_image_for_servo(self, image_name):
531 """Stage a build on a devserver and return the update_url.
532
533 @param image_name: a name like <baord>/4262.204.0
beeps12c0a3c2013-09-03 11:58:27 -0700534
beepse539be02013-07-31 21:57:39 -0700535 @return: An update URL, eg:
536 http://<devserver>/static/canary-channel/\
537 <board>/4262.204.0/factory_test/chromiumos_factory_image.bin
beeps12c0a3c2013-09-03 11:58:27 -0700538
539 @raises: ValueError if the factory artifact name is missing from
540 the config.
541
beepse539be02013-07-31 21:57:39 -0700542 """
543 if not image_name:
544 logging.error('Need an image_name to stage a factory image.')
545 return
546
Dan Shib8540a52015-07-16 14:18:23 -0700547 factory_artifact = CONFIG.get_config_value(
beeps12c0a3c2013-09-03 11:58:27 -0700548 'CROS', 'factory_artifact', type=str, default='')
549 if not factory_artifact:
550 raise ValueError('Cannot retrieve the factory artifact name from '
551 'autotest config, and hence cannot stage factory '
552 'artifacts.')
553
beepse539be02013-07-31 21:57:39 -0700554 logging.info('Staging build for servo install: %s', image_name)
Dan Shi216389c2015-12-22 11:03:06 -0800555 devserver = dev_server.ImageServer.resolve(image_name, self.hostname)
beepse539be02013-07-31 21:57:39 -0700556 devserver.stage_artifacts(
557 image_name,
beeps12c0a3c2013-09-03 11:58:27 -0700558 [factory_artifact],
559 archive_url=None)
beepse539be02013-07-31 21:57:39 -0700560
561 return tools.factory_image_url_pattern() % (devserver.url(), image_name)
562
563
Laurence Goodby778c9a42017-05-24 19:24:07 -0700564 def prepare_for_update(self):
565 """Prepares the DUT for an update.
566
567 Subclasses may override this to perform any special actions
568 required before updating.
569 """
Laurence Goodby468de252017-06-08 17:22:53 -0700570 pass
Laurence Goodby778c9a42017-05-24 19:24:07 -0700571
572
Tom Wai-Hong Tam2d00cb22016-01-08 06:40:50 +0800573 def _clear_fw_version_labels(self, rw_only):
574 """Clear firmware version labels from the machine.
575
576 @param rw_only: True to only clear fwrw_version; otherewise, clear
577 both fwro_version and fwrw_version.
578 """
Prathmesh Prabhuf8ae9a82019-10-04 15:34:13 -0700579 info = self.host_info_store.get()
580 info.clear_version_labels(provision.FW_RW_VERSION_PREFIX)
Tom Wai-Hong Tam2d00cb22016-01-08 06:40:50 +0800581 if not rw_only:
Prathmesh Prabhuf8ae9a82019-10-04 15:34:13 -0700582 info.clear_version_labels(provision.FW_RO_VERSION_PREFIX)
583 self.host_info_store.commit(info)
Dan Shi9cb0eec2014-06-03 09:04:50 -0700584
585
Tom Wai-Hong Tam2d00cb22016-01-08 06:40:50 +0800586 def _add_fw_version_label(self, build, rw_only):
Dan Shi9cb0eec2014-06-03 09:04:50 -0700587 """Add firmware version label to the machine.
588
589 @param build: Build of firmware.
Tom Wai-Hong Tam2d00cb22016-01-08 06:40:50 +0800590 @param rw_only: True to only add fwrw_version; otherwise, add both
591 fwro_version and fwrw_version.
Dan Shi9cb0eec2014-06-03 09:04:50 -0700592
593 """
Prathmesh Prabhuf8ae9a82019-10-04 15:34:13 -0700594 info = self.host_info_store.get()
595 info.set_version_label(provision.FW_RW_VERSION_PREFIX, build)
Tom Wai-Hong Tam2d00cb22016-01-08 06:40:50 +0800596 if not rw_only:
Prathmesh Prabhuf8ae9a82019-10-04 15:34:13 -0700597 info.set_version_label(provision.FW_RO_VERSION_PREFIX, build)
598 self.host_info_store.commit(info)
Dan Shi9cb0eec2014-06-03 09:04:50 -0700599
600
Mary Ruthven6481a9f2019-08-23 12:46:05 -0700601 def firmware_install(self, build=None, rw_only=False, dest=None):
Dan Shi9cb0eec2014-06-03 09:04:50 -0700602 """Install firmware to the DUT.
603
604 Use stateful update if the DUT is already running the same build.
605 Stateful update does not update kernel and tends to run much faster
606 than a full reimage. If the DUT is running a different build, or it
607 failed to do a stateful update, full update, including kernel update,
608 will be applied to the DUT.
609
Tom Wai-Hong Tam2d00cb22016-01-08 06:40:50 +0800610 Once a host enters firmware_install its fw[ro|rw]_version label will
611 be removed. After the firmware is updated successfully, a new
612 fw[ro|rw]_version label will be added to the host.
Dan Shi9cb0eec2014-06-03 09:04:50 -0700613
614 @param build: The build version to which we want to provision the
615 firmware of the machine,
616 e.g. 'link-firmware/R22-2695.1.144'.
Tom Wai-Hong Tam4ac78982016-01-08 02:34:37 +0800617 @param rw_only: True to only install firmware to its RW portions. Keep
618 the RO portions unchanged.
Mary Ruthven6481a9f2019-08-23 12:46:05 -0700619 @param dest: Directory to store the firmware in.
Dan Shi9cb0eec2014-06-03 09:04:50 -0700620
621 TODO(dshi): After bug 381718 is fixed, update here with corresponding
622 exceptions that could be raised.
623
624 """
625 if not self.servo:
626 raise error.TestError('Host %s does not have servo.' %
627 self.hostname)
628
Wai-Hong Tam3fa455a2018-07-18 14:40:43 -0700629 # Get the DUT board name from AFE.
630 info = self.host_info_store.get()
631 board = info.board
Shelley Chenac61d5a2019-06-24 15:35:46 -0700632 model = info.model
Namyoon Woo8dbfcf92019-01-15 18:37:12 -0800633
634 if board is None or board == '':
635 board = self.servo.get_board()
Dan Shi9cb0eec2014-06-03 09:04:50 -0700636
Mary Ruthvende14a8b2019-08-23 12:43:52 -0700637 if model is None or model == '':
638 model = self.get_platform_from_fwid()
639
Chris Sosae92399e2015-04-24 11:32:59 -0700640 # If build is not set, try to install firmware from stable CrOS.
Dan Shi9cb0eec2014-06-03 09:04:50 -0700641 if not build:
Richard Barnette260cbd02016-10-06 12:23:28 -0700642 build = afe_utils.get_stable_faft_version(board)
Dan Shi3d7a0e12015-10-12 11:55:45 -0700643 if not build:
644 raise error.TestError(
645 'Failed to find stable firmware build for %s.',
646 self.hostname)
647 logging.info('Will install firmware from build %s.', build)
Dan Shi9cb0eec2014-06-03 09:04:50 -0700648
Dan Shi216389c2015-12-22 11:03:06 -0800649 ds = dev_server.ImageServer.resolve(build, self.hostname)
Dan Shi9cb0eec2014-06-03 09:04:50 -0700650 ds.stage_artifacts(build, ['firmware'])
651
Mary Ruthven6481a9f2019-08-23 12:46:05 -0700652 tmpd = None
653 if not dest:
654 tmpd = autotemp.tempdir(unique_id='fwimage')
655 dest = tmpd.name
Dan Shi9cb0eec2014-06-03 09:04:50 -0700656 try:
657 fwurl = self._FW_IMAGE_URL_PATTERN % (ds.url(), build)
Mary Ruthven6481a9f2019-08-23 12:46:05 -0700658 local_tarball = os.path.join(dest, os.path.basename(fwurl))
xixuan4e116822016-11-17 15:32:10 -0800659 ds.download_file(fwurl, local_tarball)
Dan Shi9cb0eec2014-06-03 09:04:50 -0700660
Tom Wai-Hong Tam2d00cb22016-01-08 06:40:50 +0800661 self._clear_fw_version_labels(rw_only)
Shelley Chenac61d5a2019-06-24 15:35:46 -0700662 self.servo.program_firmware(board, model, local_tarball, rw_only)
Wai-Hong Tamb5f66ce2016-11-10 15:45:30 -0800663 if utils.host_is_in_lab_zone(self.hostname):
664 self._add_fw_version_label(build, rw_only)
Dan Shi9cb0eec2014-06-03 09:04:50 -0700665 finally:
Mary Ruthven6481a9f2019-08-23 12:46:05 -0700666 if tmpd:
667 tmpd.clean()
Dan Shi9cb0eec2014-06-03 09:04:50 -0700668
669
beepsf079cfb2013-09-18 17:49:51 -0700670 def servo_install(self, image_url=None, usb_boot_timeout=USB_BOOT_TIMEOUT,
671 install_timeout=INSTALL_TIMEOUT):
Scott Zawalski62bacae2013-03-05 10:40:32 -0500672 """
673 Re-install the OS on the DUT by:
674 1) installing a test image on a USB storage device attached to the Servo
675 board,
Richard Barnette03a0c132012-11-05 12:40:35 -0800676 2) booting that image in recovery mode, and then
J. Richard Barnette31b2e312013-04-04 16:05:22 -0700677 3) installing the image with chromeos-install.
678
Scott Zawalski62bacae2013-03-05 10:40:32 -0500679 @param image_url: If specified use as the url to install on the DUT.
680 otherwise boot the currently staged image on the USB stick.
beepsf079cfb2013-09-18 17:49:51 -0700681 @param usb_boot_timeout: The usb_boot_timeout to use during reimage.
682 Factory images need a longer usb_boot_timeout than regular
683 cros images.
684 @param install_timeout: The timeout to use when installing the chromeos
685 image. Factory images need a longer install_timeout.
Richard Barnette03a0c132012-11-05 12:40:35 -0800686
Scott Zawalski62bacae2013-03-05 10:40:32 -0500687 @raises AutoservError if the image fails to boot.
beepsf079cfb2013-09-18 17:49:51 -0700688
J. Richard Barnette0199cc82014-12-05 17:08:40 -0800689 """
beepsf079cfb2013-09-18 17:49:51 -0700690 logging.info('Downloading image to USB, then booting from it. Usb boot '
691 'timeout = %s', usb_boot_timeout)
Allen Li48a13fe2016-11-22 14:10:40 -0800692 with metrics.SecondsTimer(
693 'chromeos/autotest/provision/servo_install/boot_duration'):
694 self.servo.install_recovery_image(image_url)
695 if not self.wait_up(timeout=usb_boot_timeout):
696 raise hosts.AutoservRepairError(
697 'DUT failed to boot from USB after %d seconds' %
Garry Wang954f8382019-01-23 13:49:29 -0800698 usb_boot_timeout, 'failed_to_reboot')
Scott Zawalski62bacae2013-03-05 10:40:32 -0500699
Tom Wai-Hong Tamf6b4f812015-08-08 04:14:59 +0800700 # The new chromeos-tpm-recovery has been merged since R44-7073.0.0.
701 # In old CrOS images, this command fails. Skip the error.
Tom Wai-Hong Tam27af7332015-07-25 06:09:39 +0800702 logging.info('Resetting the TPM status')
Tom Wai-Hong Tamf6b4f812015-08-08 04:14:59 +0800703 try:
704 self.run('chromeos-tpm-recovery')
705 except error.AutoservRunError:
706 logging.warn('chromeos-tpm-recovery is too old.')
707
Tom Wai-Hong Tam27af7332015-07-25 06:09:39 +0800708
Allen Li48a13fe2016-11-22 14:10:40 -0800709 with metrics.SecondsTimer(
710 'chromeos/autotest/provision/servo_install/install_duration'):
711 logging.info('Installing image through chromeos-install.')
Garry Wang83fb5b32019-09-27 13:16:00 -0700712 self.run('chromeos-install --yes',timeout=install_timeout)
Anh Lee21e4032019-07-11 15:01:06 -0700713
Allen Li48a13fe2016-11-22 14:10:40 -0800714 self.halt()
beepsf079cfb2013-09-18 17:49:51 -0700715
716 logging.info('Power cycling DUT through servo.')
J. Richard Barnette0199cc82014-12-05 17:08:40 -0800717 self.servo.get_power_state_controller().power_off()
Fang Dengafb88142013-05-30 17:44:31 -0700718 self.servo.switch_usbkey('off')
J. Richard Barnette0199cc82014-12-05 17:08:40 -0800719 # N.B. The Servo API requires that we use power_on() here
720 # for two reasons:
721 # 1) After turning on a DUT in recovery mode, you must turn
722 # it off and then on with power_on() once more to
723 # disable recovery mode (this is a Parrot specific
724 # requirement).
725 # 2) After power_off(), the only way to turn on is with
726 # power_on() (this is a Storm specific requirement).
J. Richard Barnettefbcc7122013-07-24 18:24:59 -0700727 self.servo.get_power_state_controller().power_on()
beepsf079cfb2013-09-18 17:49:51 -0700728
729 logging.info('Waiting for DUT to come back up.')
Richard Barnette03a0c132012-11-05 12:40:35 -0800730 if not self.wait_up(timeout=self.BOOT_TIMEOUT):
731 raise error.AutoservError('DUT failed to reboot installed '
732 'test image after %d seconds' %
Scott Zawalski62bacae2013-03-05 10:40:32 -0500733 self.BOOT_TIMEOUT)
734
735
Richard Barnette4aeb01c2018-09-20 09:36:12 -0700736 def set_servo_host(self, host):
737 """Set our servo host member, and associated servo.
738
739 @param host Our new `ServoHost`.
740 """
741 self._servo_host = host
742 if self._servo_host is not None:
743 self.servo = self._servo_host.get_servo()
744 else:
745 self.servo = None
746
747
Richard Barnette9a26ad62016-06-10 12:03:08 -0700748 def repair_servo(self):
Dan Shi90466352015-09-22 15:01:05 -0700749 """
Richard Barnette9a26ad62016-06-10 12:03:08 -0700750 Confirm that servo is initialized and verified.
Dan Shi90466352015-09-22 15:01:05 -0700751
Richard Barnette9a26ad62016-06-10 12:03:08 -0700752 If the servo object is missing, attempt to repair the servo
753 host. Repair failures are passed back to the caller.
754
755 @raise AutoservError: If there is no servo host for this CrOS
756 host.
757 """
758 if self.servo:
759 return
760 if not self._servo_host:
761 raise error.AutoservError('No servo host for %s.' %
762 self.hostname)
763 self._servo_host.repair()
764 self.servo = self._servo_host.get_servo()
Dan Shi90466352015-09-22 15:01:05 -0700765
766
J. Richard Barnettec2d99cf2015-11-18 12:46:15 -0800767 def repair(self):
768 """Attempt to get the DUT to pass `self.verify()`.
Richard Barnette82c35912012-11-20 10:09:10 -0800769
770 This overrides the base class function for repair; it does
J. Richard Barnette91137f02016-03-10 16:52:26 -0800771 not call back to the parent class, but instead relies on
772 `self._repair_strategy` to coordinate the verification and
773 repair steps needed to get the DUT working.
Richard Barnette82c35912012-11-20 10:09:10 -0800774 """
Richard Barnetteabbdc252018-07-26 16:57:42 -0700775 message = 'Beginning repair for host %s board %s model %s'
776 info = self.host_info_store.get()
777 message %= (self.hostname, info.board, info.model)
778 self.record('INFO', None, None, message)
J. Richard Barnette91137f02016-03-10 16:52:26 -0800779 self._repair_strategy.repair(self)
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500780
Richard Barnette82c35912012-11-20 10:09:10 -0800781
J. Richard Barnette1d78b012012-05-15 13:56:30 -0700782 def close(self):
David Rileye2c6be12017-12-11 10:20:57 -0800783 """Close connection."""
Fang Deng0ca40e22013-08-27 17:47:44 -0700784 super(CrosHost, self).close()
howardchung83e55272019-08-08 14:08:05 +0800785
786 for chameleon_host in self._chameleon_host_list:
787 if chameleon_host:
788 chameleon_host.close()
xixuand6011f12016-12-08 15:01:58 -0800789
790 if self._servo_host:
791 self._servo_host.close()
J. Richard Barnette1d78b012012-05-15 13:56:30 -0700792
793
Dan Shi49ca0932014-11-14 11:22:27 -0800794 def get_power_supply_info(self):
795 """Get the output of power_supply_info.
796
797 power_supply_info outputs the info of each power supply, e.g.,
798 Device: Line Power
799 online: no
800 type: Mains
801 voltage (V): 0
802 current (A): 0
803 Device: Battery
804 state: Discharging
805 percentage: 95.9276
806 technology: Li-ion
807
808 Above output shows two devices, Line Power and Battery, with details of
809 each device listed. This function parses the output into a dictionary,
810 with key being the device name, and value being a dictionary of details
811 of the device info.
812
813 @return: The dictionary of power_supply_info, e.g.,
814 {'Line Power': {'online': 'yes', 'type': 'main'},
815 'Battery': {'vendor': 'xyz', 'percentage': '100'}}
Dan Shie9b765d2014-12-29 16:59:49 -0800816 @raise error.AutoservRunError if power_supply_info tool is not found in
817 the DUT. Caller should handle this error to avoid false failure
818 on verification.
Dan Shi49ca0932014-11-14 11:22:27 -0800819 """
820 result = self.run('power_supply_info').stdout.strip()
821 info = {}
822 device_name = None
823 device_info = {}
824 for line in result.split('\n'):
825 pair = [v.strip() for v in line.split(':')]
826 if len(pair) != 2:
827 continue
828 if pair[0] == 'Device':
829 if device_name:
830 info[device_name] = device_info
831 device_name = pair[1]
832 device_info = {}
833 else:
834 device_info[pair[0]] = pair[1]
835 if device_name and not device_name in info:
836 info[device_name] = device_info
837 return info
838
839
840 def get_battery_percentage(self):
841 """Get the battery percentage.
842
843 @return: The percentage of battery level, value range from 0-100. Return
844 None if the battery info cannot be retrieved.
845 """
846 try:
847 info = self.get_power_supply_info()
848 logging.info(info)
849 return float(info['Battery']['percentage'])
Dan Shie9b765d2014-12-29 16:59:49 -0800850 except (KeyError, ValueError, error.AutoservRunError):
Dan Shi49ca0932014-11-14 11:22:27 -0800851 return None
852
853
854 def is_ac_connected(self):
855 """Check if the dut has power adapter connected and charging.
856
857 @return: True if power adapter is connected and charging.
858 """
859 try:
860 info = self.get_power_supply_info()
861 return info['Line Power']['online'] == 'yes'
Dan Shie9b765d2014-12-29 16:59:49 -0800862 except (KeyError, error.AutoservRunError):
863 return None
Dan Shi49ca0932014-11-14 11:22:27 -0800864
865
Simran Basi5e6339a2013-03-21 11:34:32 -0700866 def _cleanup_poweron(self):
867 """Special cleanup method to make sure hosts always get power back."""
Garry Wangad4d4fd2019-01-30 17:00:38 -0800868 info = self.host_info_store.get()
869 if self._RPM_OUTLET_CHANGED not in info.attributes:
Simran Basi5e6339a2013-03-21 11:34:32 -0700870 return
871 logging.debug('This host has recently interacted with the RPM'
872 ' Infrastructure. Ensuring power is on.')
873 try:
874 self.power_on()
Garry Wangad4d4fd2019-01-30 17:00:38 -0800875 self._remove_rpm_changed_tag()
Simran Basi5e6339a2013-03-21 11:34:32 -0700876 except rpm_client.RemotePowerException:
Simran Basi5e6339a2013-03-21 11:34:32 -0700877 logging.error('Failed to turn Power On for this host after '
878 'cleanup through the RPM Infrastructure.')
Dan Shi49ca0932014-11-14 11:22:27 -0800879
880 battery_percentage = self.get_battery_percentage()
Dan Shif01ebe22014-12-05 13:10:57 -0800881 if battery_percentage and battery_percentage < 50:
Dan Shi49ca0932014-11-14 11:22:27 -0800882 raise
883 elif self.is_ac_connected():
884 logging.info('The device has power adapter connected and '
885 'charging. No need to try to turn RPM on '
886 'again.')
Garry Wangad4d4fd2019-01-30 17:00:38 -0800887 self._remove_rpm_changed_tag()
Dan Shi49ca0932014-11-14 11:22:27 -0800888 logging.info('Battery level is now at %s%%. The device may '
889 'still have enough power to run test, so no '
890 'exception will be raised.', battery_percentage)
891
Simran Basi5e6339a2013-03-21 11:34:32 -0700892
Garry Wangad4d4fd2019-01-30 17:00:38 -0800893 def _remove_rpm_changed_tag(self):
894 info = self.host_info_store.get()
895 del info.attributes[self._RPM_OUTLET_CHANGED]
896 self.host_info_store.commit(info)
897
898
899 def _add_rpm_changed_tag(self):
900 info = self.host_info_store.get()
Garry Wang518831d2019-02-21 15:15:36 -0800901 info.attributes[self._RPM_OUTLET_CHANGED] = 'true'
Garry Wangad4d4fd2019-01-30 17:00:38 -0800902 self.host_info_store.commit(info)
903
904
905
beepsc87ff602013-07-31 21:53:00 -0700906 def _is_factory_image(self):
907 """Checks if the image on the DUT is a factory image.
908
909 @return: True if the image on the DUT is a factory image.
910 False otherwise.
911 """
912 result = self.run('[ -f /root/.factory_test ]', ignore_status=True)
913 return result.exit_status == 0
914
915
916 def _restart_ui(self):
J. Richard Barnette84890bd2014-02-21 11:05:47 -0800917 """Restart the Chrome UI.
beepsc87ff602013-07-31 21:53:00 -0700918
919 @raises: FactoryImageCheckerException for factory images, since
920 we cannot attempt to restart ui on them.
921 error.AutoservRunError for any other type of error that
922 occurs while restarting ui.
923 """
924 if self._is_factory_image():
Dan Shi549fb822015-03-24 18:01:11 -0700925 raise FactoryImageCheckerException('Cannot restart ui on factory '
926 'images')
beepsc87ff602013-07-31 21:53:00 -0700927
J. Richard Barnette84890bd2014-02-21 11:05:47 -0800928 # TODO(jrbarnette): The command to stop/start the ui job
929 # should live inside cros_ui, too. However that would seem
930 # to imply interface changes to the existing start()/restart()
931 # functions, which is a bridge too far (for now).
J. Richard Barnette6069aa12015-06-08 09:10:24 -0700932 prompt = cros_ui.get_chrome_session_ident(self)
J. Richard Barnette84890bd2014-02-21 11:05:47 -0800933 self.run('stop ui; start ui')
934 cros_ui.wait_for_chrome_ready(prompt, self)
beepsc87ff602013-07-31 21:53:00 -0700935
936
Daniel Erat4b5f7e02018-07-04 22:05:30 -0700937 def _start_powerd_if_needed(self):
938 """Start powerd if it isn't already running."""
939 self.run('start powerd', ignore_status=True)
940
941
xixuana3bbc422017-05-04 15:57:21 -0700942 def _get_lsb_release_content(self):
943 """Return the content of lsb-release file of host."""
944 return self.run(
945 'cat "%s"' % client_constants.LSB_RELEASE).stdout.strip()
946
947
Dan Shi549fb822015-03-24 18:01:11 -0700948 def get_release_version(self):
949 """Get the value of attribute CHROMEOS_RELEASE_VERSION from lsb-release.
950
951 @returns The version string in lsb-release, under attribute
952 CHROMEOS_RELEASE_VERSION.
953 """
Dan Shi549fb822015-03-24 18:01:11 -0700954 return lsbrelease_utils.get_chromeos_release_version(
xixuana3bbc422017-05-04 15:57:21 -0700955 lsb_release_content=self._get_lsb_release_content())
956
957
Don Garrettb9f35802018-01-22 18:25:40 -0800958 def get_release_builder_path(self):
959 """Get the value of CHROMEOS_RELEASE_BUILDER_PATH from lsb-release.
960
961 @returns The version string in lsb-release, under attribute
962 CHROMEOS_RELEASE_BUILDER_PATH.
963 """
964 return lsbrelease_utils.get_chromeos_release_builder_path(
965 lsb_release_content=self._get_lsb_release_content())
966
967
xixuana3bbc422017-05-04 15:57:21 -0700968 def get_chromeos_release_milestone(self):
969 """Get the value of attribute CHROMEOS_RELEASE_BUILD_TYPE
970 from lsb-release.
971
972 @returns The version string in lsb-release, under attribute
973 CHROMEOS_RELEASE_BUILD_TYPE.
974 """
975 return lsbrelease_utils.get_chromeos_release_milestone(
976 lsb_release_content=self._get_lsb_release_content())
Dan Shi549fb822015-03-24 18:01:11 -0700977
978
979 def verify_cros_version_label(self):
980 """ Make sure host's cros-version label match the actual image in dut.
981
982 Remove any cros-version: label that doesn't match that installed in
983 the dut.
984
985 @param raise_error: Set to True to raise exception if any mismatch found
986
987 @raise error.AutoservError: If any mismatch between cros-version label
988 and the build installed in dut is found.
989 """
Prathmesh Prabhuce2da3a2019-10-04 11:54:51 -0700990 # crbug.com/1007333: This check is being removed.
991 return True
Dan Shi549fb822015-03-24 18:01:11 -0700992
993
Laurence Goodby778c9a42017-05-24 19:24:07 -0700994 def cleanup_services(self):
995 """Reinitializes the device for cleanup.
996
997 Subclasses may override this to customize the cleanup method.
998
999 To indicate failure of the reset, the implementation may raise
1000 any of:
1001 error.AutoservRunError
1002 error.AutotestRunError
1003 FactoryImageCheckerException
1004
1005 @raises error.AutoservRunError
1006 @raises error.AutotestRunError
1007 @raises error.FactoryImageCheckerException
1008 """
1009 self._restart_ui()
Daniel Erat4b5f7e02018-07-04 22:05:30 -07001010 self._start_powerd_if_needed()
Laurence Goodby778c9a42017-05-24 19:24:07 -07001011
1012
beepsc87ff602013-07-31 21:53:00 -07001013 def cleanup(self):
Pradeep Sawlaniaa013fa2017-11-09 06:34:18 -08001014 """Cleanup state on device."""
MK Ryu35d661e2014-09-25 17:44:10 -07001015 self.run('rm -f %s' % client_constants.CLEANUP_LOGS_PAUSED_FILE)
Scott Zawalskiddbc31e2012-11-15 11:29:01 -05001016 try:
Laurence Goodby778c9a42017-05-24 19:24:07 -07001017 self.cleanup_services()
beepsc87ff602013-07-31 21:53:00 -07001018 except (error.AutotestRunError, error.AutoservRunError,
1019 FactoryImageCheckerException):
Ilja H. Friedel04be2bd2014-05-07 21:29:59 -07001020 logging.warning('Unable to restart ui, rebooting device.')
Scott Zawalskiddbc31e2012-11-15 11:29:01 -05001021 # Since restarting the UI fails fall back to normal Autotest
1022 # cleanup routines, i.e. reboot the machine.
Fang Deng0ca40e22013-08-27 17:47:44 -07001023 super(CrosHost, self).cleanup()
Simran Basi5e6339a2013-03-21 11:34:32 -07001024 # Check if the rpm outlet was manipulated.
Simran Basid5e5e272012-09-24 15:23:59 -07001025 if self.has_power():
Simran Basi5e6339a2013-03-21 11:34:32 -07001026 self._cleanup_poweron()
Dan Shi549fb822015-03-24 18:01:11 -07001027 self.verify_cros_version_label()
J. Richard Barnette45e93de2012-04-11 17:24:15 -07001028
1029
Yu-Ju Honga2be94a2012-07-31 09:48:52 -07001030 def reboot(self, **dargs):
1031 """
1032 This function reboots the site host. The more generic
1033 RemoteHost.reboot() performs sync and sleeps for 5
1034 seconds. This is not necessary for Chrome OS devices as the
1035 sync should be finished in a short time during the reboot
1036 command.
1037 """
Tom Wai-Hong Tamf5cd1d42012-08-13 12:04:08 +08001038 if 'reboot_cmd' not in dargs:
Doug Anderson7d5aeb22014-02-27 15:12:17 -08001039 reboot_timeout = dargs.get('reboot_timeout', 10)
J. Richard Barnette9af19632015-09-25 12:18:03 -07001040 dargs['reboot_cmd'] = ('sleep 1; '
1041 'reboot & sleep %d; '
1042 'reboot -f' % reboot_timeout)
Yu-Ju Honga2be94a2012-07-31 09:48:52 -07001043 # Enable fastsync to avoid running extra sync commands before reboot.
Tom Wai-Hong Tamf5cd1d42012-08-13 12:04:08 +08001044 if 'fastsync' not in dargs:
1045 dargs['fastsync'] = True
Michael Liangda8c60a2014-06-03 13:24:51 -07001046
Prathmesh Prabhu53a4c1c2018-09-14 16:36:27 -07001047 dargs['board'] = self.host_info_store.get().board
Vincent Palatindf2372c2016-10-07 17:03:00 +02001048 # Record who called us
1049 orig = sys._getframe(1).f_code
Vincent Palatin80780b22016-07-27 16:02:37 +02001050 metric_fields = {'board' : dargs['board'],
Vincent Palatindf2372c2016-10-07 17:03:00 +02001051 'dut_host_name' : self.hostname,
1052 'success' : True}
1053 metric_debug_fields = {'board' : dargs['board'],
Prathmesh Prabhu53a4c1c2018-09-14 16:36:27 -07001054 'caller' : "%s:%s" % (orig.co_filename,
1055 orig.co_name),
Vincent Palatindf2372c2016-10-07 17:03:00 +02001056 'success' : True,
1057 'error' : ''}
1058
Vincent Palatin80780b22016-07-27 16:02:37 +02001059 t0 = time.time()
1060 try:
1061 super(CrosHost, self).reboot(**dargs)
1062 except Exception as e:
1063 metric_fields['success'] = False
Vincent Palatindf2372c2016-10-07 17:03:00 +02001064 metric_debug_fields['success'] = False
1065 metric_debug_fields['error'] = type(e).__name__
Vincent Palatin80780b22016-07-27 16:02:37 +02001066 raise
1067 finally:
1068 duration = int(time.time() - t0)
Dan Shi5e2efb72017-02-07 11:40:23 -08001069 metrics.Counter(
1070 'chromeos/autotest/autoserv/reboot_count').increment(
1071 fields=metric_fields)
1072 metrics.Counter(
1073 'chromeos/autotest/autoserv/reboot_debug').increment(
1074 fields=metric_debug_fields)
1075 metrics.SecondsDistribution(
1076 'chromeos/autotest/autoserv/reboot_duration').add(
1077 duration, fields=metric_fields)
Yu-Ju Honga2be94a2012-07-31 09:48:52 -07001078
1079
Ravi Chandra Sadineni812e61b2018-07-09 11:16:50 -07001080 def suspend(self, suspend_time=60,
1081 suspend_cmd=None, allow_early_resume=False):
Gwendal Grignou7a61d2f2014-05-23 11:05:51 -07001082 """
1083 This function suspends the site host.
Ravi Chandra Sadineni812e61b2018-07-09 11:16:50 -07001084
1085 @param suspend_time: How long to suspend as integer seconds.
1086 @param suspend_cmd: Suspend command to execute.
1087 @param allow_early_resume: If False and if device resumes before
1088 |suspend_time|, throw an error.
1089
1090 @exception AutoservSuspendError Host resumed earlier than
1091 |suspend_time|.
Gwendal Grignou7a61d2f2014-05-23 11:05:51 -07001092 """
Ravi Chandra Sadineni812e61b2018-07-09 11:16:50 -07001093
1094 if suspend_cmd is None:
1095 suspend_cmd = ' && '.join([
J. Richard Barnette9af19632015-09-25 12:18:03 -07001096 'echo 0 > /sys/class/rtc/rtc0/wakealarm',
Gwendal Grignou7a61d2f2014-05-23 11:05:51 -07001097 'echo +%d > /sys/class/rtc/rtc0/wakealarm' % suspend_time,
J. Richard Barnette9af19632015-09-25 12:18:03 -07001098 'powerd_dbus_suspend --delay=0'])
Ravi Chandra Sadineni812e61b2018-07-09 11:16:50 -07001099 super(CrosHost, self).suspend(suspend_time, suspend_cmd,
1100 allow_early_resume);
Gwendal Grignou7a61d2f2014-05-23 11:05:51 -07001101
1102
Simran Basiec564392014-08-25 16:48:09 -07001103 def upstart_status(self, service_name):
1104 """Check the status of an upstart init script.
1105
1106 @param service_name: Service to look up.
1107
1108 @returns True if the service is running, False otherwise.
1109 """
Richard Barnettee204dc52017-09-26 11:02:25 -07001110 return 'start/running' in self.run('status %s' % service_name,
1111 ignore_status=True).stdout
Simran Basiec564392014-08-25 16:48:09 -07001112
Tom Hughese9552342018-12-18 14:29:25 -08001113 def upstart_stop(self, service_name):
1114 """Stops an upstart job if it's running.
1115
1116 @param service_name: Service to stop
1117
1118 @returns True if service has been stopped or was already stopped
1119 False otherwise.
1120 """
1121 if not self.upstart_status(service_name):
1122 return True
1123
1124 result = self.run('stop %s' % service_name, ignore_status=True)
1125 if result.exit_status != 0:
1126 return False
1127 return True
1128
1129 def upstart_restart(self, service_name):
1130 """Restarts (or starts) an upstart job.
1131
1132 @param service_name: Service to start/restart
1133
1134 @returns True if service has been started/restarted, False otherwise.
1135 """
1136 cmd = 'start'
1137 if self.upstart_status(service_name):
1138 cmd = 'restart'
1139 cmd = cmd + ' %s' % service_name
1140 result = self.run(cmd)
1141 if result.exit_status != 0:
1142 return False
1143 return True
Simran Basiec564392014-08-25 16:48:09 -07001144
J. Richard Barnette45e93de2012-04-11 17:24:15 -07001145 def verify_software(self):
Richard Barnetteb2bc13c2013-01-08 17:32:51 -08001146 """Verify working software on a Chrome OS system.
J. Richard Barnette45e93de2012-04-11 17:24:15 -07001147
Richard Barnetteb2bc13c2013-01-08 17:32:51 -08001148 Tests for the following conditions:
1149 1. All conditions tested by the parent version of this
1150 function.
1151 2. Sufficient space in /mnt/stateful_partition.
Fang Deng6b05f5b2013-03-20 13:42:11 -07001152 3. Sufficient space in /mnt/stateful_partition/encrypted.
1153 4. update_engine answers a simple status request over DBus.
J. Richard Barnette45e93de2012-04-11 17:24:15 -07001154
J. Richard Barnette45e93de2012-04-11 17:24:15 -07001155 """
Fang Deng0ca40e22013-08-27 17:47:44 -07001156 super(CrosHost, self).verify_software()
Dan Shib8540a52015-07-16 14:18:23 -07001157 default_kilo_inodes_required = CONFIG.get_config_value(
1158 'SERVER', 'kilo_inodes_required', type=int, default=100)
1159 board = self.get_board().replace(ds_constants.BOARD_PREFIX, '')
1160 kilo_inodes_required = CONFIG.get_config_value(
1161 'SERVER', 'kilo_inodes_required_%s' % board,
1162 type=int, default=default_kilo_inodes_required)
1163 self.check_inodes('/mnt/stateful_partition', kilo_inodes_required)
J. Richard Barnette45e93de2012-04-11 17:24:15 -07001164 self.check_diskspace(
1165 '/mnt/stateful_partition',
Dan Shib8540a52015-07-16 14:18:23 -07001166 CONFIG.get_config_value(
Fang Deng6b05f5b2013-03-20 13:42:11 -07001167 'SERVER', 'gb_diskspace_required', type=float,
1168 default=20.0))
Gaurav Shahe448af82014-06-19 15:18:59 -07001169 encrypted_stateful_path = '/mnt/stateful_partition/encrypted'
1170 # Not all targets build with encrypted stateful support.
1171 if self.path_exists(encrypted_stateful_path):
1172 self.check_diskspace(
1173 encrypted_stateful_path,
Dan Shib8540a52015-07-16 14:18:23 -07001174 CONFIG.get_config_value(
Gaurav Shahe448af82014-06-19 15:18:59 -07001175 'SERVER', 'gb_encrypted_diskspace_required', type=float,
1176 default=0.1))
beepsc87ff602013-07-31 21:53:00 -07001177
Justin TerAvest3b0c5ba2017-11-07 09:59:11 -07001178 self.wait_for_system_services()
Prashanth B5d0a0512014-04-25 12:26:08 -07001179
beepsc87ff602013-07-31 21:53:00 -07001180 # Factory images don't run update engine,
1181 # goofy controls dbus on these DUTs.
1182 if not self._is_factory_image():
1183 self.run('update_engine_client --status')
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001184
Dan Shi549fb822015-03-24 18:01:11 -07001185 self.verify_cros_version_label()
1186
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001187
Justin TerAvest3b0c5ba2017-11-07 09:59:11 -07001188 @retry.retry(error.AutoservError, timeout_min=5, delay_sec=10)
1189 def wait_for_system_services(self):
1190 """Waits for system-services to be running.
1191
1192 Sometimes, update_engine will take a while to update firmware, so we
1193 should give this some time to finish. See crbug.com/765686#c38 for
1194 details.
1195 """
1196 if not self.upstart_status('system-services'):
1197 raise error.AutoservError('Chrome failed to reach login. '
1198 'System services not running.')
1199
1200
J. Richard Barnettea7e7fdc2016-02-12 12:35:36 -08001201 def verify(self):
Pradeep Sawlaniaa013fa2017-11-09 06:34:18 -08001202 """Verify Chrome OS system is in good state."""
Richard Barnetteabbdc252018-07-26 16:57:42 -07001203 message = 'Beginning verify for host %s board %s model %s'
1204 info = self.host_info_store.get()
1205 message %= (self.hostname, info.board, info.model)
1206 self.record('INFO', None, None, message)
J. Richard Barnettea7e7fdc2016-02-12 12:35:36 -08001207 self._repair_strategy.verify(self)
1208
1209
Fang Deng96667ca2013-08-01 17:46:18 -07001210 def make_ssh_command(self, user='root', port=22, opts='', hosts_file=None,
Dean Liaoe3e75f62017-11-14 10:36:43 +08001211 connect_timeout=None, alive_interval=None,
1212 alive_count_max=None, connection_attempts=None):
Fang Deng96667ca2013-08-01 17:46:18 -07001213 """Override default make_ssh_command to use options tuned for Chrome OS.
1214
1215 Tuning changes:
1216 - ConnectTimeout=30; maximum of 30 seconds allowed for an SSH
1217 connection failure. Consistency with remote_access.sh.
1218
Samuel Tan2ce155b2015-06-23 18:24:38 -07001219 - ServerAliveInterval=900; which causes SSH to ping connection every
1220 900 seconds. In conjunction with ServerAliveCountMax ensures
1221 that if the connection dies, Autotest will bail out.
Fang Deng96667ca2013-08-01 17:46:18 -07001222 Originally tried 60 secs, but saw frequent job ABORTS where
Samuel Tan2ce155b2015-06-23 18:24:38 -07001223 the test completed successfully. Later increased from 180 seconds to
1224 900 seconds to account for tests where the DUT is suspended for
1225 longer periods of time.
Fang Deng96667ca2013-08-01 17:46:18 -07001226
1227 - ServerAliveCountMax=3; consistency with remote_access.sh.
1228
1229 - ConnectAttempts=4; reduce flakiness in connection errors;
1230 consistency with remote_access.sh.
1231
1232 - UserKnownHostsFile=/dev/null; we don't care about the keys.
1233 Host keys change with every new installation, don't waste
1234 memory/space saving them.
1235
1236 - SSH protocol forced to 2; needed for ServerAliveInterval.
1237
1238 @param user User name to use for the ssh connection.
1239 @param port Port on the target host to use for ssh connection.
1240 @param opts Additional options to the ssh command.
1241 @param hosts_file Ignored.
1242 @param connect_timeout Ignored.
1243 @param alive_interval Ignored.
Dean Liaoe3e75f62017-11-14 10:36:43 +08001244 @param alive_count_max Ignored.
1245 @param connection_attempts Ignored.
Fang Deng96667ca2013-08-01 17:46:18 -07001246 """
Dean Liaoe3e75f62017-11-14 10:36:43 +08001247 options = ' '.join([opts, '-o Protocol=2'])
1248 return super(CrosHost, self).make_ssh_command(
1249 user=user, port=port, opts=options, hosts_file='/dev/null',
1250 connect_timeout=30, alive_interval=900, alive_count_max=3,
1251 connection_attempts=4)
1252
1253
Jason Abeleb6f924f2013-11-13 16:01:54 -08001254 def syslog(self, message, tag='autotest'):
1255 """Logs a message to syslog on host.
1256
1257 @param message String message to log into syslog
1258 @param tag String tag prefix for syslog
1259
1260 """
1261 self.run('logger -t "%s" "%s"' % (tag, message))
1262
1263
J. Richard Barnetteb6de7e32013-02-14 13:28:04 -08001264 def _ping_check_status(self, status):
1265 """Ping the host once, and return whether it has a given status.
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001266
J. Richard Barnetteb6de7e32013-02-14 13:28:04 -08001267 @param status Check the ping status against this value.
1268 @return True iff `status` and the result of ping are the same
1269 (i.e. both True or both False).
1270
1271 """
1272 ping_val = utils.ping(self.hostname, tries=1, deadline=1)
1273 return not (status ^ (ping_val == 0))
1274
1275 def _ping_wait_for_status(self, status, timeout):
1276 """Wait for the host to have a given status (UP or DOWN).
1277
1278 Status is checked by polling. Polling will not last longer
1279 than the number of seconds in `timeout`. The polling
1280 interval will be long enough that only approximately
1281 _PING_WAIT_COUNT polling cycles will be executed, subject
1282 to a maximum interval of about one minute.
1283
1284 @param status Waiting will stop immediately if `ping` of the
1285 host returns this status.
1286 @param timeout Poll for at most this many seconds.
1287 @return True iff the host status from `ping` matched the
1288 requested status at the time of return.
1289
1290 """
1291 # _ping_check_status() takes about 1 second, hence the
1292 # "- 1" in the formula below.
Nathan Ciobanu38480a32016-10-25 15:26:45 -07001293 # FIXME: if the ping command errors then _ping_check_status()
1294 # returns instantly. If timeout is also smaller than twice
1295 # _PING_WAIT_COUNT then the while loop below forks many
1296 # thousands of ping commands (see /tmp/test_that_results_XXXXX/
1297 # /results-1-logging_YYY.ZZZ/debug/autoserv.DEBUG) and hogs one
1298 # CPU core for 60 seconds.
J. Richard Barnetteb6de7e32013-02-14 13:28:04 -08001299 poll_interval = min(int(timeout / self._PING_WAIT_COUNT), 60) - 1
1300 end_time = time.time() + timeout
1301 while time.time() <= end_time:
1302 if self._ping_check_status(status):
1303 return True
1304 if poll_interval > 0:
1305 time.sleep(poll_interval)
1306
1307 # The last thing we did was sleep(poll_interval), so it may
1308 # have been too long since the last `ping`. Check one more
1309 # time, just to be sure.
1310 return self._ping_check_status(status)
1311
1312 def ping_wait_up(self, timeout):
1313 """Wait for the host to respond to `ping`.
1314
1315 N.B. This method is not a reliable substitute for
1316 `wait_up()`, because a host that responds to ping will not
1317 necessarily respond to ssh. This method should only be used
1318 if the target DUT can be considered functional even if it
1319 can't be reached via ssh.
1320
1321 @param timeout Minimum time to allow before declaring the
1322 host to be non-responsive.
1323 @return True iff the host answered to ping before the timeout.
1324
1325 """
1326 return self._ping_wait_for_status(self._PING_STATUS_UP, timeout)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001327
Andrew Bresticker678c0c72013-01-22 10:44:09 -08001328 def ping_wait_down(self, timeout):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001329 """Wait until the host no longer responds to `ping`.
1330
J. Richard Barnetteb6de7e32013-02-14 13:28:04 -08001331 This function can be used as a slightly faster version of
1332 `wait_down()`, by avoiding potentially long ssh timeouts.
1333
1334 @param timeout Minimum time to allow for the host to become
1335 non-responsive.
1336 @return True iff the host quit answering ping before the
1337 timeout.
1338
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001339 """
J. Richard Barnetteb6de7e32013-02-14 13:28:04 -08001340 return self._ping_wait_for_status(self._PING_STATUS_DOWN, timeout)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001341
Tom Wai-Hong Tamfced4f62014-04-17 10:56:30 +08001342 def test_wait_for_sleep(self, sleep_timeout=None):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001343 """Wait for the client to enter low-power sleep mode.
1344
1345 The test for "is asleep" can't distinguish a system that is
1346 powered off; to confirm that the unit was asleep, it is
1347 necessary to force resume, and then call
1348 `test_wait_for_resume()`.
1349
1350 This function is expected to be called from a test as part
1351 of a sequence like the following:
1352
1353 ~~~~~~~~
1354 boot_id = host.get_boot_id()
1355 # trigger sleep on the host
1356 host.test_wait_for_sleep()
1357 # trigger resume on the host
1358 host.test_wait_for_resume(boot_id)
1359 ~~~~~~~~
1360
Tom Wai-Hong Tamfced4f62014-04-17 10:56:30 +08001361 @param sleep_timeout time limit in seconds to allow the host sleep.
1362
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001363 @exception TestFail The host did not go to sleep within
1364 the allowed time.
1365 """
Tom Wai-Hong Tamfced4f62014-04-17 10:56:30 +08001366 if sleep_timeout is None:
1367 sleep_timeout = self.SLEEP_TIMEOUT
1368
1369 if not self.ping_wait_down(timeout=sleep_timeout):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001370 raise error.TestFail(
Tom Wai-Hong Tamfced4f62014-04-17 10:56:30 +08001371 'client failed to sleep after %d seconds' % sleep_timeout)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001372
1373
Tom Wai-Hong Tamfced4f62014-04-17 10:56:30 +08001374 def test_wait_for_resume(self, old_boot_id, resume_timeout=None):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001375 """Wait for the client to resume from low-power sleep mode.
1376
1377 The `old_boot_id` parameter should be the value from
1378 `get_boot_id()` obtained prior to entering sleep mode. A
1379 `TestFail` exception is raised if the boot id changes.
1380
1381 See @ref test_wait_for_sleep for more on this function's
1382 usage.
1383
J. Richard Barnette7214e0b2013-02-06 15:20:49 -08001384 @param old_boot_id A boot id value obtained before the
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001385 target host went to sleep.
Tom Wai-Hong Tamfced4f62014-04-17 10:56:30 +08001386 @param resume_timeout time limit in seconds to allow the host up.
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001387
1388 @exception TestFail The host did not respond within the
1389 allowed time.
1390 @exception TestFail The host responded, but the boot id test
1391 indicated a reboot rather than a sleep
1392 cycle.
1393 """
Tom Wai-Hong Tamfced4f62014-04-17 10:56:30 +08001394 if resume_timeout is None:
1395 resume_timeout = self.RESUME_TIMEOUT
1396
1397 if not self.wait_up(timeout=resume_timeout):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001398 raise error.TestFail(
1399 'client failed to resume from sleep after %d seconds' %
Tom Wai-Hong Tamfced4f62014-04-17 10:56:30 +08001400 resume_timeout)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001401 else:
1402 new_boot_id = self.get_boot_id()
1403 if new_boot_id != old_boot_id:
Tom Wai-Hong Tam01792682015-01-06 08:00:46 +08001404 logging.error('client rebooted (old boot %s, new boot %s)',
1405 old_boot_id, new_boot_id)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001406 raise error.TestFail(
Tom Wai-Hong Tam01792682015-01-06 08:00:46 +08001407 'client rebooted, but sleep was expected')
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001408
1409
Tom Wai-Hong Tamfe005c22014-12-03 09:25:44 +08001410 def test_wait_for_shutdown(self, shutdown_timeout=None):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001411 """Wait for the client to shut down.
1412
1413 The test for "has shut down" can't distinguish a system that
1414 is merely asleep; to confirm that the unit was down, it is
1415 necessary to force boot, and then call test_wait_for_boot().
1416
1417 This function is expected to be called from a test as part
1418 of a sequence like the following:
1419
1420 ~~~~~~~~
1421 boot_id = host.get_boot_id()
1422 # trigger shutdown on the host
1423 host.test_wait_for_shutdown()
1424 # trigger boot on the host
1425 host.test_wait_for_boot(boot_id)
1426 ~~~~~~~~
1427
Tom Wai-Hong Tamfe005c22014-12-03 09:25:44 +08001428 @param shutdown_timeout time limit in seconds to allow the host down.
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001429 @exception TestFail The host did not shut down within the
1430 allowed time.
1431 """
Tom Wai-Hong Tamfe005c22014-12-03 09:25:44 +08001432 if shutdown_timeout is None:
1433 shutdown_timeout = self.SHUTDOWN_TIMEOUT
1434
1435 if not self.ping_wait_down(timeout=shutdown_timeout):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001436 raise error.TestFail(
1437 'client failed to shut down after %d seconds' %
Tom Wai-Hong Tamfe005c22014-12-03 09:25:44 +08001438 shutdown_timeout)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001439
1440
1441 def test_wait_for_boot(self, old_boot_id=None):
1442 """Wait for the client to boot from cold power.
1443
1444 The `old_boot_id` parameter should be the value from
1445 `get_boot_id()` obtained prior to shutting down. A
1446 `TestFail` exception is raised if the boot id does not
1447 change. The boot id test is omitted if `old_boot_id` is not
1448 specified.
1449
1450 See @ref test_wait_for_shutdown for more on this function's
1451 usage.
1452
J. Richard Barnette7214e0b2013-02-06 15:20:49 -08001453 @param old_boot_id A boot id value obtained before the
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001454 shut down.
1455
1456 @exception TestFail The host did not respond within the
1457 allowed time.
1458 @exception TestFail The host responded, but the boot id test
1459 indicated that there was no reboot.
1460 """
J. Richard Barnetteeb69d722012-06-18 17:29:44 -07001461 if not self.wait_up(timeout=self.REBOOT_TIMEOUT):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001462 raise error.TestFail(
1463 'client failed to reboot after %d seconds' %
J. Richard Barnetteeb69d722012-06-18 17:29:44 -07001464 self.REBOOT_TIMEOUT)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001465 elif old_boot_id:
1466 if self.get_boot_id() == old_boot_id:
Tom Wai-Hong Tam01792682015-01-06 08:00:46 +08001467 logging.error('client not rebooted (boot %s)',
1468 old_boot_id)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001469 raise error.TestFail(
Tom Wai-Hong Tam01792682015-01-06 08:00:46 +08001470 'client is back up, but did not reboot')
Simran Basid5e5e272012-09-24 15:23:59 -07001471
1472
1473 @staticmethod
1474 def check_for_rpm_support(hostname):
1475 """For a given hostname, return whether or not it is powered by an RPM.
1476
Simran Basi1df55112013-09-06 11:25:09 -07001477 @param hostname: hostname to check for rpm support.
1478
Simran Basid5e5e272012-09-24 15:23:59 -07001479 @return None if this host does not follows the defined naming format
1480 for RPM powered DUT's in the lab. If it does follow the format,
1481 it returns a regular expression MatchObject instead.
1482 """
Fang Dengbaff9082015-01-06 13:46:15 -08001483 return re.match(CrosHost._RPM_HOSTNAME_REGEX, hostname)
Simran Basid5e5e272012-09-24 15:23:59 -07001484
1485
1486 def has_power(self):
1487 """For this host, return whether or not it is powered by an RPM.
1488
1489 @return True if this host is in the CROS lab and follows the defined
1490 naming format.
1491 """
Fang Deng0ca40e22013-08-27 17:47:44 -07001492 return CrosHost.check_for_rpm_support(self.hostname)
Simran Basid5e5e272012-09-24 15:23:59 -07001493
1494
Ismail Noorbasha07fdb612013-02-14 14:13:31 -08001495 def _set_power(self, state, power_method):
Garry Wang5e5538a2019-04-08 15:36:18 -07001496 """Sets the power to the host via RPM, CCD, Servo or manual.
Ismail Noorbasha07fdb612013-02-14 14:13:31 -08001497
1498 @param state Specifies which power state to set to DUT
1499 @param power_method Specifies which method of power control to
Garry Wang5e5538a2019-04-08 15:36:18 -07001500 use. By default "RPM" or "CCD" will be used based
1501 on servo type. Valid values from
1502 POWER_CONTROL_VALID_ARGS, or None to use default.
Ismail Noorbasha07fdb612013-02-14 14:13:31 -08001503
1504 """
1505 ACCEPTABLE_STATES = ['ON', 'OFF']
1506
Garry Wang5e5538a2019-04-08 15:36:18 -07001507 if not power_method:
1508 power_method = self.get_default_power_method()
1509
1510 state = state.upper()
1511 if state not in ACCEPTABLE_STATES:
Ismail Noorbasha07fdb612013-02-14 14:13:31 -08001512 raise error.TestError('State must be one of: %s.'
1513 % (ACCEPTABLE_STATES,))
1514
1515 if power_method == self.POWER_CONTROL_SERVO:
1516 logging.info('Setting servo port J10 to %s', state)
1517 self.servo.set('prtctl3_pwren', state.lower())
1518 time.sleep(self._USB_POWER_TIMEOUT)
1519 elif power_method == self.POWER_CONTROL_MANUAL:
1520 logging.info('You have %d seconds to set the AC power to %s.',
1521 self._POWER_CYCLE_TIMEOUT, state)
1522 time.sleep(self._POWER_CYCLE_TIMEOUT)
Garry Wang5e5538a2019-04-08 15:36:18 -07001523 elif power_method == self.POWER_CONTROL_CCD:
1524 servo_role = 'src' if state == 'ON' else 'snk'
1525 logging.info('servo ccd power pass through detected,'
1526 ' changing servo_role to %s.', servo_role)
1527 self.servo.set_servo_v4_role(servo_role)
1528 if not self.ping_wait_up(timeout=self._CHANGE_SERVO_ROLE_TIMEOUT):
Garry Wang94bf9de2019-06-10 17:23:37 -07001529 # Make sure we don't leave DUT with no power(servo_role=snk)
1530 # when DUT is not pingable, as we raise a exception here
1531 # that may break a power cycle in the middle.
1532 self.servo.set_servo_v4_role('src')
Garry Wang5e5538a2019-04-08 15:36:18 -07001533 raise error.AutoservError(
1534 'DUT failed to regain network connection after %d seconds.'
1535 % self._CHANGE_SERVO_ROLE_TIMEOUT)
Ismail Noorbasha07fdb612013-02-14 14:13:31 -08001536 else:
1537 if not self.has_power():
1538 raise error.TestFail('DUT does not have RPM connected.')
Garry Wangad4d4fd2019-01-30 17:00:38 -08001539 self._add_rpm_changed_tag()
Garry Wang5e5538a2019-04-08 15:36:18 -07001540 rpm_client.set_power(self, state, timeout_mins=5)
Simran Basid5e5e272012-09-24 15:23:59 -07001541
1542
Garry Wang5e5538a2019-04-08 15:36:18 -07001543 def power_off(self, power_method=None):
1544 """Turn off power to this host via RPM, CCD, Servo or manual.
Ismail Noorbasha07fdb612013-02-14 14:13:31 -08001545
1546 @param power_method Specifies which method of power control to
Garry Wang5e5538a2019-04-08 15:36:18 -07001547 use. By default "RPM" or "CCD" will be used based
1548 on servo type. Valid values from
1549 POWER_CONTROL_VALID_ARGS, or None to use default.
Ismail Noorbasha07fdb612013-02-14 14:13:31 -08001550
1551 """
1552 self._set_power('OFF', power_method)
Simran Basid5e5e272012-09-24 15:23:59 -07001553
1554
Garry Wang5e5538a2019-04-08 15:36:18 -07001555 def power_on(self, power_method=None):
1556 """Turn on power to this host via RPM, CCD, Servo or manual.
Ismail Noorbasha07fdb612013-02-14 14:13:31 -08001557
1558 @param power_method Specifies which method of power control to
Garry Wang5e5538a2019-04-08 15:36:18 -07001559 use. By default "RPM" or "CCD" will be used based
1560 on servo type. Valid values from
1561 POWER_CONTROL_VALID_ARGS, or None to use default.
Ismail Noorbasha07fdb612013-02-14 14:13:31 -08001562
1563 """
1564 self._set_power('ON', power_method)
1565
1566
Garry Wang5e5538a2019-04-08 15:36:18 -07001567 def power_cycle(self, power_method=None):
Ismail Noorbasha07fdb612013-02-14 14:13:31 -08001568 """Cycle power to this host by turning it OFF, then ON.
1569
1570 @param power_method Specifies which method of power control to
Garry Wang5e5538a2019-04-08 15:36:18 -07001571 use. By default "RPM" or "CCD" will be used based
1572 on servo type. Valid values from
1573 POWER_CONTROL_VALID_ARGS, or None to use default.
Ismail Noorbasha07fdb612013-02-14 14:13:31 -08001574
1575 """
Garry Wang5e5538a2019-04-08 15:36:18 -07001576 if not power_method:
1577 power_method = self.get_default_power_method()
1578
Ismail Noorbasha07fdb612013-02-14 14:13:31 -08001579 if power_method in (self.POWER_CONTROL_SERVO,
Garry Wang5e5538a2019-04-08 15:36:18 -07001580 self.POWER_CONTROL_MANUAL,
1581 self.POWER_CONTROL_CCD):
Ismail Noorbasha07fdb612013-02-14 14:13:31 -08001582 self.power_off(power_method=power_method)
1583 time.sleep(self._POWER_CYCLE_TIMEOUT)
1584 self.power_on(power_method=power_method)
1585 else:
Garry Wangad4d4fd2019-01-30 17:00:38 -08001586 self._add_rpm_changed_tag()
1587 rpm_client.set_power(self, 'CYCLE')
Simran Basic6f1f7a2012-10-16 10:47:46 -07001588
1589
Mary Ruthvende14a8b2019-08-23 12:43:52 -07001590 def get_platform_from_fwid(self):
1591 """Determine the platform from the crossystem fwid.
1592
1593 @returns a string representing this host's platform.
1594 """
1595 # Look at the firmware for non-unibuild cases or if mosys fails.
1596 crossystem = utils.Crossystem(self)
1597 crossystem.init()
1598 # Extract fwid value and use the leading part as the platform id.
1599 # fwid generally follow the format of {platform}.{firmware version}
1600 # Example: Alex.X.YYY.Z or Google_Alex.X.YYY.Z
1601 platform = crossystem.fwid().split('.')[0].lower()
1602 # Newer platforms start with 'Google_' while the older ones do not.
1603 return platform.replace('google_', '')
1604
Simran Basic6f1f7a2012-10-16 10:47:46 -07001605 def get_platform(self):
1606 """Determine the correct platform label for this host.
1607
1608 @returns a string representing this host's platform.
1609 """
C Shapiroed87c6f2018-04-19 09:13:58 -06001610 release_info = utils.parse_cmd_output('cat /etc/lsb-release',
1611 run_method=self.run)
1612 unibuild = release_info.get('CHROMEOS_RELEASE_UNIBUILD') == '1'
1613 platform = ''
1614 if unibuild:
1615 cmd = 'mosys platform model'
1616 result = self.run(command=cmd, ignore_status=True)
1617 if result.exit_status == 0:
1618 platform = result.stdout.strip()
Mary Ruthvende14a8b2019-08-23 12:43:52 -07001619 return platform if platform else self.get_platform_from_fwid()
Simran Basic6f1f7a2012-10-16 10:47:46 -07001620
1621
Hung-ying Tyanb1328032014-04-01 14:18:54 +08001622 def get_architecture(self):
1623 """Determine the correct architecture label for this host.
1624
1625 @returns a string representing this host's architecture.
1626 """
1627 crossystem = utils.Crossystem(self)
1628 crossystem.init()
1629 return crossystem.arch()
1630
1631
Luis Lozano40b7d0d2014-01-17 15:12:06 -08001632 def get_chrome_version(self):
1633 """Gets the Chrome version number and milestone as strings.
1634
1635 Invokes "chrome --version" to get the version number and milestone.
1636
1637 @return A tuple (chrome_ver, milestone) where "chrome_ver" is the
1638 current Chrome version number as a string (in the form "W.X.Y.Z")
1639 and "milestone" is the first component of the version number
1640 (the "W" from "W.X.Y.Z"). If the version number cannot be parsed
1641 in the "W.X.Y.Z" format, the "chrome_ver" will be the full output
1642 of "chrome --version" and the milestone will be the empty string.
1643
1644 """
MK Ryu35d661e2014-09-25 17:44:10 -07001645 version_string = self.run(client_constants.CHROME_VERSION_COMMAND).stdout
Luis Lozano40b7d0d2014-01-17 15:12:06 -08001646 return utils.parse_chrome_version(version_string)
1647
J. Richard Barnetted2af5852016-02-05 15:03:10 -08001648
Puthikorn Voravootivatfd132172017-11-16 18:24:38 -08001649 def get_ec_version(self):
1650 """Get the ec version as strings.
1651
1652 @returns a string representing this host's ec version.
1653 """
Puthikorn Voravootivat65ad7672018-01-30 14:00:01 -08001654 command = 'mosys ec info -s fw_version'
Puthikorn Voravootivat720640d2018-02-16 17:32:38 -08001655 result = self.run(command, ignore_status=True)
1656 if result.exit_status != 0:
1657 return ''
1658 return result.stdout.strip()
Puthikorn Voravootivatfd132172017-11-16 18:24:38 -08001659
1660
1661 def get_firmware_version(self):
1662 """Get the firmware version as strings.
1663
1664 @returns a string representing this host's firmware version.
1665 """
1666 crossystem = utils.Crossystem(self)
1667 crossystem.init()
1668 return crossystem.fwid()
1669
1670
1671 def get_hardware_revision(self):
1672 """Get the hardware revision as strings.
1673
1674 @returns a string representing this host's hardware revision.
1675 """
Puthikorn Voravootivat65ad7672018-01-30 14:00:01 -08001676 command = 'mosys platform version'
Puthikorn Voravootivat720640d2018-02-16 17:32:38 -08001677 result = self.run(command, ignore_status=True)
1678 if result.exit_status != 0:
1679 return ''
1680 return result.stdout.strip()
Puthikorn Voravootivatfd132172017-11-16 18:24:38 -08001681
1682
1683 def get_kernel_version(self):
1684 """Get the kernel version as strings.
1685
1686 @returns a string representing this host's kernel version.
1687 """
1688 return self.run('uname -r').stdout.strip()
1689
1690
Puthikorn Voravootivat54aa53c2018-03-01 19:00:25 -08001691 def get_cpu_name(self):
1692 """Get the cpu name as strings.
1693
1694 @returns a string representing this host's cpu name.
1695 """
1696
1697 # Try get cpu name from device tree first
1698 if self.path_exists('/proc/device-tree/compatible'):
1699 command = ' | '.join(
1700 ["sed -e 's/\\x0/\\n/g' /proc/device-tree/compatible",
1701 'tail -1'])
1702 return self.run(command).stdout.strip().replace(',', ' ')
1703
1704 # Get cpu name from uname -p
1705 command = 'uname -p'
1706 ret = self.run(command).stdout.strip()
1707
1708 # 'uname -p' return variant of unknown or amd64 or x86_64 or i686
1709 # Try get cpu name from /proc/cpuinfo instead
1710 if re.match("unknown|amd64|[ix][0-9]?86(_64)?", ret, re.IGNORECASE):
1711 command = "grep model.name /proc/cpuinfo | cut -f 2 -d: | head -1"
1712 self = self.run(command).stdout.strip()
1713
1714 # Remove bloat from CPU name, for example
1715 # Intel(R) Core(TM) i5-7Y57 CPU @ 1.20GHz -> Intel Core i5-7Y57
1716 # Intel(R) Xeon(R) CPU E5-2690 v4 @ 2.60GHz -> Intel Xeon E5-2690 v4
1717 # AMD A10-7850K APU with Radeon(TM) R7 Graphics -> AMD A10-7850K
1718 # AMD GX-212JC SOC with Radeon(TM) R2E Graphics -> AMD GX-212JC
1719 trim_re = r' (@|processor|apu|soc|radeon).*|\(.*?\)| cpu'
1720 return re.sub(trim_re, '', ret, flags=re.IGNORECASE)
1721
1722
1723 def get_screen_resolution(self):
1724 """Get the screen(s) resolution as strings.
1725 In case of more than 1 monitor, return resolution for each monitor
1726 separate with plus sign.
1727
1728 @returns a string representing this host's screen(s) resolution.
1729 """
1730 command = 'for f in /sys/class/drm/*/*/modes; do head -1 $f; done'
1731 ret = self.run(command, ignore_status=True)
1732 # We might have Chromebox without a screen
1733 if ret.exit_status != 0:
1734 return ''
1735 return ret.stdout.strip().replace('\n', '+')
1736
1737
1738 def get_mem_total_gb(self):
1739 """Get total memory available in the system in GiB (2^20).
1740
1741 @returns an integer representing total memory
1742 """
1743 mem_total_kb = self.read_from_meminfo('MemTotal')
1744 kb_in_gb = float(2 ** 20)
1745 return int(round(mem_total_kb / kb_in_gb))
1746
1747
1748 def get_disk_size_gb(self):
1749 """Get size of disk in GB (10^9)
1750
1751 @returns an integer representing size of disk, 0 in Error Case
1752 """
1753 command = 'grep $(rootdev -s -d | cut -f3 -d/)$ /proc/partitions'
1754 result = self.run(command, ignore_status=True)
1755 if result.exit_status != 0:
1756 return 0
1757 _, _, block, _ = re.split(r' +', result.stdout.strip())
1758 byte_per_block = 1024.0
1759 disk_kb_in_gb = 1e9
1760 return int(int(block) * byte_per_block / disk_kb_in_gb + 0.5)
1761
1762
1763 def get_battery_size(self):
1764 """Get size of battery in Watt-hour via sysfs
1765
1766 This method assumes that battery support voltage_min_design and
1767 charge_full_design sysfs.
1768
1769 @returns a float representing Battery size, 0 if error.
1770 """
1771 # sysfs report data in micro scale
1772 battery_scale = 1e6
1773
1774 command = 'cat /sys/class/power_supply/*/voltage_min_design'
1775 result = self.run(command, ignore_status=True)
1776 if result.exit_status != 0:
1777 return 0
1778 voltage = float(result.stdout.strip()) / battery_scale
1779
1780 command = 'cat /sys/class/power_supply/*/charge_full_design'
1781 result = self.run(command, ignore_status=True)
1782 if result.exit_status != 0:
1783 return 0
1784 amphereHour = float(result.stdout.strip()) / battery_scale
1785
1786 return voltage * amphereHour
1787
1788
1789 def get_low_battery_shutdown_percent(self):
1790 """Get the percent-based low-battery shutdown threshold.
1791
1792 @returns a float representing low-battery shutdown percent, 0 if error.
1793 """
1794 ret = 0.0
1795 try:
1796 command = 'check_powerd_config --low_battery_shutdown_percent'
1797 ret = float(self.run(command).stdout)
1798 except error.CmdError:
1799 logging.debug("Can't run %s", command)
1800 except ValueError:
1801 logging.debug("Didn't get number from %s", command)
1802
1803 return ret
1804
1805
Puthikorn Voravootivat09c83d72018-08-10 15:58:32 -07001806 def has_hammer(self):
1807 """Check whether DUT has hammer device or not.
1808
1809 @returns boolean whether device has hammer or not
1810 """
1811 command = 'grep Hammer /sys/bus/usb/devices/*/product'
1812 return self.run(command, ignore_status=True).exit_status == 0
1813
1814
Niranjan Kumar34618872017-05-31 12:57:09 -07001815 def is_chrome_switch_present(self, switch):
David Haddock3ce538e2017-06-22 13:37:05 -07001816 """Returns True if the specified switch was provided to Chrome.
1817
1818 @param switch The chrome switch to search for.
1819 """
Niranjan Kumar34618872017-05-31 12:57:09 -07001820
Niranjan Kumar5f23fe92017-06-22 15:18:55 -07001821 command = 'pgrep -x -f -c "/opt/google/chrome/chrome.*%s.*"' % switch
1822 return self.run(command, ignore_status=True).exit_status == 0
Niranjan Kumar34618872017-05-31 12:57:09 -07001823
1824
1825 def oobe_triggers_update(self):
1826 """Returns True if this host has an OOBE flow during which
1827 it will perform an update check and perhaps an update.
1828 One example of such a flow is Hands-Off Zero-Touch Enrollment.
1829 As more such flows are developed, code handling them needs
1830 to be added here.
1831
1832 @return Boolean indicating whether this host's OOBE triggers an update.
1833 """
1834 return self.is_chrome_switch_present(
1835 '--enterprise-enable-zero-touch-enrollment=hands-off')
1836
1837
Kevin Chenga2619dc2016-03-28 11:42:08 -07001838 # TODO(kevcheng): change this to just return the board without the
1839 # 'board:' prefix and fix up all the callers. Also look into removing the
1840 # need for this method.
Simran Basic6f1f7a2012-10-16 10:47:46 -07001841 def get_board(self):
1842 """Determine the correct board label for this host.
1843
1844 @returns a string representing this host's board.
1845 """
1846 release_info = utils.parse_cmd_output('cat /etc/lsb-release',
1847 run_method=self.run)
J. Richard Barnetted2af5852016-02-05 15:03:10 -08001848 return (ds_constants.BOARD_PREFIX +
1849 release_info['CHROMEOS_RELEASE_BOARD'])
Simran Basic6f1f7a2012-10-16 10:47:46 -07001850
Po-Hsien Wang4618adf2017-10-10 14:40:21 -07001851 def get_channel(self):
1852 """Determine the correct channel label for this host.
Simran Basic6f1f7a2012-10-16 10:47:46 -07001853
Po-Hsien Wang4618adf2017-10-10 14:40:21 -07001854 @returns: a string represeting this host's build channel.
1855 (stable, dev, beta). None on fail.
1856 """
1857 return lsbrelease_utils.get_chromeos_channel(
1858 lsb_release_content=self._get_lsb_release_content())
Kevin Chenga328da62016-03-31 10:49:04 -07001859
Kevin Chenga328da62016-03-31 10:49:04 -07001860 def get_power_supply(self):
1861 """
1862 Determine what type of power supply the host has
1863
1864 @returns a string representing this host's power supply.
1865 'power:battery' when the device has a battery intended for
1866 extended use
1867 'power:AC_primary' when the device has a battery not intended
1868 for extended use (for moving the machine, etc)
1869 'power:AC_only' when the device has no battery at all.
1870 """
1871 psu = self.run(command='mosys psu type', ignore_status=True)
1872 if psu.exit_status:
1873 # The psu command for mosys is not included for all platforms. The
1874 # assumption is that the device will have a battery if the command
1875 # is not found.
1876 return 'power:battery'
1877
1878 psu_str = psu.stdout.strip()
1879 if psu_str == 'unknown':
1880 return None
1881
1882 return 'power:%s' % psu_str
1883
1884
Puthikorn Voravootivat54aa53c2018-03-01 19:00:25 -08001885 def has_battery(self):
1886 """Determine if DUT has a battery.
1887
1888 Returns:
1889 Boolean, False if known not to have battery, True otherwise.
1890 """
1891 rv = True
1892 power_supply = self.get_power_supply()
1893 if power_supply == 'power:battery':
1894 _NO_BATTERY_BOARD_TYPE = ['CHROMEBOX', 'CHROMEBIT', 'CHROMEBASE']
1895 board_type = self.get_board_type()
1896 if board_type in _NO_BATTERY_BOARD_TYPE:
1897 logging.warn('Do NOT believe type %s has battery. '
1898 'See debug for mosys details', board_type)
1899 psu = self.system_output('mosys -vvvv psu type',
1900 ignore_status=True)
1901 logging.debug(psu)
1902 rv = False
1903 elif power_supply == 'power:AC_only':
1904 rv = False
1905
1906 return rv
1907
1908
Kevin Chenga328da62016-03-31 10:49:04 -07001909 def get_servo(self):
1910 """Determine if the host has a servo attached.
1911
1912 If the host has a working servo attached, it should have a servo label.
1913
1914 @return: string 'servo' if the host has servo attached. Otherwise,
1915 returns None.
1916 """
1917 return 'servo' if self._servo_host else None
1918
1919
Kevin Chenga328da62016-03-31 10:49:04 -07001920 def has_internal_display(self):
1921 """Determine if the device under test is equipped with an internal
1922 display.
1923
1924 @return: 'internal_display' if one is present; None otherwise.
1925 """
1926 from autotest_lib.client.cros.graphics import graphics_utils
1927 from autotest_lib.client.common_lib import utils as common_utils
1928
1929 def __system_output(cmd):
1930 return self.run(cmd).stdout
1931
1932 def __read_file(remote_path):
1933 return self.run('cat %s' % remote_path).stdout
1934
1935 # Hijack the necessary client functions so that we can take advantage
1936 # of the client lib here.
1937 # FIXME: find a less hacky way than this
1938 original_system_output = utils.system_output
1939 original_read_file = common_utils.read_file
1940 utils.system_output = __system_output
1941 common_utils.read_file = __read_file
1942 try:
1943 return ('internal_display' if graphics_utils.has_internal_display()
1944 else None)
1945 finally:
1946 utils.system_output = original_system_output
1947 common_utils.read_file = original_read_file
1948
1949
Dan Shi85276d42014-04-08 22:11:45 -07001950 def is_boot_from_usb(self):
1951 """Check if DUT is boot from USB.
1952
1953 @return: True if DUT is boot from usb.
1954 """
1955 device = self.run('rootdev -s -d').stdout.strip()
1956 removable = int(self.run('cat /sys/block/%s/removable' %
1957 os.path.basename(device)).stdout.strip())
1958 return removable == 1
Helen Zhang17dae2b2014-11-11 09:25:52 -08001959
1960
1961 def read_from_meminfo(self, key):
Dan Shi49ca0932014-11-14 11:22:27 -08001962 """Return the memory info from /proc/meminfo
Helen Zhang17dae2b2014-11-11 09:25:52 -08001963
1964 @param key: meminfo requested
1965
1966 @return the memory value as a string
1967
1968 """
Helen Zhang17dae2b2014-11-11 09:25:52 -08001969 meminfo = self.run('grep %s /proc/meminfo' % key).stdout.strip()
1970 logging.debug('%s', meminfo)
1971 return int(re.search(r'\d+', meminfo).group(0))
Rohit Makasana8a4923c2015-08-13 17:04:26 -07001972
1973
Rohit Makasana98e696f2016-06-03 18:48:10 -07001974 def get_cpu_arch(self):
1975 """Returns CPU arch of the device.
1976
1977 @return CPU architecture of the DUT.
1978 """
Allen Li2c32d6b2017-02-03 15:28:10 -08001979 # Add CPUs by following logic in client/bin/utils.py.
Rohit Makasana98e696f2016-06-03 18:48:10 -07001980 if self.run("grep '^flags.*:.* lm .*' /proc/cpuinfo",
1981 ignore_status=True).stdout:
1982 return 'x86_64'
1983 if self.run("grep -Ei 'ARM|CPU implementer' /proc/cpuinfo",
1984 ignore_status=True).stdout:
1985 return 'arm'
1986 return 'i386'
1987
1988
Rohit Makasana8a4923c2015-08-13 17:04:26 -07001989 def get_board_type(self):
1990 """
1991 Get the DUT's device type from /etc/lsb-release.
Danny Chan471a8d12015-08-18 14:57:41 -07001992 DEVICETYPE can be one of CHROMEBOX, CHROMEBASE, CHROMEBOOK or more.
1993
1994 @return value of DEVICETYPE param from lsb-release.
Rohit Makasana8a4923c2015-08-13 17:04:26 -07001995 """
Danny Chan471a8d12015-08-18 14:57:41 -07001996 device_type = self.run('grep DEVICETYPE /etc/lsb-release',
1997 ignore_status=True).stdout
1998 if device_type:
Kalin Stoyanov524310b2015-08-21 16:24:04 -07001999 return device_type.split('=')[-1].strip()
Danny Chan471a8d12015-08-18 14:57:41 -07002000 return ''
Gilad Arnolda76bef02015-09-29 13:55:15 -07002001
2002
Rohit Makasanadf0a3a32017-06-30 13:55:18 -07002003 def get_arc_version(self):
2004 """Return ARC version installed on the DUT.
2005
2006 @returns ARC version as string if the CrOS build has ARC, else None.
2007 """
2008 arc_version = self.run('grep CHROMEOS_ARC_VERSION /etc/lsb-release',
2009 ignore_status=True).stdout
2010 if arc_version:
2011 return arc_version.split('=')[-1].strip()
2012 return None
2013
2014
Gilad Arnolda76bef02015-09-29 13:55:15 -07002015 def get_os_type(self):
2016 return 'cros'
Simran Basia5522a32015-10-06 11:01:24 -07002017
2018
Kevin Chenga2619dc2016-03-28 11:42:08 -07002019 def get_labels(self):
Kevin Chengf8660142016-08-12 10:17:41 -07002020 """Return the detected labels on the host."""
Kevin Chenga2619dc2016-03-28 11:42:08 -07002021 return self.labels.get_labels(self)
Garry Wang5e5538a2019-04-08 15:36:18 -07002022
2023
2024 def get_default_power_method(self):
2025 """
2026 Get the default power method for power_on/off/cycle() methods.
2027 @return POWER_CONTROL_RPM or POWER_CONTROL_CCD
2028 """
2029 if not self._default_power_method:
Garry Wang1a004aa2019-05-16 22:56:51 -07002030 self._default_power_method = self.POWER_CONTROL_RPM
Ruben Rodriguez Buchillon3eeeab32019-10-02 15:29:58 -07002031 if self.servo and self.servo.supports_built_in_pd_control():
2032 self._default_power_method = self.POWER_CONTROL_CCD
2033 else:
2034 logging.debug('Either servo is unitialized or the servo '
2035 'setup does not support pd controls. Falling '
2036 'back to default RPM method.')
Garry Wang5e5538a2019-04-08 15:36:18 -07002037 return self._default_power_method