blob: d798210d9158be5d1e2807d61bf651aa06ed2f5a [file] [log] [blame]
J. Richard Barnette24adbf42012-04-11 15:04:53 -07001# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
Dale Curtisaa5eedb2011-08-23 16:18:52 -07002# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
Aviv Keshet74c89a92013-02-04 15:18:30 -08005import functools
Darren Krahn0bd18e82015-10-28 23:30:46 +00006import json
J. Richard Barnette1d78b012012-05-15 13:56:30 -07007import logging
Dan Shi0f466e82013-02-22 15:44:58 -08008import os
Simran Basid5e5e272012-09-24 15:23:59 -07009import re
J. Richard Barnette134ec2c2012-04-25 12:59:37 -070010import time
11
mussa584b4462014-06-20 15:13:28 -070012import common
J. Richard Barnette45e93de2012-04-11 17:24:15 -070013from autotest_lib.client.bin import utils
Dan Shi9cb0eec2014-06-03 09:04:50 -070014from autotest_lib.client.common_lib import autotemp
Richard Barnette0c73ffc2012-11-19 15:21:18 -080015from autotest_lib.client.common_lib import error
16from autotest_lib.client.common_lib import global_config
Dan Shi549fb822015-03-24 18:01:11 -070017from autotest_lib.client.common_lib import lsbrelease_utils
J. Richard Barnette45e93de2012-04-11 17:24:15 -070018from autotest_lib.client.common_lib.cros import autoupdater
Richard Barnette03a0c132012-11-05 12:40:35 -080019from autotest_lib.client.common_lib.cros import dev_server
Gabe Blackb72f4fb2015-01-20 16:47:13 -080020from autotest_lib.client.common_lib.cros.graphite import autotest_es
Gabe Black1e1c41b2015-02-04 23:55:15 -080021from autotest_lib.client.common_lib.cros.graphite import autotest_stats
Hsinyu Chaoe0b08e62015-08-11 10:50:37 +000022from autotest_lib.client.cros import constants as client_constants
J. Richard Barnette84890bd2014-02-21 11:05:47 -080023from autotest_lib.client.cros import cros_ui
Cheng-Yi Chiangf4104ff2014-12-23 19:39:01 +080024from autotest_lib.client.cros.audio import cras_utils
Katherine Threlkeldab83d392015-06-18 16:45:57 -070025from autotest_lib.client.cros.input_playback import input_playback
Mussa5b589052015-10-26 17:55:26 -070026from autotest_lib.client.cros.video import constants as video_test_constants
Simran Basi5ace6f22016-01-06 17:30:44 -080027from autotest_lib.server import afe_utils
MK Ryu35d661e2014-09-25 17:44:10 -070028from autotest_lib.server import autoserv_parser
29from autotest_lib.server import autotest
30from autotest_lib.server import constants
31from autotest_lib.server import crashcollect
Dan Shia1ecd5c2013-06-06 11:21:31 -070032from autotest_lib.server import utils as server_utils
Dan Shi9cb0eec2014-06-03 09:04:50 -070033from autotest_lib.server.cros import provision
Scott Zawalski89c44dd2013-02-26 09:28:02 -050034from autotest_lib.server.cros.dynamic_suite import constants as ds_constants
Simran Basi5e6339a2013-03-21 11:34:32 -070035from autotest_lib.server.cros.dynamic_suite import tools, frontend_wrappers
Dan Shi9cb0eec2014-06-03 09:04:50 -070036from autotest_lib.server.cros.faft.config.config import Config as FAFTConfig
Scottfe06ed82015-11-05 17:15:01 -080037from autotest_lib.server.cros.servo import plankton
Fang Deng96667ca2013-08-01 17:46:18 -070038from autotest_lib.server.hosts import abstract_ssh
Tom Wai-Hong Tamefe1c7f2014-01-02 14:00:11 +080039from autotest_lib.server.hosts import chameleon_host
Scottfe06ed82015-11-05 17:15:01 -080040from autotest_lib.server.hosts import plankton_host
Fang Deng5d518f42013-08-02 14:04:32 -070041from autotest_lib.server.hosts import servo_host
Simran Basidcff4252012-11-20 16:13:20 -080042from autotest_lib.site_utils.rpm_control_system import rpm_client
Simran Basid5e5e272012-09-24 15:23:59 -070043
44
Dan Shib8540a52015-07-16 14:18:23 -070045CONFIG = global_config.global_config
46
Eric Carusoee673ac2015-08-05 17:03:04 -070047LUCID_SLEEP_BOARDS = ['samus', 'lulu']
48
Dan Shid07ee2e2015-09-24 14:49:25 -070049# A file to indicate provision failure and require Repair job to powerwash the
50# dut.
51PROVISION_FAILED = '/var/tmp/provision_failed'
52
beepsc87ff602013-07-31 21:53:00 -070053class FactoryImageCheckerException(error.AutoservError):
54 """Exception raised when an image is a factory image."""
55 pass
56
57
Fang Deng0ca40e22013-08-27 17:47:44 -070058class CrosHost(abstract_ssh.AbstractSSHHost):
J. Richard Barnette45e93de2012-04-11 17:24:15 -070059 """Chromium OS specific subclass of Host."""
60
Simran Basi5ace6f22016-01-06 17:30:44 -080061 VERSION_PREFIX = provision.CROS_VERSION_PREFIX
62
J. Richard Barnette45e93de2012-04-11 17:24:15 -070063 _parser = autoserv_parser.autoserv_parser
Scott Zawalski62bacae2013-03-05 10:40:32 -050064 _AFE = frontend_wrappers.RetryingAFE(timeout_min=5, delay_sec=10)
J. Richard Barnette45e93de2012-04-11 17:24:15 -070065
Richard Barnette03a0c132012-11-05 12:40:35 -080066 # Timeout values (in seconds) associated with various Chrome OS
67 # state changes.
J. Richard Barnette134ec2c2012-04-25 12:59:37 -070068 #
Richard Barnette0c73ffc2012-11-19 15:21:18 -080069 # In general, a good rule of thumb is that the timeout can be up
70 # to twice the typical measured value on the slowest platform.
71 # The times here have not necessarily been empirically tested to
72 # meet this criterion.
J. Richard Barnetteeb69d722012-06-18 17:29:44 -070073 #
74 # SLEEP_TIMEOUT: Time to allow for suspend to memory.
Richard Barnette0c73ffc2012-11-19 15:21:18 -080075 # RESUME_TIMEOUT: Time to allow for resume after suspend, plus
76 # time to restart the netwowrk.
J. Richard Barnette84890bd2014-02-21 11:05:47 -080077 # SHUTDOWN_TIMEOUT: Time to allow for shut down.
J. Richard Barnetteeb69d722012-06-18 17:29:44 -070078 # BOOT_TIMEOUT: Time to allow for boot from power off. Among
Richard Barnette0c73ffc2012-11-19 15:21:18 -080079 # other things, this must account for the 30 second dev-mode
J. Richard Barnette417cc792015-10-01 09:56:36 -070080 # screen delay, time to start the network on the DUT, and the
81 # ssh timeout of 120 seconds.
J. Richard Barnetteeb69d722012-06-18 17:29:44 -070082 # USB_BOOT_TIMEOUT: Time to allow for boot from a USB device,
Richard Barnette0c73ffc2012-11-19 15:21:18 -080083 # including the 30 second dev-mode delay and time to start the
J. Richard Barnetted4649c62013-03-06 17:42:27 -080084 # network.
beepsf079cfb2013-09-18 17:49:51 -070085 # INSTALL_TIMEOUT: Time to allow for chromeos-install.
J. Richard Barnette84890bd2014-02-21 11:05:47 -080086 # POWERWASH_BOOT_TIMEOUT: Time to allow for a reboot that
87 # includes powerwash.
J. Richard Barnetteeb69d722012-06-18 17:29:44 -070088
89 SLEEP_TIMEOUT = 2
J. Richard Barnetted4649c62013-03-06 17:42:27 -080090 RESUME_TIMEOUT = 10
Tom Wai-Hong Tamfe005c22014-12-03 09:25:44 +080091 SHUTDOWN_TIMEOUT = 10
J. Richard Barnette417cc792015-10-01 09:56:36 -070092 BOOT_TIMEOUT = 150
J. Richard Barnette5bab5f52015-08-03 13:14:38 -070093 USB_BOOT_TIMEOUT = 300
J. Richard Barnette7817b052014-08-28 09:47:29 -070094 INSTALL_TIMEOUT = 480
Dan Shi2c88eed2013-11-12 10:18:38 -080095 POWERWASH_BOOT_TIMEOUT = 60
Chris Sosab76e0ee2013-05-22 16:55:41 -070096
Dan Shica503482015-03-30 17:23:25 -070097 # Minimum OS version that supports server side packaging. Older builds may
98 # not have server side package built or with Autotest code change to support
99 # server-side packaging.
Dan Shib8540a52015-07-16 14:18:23 -0700100 MIN_VERSION_SUPPORT_SSP = CONFIG.get_config_value(
Dan Shiced09e42015-04-17 16:09:34 -0700101 'AUTOSERV', 'min_version_support_ssp', type=int)
Dan Shica503482015-03-30 17:23:25 -0700102
J. Richard Barnette84890bd2014-02-21 11:05:47 -0800103 # REBOOT_TIMEOUT: How long to wait for a reboot.
104 #
Chris Sosab76e0ee2013-05-22 16:55:41 -0700105 # We have a long timeout to ensure we don't flakily fail due to other
106 # issues. Shorter timeouts are vetted in platform_RebootAfterUpdate.
Simran Basi1160e2c2013-10-04 16:00:24 -0700107 # TODO(sbasi - crbug.com/276094) Restore to 5 mins once the 'host did not
108 # return from reboot' bug is solved.
109 REBOOT_TIMEOUT = 480
Chris Sosab76e0ee2013-05-22 16:55:41 -0700110
Ismail Noorbasha07fdb612013-02-14 14:13:31 -0800111 # _USB_POWER_TIMEOUT: Time to allow for USB to power toggle ON and OFF.
112 # _POWER_CYCLE_TIMEOUT: Time to allow for manual power cycle.
113 _USB_POWER_TIMEOUT = 5
114 _POWER_CYCLE_TIMEOUT = 10
115
Dan Shib8540a52015-07-16 14:18:23 -0700116 _RPM_RECOVERY_BOARDS = CONFIG.get_config_value('CROS',
Richard Barnette82c35912012-11-20 10:09:10 -0800117 'rpm_recovery_boards', type=str).split(',')
118
119 _MAX_POWER_CYCLE_ATTEMPTS = 6
120 _LAB_MACHINE_FILE = '/mnt/stateful_partition/.labmachine'
Fang Dengdeba14f2014-11-14 11:54:09 -0800121 _RPM_HOSTNAME_REGEX = ('chromeos(\d+)(-row(\d+))?-rack(\d+[a-z]*)'
122 '-host(\d+)')
Katherine Threlkeldab83d392015-06-18 16:45:57 -0700123 _LIGHTSENSOR_FILES = [ "in_illuminance0_input",
124 "in_illuminance_input",
125 "in_illuminance0_raw",
126 "in_illuminance_raw",
127 "illuminance0_input"]
Richard Barnette82c35912012-11-20 10:09:10 -0800128 _LIGHTSENSOR_SEARCH_DIR = '/sys/bus/iio/devices'
129 _LABEL_FUNCTIONS = []
Aviv Keshet74c89a92013-02-04 15:18:30 -0800130 _DETECTABLE_LABELS = []
Kevin Cheng3a4a57a2015-09-30 12:09:50 -0700131 label_decorator = functools.partial(server_utils.add_label_detector,
132 _LABEL_FUNCTIONS,
Aviv Keshet74c89a92013-02-04 15:18:30 -0800133 _DETECTABLE_LABELS)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -0700134
J. Richard Barnetteb6de7e32013-02-14 13:28:04 -0800135 # Constants used in ping_wait_up() and ping_wait_down().
136 #
137 # _PING_WAIT_COUNT is the approximate number of polling
138 # cycles to use when waiting for a host state change.
139 #
140 # _PING_STATUS_DOWN and _PING_STATUS_UP are names used
141 # for arguments to the internal _ping_wait_for_status()
142 # method.
143 _PING_WAIT_COUNT = 40
144 _PING_STATUS_DOWN = False
145 _PING_STATUS_UP = True
146
Ismail Noorbasha07fdb612013-02-14 14:13:31 -0800147 # Allowed values for the power_method argument.
148
149 # POWER_CONTROL_RPM: Passed as default arg for power_off/on/cycle() methods.
150 # POWER_CONTROL_SERVO: Used in set_power() and power_cycle() methods.
151 # POWER_CONTROL_MANUAL: Used in set_power() and power_cycle() methods.
152 POWER_CONTROL_RPM = 'RPM'
153 POWER_CONTROL_SERVO = 'servoj10'
154 POWER_CONTROL_MANUAL = 'manual'
155
156 POWER_CONTROL_VALID_ARGS = (POWER_CONTROL_RPM,
157 POWER_CONTROL_SERVO,
158 POWER_CONTROL_MANUAL)
Richard Barnette0c73ffc2012-11-19 15:21:18 -0800159
Simran Basi5e6339a2013-03-21 11:34:32 -0700160 _RPM_OUTLET_CHANGED = 'outlet_changed'
161
Dan Shi9cb0eec2014-06-03 09:04:50 -0700162 # URL pattern to download firmware image.
Dan Shib8540a52015-07-16 14:18:23 -0700163 _FW_IMAGE_URL_PATTERN = CONFIG.get_config_value(
Dan Shi9cb0eec2014-06-03 09:04:50 -0700164 'CROS', 'firmware_url_pattern', type=str)
beeps687243d2013-07-18 15:29:27 -0700165
MK Ryu35d661e2014-09-25 17:44:10 -0700166 # File that has a list of directories to be collected
167 _LOGS_TO_COLLECT_FILE = os.path.join(
168 common.client_dir, 'common_lib', 'logs_to_collect')
169
170 # Prefix of logging message w.r.t. crash collection
171 _CRASHLOGS_PREFIX = 'collect_crashlogs'
172
173 # Time duration waiting for host up/down check
174 _CHECK_HOST_UP_TIMEOUT_SECS = 15
175
176 # A command that interacts with kernel and hardware (e.g., rm, mkdir, etc)
177 # might not be completely done deep through the hardware when the machine
178 # is powered down right after the command returns.
179 # We should wait for a few seconds to make them done. Finger crossed.
180 _SAFE_WAIT_SECS = 10
181
182
J. Richard Barnette964fba02012-10-24 17:34:29 -0700183 @staticmethod
beeps46dadc92013-11-07 14:07:10 -0800184 def check_host(host, timeout=10):
185 """
186 Check if the given host is a chrome-os host.
187
188 @param host: An ssh host representing a device.
189 @param timeout: The timeout for the run command.
190
191 @return: True if the host device is chromeos.
192
beeps46dadc92013-11-07 14:07:10 -0800193 """
194 try:
Simran Basi933c8af2015-04-29 14:05:07 -0700195 result = host.run(
196 'grep -q CHROMEOS /etc/lsb-release && '
197 '! test -f /mnt/stateful_partition/.android_tester && '
198 '! grep -q moblab /etc/lsb-release',
199 ignore_status=True, timeout=timeout)
beeps46dadc92013-11-07 14:07:10 -0800200 except (error.AutoservRunError, error.AutoservSSHTimeout):
201 return False
202 return result.exit_status == 0
203
204
205 @staticmethod
Tom Wai-Hong Tamefe1c7f2014-01-02 14:00:11 +0800206 def _extract_arguments(args_dict, key_subset):
207 """Extract options from `args_dict` and return a subset result.
J. Richard Barnette7214e0b2013-02-06 15:20:49 -0800208
209 Take the provided dictionary of argument options and return
Tom Wai-Hong Tamefe1c7f2014-01-02 14:00:11 +0800210 a subset that represent standard arguments needed to construct
211 a test-assistant object (chameleon or servo) for a host. The
212 intent is to provide standard argument processing from
Christopher Wiley644ef3e2015-05-15 13:14:14 -0700213 CrosHost for tests that require a test-assistant board
Tom Wai-Hong Tamefe1c7f2014-01-02 14:00:11 +0800214 to operate.
215
216 @param args_dict Dictionary from which to extract the arguments.
217 @param key_subset Tuple of keys to extract from the args_dict, e.g.
218 ('servo_host', 'servo_port').
219 """
220 result = {}
221 for arg in key_subset:
222 if arg in args_dict:
223 result[arg] = args_dict[arg]
224 return result
225
226
227 @staticmethod
228 def get_chameleon_arguments(args_dict):
229 """Extract chameleon options from `args_dict` and return the result.
230
231 Recommended usage:
232 ~~~~~~~~
233 args_dict = utils.args_to_dict(args)
234 chameleon_args = hosts.CrosHost.get_chameleon_arguments(args_dict)
235 host = hosts.create_host(machine, chameleon_args=chameleon_args)
236 ~~~~~~~~
237
238 @param args_dict Dictionary from which to extract the chameleon
239 arguments.
240 """
241 return CrosHost._extract_arguments(
242 args_dict, ('chameleon_host', 'chameleon_port'))
243
244
245 @staticmethod
Scottfe06ed82015-11-05 17:15:01 -0800246 def get_plankton_arguments(args_dict):
247 """Extract chameleon options from `args_dict` and return the result.
248
249 Recommended usage:
250 ~~~~~~~~
251 args_dict = utils.args_to_dict(args)
252 plankon_args = hosts.CrosHost.get_plankton_arguments(args_dict)
253 host = hosts.create_host(machine, plankton_args=polankton_args)
254 ~~~~~~~~
255
256 @param args_dict Dictionary from which to extract the plankton
257 arguments.
258 """
259 args = CrosHost._extract_arguments(
260 args_dict, ('plankton_host', 'plankton_port'))
261 return args
262
263
264 @staticmethod
Tom Wai-Hong Tamefe1c7f2014-01-02 14:00:11 +0800265 def get_servo_arguments(args_dict):
266 """Extract servo options from `args_dict` and return the result.
J. Richard Barnette7214e0b2013-02-06 15:20:49 -0800267
268 Recommended usage:
269 ~~~~~~~~
270 args_dict = utils.args_to_dict(args)
Fang Deng0ca40e22013-08-27 17:47:44 -0700271 servo_args = hosts.CrosHost.get_servo_arguments(args_dict)
J. Richard Barnette7214e0b2013-02-06 15:20:49 -0800272 host = hosts.create_host(machine, servo_args=servo_args)
273 ~~~~~~~~
274
275 @param args_dict Dictionary from which to extract the servo
276 arguments.
277 """
Tom Wai-Hong Tamefe1c7f2014-01-02 14:00:11 +0800278 return CrosHost._extract_arguments(
279 args_dict, ('servo_host', 'servo_port'))
J. Richard Barnette134ec2c2012-04-25 12:59:37 -0700280
J. Richard Barnette964fba02012-10-24 17:34:29 -0700281
Scottfe06ed82015-11-05 17:15:01 -0800282 def _initialize(self, hostname, chameleon_args=None, servo_args=None, plankton_args=None,
Fang Denge545abb2014-12-30 18:43:47 -0800283 try_lab_servo=False, ssh_verbosity_flag='', ssh_options='',
Fang Dengd1c2b732013-08-20 12:59:46 -0700284 *args, **dargs):
Tom Wai-Hong Tamefe1c7f2014-01-02 14:00:11 +0800285 """Initialize superclasses, |self.chameleon|, and |self.servo|.
J. Richard Barnette67ccb872012-04-19 16:34:56 -0700286
Fang Denge545abb2014-12-30 18:43:47 -0800287 This method will attempt to create the test-assistant object
288 (chameleon/servo) when it is needed by the test. Check
289 the docstring of chameleon_host.create_chameleon_host and
290 servo_host.create_servo_host for how this is determined.
Fang Deng5d518f42013-08-02 14:04:32 -0700291
Fang Denge545abb2014-12-30 18:43:47 -0800292 @param hostname: Hostname of the dut.
293 @param chameleon_args: A dictionary that contains args for creating
294 a ChameleonHost. See chameleon_host for details.
295 @param servo_args: A dictionary that contains args for creating
296 a ServoHost object. See servo_host for details.
297 @param try_lab_servo: Boolean, False indicates that ServoHost should
298 not be created for a device in Cros test lab.
299 See servo_host for details.
300 @param ssh_verbosity_flag: String, to pass to the ssh command to control
301 verbosity.
302 @param ssh_options: String, other ssh options to pass to the ssh
303 command.
J. Richard Barnette67ccb872012-04-19 16:34:56 -0700304 """
Fang Deng0ca40e22013-08-27 17:47:44 -0700305 super(CrosHost, self)._initialize(hostname=hostname,
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700306 *args, **dargs)
J. Richard Barnettef0859852012-08-20 14:55:50 -0700307 # self.env is a dictionary of environment variable settings
308 # to be exported for commands run on the host.
309 # LIBC_FATAL_STDERR_ can be useful for diagnosing certain
310 # errors that might happen.
311 self.env['LIBC_FATAL_STDERR_'] = '1'
Fang Dengd1c2b732013-08-20 12:59:46 -0700312 self._ssh_verbosity_flag = ssh_verbosity_flag
Aviv Keshetc5947fa2013-09-04 14:06:29 -0700313 self._ssh_options = ssh_options
Fang Deng5d518f42013-08-02 14:04:32 -0700314 # TODO(fdeng): We need to simplify the
315 # process of servo and servo_host initialization.
316 # crbug.com/298432
Fang Denge545abb2014-12-30 18:43:47 -0800317 self._servo_host = servo_host.create_servo_host(
318 dut=self.hostname, servo_args=servo_args,
319 try_lab_servo=try_lab_servo)
Tom Wai-Hong Tamefe1c7f2014-01-02 14:00:11 +0800320 # TODO(waihong): Do the simplication on Chameleon too.
Tom Wai-Hong Tam3d6790d2014-04-14 16:15:47 +0800321 self._chameleon_host = chameleon_host.create_chameleon_host(
322 dut=self.hostname, chameleon_args=chameleon_args)
Scottfe06ed82015-11-05 17:15:01 -0800323 # Add plankton host if plankton args were added on command line
324 self._plankton_host = plankton_host.create_plankton_host(plankton_args)
Tom Wai-Hong Tam3d6790d2014-04-14 16:15:47 +0800325
Dan Shi4d478522014-02-14 13:46:32 -0800326 if self._servo_host is not None:
327 self.servo = self._servo_host.get_servo()
328 else:
329 self.servo = None
330
Tom Wai-Hong Tam3d6790d2014-04-14 16:15:47 +0800331 if self._chameleon_host:
Tom Wai-Hong Tameaee3402014-01-22 08:52:10 +0800332 self.chameleon = self._chameleon_host.create_chameleon_board()
Tom Wai-Hong Tamefe1c7f2014-01-02 14:00:11 +0800333 else:
Tom Wai-Hong Tam3d6790d2014-04-14 16:15:47 +0800334 self.chameleon = None
Fang Deng5d518f42013-08-02 14:04:32 -0700335
Scottfe06ed82015-11-05 17:15:01 -0800336 if self._plankton_host:
337 self.plankton_servo = self._plankton_host.get_servo()
338 logging.info('plankton_servo: %r', self.plankton_servo)
339 # Create the plankton object used to access the ec uart
Scott07a848f2016-01-12 15:04:52 -0800340 self.plankton = plankton.Plankton(self.plankton_servo,
341 self._plankton_host.get_servod_server_proxy())
Scottfe06ed82015-11-05 17:15:01 -0800342 else:
Scott07a848f2016-01-12 15:04:52 -0800343 self.plankton = None
Scottfe06ed82015-11-05 17:15:01 -0800344
Fang Deng5d518f42013-08-02 14:04:32 -0700345
Dan Shi3d7a0e12015-10-12 11:55:45 -0700346 def get_repair_image_name(self, image_type='cros'):
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500347 """Generate a image_name from variables in the global config.
348
Dan Shi3d7a0e12015-10-12 11:55:45 -0700349 image_type is used to differentiate different images. Default is CrOS,
350 in which case, repair image's name follows the naming convention defined
351 in global setting CROS/stable_build_pattern.
352 If the image_type is not `cros`, the repair image will be looked up
353 using key `board_name/image_type`, e.g., daisy_spring/firmware.
354
355 @param image_type: Type of the image. Default is `cros`.
356
Dan Shi08173202015-11-12 13:08:45 -0800357 @returns a str of $board-version/$BUILD. Returns None if stable version
358 for the board and the default are both not set, e.g., stable
359 firmware version for a new board.
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500360
361 """
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500362 board = self._get_board_from_afe()
363 if board is None:
364 raise error.AutoservError('DUT has no board attribute, '
365 'cannot be repaired.')
Dan Shi3d7a0e12015-10-12 11:55:45 -0700366 if image_type != 'cros':
367 board = '%s/%s' % (board, image_type)
Dan Shi6964fa52014-12-18 11:04:27 -0800368 stable_version = self._AFE.run('get_stable_version', board=board)
Dan Shi3d7a0e12015-10-12 11:55:45 -0700369 if image_type == 'cros':
370 build_pattern = CONFIG.get_config_value(
371 'CROS', 'stable_build_pattern')
372 stable_version = build_pattern % (board, stable_version)
Dan Shi08173202015-11-12 13:08:45 -0800373 elif image_type == 'firmware':
374 # If firmware stable version is not specified, `stable_version`
375 # from the RPC is the default stable version for CrOS image.
376 # firmware stable version must be from firmware branch, thus its
377 # value must be like board-firmware/R31-1234.0.0. Check if
378 # firmware exists in the stable version, if not, return None.
379 if 'firmware' not in stable_version:
380 return None
Dan Shi3d7a0e12015-10-12 11:55:45 -0700381 return stable_version
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500382
383
Chris Sosab76e0ee2013-05-22 16:55:41 -0700384 def lookup_job_repo_url(self):
385 """Looks up the job_repo_url for the host.
386
387 @returns job_repo_url from AFE or None if not found.
388
389 @raises KeyError if the host does not have a job_repo_url
390 """
Chris Sosab76e0ee2013-05-22 16:55:41 -0700391 hosts = self._AFE.get_hosts(hostname=self.hostname)
beepsb5efc532013-06-04 11:29:34 -0700392 if hosts and ds_constants.JOB_REPO_URL in hosts[0].attributes:
393 return hosts[0].attributes[ds_constants.JOB_REPO_URL]
J. Richard Barnette85d0aac2015-08-20 10:34:39 -0700394 else:
395 return None
Chris Sosab76e0ee2013-05-22 16:55:41 -0700396
397
Simran Basi5ace6f22016-01-06 17:30:44 -0800398 def clear_job_repo_url(self):
399 """Clear host attribute job_repo_url."""
400 if not afe_utils.host_in_lab(self):
Scott Zawalskieadbf702013-03-14 09:23:06 -0400401 return
beepscb6f1e22013-06-28 19:14:10 -0700402 self.update_job_repo_url(None, None)
403
404
405 def update_job_repo_url(self, devserver_url, image_name):
406 """
407 Updates the job_repo_url host attribute and asserts it's value.
408
409 @param devserver_url: The devserver to use in the job_repo_url.
410 @param image_name: The name of the image to use in the job_repo_url.
411
412 @raises AutoservError: If we failed to update the job_repo_url.
413 """
414 repo_url = None
415 if devserver_url and image_name:
416 repo_url = tools.get_package_url(devserver_url, image_name)
417 self._AFE.set_host_attribute(ds_constants.JOB_REPO_URL, repo_url,
Scott Zawalski62bacae2013-03-05 10:40:32 -0500418 hostname=self.hostname)
beepscb6f1e22013-06-28 19:14:10 -0700419 if self.lookup_job_repo_url() != repo_url:
420 raise error.AutoservError('Failed to update job_repo_url with %s, '
421 'host %s' % (repo_url, self.hostname))
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500422
423
Simran Basi5ace6f22016-01-06 17:30:44 -0800424 def add_job_repo_url(self, image_name):
Scott Zawalskieadbf702013-03-14 09:23:06 -0400425 """Add cros_version labels and host attribute job_repo_url.
426
427 @param image_name: The name of the image e.g.
428 lumpy-release/R27-3837.0.0
Dan Shi7458bf62013-06-10 12:50:16 -0700429
Scott Zawalskieadbf702013-03-14 09:23:06 -0400430 """
Simran Basi5ace6f22016-01-06 17:30:44 -0800431 if not afe_utils.host_in_lab(self):
Scott Zawalskieadbf702013-03-14 09:23:06 -0400432 return
Scott Zawalski62bacae2013-03-05 10:40:32 -0500433
Dan Shi216389c2015-12-22 11:03:06 -0800434 devserver_url = dev_server.ImageServer.resolve(image_name,
435 self.hostname).url()
beepscb6f1e22013-06-28 19:14:10 -0700436 self.update_job_repo_url(devserver_url, image_name)
437
438
beepsdae65fd2013-07-26 16:24:41 -0700439 def verify_job_repo_url(self, tag=''):
beepscb6f1e22013-06-28 19:14:10 -0700440 """
441 Make sure job_repo_url of this host is valid.
442
joychen03eaad92013-06-26 09:55:21 -0700443 Eg: The job_repo_url "http://lmn.cd.ab.xyx:8080/static/\
beepscb6f1e22013-06-28 19:14:10 -0700444 lumpy-release/R29-4279.0.0/autotest/packages" claims to have the
445 autotest package for lumpy-release/R29-4279.0.0. If this isn't the case,
446 download and extract it. If the devserver embedded in the url is
447 unresponsive, update the job_repo_url of the host after staging it on
448 another devserver.
449
450 @param job_repo_url: A url pointing to the devserver where the autotest
451 package for this build should be staged.
beepsdae65fd2013-07-26 16:24:41 -0700452 @param tag: The tag from the server job, in the format
453 <job_id>-<user>/<hostname>, or <hostless> for a server job.
beepscb6f1e22013-06-28 19:14:10 -0700454
455 @raises DevServerException: If we could not resolve a devserver.
456 @raises AutoservError: If we're unable to save the new job_repo_url as
457 a result of choosing a new devserver because the old one failed to
458 respond to a health check.
beeps0c865032013-07-30 11:37:06 -0700459 @raises urllib2.URLError: If the devserver embedded in job_repo_url
460 doesn't respond within the timeout.
beepscb6f1e22013-06-28 19:14:10 -0700461 """
462 job_repo_url = self.lookup_job_repo_url()
463 if not job_repo_url:
464 logging.warning('No job repo url set on host %s', self.hostname)
465 return
466
467 logging.info('Verifying job repo url %s', job_repo_url)
468 devserver_url, image_name = tools.get_devserver_build_from_package_url(
469 job_repo_url)
470
beeps0c865032013-07-30 11:37:06 -0700471 ds = dev_server.ImageServer(devserver_url)
beepscb6f1e22013-06-28 19:14:10 -0700472
473 logging.info('Staging autotest artifacts for %s on devserver %s',
474 image_name, ds.url())
beeps687243d2013-07-18 15:29:27 -0700475
476 start_time = time.time()
Simran Basi25e7a922014-10-31 11:56:10 -0700477 ds.stage_artifacts(image_name, ['autotest_packages'])
beeps687243d2013-07-18 15:29:27 -0700478 stage_time = time.time() - start_time
479
480 # Record how much of the verification time comes from a devserver
481 # restage. If we're doing things right we should not see multiple
482 # devservers for a given board/build/branch path.
483 try:
J. Richard Barnette3cbd76b2013-11-27 12:11:25 -0800484 board, build_type, branch = server_utils.ParseBuildName(
beeps687243d2013-07-18 15:29:27 -0700485 image_name)[:3]
J. Richard Barnette3cbd76b2013-11-27 12:11:25 -0800486 except server_utils.ParseBuildNameException:
beeps687243d2013-07-18 15:29:27 -0700487 pass
488 else:
beeps0c865032013-07-30 11:37:06 -0700489 devserver = devserver_url[
Chris Sosa65425082013-10-16 13:26:22 -0700490 devserver_url.find('/') + 2:devserver_url.rfind(':')]
beeps687243d2013-07-18 15:29:27 -0700491 stats_key = {
492 'board': board,
493 'build_type': build_type,
494 'branch': branch,
beeps0c865032013-07-30 11:37:06 -0700495 'devserver': devserver.replace('.', '_'),
beeps687243d2013-07-18 15:29:27 -0700496 }
Gabe Black1e1c41b2015-02-04 23:55:15 -0800497 autotest_stats.Gauge('verify_job_repo_url').send(
beeps687243d2013-07-18 15:29:27 -0700498 '%(board)s.%(build_type)s.%(branch)s.%(devserver)s' % stats_key,
499 stage_time)
beepscb6f1e22013-06-28 19:14:10 -0700500
Scott Zawalskieadbf702013-03-14 09:23:06 -0400501
Dan Shicf4d2032015-03-12 15:04:21 -0700502 def stage_server_side_package(self, image=None):
503 """Stage autotest server-side package on devserver.
504
505 @param image: Full path of an OS image to install or a build name.
506
507 @return: A url to the autotest server-side package.
508 """
509 if image:
510 image_name = tools.get_build_from_image(image)
511 if not image_name:
512 raise error.AutoservError(
513 'Failed to parse build name from %s' % image)
514 ds = dev_server.ImageServer.resolve(image_name)
515 else:
516 job_repo_url = self.lookup_job_repo_url()
517 if job_repo_url:
518 devserver_url, image_name = (
519 tools.get_devserver_build_from_package_url(job_repo_url))
520 ds = dev_server.ImageServer(devserver_url)
521 else:
522 labels = self._AFE.get_labels(
523 name__startswith=ds_constants.VERSION_PREFIX,
524 host__hostname=self.hostname)
525 if not labels:
526 raise error.AutoservError(
527 'Failed to stage server-side package. The host has '
528 'no job_report_url attribute or version label.')
529 image_name = labels[0].name[len(ds_constants.VERSION_PREFIX):]
530 ds = dev_server.ImageServer.resolve(image_name)
Dan Shica503482015-03-30 17:23:25 -0700531
532 # Get the OS version of the build, for any build older than
533 # MIN_VERSION_SUPPORT_SSP, server side packaging is not supported.
534 match = re.match('.*/R\d+-(\d+)\.', image_name)
535 if match and int(match.group(1)) < self.MIN_VERSION_SUPPORT_SSP:
536 logging.warn('Build %s is older than %s. Server side packaging is '
537 'disabled.', image_name, self.MIN_VERSION_SUPPORT_SSP)
538 return None
539
Dan Shicf4d2032015-03-12 15:04:21 -0700540 ds.stage_artifacts(image_name, ['autotest_server_package'])
541 return '%s/static/%s/%s' % (ds.url(), image_name,
542 'autotest_server_package.tar.bz2')
543
544
Dan Shi0f466e82013-02-22 15:44:58 -0800545 def _try_stateful_update(self, update_url, force_update, updater):
546 """Try to use stateful update to initialize DUT.
547
548 When DUT is already running the same version that machine_install
549 tries to install, stateful update is a much faster way to clean up
550 the DUT for testing, compared to a full reimage. It is implemeted
551 by calling autoupdater.run_update, but skipping updating root, as
552 updating the kernel is time consuming and not necessary.
553
554 @param update_url: url of the image.
555 @param force_update: Set to True to update the image even if the DUT
556 is running the same version.
557 @param updater: ChromiumOSUpdater instance used to update the DUT.
558 @returns: True if the DUT was updated with stateful update.
559
560 """
Dan Shi10b98482016-02-02 14:38:50 -0800561 # Stop service ap-update-manager to prevent rebooting during autoupdate.
562 # The service is used in jetstream boards, but not other CrOS devices.
563 self.run('sudo stop ap-update-manager', ignore_status=True)
564
J. Richard Barnette3f731032014-04-07 17:42:59 -0700565 # TODO(jrbarnette): Yes, I hate this re.match() test case.
566 # It's better than the alternative: see crbug.com/360944.
567 image_name = autoupdater.url_to_image_name(update_url)
568 release_pattern = r'^.*-release/R[0-9]+-[0-9]+\.[0-9]+\.0$'
569 if not re.match(release_pattern, image_name):
570 return False
Dan Shi0f466e82013-02-22 15:44:58 -0800571 if not updater.check_version():
572 return False
573 if not force_update:
574 logging.info('Canceling stateful update because the new and '
575 'old versions are the same.')
576 return False
577 # Following folders should be rebuilt after stateful update.
578 # A test file is used to confirm each folder gets rebuilt after
579 # the stateful update.
580 folders_to_check = ['/var', '/home', '/mnt/stateful_partition']
581 test_file = '.test_file_to_be_deleted'
582 for folder in folders_to_check:
583 touch_path = os.path.join(folder, test_file)
584 self.run('touch %s' % touch_path)
585
Chris Sosae92399e2015-04-24 11:32:59 -0700586 updater.run_update(update_root=False)
Dan Shi0f466e82013-02-22 15:44:58 -0800587
588 # Reboot to complete stateful update.
Chris Sosab76e0ee2013-05-22 16:55:41 -0700589 self.reboot(timeout=self.REBOOT_TIMEOUT, wait=True)
Dan Shi0f466e82013-02-22 15:44:58 -0800590 check_file_cmd = 'test -f %s; echo $?'
591 for folder in folders_to_check:
592 test_file_path = os.path.join(folder, test_file)
593 result = self.run(check_file_cmd % test_file_path,
594 ignore_status=True)
595 if result.exit_status == 1:
596 return False
597 return True
598
599
J. Richard Barnette7275b612013-06-04 18:13:11 -0700600 def _post_update_processing(self, updater, expected_kernel=None):
Dan Shi0f466e82013-02-22 15:44:58 -0800601 """After the DUT is updated, confirm machine_install succeeded.
602
603 @param updater: ChromiumOSUpdater instance used to update the DUT.
J. Richard Barnette7275b612013-06-04 18:13:11 -0700604 @param expected_kernel: kernel expected to be active after reboot,
605 or `None` to skip rollback checking.
Dan Shi0f466e82013-02-22 15:44:58 -0800606
607 """
J. Richard Barnette7275b612013-06-04 18:13:11 -0700608 # Touch the lab machine file to leave a marker that
609 # distinguishes this image from other test images.
610 # Afterwards, we must re-run the autoreboot script because
611 # it depends on the _LAB_MACHINE_FILE.
J. Richard Barnette71cc1862015-12-02 10:32:38 -0800612 autoreboot_cmd = ('FILE="%s" ; [ -f "$FILE" ] || '
613 '( touch "$FILE" ; start autoreboot )')
614 self.run(autoreboot_cmd % self._LAB_MACHINE_FILE)
Chris Sosa65425082013-10-16 13:26:22 -0700615 updater.verify_boot_expectations(
616 expected_kernel, rollback_message=
Gilad Arnoldc26ae1f2015-10-22 16:09:41 -0700617 'Build %s failed to boot on %s; system rolled back to previous '
Chris Sosa65425082013-10-16 13:26:22 -0700618 'build' % (updater.update_version, self.hostname))
J. Richard Barnette7275b612013-06-04 18:13:11 -0700619 # Check that we've got the build we meant to install.
620 if not updater.check_version_to_confirm_install():
621 raise autoupdater.ChromiumOSError(
622 'Failed to update %s to build %s; found build '
623 '%s instead' % (self.hostname,
Chris Sosa65425082013-10-16 13:26:22 -0700624 updater.update_version,
Dan Shi0942b1d2015-03-31 11:07:00 -0700625 self.get_release_version()))
Dan Shi0f466e82013-02-22 15:44:58 -0800626
Chris Sosae92399e2015-04-24 11:32:59 -0700627 logging.debug('Cleaning up old autotest directories.')
628 try:
629 installed_autodir = autotest.Autotest.get_installed_autodir(self)
630 self.run('rm -rf ' + installed_autodir)
631 except autotest.AutodirNotFoundError:
632 logging.debug('No autotest installed directory found.')
633
Dan Shi0f466e82013-02-22 15:44:58 -0800634
J. Richard Barnettee4af8b92013-05-01 13:16:12 -0700635 def _stage_image_for_update(self, image_name=None):
Chris Sosae92399e2015-04-24 11:32:59 -0700636 """Stage a build on a devserver and return the update_url and devserver.
Scott Zawalskieadbf702013-03-14 09:23:06 -0400637
638 @param image_name: a name like lumpy-release/R27-3837.0.0
Chris Sosae92399e2015-04-24 11:32:59 -0700639 @returns a tuple with an update URL like:
Scott Zawalskieadbf702013-03-14 09:23:06 -0400640 http://172.22.50.205:8082/update/lumpy-release/R27-3837.0.0
Chris Sosae92399e2015-04-24 11:32:59 -0700641 and the devserver instance.
Scott Zawalskieadbf702013-03-14 09:23:06 -0400642 """
J. Richard Barnettee4af8b92013-05-01 13:16:12 -0700643 if not image_name:
644 image_name = self.get_repair_image_name()
Chris Sosae92399e2015-04-24 11:32:59 -0700645
J. Richard Barnettee4af8b92013-05-01 13:16:12 -0700646 logging.info('Staging build for AU: %s', image_name)
Dan Shi216389c2015-12-22 11:03:06 -0800647 devserver = dev_server.ImageServer.resolve(image_name, self.hostname)
Scott Zawalskieadbf702013-03-14 09:23:06 -0400648 devserver.trigger_download(image_name, synchronous=False)
Chris Sosae92399e2015-04-24 11:32:59 -0700649 return (tools.image_url_pattern() % (devserver.url(), image_name),
650 devserver)
Scott Zawalskieadbf702013-03-14 09:23:06 -0400651
652
J. Richard Barnettee4af8b92013-05-01 13:16:12 -0700653 def stage_image_for_servo(self, image_name=None):
654 """Stage a build on a devserver and return the update_url.
655
656 @param image_name: a name like lumpy-release/R27-3837.0.0
657 @returns an update URL like:
658 http://172.22.50.205:8082/update/lumpy-release/R27-3837.0.0
659 """
660 if not image_name:
661 image_name = self.get_repair_image_name()
662 logging.info('Staging build for servo install: %s', image_name)
Dan Shi216389c2015-12-22 11:03:06 -0800663 devserver = dev_server.ImageServer.resolve(image_name, self.hostname)
J. Richard Barnettee4af8b92013-05-01 13:16:12 -0700664 devserver.stage_artifacts(image_name, ['test_image'])
665 return devserver.get_test_image_url(image_name)
666
667
beepse539be02013-07-31 21:57:39 -0700668 def stage_factory_image_for_servo(self, image_name):
669 """Stage a build on a devserver and return the update_url.
670
671 @param image_name: a name like <baord>/4262.204.0
beeps12c0a3c2013-09-03 11:58:27 -0700672
beepse539be02013-07-31 21:57:39 -0700673 @return: An update URL, eg:
674 http://<devserver>/static/canary-channel/\
675 <board>/4262.204.0/factory_test/chromiumos_factory_image.bin
beeps12c0a3c2013-09-03 11:58:27 -0700676
677 @raises: ValueError if the factory artifact name is missing from
678 the config.
679
beepse539be02013-07-31 21:57:39 -0700680 """
681 if not image_name:
682 logging.error('Need an image_name to stage a factory image.')
683 return
684
Dan Shib8540a52015-07-16 14:18:23 -0700685 factory_artifact = CONFIG.get_config_value(
beeps12c0a3c2013-09-03 11:58:27 -0700686 'CROS', 'factory_artifact', type=str, default='')
687 if not factory_artifact:
688 raise ValueError('Cannot retrieve the factory artifact name from '
689 'autotest config, and hence cannot stage factory '
690 'artifacts.')
691
beepse539be02013-07-31 21:57:39 -0700692 logging.info('Staging build for servo install: %s', image_name)
Dan Shi216389c2015-12-22 11:03:06 -0800693 devserver = dev_server.ImageServer.resolve(image_name, self.hostname)
beepse539be02013-07-31 21:57:39 -0700694 devserver.stage_artifacts(
695 image_name,
beeps12c0a3c2013-09-03 11:58:27 -0700696 [factory_artifact],
697 archive_url=None)
beepse539be02013-07-31 21:57:39 -0700698
699 return tools.factory_image_url_pattern() % (devserver.url(), image_name)
700
701
Chris Sosaa3ac2152012-05-23 22:23:13 -0700702 def machine_install(self, update_url=None, force_update=False,
Richard Barnette0b023a72015-04-24 16:07:30 +0000703 local_devserver=False, repair=False,
704 force_full_update=False):
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500705 """Install the DUT.
706
Dan Shi0f466e82013-02-22 15:44:58 -0800707 Use stateful update if the DUT is already running the same build.
708 Stateful update does not update kernel and tends to run much faster
709 than a full reimage. If the DUT is running a different build, or it
710 failed to do a stateful update, full update, including kernel update,
711 will be applied to the DUT.
712
Simran Basi5ace6f22016-01-06 17:30:44 -0800713 Once a host enters machine_install its host attribute job_repo_url
714 (used for package install) will be removed and then updated.
Scott Zawalskieadbf702013-03-14 09:23:06 -0400715
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500716 @param update_url: The url to use for the update
717 pattern: http://$devserver:###/update/$build
718 If update_url is None and repair is True we will install the
Dan Shi6964fa52014-12-18 11:04:27 -0800719 stable image listed in afe_stable_versions table. If the table
720 is not setup, global_config value under CROS.stable_cros_version
721 will be used instead.
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500722 @param force_update: Force an update even if the version installed
723 is the same. Default:False
Christopher Wiley6a4ff932015-05-15 14:00:47 -0700724 @param local_devserver: Used by test_that to allow people to
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500725 use their local devserver. Default: False
Chris Sosae92399e2015-04-24 11:32:59 -0700726 @param repair: Forces update to repair image. Implies force_update.
Fang Deng3d3b9272014-12-22 12:20:28 -0800727 @param force_full_update: If True, do not attempt to run stateful
728 update, force a full reimage. If False, try stateful update
729 first when the dut is already installed with the same version.
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500730 @raises autoupdater.ChromiumOSError
731
Simran Basi5ace6f22016-01-06 17:30:44 -0800732 @returns Name of the image installed.
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500733 """
Chris Sosae92399e2015-04-24 11:32:59 -0700734 devserver = None
Richard Barnette0b023a72015-04-24 16:07:30 +0000735 if repair:
Chris Sosae92399e2015-04-24 11:32:59 -0700736 update_url, devserver = self._stage_image_for_update()
Richard Barnette0b023a72015-04-24 16:07:30 +0000737 force_update = True
Dan Shi0f466e82013-02-22 15:44:58 -0800738
Chris Sosae92399e2015-04-24 11:32:59 -0700739 if not update_url and not self._parser.options.image:
740 raise error.AutoservError(
Dan Shid07ee2e2015-09-24 14:49:25 -0700741 'There is no update URL, nor a method to get one.')
Chris Sosae92399e2015-04-24 11:32:59 -0700742
743 if not update_url and self._parser.options.image:
744 # This is the base case where we have no given update URL i.e.
745 # dynamic suites logic etc. This is the most flexible case where we
746 # can serve an update from any of our fleet of devservers.
747 requested_build = self._parser.options.image
748 if not requested_build.startswith('http://'):
749 logging.debug('Update will be staged for this installation')
750 update_url, devserver = self._stage_image_for_update(
Dan Shid07ee2e2015-09-24 14:49:25 -0700751 requested_build)
Chris Sosae92399e2015-04-24 11:32:59 -0700752 else:
753 update_url = requested_build
754
755 logging.debug('Update URL is %s', update_url)
756
Scott Zawalskieadbf702013-03-14 09:23:06 -0400757 # Remove cros-version and job_repo_url host attribute from host.
Simran Basi5ace6f22016-01-06 17:30:44 -0800758 self.clear_job_repo_url()
Chris Sosae92399e2015-04-24 11:32:59 -0700759
Dan Shid07ee2e2015-09-24 14:49:25 -0700760 # Create a file to indicate if provision fails. The file will be removed
761 # by stateful update or full install.
762 self.run('touch %s' % PROVISION_FAILED)
763
Chris Sosae92399e2015-04-24 11:32:59 -0700764 update_complete = False
765 updater = autoupdater.ChromiumOSUpdater(
766 update_url, host=self, local_devserver=local_devserver)
Fang Deng3d3b9272014-12-22 12:20:28 -0800767 if not force_full_update:
768 try:
Chris Sosae92399e2015-04-24 11:32:59 -0700769 # If the DUT is already running the same build, try stateful
770 # update first as it's much quicker than a full re-image.
771 update_complete = self._try_stateful_update(
Dan Shid07ee2e2015-09-24 14:49:25 -0700772 update_url, force_update, updater)
Fang Deng3d3b9272014-12-22 12:20:28 -0800773 except Exception as e:
774 logging.exception(e)
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700775
Dan Shi0f466e82013-02-22 15:44:58 -0800776 inactive_kernel = None
Chris Sosae92399e2015-04-24 11:32:59 -0700777 if update_complete or (not force_update and updater.check_version()):
778 logging.info('Install complete without full update')
779 else:
780 logging.info('DUT requires full update.')
781 self.reboot(timeout=self.REBOOT_TIMEOUT, wait=True)
Dan Shi10b98482016-02-02 14:38:50 -0800782 # Stop service ap-update-manager to prevent rebooting during
783 # autoupdate. The service is used in jetstream boards, but not other
784 # CrOS devices.
785 self.run('sudo stop ap-update-manager', ignore_status=True)
786
Chris Sosae92399e2015-04-24 11:32:59 -0700787 num_of_attempts = provision.FLAKY_DEVSERVER_ATTEMPTS
Chris Sosab7612bc2013-03-21 10:32:37 -0700788
Chris Sosae92399e2015-04-24 11:32:59 -0700789 while num_of_attempts > 0:
790 num_of_attempts -= 1
791 try:
792 updater.run_update()
793 except Exception:
794 logging.warn('Autoupdate did not complete.')
795 # Do additional check for the devserver health. Ideally,
796 # the autoupdater.py could raise an exception when it
797 # detected network flake but that would require
798 # instrumenting the update engine and parsing it log.
799 if (num_of_attempts <= 0 or
800 devserver is None or
801 dev_server.DevServer.devserver_healthy(
802 devserver.url())):
Dan Shid07ee2e2015-09-24 14:49:25 -0700803 raise
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700804
Chris Sosae92399e2015-04-24 11:32:59 -0700805 logging.warn('Devserver looks unhealthy. Trying another')
806 update_url, devserver = self._stage_image_for_update(
807 requested_build)
808 logging.debug('New Update URL is %s', update_url)
809 updater = autoupdater.ChromiumOSUpdater(
810 update_url, host=self,
811 local_devserver=local_devserver)
812 else:
813 break
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700814
Chris Sosae92399e2015-04-24 11:32:59 -0700815 # Give it some time in case of IO issues.
816 time.sleep(10)
Dan Shi5699ac22014-12-19 10:55:49 -0800817
Chris Sosae92399e2015-04-24 11:32:59 -0700818 # Figure out active and inactive kernel.
819 active_kernel, inactive_kernel = updater.get_kernel_state()
Simran Basi13fa1ba2013-03-04 10:56:47 -0800820
Chris Sosae92399e2015-04-24 11:32:59 -0700821 # Ensure inactive kernel has higher priority than active.
822 if (updater.get_kernel_priority(inactive_kernel)
823 < updater.get_kernel_priority(active_kernel)):
824 raise autoupdater.ChromiumOSError(
825 'Update failed. The priority of the inactive kernel'
826 ' partition is less than that of the active kernel'
827 ' partition.')
828
829 # Updater has returned successfully; reboot the host.
830 self.reboot(timeout=self.REBOOT_TIMEOUT, wait=True)
831
832 self._post_update_processing(updater, inactive_kernel)
Simran Basi5ace6f22016-01-06 17:30:44 -0800833 image_name = autoupdater.url_to_image_name(update_url)
834 self.add_job_repo_url(image_name)
835 return image_name
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700836
837
Tom Wai-Hong Tam2d00cb22016-01-08 06:40:50 +0800838 def _clear_fw_version_labels(self, rw_only):
839 """Clear firmware version labels from the machine.
840
841 @param rw_only: True to only clear fwrw_version; otherewise, clear
842 both fwro_version and fwrw_version.
843 """
Dan Shi9cb0eec2014-06-03 09:04:50 -0700844 labels = self._AFE.get_labels(
Dan Shi0723bf52015-06-24 10:52:38 -0700845 name__startswith=provision.FW_RW_VERSION_PREFIX,
Dan Shi9cb0eec2014-06-03 09:04:50 -0700846 host__hostname=self.hostname)
Tom Wai-Hong Tam2d00cb22016-01-08 06:40:50 +0800847 if not rw_only:
848 labels = labels + self._AFE.get_labels(
849 name__startswith=provision.FW_RO_VERSION_PREFIX,
850 host__hostname=self.hostname)
Dan Shi9cb0eec2014-06-03 09:04:50 -0700851 for label in labels:
852 label.remove_hosts(hosts=[self.hostname])
853
854
Tom Wai-Hong Tam2d00cb22016-01-08 06:40:50 +0800855 def _add_fw_version_label(self, build, rw_only):
Dan Shi9cb0eec2014-06-03 09:04:50 -0700856 """Add firmware version label to the machine.
857
858 @param build: Build of firmware.
Tom Wai-Hong Tam2d00cb22016-01-08 06:40:50 +0800859 @param rw_only: True to only add fwrw_version; otherwise, add both
860 fwro_version and fwrw_version.
Dan Shi9cb0eec2014-06-03 09:04:50 -0700861
862 """
Tom Wai-Hong Tam2d00cb22016-01-08 06:40:50 +0800863 fw_label = provision.fwrw_version_to_label(build)
MK Ryu73be9862015-07-06 12:25:00 -0700864 self._AFE.run('label_add_hosts', id=fw_label, hosts=[self.hostname])
Tom Wai-Hong Tam2d00cb22016-01-08 06:40:50 +0800865 if not rw_only:
866 fw_label = provision.fwro_version_to_label(build)
867 self._AFE.run('label_add_hosts', id=fw_label, hosts=[self.hostname])
Dan Shi9cb0eec2014-06-03 09:04:50 -0700868
869
Tom Wai-Hong Tam4ac78982016-01-08 02:34:37 +0800870 def firmware_install(self, build=None, rw_only=False):
Dan Shi9cb0eec2014-06-03 09:04:50 -0700871 """Install firmware to the DUT.
872
873 Use stateful update if the DUT is already running the same build.
874 Stateful update does not update kernel and tends to run much faster
875 than a full reimage. If the DUT is running a different build, or it
876 failed to do a stateful update, full update, including kernel update,
877 will be applied to the DUT.
878
Tom Wai-Hong Tam2d00cb22016-01-08 06:40:50 +0800879 Once a host enters firmware_install its fw[ro|rw]_version label will
880 be removed. After the firmware is updated successfully, a new
881 fw[ro|rw]_version label will be added to the host.
Dan Shi9cb0eec2014-06-03 09:04:50 -0700882
883 @param build: The build version to which we want to provision the
884 firmware of the machine,
885 e.g. 'link-firmware/R22-2695.1.144'.
Tom Wai-Hong Tam4ac78982016-01-08 02:34:37 +0800886 @param rw_only: True to only install firmware to its RW portions. Keep
887 the RO portions unchanged.
Dan Shi9cb0eec2014-06-03 09:04:50 -0700888
889 TODO(dshi): After bug 381718 is fixed, update here with corresponding
890 exceptions that could be raised.
891
892 """
893 if not self.servo:
894 raise error.TestError('Host %s does not have servo.' %
895 self.hostname)
896
897 # TODO(fdeng): use host.get_board() after
898 # crbug.com/271834 is fixed.
899 board = self._get_board_from_afe()
900
Chris Sosae92399e2015-04-24 11:32:59 -0700901 # If build is not set, try to install firmware from stable CrOS.
Dan Shi9cb0eec2014-06-03 09:04:50 -0700902 if not build:
Dan Shi3d7a0e12015-10-12 11:55:45 -0700903 build = self.get_repair_image_name(image_type='firmware')
904 if not build:
905 raise error.TestError(
906 'Failed to find stable firmware build for %s.',
907 self.hostname)
908 logging.info('Will install firmware from build %s.', build)
Dan Shi9cb0eec2014-06-03 09:04:50 -0700909
910 config = FAFTConfig(board)
911 if config.use_u_boot:
912 ap_image = 'image-%s.bin' % board
913 else: # Depthcharge platform
914 ap_image = 'image.bin'
915 ec_image = 'ec.bin'
Dan Shi216389c2015-12-22 11:03:06 -0800916 ds = dev_server.ImageServer.resolve(build, self.hostname)
Dan Shi9cb0eec2014-06-03 09:04:50 -0700917 ds.stage_artifacts(build, ['firmware'])
918
919 tmpd = autotemp.tempdir(unique_id='fwimage')
920 try:
921 fwurl = self._FW_IMAGE_URL_PATTERN % (ds.url(), build)
922 local_tarball = os.path.join(tmpd.name, os.path.basename(fwurl))
923 server_utils.system('wget -O %s %s' % (local_tarball, fwurl),
924 timeout=60)
925 server_utils.system('tar xf %s -C %s %s %s' %
926 (local_tarball, tmpd.name, ap_image, ec_image),
927 timeout=60)
928 server_utils.system('tar xf %s --wildcards -C %s "dts/*"' %
929 (local_tarball, tmpd.name),
930 timeout=60, ignore_status=True)
931
Tom Wai-Hong Tam2d00cb22016-01-08 06:40:50 +0800932 self._clear_fw_version_labels(rw_only)
Tom Wai-Hong Tam4ac78982016-01-08 02:34:37 +0800933 logging.info('Will re-program EC %snow', 'RW ' if rw_only else '')
934 self.servo.program_ec(os.path.join(tmpd.name, ec_image), rw_only)
935 logging.info('Will re-program BIOS %snow', 'RW ' if rw_only else '')
936 self.servo.program_bios(os.path.join(tmpd.name, ap_image), rw_only)
Dan Shi9cb0eec2014-06-03 09:04:50 -0700937 self.servo.get_power_state_controller().reset()
938 time.sleep(self.servo.BOOT_DELAY)
Tom Wai-Hong Tam2d00cb22016-01-08 06:40:50 +0800939 self._add_fw_version_label(build, rw_only)
Dan Shi9cb0eec2014-06-03 09:04:50 -0700940 finally:
941 tmpd.clean()
942
943
Dan Shi10e992b2013-08-30 11:02:59 -0700944 def show_update_engine_log(self):
945 """Output update engine log."""
MK Ryu35d661e2014-09-25 17:44:10 -0700946 logging.debug('Dumping %s', client_constants.UPDATE_ENGINE_LOG)
947 self.run('cat %s' % client_constants.UPDATE_ENGINE_LOG)
Dan Shi10e992b2013-08-30 11:02:59 -0700948
949
Richard Barnette82c35912012-11-20 10:09:10 -0800950 def _get_board_from_afe(self):
951 """Retrieve this host's board from its labels in the AFE.
952
953 Looks for a host label of the form "board:<board>", and
954 returns the "<board>" part of the label. `None` is returned
955 if there is not a single, unique label matching the pattern.
956
957 @returns board from label, or `None`.
958 """
Dan Shia1ecd5c2013-06-06 11:21:31 -0700959 return server_utils.get_board_from_afe(self.hostname, self._AFE)
Simran Basi833814b2013-01-29 13:13:43 -0800960
961
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500962 def _install_repair(self):
Chris Sosae92399e2015-04-24 11:32:59 -0700963 """Attempt to repair this host using the update-engine.
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500964
965 If the host is up, try installing the DUT with a stable
Dan Shi6964fa52014-12-18 11:04:27 -0800966 "repair" version of Chrome OS as defined in afe_stable_versions table.
967 If the table is not setup, global_config value under
968 CROS.stable_cros_version will be used instead.
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500969
Scott Zawalski62bacae2013-03-05 10:40:32 -0500970 @raises AutoservRepairMethodNA if the DUT is not reachable.
971 @raises ChromiumOSError if the install failed for some reason.
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500972
973 """
974 if not self.is_up():
Scott Zawalski62bacae2013-03-05 10:40:32 -0500975 raise error.AutoservRepairMethodNA('DUT unreachable for install.')
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500976 logging.info('Attempting to reimage machine to repair image.')
977 try:
Simran Basi5ace6f22016-01-06 17:30:44 -0800978 afe_utils.machine_install_and_update_labels(self, repair=True)
Fang Dengd0672f32013-03-18 17:18:09 -0700979 except autoupdater.ChromiumOSError as e:
980 logging.exception(e)
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500981 logging.info('Repair via install failed.')
Scott Zawalski62bacae2013-03-05 10:40:32 -0500982 raise
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500983
984
Dan Shi2c88eed2013-11-12 10:18:38 -0800985 def _install_repair_with_powerwash(self):
Dan Shi9cc48452013-11-12 12:39:26 -0800986 """Attempt to powerwash first then repair this host using update-engine.
Dan Shi2c88eed2013-11-12 10:18:38 -0800987
Dan Shi9cc48452013-11-12 12:39:26 -0800988 update-engine may fail due to a bad image. In such case, powerwash
989 may help to cleanup the DUT for update-engine to work again.
Dan Shi2c88eed2013-11-12 10:18:38 -0800990
991 @raises AutoservRepairMethodNA if the DUT is not reachable.
992 @raises ChromiumOSError if the install failed for some reason.
993
994 """
995 if not self.is_up():
996 raise error.AutoservRepairMethodNA('DUT unreachable for install.')
997
998 logging.info('Attempting to powerwash the DUT.')
999 self.run('echo "fast safe" > '
1000 '/mnt/stateful_partition/factory_install_reset')
1001 self.reboot(timeout=self.POWERWASH_BOOT_TIMEOUT, wait=True)
1002 if not self.is_up():
Dan Shi9cc48452013-11-12 12:39:26 -08001003 logging.error('Powerwash failed. DUT did not come back after '
Dan Shi2c88eed2013-11-12 10:18:38 -08001004 'reboot.')
1005 raise error.AutoservRepairFailure(
1006 'DUT failed to boot from powerwash after %d seconds' %
1007 self.POWERWASH_BOOT_TIMEOUT)
1008
1009 logging.info('Powerwash succeeded.')
1010 self._install_repair()
1011
1012
beepsf079cfb2013-09-18 17:49:51 -07001013 def servo_install(self, image_url=None, usb_boot_timeout=USB_BOOT_TIMEOUT,
1014 install_timeout=INSTALL_TIMEOUT):
Scott Zawalski62bacae2013-03-05 10:40:32 -05001015 """
1016 Re-install the OS on the DUT by:
1017 1) installing a test image on a USB storage device attached to the Servo
1018 board,
Richard Barnette03a0c132012-11-05 12:40:35 -08001019 2) booting that image in recovery mode, and then
J. Richard Barnette31b2e312013-04-04 16:05:22 -07001020 3) installing the image with chromeos-install.
1021
Scott Zawalski62bacae2013-03-05 10:40:32 -05001022 @param image_url: If specified use as the url to install on the DUT.
1023 otherwise boot the currently staged image on the USB stick.
beepsf079cfb2013-09-18 17:49:51 -07001024 @param usb_boot_timeout: The usb_boot_timeout to use during reimage.
1025 Factory images need a longer usb_boot_timeout than regular
1026 cros images.
1027 @param install_timeout: The timeout to use when installing the chromeos
1028 image. Factory images need a longer install_timeout.
Richard Barnette03a0c132012-11-05 12:40:35 -08001029
Scott Zawalski62bacae2013-03-05 10:40:32 -05001030 @raises AutoservError if the image fails to boot.
beepsf079cfb2013-09-18 17:49:51 -07001031
J. Richard Barnette0199cc82014-12-05 17:08:40 -08001032 """
beepsf079cfb2013-09-18 17:49:51 -07001033 usb_boot_timer_key = ('servo_install.usb_boot_timeout_%s'
1034 % usb_boot_timeout)
1035 logging.info('Downloading image to USB, then booting from it. Usb boot '
1036 'timeout = %s', usb_boot_timeout)
Gabe Black1e1c41b2015-02-04 23:55:15 -08001037 timer = autotest_stats.Timer(usb_boot_timer_key)
beepsf079cfb2013-09-18 17:49:51 -07001038 timer.start()
J. Richard Barnette31b2e312013-04-04 16:05:22 -07001039 self.servo.install_recovery_image(image_url)
beepsf079cfb2013-09-18 17:49:51 -07001040 if not self.wait_up(timeout=usb_boot_timeout):
Scott Zawalski62bacae2013-03-05 10:40:32 -05001041 raise error.AutoservRepairFailure(
1042 'DUT failed to boot from USB after %d seconds' %
beepsf079cfb2013-09-18 17:49:51 -07001043 usb_boot_timeout)
1044 timer.stop()
Scott Zawalski62bacae2013-03-05 10:40:32 -05001045
Tom Wai-Hong Tamf6b4f812015-08-08 04:14:59 +08001046 # The new chromeos-tpm-recovery has been merged since R44-7073.0.0.
1047 # In old CrOS images, this command fails. Skip the error.
Tom Wai-Hong Tam27af7332015-07-25 06:09:39 +08001048 logging.info('Resetting the TPM status')
Tom Wai-Hong Tamf6b4f812015-08-08 04:14:59 +08001049 try:
1050 self.run('chromeos-tpm-recovery')
1051 except error.AutoservRunError:
1052 logging.warn('chromeos-tpm-recovery is too old.')
1053
Tom Wai-Hong Tam27af7332015-07-25 06:09:39 +08001054
beepsf079cfb2013-09-18 17:49:51 -07001055 install_timer_key = ('servo_install.install_timeout_%s'
1056 % install_timeout)
Gabe Black1e1c41b2015-02-04 23:55:15 -08001057 timer = autotest_stats.Timer(install_timer_key)
beepsf079cfb2013-09-18 17:49:51 -07001058 timer.start()
1059 logging.info('Installing image through chromeos-install.')
J. Richard Barnette9af19632015-09-25 12:18:03 -07001060 self.run('chromeos-install --yes', timeout=install_timeout)
1061 self.halt()
beepsf079cfb2013-09-18 17:49:51 -07001062 timer.stop()
1063
1064 logging.info('Power cycling DUT through servo.')
J. Richard Barnette0199cc82014-12-05 17:08:40 -08001065 self.servo.get_power_state_controller().power_off()
Fang Dengafb88142013-05-30 17:44:31 -07001066 self.servo.switch_usbkey('off')
J. Richard Barnette0199cc82014-12-05 17:08:40 -08001067 # N.B. The Servo API requires that we use power_on() here
1068 # for two reasons:
1069 # 1) After turning on a DUT in recovery mode, you must turn
1070 # it off and then on with power_on() once more to
1071 # disable recovery mode (this is a Parrot specific
1072 # requirement).
1073 # 2) After power_off(), the only way to turn on is with
1074 # power_on() (this is a Storm specific requirement).
J. Richard Barnettefbcc7122013-07-24 18:24:59 -07001075 self.servo.get_power_state_controller().power_on()
beepsf079cfb2013-09-18 17:49:51 -07001076
1077 logging.info('Waiting for DUT to come back up.')
Richard Barnette03a0c132012-11-05 12:40:35 -08001078 if not self.wait_up(timeout=self.BOOT_TIMEOUT):
1079 raise error.AutoservError('DUT failed to reboot installed '
1080 'test image after %d seconds' %
Scott Zawalski62bacae2013-03-05 10:40:32 -05001081 self.BOOT_TIMEOUT)
1082
1083
Dan Shic1b8bdd2015-09-14 23:11:24 -07001084 def _setup_servo(self):
1085 """Try to force to create servo object if it's not set up yet.
1086 """
1087 if self.servo:
1088 return
1089
1090 try:
1091 # Setting servo_args to {} will force it to create the servo_host
1092 # object if possible.
1093 self._servo_host = servo_host.create_servo_host(
1094 dut=self.hostname, servo_args={})
1095 if self._servo_host:
1096 self.servo = self._servo_host.get_servo()
1097 else:
1098 logging.error('Failed to create servo_host object.')
1099 except Exception as e:
1100 logging.error('Failed to create servo object: %s', e)
1101
1102
J. Richard Barnettee4af8b92013-05-01 13:16:12 -07001103 def _servo_repair_reinstall(self):
Scott Zawalski62bacae2013-03-05 10:40:32 -05001104 """Reinstall the DUT utilizing servo and a test image.
1105
1106 Re-install the OS on the DUT by:
1107 1) installing a test image on a USB storage device attached to the Servo
1108 board,
Tom Wai-Hong Tam27af7332015-07-25 06:09:39 +08001109 2) booting that image in recovery mode,
1110 3) resetting the TPM status, and then
1111 4) installing the image with chromeos-install.
Scott Zawalski62bacae2013-03-05 10:40:32 -05001112
Scott Zawalski62bacae2013-03-05 10:40:32 -05001113 @raises AutoservRepairMethodNA if the device does not have servo
1114 support.
1115
1116 """
1117 if not self.servo:
1118 raise error.AutoservRepairMethodNA('Repair Reinstall NA: '
1119 'DUT has no servo support.')
1120
1121 logging.info('Attempting to recovery servo enabled device with '
1122 'servo_repair_reinstall')
1123
J. Richard Barnettee4af8b92013-05-01 13:16:12 -07001124 image_url = self.stage_image_for_servo()
Scott Zawalski62bacae2013-03-05 10:40:32 -05001125 self.servo_install(image_url)
1126
1127
Tom Wai-Hong Tambea741c2016-01-21 07:20:14 +08001128 def _is_firmware_repair_supported(self):
1129 """Check if the firmware repair is supported.
Dan Shi3d7a0e12015-10-12 11:55:45 -07001130
Tom Wai-Hong Tambea741c2016-01-21 07:20:14 +08001131 The firmware repair is only applicable to DUTs in pools listed in
1132 global config CROS/pools_support_firmware_repair.
Dan Shi3d7a0e12015-10-12 11:55:45 -07001133
Tom Wai-Hong Tambea741c2016-01-21 07:20:14 +08001134 @return: True if it is supported; otherwise False.
Dan Shi3d7a0e12015-10-12 11:55:45 -07001135 """
1136 logging.info('Checking if host %s can be repaired with firmware '
1137 'repair.', self.hostname)
1138 pools = server_utils.get_labels_from_afe(self.hostname, 'pool:',
1139 self._AFE)
1140 pools_support_firmware_repair = CONFIG.get_config_value('CROS',
1141 'pools_support_firmware_repair', type=str).split(',')
Tom Wai-Hong Tambea741c2016-01-21 07:20:14 +08001142
1143 return (pools and pools_support_firmware_repair and
1144 set(pools).intersection(set(pools_support_firmware_repair)))
1145
1146
1147 def _firmware_repair(self):
1148 """Reinstall the firmware image using servo.
1149
1150 This repair function attempts to install the stable firmware specified
1151 by the stable firmware version.
1152 Then reset the DUT and try to verify it. If verify fails, it will try to
1153 install the CrOS image using servo.
1154 """
1155 if not self._is_firmware_repair_supported():
1156 logging.info('Host is not in pools that support firmware repair.')
Dan Shi3d7a0e12015-10-12 11:55:45 -07001157 raise error.AutoservRepairMethodNA(
1158 'Firmware repair is not applicable to host %s.' %
1159 self.hostname)
1160
1161 # To repair a DUT connected to a moblab, try to create a servo object if
1162 # it was failed to be created earlier as there may be a servo_host host
1163 # attribute for this host.
1164 if utils.is_moblab():
1165 self._setup_servo()
1166
1167 if not self.servo:
1168 raise error.AutoservRepairMethodNA('Repair Reinstall NA: '
1169 'DUT has no servo support.')
1170
1171 logging.info('Attempting to recovery servo enabled device with '
1172 'firmware_repair.')
1173 self.firmware_install()
1174
1175 logging.info('Firmware repaired. Check if the DUT can boot. If not, '
1176 'reinstall the CrOS using servo.')
1177 try:
Dan Shi3d7a0e12015-10-12 11:55:45 -07001178 self.verify()
1179 except Exception as e:
1180 logging.warn('Failed to verify DUT, error: %s. Will try to repair '
1181 'the DUT with servo_repair_reinstall.', e)
1182 self._servo_repair_reinstall()
1183
1184
Scott Zawalski62bacae2013-03-05 10:40:32 -05001185 def _servo_repair_power(self):
1186 """Attempt to repair DUT using an attached Servo.
1187
J. Richard Barnette13165972016-01-13 10:53:09 -08001188 Attempt to power cycle the DUT via cold_reset.
Scott Zawalski62bacae2013-03-05 10:40:32 -05001189
1190 @raises AutoservRepairMethodNA if the device does not have servo
1191 support.
1192 @raises AutoservRepairFailure if the repair fails for any reason.
1193 """
1194 if not self.servo:
1195 raise error.AutoservRepairMethodNA('Repair Power NA: '
1196 'DUT has no servo support.')
1197
1198 logging.info('Attempting to recover servo enabled device by '
J. Richard Barnette13165972016-01-13 10:53:09 -08001199 'powering cycling with cold reset.')
1200 self.servo.get_power_state_controller().reset()
Scott Zawalski62bacae2013-03-05 10:40:32 -05001201 if self.wait_up(self.BOOT_TIMEOUT):
1202 return
1203
1204 raise error.AutoservRepairFailure('DUT did not boot after long_press.')
Richard Barnette03a0c132012-11-05 12:40:35 -08001205
1206
Richard Barnette82c35912012-11-20 10:09:10 -08001207 def _powercycle_to_repair(self):
1208 """Utilize the RPM Infrastructure to bring the host back up.
1209
1210 If the host is not up/repaired after the first powercycle we utilize
1211 auto fallback to the last good install by powercycling and rebooting the
1212 host 6 times.
Scott Zawalski62bacae2013-03-05 10:40:32 -05001213
1214 @raises AutoservRepairMethodNA if the device does not support remote
1215 power.
1216 @raises AutoservRepairFailure if the repair fails for any reason.
1217
Richard Barnette82c35912012-11-20 10:09:10 -08001218 """
Scott Zawalski62bacae2013-03-05 10:40:32 -05001219 if not self.has_power():
1220 raise error.AutoservRepairMethodNA('Device does not support power.')
1221
Richard Barnette82c35912012-11-20 10:09:10 -08001222 logging.info('Attempting repair via RPM powercycle.')
1223 failed_cycles = 0
1224 self.power_cycle()
1225 while not self.wait_up(timeout=self.BOOT_TIMEOUT):
1226 failed_cycles += 1
1227 if failed_cycles >= self._MAX_POWER_CYCLE_ATTEMPTS:
Scott Zawalski62bacae2013-03-05 10:40:32 -05001228 raise error.AutoservRepairFailure(
1229 'Powercycled host %s %d times; device did not come back'
1230 ' online.' % (self.hostname, failed_cycles))
Richard Barnette82c35912012-11-20 10:09:10 -08001231 self.power_cycle()
1232 if failed_cycles == 0:
1233 logging.info('Powercycling was successful first time.')
1234 else:
1235 logging.info('Powercycling was successful after %d failures.',
1236 failed_cycles)
1237
1238
MK Ryu35d661e2014-09-25 17:44:10 -07001239 def _reboot_repair(self):
1240 """SSH to this host and reboot."""
1241 if not self.is_up(self._CHECK_HOST_UP_TIMEOUT_SECS):
1242 raise error.AutoservRepairMethodNA('DUT unreachable for reboot.')
1243 logging.info('Attempting repair via SSH reboot.')
1244 self.reboot(timeout=self.BOOT_TIMEOUT, wait=True)
1245
1246
Prashanth B4d8184f2014-05-05 12:22:02 -07001247 def check_device(self):
1248 """Check if a device is ssh-able, and if so, clean and verify it.
1249
1250 @raise AutoservSSHTimeout: If the ssh ping times out.
1251 @raise AutoservSshPermissionDeniedError: If ssh ping fails due to
1252 permissions.
1253 @raise AutoservSshPingHostError: For other AutoservRunErrors during
1254 ssh_ping.
1255 @raises AutoservError: As appropriate, during cleanup and verify.
1256 """
1257 self.ssh_ping()
1258 self.cleanup()
1259 self.verify()
1260
1261
Dan Shi90466352015-09-22 15:01:05 -07001262 def confirm_servo(self):
1263 """Confirm servo is initialized and verified.
1264
1265 @raise AutoservError: If servo is not initialized and verified.
1266 """
Tom Wai-Hong Tam244acc22016-01-09 07:04:21 +08001267 if self.servo and self._servo_host.required_by_test:
Dan Shi90466352015-09-22 15:01:05 -07001268 return
1269
1270 # Force to re-create the servo object to make sure servo is verified.
1271 logging.debug('Rebuilding the servo object.')
1272 self.servo = None
1273 self._servo_host = None
1274 self._setup_servo()
1275 if not self.servo:
1276 raise error.AutoservError('Failed to create servo object.')
1277
1278
Dan Shid07ee2e2015-09-24 14:49:25 -07001279 def _is_last_provision_failed(self):
1280 """Checks if the last provision job failed.
1281
1282 @return: True if there exists file /var/tmp/provision_failed, which
1283 indicates the last provision job failed.
1284 False if the file does not exist or the dut can't be reached.
1285 """
1286 try:
1287 result = self.run('test -f %s' % PROVISION_FAILED,
1288 ignore_status=True, timeout=5)
1289 return result.exit_status == 0
1290 except (error.AutoservRunError, error.AutoservSSHTimeout):
1291 # Default to False, for repair to try all repair method if the dut
1292 # can't be reached.
1293 return False
1294
1295
J. Richard Barnettec2d99cf2015-11-18 12:46:15 -08001296 def repair(self):
1297 """Attempt to get the DUT to pass `self.verify()`.
Richard Barnette82c35912012-11-20 10:09:10 -08001298
1299 This overrides the base class function for repair; it does
1300 not call back to the parent class, but instead offers a
1301 simplified implementation based on the capabilities in the
1302 Chrome OS test lab.
1303
Fang Deng5d518f42013-08-02 14:04:32 -07001304 It first verifies and repairs servo if it is a DUT in CrOS
Fang Deng03590af2013-10-07 17:34:20 -07001305 lab and a servo is attached.
Fang Deng5d518f42013-08-02 14:04:32 -07001306
Jakob Juelich82b7d1c2014-09-15 16:10:57 -07001307 This escalates in order through the following procedures and verifies
1308 the status using `self.check_device()` after each of them. This is done
1309 until both the repair and the veryfing step succeed.
1310
MK Ryu35d661e2014-09-25 17:44:10 -07001311 Escalation order of repair procedures from less intrusive to
1312 more intrusive repairs:
1313 1. SSH to the DUT and reboot.
Scott Zawalski62bacae2013-03-05 10:40:32 -05001314 2. If there's a servo for the DUT, try to power the DUT off and
1315 on.
MK Ryu35d661e2014-09-25 17:44:10 -07001316 3. If the DUT can be power-cycled via RPM, try to repair
Richard Barnette82c35912012-11-20 10:09:10 -08001317 by power-cycling.
MK Ryu35d661e2014-09-25 17:44:10 -07001318 4. Try to re-install to a known stable image using
1319 auto-update.
1320 5. If there's a servo for the DUT, try to re-install via
1321 the servo.
Richard Barnette82c35912012-11-20 10:09:10 -08001322
1323 As with the parent method, the last operation performed on
Prashanth B4d8184f2014-05-05 12:22:02 -07001324 the DUT must be to call `self.check_device()`; If that call fails the
1325 exception it raises is passed back to the caller.
J. Richard Barnettefde55fc2013-03-15 17:47:01 -07001326
Scott Zawalski62bacae2013-03-05 10:40:32 -05001327 @raises AutoservRepairTotalFailure if the repair process fails to
1328 fix the DUT.
Fang Deng5d518f42013-08-02 14:04:32 -07001329 @raises ServoHostRepairTotalFailure if the repair process fails to
1330 fix the servo host if one is attached to the DUT.
1331 @raises AutoservSshPermissionDeniedError if it is unable
1332 to ssh to the servo host due to permission error.
1333
Richard Barnette82c35912012-11-20 10:09:10 -08001334 """
Jakob Juelich82b7d1c2014-09-15 16:10:57 -07001335 # Caution: Deleting shards relies on repair to always reboot the DUT.
1336
Nicolas Boichate30c7e12015-11-05 11:12:50 +08001337 # To repair a DUT connected to a moblab, try to create a servo object if
1338 # it was failed to be created earlier as there may be a servo_host host
1339 # attribute for this host.
1340 if utils.is_moblab():
1341 self._setup_servo()
1342
Dan Shi4d478522014-02-14 13:46:32 -08001343 if self._servo_host and not self.servo:
Fang Deng03590af2013-10-07 17:34:20 -07001344 try:
J. Richard Barnette4fc59c42015-12-15 16:58:50 -08001345 self._servo_host.repair()
Fang Deng03590af2013-10-07 17:34:20 -07001346 except Exception as e:
Fang Deng03590af2013-10-07 17:34:20 -07001347 logging.error('Could not create a healthy servo: %s', e)
Dan Shi4d478522014-02-14 13:46:32 -08001348 self.servo = self._servo_host.get_servo()
Fang Deng5d518f42013-08-02 14:04:32 -07001349
MK Ryu35d661e2014-09-25 17:44:10 -07001350 self.try_collect_crashlogs()
1351
Scott Zawalski62bacae2013-03-05 10:40:32 -05001352 # TODO(scottz): This should use something similar to label_decorator,
1353 # but needs to be populated in order so DUTs are repaired with the
1354 # least amount of effort.
Dan Shid07ee2e2015-09-24 14:49:25 -07001355 force_powerwash = self._is_last_provision_failed()
1356 if force_powerwash:
1357 logging.info('Last provision failed, try powerwash first.')
1358 autotest_stats.Counter(
1359 'repair_force_powerwash.TOTAL').increment()
Tom Wai-Hong Tamb284ce42016-01-15 08:11:38 +08001360 repair_funcs = [self._firmware_repair,
1361 self._install_repair_with_powerwash,
1362 self._servo_repair_reinstall]
Dan Shid07ee2e2015-09-24 14:49:25 -07001363 else:
1364 repair_funcs = [self._reboot_repair,
1365 self._servo_repair_power,
Tom Wai-Hong Tamb284ce42016-01-15 08:11:38 +08001366 self._firmware_repair,
Dan Shid07ee2e2015-09-24 14:49:25 -07001367 self._powercycle_to_repair,
1368 self._install_repair,
1369 self._install_repair_with_powerwash,
Tom Wai-Hong Tamb284ce42016-01-15 08:11:38 +08001370 self._servo_repair_reinstall]
Scott Zawalski62bacae2013-03-05 10:40:32 -05001371 errors = []
Simran Basie6130932013-10-01 14:07:52 -07001372 board = self._get_board_from_afe()
Scott Zawalski62bacae2013-03-05 10:40:32 -05001373 for repair_func in repair_funcs:
1374 try:
1375 repair_func()
MK Ryu35d661e2014-09-25 17:44:10 -07001376 self.try_collect_crashlogs()
Prashanth B4d8184f2014-05-05 12:22:02 -07001377 self.check_device()
Gabe Black1e1c41b2015-02-04 23:55:15 -08001378 autotest_stats.Counter(
Simran Basie6130932013-10-01 14:07:52 -07001379 '%s.SUCCEEDED' % repair_func.__name__).increment()
1380 if board:
Gabe Black1e1c41b2015-02-04 23:55:15 -08001381 autotest_stats.Counter(
Dan Shid07ee2e2015-09-24 14:49:25 -07001382 '%s.%s.SUCCEEDED' % (repair_func.__name__,
Simran Basie6130932013-10-01 14:07:52 -07001383 board)).increment()
Dan Shid07ee2e2015-09-24 14:49:25 -07001384 if force_powerwash:
1385 autotest_stats.Counter(
1386 'repair_force_powerwash.SUCCEEDED').increment()
Scott Zawalski62bacae2013-03-05 10:40:32 -05001387 return
Simran Basie6130932013-10-01 14:07:52 -07001388 except error.AutoservRepairMethodNA as e:
Gabe Black1e1c41b2015-02-04 23:55:15 -08001389 autotest_stats.Counter(
Simran Basie6130932013-10-01 14:07:52 -07001390 '%s.RepairNA' % repair_func.__name__).increment()
1391 if board:
Gabe Black1e1c41b2015-02-04 23:55:15 -08001392 autotest_stats.Counter(
Dan Shid07ee2e2015-09-24 14:49:25 -07001393 '%s.%s.RepairNA' % (repair_func.__name__,
1394 board)).increment()
Ilja H. Friedel04be2bd2014-05-07 21:29:59 -07001395 logging.warning('Repair function NA: %s', e)
Simran Basie6130932013-10-01 14:07:52 -07001396 errors.append(str(e))
Scott Zawalski62bacae2013-03-05 10:40:32 -05001397 except Exception as e:
Gabe Black1e1c41b2015-02-04 23:55:15 -08001398 autotest_stats.Counter(
Simran Basie6130932013-10-01 14:07:52 -07001399 '%s.FAILED' % repair_func.__name__).increment()
1400 if board:
Gabe Black1e1c41b2015-02-04 23:55:15 -08001401 autotest_stats.Counter(
Dan Shid07ee2e2015-09-24 14:49:25 -07001402 '%s.%s.FAILED' % (repair_func.__name__,
1403 board)).increment()
Ilja H. Friedel04be2bd2014-05-07 21:29:59 -07001404 logging.warning('Failed to repair device: %s', e)
Scott Zawalski62bacae2013-03-05 10:40:32 -05001405 errors.append(str(e))
Scott Zawalski89c44dd2013-02-26 09:28:02 -05001406
Dan Shid07ee2e2015-09-24 14:49:25 -07001407 if force_powerwash:
1408 autotest_stats.Counter(
1409 'repair_force_powerwash.FAILED').increment()
Gabe Black1e1c41b2015-02-04 23:55:15 -08001410 autotest_stats.Counter('Full_Repair_Failed').increment()
Simran Basie6130932013-10-01 14:07:52 -07001411 if board:
Gabe Black1e1c41b2015-02-04 23:55:15 -08001412 autotest_stats.Counter(
Dan Shid07ee2e2015-09-24 14:49:25 -07001413 'Full_Repair_Failed.%s' % board).increment()
Scott Zawalski62bacae2013-03-05 10:40:32 -05001414 raise error.AutoservRepairTotalFailure(
1415 'All attempts at repairing the device failed:\n%s' %
1416 '\n'.join(errors))
Richard Barnette82c35912012-11-20 10:09:10 -08001417
1418
MK Ryu35d661e2014-09-25 17:44:10 -07001419 def try_collect_crashlogs(self, check_host_up=True):
1420 """
1421 Check if a host is up and logs need to be collected from the host,
1422 if yes, collect them.
1423
1424 @param check_host_up: Flag for checking host is up. Default is True.
1425 """
1426 try:
1427 crash_job = self._need_crash_logs()
1428 if crash_job:
1429 logging.debug('%s: Job %s was crashed', self._CRASHLOGS_PREFIX,
1430 crash_job)
1431 if not check_host_up or self.is_up(
1432 self._CHECK_HOST_UP_TIMEOUT_SECS):
1433 self._collect_crashlogs(crash_job)
1434 logging.debug('%s: Completed collecting logs for the '
1435 'crashed job %s', self._CRASHLOGS_PREFIX,
1436 crash_job)
1437 except Exception as e:
1438 # Exception should not result in repair failure.
1439 # Therefore, suppress all exceptions here.
1440 logging.error('%s: Failed while trying to collect crash-logs: %s',
1441 self._CRASHLOGS_PREFIX, e)
1442
1443
1444 def _need_crash_logs(self):
1445 """Get the value of need_crash_logs attribute of this host.
1446
1447 @return: Value string of need_crash_logs attribute
1448 None if there is no need_crash_logs attribute
1449 """
1450 attrs = self._AFE.get_host_attribute(constants.CRASHLOGS_HOST_ATTRIBUTE,
1451 hostname=self.hostname)
1452 assert len(attrs) < 2
1453 return attrs[0].value if attrs else None
1454
1455
1456 def _collect_crashlogs(self, job_id):
1457 """Grab logs from the host where a job was crashed.
1458
1459 First, check if PRIOR_LOGS_DIR exists in the host.
1460 If yes, collect them.
1461 Otherwise, check if a lab-machine marker (_LAB_MACHINE_FILE) exists
1462 in the host.
1463 If yes, the host was repaired automatically, and we collect normal
1464 system logs.
1465
1466 @param job_id: Id of the job that was crashed.
1467 """
1468 crashlogs_dir = crashcollect.get_crashinfo_dir(self,
1469 constants.CRASHLOGS_DEST_DIR_PREFIX)
1470 flag_prior_logs = False
1471
1472 if self.path_exists(client_constants.PRIOR_LOGS_DIR):
1473 flag_prior_logs = True
1474 self._collect_prior_logs(crashlogs_dir)
1475 elif self.path_exists(self._LAB_MACHINE_FILE):
1476 self._collect_system_logs(crashlogs_dir)
1477 else:
1478 logging.warning('%s: Host was manually re-installed without '
1479 '--lab_preserve_log option. Skip collecting '
1480 'crash-logs.', self._CRASHLOGS_PREFIX)
1481
1482 # We make crash collection be one-time effort.
1483 # _collect_prior_logs() and _collect_system_logs() will not throw
1484 # any exception, and following codes will be executed even when
1485 # those methods fail.
1486 # _collect_crashlogs() is called only when the host is up (refer
1487 # to try_collect_crashlogs()). We assume _collect_prior_logs() and
1488 # _collect_system_logs() fail rarely when the host is up.
1489 # In addition, it is not clear how many times we should try crash
1490 # collection again while not triggering next repair unnecessarily.
1491 # Threfore, we try crash collection one time.
1492
1493 # Create a marker file as soon as log collection is done.
1494 # Leave the job id to this marker for gs_offloader to consume.
1495 marker_file = os.path.join(crashlogs_dir, constants.CRASHLOGS_MARKER)
1496 with open(marker_file, 'a') as f:
1497 f.write('%s\n' % job_id)
1498
1499 # Remove need_crash_logs attribute
1500 logging.debug('%s: Remove attribute need_crash_logs from host %s',
1501 self._CRASHLOGS_PREFIX, self.hostname)
1502 self._AFE.set_host_attribute(constants.CRASHLOGS_HOST_ATTRIBUTE,
1503 None, hostname=self.hostname)
1504
1505 if flag_prior_logs:
1506 logging.debug('%s: Remove %s from host %s', self._CRASHLOGS_PREFIX,
1507 client_constants.PRIOR_LOGS_DIR, self.hostname)
1508 self.run('rm -rf %s; sync' % client_constants.PRIOR_LOGS_DIR)
1509 # Wait for a few seconds to make sure the prior command is
1510 # done deep through storage.
1511 time.sleep(self._SAFE_WAIT_SECS)
1512
1513
1514 def _collect_prior_logs(self, crashlogs_dir):
1515 """Grab prior logs that were stashed before re-installing a host.
1516
1517 @param crashlogs_dir: Directory path where crash-logs are stored.
1518 """
1519 logging.debug('%s: Found %s, collecting them...',
1520 self._CRASHLOGS_PREFIX, client_constants.PRIOR_LOGS_DIR)
1521 try:
1522 self.collect_logs(client_constants.PRIOR_LOGS_DIR,
1523 crashlogs_dir, False)
1524 logging.debug('%s: %s is collected',
1525 self._CRASHLOGS_PREFIX, client_constants.PRIOR_LOGS_DIR)
1526 except Exception as e:
1527 logging.error('%s: Failed to collect %s: %s',
1528 self._CRASHLOGS_PREFIX, client_constants.PRIOR_LOGS_DIR,
1529 e)
1530
1531
1532 def _collect_system_logs(self, crashlogs_dir):
1533 """Grab normal system logs from a host.
1534
1535 @param crashlogs_dir: Directory path where crash-logs are stored.
1536 """
1537 logging.debug('%s: Found %s, collecting system logs...',
1538 self._CRASHLOGS_PREFIX, self._LAB_MACHINE_FILE)
1539 sources = server_utils.parse_simple_config(self._LOGS_TO_COLLECT_FILE)
1540 for src in sources:
1541 try:
1542 if self.path_exists(src):
1543 logging.debug('%s: Collecting %s...',
1544 self._CRASHLOGS_PREFIX, src)
1545 dest = server_utils.concat_path_except_last(
1546 crashlogs_dir, src)
1547 self.collect_logs(src, dest, False)
1548 logging.debug('%s: %s is collected',
1549 self._CRASHLOGS_PREFIX, src)
1550 except Exception as e:
1551 logging.error('%s: Failed to collect %s: %s',
1552 self._CRASHLOGS_PREFIX, src, e)
1553
1554
J. Richard Barnette1d78b012012-05-15 13:56:30 -07001555 def close(self):
Fang Deng0ca40e22013-08-27 17:47:44 -07001556 super(CrosHost, self).close()
J. Richard Barnette1d78b012012-05-15 13:56:30 -07001557
1558
Dan Shi49ca0932014-11-14 11:22:27 -08001559 def get_power_supply_info(self):
1560 """Get the output of power_supply_info.
1561
1562 power_supply_info outputs the info of each power supply, e.g.,
1563 Device: Line Power
1564 online: no
1565 type: Mains
1566 voltage (V): 0
1567 current (A): 0
1568 Device: Battery
1569 state: Discharging
1570 percentage: 95.9276
1571 technology: Li-ion
1572
1573 Above output shows two devices, Line Power and Battery, with details of
1574 each device listed. This function parses the output into a dictionary,
1575 with key being the device name, and value being a dictionary of details
1576 of the device info.
1577
1578 @return: The dictionary of power_supply_info, e.g.,
1579 {'Line Power': {'online': 'yes', 'type': 'main'},
1580 'Battery': {'vendor': 'xyz', 'percentage': '100'}}
Dan Shie9b765d2014-12-29 16:59:49 -08001581 @raise error.AutoservRunError if power_supply_info tool is not found in
1582 the DUT. Caller should handle this error to avoid false failure
1583 on verification.
Dan Shi49ca0932014-11-14 11:22:27 -08001584 """
1585 result = self.run('power_supply_info').stdout.strip()
1586 info = {}
1587 device_name = None
1588 device_info = {}
1589 for line in result.split('\n'):
1590 pair = [v.strip() for v in line.split(':')]
1591 if len(pair) != 2:
1592 continue
1593 if pair[0] == 'Device':
1594 if device_name:
1595 info[device_name] = device_info
1596 device_name = pair[1]
1597 device_info = {}
1598 else:
1599 device_info[pair[0]] = pair[1]
1600 if device_name and not device_name in info:
1601 info[device_name] = device_info
1602 return info
1603
1604
1605 def get_battery_percentage(self):
1606 """Get the battery percentage.
1607
1608 @return: The percentage of battery level, value range from 0-100. Return
1609 None if the battery info cannot be retrieved.
1610 """
1611 try:
1612 info = self.get_power_supply_info()
1613 logging.info(info)
1614 return float(info['Battery']['percentage'])
Dan Shie9b765d2014-12-29 16:59:49 -08001615 except (KeyError, ValueError, error.AutoservRunError):
Dan Shi49ca0932014-11-14 11:22:27 -08001616 return None
1617
1618
1619 def is_ac_connected(self):
1620 """Check if the dut has power adapter connected and charging.
1621
1622 @return: True if power adapter is connected and charging.
1623 """
1624 try:
1625 info = self.get_power_supply_info()
1626 return info['Line Power']['online'] == 'yes'
Dan Shie9b765d2014-12-29 16:59:49 -08001627 except (KeyError, error.AutoservRunError):
1628 return None
Dan Shi49ca0932014-11-14 11:22:27 -08001629
1630
Simran Basi5e6339a2013-03-21 11:34:32 -07001631 def _cleanup_poweron(self):
1632 """Special cleanup method to make sure hosts always get power back."""
1633 afe = frontend_wrappers.RetryingAFE(timeout_min=5, delay_sec=10)
1634 hosts = afe.get_hosts(hostname=self.hostname)
1635 if not hosts or not (self._RPM_OUTLET_CHANGED in
1636 hosts[0].attributes):
1637 return
1638 logging.debug('This host has recently interacted with the RPM'
1639 ' Infrastructure. Ensuring power is on.')
1640 try:
1641 self.power_on()
Dan Shi7dca56e2014-11-11 17:07:56 -08001642 afe.set_host_attribute(self._RPM_OUTLET_CHANGED, None,
1643 hostname=self.hostname)
Simran Basi5e6339a2013-03-21 11:34:32 -07001644 except rpm_client.RemotePowerException:
Simran Basi5e6339a2013-03-21 11:34:32 -07001645 logging.error('Failed to turn Power On for this host after '
1646 'cleanup through the RPM Infrastructure.')
Gabe Blackb72f4fb2015-01-20 16:47:13 -08001647 autotest_es.post(
Dan Shi7dca56e2014-11-11 17:07:56 -08001648 type_str='RPM_poweron_failure',
1649 metadata={'hostname': self.hostname})
Dan Shi49ca0932014-11-14 11:22:27 -08001650
1651 battery_percentage = self.get_battery_percentage()
Dan Shif01ebe22014-12-05 13:10:57 -08001652 if battery_percentage and battery_percentage < 50:
Dan Shi49ca0932014-11-14 11:22:27 -08001653 raise
1654 elif self.is_ac_connected():
1655 logging.info('The device has power adapter connected and '
1656 'charging. No need to try to turn RPM on '
1657 'again.')
1658 afe.set_host_attribute(self._RPM_OUTLET_CHANGED, None,
1659 hostname=self.hostname)
1660 logging.info('Battery level is now at %s%%. The device may '
1661 'still have enough power to run test, so no '
1662 'exception will be raised.', battery_percentage)
1663
Simran Basi5e6339a2013-03-21 11:34:32 -07001664
beepsc87ff602013-07-31 21:53:00 -07001665 def _is_factory_image(self):
1666 """Checks if the image on the DUT is a factory image.
1667
1668 @return: True if the image on the DUT is a factory image.
1669 False otherwise.
1670 """
1671 result = self.run('[ -f /root/.factory_test ]', ignore_status=True)
1672 return result.exit_status == 0
1673
1674
1675 def _restart_ui(self):
J. Richard Barnette84890bd2014-02-21 11:05:47 -08001676 """Restart the Chrome UI.
beepsc87ff602013-07-31 21:53:00 -07001677
1678 @raises: FactoryImageCheckerException for factory images, since
1679 we cannot attempt to restart ui on them.
1680 error.AutoservRunError for any other type of error that
1681 occurs while restarting ui.
1682 """
1683 if self._is_factory_image():
Dan Shi549fb822015-03-24 18:01:11 -07001684 raise FactoryImageCheckerException('Cannot restart ui on factory '
1685 'images')
beepsc87ff602013-07-31 21:53:00 -07001686
J. Richard Barnette84890bd2014-02-21 11:05:47 -08001687 # TODO(jrbarnette): The command to stop/start the ui job
1688 # should live inside cros_ui, too. However that would seem
1689 # to imply interface changes to the existing start()/restart()
1690 # functions, which is a bridge too far (for now).
J. Richard Barnette6069aa12015-06-08 09:10:24 -07001691 prompt = cros_ui.get_chrome_session_ident(self)
J. Richard Barnette84890bd2014-02-21 11:05:47 -08001692 self.run('stop ui; start ui')
1693 cros_ui.wait_for_chrome_ready(prompt, self)
beepsc87ff602013-07-31 21:53:00 -07001694
1695
Dan Shi549fb822015-03-24 18:01:11 -07001696 def get_release_version(self):
1697 """Get the value of attribute CHROMEOS_RELEASE_VERSION from lsb-release.
1698
1699 @returns The version string in lsb-release, under attribute
1700 CHROMEOS_RELEASE_VERSION.
1701 """
1702 lsb_release_content = self.run(
1703 'cat "%s"' % client_constants.LSB_RELEASE).stdout.strip()
1704 return lsbrelease_utils.get_chromeos_release_version(
1705 lsb_release_content=lsb_release_content)
1706
1707
1708 def verify_cros_version_label(self):
1709 """ Make sure host's cros-version label match the actual image in dut.
1710
1711 Remove any cros-version: label that doesn't match that installed in
1712 the dut.
1713
1714 @param raise_error: Set to True to raise exception if any mismatch found
1715
1716 @raise error.AutoservError: If any mismatch between cros-version label
1717 and the build installed in dut is found.
1718 """
1719 labels = self._AFE.get_labels(
1720 name__startswith=ds_constants.VERSION_PREFIX,
1721 host__hostname=self.hostname)
1722 mismatch_found = False
1723 if labels:
1724 # Get CHROMEOS_RELEASE_VERSION from lsb-release, e.g., 6908.0.0.
1725 # Note that it's different from cros-version label, which has
1726 # builder and branch info, e.g.,
1727 # cros-version:peppy-release/R43-6908.0.0
1728 release_version = self.get_release_version()
1729 host_list = [self.hostname]
1730 for label in labels:
1731 # Remove any cros-version label that does not match
1732 # release_version.
1733 build_version = label.name[len(ds_constants.VERSION_PREFIX):]
1734 if not utils.version_match(build_version, release_version):
1735 logging.warn('cros-version label "%s" does not match '
1736 'release version %s. Removing the label.',
1737 label.name, release_version)
1738 label.remove_hosts(hosts=host_list)
1739 mismatch_found = True
1740 if mismatch_found:
Dan Shi1057bae2015-03-30 11:35:09 -07001741 autotest_es.post(use_http=True,
1742 type_str='cros_version_label_mismatch',
1743 metadata={'hostname': self.hostname})
Dan Shi549fb822015-03-24 18:01:11 -07001744 raise error.AutoservError('The host has wrong cros-version label.')
1745
1746
Darren Krahn0bd18e82015-10-28 23:30:46 +00001747 def verify_tpm_status(self):
1748 """ Verify the host's TPM is in a good state.
1749
1750 @raise error.AutoservError: If state is not good.
1751 """
1752 # This cryptohome command emits status information in JSON format. It
1753 # looks something like this:
1754 # {
1755 # "installattrs": {
1756 # "first_install": false,
1757 # "initialized": true,
1758 # "invalid": false,
1759 # "lockbox_index": 536870916,
1760 # "lockbox_nvram_version": 2,
1761 # "secure": true,
1762 # "size": 0,
1763 # "version": 1
1764 # },
1765 # "mounts": [ {
1766 # "enterprise": false,
1767 # "keysets": [ {
1768 # "current": true,
1769 # "index": 0,
1770 # "last_activity": 1330111359,
1771 # "ok": true,
1772 # "scrypt": true,
1773 # "tpm": false
1774 # } ],
1775 # "mounted": true,
1776 # "owner": "dbb3dd34edb181245130e136be51fa08478d3909"
1777 # } ],
1778 # "tpm": {
1779 # "being_owned": false,
1780 # "can_connect": true,
1781 # "can_decrypt": false,
1782 # "can_encrypt": false,
1783 # "can_load_srk": true,
1784 # "can_load_srk_pubkey": true,
1785 # "enabled": true,
1786 # "has_context": true,
1787 # "has_cryptohome_key": false,
1788 # "has_key_handle": false,
1789 # "last_error": 0,
1790 # "owned": true
1791 # }
1792 # }
1793 output = self.run('cryptohome --action=status').stdout.strip()
1794 try:
1795 status = json.loads(output)
1796 except ValueError:
1797 logging.error('TPM_VERIFY: Cryptohome did not return valid status.')
1798 return
1799 try:
1800 tpm = status['tpm']
1801 if (not tpm['enabled'] or not tpm['can_connect'] or
1802 (tpm['owned'] and not tpm['can_load_srk']) or
1803 (tpm['can_load_srk'] and not tpm['can_load_srk_pubkey'])):
1804 logging.error('TPM_VERIFY: The host TPM is in a bad state.')
1805 raise error.AutoservError('The host TPM is in a bad state.')
1806 else:
1807 logging.debug('TPM_VERIFY: The host TPM is in a good state.')
1808 except KeyError:
1809 logging.error('TPM_VERIFY: Cryptohome did not return valid status.')
1810
1811
Tom Wai-Hong Tambea741c2016-01-21 07:20:14 +08001812 def verify_firmware_status(self):
1813 """Verify the host's firmware is in a good state.
1814
1815 @raise error.AutoservError: If state is not good.
1816 """
1817 if self._is_firmware_repair_supported():
Tom Wai-Hong Tam93a29562016-01-23 04:16:53 +08001818 try:
1819 # Read the AP firmware and dump the sections we are interested.
1820 cmd = ('mkdir /tmp/verify_firmware; '
1821 'cd /tmp/verify_firmware; '
1822 'for section in VBLOCK_A VBLOCK_B FW_MAIN_A FW_MAIN_B; '
1823 'do flashrom -r image.bin -i $section:$section; '
1824 'done')
1825 self.run(cmd)
1826
1827 # Verify the firmware blocks A and B.
1828 cmd = ('vbutil_firmware --verify /tmp/verify_firmware/VBLOCK_%c'
1829 ' --signpubkey /usr/share/vboot/devkeys/root_key.vbpubk'
1830 ' --fv /tmp/verify_firmware/FW_MAIN_%c')
1831 for c in ('A', 'B'):
1832 rv = self.run(cmd % (c, c), ignore_status=True)
1833 if rv.exit_status:
1834 raise error.AutoservError(
1835 'Firmware %c is in a bad state.' % c)
1836 finally:
1837 # Remove the tempoary files.
1838 self.run('rm -rf /tmp/verify_firmware')
Tom Wai-Hong Tambea741c2016-01-21 07:20:14 +08001839 else:
1840 logging.info('Do not care about firmware status when the host '
1841 'is not in pools that support firmware repair.')
1842
1843
Shelley Chena11b9e72016-01-21 15:15:18 -08001844 def verify_filesystem_write_status(self):
1845 """Verify the DUT's filesystem is read/writable
1846
1847 @raise error.AutoservError: if filesystem is not writable.
1848 """
1849 # try to create & delete a file
1850 filename = "/mnt/stateful_partition/test.txt"
1851 cmd = 'touch %s && rm %s' % (filename, filename)
1852 rv = self.run(command=cmd, ignore_status=True)
1853
1854 if rv.exit_status == 1:
1855 raise error.AutoservError('DUT filesystem is read-only.')
1856
1857
beepsc87ff602013-07-31 21:53:00 -07001858 def cleanup(self):
MK Ryu35d661e2014-09-25 17:44:10 -07001859 self.run('rm -f %s' % client_constants.CLEANUP_LOGS_PAUSED_FILE)
Scott Zawalskiddbc31e2012-11-15 11:29:01 -05001860 try:
beepsc87ff602013-07-31 21:53:00 -07001861 self._restart_ui()
1862 except (error.AutotestRunError, error.AutoservRunError,
1863 FactoryImageCheckerException):
Ilja H. Friedel04be2bd2014-05-07 21:29:59 -07001864 logging.warning('Unable to restart ui, rebooting device.')
Scott Zawalskiddbc31e2012-11-15 11:29:01 -05001865 # Since restarting the UI fails fall back to normal Autotest
1866 # cleanup routines, i.e. reboot the machine.
Fang Deng0ca40e22013-08-27 17:47:44 -07001867 super(CrosHost, self).cleanup()
Simran Basi5e6339a2013-03-21 11:34:32 -07001868 # Check if the rpm outlet was manipulated.
Simran Basid5e5e272012-09-24 15:23:59 -07001869 if self.has_power():
Simran Basi5e6339a2013-03-21 11:34:32 -07001870 self._cleanup_poweron()
Dan Shi549fb822015-03-24 18:01:11 -07001871 self.verify_cros_version_label()
J. Richard Barnette45e93de2012-04-11 17:24:15 -07001872
1873
Yu-Ju Honga2be94a2012-07-31 09:48:52 -07001874 def reboot(self, **dargs):
1875 """
1876 This function reboots the site host. The more generic
1877 RemoteHost.reboot() performs sync and sleeps for 5
1878 seconds. This is not necessary for Chrome OS devices as the
1879 sync should be finished in a short time during the reboot
1880 command.
1881 """
Tom Wai-Hong Tamf5cd1d42012-08-13 12:04:08 +08001882 if 'reboot_cmd' not in dargs:
Doug Anderson7d5aeb22014-02-27 15:12:17 -08001883 reboot_timeout = dargs.get('reboot_timeout', 10)
J. Richard Barnette9af19632015-09-25 12:18:03 -07001884 dargs['reboot_cmd'] = ('sleep 1; '
1885 'reboot & sleep %d; '
1886 'reboot -f' % reboot_timeout)
Yu-Ju Honga2be94a2012-07-31 09:48:52 -07001887 # Enable fastsync to avoid running extra sync commands before reboot.
Tom Wai-Hong Tamf5cd1d42012-08-13 12:04:08 +08001888 if 'fastsync' not in dargs:
1889 dargs['fastsync'] = True
Michael Liangda8c60a2014-06-03 13:24:51 -07001890
Charlie Mooneya8e6dab2014-05-29 14:37:55 -07001891 # For purposes of logging reboot times:
1892 # Get the board name i.e. 'daisy_spring'
Michael Liangca4f5a62014-07-10 15:45:13 -07001893 board_fullname = self.get_board()
1894
1895 # Strip the prefix and add it to dargs.
1896 dargs['board'] = board_fullname[board_fullname.find(':')+1:]
Fang Deng0ca40e22013-08-27 17:47:44 -07001897 super(CrosHost, self).reboot(**dargs)
Yu-Ju Honga2be94a2012-07-31 09:48:52 -07001898
1899
Gwendal Grignou7a61d2f2014-05-23 11:05:51 -07001900 def suspend(self, **dargs):
1901 """
1902 This function suspends the site host.
1903 """
1904 suspend_time = dargs.get('suspend_time', 60)
1905 dargs['timeout'] = suspend_time
1906 if 'suspend_cmd' not in dargs:
J. Richard Barnette9af19632015-09-25 12:18:03 -07001907 dargs['suspend_cmd'] = ' && '.join([
1908 'echo 0 > /sys/class/rtc/rtc0/wakealarm',
Gwendal Grignou7a61d2f2014-05-23 11:05:51 -07001909 'echo +%d > /sys/class/rtc/rtc0/wakealarm' % suspend_time,
J. Richard Barnette9af19632015-09-25 12:18:03 -07001910 'powerd_dbus_suspend --delay=0'])
Gwendal Grignou7a61d2f2014-05-23 11:05:51 -07001911 super(CrosHost, self).suspend(**dargs)
1912
1913
Simran Basiec564392014-08-25 16:48:09 -07001914 def upstart_status(self, service_name):
1915 """Check the status of an upstart init script.
1916
1917 @param service_name: Service to look up.
1918
1919 @returns True if the service is running, False otherwise.
1920 """
1921 return self.run('status %s | grep start/running' %
1922 service_name).stdout.strip() != ''
1923
1924
J. Richard Barnette45e93de2012-04-11 17:24:15 -07001925 def verify_software(self):
Richard Barnetteb2bc13c2013-01-08 17:32:51 -08001926 """Verify working software on a Chrome OS system.
J. Richard Barnette45e93de2012-04-11 17:24:15 -07001927
Richard Barnetteb2bc13c2013-01-08 17:32:51 -08001928 Tests for the following conditions:
1929 1. All conditions tested by the parent version of this
1930 function.
1931 2. Sufficient space in /mnt/stateful_partition.
Fang Deng6b05f5b2013-03-20 13:42:11 -07001932 3. Sufficient space in /mnt/stateful_partition/encrypted.
1933 4. update_engine answers a simple status request over DBus.
J. Richard Barnette45e93de2012-04-11 17:24:15 -07001934
J. Richard Barnette45e93de2012-04-11 17:24:15 -07001935 """
MK Ryu35d661e2014-09-25 17:44:10 -07001936 # Check if a job was crashed on this host.
1937 # If yes, avoid verification until crash-logs are collected.
1938 if self._need_crash_logs():
1939 raise error.AutoservCrashLogCollectRequired(
1940 'Need to collect crash-logs before verification')
1941
Fang Deng0ca40e22013-08-27 17:47:44 -07001942 super(CrosHost, self).verify_software()
Dan Shib8540a52015-07-16 14:18:23 -07001943 default_kilo_inodes_required = CONFIG.get_config_value(
1944 'SERVER', 'kilo_inodes_required', type=int, default=100)
1945 board = self.get_board().replace(ds_constants.BOARD_PREFIX, '')
1946 kilo_inodes_required = CONFIG.get_config_value(
1947 'SERVER', 'kilo_inodes_required_%s' % board,
1948 type=int, default=default_kilo_inodes_required)
1949 self.check_inodes('/mnt/stateful_partition', kilo_inodes_required)
J. Richard Barnette45e93de2012-04-11 17:24:15 -07001950 self.check_diskspace(
1951 '/mnt/stateful_partition',
Dan Shib8540a52015-07-16 14:18:23 -07001952 CONFIG.get_config_value(
Fang Deng6b05f5b2013-03-20 13:42:11 -07001953 'SERVER', 'gb_diskspace_required', type=float,
1954 default=20.0))
Gaurav Shahe448af82014-06-19 15:18:59 -07001955 encrypted_stateful_path = '/mnt/stateful_partition/encrypted'
1956 # Not all targets build with encrypted stateful support.
1957 if self.path_exists(encrypted_stateful_path):
1958 self.check_diskspace(
1959 encrypted_stateful_path,
Dan Shib8540a52015-07-16 14:18:23 -07001960 CONFIG.get_config_value(
Gaurav Shahe448af82014-06-19 15:18:59 -07001961 'SERVER', 'gb_encrypted_diskspace_required', type=float,
1962 default=0.1))
beepsc87ff602013-07-31 21:53:00 -07001963
Simran Basiec564392014-08-25 16:48:09 -07001964 if not self.upstart_status('system-services'):
Prashanth B5d0a0512014-04-25 12:26:08 -07001965 raise error.AutoservError('Chrome failed to reach login. '
1966 'System services not running.')
1967
beepsc87ff602013-07-31 21:53:00 -07001968 # Factory images don't run update engine,
1969 # goofy controls dbus on these DUTs.
1970 if not self._is_factory_image():
1971 self.run('update_engine_client --status')
Scott Zawalskifbca4a92013-03-04 15:56:42 -05001972 # Makes sure python is present, loads and can use built in functions.
1973 # We have seen cases where importing cPickle fails with undefined
1974 # symbols in cPickle.so.
1975 self.run('python -c "import cPickle"')
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001976
Dan Shi549fb822015-03-24 18:01:11 -07001977 self.verify_cros_version_label()
1978
Darren Krahn0bd18e82015-10-28 23:30:46 +00001979 self.verify_tpm_status()
1980
Tom Wai-Hong Tambea741c2016-01-21 07:20:14 +08001981 self.verify_firmware_status()
1982
Shelley Chena11b9e72016-01-21 15:15:18 -08001983 self.verify_filesystem_write_status()
1984
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001985
Dan Shi49ca0932014-11-14 11:22:27 -08001986 def verify_hardware(self):
1987 """Verify hardware system of a Chrome OS system.
1988
1989 Check following hardware conditions:
1990 1. Battery level.
1991 2. Is power adapter connected.
1992 """
1993 logging.info('Battery percentage: %s', self.get_battery_percentage())
Dan Shie9b765d2014-12-29 16:59:49 -08001994 if self.is_ac_connected() is None:
1995 logging.info('Can not determine if the device has power adapter '
1996 'connected.')
1997 else:
1998 logging.info('Device %s power adapter connected and charging.',
1999 'has' if self.is_ac_connected() else 'does not have')
Dan Shi49ca0932014-11-14 11:22:27 -08002000
2001
Fang Deng96667ca2013-08-01 17:46:18 -07002002 def make_ssh_command(self, user='root', port=22, opts='', hosts_file=None,
2003 connect_timeout=None, alive_interval=None):
2004 """Override default make_ssh_command to use options tuned for Chrome OS.
2005
2006 Tuning changes:
2007 - ConnectTimeout=30; maximum of 30 seconds allowed for an SSH
2008 connection failure. Consistency with remote_access.sh.
2009
Samuel Tan2ce155b2015-06-23 18:24:38 -07002010 - ServerAliveInterval=900; which causes SSH to ping connection every
2011 900 seconds. In conjunction with ServerAliveCountMax ensures
2012 that if the connection dies, Autotest will bail out.
Fang Deng96667ca2013-08-01 17:46:18 -07002013 Originally tried 60 secs, but saw frequent job ABORTS where
Samuel Tan2ce155b2015-06-23 18:24:38 -07002014 the test completed successfully. Later increased from 180 seconds to
2015 900 seconds to account for tests where the DUT is suspended for
2016 longer periods of time.
Fang Deng96667ca2013-08-01 17:46:18 -07002017
2018 - ServerAliveCountMax=3; consistency with remote_access.sh.
2019
2020 - ConnectAttempts=4; reduce flakiness in connection errors;
2021 consistency with remote_access.sh.
2022
2023 - UserKnownHostsFile=/dev/null; we don't care about the keys.
2024 Host keys change with every new installation, don't waste
2025 memory/space saving them.
2026
2027 - SSH protocol forced to 2; needed for ServerAliveInterval.
2028
2029 @param user User name to use for the ssh connection.
2030 @param port Port on the target host to use for ssh connection.
2031 @param opts Additional options to the ssh command.
2032 @param hosts_file Ignored.
2033 @param connect_timeout Ignored.
2034 @param alive_interval Ignored.
2035 """
Aviv Keshetc5947fa2013-09-04 14:06:29 -07002036 base_command = ('/usr/bin/ssh -a -x %s %s %s'
2037 ' -o StrictHostKeyChecking=no'
Fang Deng96667ca2013-08-01 17:46:18 -07002038 ' -o UserKnownHostsFile=/dev/null -o BatchMode=yes'
Samuel Tan2ce155b2015-06-23 18:24:38 -07002039 ' -o ConnectTimeout=30 -o ServerAliveInterval=900'
Fang Deng96667ca2013-08-01 17:46:18 -07002040 ' -o ServerAliveCountMax=3 -o ConnectionAttempts=4'
2041 ' -o Protocol=2 -l %s -p %d')
Aviv Keshetc5947fa2013-09-04 14:06:29 -07002042 return base_command % (self._ssh_verbosity_flag, self._ssh_options,
2043 opts, user, port)
Jason Abeleb6f924f2013-11-13 16:01:54 -08002044 def syslog(self, message, tag='autotest'):
2045 """Logs a message to syslog on host.
2046
2047 @param message String message to log into syslog
2048 @param tag String tag prefix for syslog
2049
2050 """
2051 self.run('logger -t "%s" "%s"' % (tag, message))
2052
2053
J. Richard Barnetteb6de7e32013-02-14 13:28:04 -08002054 def _ping_check_status(self, status):
2055 """Ping the host once, and return whether it has a given status.
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002056
J. Richard Barnetteb6de7e32013-02-14 13:28:04 -08002057 @param status Check the ping status against this value.
2058 @return True iff `status` and the result of ping are the same
2059 (i.e. both True or both False).
2060
2061 """
2062 ping_val = utils.ping(self.hostname, tries=1, deadline=1)
2063 return not (status ^ (ping_val == 0))
2064
2065 def _ping_wait_for_status(self, status, timeout):
2066 """Wait for the host to have a given status (UP or DOWN).
2067
2068 Status is checked by polling. Polling will not last longer
2069 than the number of seconds in `timeout`. The polling
2070 interval will be long enough that only approximately
2071 _PING_WAIT_COUNT polling cycles will be executed, subject
2072 to a maximum interval of about one minute.
2073
2074 @param status Waiting will stop immediately if `ping` of the
2075 host returns this status.
2076 @param timeout Poll for at most this many seconds.
2077 @return True iff the host status from `ping` matched the
2078 requested status at the time of return.
2079
2080 """
2081 # _ping_check_status() takes about 1 second, hence the
2082 # "- 1" in the formula below.
2083 poll_interval = min(int(timeout / self._PING_WAIT_COUNT), 60) - 1
2084 end_time = time.time() + timeout
2085 while time.time() <= end_time:
2086 if self._ping_check_status(status):
2087 return True
2088 if poll_interval > 0:
2089 time.sleep(poll_interval)
2090
2091 # The last thing we did was sleep(poll_interval), so it may
2092 # have been too long since the last `ping`. Check one more
2093 # time, just to be sure.
2094 return self._ping_check_status(status)
2095
2096 def ping_wait_up(self, timeout):
2097 """Wait for the host to respond to `ping`.
2098
2099 N.B. This method is not a reliable substitute for
2100 `wait_up()`, because a host that responds to ping will not
2101 necessarily respond to ssh. This method should only be used
2102 if the target DUT can be considered functional even if it
2103 can't be reached via ssh.
2104
2105 @param timeout Minimum time to allow before declaring the
2106 host to be non-responsive.
2107 @return True iff the host answered to ping before the timeout.
2108
2109 """
2110 return self._ping_wait_for_status(self._PING_STATUS_UP, timeout)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002111
Andrew Bresticker678c0c72013-01-22 10:44:09 -08002112 def ping_wait_down(self, timeout):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002113 """Wait until the host no longer responds to `ping`.
2114
J. Richard Barnetteb6de7e32013-02-14 13:28:04 -08002115 This function can be used as a slightly faster version of
2116 `wait_down()`, by avoiding potentially long ssh timeouts.
2117
2118 @param timeout Minimum time to allow for the host to become
2119 non-responsive.
2120 @return True iff the host quit answering ping before the
2121 timeout.
2122
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002123 """
J. Richard Barnetteb6de7e32013-02-14 13:28:04 -08002124 return self._ping_wait_for_status(self._PING_STATUS_DOWN, timeout)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002125
Tom Wai-Hong Tamfced4f62014-04-17 10:56:30 +08002126 def test_wait_for_sleep(self, sleep_timeout=None):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002127 """Wait for the client to enter low-power sleep mode.
2128
2129 The test for "is asleep" can't distinguish a system that is
2130 powered off; to confirm that the unit was asleep, it is
2131 necessary to force resume, and then call
2132 `test_wait_for_resume()`.
2133
2134 This function is expected to be called from a test as part
2135 of a sequence like the following:
2136
2137 ~~~~~~~~
2138 boot_id = host.get_boot_id()
2139 # trigger sleep on the host
2140 host.test_wait_for_sleep()
2141 # trigger resume on the host
2142 host.test_wait_for_resume(boot_id)
2143 ~~~~~~~~
2144
Tom Wai-Hong Tamfced4f62014-04-17 10:56:30 +08002145 @param sleep_timeout time limit in seconds to allow the host sleep.
2146
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002147 @exception TestFail The host did not go to sleep within
2148 the allowed time.
2149 """
Tom Wai-Hong Tamfced4f62014-04-17 10:56:30 +08002150 if sleep_timeout is None:
2151 sleep_timeout = self.SLEEP_TIMEOUT
2152
2153 if not self.ping_wait_down(timeout=sleep_timeout):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002154 raise error.TestFail(
Tom Wai-Hong Tamfced4f62014-04-17 10:56:30 +08002155 'client failed to sleep after %d seconds' % sleep_timeout)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002156
2157
Tom Wai-Hong Tamfced4f62014-04-17 10:56:30 +08002158 def test_wait_for_resume(self, old_boot_id, resume_timeout=None):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002159 """Wait for the client to resume from low-power sleep mode.
2160
2161 The `old_boot_id` parameter should be the value from
2162 `get_boot_id()` obtained prior to entering sleep mode. A
2163 `TestFail` exception is raised if the boot id changes.
2164
2165 See @ref test_wait_for_sleep for more on this function's
2166 usage.
2167
J. Richard Barnette7214e0b2013-02-06 15:20:49 -08002168 @param old_boot_id A boot id value obtained before the
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002169 target host went to sleep.
Tom Wai-Hong Tamfced4f62014-04-17 10:56:30 +08002170 @param resume_timeout time limit in seconds to allow the host up.
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002171
2172 @exception TestFail The host did not respond within the
2173 allowed time.
2174 @exception TestFail The host responded, but the boot id test
2175 indicated a reboot rather than a sleep
2176 cycle.
2177 """
Tom Wai-Hong Tamfced4f62014-04-17 10:56:30 +08002178 if resume_timeout is None:
2179 resume_timeout = self.RESUME_TIMEOUT
2180
2181 if not self.wait_up(timeout=resume_timeout):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002182 raise error.TestFail(
2183 'client failed to resume from sleep after %d seconds' %
Tom Wai-Hong Tamfced4f62014-04-17 10:56:30 +08002184 resume_timeout)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002185 else:
2186 new_boot_id = self.get_boot_id()
2187 if new_boot_id != old_boot_id:
Tom Wai-Hong Tam01792682015-01-06 08:00:46 +08002188 logging.error('client rebooted (old boot %s, new boot %s)',
2189 old_boot_id, new_boot_id)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002190 raise error.TestFail(
Tom Wai-Hong Tam01792682015-01-06 08:00:46 +08002191 'client rebooted, but sleep was expected')
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002192
2193
Tom Wai-Hong Tamfe005c22014-12-03 09:25:44 +08002194 def test_wait_for_shutdown(self, shutdown_timeout=None):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002195 """Wait for the client to shut down.
2196
2197 The test for "has shut down" can't distinguish a system that
2198 is merely asleep; to confirm that the unit was down, it is
2199 necessary to force boot, and then call test_wait_for_boot().
2200
2201 This function is expected to be called from a test as part
2202 of a sequence like the following:
2203
2204 ~~~~~~~~
2205 boot_id = host.get_boot_id()
2206 # trigger shutdown on the host
2207 host.test_wait_for_shutdown()
2208 # trigger boot on the host
2209 host.test_wait_for_boot(boot_id)
2210 ~~~~~~~~
2211
Tom Wai-Hong Tamfe005c22014-12-03 09:25:44 +08002212 @param shutdown_timeout time limit in seconds to allow the host down.
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002213 @exception TestFail The host did not shut down within the
2214 allowed time.
2215 """
Tom Wai-Hong Tamfe005c22014-12-03 09:25:44 +08002216 if shutdown_timeout is None:
2217 shutdown_timeout = self.SHUTDOWN_TIMEOUT
2218
2219 if not self.ping_wait_down(timeout=shutdown_timeout):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002220 raise error.TestFail(
2221 'client failed to shut down after %d seconds' %
Tom Wai-Hong Tamfe005c22014-12-03 09:25:44 +08002222 shutdown_timeout)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002223
2224
2225 def test_wait_for_boot(self, old_boot_id=None):
2226 """Wait for the client to boot from cold power.
2227
2228 The `old_boot_id` parameter should be the value from
2229 `get_boot_id()` obtained prior to shutting down. A
2230 `TestFail` exception is raised if the boot id does not
2231 change. The boot id test is omitted if `old_boot_id` is not
2232 specified.
2233
2234 See @ref test_wait_for_shutdown for more on this function's
2235 usage.
2236
J. Richard Barnette7214e0b2013-02-06 15:20:49 -08002237 @param old_boot_id A boot id value obtained before the
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002238 shut down.
2239
2240 @exception TestFail The host did not respond within the
2241 allowed time.
2242 @exception TestFail The host responded, but the boot id test
2243 indicated that there was no reboot.
2244 """
J. Richard Barnetteeb69d722012-06-18 17:29:44 -07002245 if not self.wait_up(timeout=self.REBOOT_TIMEOUT):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002246 raise error.TestFail(
2247 'client failed to reboot after %d seconds' %
J. Richard Barnetteeb69d722012-06-18 17:29:44 -07002248 self.REBOOT_TIMEOUT)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002249 elif old_boot_id:
2250 if self.get_boot_id() == old_boot_id:
Tom Wai-Hong Tam01792682015-01-06 08:00:46 +08002251 logging.error('client not rebooted (boot %s)',
2252 old_boot_id)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002253 raise error.TestFail(
Tom Wai-Hong Tam01792682015-01-06 08:00:46 +08002254 'client is back up, but did not reboot')
Simran Basid5e5e272012-09-24 15:23:59 -07002255
2256
2257 @staticmethod
2258 def check_for_rpm_support(hostname):
2259 """For a given hostname, return whether or not it is powered by an RPM.
2260
Simran Basi1df55112013-09-06 11:25:09 -07002261 @param hostname: hostname to check for rpm support.
2262
Simran Basid5e5e272012-09-24 15:23:59 -07002263 @return None if this host does not follows the defined naming format
2264 for RPM powered DUT's in the lab. If it does follow the format,
2265 it returns a regular expression MatchObject instead.
2266 """
Fang Dengbaff9082015-01-06 13:46:15 -08002267 return re.match(CrosHost._RPM_HOSTNAME_REGEX, hostname)
Simran Basid5e5e272012-09-24 15:23:59 -07002268
2269
2270 def has_power(self):
2271 """For this host, return whether or not it is powered by an RPM.
2272
2273 @return True if this host is in the CROS lab and follows the defined
2274 naming format.
2275 """
Fang Deng0ca40e22013-08-27 17:47:44 -07002276 return CrosHost.check_for_rpm_support(self.hostname)
Simran Basid5e5e272012-09-24 15:23:59 -07002277
2278
Ismail Noorbasha07fdb612013-02-14 14:13:31 -08002279 def _set_power(self, state, power_method):
2280 """Sets the power to the host via RPM, Servo or manual.
2281
2282 @param state Specifies which power state to set to DUT
2283 @param power_method Specifies which method of power control to
2284 use. By default "RPM" will be used. Valid values
2285 are the strings "RPM", "manual", "servoj10".
2286
2287 """
2288 ACCEPTABLE_STATES = ['ON', 'OFF']
2289
2290 if state.upper() not in ACCEPTABLE_STATES:
2291 raise error.TestError('State must be one of: %s.'
2292 % (ACCEPTABLE_STATES,))
2293
2294 if power_method == self.POWER_CONTROL_SERVO:
2295 logging.info('Setting servo port J10 to %s', state)
2296 self.servo.set('prtctl3_pwren', state.lower())
2297 time.sleep(self._USB_POWER_TIMEOUT)
2298 elif power_method == self.POWER_CONTROL_MANUAL:
2299 logging.info('You have %d seconds to set the AC power to %s.',
2300 self._POWER_CYCLE_TIMEOUT, state)
2301 time.sleep(self._POWER_CYCLE_TIMEOUT)
2302 else:
2303 if not self.has_power():
2304 raise error.TestFail('DUT does not have RPM connected.')
Simran Basi5e6339a2013-03-21 11:34:32 -07002305 afe = frontend_wrappers.RetryingAFE(timeout_min=5, delay_sec=10)
2306 afe.set_host_attribute(self._RPM_OUTLET_CHANGED, True,
2307 hostname=self.hostname)
Simran Basi1df55112013-09-06 11:25:09 -07002308 rpm_client.set_power(self.hostname, state.upper(), timeout_mins=5)
Simran Basid5e5e272012-09-24 15:23:59 -07002309
2310
Ismail Noorbasha07fdb612013-02-14 14:13:31 -08002311 def power_off(self, power_method=POWER_CONTROL_RPM):
2312 """Turn off power to this host via RPM, Servo or manual.
2313
2314 @param power_method Specifies which method of power control to
2315 use. By default "RPM" will be used. Valid values
2316 are the strings "RPM", "manual", "servoj10".
2317
2318 """
2319 self._set_power('OFF', power_method)
Simran Basid5e5e272012-09-24 15:23:59 -07002320
2321
Ismail Noorbasha07fdb612013-02-14 14:13:31 -08002322 def power_on(self, power_method=POWER_CONTROL_RPM):
2323 """Turn on power to this host via RPM, Servo or manual.
2324
2325 @param power_method Specifies which method of power control to
2326 use. By default "RPM" will be used. Valid values
2327 are the strings "RPM", "manual", "servoj10".
2328
2329 """
2330 self._set_power('ON', power_method)
2331
2332
2333 def power_cycle(self, power_method=POWER_CONTROL_RPM):
2334 """Cycle power to this host by turning it OFF, then ON.
2335
2336 @param power_method Specifies which method of power control to
2337 use. By default "RPM" will be used. Valid values
2338 are the strings "RPM", "manual", "servoj10".
2339
2340 """
2341 if power_method in (self.POWER_CONTROL_SERVO,
2342 self.POWER_CONTROL_MANUAL):
2343 self.power_off(power_method=power_method)
2344 time.sleep(self._POWER_CYCLE_TIMEOUT)
2345 self.power_on(power_method=power_method)
2346 else:
2347 rpm_client.set_power(self.hostname, 'CYCLE')
Simran Basic6f1f7a2012-10-16 10:47:46 -07002348
2349
2350 def get_platform(self):
2351 """Determine the correct platform label for this host.
2352
2353 @returns a string representing this host's platform.
2354 """
2355 crossystem = utils.Crossystem(self)
2356 crossystem.init()
2357 # Extract fwid value and use the leading part as the platform id.
2358 # fwid generally follow the format of {platform}.{firmware version}
2359 # Example: Alex.X.YYY.Z or Google_Alex.X.YYY.Z
2360 platform = crossystem.fwid().split('.')[0].lower()
2361 # Newer platforms start with 'Google_' while the older ones do not.
2362 return platform.replace('google_', '')
2363
2364
Hung-ying Tyanb1328032014-04-01 14:18:54 +08002365 def get_architecture(self):
2366 """Determine the correct architecture label for this host.
2367
2368 @returns a string representing this host's architecture.
2369 """
2370 crossystem = utils.Crossystem(self)
2371 crossystem.init()
2372 return crossystem.arch()
2373
2374
Luis Lozano40b7d0d2014-01-17 15:12:06 -08002375 def get_chrome_version(self):
2376 """Gets the Chrome version number and milestone as strings.
2377
2378 Invokes "chrome --version" to get the version number and milestone.
2379
2380 @return A tuple (chrome_ver, milestone) where "chrome_ver" is the
2381 current Chrome version number as a string (in the form "W.X.Y.Z")
2382 and "milestone" is the first component of the version number
2383 (the "W" from "W.X.Y.Z"). If the version number cannot be parsed
2384 in the "W.X.Y.Z" format, the "chrome_ver" will be the full output
2385 of "chrome --version" and the milestone will be the empty string.
2386
2387 """
MK Ryu35d661e2014-09-25 17:44:10 -07002388 version_string = self.run(client_constants.CHROME_VERSION_COMMAND).stdout
Luis Lozano40b7d0d2014-01-17 15:12:06 -08002389 return utils.parse_chrome_version(version_string)
2390
Aviv Keshet74c89a92013-02-04 15:18:30 -08002391 @label_decorator()
Simran Basic6f1f7a2012-10-16 10:47:46 -07002392 def get_board(self):
2393 """Determine the correct board label for this host.
2394
2395 @returns a string representing this host's board.
2396 """
2397 release_info = utils.parse_cmd_output('cat /etc/lsb-release',
2398 run_method=self.run)
2399 board = release_info['CHROMEOS_RELEASE_BOARD']
2400 # Devices in the lab generally have the correct board name but our own
2401 # development devices have {board_name}-signed-{key_type}. The board
2402 # name may also begin with 'x86-' which we need to keep.
Simran Basi833814b2013-01-29 13:13:43 -08002403 board_format_string = ds_constants.BOARD_PREFIX + '%s'
Simran Basic6f1f7a2012-10-16 10:47:46 -07002404 if 'x86' not in board:
Simran Basi833814b2013-01-29 13:13:43 -08002405 return board_format_string % board.split('-')[0]
2406 return board_format_string % '-'.join(board.split('-')[0:2])
Simran Basic6f1f7a2012-10-16 10:47:46 -07002407
2408
Aviv Keshet74c89a92013-02-04 15:18:30 -08002409 @label_decorator('lightsensor')
Simran Basic6f1f7a2012-10-16 10:47:46 -07002410 def has_lightsensor(self):
2411 """Determine the correct board label for this host.
2412
2413 @returns the string 'lightsensor' if this host has a lightsensor or
2414 None if it does not.
2415 """
2416 search_cmd = "find -L %s -maxdepth 4 | egrep '%s'" % (
Richard Barnette82c35912012-11-20 10:09:10 -08002417 self._LIGHTSENSOR_SEARCH_DIR, '|'.join(self._LIGHTSENSOR_FILES))
Simran Basic6f1f7a2012-10-16 10:47:46 -07002418 try:
2419 # Run the search cmd following the symlinks. Stderr_tee is set to
2420 # None as there can be a symlink loop, but the command will still
2421 # execute correctly with a few messages printed to stderr.
2422 self.run(search_cmd, stdout_tee=None, stderr_tee=None)
2423 return 'lightsensor'
2424 except error.AutoservRunError:
2425 # egrep exited with a return code of 1 meaning none of the possible
2426 # lightsensor files existed.
2427 return None
2428
2429
Aviv Keshet74c89a92013-02-04 15:18:30 -08002430 @label_decorator('bluetooth')
Simran Basic6f1f7a2012-10-16 10:47:46 -07002431 def has_bluetooth(self):
2432 """Determine the correct board label for this host.
2433
2434 @returns the string 'bluetooth' if this host has bluetooth or
2435 None if it does not.
2436 """
2437 try:
2438 self.run('test -d /sys/class/bluetooth/hci0')
2439 # test exited with a return code of 0.
2440 return 'bluetooth'
2441 except error.AutoservRunError:
2442 # test exited with a return code 1 meaning the directory did not
2443 # exist.
2444 return None
2445
2446
Bill Richardson4f595f52014-02-13 16:20:26 -08002447 @label_decorator('ec')
2448 def get_ec(self):
2449 """
2450 Determine the type of EC on this host.
2451
2452 @returns a string representing this host's embedded controller type.
2453 At present, it only returns "ec:cros", for Chrome OS ECs. Other types
2454 of EC (or none) don't return any strings, since no tests depend on
2455 those.
2456 """
2457 cmd = 'mosys ec info'
2458 # The output should look like these, so that the last field should
2459 # match our EC version scheme:
2460 #
2461 # stm | stm32f100 | snow_v1.3.139-375eb9f
2462 # ti | Unknown-10de | peppy_v1.5.114-5d52788
2463 #
2464 # Non-Chrome OS ECs will look like these:
2465 #
2466 # ENE | KB932 | 00BE107A00
2467 # ite | it8518 | 3.08
2468 #
2469 # And some systems don't have ECs at all (Lumpy, for example).
2470 regexp = r'^.*\|\s*(\S+_v\d+\.\d+\.\d+-[0-9a-f]+)\s*$'
2471
2472 ecinfo = self.run(command=cmd, ignore_status=True)
2473 if ecinfo.exit_status == 0:
2474 res = re.search(regexp, ecinfo.stdout)
2475 if res:
2476 logging.info("EC version is %s", res.groups()[0])
2477 return 'ec:cros'
2478 logging.info("%s got: %s", cmd, ecinfo.stdout)
2479 # Has an EC, but it's not a Chrome OS EC
2480 return None
2481 logging.info("%s exited with status %d", cmd, ecinfo.exit_status)
2482 # No EC present
2483 return None
2484
2485
Alec Berg31b932b2014-04-04 16:09:11 -07002486 @label_decorator('accels')
2487 def get_accels(self):
2488 """
2489 Determine the type of accelerometers on this host.
2490
2491 @returns a string representing this host's accelerometer type.
2492 At present, it only returns "accel:cros-ec", for accelerometers
2493 attached to a Chrome OS EC, or none, if no accelerometers.
2494 """
2495 # Check to make sure we have ectool
2496 rv = self.run('which ectool', ignore_status=True)
2497 if rv.exit_status:
2498 logging.info("No ectool cmd found, assuming no EC accelerometers")
2499 return None
2500
2501 # Check that the EC supports the motionsense command
2502 rv = self.run('ectool motionsense', ignore_status=True)
2503 if rv.exit_status:
2504 logging.info("EC does not support motionsense command "
2505 "assuming no EC accelerometers")
2506 return None
2507
2508 # Check that EC motion sensors are active
2509 active = self.run('ectool motionsense active').stdout.split('\n')
2510 if active[0] == "0":
2511 logging.info("Motion sense inactive, assuming no EC accelerometers")
2512 return None
2513
2514 logging.info("EC accelerometers found")
2515 return 'accel:cros-ec'
2516
2517
Tom Wai-Hong Tam3d6790d2014-04-14 16:15:47 +08002518 @label_decorator('chameleon')
2519 def has_chameleon(self):
2520 """Determine if a Chameleon connected to this host.
2521
Tom Wai-Hong Tambadbb332014-10-10 02:59:41 +08002522 @returns a list containing two strings ('chameleon' and
2523 'chameleon:' + label, e.g. 'chameleon:hdmi') if this host
2524 has a Chameleon or None if it has not.
Tom Wai-Hong Tam3d6790d2014-04-14 16:15:47 +08002525 """
2526 if self._chameleon_host:
Tom Wai-Hong Tambadbb332014-10-10 02:59:41 +08002527 return ['chameleon', 'chameleon:' + self.chameleon.get_label()]
Tom Wai-Hong Tam3d6790d2014-04-14 16:15:47 +08002528 else:
2529 return None
2530
2531
Cheng-Yi Chiangf4104ff2014-12-23 19:39:01 +08002532 @label_decorator('audio_loopback_dongle')
2533 def has_loopback_dongle(self):
2534 """Determine if an audio loopback dongle is plugged to this host.
2535
2536 @returns 'audio_loopback_dongle' when there is an audio loopback dongle
2537 plugged to this host.
2538 None when there is no audio loopback dongle
2539 plugged to this host.
2540 """
Cheng-Yi Chiang8de78112015-05-27 14:47:08 +08002541 nodes_info = self.run(command=cras_utils.get_cras_nodes_cmd(),
2542 ignore_status=True).stdout
2543 if (cras_utils.node_type_is_plugged('HEADPHONE', nodes_info) and
2544 cras_utils.node_type_is_plugged('MIC', nodes_info)):
Cheng-Yi Chiangf4104ff2014-12-23 19:39:01 +08002545 return 'audio_loopback_dongle'
2546 else:
2547 return None
2548
2549
Derek Basehorec71ff622014-07-07 15:18:40 -07002550 @label_decorator('power_supply')
2551 def get_power_supply(self):
2552 """
2553 Determine what type of power supply the host has
2554
2555 @returns a string representing this host's power supply.
2556 'power:battery' when the device has a battery intended for
2557 extended use
2558 'power:AC_primary' when the device has a battery not intended
2559 for extended use (for moving the machine, etc)
2560 'power:AC_only' when the device has no battery at all.
2561 """
2562 psu = self.run(command='mosys psu type', ignore_status=True)
2563 if psu.exit_status:
2564 # The psu command for mosys is not included for all platforms. The
2565 # assumption is that the device will have a battery if the command
2566 # is not found.
2567 return 'power:battery'
2568
2569 psu_str = psu.stdout.strip()
2570 if psu_str == 'unknown':
2571 return None
2572
2573 return 'power:%s' % psu_str
2574
2575
Puthikorn Voravootivatfa011242014-03-14 18:45:11 -07002576 @label_decorator('storage')
2577 def get_storage(self):
2578 """
2579 Determine the type of boot device for this host.
2580
2581 Determine if the internal device is SCSI or dw_mmc device.
2582 Then check that it is SSD or HDD or eMMC or something else.
2583
2584 @returns a string representing this host's internal device type.
2585 'storage:ssd' when internal device is solid state drive
2586 'storage:hdd' when internal device is hard disk drive
2587 'storage:mmc' when internal device is mmc drive
2588 None When internal device is something else or
2589 when we are unable to determine the type
2590 """
2591 # The output should be /dev/mmcblk* for SD/eMMC or /dev/sd* for scsi
2592 rootdev_cmd = ' '.join(['. /usr/sbin/write_gpt.sh;',
2593 '. /usr/share/misc/chromeos-common.sh;',
2594 'load_base_vars;',
2595 'get_fixed_dst_drive'])
Puthikorn Voravootivat03c51682014-04-24 13:52:12 -07002596 rootdev = self.run(command=rootdev_cmd, ignore_status=True)
2597 if rootdev.exit_status:
2598 logging.info("Fail to run %s", rootdev_cmd)
2599 return None
Puthikorn Voravootivatfa011242014-03-14 18:45:11 -07002600 rootdev_str = rootdev.stdout.strip()
2601
2602 if not rootdev_str:
2603 return None
2604
2605 rootdev_base = os.path.basename(rootdev_str)
2606
2607 mmc_pattern = '/dev/mmcblk[0-9]'
2608 if re.match(mmc_pattern, rootdev_str):
2609 # Use type to determine if the internal device is eMMC or somthing
2610 # else. We can assume that MMC is always an internal device.
2611 type_cmd = 'cat /sys/block/%s/device/type' % rootdev_base
Puthikorn Voravootivat03c51682014-04-24 13:52:12 -07002612 type = self.run(command=type_cmd, ignore_status=True)
2613 if type.exit_status:
2614 logging.info("Fail to run %s", type_cmd)
2615 return None
Puthikorn Voravootivatfa011242014-03-14 18:45:11 -07002616 type_str = type.stdout.strip()
2617
2618 if type_str == 'MMC':
2619 return 'storage:mmc'
2620
2621 scsi_pattern = '/dev/sd[a-z]+'
2622 if re.match(scsi_pattern, rootdev.stdout):
2623 # Read symlink for /sys/block/sd* to determine if the internal
2624 # device is connected via ata or usb.
2625 link_cmd = 'readlink /sys/block/%s' % rootdev_base
Puthikorn Voravootivat03c51682014-04-24 13:52:12 -07002626 link = self.run(command=link_cmd, ignore_status=True)
2627 if link.exit_status:
2628 logging.info("Fail to run %s", link_cmd)
2629 return None
Puthikorn Voravootivatfa011242014-03-14 18:45:11 -07002630 link_str = link.stdout.strip()
2631 if 'usb' in link_str:
2632 return None
2633
2634 # Read rotation to determine if the internal device is ssd or hdd.
2635 rotate_cmd = str('cat /sys/block/%s/queue/rotational'
2636 % rootdev_base)
Puthikorn Voravootivat03c51682014-04-24 13:52:12 -07002637 rotate = self.run(command=rotate_cmd, ignore_status=True)
2638 if rotate.exit_status:
2639 logging.info("Fail to run %s", rotate_cmd)
2640 return None
Puthikorn Voravootivatfa011242014-03-14 18:45:11 -07002641 rotate_str = rotate.stdout.strip()
2642
2643 rotate_dict = {'0':'storage:ssd', '1':'storage:hdd'}
2644 return rotate_dict.get(rotate_str)
2645
2646 # All other internal device / error case will always fall here
2647 return None
2648
2649
Dan Shi4e9a2aa2014-03-24 14:28:42 -07002650 @label_decorator('servo')
2651 def get_servo(self):
2652 """Determine if the host has a servo attached.
2653
2654 If the host has a working servo attached, it should have a servo label.
2655
2656 @return: string 'servo' if the host has servo attached. Otherwise,
2657 returns None.
2658 """
2659 return 'servo' if self._servo_host else None
2660
2661
Dan Shi5beba472014-05-28 22:46:07 -07002662 @label_decorator('video_labels')
2663 def get_video_labels(self):
2664 """Run /usr/local/bin/avtest_label_detect to get a list of video labels.
2665
2666 Sample output of avtest_label_detect:
2667 Detected label: hw_video_acc_vp8
2668 Detected label: webcam
2669
2670 @return: A list of labels detected by tool avtest_label_detect.
2671 """
2672 try:
2673 result = self.run('/usr/local/bin/avtest_label_detect').stdout
2674 return re.findall('^Detected label: (\w+)$', result, re.M)
2675 except error.AutoservRunError:
2676 # The tool is not installed.
2677 return []
2678
2679
mussa584b4462014-06-20 15:13:28 -07002680 @label_decorator('video_glitch_detection')
2681 def is_video_glitch_detection_supported(self):
2682 """ Determine if a board under test is supported for video glitch
2683 detection tests.
2684
2685 @return: 'video_glitch_detection' if board is supported, None otherwise.
2686 """
Mussa5b589052015-10-26 17:55:26 -07002687 board = self.get_board().replace(ds_constants.BOARD_PREFIX, '')
mussa584b4462014-06-20 15:13:28 -07002688
Mussa5b589052015-10-26 17:55:26 -07002689 if board in video_test_constants.SUPPORTED_BOARDS:
2690 return 'video_glitch_detection'
mussa584b4462014-06-20 15:13:28 -07002691
Mussa5b589052015-10-26 17:55:26 -07002692 return None
mussa584b4462014-06-20 15:13:28 -07002693
mussa584b4462014-06-20 15:13:28 -07002694
Katherine Threlkeld7b97a9f2014-06-24 13:47:14 -07002695 @label_decorator('touch_labels')
2696 def get_touch(self):
2697 """
2698 Determine whether board under test has a touchpad or touchscreen.
2699
2700 @return: A list of some combination of 'touchscreen' and 'touchpad',
2701 depending on what is present on the device.
Katherine Threlkeldab83d392015-06-18 16:45:57 -07002702
Katherine Threlkeld7b97a9f2014-06-24 13:47:14 -07002703 """
2704 labels = []
Katherine Threlkeldab83d392015-06-18 16:45:57 -07002705 looking_for = ['touchpad', 'touchscreen']
2706 player = input_playback.InputPlayback()
2707 input_events = self.run('ls /dev/input/event*').stdout.strip().split()
2708 filename = '/tmp/touch_labels'
2709 for event in input_events:
2710 self.run('evtest %s > %s' % (event, filename), timeout=1,
2711 ignore_timeout=True)
2712 properties = self.run('cat %s' % filename).stdout
2713 input_type = player._determine_input_type(properties)
2714 if input_type in looking_for:
2715 labels.append(input_type)
2716 looking_for.remove(input_type)
2717 if len(looking_for) == 0:
2718 break
2719 self.run('rm %s' % filename)
2720
Katherine Threlkeld7b97a9f2014-06-24 13:47:14 -07002721 return labels
2722
Hung-ying Tyana39b0542015-06-30 10:36:42 +08002723
2724 @label_decorator('internal_display')
2725 def has_internal_display(self):
2726 """Determine if the device under test is equipped with an internal
2727 display.
2728
2729 @return: 'internal_display' if one is present; None otherwise.
2730 """
2731 from autotest_lib.client.cros.graphics import graphics_utils
2732 from autotest_lib.client.common_lib import utils as common_utils
2733
2734 def __system_output(cmd):
2735 return self.run(cmd).stdout
2736
2737 def __read_file(remote_path):
2738 return self.run('cat %s' % remote_path).stdout
2739
2740 # Hijack the necessary client functions so that we can take advantage
2741 # of the client lib here.
2742 # FIXME: find a less hacky way than this
2743 original_system_output = utils.system_output
2744 original_read_file = common_utils.read_file
2745 utils.system_output = __system_output
2746 common_utils.read_file = __read_file
2747 try:
2748 return ('internal_display' if graphics_utils.has_internal_display()
2749 else None)
2750 finally:
2751 utils.system_output = original_system_output
2752 common_utils.read_file = original_read_file
2753
2754
Eric Carusoee673ac2015-08-05 17:03:04 -07002755 @label_decorator('lucidsleep')
2756 def has_lucid_sleep_support(self):
2757 """Determine if the device under test has support for lucid sleep.
2758
2759 @return 'lucidsleep' if this board supports lucid sleep; None otherwise
2760 """
2761 board = self.get_board().replace(ds_constants.BOARD_PREFIX, '')
2762 return 'lucidsleep' if board in LUCID_SLEEP_BOARDS else None
2763
2764
Dan Shi85276d42014-04-08 22:11:45 -07002765 def is_boot_from_usb(self):
2766 """Check if DUT is boot from USB.
2767
2768 @return: True if DUT is boot from usb.
2769 """
2770 device = self.run('rootdev -s -d').stdout.strip()
2771 removable = int(self.run('cat /sys/block/%s/removable' %
2772 os.path.basename(device)).stdout.strip())
2773 return removable == 1
Helen Zhang17dae2b2014-11-11 09:25:52 -08002774
2775
2776 def read_from_meminfo(self, key):
Dan Shi49ca0932014-11-14 11:22:27 -08002777 """Return the memory info from /proc/meminfo
Helen Zhang17dae2b2014-11-11 09:25:52 -08002778
2779 @param key: meminfo requested
2780
2781 @return the memory value as a string
2782
2783 """
Helen Zhang17dae2b2014-11-11 09:25:52 -08002784 meminfo = self.run('grep %s /proc/meminfo' % key).stdout.strip()
2785 logging.debug('%s', meminfo)
2786 return int(re.search(r'\d+', meminfo).group(0))
Rohit Makasana8a4923c2015-08-13 17:04:26 -07002787
2788
2789 def get_board_type(self):
2790 """
2791 Get the DUT's device type from /etc/lsb-release.
Danny Chan471a8d12015-08-18 14:57:41 -07002792 DEVICETYPE can be one of CHROMEBOX, CHROMEBASE, CHROMEBOOK or more.
2793
2794 @return value of DEVICETYPE param from lsb-release.
Rohit Makasana8a4923c2015-08-13 17:04:26 -07002795 """
Danny Chan471a8d12015-08-18 14:57:41 -07002796 device_type = self.run('grep DEVICETYPE /etc/lsb-release',
2797 ignore_status=True).stdout
2798 if device_type:
Kalin Stoyanov524310b2015-08-21 16:24:04 -07002799 return device_type.split('=')[-1].strip()
Danny Chan471a8d12015-08-18 14:57:41 -07002800 return ''
Gilad Arnolda76bef02015-09-29 13:55:15 -07002801
2802
2803 def get_os_type(self):
2804 return 'cros'
Simran Basia5522a32015-10-06 11:01:24 -07002805
2806
2807 def enable_adb_testing(self):
2808 """Mark this host as an adb tester."""
Dan Shia2872172015-10-31 01:16:51 -07002809 self.run('touch %s' % constants.ANDROID_TESTER_FILEFLAG)