blob: 1979916436262da83eead4ac23e79419bab0983b [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
MK Ryu35d661e2014-09-25 17:44:10 -070027from autotest_lib.server import autoserv_parser
28from autotest_lib.server import autotest
29from autotest_lib.server import constants
30from autotest_lib.server import crashcollect
Dan Shia1ecd5c2013-06-06 11:21:31 -070031from autotest_lib.server import utils as server_utils
Dan Shi9cb0eec2014-06-03 09:04:50 -070032from autotest_lib.server.cros import provision
Scott Zawalski89c44dd2013-02-26 09:28:02 -050033from autotest_lib.server.cros.dynamic_suite import constants as ds_constants
Simran Basi5e6339a2013-03-21 11:34:32 -070034from autotest_lib.server.cros.dynamic_suite import tools, frontend_wrappers
Dan Shi9cb0eec2014-06-03 09:04:50 -070035from autotest_lib.server.cros.faft.config.config import Config as FAFTConfig
Scottfe06ed82015-11-05 17:15:01 -080036from autotest_lib.server.cros.servo import plankton
Fang Deng96667ca2013-08-01 17:46:18 -070037from autotest_lib.server.hosts import abstract_ssh
Tom Wai-Hong Tamefe1c7f2014-01-02 14:00:11 +080038from autotest_lib.server.hosts import chameleon_host
Scottfe06ed82015-11-05 17:15:01 -080039from autotest_lib.server.hosts import plankton_host
Fang Deng5d518f42013-08-02 14:04:32 -070040from autotest_lib.server.hosts import servo_host
Simran Basidcff4252012-11-20 16:13:20 -080041from autotest_lib.site_utils.rpm_control_system import rpm_client
Simran Basid5e5e272012-09-24 15:23:59 -070042
43
Dan Shib8540a52015-07-16 14:18:23 -070044CONFIG = global_config.global_config
45
Eric Carusoee673ac2015-08-05 17:03:04 -070046LUCID_SLEEP_BOARDS = ['samus', 'lulu']
47
Dan Shid07ee2e2015-09-24 14:49:25 -070048# A file to indicate provision failure and require Repair job to powerwash the
49# dut.
50PROVISION_FAILED = '/var/tmp/provision_failed'
51
beepsc87ff602013-07-31 21:53:00 -070052class FactoryImageCheckerException(error.AutoservError):
53 """Exception raised when an image is a factory image."""
54 pass
55
56
Fang Deng0ca40e22013-08-27 17:47:44 -070057class CrosHost(abstract_ssh.AbstractSSHHost):
J. Richard Barnette45e93de2012-04-11 17:24:15 -070058 """Chromium OS specific subclass of Host."""
59
60 _parser = autoserv_parser.autoserv_parser
Scott Zawalski62bacae2013-03-05 10:40:32 -050061 _AFE = frontend_wrappers.RetryingAFE(timeout_min=5, delay_sec=10)
J. Richard Barnette45e93de2012-04-11 17:24:15 -070062
Richard Barnette03a0c132012-11-05 12:40:35 -080063 # Timeout values (in seconds) associated with various Chrome OS
64 # state changes.
J. Richard Barnette134ec2c2012-04-25 12:59:37 -070065 #
Richard Barnette0c73ffc2012-11-19 15:21:18 -080066 # In general, a good rule of thumb is that the timeout can be up
67 # to twice the typical measured value on the slowest platform.
68 # The times here have not necessarily been empirically tested to
69 # meet this criterion.
J. Richard Barnetteeb69d722012-06-18 17:29:44 -070070 #
71 # SLEEP_TIMEOUT: Time to allow for suspend to memory.
Richard Barnette0c73ffc2012-11-19 15:21:18 -080072 # RESUME_TIMEOUT: Time to allow for resume after suspend, plus
73 # time to restart the netwowrk.
J. Richard Barnette84890bd2014-02-21 11:05:47 -080074 # SHUTDOWN_TIMEOUT: Time to allow for shut down.
J. Richard Barnetteeb69d722012-06-18 17:29:44 -070075 # BOOT_TIMEOUT: Time to allow for boot from power off. Among
Richard Barnette0c73ffc2012-11-19 15:21:18 -080076 # other things, this must account for the 30 second dev-mode
J. Richard Barnette417cc792015-10-01 09:56:36 -070077 # screen delay, time to start the network on the DUT, and the
78 # ssh timeout of 120 seconds.
J. Richard Barnetteeb69d722012-06-18 17:29:44 -070079 # USB_BOOT_TIMEOUT: Time to allow for boot from a USB device,
Richard Barnette0c73ffc2012-11-19 15:21:18 -080080 # including the 30 second dev-mode delay and time to start the
J. Richard Barnetted4649c62013-03-06 17:42:27 -080081 # network.
beepsf079cfb2013-09-18 17:49:51 -070082 # INSTALL_TIMEOUT: Time to allow for chromeos-install.
J. Richard Barnette84890bd2014-02-21 11:05:47 -080083 # POWERWASH_BOOT_TIMEOUT: Time to allow for a reboot that
84 # includes powerwash.
J. Richard Barnetteeb69d722012-06-18 17:29:44 -070085
86 SLEEP_TIMEOUT = 2
J. Richard Barnetted4649c62013-03-06 17:42:27 -080087 RESUME_TIMEOUT = 10
Tom Wai-Hong Tamfe005c22014-12-03 09:25:44 +080088 SHUTDOWN_TIMEOUT = 10
J. Richard Barnette417cc792015-10-01 09:56:36 -070089 BOOT_TIMEOUT = 150
J. Richard Barnette5bab5f52015-08-03 13:14:38 -070090 USB_BOOT_TIMEOUT = 300
J. Richard Barnette7817b052014-08-28 09:47:29 -070091 INSTALL_TIMEOUT = 480
Dan Shi2c88eed2013-11-12 10:18:38 -080092 POWERWASH_BOOT_TIMEOUT = 60
Chris Sosab76e0ee2013-05-22 16:55:41 -070093
Dan Shica503482015-03-30 17:23:25 -070094 # Minimum OS version that supports server side packaging. Older builds may
95 # not have server side package built or with Autotest code change to support
96 # server-side packaging.
Dan Shib8540a52015-07-16 14:18:23 -070097 MIN_VERSION_SUPPORT_SSP = CONFIG.get_config_value(
Dan Shiced09e42015-04-17 16:09:34 -070098 'AUTOSERV', 'min_version_support_ssp', type=int)
Dan Shica503482015-03-30 17:23:25 -070099
J. Richard Barnette84890bd2014-02-21 11:05:47 -0800100 # REBOOT_TIMEOUT: How long to wait for a reboot.
101 #
Chris Sosab76e0ee2013-05-22 16:55:41 -0700102 # We have a long timeout to ensure we don't flakily fail due to other
103 # issues. Shorter timeouts are vetted in platform_RebootAfterUpdate.
Simran Basi1160e2c2013-10-04 16:00:24 -0700104 # TODO(sbasi - crbug.com/276094) Restore to 5 mins once the 'host did not
105 # return from reboot' bug is solved.
106 REBOOT_TIMEOUT = 480
Chris Sosab76e0ee2013-05-22 16:55:41 -0700107
Ismail Noorbasha07fdb612013-02-14 14:13:31 -0800108 # _USB_POWER_TIMEOUT: Time to allow for USB to power toggle ON and OFF.
109 # _POWER_CYCLE_TIMEOUT: Time to allow for manual power cycle.
110 _USB_POWER_TIMEOUT = 5
111 _POWER_CYCLE_TIMEOUT = 10
112
Dan Shib8540a52015-07-16 14:18:23 -0700113 _RPM_RECOVERY_BOARDS = CONFIG.get_config_value('CROS',
Richard Barnette82c35912012-11-20 10:09:10 -0800114 'rpm_recovery_boards', type=str).split(',')
115
116 _MAX_POWER_CYCLE_ATTEMPTS = 6
117 _LAB_MACHINE_FILE = '/mnt/stateful_partition/.labmachine'
Fang Dengdeba14f2014-11-14 11:54:09 -0800118 _RPM_HOSTNAME_REGEX = ('chromeos(\d+)(-row(\d+))?-rack(\d+[a-z]*)'
119 '-host(\d+)')
Katherine Threlkeldab83d392015-06-18 16:45:57 -0700120 _LIGHTSENSOR_FILES = [ "in_illuminance0_input",
121 "in_illuminance_input",
122 "in_illuminance0_raw",
123 "in_illuminance_raw",
124 "illuminance0_input"]
Richard Barnette82c35912012-11-20 10:09:10 -0800125 _LIGHTSENSOR_SEARCH_DIR = '/sys/bus/iio/devices'
126 _LABEL_FUNCTIONS = []
Aviv Keshet74c89a92013-02-04 15:18:30 -0800127 _DETECTABLE_LABELS = []
Kevin Cheng3a4a57a2015-09-30 12:09:50 -0700128 label_decorator = functools.partial(server_utils.add_label_detector,
129 _LABEL_FUNCTIONS,
Aviv Keshet74c89a92013-02-04 15:18:30 -0800130 _DETECTABLE_LABELS)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -0700131
J. Richard Barnetteb6de7e32013-02-14 13:28:04 -0800132 # Constants used in ping_wait_up() and ping_wait_down().
133 #
134 # _PING_WAIT_COUNT is the approximate number of polling
135 # cycles to use when waiting for a host state change.
136 #
137 # _PING_STATUS_DOWN and _PING_STATUS_UP are names used
138 # for arguments to the internal _ping_wait_for_status()
139 # method.
140 _PING_WAIT_COUNT = 40
141 _PING_STATUS_DOWN = False
142 _PING_STATUS_UP = True
143
Ismail Noorbasha07fdb612013-02-14 14:13:31 -0800144 # Allowed values for the power_method argument.
145
146 # POWER_CONTROL_RPM: Passed as default arg for power_off/on/cycle() methods.
147 # POWER_CONTROL_SERVO: Used in set_power() and power_cycle() methods.
148 # POWER_CONTROL_MANUAL: Used in set_power() and power_cycle() methods.
149 POWER_CONTROL_RPM = 'RPM'
150 POWER_CONTROL_SERVO = 'servoj10'
151 POWER_CONTROL_MANUAL = 'manual'
152
153 POWER_CONTROL_VALID_ARGS = (POWER_CONTROL_RPM,
154 POWER_CONTROL_SERVO,
155 POWER_CONTROL_MANUAL)
Richard Barnette0c73ffc2012-11-19 15:21:18 -0800156
Simran Basi5e6339a2013-03-21 11:34:32 -0700157 _RPM_OUTLET_CHANGED = 'outlet_changed'
158
Dan Shi9cb0eec2014-06-03 09:04:50 -0700159 # URL pattern to download firmware image.
Dan Shib8540a52015-07-16 14:18:23 -0700160 _FW_IMAGE_URL_PATTERN = CONFIG.get_config_value(
Dan Shi9cb0eec2014-06-03 09:04:50 -0700161 'CROS', 'firmware_url_pattern', type=str)
beeps687243d2013-07-18 15:29:27 -0700162
MK Ryu35d661e2014-09-25 17:44:10 -0700163 # File that has a list of directories to be collected
164 _LOGS_TO_COLLECT_FILE = os.path.join(
165 common.client_dir, 'common_lib', 'logs_to_collect')
166
167 # Prefix of logging message w.r.t. crash collection
168 _CRASHLOGS_PREFIX = 'collect_crashlogs'
169
170 # Time duration waiting for host up/down check
171 _CHECK_HOST_UP_TIMEOUT_SECS = 15
172
173 # A command that interacts with kernel and hardware (e.g., rm, mkdir, etc)
174 # might not be completely done deep through the hardware when the machine
175 # is powered down right after the command returns.
176 # We should wait for a few seconds to make them done. Finger crossed.
177 _SAFE_WAIT_SECS = 10
178
179
J. Richard Barnette964fba02012-10-24 17:34:29 -0700180 @staticmethod
beeps46dadc92013-11-07 14:07:10 -0800181 def check_host(host, timeout=10):
182 """
183 Check if the given host is a chrome-os host.
184
185 @param host: An ssh host representing a device.
186 @param timeout: The timeout for the run command.
187
188 @return: True if the host device is chromeos.
189
beeps46dadc92013-11-07 14:07:10 -0800190 """
191 try:
Simran Basi933c8af2015-04-29 14:05:07 -0700192 result = host.run(
193 'grep -q CHROMEOS /etc/lsb-release && '
194 '! test -f /mnt/stateful_partition/.android_tester && '
195 '! grep -q moblab /etc/lsb-release',
196 ignore_status=True, timeout=timeout)
beeps46dadc92013-11-07 14:07:10 -0800197 except (error.AutoservRunError, error.AutoservSSHTimeout):
198 return False
199 return result.exit_status == 0
200
201
202 @staticmethod
Tom Wai-Hong Tamefe1c7f2014-01-02 14:00:11 +0800203 def _extract_arguments(args_dict, key_subset):
204 """Extract options from `args_dict` and return a subset result.
J. Richard Barnette7214e0b2013-02-06 15:20:49 -0800205
206 Take the provided dictionary of argument options and return
Tom Wai-Hong Tamefe1c7f2014-01-02 14:00:11 +0800207 a subset that represent standard arguments needed to construct
208 a test-assistant object (chameleon or servo) for a host. The
209 intent is to provide standard argument processing from
Christopher Wiley644ef3e2015-05-15 13:14:14 -0700210 CrosHost for tests that require a test-assistant board
Tom Wai-Hong Tamefe1c7f2014-01-02 14:00:11 +0800211 to operate.
212
213 @param args_dict Dictionary from which to extract the arguments.
214 @param key_subset Tuple of keys to extract from the args_dict, e.g.
215 ('servo_host', 'servo_port').
216 """
217 result = {}
218 for arg in key_subset:
219 if arg in args_dict:
220 result[arg] = args_dict[arg]
221 return result
222
223
224 @staticmethod
225 def get_chameleon_arguments(args_dict):
226 """Extract chameleon options from `args_dict` and return the result.
227
228 Recommended usage:
229 ~~~~~~~~
230 args_dict = utils.args_to_dict(args)
231 chameleon_args = hosts.CrosHost.get_chameleon_arguments(args_dict)
232 host = hosts.create_host(machine, chameleon_args=chameleon_args)
233 ~~~~~~~~
234
235 @param args_dict Dictionary from which to extract the chameleon
236 arguments.
237 """
238 return CrosHost._extract_arguments(
239 args_dict, ('chameleon_host', 'chameleon_port'))
240
241
242 @staticmethod
Scottfe06ed82015-11-05 17:15:01 -0800243 def get_plankton_arguments(args_dict):
244 """Extract chameleon options from `args_dict` and return the result.
245
246 Recommended usage:
247 ~~~~~~~~
248 args_dict = utils.args_to_dict(args)
249 plankon_args = hosts.CrosHost.get_plankton_arguments(args_dict)
250 host = hosts.create_host(machine, plankton_args=polankton_args)
251 ~~~~~~~~
252
253 @param args_dict Dictionary from which to extract the plankton
254 arguments.
255 """
256 args = CrosHost._extract_arguments(
257 args_dict, ('plankton_host', 'plankton_port'))
258 return args
259
260
261 @staticmethod
Tom Wai-Hong Tamefe1c7f2014-01-02 14:00:11 +0800262 def get_servo_arguments(args_dict):
263 """Extract servo options from `args_dict` and return the result.
J. Richard Barnette7214e0b2013-02-06 15:20:49 -0800264
265 Recommended usage:
266 ~~~~~~~~
267 args_dict = utils.args_to_dict(args)
Fang Deng0ca40e22013-08-27 17:47:44 -0700268 servo_args = hosts.CrosHost.get_servo_arguments(args_dict)
J. Richard Barnette7214e0b2013-02-06 15:20:49 -0800269 host = hosts.create_host(machine, servo_args=servo_args)
270 ~~~~~~~~
271
272 @param args_dict Dictionary from which to extract the servo
273 arguments.
274 """
Tom Wai-Hong Tamefe1c7f2014-01-02 14:00:11 +0800275 return CrosHost._extract_arguments(
276 args_dict, ('servo_host', 'servo_port'))
J. Richard Barnette134ec2c2012-04-25 12:59:37 -0700277
J. Richard Barnette964fba02012-10-24 17:34:29 -0700278
Scottfe06ed82015-11-05 17:15:01 -0800279 def _initialize(self, hostname, chameleon_args=None, servo_args=None, plankton_args=None,
Fang Denge545abb2014-12-30 18:43:47 -0800280 try_lab_servo=False, ssh_verbosity_flag='', ssh_options='',
Fang Dengd1c2b732013-08-20 12:59:46 -0700281 *args, **dargs):
Tom Wai-Hong Tamefe1c7f2014-01-02 14:00:11 +0800282 """Initialize superclasses, |self.chameleon|, and |self.servo|.
J. Richard Barnette67ccb872012-04-19 16:34:56 -0700283
Fang Denge545abb2014-12-30 18:43:47 -0800284 This method will attempt to create the test-assistant object
285 (chameleon/servo) when it is needed by the test. Check
286 the docstring of chameleon_host.create_chameleon_host and
287 servo_host.create_servo_host for how this is determined.
Fang Deng5d518f42013-08-02 14:04:32 -0700288
Fang Denge545abb2014-12-30 18:43:47 -0800289 @param hostname: Hostname of the dut.
290 @param chameleon_args: A dictionary that contains args for creating
291 a ChameleonHost. See chameleon_host for details.
292 @param servo_args: A dictionary that contains args for creating
293 a ServoHost object. See servo_host for details.
294 @param try_lab_servo: Boolean, False indicates that ServoHost should
295 not be created for a device in Cros test lab.
296 See servo_host for details.
297 @param ssh_verbosity_flag: String, to pass to the ssh command to control
298 verbosity.
299 @param ssh_options: String, other ssh options to pass to the ssh
300 command.
J. Richard Barnette67ccb872012-04-19 16:34:56 -0700301 """
Fang Deng0ca40e22013-08-27 17:47:44 -0700302 super(CrosHost, self)._initialize(hostname=hostname,
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700303 *args, **dargs)
J. Richard Barnettef0859852012-08-20 14:55:50 -0700304 # self.env is a dictionary of environment variable settings
305 # to be exported for commands run on the host.
306 # LIBC_FATAL_STDERR_ can be useful for diagnosing certain
307 # errors that might happen.
308 self.env['LIBC_FATAL_STDERR_'] = '1'
Fang Dengd1c2b732013-08-20 12:59:46 -0700309 self._ssh_verbosity_flag = ssh_verbosity_flag
Aviv Keshetc5947fa2013-09-04 14:06:29 -0700310 self._ssh_options = ssh_options
Fang Deng5d518f42013-08-02 14:04:32 -0700311 # TODO(fdeng): We need to simplify the
312 # process of servo and servo_host initialization.
313 # crbug.com/298432
Fang Denge545abb2014-12-30 18:43:47 -0800314 self._servo_host = servo_host.create_servo_host(
315 dut=self.hostname, servo_args=servo_args,
316 try_lab_servo=try_lab_servo)
Tom Wai-Hong Tamefe1c7f2014-01-02 14:00:11 +0800317 # TODO(waihong): Do the simplication on Chameleon too.
Tom Wai-Hong Tam3d6790d2014-04-14 16:15:47 +0800318 self._chameleon_host = chameleon_host.create_chameleon_host(
319 dut=self.hostname, chameleon_args=chameleon_args)
Scottfe06ed82015-11-05 17:15:01 -0800320 # Add plankton host if plankton args were added on command line
321 self._plankton_host = plankton_host.create_plankton_host(plankton_args)
Tom Wai-Hong Tam3d6790d2014-04-14 16:15:47 +0800322
Dan Shi4d478522014-02-14 13:46:32 -0800323 if self._servo_host is not None:
324 self.servo = self._servo_host.get_servo()
325 else:
326 self.servo = None
327
Tom Wai-Hong Tam3d6790d2014-04-14 16:15:47 +0800328 if self._chameleon_host:
Tom Wai-Hong Tameaee3402014-01-22 08:52:10 +0800329 self.chameleon = self._chameleon_host.create_chameleon_board()
Tom Wai-Hong Tamefe1c7f2014-01-02 14:00:11 +0800330 else:
Tom Wai-Hong Tam3d6790d2014-04-14 16:15:47 +0800331 self.chameleon = None
Fang Deng5d518f42013-08-02 14:04:32 -0700332
Scottfe06ed82015-11-05 17:15:01 -0800333 if self._plankton_host:
334 self.plankton_servo = self._plankton_host.get_servo()
335 logging.info('plankton_servo: %r', self.plankton_servo)
336 # Create the plankton object used to access the ec uart
337 self.plankton_console = plankton.PlanktonConsole(self.plankton_servo)
338 else:
339 self.plankton_console = None
340
Fang Deng5d518f42013-08-02 14:04:32 -0700341
Dan Shi3d7a0e12015-10-12 11:55:45 -0700342 def get_repair_image_name(self, image_type='cros'):
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500343 """Generate a image_name from variables in the global config.
344
Dan Shi3d7a0e12015-10-12 11:55:45 -0700345 image_type is used to differentiate different images. Default is CrOS,
346 in which case, repair image's name follows the naming convention defined
347 in global setting CROS/stable_build_pattern.
348 If the image_type is not `cros`, the repair image will be looked up
349 using key `board_name/image_type`, e.g., daisy_spring/firmware.
350
351 @param image_type: Type of the image. Default is `cros`.
352
Dan Shi08173202015-11-12 13:08:45 -0800353 @returns a str of $board-version/$BUILD. Returns None if stable version
354 for the board and the default are both not set, e.g., stable
355 firmware version for a new board.
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500356
357 """
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500358 board = self._get_board_from_afe()
359 if board is None:
360 raise error.AutoservError('DUT has no board attribute, '
361 'cannot be repaired.')
Dan Shi3d7a0e12015-10-12 11:55:45 -0700362 if image_type != 'cros':
363 board = '%s/%s' % (board, image_type)
Dan Shi6964fa52014-12-18 11:04:27 -0800364 stable_version = self._AFE.run('get_stable_version', board=board)
Dan Shi3d7a0e12015-10-12 11:55:45 -0700365 if image_type == 'cros':
366 build_pattern = CONFIG.get_config_value(
367 'CROS', 'stable_build_pattern')
368 stable_version = build_pattern % (board, stable_version)
Dan Shi08173202015-11-12 13:08:45 -0800369 elif image_type == 'firmware':
370 # If firmware stable version is not specified, `stable_version`
371 # from the RPC is the default stable version for CrOS image.
372 # firmware stable version must be from firmware branch, thus its
373 # value must be like board-firmware/R31-1234.0.0. Check if
374 # firmware exists in the stable version, if not, return None.
375 if 'firmware' not in stable_version:
376 return None
Dan Shi3d7a0e12015-10-12 11:55:45 -0700377 return stable_version
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500378
379
Scott Zawalski62bacae2013-03-05 10:40:32 -0500380 def _host_in_AFE(self):
381 """Check if the host is an object the AFE knows.
382
383 @returns the host object.
384 """
385 return self._AFE.get_hosts(hostname=self.hostname)
386
387
Chris Sosab76e0ee2013-05-22 16:55:41 -0700388 def lookup_job_repo_url(self):
389 """Looks up the job_repo_url for the host.
390
391 @returns job_repo_url from AFE or None if not found.
392
393 @raises KeyError if the host does not have a job_repo_url
394 """
Chris Sosab76e0ee2013-05-22 16:55:41 -0700395 hosts = self._AFE.get_hosts(hostname=self.hostname)
beepsb5efc532013-06-04 11:29:34 -0700396 if hosts and ds_constants.JOB_REPO_URL in hosts[0].attributes:
397 return hosts[0].attributes[ds_constants.JOB_REPO_URL]
J. Richard Barnette85d0aac2015-08-20 10:34:39 -0700398 else:
399 return None
Chris Sosab76e0ee2013-05-22 16:55:41 -0700400
401
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500402 def clear_cros_version_labels_and_job_repo_url(self):
403 """Clear cros_version labels and host attribute job_repo_url."""
Scott Zawalski62bacae2013-03-05 10:40:32 -0500404 if not self._host_in_AFE():
Scott Zawalskieadbf702013-03-14 09:23:06 -0400405 return
406
Scott Zawalski62bacae2013-03-05 10:40:32 -0500407 host_list = [self.hostname]
408 labels = self._AFE.get_labels(
409 name__startswith=ds_constants.VERSION_PREFIX,
410 host__hostname=self.hostname)
Dan Shi0f466e82013-02-22 15:44:58 -0800411
Scott Zawalski62bacae2013-03-05 10:40:32 -0500412 for label in labels:
413 label.remove_hosts(hosts=host_list)
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500414
beepscb6f1e22013-06-28 19:14:10 -0700415 self.update_job_repo_url(None, None)
416
417
418 def update_job_repo_url(self, devserver_url, image_name):
419 """
420 Updates the job_repo_url host attribute and asserts it's value.
421
422 @param devserver_url: The devserver to use in the job_repo_url.
423 @param image_name: The name of the image to use in the job_repo_url.
424
425 @raises AutoservError: If we failed to update the job_repo_url.
426 """
427 repo_url = None
428 if devserver_url and image_name:
429 repo_url = tools.get_package_url(devserver_url, image_name)
430 self._AFE.set_host_attribute(ds_constants.JOB_REPO_URL, repo_url,
Scott Zawalski62bacae2013-03-05 10:40:32 -0500431 hostname=self.hostname)
beepscb6f1e22013-06-28 19:14:10 -0700432 if self.lookup_job_repo_url() != repo_url:
433 raise error.AutoservError('Failed to update job_repo_url with %s, '
434 'host %s' % (repo_url, self.hostname))
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500435
436
Dan Shie9309262013-06-19 22:50:21 -0700437 def add_cros_version_labels_and_job_repo_url(self, image_name):
Scott Zawalskieadbf702013-03-14 09:23:06 -0400438 """Add cros_version labels and host attribute job_repo_url.
439
440 @param image_name: The name of the image e.g.
441 lumpy-release/R27-3837.0.0
Dan Shi7458bf62013-06-10 12:50:16 -0700442
Scott Zawalskieadbf702013-03-14 09:23:06 -0400443 """
Scott Zawalski62bacae2013-03-05 10:40:32 -0500444 if not self._host_in_AFE():
Scott Zawalskieadbf702013-03-14 09:23:06 -0400445 return
Scott Zawalski62bacae2013-03-05 10:40:32 -0500446
Scott Zawalskieadbf702013-03-14 09:23:06 -0400447 cros_label = '%s%s' % (ds_constants.VERSION_PREFIX, image_name)
Dan Shi216389c2015-12-22 11:03:06 -0800448 devserver_url = dev_server.ImageServer.resolve(image_name,
449 self.hostname).url()
Scott Zawalski62bacae2013-03-05 10:40:32 -0500450
MK Ryufb5e3a82015-07-01 12:21:20 -0700451 self._AFE.run('label_add_hosts', id=cros_label, hosts=[self.hostname])
beepscb6f1e22013-06-28 19:14:10 -0700452 self.update_job_repo_url(devserver_url, image_name)
453
454
beepsdae65fd2013-07-26 16:24:41 -0700455 def verify_job_repo_url(self, tag=''):
beepscb6f1e22013-06-28 19:14:10 -0700456 """
457 Make sure job_repo_url of this host is valid.
458
joychen03eaad92013-06-26 09:55:21 -0700459 Eg: The job_repo_url "http://lmn.cd.ab.xyx:8080/static/\
beepscb6f1e22013-06-28 19:14:10 -0700460 lumpy-release/R29-4279.0.0/autotest/packages" claims to have the
461 autotest package for lumpy-release/R29-4279.0.0. If this isn't the case,
462 download and extract it. If the devserver embedded in the url is
463 unresponsive, update the job_repo_url of the host after staging it on
464 another devserver.
465
466 @param job_repo_url: A url pointing to the devserver where the autotest
467 package for this build should be staged.
beepsdae65fd2013-07-26 16:24:41 -0700468 @param tag: The tag from the server job, in the format
469 <job_id>-<user>/<hostname>, or <hostless> for a server job.
beepscb6f1e22013-06-28 19:14:10 -0700470
471 @raises DevServerException: If we could not resolve a devserver.
472 @raises AutoservError: If we're unable to save the new job_repo_url as
473 a result of choosing a new devserver because the old one failed to
474 respond to a health check.
beeps0c865032013-07-30 11:37:06 -0700475 @raises urllib2.URLError: If the devserver embedded in job_repo_url
476 doesn't respond within the timeout.
beepscb6f1e22013-06-28 19:14:10 -0700477 """
478 job_repo_url = self.lookup_job_repo_url()
479 if not job_repo_url:
480 logging.warning('No job repo url set on host %s', self.hostname)
481 return
482
483 logging.info('Verifying job repo url %s', job_repo_url)
484 devserver_url, image_name = tools.get_devserver_build_from_package_url(
485 job_repo_url)
486
beeps0c865032013-07-30 11:37:06 -0700487 ds = dev_server.ImageServer(devserver_url)
beepscb6f1e22013-06-28 19:14:10 -0700488
489 logging.info('Staging autotest artifacts for %s on devserver %s',
490 image_name, ds.url())
beeps687243d2013-07-18 15:29:27 -0700491
492 start_time = time.time()
Simran Basi25e7a922014-10-31 11:56:10 -0700493 ds.stage_artifacts(image_name, ['autotest_packages'])
beeps687243d2013-07-18 15:29:27 -0700494 stage_time = time.time() - start_time
495
496 # Record how much of the verification time comes from a devserver
497 # restage. If we're doing things right we should not see multiple
498 # devservers for a given board/build/branch path.
499 try:
J. Richard Barnette3cbd76b2013-11-27 12:11:25 -0800500 board, build_type, branch = server_utils.ParseBuildName(
beeps687243d2013-07-18 15:29:27 -0700501 image_name)[:3]
J. Richard Barnette3cbd76b2013-11-27 12:11:25 -0800502 except server_utils.ParseBuildNameException:
beeps687243d2013-07-18 15:29:27 -0700503 pass
504 else:
beeps0c865032013-07-30 11:37:06 -0700505 devserver = devserver_url[
Chris Sosa65425082013-10-16 13:26:22 -0700506 devserver_url.find('/') + 2:devserver_url.rfind(':')]
beeps687243d2013-07-18 15:29:27 -0700507 stats_key = {
508 'board': board,
509 'build_type': build_type,
510 'branch': branch,
beeps0c865032013-07-30 11:37:06 -0700511 'devserver': devserver.replace('.', '_'),
beeps687243d2013-07-18 15:29:27 -0700512 }
Gabe Black1e1c41b2015-02-04 23:55:15 -0800513 autotest_stats.Gauge('verify_job_repo_url').send(
beeps687243d2013-07-18 15:29:27 -0700514 '%(board)s.%(build_type)s.%(branch)s.%(devserver)s' % stats_key,
515 stage_time)
beepscb6f1e22013-06-28 19:14:10 -0700516
Scott Zawalskieadbf702013-03-14 09:23:06 -0400517
Dan Shicf4d2032015-03-12 15:04:21 -0700518 def stage_server_side_package(self, image=None):
519 """Stage autotest server-side package on devserver.
520
521 @param image: Full path of an OS image to install or a build name.
522
523 @return: A url to the autotest server-side package.
524 """
525 if image:
526 image_name = tools.get_build_from_image(image)
527 if not image_name:
528 raise error.AutoservError(
529 'Failed to parse build name from %s' % image)
530 ds = dev_server.ImageServer.resolve(image_name)
531 else:
532 job_repo_url = self.lookup_job_repo_url()
533 if job_repo_url:
534 devserver_url, image_name = (
535 tools.get_devserver_build_from_package_url(job_repo_url))
536 ds = dev_server.ImageServer(devserver_url)
537 else:
538 labels = self._AFE.get_labels(
539 name__startswith=ds_constants.VERSION_PREFIX,
540 host__hostname=self.hostname)
541 if not labels:
542 raise error.AutoservError(
543 'Failed to stage server-side package. The host has '
544 'no job_report_url attribute or version label.')
545 image_name = labels[0].name[len(ds_constants.VERSION_PREFIX):]
546 ds = dev_server.ImageServer.resolve(image_name)
Dan Shica503482015-03-30 17:23:25 -0700547
548 # Get the OS version of the build, for any build older than
549 # MIN_VERSION_SUPPORT_SSP, server side packaging is not supported.
550 match = re.match('.*/R\d+-(\d+)\.', image_name)
551 if match and int(match.group(1)) < self.MIN_VERSION_SUPPORT_SSP:
552 logging.warn('Build %s is older than %s. Server side packaging is '
553 'disabled.', image_name, self.MIN_VERSION_SUPPORT_SSP)
554 return None
555
Dan Shicf4d2032015-03-12 15:04:21 -0700556 ds.stage_artifacts(image_name, ['autotest_server_package'])
557 return '%s/static/%s/%s' % (ds.url(), image_name,
558 'autotest_server_package.tar.bz2')
559
560
Dan Shi0f466e82013-02-22 15:44:58 -0800561 def _try_stateful_update(self, update_url, force_update, updater):
562 """Try to use stateful update to initialize DUT.
563
564 When DUT is already running the same version that machine_install
565 tries to install, stateful update is a much faster way to clean up
566 the DUT for testing, compared to a full reimage. It is implemeted
567 by calling autoupdater.run_update, but skipping updating root, as
568 updating the kernel is time consuming and not necessary.
569
570 @param update_url: url of the image.
571 @param force_update: Set to True to update the image even if the DUT
572 is running the same version.
573 @param updater: ChromiumOSUpdater instance used to update the DUT.
574 @returns: True if the DUT was updated with stateful update.
575
576 """
J. Richard Barnette3f731032014-04-07 17:42:59 -0700577 # TODO(jrbarnette): Yes, I hate this re.match() test case.
578 # It's better than the alternative: see crbug.com/360944.
579 image_name = autoupdater.url_to_image_name(update_url)
580 release_pattern = r'^.*-release/R[0-9]+-[0-9]+\.[0-9]+\.0$'
581 if not re.match(release_pattern, image_name):
582 return False
Dan Shi0f466e82013-02-22 15:44:58 -0800583 if not updater.check_version():
584 return False
585 if not force_update:
586 logging.info('Canceling stateful update because the new and '
587 'old versions are the same.')
588 return False
589 # Following folders should be rebuilt after stateful update.
590 # A test file is used to confirm each folder gets rebuilt after
591 # the stateful update.
592 folders_to_check = ['/var', '/home', '/mnt/stateful_partition']
593 test_file = '.test_file_to_be_deleted'
594 for folder in folders_to_check:
595 touch_path = os.path.join(folder, test_file)
596 self.run('touch %s' % touch_path)
597
Chris Sosae92399e2015-04-24 11:32:59 -0700598 updater.run_update(update_root=False)
Dan Shi0f466e82013-02-22 15:44:58 -0800599
600 # Reboot to complete stateful update.
Chris Sosab76e0ee2013-05-22 16:55:41 -0700601 self.reboot(timeout=self.REBOOT_TIMEOUT, wait=True)
Dan Shi0f466e82013-02-22 15:44:58 -0800602 check_file_cmd = 'test -f %s; echo $?'
603 for folder in folders_to_check:
604 test_file_path = os.path.join(folder, test_file)
605 result = self.run(check_file_cmd % test_file_path,
606 ignore_status=True)
607 if result.exit_status == 1:
608 return False
609 return True
610
611
J. Richard Barnette7275b612013-06-04 18:13:11 -0700612 def _post_update_processing(self, updater, expected_kernel=None):
Dan Shi0f466e82013-02-22 15:44:58 -0800613 """After the DUT is updated, confirm machine_install succeeded.
614
615 @param updater: ChromiumOSUpdater instance used to update the DUT.
J. Richard Barnette7275b612013-06-04 18:13:11 -0700616 @param expected_kernel: kernel expected to be active after reboot,
617 or `None` to skip rollback checking.
Dan Shi0f466e82013-02-22 15:44:58 -0800618
619 """
J. Richard Barnette7275b612013-06-04 18:13:11 -0700620 # Touch the lab machine file to leave a marker that
621 # distinguishes this image from other test images.
622 # Afterwards, we must re-run the autoreboot script because
623 # it depends on the _LAB_MACHINE_FILE.
J. Richard Barnette71cc1862015-12-02 10:32:38 -0800624 autoreboot_cmd = ('FILE="%s" ; [ -f "$FILE" ] || '
625 '( touch "$FILE" ; start autoreboot )')
626 self.run(autoreboot_cmd % self._LAB_MACHINE_FILE)
Chris Sosa65425082013-10-16 13:26:22 -0700627 updater.verify_boot_expectations(
628 expected_kernel, rollback_message=
Gilad Arnoldc26ae1f2015-10-22 16:09:41 -0700629 'Build %s failed to boot on %s; system rolled back to previous '
Chris Sosa65425082013-10-16 13:26:22 -0700630 'build' % (updater.update_version, self.hostname))
J. Richard Barnette7275b612013-06-04 18:13:11 -0700631 # Check that we've got the build we meant to install.
632 if not updater.check_version_to_confirm_install():
633 raise autoupdater.ChromiumOSError(
634 'Failed to update %s to build %s; found build '
635 '%s instead' % (self.hostname,
Chris Sosa65425082013-10-16 13:26:22 -0700636 updater.update_version,
Dan Shi0942b1d2015-03-31 11:07:00 -0700637 self.get_release_version()))
Dan Shi0f466e82013-02-22 15:44:58 -0800638
Chris Sosae92399e2015-04-24 11:32:59 -0700639 logging.debug('Cleaning up old autotest directories.')
640 try:
641 installed_autodir = autotest.Autotest.get_installed_autodir(self)
642 self.run('rm -rf ' + installed_autodir)
643 except autotest.AutodirNotFoundError:
644 logging.debug('No autotest installed directory found.')
645
Dan Shi0f466e82013-02-22 15:44:58 -0800646
J. Richard Barnettee4af8b92013-05-01 13:16:12 -0700647 def _stage_image_for_update(self, image_name=None):
Chris Sosae92399e2015-04-24 11:32:59 -0700648 """Stage a build on a devserver and return the update_url and devserver.
Scott Zawalskieadbf702013-03-14 09:23:06 -0400649
650 @param image_name: a name like lumpy-release/R27-3837.0.0
Chris Sosae92399e2015-04-24 11:32:59 -0700651 @returns a tuple with an update URL like:
Scott Zawalskieadbf702013-03-14 09:23:06 -0400652 http://172.22.50.205:8082/update/lumpy-release/R27-3837.0.0
Chris Sosae92399e2015-04-24 11:32:59 -0700653 and the devserver instance.
Scott Zawalskieadbf702013-03-14 09:23:06 -0400654 """
J. Richard Barnettee4af8b92013-05-01 13:16:12 -0700655 if not image_name:
656 image_name = self.get_repair_image_name()
Chris Sosae92399e2015-04-24 11:32:59 -0700657
J. Richard Barnettee4af8b92013-05-01 13:16:12 -0700658 logging.info('Staging build for AU: %s', image_name)
Dan Shi216389c2015-12-22 11:03:06 -0800659 devserver = dev_server.ImageServer.resolve(image_name, self.hostname)
Scott Zawalskieadbf702013-03-14 09:23:06 -0400660 devserver.trigger_download(image_name, synchronous=False)
Chris Sosae92399e2015-04-24 11:32:59 -0700661 return (tools.image_url_pattern() % (devserver.url(), image_name),
662 devserver)
Scott Zawalskieadbf702013-03-14 09:23:06 -0400663
664
J. Richard Barnettee4af8b92013-05-01 13:16:12 -0700665 def stage_image_for_servo(self, image_name=None):
666 """Stage a build on a devserver and return the update_url.
667
668 @param image_name: a name like lumpy-release/R27-3837.0.0
669 @returns an update URL like:
670 http://172.22.50.205:8082/update/lumpy-release/R27-3837.0.0
671 """
672 if not image_name:
673 image_name = self.get_repair_image_name()
674 logging.info('Staging build for servo install: %s', image_name)
Dan Shi216389c2015-12-22 11:03:06 -0800675 devserver = dev_server.ImageServer.resolve(image_name, self.hostname)
J. Richard Barnettee4af8b92013-05-01 13:16:12 -0700676 devserver.stage_artifacts(image_name, ['test_image'])
677 return devserver.get_test_image_url(image_name)
678
679
beepse539be02013-07-31 21:57:39 -0700680 def stage_factory_image_for_servo(self, image_name):
681 """Stage a build on a devserver and return the update_url.
682
683 @param image_name: a name like <baord>/4262.204.0
beeps12c0a3c2013-09-03 11:58:27 -0700684
beepse539be02013-07-31 21:57:39 -0700685 @return: An update URL, eg:
686 http://<devserver>/static/canary-channel/\
687 <board>/4262.204.0/factory_test/chromiumos_factory_image.bin
beeps12c0a3c2013-09-03 11:58:27 -0700688
689 @raises: ValueError if the factory artifact name is missing from
690 the config.
691
beepse539be02013-07-31 21:57:39 -0700692 """
693 if not image_name:
694 logging.error('Need an image_name to stage a factory image.')
695 return
696
Dan Shib8540a52015-07-16 14:18:23 -0700697 factory_artifact = CONFIG.get_config_value(
beeps12c0a3c2013-09-03 11:58:27 -0700698 'CROS', 'factory_artifact', type=str, default='')
699 if not factory_artifact:
700 raise ValueError('Cannot retrieve the factory artifact name from '
701 'autotest config, and hence cannot stage factory '
702 'artifacts.')
703
beepse539be02013-07-31 21:57:39 -0700704 logging.info('Staging build for servo install: %s', image_name)
Dan Shi216389c2015-12-22 11:03:06 -0800705 devserver = dev_server.ImageServer.resolve(image_name, self.hostname)
beepse539be02013-07-31 21:57:39 -0700706 devserver.stage_artifacts(
707 image_name,
beeps12c0a3c2013-09-03 11:58:27 -0700708 [factory_artifact],
709 archive_url=None)
beepse539be02013-07-31 21:57:39 -0700710
711 return tools.factory_image_url_pattern() % (devserver.url(), image_name)
712
713
Chris Sosaa3ac2152012-05-23 22:23:13 -0700714 def machine_install(self, update_url=None, force_update=False,
Richard Barnette0b023a72015-04-24 16:07:30 +0000715 local_devserver=False, repair=False,
716 force_full_update=False):
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500717 """Install the DUT.
718
Dan Shi0f466e82013-02-22 15:44:58 -0800719 Use stateful update if the DUT is already running the same build.
720 Stateful update does not update kernel and tends to run much faster
721 than a full reimage. If the DUT is running a different build, or it
722 failed to do a stateful update, full update, including kernel update,
723 will be applied to the DUT.
724
Scott Zawalskieadbf702013-03-14 09:23:06 -0400725 Once a host enters machine_install its cros_version label will be
726 removed as well as its host attribute job_repo_url (used for
727 package install).
728
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500729 @param update_url: The url to use for the update
730 pattern: http://$devserver:###/update/$build
731 If update_url is None and repair is True we will install the
Dan Shi6964fa52014-12-18 11:04:27 -0800732 stable image listed in afe_stable_versions table. If the table
733 is not setup, global_config value under CROS.stable_cros_version
734 will be used instead.
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500735 @param force_update: Force an update even if the version installed
736 is the same. Default:False
Christopher Wiley6a4ff932015-05-15 14:00:47 -0700737 @param local_devserver: Used by test_that to allow people to
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500738 use their local devserver. Default: False
Chris Sosae92399e2015-04-24 11:32:59 -0700739 @param repair: Forces update to repair image. Implies force_update.
Fang Deng3d3b9272014-12-22 12:20:28 -0800740 @param force_full_update: If True, do not attempt to run stateful
741 update, force a full reimage. If False, try stateful update
742 first when the dut is already installed with the same version.
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500743 @raises autoupdater.ChromiumOSError
744
745 """
Chris Sosae92399e2015-04-24 11:32:59 -0700746 devserver = None
Richard Barnette0b023a72015-04-24 16:07:30 +0000747 if repair:
Chris Sosae92399e2015-04-24 11:32:59 -0700748 update_url, devserver = self._stage_image_for_update()
Richard Barnette0b023a72015-04-24 16:07:30 +0000749 force_update = True
Dan Shi0f466e82013-02-22 15:44:58 -0800750
Chris Sosae92399e2015-04-24 11:32:59 -0700751 if not update_url and not self._parser.options.image:
752 raise error.AutoservError(
Dan Shid07ee2e2015-09-24 14:49:25 -0700753 'There is no update URL, nor a method to get one.')
Chris Sosae92399e2015-04-24 11:32:59 -0700754
755 if not update_url and self._parser.options.image:
756 # This is the base case where we have no given update URL i.e.
757 # dynamic suites logic etc. This is the most flexible case where we
758 # can serve an update from any of our fleet of devservers.
759 requested_build = self._parser.options.image
760 if not requested_build.startswith('http://'):
761 logging.debug('Update will be staged for this installation')
762 update_url, devserver = self._stage_image_for_update(
Dan Shid07ee2e2015-09-24 14:49:25 -0700763 requested_build)
Chris Sosae92399e2015-04-24 11:32:59 -0700764 else:
765 update_url = requested_build
766
767 logging.debug('Update URL is %s', update_url)
768
Scott Zawalskieadbf702013-03-14 09:23:06 -0400769 # Remove cros-version and job_repo_url host attribute from host.
770 self.clear_cros_version_labels_and_job_repo_url()
Chris Sosae92399e2015-04-24 11:32:59 -0700771
Dan Shid07ee2e2015-09-24 14:49:25 -0700772 # Create a file to indicate if provision fails. The file will be removed
773 # by stateful update or full install.
774 self.run('touch %s' % PROVISION_FAILED)
775
Chris Sosae92399e2015-04-24 11:32:59 -0700776 update_complete = False
777 updater = autoupdater.ChromiumOSUpdater(
778 update_url, host=self, local_devserver=local_devserver)
Fang Deng3d3b9272014-12-22 12:20:28 -0800779 if not force_full_update:
780 try:
Chris Sosae92399e2015-04-24 11:32:59 -0700781 # If the DUT is already running the same build, try stateful
782 # update first as it's much quicker than a full re-image.
783 update_complete = self._try_stateful_update(
Dan Shid07ee2e2015-09-24 14:49:25 -0700784 update_url, force_update, updater)
Fang Deng3d3b9272014-12-22 12:20:28 -0800785 except Exception as e:
786 logging.exception(e)
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700787
Dan Shi0f466e82013-02-22 15:44:58 -0800788 inactive_kernel = None
Chris Sosae92399e2015-04-24 11:32:59 -0700789 if update_complete or (not force_update and updater.check_version()):
790 logging.info('Install complete without full update')
791 else:
792 logging.info('DUT requires full update.')
793 self.reboot(timeout=self.REBOOT_TIMEOUT, wait=True)
794 num_of_attempts = provision.FLAKY_DEVSERVER_ATTEMPTS
Chris Sosab7612bc2013-03-21 10:32:37 -0700795
Chris Sosae92399e2015-04-24 11:32:59 -0700796 while num_of_attempts > 0:
797 num_of_attempts -= 1
798 try:
799 updater.run_update()
800 except Exception:
801 logging.warn('Autoupdate did not complete.')
802 # Do additional check for the devserver health. Ideally,
803 # the autoupdater.py could raise an exception when it
804 # detected network flake but that would require
805 # instrumenting the update engine and parsing it log.
806 if (num_of_attempts <= 0 or
807 devserver is None or
808 dev_server.DevServer.devserver_healthy(
809 devserver.url())):
Dan Shid07ee2e2015-09-24 14:49:25 -0700810 raise
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700811
Chris Sosae92399e2015-04-24 11:32:59 -0700812 logging.warn('Devserver looks unhealthy. Trying another')
813 update_url, devserver = self._stage_image_for_update(
814 requested_build)
815 logging.debug('New Update URL is %s', update_url)
816 updater = autoupdater.ChromiumOSUpdater(
817 update_url, host=self,
818 local_devserver=local_devserver)
819 else:
820 break
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700821
Chris Sosae92399e2015-04-24 11:32:59 -0700822 # Give it some time in case of IO issues.
823 time.sleep(10)
Dan Shi5699ac22014-12-19 10:55:49 -0800824
Chris Sosae92399e2015-04-24 11:32:59 -0700825 # Figure out active and inactive kernel.
826 active_kernel, inactive_kernel = updater.get_kernel_state()
Simran Basi13fa1ba2013-03-04 10:56:47 -0800827
Chris Sosae92399e2015-04-24 11:32:59 -0700828 # Ensure inactive kernel has higher priority than active.
829 if (updater.get_kernel_priority(inactive_kernel)
830 < updater.get_kernel_priority(active_kernel)):
831 raise autoupdater.ChromiumOSError(
832 'Update failed. The priority of the inactive kernel'
833 ' partition is less than that of the active kernel'
834 ' partition.')
835
836 # Updater has returned successfully; reboot the host.
837 self.reboot(timeout=self.REBOOT_TIMEOUT, wait=True)
838
839 self._post_update_processing(updater, inactive_kernel)
840 self.add_cros_version_labels_and_job_repo_url(
841 autoupdater.url_to_image_name(update_url))
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700842
843
Tom Wai-Hong Tam2d00cb22016-01-08 06:40:50 +0800844 def _clear_fw_version_labels(self, rw_only):
845 """Clear firmware version labels from the machine.
846
847 @param rw_only: True to only clear fwrw_version; otherewise, clear
848 both fwro_version and fwrw_version.
849 """
Dan Shi9cb0eec2014-06-03 09:04:50 -0700850 labels = self._AFE.get_labels(
Dan Shi0723bf52015-06-24 10:52:38 -0700851 name__startswith=provision.FW_RW_VERSION_PREFIX,
Dan Shi9cb0eec2014-06-03 09:04:50 -0700852 host__hostname=self.hostname)
Tom Wai-Hong Tam2d00cb22016-01-08 06:40:50 +0800853 if not rw_only:
854 labels = labels + self._AFE.get_labels(
855 name__startswith=provision.FW_RO_VERSION_PREFIX,
856 host__hostname=self.hostname)
Dan Shi9cb0eec2014-06-03 09:04:50 -0700857 for label in labels:
858 label.remove_hosts(hosts=[self.hostname])
859
860
Tom Wai-Hong Tam2d00cb22016-01-08 06:40:50 +0800861 def _add_fw_version_label(self, build, rw_only):
Dan Shi9cb0eec2014-06-03 09:04:50 -0700862 """Add firmware version label to the machine.
863
864 @param build: Build of firmware.
Tom Wai-Hong Tam2d00cb22016-01-08 06:40:50 +0800865 @param rw_only: True to only add fwrw_version; otherwise, add both
866 fwro_version and fwrw_version.
Dan Shi9cb0eec2014-06-03 09:04:50 -0700867
868 """
Tom Wai-Hong Tam2d00cb22016-01-08 06:40:50 +0800869 fw_label = provision.fwrw_version_to_label(build)
MK Ryu73be9862015-07-06 12:25:00 -0700870 self._AFE.run('label_add_hosts', id=fw_label, hosts=[self.hostname])
Tom Wai-Hong Tam2d00cb22016-01-08 06:40:50 +0800871 if not rw_only:
872 fw_label = provision.fwro_version_to_label(build)
873 self._AFE.run('label_add_hosts', id=fw_label, hosts=[self.hostname])
Dan Shi9cb0eec2014-06-03 09:04:50 -0700874
875
Tom Wai-Hong Tam4ac78982016-01-08 02:34:37 +0800876 def firmware_install(self, build=None, rw_only=False):
Dan Shi9cb0eec2014-06-03 09:04:50 -0700877 """Install firmware to the DUT.
878
879 Use stateful update if the DUT is already running the same build.
880 Stateful update does not update kernel and tends to run much faster
881 than a full reimage. If the DUT is running a different build, or it
882 failed to do a stateful update, full update, including kernel update,
883 will be applied to the DUT.
884
Tom Wai-Hong Tam2d00cb22016-01-08 06:40:50 +0800885 Once a host enters firmware_install its fw[ro|rw]_version label will
886 be removed. After the firmware is updated successfully, a new
887 fw[ro|rw]_version label will be added to the host.
Dan Shi9cb0eec2014-06-03 09:04:50 -0700888
889 @param build: The build version to which we want to provision the
890 firmware of the machine,
891 e.g. 'link-firmware/R22-2695.1.144'.
Tom Wai-Hong Tam4ac78982016-01-08 02:34:37 +0800892 @param rw_only: True to only install firmware to its RW portions. Keep
893 the RO portions unchanged.
Dan Shi9cb0eec2014-06-03 09:04:50 -0700894
895 TODO(dshi): After bug 381718 is fixed, update here with corresponding
896 exceptions that could be raised.
897
898 """
899 if not self.servo:
900 raise error.TestError('Host %s does not have servo.' %
901 self.hostname)
902
903 # TODO(fdeng): use host.get_board() after
904 # crbug.com/271834 is fixed.
905 board = self._get_board_from_afe()
906
Chris Sosae92399e2015-04-24 11:32:59 -0700907 # If build is not set, try to install firmware from stable CrOS.
Dan Shi9cb0eec2014-06-03 09:04:50 -0700908 if not build:
Dan Shi3d7a0e12015-10-12 11:55:45 -0700909 build = self.get_repair_image_name(image_type='firmware')
910 if not build:
911 raise error.TestError(
912 'Failed to find stable firmware build for %s.',
913 self.hostname)
914 logging.info('Will install firmware from build %s.', build)
Dan Shi9cb0eec2014-06-03 09:04:50 -0700915
916 config = FAFTConfig(board)
917 if config.use_u_boot:
918 ap_image = 'image-%s.bin' % board
919 else: # Depthcharge platform
920 ap_image = 'image.bin'
921 ec_image = 'ec.bin'
Dan Shi216389c2015-12-22 11:03:06 -0800922 ds = dev_server.ImageServer.resolve(build, self.hostname)
Dan Shi9cb0eec2014-06-03 09:04:50 -0700923 ds.stage_artifacts(build, ['firmware'])
924
925 tmpd = autotemp.tempdir(unique_id='fwimage')
926 try:
927 fwurl = self._FW_IMAGE_URL_PATTERN % (ds.url(), build)
928 local_tarball = os.path.join(tmpd.name, os.path.basename(fwurl))
929 server_utils.system('wget -O %s %s' % (local_tarball, fwurl),
930 timeout=60)
931 server_utils.system('tar xf %s -C %s %s %s' %
932 (local_tarball, tmpd.name, ap_image, ec_image),
933 timeout=60)
934 server_utils.system('tar xf %s --wildcards -C %s "dts/*"' %
935 (local_tarball, tmpd.name),
936 timeout=60, ignore_status=True)
937
Tom Wai-Hong Tam2d00cb22016-01-08 06:40:50 +0800938 self._clear_fw_version_labels(rw_only)
Tom Wai-Hong Tam4ac78982016-01-08 02:34:37 +0800939 logging.info('Will re-program EC %snow', 'RW ' if rw_only else '')
940 self.servo.program_ec(os.path.join(tmpd.name, ec_image), rw_only)
941 logging.info('Will re-program BIOS %snow', 'RW ' if rw_only else '')
942 self.servo.program_bios(os.path.join(tmpd.name, ap_image), rw_only)
Dan Shi9cb0eec2014-06-03 09:04:50 -0700943 self.servo.get_power_state_controller().reset()
944 time.sleep(self.servo.BOOT_DELAY)
Tom Wai-Hong Tam2d00cb22016-01-08 06:40:50 +0800945 self._add_fw_version_label(build, rw_only)
Dan Shi9cb0eec2014-06-03 09:04:50 -0700946 finally:
947 tmpd.clean()
948
949
Dan Shi10e992b2013-08-30 11:02:59 -0700950 def show_update_engine_log(self):
951 """Output update engine log."""
MK Ryu35d661e2014-09-25 17:44:10 -0700952 logging.debug('Dumping %s', client_constants.UPDATE_ENGINE_LOG)
953 self.run('cat %s' % client_constants.UPDATE_ENGINE_LOG)
Dan Shi10e992b2013-08-30 11:02:59 -0700954
955
Richard Barnette82c35912012-11-20 10:09:10 -0800956 def _get_board_from_afe(self):
957 """Retrieve this host's board from its labels in the AFE.
958
959 Looks for a host label of the form "board:<board>", and
960 returns the "<board>" part of the label. `None` is returned
961 if there is not a single, unique label matching the pattern.
962
963 @returns board from label, or `None`.
964 """
Dan Shia1ecd5c2013-06-06 11:21:31 -0700965 return server_utils.get_board_from_afe(self.hostname, self._AFE)
Simran Basi833814b2013-01-29 13:13:43 -0800966
967
968 def get_build(self):
969 """Retrieve the current build for this Host from the AFE.
970
971 Looks through this host's labels in the AFE to determine its build.
972
973 @returns The current build or None if it could not find it or if there
974 were multiple build labels assigned to this host.
975 """
Dan Shia1ecd5c2013-06-06 11:21:31 -0700976 return server_utils.get_build_from_afe(self.hostname, self._AFE)
Richard Barnette82c35912012-11-20 10:09:10 -0800977
978
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500979 def _install_repair(self):
Chris Sosae92399e2015-04-24 11:32:59 -0700980 """Attempt to repair this host using the update-engine.
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500981
982 If the host is up, try installing the DUT with a stable
Dan Shi6964fa52014-12-18 11:04:27 -0800983 "repair" version of Chrome OS as defined in afe_stable_versions table.
984 If the table is not setup, global_config value under
985 CROS.stable_cros_version will be used instead.
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500986
Scott Zawalski62bacae2013-03-05 10:40:32 -0500987 @raises AutoservRepairMethodNA if the DUT is not reachable.
988 @raises ChromiumOSError if the install failed for some reason.
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500989
990 """
991 if not self.is_up():
Scott Zawalski62bacae2013-03-05 10:40:32 -0500992 raise error.AutoservRepairMethodNA('DUT unreachable for install.')
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500993 logging.info('Attempting to reimage machine to repair image.')
994 try:
Richard Barnette0b023a72015-04-24 16:07:30 +0000995 self.machine_install(repair=True)
Fang Dengd0672f32013-03-18 17:18:09 -0700996 except autoupdater.ChromiumOSError as e:
997 logging.exception(e)
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500998 logging.info('Repair via install failed.')
Scott Zawalski62bacae2013-03-05 10:40:32 -0500999 raise
Scott Zawalski89c44dd2013-02-26 09:28:02 -05001000
1001
Dan Shi2c88eed2013-11-12 10:18:38 -08001002 def _install_repair_with_powerwash(self):
Dan Shi9cc48452013-11-12 12:39:26 -08001003 """Attempt to powerwash first then repair this host using update-engine.
Dan Shi2c88eed2013-11-12 10:18:38 -08001004
Dan Shi9cc48452013-11-12 12:39:26 -08001005 update-engine may fail due to a bad image. In such case, powerwash
1006 may help to cleanup the DUT for update-engine to work again.
Dan Shi2c88eed2013-11-12 10:18:38 -08001007
1008 @raises AutoservRepairMethodNA if the DUT is not reachable.
1009 @raises ChromiumOSError if the install failed for some reason.
1010
1011 """
1012 if not self.is_up():
1013 raise error.AutoservRepairMethodNA('DUT unreachable for install.')
1014
1015 logging.info('Attempting to powerwash the DUT.')
1016 self.run('echo "fast safe" > '
1017 '/mnt/stateful_partition/factory_install_reset')
1018 self.reboot(timeout=self.POWERWASH_BOOT_TIMEOUT, wait=True)
1019 if not self.is_up():
Dan Shi9cc48452013-11-12 12:39:26 -08001020 logging.error('Powerwash failed. DUT did not come back after '
Dan Shi2c88eed2013-11-12 10:18:38 -08001021 'reboot.')
1022 raise error.AutoservRepairFailure(
1023 'DUT failed to boot from powerwash after %d seconds' %
1024 self.POWERWASH_BOOT_TIMEOUT)
1025
1026 logging.info('Powerwash succeeded.')
1027 self._install_repair()
1028
1029
beepsf079cfb2013-09-18 17:49:51 -07001030 def servo_install(self, image_url=None, usb_boot_timeout=USB_BOOT_TIMEOUT,
1031 install_timeout=INSTALL_TIMEOUT):
Scott Zawalski62bacae2013-03-05 10:40:32 -05001032 """
1033 Re-install the OS on the DUT by:
1034 1) installing a test image on a USB storage device attached to the Servo
1035 board,
Richard Barnette03a0c132012-11-05 12:40:35 -08001036 2) booting that image in recovery mode, and then
J. Richard Barnette31b2e312013-04-04 16:05:22 -07001037 3) installing the image with chromeos-install.
1038
Scott Zawalski62bacae2013-03-05 10:40:32 -05001039 @param image_url: If specified use as the url to install on the DUT.
1040 otherwise boot the currently staged image on the USB stick.
beepsf079cfb2013-09-18 17:49:51 -07001041 @param usb_boot_timeout: The usb_boot_timeout to use during reimage.
1042 Factory images need a longer usb_boot_timeout than regular
1043 cros images.
1044 @param install_timeout: The timeout to use when installing the chromeos
1045 image. Factory images need a longer install_timeout.
Richard Barnette03a0c132012-11-05 12:40:35 -08001046
Scott Zawalski62bacae2013-03-05 10:40:32 -05001047 @raises AutoservError if the image fails to boot.
beepsf079cfb2013-09-18 17:49:51 -07001048
J. Richard Barnette0199cc82014-12-05 17:08:40 -08001049 """
beepsf079cfb2013-09-18 17:49:51 -07001050 usb_boot_timer_key = ('servo_install.usb_boot_timeout_%s'
1051 % usb_boot_timeout)
1052 logging.info('Downloading image to USB, then booting from it. Usb boot '
1053 'timeout = %s', usb_boot_timeout)
Gabe Black1e1c41b2015-02-04 23:55:15 -08001054 timer = autotest_stats.Timer(usb_boot_timer_key)
beepsf079cfb2013-09-18 17:49:51 -07001055 timer.start()
J. Richard Barnette31b2e312013-04-04 16:05:22 -07001056 self.servo.install_recovery_image(image_url)
beepsf079cfb2013-09-18 17:49:51 -07001057 if not self.wait_up(timeout=usb_boot_timeout):
Scott Zawalski62bacae2013-03-05 10:40:32 -05001058 raise error.AutoservRepairFailure(
1059 'DUT failed to boot from USB after %d seconds' %
beepsf079cfb2013-09-18 17:49:51 -07001060 usb_boot_timeout)
1061 timer.stop()
Scott Zawalski62bacae2013-03-05 10:40:32 -05001062
Tom Wai-Hong Tamf6b4f812015-08-08 04:14:59 +08001063 # The new chromeos-tpm-recovery has been merged since R44-7073.0.0.
1064 # In old CrOS images, this command fails. Skip the error.
Tom Wai-Hong Tam27af7332015-07-25 06:09:39 +08001065 logging.info('Resetting the TPM status')
Tom Wai-Hong Tamf6b4f812015-08-08 04:14:59 +08001066 try:
1067 self.run('chromeos-tpm-recovery')
1068 except error.AutoservRunError:
1069 logging.warn('chromeos-tpm-recovery is too old.')
1070
Tom Wai-Hong Tam27af7332015-07-25 06:09:39 +08001071
beepsf079cfb2013-09-18 17:49:51 -07001072 install_timer_key = ('servo_install.install_timeout_%s'
1073 % install_timeout)
Gabe Black1e1c41b2015-02-04 23:55:15 -08001074 timer = autotest_stats.Timer(install_timer_key)
beepsf079cfb2013-09-18 17:49:51 -07001075 timer.start()
1076 logging.info('Installing image through chromeos-install.')
J. Richard Barnette9af19632015-09-25 12:18:03 -07001077 self.run('chromeos-install --yes', timeout=install_timeout)
1078 self.halt()
beepsf079cfb2013-09-18 17:49:51 -07001079 timer.stop()
1080
1081 logging.info('Power cycling DUT through servo.')
J. Richard Barnette0199cc82014-12-05 17:08:40 -08001082 self.servo.get_power_state_controller().power_off()
Fang Dengafb88142013-05-30 17:44:31 -07001083 self.servo.switch_usbkey('off')
J. Richard Barnette0199cc82014-12-05 17:08:40 -08001084 # N.B. The Servo API requires that we use power_on() here
1085 # for two reasons:
1086 # 1) After turning on a DUT in recovery mode, you must turn
1087 # it off and then on with power_on() once more to
1088 # disable recovery mode (this is a Parrot specific
1089 # requirement).
1090 # 2) After power_off(), the only way to turn on is with
1091 # power_on() (this is a Storm specific requirement).
J. Richard Barnettefbcc7122013-07-24 18:24:59 -07001092 self.servo.get_power_state_controller().power_on()
beepsf079cfb2013-09-18 17:49:51 -07001093
1094 logging.info('Waiting for DUT to come back up.')
Richard Barnette03a0c132012-11-05 12:40:35 -08001095 if not self.wait_up(timeout=self.BOOT_TIMEOUT):
1096 raise error.AutoservError('DUT failed to reboot installed '
1097 'test image after %d seconds' %
Scott Zawalski62bacae2013-03-05 10:40:32 -05001098 self.BOOT_TIMEOUT)
1099
1100
Dan Shic1b8bdd2015-09-14 23:11:24 -07001101 def _setup_servo(self):
1102 """Try to force to create servo object if it's not set up yet.
1103 """
1104 if self.servo:
1105 return
1106
1107 try:
1108 # Setting servo_args to {} will force it to create the servo_host
1109 # object if possible.
1110 self._servo_host = servo_host.create_servo_host(
1111 dut=self.hostname, servo_args={})
1112 if self._servo_host:
1113 self.servo = self._servo_host.get_servo()
1114 else:
1115 logging.error('Failed to create servo_host object.')
1116 except Exception as e:
1117 logging.error('Failed to create servo object: %s', e)
1118
1119
J. Richard Barnettee4af8b92013-05-01 13:16:12 -07001120 def _servo_repair_reinstall(self):
Scott Zawalski62bacae2013-03-05 10:40:32 -05001121 """Reinstall the DUT utilizing servo and a test image.
1122
1123 Re-install the OS on the DUT by:
1124 1) installing a test image on a USB storage device attached to the Servo
1125 board,
Tom Wai-Hong Tam27af7332015-07-25 06:09:39 +08001126 2) booting that image in recovery mode,
1127 3) resetting the TPM status, and then
1128 4) installing the image with chromeos-install.
Scott Zawalski62bacae2013-03-05 10:40:32 -05001129
Scott Zawalski62bacae2013-03-05 10:40:32 -05001130 @raises AutoservRepairMethodNA if the device does not have servo
1131 support.
1132
1133 """
1134 if not self.servo:
1135 raise error.AutoservRepairMethodNA('Repair Reinstall NA: '
1136 'DUT has no servo support.')
1137
1138 logging.info('Attempting to recovery servo enabled device with '
1139 'servo_repair_reinstall')
1140
J. Richard Barnettee4af8b92013-05-01 13:16:12 -07001141 image_url = self.stage_image_for_servo()
Scott Zawalski62bacae2013-03-05 10:40:32 -05001142 self.servo_install(image_url)
1143
1144
Dan Shi3d7a0e12015-10-12 11:55:45 -07001145 def _firmware_repair(self):
1146 """Reinstall the firmware image using servo.
1147
1148 This repair function attempts to install the stable firmware specified
1149 by the stable firmware version.
1150 Then reset the DUT and try to verify it. If verify fails, it will try to
1151 install the CrOS image using servo.
1152
1153 Note that the firmware repair is only applicable to DUTs in pools listed
1154 in global config CROS/pools_support_firmware_repair.
1155 """
1156 logging.info('Checking if host %s can be repaired with firmware '
1157 'repair.', self.hostname)
1158 pools = server_utils.get_labels_from_afe(self.hostname, 'pool:',
1159 self._AFE)
1160 pools_support_firmware_repair = CONFIG.get_config_value('CROS',
1161 'pools_support_firmware_repair', type=str).split(',')
1162 if (not pools or not pools_support_firmware_repair or
1163 not set(pools).intersection(set(pools_support_firmware_repair))):
1164 logging.info('Host %s is not in pools that support firmware repair.'
1165 ' pools supporting firmware repair are: %s.',
1166 self.hostname, pools_support_firmware_repair)
1167 raise error.AutoservRepairMethodNA(
1168 'Firmware repair is not applicable to host %s.' %
1169 self.hostname)
1170
1171 # To repair a DUT connected to a moblab, try to create a servo object if
1172 # it was failed to be created earlier as there may be a servo_host host
1173 # attribute for this host.
1174 if utils.is_moblab():
1175 self._setup_servo()
1176
1177 if not self.servo:
1178 raise error.AutoservRepairMethodNA('Repair Reinstall NA: '
1179 'DUT has no servo support.')
1180
1181 logging.info('Attempting to recovery servo enabled device with '
1182 'firmware_repair.')
1183 self.firmware_install()
1184
1185 logging.info('Firmware repaired. Check if the DUT can boot. If not, '
1186 'reinstall the CrOS using servo.')
1187 try:
1188 self.servo.reset()
1189 self.verify()
1190 except Exception as e:
1191 logging.warn('Failed to verify DUT, error: %s. Will try to repair '
1192 'the DUT with servo_repair_reinstall.', e)
1193 self._servo_repair_reinstall()
1194
1195
Scott Zawalski62bacae2013-03-05 10:40:32 -05001196 def _servo_repair_power(self):
1197 """Attempt to repair DUT using an attached Servo.
1198
1199 Attempt to power on the DUT via power_long_press.
1200
1201 @raises AutoservRepairMethodNA if the device does not have servo
1202 support.
1203 @raises AutoservRepairFailure if the repair fails for any reason.
1204 """
1205 if not self.servo:
1206 raise error.AutoservRepairMethodNA('Repair Power NA: '
1207 'DUT has no servo support.')
1208
1209 logging.info('Attempting to recover servo enabled device by '
1210 'powering it off and on.')
1211 self.servo.get_power_state_controller().power_off()
1212 self.servo.get_power_state_controller().power_on()
1213 if self.wait_up(self.BOOT_TIMEOUT):
1214 return
1215
1216 raise error.AutoservRepairFailure('DUT did not boot after long_press.')
Richard Barnette03a0c132012-11-05 12:40:35 -08001217
1218
Richard Barnette82c35912012-11-20 10:09:10 -08001219 def _powercycle_to_repair(self):
1220 """Utilize the RPM Infrastructure to bring the host back up.
1221
1222 If the host is not up/repaired after the first powercycle we utilize
1223 auto fallback to the last good install by powercycling and rebooting the
1224 host 6 times.
Scott Zawalski62bacae2013-03-05 10:40:32 -05001225
1226 @raises AutoservRepairMethodNA if the device does not support remote
1227 power.
1228 @raises AutoservRepairFailure if the repair fails for any reason.
1229
Richard Barnette82c35912012-11-20 10:09:10 -08001230 """
Scott Zawalski62bacae2013-03-05 10:40:32 -05001231 if not self.has_power():
1232 raise error.AutoservRepairMethodNA('Device does not support power.')
1233
Richard Barnette82c35912012-11-20 10:09:10 -08001234 logging.info('Attempting repair via RPM powercycle.')
1235 failed_cycles = 0
1236 self.power_cycle()
1237 while not self.wait_up(timeout=self.BOOT_TIMEOUT):
1238 failed_cycles += 1
1239 if failed_cycles >= self._MAX_POWER_CYCLE_ATTEMPTS:
Scott Zawalski62bacae2013-03-05 10:40:32 -05001240 raise error.AutoservRepairFailure(
1241 'Powercycled host %s %d times; device did not come back'
1242 ' online.' % (self.hostname, failed_cycles))
Richard Barnette82c35912012-11-20 10:09:10 -08001243 self.power_cycle()
1244 if failed_cycles == 0:
1245 logging.info('Powercycling was successful first time.')
1246 else:
1247 logging.info('Powercycling was successful after %d failures.',
1248 failed_cycles)
1249
1250
MK Ryu35d661e2014-09-25 17:44:10 -07001251 def _reboot_repair(self):
1252 """SSH to this host and reboot."""
1253 if not self.is_up(self._CHECK_HOST_UP_TIMEOUT_SECS):
1254 raise error.AutoservRepairMethodNA('DUT unreachable for reboot.')
1255 logging.info('Attempting repair via SSH reboot.')
1256 self.reboot(timeout=self.BOOT_TIMEOUT, wait=True)
1257
1258
Prashanth B4d8184f2014-05-05 12:22:02 -07001259 def check_device(self):
1260 """Check if a device is ssh-able, and if so, clean and verify it.
1261
1262 @raise AutoservSSHTimeout: If the ssh ping times out.
1263 @raise AutoservSshPermissionDeniedError: If ssh ping fails due to
1264 permissions.
1265 @raise AutoservSshPingHostError: For other AutoservRunErrors during
1266 ssh_ping.
1267 @raises AutoservError: As appropriate, during cleanup and verify.
1268 """
1269 self.ssh_ping()
1270 self.cleanup()
1271 self.verify()
1272
1273
Dan Shi90466352015-09-22 15:01:05 -07001274 def confirm_servo(self):
1275 """Confirm servo is initialized and verified.
1276
1277 @raise AutoservError: If servo is not initialized and verified.
1278 """
1279 if self._servo_host.required_by_test and self.servo:
1280 return
1281
1282 # Force to re-create the servo object to make sure servo is verified.
1283 logging.debug('Rebuilding the servo object.')
1284 self.servo = None
1285 self._servo_host = None
1286 self._setup_servo()
1287 if not self.servo:
1288 raise error.AutoservError('Failed to create servo object.')
1289
1290
Dan Shid07ee2e2015-09-24 14:49:25 -07001291 def _is_last_provision_failed(self):
1292 """Checks if the last provision job failed.
1293
1294 @return: True if there exists file /var/tmp/provision_failed, which
1295 indicates the last provision job failed.
1296 False if the file does not exist or the dut can't be reached.
1297 """
1298 try:
1299 result = self.run('test -f %s' % PROVISION_FAILED,
1300 ignore_status=True, timeout=5)
1301 return result.exit_status == 0
1302 except (error.AutoservRunError, error.AutoservSSHTimeout):
1303 # Default to False, for repair to try all repair method if the dut
1304 # can't be reached.
1305 return False
1306
1307
J. Richard Barnettec2d99cf2015-11-18 12:46:15 -08001308 def repair(self):
1309 """Attempt to get the DUT to pass `self.verify()`.
Richard Barnette82c35912012-11-20 10:09:10 -08001310
1311 This overrides the base class function for repair; it does
1312 not call back to the parent class, but instead offers a
1313 simplified implementation based on the capabilities in the
1314 Chrome OS test lab.
1315
Fang Deng5d518f42013-08-02 14:04:32 -07001316 It first verifies and repairs servo if it is a DUT in CrOS
Fang Deng03590af2013-10-07 17:34:20 -07001317 lab and a servo is attached.
Fang Deng5d518f42013-08-02 14:04:32 -07001318
Jakob Juelich82b7d1c2014-09-15 16:10:57 -07001319 This escalates in order through the following procedures and verifies
1320 the status using `self.check_device()` after each of them. This is done
1321 until both the repair and the veryfing step succeed.
1322
MK Ryu35d661e2014-09-25 17:44:10 -07001323 Escalation order of repair procedures from less intrusive to
1324 more intrusive repairs:
1325 1. SSH to the DUT and reboot.
Scott Zawalski62bacae2013-03-05 10:40:32 -05001326 2. If there's a servo for the DUT, try to power the DUT off and
1327 on.
MK Ryu35d661e2014-09-25 17:44:10 -07001328 3. If the DUT can be power-cycled via RPM, try to repair
Richard Barnette82c35912012-11-20 10:09:10 -08001329 by power-cycling.
MK Ryu35d661e2014-09-25 17:44:10 -07001330 4. Try to re-install to a known stable image using
1331 auto-update.
1332 5. If there's a servo for the DUT, try to re-install via
1333 the servo.
Richard Barnette82c35912012-11-20 10:09:10 -08001334
1335 As with the parent method, the last operation performed on
Prashanth B4d8184f2014-05-05 12:22:02 -07001336 the DUT must be to call `self.check_device()`; If that call fails the
1337 exception it raises is passed back to the caller.
J. Richard Barnettefde55fc2013-03-15 17:47:01 -07001338
Scott Zawalski62bacae2013-03-05 10:40:32 -05001339 @raises AutoservRepairTotalFailure if the repair process fails to
1340 fix the DUT.
Fang Deng5d518f42013-08-02 14:04:32 -07001341 @raises ServoHostRepairTotalFailure if the repair process fails to
1342 fix the servo host if one is attached to the DUT.
1343 @raises AutoservSshPermissionDeniedError if it is unable
1344 to ssh to the servo host due to permission error.
1345
Richard Barnette82c35912012-11-20 10:09:10 -08001346 """
Jakob Juelich82b7d1c2014-09-15 16:10:57 -07001347 # Caution: Deleting shards relies on repair to always reboot the DUT.
1348
Nicolas Boichate30c7e12015-11-05 11:12:50 +08001349 # To repair a DUT connected to a moblab, try to create a servo object if
1350 # it was failed to be created earlier as there may be a servo_host host
1351 # attribute for this host.
1352 if utils.is_moblab():
1353 self._setup_servo()
1354
Dan Shi4d478522014-02-14 13:46:32 -08001355 if self._servo_host and not self.servo:
Fang Deng03590af2013-10-07 17:34:20 -07001356 try:
J. Richard Barnette4fc59c42015-12-15 16:58:50 -08001357 self._servo_host.repair()
Fang Deng03590af2013-10-07 17:34:20 -07001358 except Exception as e:
Fang Deng03590af2013-10-07 17:34:20 -07001359 logging.error('Could not create a healthy servo: %s', e)
Dan Shi4d478522014-02-14 13:46:32 -08001360 self.servo = self._servo_host.get_servo()
Fang Deng5d518f42013-08-02 14:04:32 -07001361
MK Ryu35d661e2014-09-25 17:44:10 -07001362 self.try_collect_crashlogs()
1363
Scott Zawalski62bacae2013-03-05 10:40:32 -05001364 # TODO(scottz): This should use something similar to label_decorator,
1365 # but needs to be populated in order so DUTs are repaired with the
1366 # least amount of effort.
Dan Shid07ee2e2015-09-24 14:49:25 -07001367 force_powerwash = self._is_last_provision_failed()
1368 if force_powerwash:
1369 logging.info('Last provision failed, try powerwash first.')
1370 autotest_stats.Counter(
1371 'repair_force_powerwash.TOTAL').increment()
1372 repair_funcs = [self._install_repair_with_powerwash,
Dan Shi3d7a0e12015-10-12 11:55:45 -07001373 self._servo_repair_reinstall,
1374 self._firmware_repair]
Dan Shid07ee2e2015-09-24 14:49:25 -07001375 else:
1376 repair_funcs = [self._reboot_repair,
1377 self._servo_repair_power,
1378 self._powercycle_to_repair,
1379 self._install_repair,
1380 self._install_repair_with_powerwash,
Dan Shi3d7a0e12015-10-12 11:55:45 -07001381 self._servo_repair_reinstall,
1382 self._firmware_repair]
Scott Zawalski62bacae2013-03-05 10:40:32 -05001383 errors = []
Simran Basie6130932013-10-01 14:07:52 -07001384 board = self._get_board_from_afe()
Scott Zawalski62bacae2013-03-05 10:40:32 -05001385 for repair_func in repair_funcs:
1386 try:
1387 repair_func()
MK Ryu35d661e2014-09-25 17:44:10 -07001388 self.try_collect_crashlogs()
Prashanth B4d8184f2014-05-05 12:22:02 -07001389 self.check_device()
Gabe Black1e1c41b2015-02-04 23:55:15 -08001390 autotest_stats.Counter(
Simran Basie6130932013-10-01 14:07:52 -07001391 '%s.SUCCEEDED' % repair_func.__name__).increment()
1392 if board:
Gabe Black1e1c41b2015-02-04 23:55:15 -08001393 autotest_stats.Counter(
Dan Shid07ee2e2015-09-24 14:49:25 -07001394 '%s.%s.SUCCEEDED' % (repair_func.__name__,
Simran Basie6130932013-10-01 14:07:52 -07001395 board)).increment()
Dan Shid07ee2e2015-09-24 14:49:25 -07001396 if force_powerwash:
1397 autotest_stats.Counter(
1398 'repair_force_powerwash.SUCCEEDED').increment()
Scott Zawalski62bacae2013-03-05 10:40:32 -05001399 return
Simran Basie6130932013-10-01 14:07:52 -07001400 except error.AutoservRepairMethodNA as e:
Gabe Black1e1c41b2015-02-04 23:55:15 -08001401 autotest_stats.Counter(
Simran Basie6130932013-10-01 14:07:52 -07001402 '%s.RepairNA' % repair_func.__name__).increment()
1403 if board:
Gabe Black1e1c41b2015-02-04 23:55:15 -08001404 autotest_stats.Counter(
Dan Shid07ee2e2015-09-24 14:49:25 -07001405 '%s.%s.RepairNA' % (repair_func.__name__,
1406 board)).increment()
Ilja H. Friedel04be2bd2014-05-07 21:29:59 -07001407 logging.warning('Repair function NA: %s', e)
Simran Basie6130932013-10-01 14:07:52 -07001408 errors.append(str(e))
Scott Zawalski62bacae2013-03-05 10:40:32 -05001409 except Exception as e:
Gabe Black1e1c41b2015-02-04 23:55:15 -08001410 autotest_stats.Counter(
Simran Basie6130932013-10-01 14:07:52 -07001411 '%s.FAILED' % repair_func.__name__).increment()
1412 if board:
Gabe Black1e1c41b2015-02-04 23:55:15 -08001413 autotest_stats.Counter(
Dan Shid07ee2e2015-09-24 14:49:25 -07001414 '%s.%s.FAILED' % (repair_func.__name__,
1415 board)).increment()
Ilja H. Friedel04be2bd2014-05-07 21:29:59 -07001416 logging.warning('Failed to repair device: %s', e)
Scott Zawalski62bacae2013-03-05 10:40:32 -05001417 errors.append(str(e))
Scott Zawalski89c44dd2013-02-26 09:28:02 -05001418
Dan Shid07ee2e2015-09-24 14:49:25 -07001419 if force_powerwash:
1420 autotest_stats.Counter(
1421 'repair_force_powerwash.FAILED').increment()
Gabe Black1e1c41b2015-02-04 23:55:15 -08001422 autotest_stats.Counter('Full_Repair_Failed').increment()
Simran Basie6130932013-10-01 14:07:52 -07001423 if board:
Gabe Black1e1c41b2015-02-04 23:55:15 -08001424 autotest_stats.Counter(
Dan Shid07ee2e2015-09-24 14:49:25 -07001425 'Full_Repair_Failed.%s' % board).increment()
Scott Zawalski62bacae2013-03-05 10:40:32 -05001426 raise error.AutoservRepairTotalFailure(
1427 'All attempts at repairing the device failed:\n%s' %
1428 '\n'.join(errors))
Richard Barnette82c35912012-11-20 10:09:10 -08001429
1430
MK Ryu35d661e2014-09-25 17:44:10 -07001431 def try_collect_crashlogs(self, check_host_up=True):
1432 """
1433 Check if a host is up and logs need to be collected from the host,
1434 if yes, collect them.
1435
1436 @param check_host_up: Flag for checking host is up. Default is True.
1437 """
1438 try:
1439 crash_job = self._need_crash_logs()
1440 if crash_job:
1441 logging.debug('%s: Job %s was crashed', self._CRASHLOGS_PREFIX,
1442 crash_job)
1443 if not check_host_up or self.is_up(
1444 self._CHECK_HOST_UP_TIMEOUT_SECS):
1445 self._collect_crashlogs(crash_job)
1446 logging.debug('%s: Completed collecting logs for the '
1447 'crashed job %s', self._CRASHLOGS_PREFIX,
1448 crash_job)
1449 except Exception as e:
1450 # Exception should not result in repair failure.
1451 # Therefore, suppress all exceptions here.
1452 logging.error('%s: Failed while trying to collect crash-logs: %s',
1453 self._CRASHLOGS_PREFIX, e)
1454
1455
1456 def _need_crash_logs(self):
1457 """Get the value of need_crash_logs attribute of this host.
1458
1459 @return: Value string of need_crash_logs attribute
1460 None if there is no need_crash_logs attribute
1461 """
1462 attrs = self._AFE.get_host_attribute(constants.CRASHLOGS_HOST_ATTRIBUTE,
1463 hostname=self.hostname)
1464 assert len(attrs) < 2
1465 return attrs[0].value if attrs else None
1466
1467
1468 def _collect_crashlogs(self, job_id):
1469 """Grab logs from the host where a job was crashed.
1470
1471 First, check if PRIOR_LOGS_DIR exists in the host.
1472 If yes, collect them.
1473 Otherwise, check if a lab-machine marker (_LAB_MACHINE_FILE) exists
1474 in the host.
1475 If yes, the host was repaired automatically, and we collect normal
1476 system logs.
1477
1478 @param job_id: Id of the job that was crashed.
1479 """
1480 crashlogs_dir = crashcollect.get_crashinfo_dir(self,
1481 constants.CRASHLOGS_DEST_DIR_PREFIX)
1482 flag_prior_logs = False
1483
1484 if self.path_exists(client_constants.PRIOR_LOGS_DIR):
1485 flag_prior_logs = True
1486 self._collect_prior_logs(crashlogs_dir)
1487 elif self.path_exists(self._LAB_MACHINE_FILE):
1488 self._collect_system_logs(crashlogs_dir)
1489 else:
1490 logging.warning('%s: Host was manually re-installed without '
1491 '--lab_preserve_log option. Skip collecting '
1492 'crash-logs.', self._CRASHLOGS_PREFIX)
1493
1494 # We make crash collection be one-time effort.
1495 # _collect_prior_logs() and _collect_system_logs() will not throw
1496 # any exception, and following codes will be executed even when
1497 # those methods fail.
1498 # _collect_crashlogs() is called only when the host is up (refer
1499 # to try_collect_crashlogs()). We assume _collect_prior_logs() and
1500 # _collect_system_logs() fail rarely when the host is up.
1501 # In addition, it is not clear how many times we should try crash
1502 # collection again while not triggering next repair unnecessarily.
1503 # Threfore, we try crash collection one time.
1504
1505 # Create a marker file as soon as log collection is done.
1506 # Leave the job id to this marker for gs_offloader to consume.
1507 marker_file = os.path.join(crashlogs_dir, constants.CRASHLOGS_MARKER)
1508 with open(marker_file, 'a') as f:
1509 f.write('%s\n' % job_id)
1510
1511 # Remove need_crash_logs attribute
1512 logging.debug('%s: Remove attribute need_crash_logs from host %s',
1513 self._CRASHLOGS_PREFIX, self.hostname)
1514 self._AFE.set_host_attribute(constants.CRASHLOGS_HOST_ATTRIBUTE,
1515 None, hostname=self.hostname)
1516
1517 if flag_prior_logs:
1518 logging.debug('%s: Remove %s from host %s', self._CRASHLOGS_PREFIX,
1519 client_constants.PRIOR_LOGS_DIR, self.hostname)
1520 self.run('rm -rf %s; sync' % client_constants.PRIOR_LOGS_DIR)
1521 # Wait for a few seconds to make sure the prior command is
1522 # done deep through storage.
1523 time.sleep(self._SAFE_WAIT_SECS)
1524
1525
1526 def _collect_prior_logs(self, crashlogs_dir):
1527 """Grab prior logs that were stashed before re-installing a host.
1528
1529 @param crashlogs_dir: Directory path where crash-logs are stored.
1530 """
1531 logging.debug('%s: Found %s, collecting them...',
1532 self._CRASHLOGS_PREFIX, client_constants.PRIOR_LOGS_DIR)
1533 try:
1534 self.collect_logs(client_constants.PRIOR_LOGS_DIR,
1535 crashlogs_dir, False)
1536 logging.debug('%s: %s is collected',
1537 self._CRASHLOGS_PREFIX, client_constants.PRIOR_LOGS_DIR)
1538 except Exception as e:
1539 logging.error('%s: Failed to collect %s: %s',
1540 self._CRASHLOGS_PREFIX, client_constants.PRIOR_LOGS_DIR,
1541 e)
1542
1543
1544 def _collect_system_logs(self, crashlogs_dir):
1545 """Grab normal system logs from a host.
1546
1547 @param crashlogs_dir: Directory path where crash-logs are stored.
1548 """
1549 logging.debug('%s: Found %s, collecting system logs...',
1550 self._CRASHLOGS_PREFIX, self._LAB_MACHINE_FILE)
1551 sources = server_utils.parse_simple_config(self._LOGS_TO_COLLECT_FILE)
1552 for src in sources:
1553 try:
1554 if self.path_exists(src):
1555 logging.debug('%s: Collecting %s...',
1556 self._CRASHLOGS_PREFIX, src)
1557 dest = server_utils.concat_path_except_last(
1558 crashlogs_dir, src)
1559 self.collect_logs(src, dest, False)
1560 logging.debug('%s: %s is collected',
1561 self._CRASHLOGS_PREFIX, src)
1562 except Exception as e:
1563 logging.error('%s: Failed to collect %s: %s',
1564 self._CRASHLOGS_PREFIX, src, e)
1565
1566
J. Richard Barnette1d78b012012-05-15 13:56:30 -07001567 def close(self):
Fang Deng0ca40e22013-08-27 17:47:44 -07001568 super(CrosHost, self).close()
J. Richard Barnette1d78b012012-05-15 13:56:30 -07001569
1570
Dan Shi49ca0932014-11-14 11:22:27 -08001571 def get_power_supply_info(self):
1572 """Get the output of power_supply_info.
1573
1574 power_supply_info outputs the info of each power supply, e.g.,
1575 Device: Line Power
1576 online: no
1577 type: Mains
1578 voltage (V): 0
1579 current (A): 0
1580 Device: Battery
1581 state: Discharging
1582 percentage: 95.9276
1583 technology: Li-ion
1584
1585 Above output shows two devices, Line Power and Battery, with details of
1586 each device listed. This function parses the output into a dictionary,
1587 with key being the device name, and value being a dictionary of details
1588 of the device info.
1589
1590 @return: The dictionary of power_supply_info, e.g.,
1591 {'Line Power': {'online': 'yes', 'type': 'main'},
1592 'Battery': {'vendor': 'xyz', 'percentage': '100'}}
Dan Shie9b765d2014-12-29 16:59:49 -08001593 @raise error.AutoservRunError if power_supply_info tool is not found in
1594 the DUT. Caller should handle this error to avoid false failure
1595 on verification.
Dan Shi49ca0932014-11-14 11:22:27 -08001596 """
1597 result = self.run('power_supply_info').stdout.strip()
1598 info = {}
1599 device_name = None
1600 device_info = {}
1601 for line in result.split('\n'):
1602 pair = [v.strip() for v in line.split(':')]
1603 if len(pair) != 2:
1604 continue
1605 if pair[0] == 'Device':
1606 if device_name:
1607 info[device_name] = device_info
1608 device_name = pair[1]
1609 device_info = {}
1610 else:
1611 device_info[pair[0]] = pair[1]
1612 if device_name and not device_name in info:
1613 info[device_name] = device_info
1614 return info
1615
1616
1617 def get_battery_percentage(self):
1618 """Get the battery percentage.
1619
1620 @return: The percentage of battery level, value range from 0-100. Return
1621 None if the battery info cannot be retrieved.
1622 """
1623 try:
1624 info = self.get_power_supply_info()
1625 logging.info(info)
1626 return float(info['Battery']['percentage'])
Dan Shie9b765d2014-12-29 16:59:49 -08001627 except (KeyError, ValueError, error.AutoservRunError):
Dan Shi49ca0932014-11-14 11:22:27 -08001628 return None
1629
1630
1631 def is_ac_connected(self):
1632 """Check if the dut has power adapter connected and charging.
1633
1634 @return: True if power adapter is connected and charging.
1635 """
1636 try:
1637 info = self.get_power_supply_info()
1638 return info['Line Power']['online'] == 'yes'
Dan Shie9b765d2014-12-29 16:59:49 -08001639 except (KeyError, error.AutoservRunError):
1640 return None
Dan Shi49ca0932014-11-14 11:22:27 -08001641
1642
Simran Basi5e6339a2013-03-21 11:34:32 -07001643 def _cleanup_poweron(self):
1644 """Special cleanup method to make sure hosts always get power back."""
1645 afe = frontend_wrappers.RetryingAFE(timeout_min=5, delay_sec=10)
1646 hosts = afe.get_hosts(hostname=self.hostname)
1647 if not hosts or not (self._RPM_OUTLET_CHANGED in
1648 hosts[0].attributes):
1649 return
1650 logging.debug('This host has recently interacted with the RPM'
1651 ' Infrastructure. Ensuring power is on.')
1652 try:
1653 self.power_on()
Dan Shi7dca56e2014-11-11 17:07:56 -08001654 afe.set_host_attribute(self._RPM_OUTLET_CHANGED, None,
1655 hostname=self.hostname)
Simran Basi5e6339a2013-03-21 11:34:32 -07001656 except rpm_client.RemotePowerException:
Simran Basi5e6339a2013-03-21 11:34:32 -07001657 logging.error('Failed to turn Power On for this host after '
1658 'cleanup through the RPM Infrastructure.')
Gabe Blackb72f4fb2015-01-20 16:47:13 -08001659 autotest_es.post(
Dan Shi7dca56e2014-11-11 17:07:56 -08001660 type_str='RPM_poweron_failure',
1661 metadata={'hostname': self.hostname})
Dan Shi49ca0932014-11-14 11:22:27 -08001662
1663 battery_percentage = self.get_battery_percentage()
Dan Shif01ebe22014-12-05 13:10:57 -08001664 if battery_percentage and battery_percentage < 50:
Dan Shi49ca0932014-11-14 11:22:27 -08001665 raise
1666 elif self.is_ac_connected():
1667 logging.info('The device has power adapter connected and '
1668 'charging. No need to try to turn RPM on '
1669 'again.')
1670 afe.set_host_attribute(self._RPM_OUTLET_CHANGED, None,
1671 hostname=self.hostname)
1672 logging.info('Battery level is now at %s%%. The device may '
1673 'still have enough power to run test, so no '
1674 'exception will be raised.', battery_percentage)
1675
Simran Basi5e6339a2013-03-21 11:34:32 -07001676
beepsc87ff602013-07-31 21:53:00 -07001677 def _is_factory_image(self):
1678 """Checks if the image on the DUT is a factory image.
1679
1680 @return: True if the image on the DUT is a factory image.
1681 False otherwise.
1682 """
1683 result = self.run('[ -f /root/.factory_test ]', ignore_status=True)
1684 return result.exit_status == 0
1685
1686
1687 def _restart_ui(self):
J. Richard Barnette84890bd2014-02-21 11:05:47 -08001688 """Restart the Chrome UI.
beepsc87ff602013-07-31 21:53:00 -07001689
1690 @raises: FactoryImageCheckerException for factory images, since
1691 we cannot attempt to restart ui on them.
1692 error.AutoservRunError for any other type of error that
1693 occurs while restarting ui.
1694 """
1695 if self._is_factory_image():
Dan Shi549fb822015-03-24 18:01:11 -07001696 raise FactoryImageCheckerException('Cannot restart ui on factory '
1697 'images')
beepsc87ff602013-07-31 21:53:00 -07001698
J. Richard Barnette84890bd2014-02-21 11:05:47 -08001699 # TODO(jrbarnette): The command to stop/start the ui job
1700 # should live inside cros_ui, too. However that would seem
1701 # to imply interface changes to the existing start()/restart()
1702 # functions, which is a bridge too far (for now).
J. Richard Barnette6069aa12015-06-08 09:10:24 -07001703 prompt = cros_ui.get_chrome_session_ident(self)
J. Richard Barnette84890bd2014-02-21 11:05:47 -08001704 self.run('stop ui; start ui')
1705 cros_ui.wait_for_chrome_ready(prompt, self)
beepsc87ff602013-07-31 21:53:00 -07001706
1707
Dan Shi549fb822015-03-24 18:01:11 -07001708 def get_release_version(self):
1709 """Get the value of attribute CHROMEOS_RELEASE_VERSION from lsb-release.
1710
1711 @returns The version string in lsb-release, under attribute
1712 CHROMEOS_RELEASE_VERSION.
1713 """
1714 lsb_release_content = self.run(
1715 'cat "%s"' % client_constants.LSB_RELEASE).stdout.strip()
1716 return lsbrelease_utils.get_chromeos_release_version(
1717 lsb_release_content=lsb_release_content)
1718
1719
1720 def verify_cros_version_label(self):
1721 """ Make sure host's cros-version label match the actual image in dut.
1722
1723 Remove any cros-version: label that doesn't match that installed in
1724 the dut.
1725
1726 @param raise_error: Set to True to raise exception if any mismatch found
1727
1728 @raise error.AutoservError: If any mismatch between cros-version label
1729 and the build installed in dut is found.
1730 """
1731 labels = self._AFE.get_labels(
1732 name__startswith=ds_constants.VERSION_PREFIX,
1733 host__hostname=self.hostname)
1734 mismatch_found = False
1735 if labels:
1736 # Get CHROMEOS_RELEASE_VERSION from lsb-release, e.g., 6908.0.0.
1737 # Note that it's different from cros-version label, which has
1738 # builder and branch info, e.g.,
1739 # cros-version:peppy-release/R43-6908.0.0
1740 release_version = self.get_release_version()
1741 host_list = [self.hostname]
1742 for label in labels:
1743 # Remove any cros-version label that does not match
1744 # release_version.
1745 build_version = label.name[len(ds_constants.VERSION_PREFIX):]
1746 if not utils.version_match(build_version, release_version):
1747 logging.warn('cros-version label "%s" does not match '
1748 'release version %s. Removing the label.',
1749 label.name, release_version)
1750 label.remove_hosts(hosts=host_list)
1751 mismatch_found = True
1752 if mismatch_found:
Dan Shi1057bae2015-03-30 11:35:09 -07001753 autotest_es.post(use_http=True,
1754 type_str='cros_version_label_mismatch',
1755 metadata={'hostname': self.hostname})
Dan Shi549fb822015-03-24 18:01:11 -07001756 raise error.AutoservError('The host has wrong cros-version label.')
1757
1758
Darren Krahn0bd18e82015-10-28 23:30:46 +00001759 def verify_tpm_status(self):
1760 """ Verify the host's TPM is in a good state.
1761
1762 @raise error.AutoservError: If state is not good.
1763 """
1764 # This cryptohome command emits status information in JSON format. It
1765 # looks something like this:
1766 # {
1767 # "installattrs": {
1768 # "first_install": false,
1769 # "initialized": true,
1770 # "invalid": false,
1771 # "lockbox_index": 536870916,
1772 # "lockbox_nvram_version": 2,
1773 # "secure": true,
1774 # "size": 0,
1775 # "version": 1
1776 # },
1777 # "mounts": [ {
1778 # "enterprise": false,
1779 # "keysets": [ {
1780 # "current": true,
1781 # "index": 0,
1782 # "last_activity": 1330111359,
1783 # "ok": true,
1784 # "scrypt": true,
1785 # "tpm": false
1786 # } ],
1787 # "mounted": true,
1788 # "owner": "dbb3dd34edb181245130e136be51fa08478d3909"
1789 # } ],
1790 # "tpm": {
1791 # "being_owned": false,
1792 # "can_connect": true,
1793 # "can_decrypt": false,
1794 # "can_encrypt": false,
1795 # "can_load_srk": true,
1796 # "can_load_srk_pubkey": true,
1797 # "enabled": true,
1798 # "has_context": true,
1799 # "has_cryptohome_key": false,
1800 # "has_key_handle": false,
1801 # "last_error": 0,
1802 # "owned": true
1803 # }
1804 # }
1805 output = self.run('cryptohome --action=status').stdout.strip()
1806 try:
1807 status = json.loads(output)
1808 except ValueError:
1809 logging.error('TPM_VERIFY: Cryptohome did not return valid status.')
1810 return
1811 try:
1812 tpm = status['tpm']
1813 if (not tpm['enabled'] or not tpm['can_connect'] or
1814 (tpm['owned'] and not tpm['can_load_srk']) or
1815 (tpm['can_load_srk'] and not tpm['can_load_srk_pubkey'])):
1816 logging.error('TPM_VERIFY: The host TPM is in a bad state.')
1817 raise error.AutoservError('The host TPM is in a bad state.')
1818 else:
1819 logging.debug('TPM_VERIFY: The host TPM is in a good state.')
1820 except KeyError:
1821 logging.error('TPM_VERIFY: Cryptohome did not return valid status.')
1822
1823
beepsc87ff602013-07-31 21:53:00 -07001824 def cleanup(self):
MK Ryu35d661e2014-09-25 17:44:10 -07001825 self.run('rm -f %s' % client_constants.CLEANUP_LOGS_PAUSED_FILE)
Scott Zawalskiddbc31e2012-11-15 11:29:01 -05001826 try:
beepsc87ff602013-07-31 21:53:00 -07001827 self._restart_ui()
1828 except (error.AutotestRunError, error.AutoservRunError,
1829 FactoryImageCheckerException):
Ilja H. Friedel04be2bd2014-05-07 21:29:59 -07001830 logging.warning('Unable to restart ui, rebooting device.')
Scott Zawalskiddbc31e2012-11-15 11:29:01 -05001831 # Since restarting the UI fails fall back to normal Autotest
1832 # cleanup routines, i.e. reboot the machine.
Fang Deng0ca40e22013-08-27 17:47:44 -07001833 super(CrosHost, self).cleanup()
Simran Basi5e6339a2013-03-21 11:34:32 -07001834 # Check if the rpm outlet was manipulated.
Simran Basid5e5e272012-09-24 15:23:59 -07001835 if self.has_power():
Simran Basi5e6339a2013-03-21 11:34:32 -07001836 self._cleanup_poweron()
Dan Shi549fb822015-03-24 18:01:11 -07001837 self.verify_cros_version_label()
J. Richard Barnette45e93de2012-04-11 17:24:15 -07001838
1839
Yu-Ju Honga2be94a2012-07-31 09:48:52 -07001840 def reboot(self, **dargs):
1841 """
1842 This function reboots the site host. The more generic
1843 RemoteHost.reboot() performs sync and sleeps for 5
1844 seconds. This is not necessary for Chrome OS devices as the
1845 sync should be finished in a short time during the reboot
1846 command.
1847 """
Tom Wai-Hong Tamf5cd1d42012-08-13 12:04:08 +08001848 if 'reboot_cmd' not in dargs:
Doug Anderson7d5aeb22014-02-27 15:12:17 -08001849 reboot_timeout = dargs.get('reboot_timeout', 10)
J. Richard Barnette9af19632015-09-25 12:18:03 -07001850 dargs['reboot_cmd'] = ('sleep 1; '
1851 'reboot & sleep %d; '
1852 'reboot -f' % reboot_timeout)
Yu-Ju Honga2be94a2012-07-31 09:48:52 -07001853 # Enable fastsync to avoid running extra sync commands before reboot.
Tom Wai-Hong Tamf5cd1d42012-08-13 12:04:08 +08001854 if 'fastsync' not in dargs:
1855 dargs['fastsync'] = True
Michael Liangda8c60a2014-06-03 13:24:51 -07001856
Charlie Mooneya8e6dab2014-05-29 14:37:55 -07001857 # For purposes of logging reboot times:
1858 # Get the board name i.e. 'daisy_spring'
Michael Liangca4f5a62014-07-10 15:45:13 -07001859 board_fullname = self.get_board()
1860
1861 # Strip the prefix and add it to dargs.
1862 dargs['board'] = board_fullname[board_fullname.find(':')+1:]
Fang Deng0ca40e22013-08-27 17:47:44 -07001863 super(CrosHost, self).reboot(**dargs)
Yu-Ju Honga2be94a2012-07-31 09:48:52 -07001864
1865
Gwendal Grignou7a61d2f2014-05-23 11:05:51 -07001866 def suspend(self, **dargs):
1867 """
1868 This function suspends the site host.
1869 """
1870 suspend_time = dargs.get('suspend_time', 60)
1871 dargs['timeout'] = suspend_time
1872 if 'suspend_cmd' not in dargs:
J. Richard Barnette9af19632015-09-25 12:18:03 -07001873 dargs['suspend_cmd'] = ' && '.join([
1874 'echo 0 > /sys/class/rtc/rtc0/wakealarm',
Gwendal Grignou7a61d2f2014-05-23 11:05:51 -07001875 'echo +%d > /sys/class/rtc/rtc0/wakealarm' % suspend_time,
J. Richard Barnette9af19632015-09-25 12:18:03 -07001876 'powerd_dbus_suspend --delay=0'])
Gwendal Grignou7a61d2f2014-05-23 11:05:51 -07001877 super(CrosHost, self).suspend(**dargs)
1878
1879
Simran Basiec564392014-08-25 16:48:09 -07001880 def upstart_status(self, service_name):
1881 """Check the status of an upstart init script.
1882
1883 @param service_name: Service to look up.
1884
1885 @returns True if the service is running, False otherwise.
1886 """
1887 return self.run('status %s | grep start/running' %
1888 service_name).stdout.strip() != ''
1889
1890
J. Richard Barnette45e93de2012-04-11 17:24:15 -07001891 def verify_software(self):
Richard Barnetteb2bc13c2013-01-08 17:32:51 -08001892 """Verify working software on a Chrome OS system.
J. Richard Barnette45e93de2012-04-11 17:24:15 -07001893
Richard Barnetteb2bc13c2013-01-08 17:32:51 -08001894 Tests for the following conditions:
1895 1. All conditions tested by the parent version of this
1896 function.
1897 2. Sufficient space in /mnt/stateful_partition.
Fang Deng6b05f5b2013-03-20 13:42:11 -07001898 3. Sufficient space in /mnt/stateful_partition/encrypted.
1899 4. update_engine answers a simple status request over DBus.
J. Richard Barnette45e93de2012-04-11 17:24:15 -07001900
J. Richard Barnette45e93de2012-04-11 17:24:15 -07001901 """
MK Ryu35d661e2014-09-25 17:44:10 -07001902 # Check if a job was crashed on this host.
1903 # If yes, avoid verification until crash-logs are collected.
1904 if self._need_crash_logs():
1905 raise error.AutoservCrashLogCollectRequired(
1906 'Need to collect crash-logs before verification')
1907
Fang Deng0ca40e22013-08-27 17:47:44 -07001908 super(CrosHost, self).verify_software()
Dan Shib8540a52015-07-16 14:18:23 -07001909 default_kilo_inodes_required = CONFIG.get_config_value(
1910 'SERVER', 'kilo_inodes_required', type=int, default=100)
1911 board = self.get_board().replace(ds_constants.BOARD_PREFIX, '')
1912 kilo_inodes_required = CONFIG.get_config_value(
1913 'SERVER', 'kilo_inodes_required_%s' % board,
1914 type=int, default=default_kilo_inodes_required)
1915 self.check_inodes('/mnt/stateful_partition', kilo_inodes_required)
J. Richard Barnette45e93de2012-04-11 17:24:15 -07001916 self.check_diskspace(
1917 '/mnt/stateful_partition',
Dan Shib8540a52015-07-16 14:18:23 -07001918 CONFIG.get_config_value(
Fang Deng6b05f5b2013-03-20 13:42:11 -07001919 'SERVER', 'gb_diskspace_required', type=float,
1920 default=20.0))
Gaurav Shahe448af82014-06-19 15:18:59 -07001921 encrypted_stateful_path = '/mnt/stateful_partition/encrypted'
1922 # Not all targets build with encrypted stateful support.
1923 if self.path_exists(encrypted_stateful_path):
1924 self.check_diskspace(
1925 encrypted_stateful_path,
Dan Shib8540a52015-07-16 14:18:23 -07001926 CONFIG.get_config_value(
Gaurav Shahe448af82014-06-19 15:18:59 -07001927 'SERVER', 'gb_encrypted_diskspace_required', type=float,
1928 default=0.1))
beepsc87ff602013-07-31 21:53:00 -07001929
Simran Basiec564392014-08-25 16:48:09 -07001930 if not self.upstart_status('system-services'):
Prashanth B5d0a0512014-04-25 12:26:08 -07001931 raise error.AutoservError('Chrome failed to reach login. '
1932 'System services not running.')
1933
beepsc87ff602013-07-31 21:53:00 -07001934 # Factory images don't run update engine,
1935 # goofy controls dbus on these DUTs.
1936 if not self._is_factory_image():
1937 self.run('update_engine_client --status')
Scott Zawalskifbca4a92013-03-04 15:56:42 -05001938 # Makes sure python is present, loads and can use built in functions.
1939 # We have seen cases where importing cPickle fails with undefined
1940 # symbols in cPickle.so.
1941 self.run('python -c "import cPickle"')
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001942
Dan Shi549fb822015-03-24 18:01:11 -07001943 self.verify_cros_version_label()
1944
Darren Krahn0bd18e82015-10-28 23:30:46 +00001945 self.verify_tpm_status()
1946
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001947
Dan Shi49ca0932014-11-14 11:22:27 -08001948 def verify_hardware(self):
1949 """Verify hardware system of a Chrome OS system.
1950
1951 Check following hardware conditions:
1952 1. Battery level.
1953 2. Is power adapter connected.
1954 """
1955 logging.info('Battery percentage: %s', self.get_battery_percentage())
Dan Shie9b765d2014-12-29 16:59:49 -08001956 if self.is_ac_connected() is None:
1957 logging.info('Can not determine if the device has power adapter '
1958 'connected.')
1959 else:
1960 logging.info('Device %s power adapter connected and charging.',
1961 'has' if self.is_ac_connected() else 'does not have')
Dan Shi49ca0932014-11-14 11:22:27 -08001962
1963
Fang Deng96667ca2013-08-01 17:46:18 -07001964 def make_ssh_command(self, user='root', port=22, opts='', hosts_file=None,
1965 connect_timeout=None, alive_interval=None):
1966 """Override default make_ssh_command to use options tuned for Chrome OS.
1967
1968 Tuning changes:
1969 - ConnectTimeout=30; maximum of 30 seconds allowed for an SSH
1970 connection failure. Consistency with remote_access.sh.
1971
Samuel Tan2ce155b2015-06-23 18:24:38 -07001972 - ServerAliveInterval=900; which causes SSH to ping connection every
1973 900 seconds. In conjunction with ServerAliveCountMax ensures
1974 that if the connection dies, Autotest will bail out.
Fang Deng96667ca2013-08-01 17:46:18 -07001975 Originally tried 60 secs, but saw frequent job ABORTS where
Samuel Tan2ce155b2015-06-23 18:24:38 -07001976 the test completed successfully. Later increased from 180 seconds to
1977 900 seconds to account for tests where the DUT is suspended for
1978 longer periods of time.
Fang Deng96667ca2013-08-01 17:46:18 -07001979
1980 - ServerAliveCountMax=3; consistency with remote_access.sh.
1981
1982 - ConnectAttempts=4; reduce flakiness in connection errors;
1983 consistency with remote_access.sh.
1984
1985 - UserKnownHostsFile=/dev/null; we don't care about the keys.
1986 Host keys change with every new installation, don't waste
1987 memory/space saving them.
1988
1989 - SSH protocol forced to 2; needed for ServerAliveInterval.
1990
1991 @param user User name to use for the ssh connection.
1992 @param port Port on the target host to use for ssh connection.
1993 @param opts Additional options to the ssh command.
1994 @param hosts_file Ignored.
1995 @param connect_timeout Ignored.
1996 @param alive_interval Ignored.
1997 """
Aviv Keshetc5947fa2013-09-04 14:06:29 -07001998 base_command = ('/usr/bin/ssh -a -x %s %s %s'
1999 ' -o StrictHostKeyChecking=no'
Fang Deng96667ca2013-08-01 17:46:18 -07002000 ' -o UserKnownHostsFile=/dev/null -o BatchMode=yes'
Samuel Tan2ce155b2015-06-23 18:24:38 -07002001 ' -o ConnectTimeout=30 -o ServerAliveInterval=900'
Fang Deng96667ca2013-08-01 17:46:18 -07002002 ' -o ServerAliveCountMax=3 -o ConnectionAttempts=4'
2003 ' -o Protocol=2 -l %s -p %d')
Aviv Keshetc5947fa2013-09-04 14:06:29 -07002004 return base_command % (self._ssh_verbosity_flag, self._ssh_options,
2005 opts, user, port)
Jason Abeleb6f924f2013-11-13 16:01:54 -08002006 def syslog(self, message, tag='autotest'):
2007 """Logs a message to syslog on host.
2008
2009 @param message String message to log into syslog
2010 @param tag String tag prefix for syslog
2011
2012 """
2013 self.run('logger -t "%s" "%s"' % (tag, message))
2014
2015
J. Richard Barnetteb6de7e32013-02-14 13:28:04 -08002016 def _ping_check_status(self, status):
2017 """Ping the host once, and return whether it has a given status.
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002018
J. Richard Barnetteb6de7e32013-02-14 13:28:04 -08002019 @param status Check the ping status against this value.
2020 @return True iff `status` and the result of ping are the same
2021 (i.e. both True or both False).
2022
2023 """
2024 ping_val = utils.ping(self.hostname, tries=1, deadline=1)
2025 return not (status ^ (ping_val == 0))
2026
2027 def _ping_wait_for_status(self, status, timeout):
2028 """Wait for the host to have a given status (UP or DOWN).
2029
2030 Status is checked by polling. Polling will not last longer
2031 than the number of seconds in `timeout`. The polling
2032 interval will be long enough that only approximately
2033 _PING_WAIT_COUNT polling cycles will be executed, subject
2034 to a maximum interval of about one minute.
2035
2036 @param status Waiting will stop immediately if `ping` of the
2037 host returns this status.
2038 @param timeout Poll for at most this many seconds.
2039 @return True iff the host status from `ping` matched the
2040 requested status at the time of return.
2041
2042 """
2043 # _ping_check_status() takes about 1 second, hence the
2044 # "- 1" in the formula below.
2045 poll_interval = min(int(timeout / self._PING_WAIT_COUNT), 60) - 1
2046 end_time = time.time() + timeout
2047 while time.time() <= end_time:
2048 if self._ping_check_status(status):
2049 return True
2050 if poll_interval > 0:
2051 time.sleep(poll_interval)
2052
2053 # The last thing we did was sleep(poll_interval), so it may
2054 # have been too long since the last `ping`. Check one more
2055 # time, just to be sure.
2056 return self._ping_check_status(status)
2057
2058 def ping_wait_up(self, timeout):
2059 """Wait for the host to respond to `ping`.
2060
2061 N.B. This method is not a reliable substitute for
2062 `wait_up()`, because a host that responds to ping will not
2063 necessarily respond to ssh. This method should only be used
2064 if the target DUT can be considered functional even if it
2065 can't be reached via ssh.
2066
2067 @param timeout Minimum time to allow before declaring the
2068 host to be non-responsive.
2069 @return True iff the host answered to ping before the timeout.
2070
2071 """
2072 return self._ping_wait_for_status(self._PING_STATUS_UP, timeout)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002073
Andrew Bresticker678c0c72013-01-22 10:44:09 -08002074 def ping_wait_down(self, timeout):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002075 """Wait until the host no longer responds to `ping`.
2076
J. Richard Barnetteb6de7e32013-02-14 13:28:04 -08002077 This function can be used as a slightly faster version of
2078 `wait_down()`, by avoiding potentially long ssh timeouts.
2079
2080 @param timeout Minimum time to allow for the host to become
2081 non-responsive.
2082 @return True iff the host quit answering ping before the
2083 timeout.
2084
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002085 """
J. Richard Barnetteb6de7e32013-02-14 13:28:04 -08002086 return self._ping_wait_for_status(self._PING_STATUS_DOWN, timeout)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002087
Tom Wai-Hong Tamfced4f62014-04-17 10:56:30 +08002088 def test_wait_for_sleep(self, sleep_timeout=None):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002089 """Wait for the client to enter low-power sleep mode.
2090
2091 The test for "is asleep" can't distinguish a system that is
2092 powered off; to confirm that the unit was asleep, it is
2093 necessary to force resume, and then call
2094 `test_wait_for_resume()`.
2095
2096 This function is expected to be called from a test as part
2097 of a sequence like the following:
2098
2099 ~~~~~~~~
2100 boot_id = host.get_boot_id()
2101 # trigger sleep on the host
2102 host.test_wait_for_sleep()
2103 # trigger resume on the host
2104 host.test_wait_for_resume(boot_id)
2105 ~~~~~~~~
2106
Tom Wai-Hong Tamfced4f62014-04-17 10:56:30 +08002107 @param sleep_timeout time limit in seconds to allow the host sleep.
2108
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002109 @exception TestFail The host did not go to sleep within
2110 the allowed time.
2111 """
Tom Wai-Hong Tamfced4f62014-04-17 10:56:30 +08002112 if sleep_timeout is None:
2113 sleep_timeout = self.SLEEP_TIMEOUT
2114
2115 if not self.ping_wait_down(timeout=sleep_timeout):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002116 raise error.TestFail(
Tom Wai-Hong Tamfced4f62014-04-17 10:56:30 +08002117 'client failed to sleep after %d seconds' % sleep_timeout)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002118
2119
Tom Wai-Hong Tamfced4f62014-04-17 10:56:30 +08002120 def test_wait_for_resume(self, old_boot_id, resume_timeout=None):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002121 """Wait for the client to resume from low-power sleep mode.
2122
2123 The `old_boot_id` parameter should be the value from
2124 `get_boot_id()` obtained prior to entering sleep mode. A
2125 `TestFail` exception is raised if the boot id changes.
2126
2127 See @ref test_wait_for_sleep for more on this function's
2128 usage.
2129
J. Richard Barnette7214e0b2013-02-06 15:20:49 -08002130 @param old_boot_id A boot id value obtained before the
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002131 target host went to sleep.
Tom Wai-Hong Tamfced4f62014-04-17 10:56:30 +08002132 @param resume_timeout time limit in seconds to allow the host up.
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002133
2134 @exception TestFail The host did not respond within the
2135 allowed time.
2136 @exception TestFail The host responded, but the boot id test
2137 indicated a reboot rather than a sleep
2138 cycle.
2139 """
Tom Wai-Hong Tamfced4f62014-04-17 10:56:30 +08002140 if resume_timeout is None:
2141 resume_timeout = self.RESUME_TIMEOUT
2142
2143 if not self.wait_up(timeout=resume_timeout):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002144 raise error.TestFail(
2145 'client failed to resume from sleep after %d seconds' %
Tom Wai-Hong Tamfced4f62014-04-17 10:56:30 +08002146 resume_timeout)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002147 else:
2148 new_boot_id = self.get_boot_id()
2149 if new_boot_id != old_boot_id:
Tom Wai-Hong Tam01792682015-01-06 08:00:46 +08002150 logging.error('client rebooted (old boot %s, new boot %s)',
2151 old_boot_id, new_boot_id)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002152 raise error.TestFail(
Tom Wai-Hong Tam01792682015-01-06 08:00:46 +08002153 'client rebooted, but sleep was expected')
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002154
2155
Tom Wai-Hong Tamfe005c22014-12-03 09:25:44 +08002156 def test_wait_for_shutdown(self, shutdown_timeout=None):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002157 """Wait for the client to shut down.
2158
2159 The test for "has shut down" can't distinguish a system that
2160 is merely asleep; to confirm that the unit was down, it is
2161 necessary to force boot, and then call test_wait_for_boot().
2162
2163 This function is expected to be called from a test as part
2164 of a sequence like the following:
2165
2166 ~~~~~~~~
2167 boot_id = host.get_boot_id()
2168 # trigger shutdown on the host
2169 host.test_wait_for_shutdown()
2170 # trigger boot on the host
2171 host.test_wait_for_boot(boot_id)
2172 ~~~~~~~~
2173
Tom Wai-Hong Tamfe005c22014-12-03 09:25:44 +08002174 @param shutdown_timeout time limit in seconds to allow the host down.
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002175 @exception TestFail The host did not shut down within the
2176 allowed time.
2177 """
Tom Wai-Hong Tamfe005c22014-12-03 09:25:44 +08002178 if shutdown_timeout is None:
2179 shutdown_timeout = self.SHUTDOWN_TIMEOUT
2180
2181 if not self.ping_wait_down(timeout=shutdown_timeout):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002182 raise error.TestFail(
2183 'client failed to shut down after %d seconds' %
Tom Wai-Hong Tamfe005c22014-12-03 09:25:44 +08002184 shutdown_timeout)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002185
2186
2187 def test_wait_for_boot(self, old_boot_id=None):
2188 """Wait for the client to boot from cold power.
2189
2190 The `old_boot_id` parameter should be the value from
2191 `get_boot_id()` obtained prior to shutting down. A
2192 `TestFail` exception is raised if the boot id does not
2193 change. The boot id test is omitted if `old_boot_id` is not
2194 specified.
2195
2196 See @ref test_wait_for_shutdown for more on this function's
2197 usage.
2198
J. Richard Barnette7214e0b2013-02-06 15:20:49 -08002199 @param old_boot_id A boot id value obtained before the
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002200 shut down.
2201
2202 @exception TestFail The host did not respond within the
2203 allowed time.
2204 @exception TestFail The host responded, but the boot id test
2205 indicated that there was no reboot.
2206 """
J. Richard Barnetteeb69d722012-06-18 17:29:44 -07002207 if not self.wait_up(timeout=self.REBOOT_TIMEOUT):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002208 raise error.TestFail(
2209 'client failed to reboot after %d seconds' %
J. Richard Barnetteeb69d722012-06-18 17:29:44 -07002210 self.REBOOT_TIMEOUT)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002211 elif old_boot_id:
2212 if self.get_boot_id() == old_boot_id:
Tom Wai-Hong Tam01792682015-01-06 08:00:46 +08002213 logging.error('client not rebooted (boot %s)',
2214 old_boot_id)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07002215 raise error.TestFail(
Tom Wai-Hong Tam01792682015-01-06 08:00:46 +08002216 'client is back up, but did not reboot')
Simran Basid5e5e272012-09-24 15:23:59 -07002217
2218
2219 @staticmethod
2220 def check_for_rpm_support(hostname):
2221 """For a given hostname, return whether or not it is powered by an RPM.
2222
Simran Basi1df55112013-09-06 11:25:09 -07002223 @param hostname: hostname to check for rpm support.
2224
Simran Basid5e5e272012-09-24 15:23:59 -07002225 @return None if this host does not follows the defined naming format
2226 for RPM powered DUT's in the lab. If it does follow the format,
2227 it returns a regular expression MatchObject instead.
2228 """
Fang Dengbaff9082015-01-06 13:46:15 -08002229 return re.match(CrosHost._RPM_HOSTNAME_REGEX, hostname)
Simran Basid5e5e272012-09-24 15:23:59 -07002230
2231
2232 def has_power(self):
2233 """For this host, return whether or not it is powered by an RPM.
2234
2235 @return True if this host is in the CROS lab and follows the defined
2236 naming format.
2237 """
Fang Deng0ca40e22013-08-27 17:47:44 -07002238 return CrosHost.check_for_rpm_support(self.hostname)
Simran Basid5e5e272012-09-24 15:23:59 -07002239
2240
Ismail Noorbasha07fdb612013-02-14 14:13:31 -08002241 def _set_power(self, state, power_method):
2242 """Sets the power to the host via RPM, Servo or manual.
2243
2244 @param state Specifies which power state to set to DUT
2245 @param power_method Specifies which method of power control to
2246 use. By default "RPM" will be used. Valid values
2247 are the strings "RPM", "manual", "servoj10".
2248
2249 """
2250 ACCEPTABLE_STATES = ['ON', 'OFF']
2251
2252 if state.upper() not in ACCEPTABLE_STATES:
2253 raise error.TestError('State must be one of: %s.'
2254 % (ACCEPTABLE_STATES,))
2255
2256 if power_method == self.POWER_CONTROL_SERVO:
2257 logging.info('Setting servo port J10 to %s', state)
2258 self.servo.set('prtctl3_pwren', state.lower())
2259 time.sleep(self._USB_POWER_TIMEOUT)
2260 elif power_method == self.POWER_CONTROL_MANUAL:
2261 logging.info('You have %d seconds to set the AC power to %s.',
2262 self._POWER_CYCLE_TIMEOUT, state)
2263 time.sleep(self._POWER_CYCLE_TIMEOUT)
2264 else:
2265 if not self.has_power():
2266 raise error.TestFail('DUT does not have RPM connected.')
Simran Basi5e6339a2013-03-21 11:34:32 -07002267 afe = frontend_wrappers.RetryingAFE(timeout_min=5, delay_sec=10)
2268 afe.set_host_attribute(self._RPM_OUTLET_CHANGED, True,
2269 hostname=self.hostname)
Simran Basi1df55112013-09-06 11:25:09 -07002270 rpm_client.set_power(self.hostname, state.upper(), timeout_mins=5)
Simran Basid5e5e272012-09-24 15:23:59 -07002271
2272
Ismail Noorbasha07fdb612013-02-14 14:13:31 -08002273 def power_off(self, power_method=POWER_CONTROL_RPM):
2274 """Turn off power to this host via RPM, Servo or manual.
2275
2276 @param power_method Specifies which method of power control to
2277 use. By default "RPM" will be used. Valid values
2278 are the strings "RPM", "manual", "servoj10".
2279
2280 """
2281 self._set_power('OFF', power_method)
Simran Basid5e5e272012-09-24 15:23:59 -07002282
2283
Ismail Noorbasha07fdb612013-02-14 14:13:31 -08002284 def power_on(self, power_method=POWER_CONTROL_RPM):
2285 """Turn on power to this host via RPM, Servo or manual.
2286
2287 @param power_method Specifies which method of power control to
2288 use. By default "RPM" will be used. Valid values
2289 are the strings "RPM", "manual", "servoj10".
2290
2291 """
2292 self._set_power('ON', power_method)
2293
2294
2295 def power_cycle(self, power_method=POWER_CONTROL_RPM):
2296 """Cycle power to this host by turning it OFF, then ON.
2297
2298 @param power_method Specifies which method of power control to
2299 use. By default "RPM" will be used. Valid values
2300 are the strings "RPM", "manual", "servoj10".
2301
2302 """
2303 if power_method in (self.POWER_CONTROL_SERVO,
2304 self.POWER_CONTROL_MANUAL):
2305 self.power_off(power_method=power_method)
2306 time.sleep(self._POWER_CYCLE_TIMEOUT)
2307 self.power_on(power_method=power_method)
2308 else:
2309 rpm_client.set_power(self.hostname, 'CYCLE')
Simran Basic6f1f7a2012-10-16 10:47:46 -07002310
2311
2312 def get_platform(self):
2313 """Determine the correct platform label for this host.
2314
2315 @returns a string representing this host's platform.
2316 """
2317 crossystem = utils.Crossystem(self)
2318 crossystem.init()
2319 # Extract fwid value and use the leading part as the platform id.
2320 # fwid generally follow the format of {platform}.{firmware version}
2321 # Example: Alex.X.YYY.Z or Google_Alex.X.YYY.Z
2322 platform = crossystem.fwid().split('.')[0].lower()
2323 # Newer platforms start with 'Google_' while the older ones do not.
2324 return platform.replace('google_', '')
2325
2326
Hung-ying Tyanb1328032014-04-01 14:18:54 +08002327 def get_architecture(self):
2328 """Determine the correct architecture label for this host.
2329
2330 @returns a string representing this host's architecture.
2331 """
2332 crossystem = utils.Crossystem(self)
2333 crossystem.init()
2334 return crossystem.arch()
2335
2336
Luis Lozano40b7d0d2014-01-17 15:12:06 -08002337 def get_chrome_version(self):
2338 """Gets the Chrome version number and milestone as strings.
2339
2340 Invokes "chrome --version" to get the version number and milestone.
2341
2342 @return A tuple (chrome_ver, milestone) where "chrome_ver" is the
2343 current Chrome version number as a string (in the form "W.X.Y.Z")
2344 and "milestone" is the first component of the version number
2345 (the "W" from "W.X.Y.Z"). If the version number cannot be parsed
2346 in the "W.X.Y.Z" format, the "chrome_ver" will be the full output
2347 of "chrome --version" and the milestone will be the empty string.
2348
2349 """
MK Ryu35d661e2014-09-25 17:44:10 -07002350 version_string = self.run(client_constants.CHROME_VERSION_COMMAND).stdout
Luis Lozano40b7d0d2014-01-17 15:12:06 -08002351 return utils.parse_chrome_version(version_string)
2352
Aviv Keshet74c89a92013-02-04 15:18:30 -08002353 @label_decorator()
Simran Basic6f1f7a2012-10-16 10:47:46 -07002354 def get_board(self):
2355 """Determine the correct board label for this host.
2356
2357 @returns a string representing this host's board.
2358 """
2359 release_info = utils.parse_cmd_output('cat /etc/lsb-release',
2360 run_method=self.run)
2361 board = release_info['CHROMEOS_RELEASE_BOARD']
2362 # Devices in the lab generally have the correct board name but our own
2363 # development devices have {board_name}-signed-{key_type}. The board
2364 # name may also begin with 'x86-' which we need to keep.
Simran Basi833814b2013-01-29 13:13:43 -08002365 board_format_string = ds_constants.BOARD_PREFIX + '%s'
Simran Basic6f1f7a2012-10-16 10:47:46 -07002366 if 'x86' not in board:
Simran Basi833814b2013-01-29 13:13:43 -08002367 return board_format_string % board.split('-')[0]
2368 return board_format_string % '-'.join(board.split('-')[0:2])
Simran Basic6f1f7a2012-10-16 10:47:46 -07002369
2370
Aviv Keshet74c89a92013-02-04 15:18:30 -08002371 @label_decorator('lightsensor')
Simran Basic6f1f7a2012-10-16 10:47:46 -07002372 def has_lightsensor(self):
2373 """Determine the correct board label for this host.
2374
2375 @returns the string 'lightsensor' if this host has a lightsensor or
2376 None if it does not.
2377 """
2378 search_cmd = "find -L %s -maxdepth 4 | egrep '%s'" % (
Richard Barnette82c35912012-11-20 10:09:10 -08002379 self._LIGHTSENSOR_SEARCH_DIR, '|'.join(self._LIGHTSENSOR_FILES))
Simran Basic6f1f7a2012-10-16 10:47:46 -07002380 try:
2381 # Run the search cmd following the symlinks. Stderr_tee is set to
2382 # None as there can be a symlink loop, but the command will still
2383 # execute correctly with a few messages printed to stderr.
2384 self.run(search_cmd, stdout_tee=None, stderr_tee=None)
2385 return 'lightsensor'
2386 except error.AutoservRunError:
2387 # egrep exited with a return code of 1 meaning none of the possible
2388 # lightsensor files existed.
2389 return None
2390
2391
Aviv Keshet74c89a92013-02-04 15:18:30 -08002392 @label_decorator('bluetooth')
Simran Basic6f1f7a2012-10-16 10:47:46 -07002393 def has_bluetooth(self):
2394 """Determine the correct board label for this host.
2395
2396 @returns the string 'bluetooth' if this host has bluetooth or
2397 None if it does not.
2398 """
2399 try:
2400 self.run('test -d /sys/class/bluetooth/hci0')
2401 # test exited with a return code of 0.
2402 return 'bluetooth'
2403 except error.AutoservRunError:
2404 # test exited with a return code 1 meaning the directory did not
2405 # exist.
2406 return None
2407
2408
Bill Richardson4f595f52014-02-13 16:20:26 -08002409 @label_decorator('ec')
2410 def get_ec(self):
2411 """
2412 Determine the type of EC on this host.
2413
2414 @returns a string representing this host's embedded controller type.
2415 At present, it only returns "ec:cros", for Chrome OS ECs. Other types
2416 of EC (or none) don't return any strings, since no tests depend on
2417 those.
2418 """
2419 cmd = 'mosys ec info'
2420 # The output should look like these, so that the last field should
2421 # match our EC version scheme:
2422 #
2423 # stm | stm32f100 | snow_v1.3.139-375eb9f
2424 # ti | Unknown-10de | peppy_v1.5.114-5d52788
2425 #
2426 # Non-Chrome OS ECs will look like these:
2427 #
2428 # ENE | KB932 | 00BE107A00
2429 # ite | it8518 | 3.08
2430 #
2431 # And some systems don't have ECs at all (Lumpy, for example).
2432 regexp = r'^.*\|\s*(\S+_v\d+\.\d+\.\d+-[0-9a-f]+)\s*$'
2433
2434 ecinfo = self.run(command=cmd, ignore_status=True)
2435 if ecinfo.exit_status == 0:
2436 res = re.search(regexp, ecinfo.stdout)
2437 if res:
2438 logging.info("EC version is %s", res.groups()[0])
2439 return 'ec:cros'
2440 logging.info("%s got: %s", cmd, ecinfo.stdout)
2441 # Has an EC, but it's not a Chrome OS EC
2442 return None
2443 logging.info("%s exited with status %d", cmd, ecinfo.exit_status)
2444 # No EC present
2445 return None
2446
2447
Alec Berg31b932b2014-04-04 16:09:11 -07002448 @label_decorator('accels')
2449 def get_accels(self):
2450 """
2451 Determine the type of accelerometers on this host.
2452
2453 @returns a string representing this host's accelerometer type.
2454 At present, it only returns "accel:cros-ec", for accelerometers
2455 attached to a Chrome OS EC, or none, if no accelerometers.
2456 """
2457 # Check to make sure we have ectool
2458 rv = self.run('which ectool', ignore_status=True)
2459 if rv.exit_status:
2460 logging.info("No ectool cmd found, assuming no EC accelerometers")
2461 return None
2462
2463 # Check that the EC supports the motionsense command
2464 rv = self.run('ectool motionsense', ignore_status=True)
2465 if rv.exit_status:
2466 logging.info("EC does not support motionsense command "
2467 "assuming no EC accelerometers")
2468 return None
2469
2470 # Check that EC motion sensors are active
2471 active = self.run('ectool motionsense active').stdout.split('\n')
2472 if active[0] == "0":
2473 logging.info("Motion sense inactive, assuming no EC accelerometers")
2474 return None
2475
2476 logging.info("EC accelerometers found")
2477 return 'accel:cros-ec'
2478
2479
Tom Wai-Hong Tam3d6790d2014-04-14 16:15:47 +08002480 @label_decorator('chameleon')
2481 def has_chameleon(self):
2482 """Determine if a Chameleon connected to this host.
2483
Tom Wai-Hong Tambadbb332014-10-10 02:59:41 +08002484 @returns a list containing two strings ('chameleon' and
2485 'chameleon:' + label, e.g. 'chameleon:hdmi') if this host
2486 has a Chameleon or None if it has not.
Tom Wai-Hong Tam3d6790d2014-04-14 16:15:47 +08002487 """
2488 if self._chameleon_host:
Tom Wai-Hong Tambadbb332014-10-10 02:59:41 +08002489 return ['chameleon', 'chameleon:' + self.chameleon.get_label()]
Tom Wai-Hong Tam3d6790d2014-04-14 16:15:47 +08002490 else:
2491 return None
2492
2493
Cheng-Yi Chiangf4104ff2014-12-23 19:39:01 +08002494 @label_decorator('audio_loopback_dongle')
2495 def has_loopback_dongle(self):
2496 """Determine if an audio loopback dongle is plugged to this host.
2497
2498 @returns 'audio_loopback_dongle' when there is an audio loopback dongle
2499 plugged to this host.
2500 None when there is no audio loopback dongle
2501 plugged to this host.
2502 """
Cheng-Yi Chiang8de78112015-05-27 14:47:08 +08002503 nodes_info = self.run(command=cras_utils.get_cras_nodes_cmd(),
2504 ignore_status=True).stdout
2505 if (cras_utils.node_type_is_plugged('HEADPHONE', nodes_info) and
2506 cras_utils.node_type_is_plugged('MIC', nodes_info)):
Cheng-Yi Chiangf4104ff2014-12-23 19:39:01 +08002507 return 'audio_loopback_dongle'
2508 else:
2509 return None
2510
2511
Derek Basehorec71ff622014-07-07 15:18:40 -07002512 @label_decorator('power_supply')
2513 def get_power_supply(self):
2514 """
2515 Determine what type of power supply the host has
2516
2517 @returns a string representing this host's power supply.
2518 'power:battery' when the device has a battery intended for
2519 extended use
2520 'power:AC_primary' when the device has a battery not intended
2521 for extended use (for moving the machine, etc)
2522 'power:AC_only' when the device has no battery at all.
2523 """
2524 psu = self.run(command='mosys psu type', ignore_status=True)
2525 if psu.exit_status:
2526 # The psu command for mosys is not included for all platforms. The
2527 # assumption is that the device will have a battery if the command
2528 # is not found.
2529 return 'power:battery'
2530
2531 psu_str = psu.stdout.strip()
2532 if psu_str == 'unknown':
2533 return None
2534
2535 return 'power:%s' % psu_str
2536
2537
Puthikorn Voravootivatfa011242014-03-14 18:45:11 -07002538 @label_decorator('storage')
2539 def get_storage(self):
2540 """
2541 Determine the type of boot device for this host.
2542
2543 Determine if the internal device is SCSI or dw_mmc device.
2544 Then check that it is SSD or HDD or eMMC or something else.
2545
2546 @returns a string representing this host's internal device type.
2547 'storage:ssd' when internal device is solid state drive
2548 'storage:hdd' when internal device is hard disk drive
2549 'storage:mmc' when internal device is mmc drive
2550 None When internal device is something else or
2551 when we are unable to determine the type
2552 """
2553 # The output should be /dev/mmcblk* for SD/eMMC or /dev/sd* for scsi
2554 rootdev_cmd = ' '.join(['. /usr/sbin/write_gpt.sh;',
2555 '. /usr/share/misc/chromeos-common.sh;',
2556 'load_base_vars;',
2557 'get_fixed_dst_drive'])
Puthikorn Voravootivat03c51682014-04-24 13:52:12 -07002558 rootdev = self.run(command=rootdev_cmd, ignore_status=True)
2559 if rootdev.exit_status:
2560 logging.info("Fail to run %s", rootdev_cmd)
2561 return None
Puthikorn Voravootivatfa011242014-03-14 18:45:11 -07002562 rootdev_str = rootdev.stdout.strip()
2563
2564 if not rootdev_str:
2565 return None
2566
2567 rootdev_base = os.path.basename(rootdev_str)
2568
2569 mmc_pattern = '/dev/mmcblk[0-9]'
2570 if re.match(mmc_pattern, rootdev_str):
2571 # Use type to determine if the internal device is eMMC or somthing
2572 # else. We can assume that MMC is always an internal device.
2573 type_cmd = 'cat /sys/block/%s/device/type' % rootdev_base
Puthikorn Voravootivat03c51682014-04-24 13:52:12 -07002574 type = self.run(command=type_cmd, ignore_status=True)
2575 if type.exit_status:
2576 logging.info("Fail to run %s", type_cmd)
2577 return None
Puthikorn Voravootivatfa011242014-03-14 18:45:11 -07002578 type_str = type.stdout.strip()
2579
2580 if type_str == 'MMC':
2581 return 'storage:mmc'
2582
2583 scsi_pattern = '/dev/sd[a-z]+'
2584 if re.match(scsi_pattern, rootdev.stdout):
2585 # Read symlink for /sys/block/sd* to determine if the internal
2586 # device is connected via ata or usb.
2587 link_cmd = 'readlink /sys/block/%s' % rootdev_base
Puthikorn Voravootivat03c51682014-04-24 13:52:12 -07002588 link = self.run(command=link_cmd, ignore_status=True)
2589 if link.exit_status:
2590 logging.info("Fail to run %s", link_cmd)
2591 return None
Puthikorn Voravootivatfa011242014-03-14 18:45:11 -07002592 link_str = link.stdout.strip()
2593 if 'usb' in link_str:
2594 return None
2595
2596 # Read rotation to determine if the internal device is ssd or hdd.
2597 rotate_cmd = str('cat /sys/block/%s/queue/rotational'
2598 % rootdev_base)
Puthikorn Voravootivat03c51682014-04-24 13:52:12 -07002599 rotate = self.run(command=rotate_cmd, ignore_status=True)
2600 if rotate.exit_status:
2601 logging.info("Fail to run %s", rotate_cmd)
2602 return None
Puthikorn Voravootivatfa011242014-03-14 18:45:11 -07002603 rotate_str = rotate.stdout.strip()
2604
2605 rotate_dict = {'0':'storage:ssd', '1':'storage:hdd'}
2606 return rotate_dict.get(rotate_str)
2607
2608 # All other internal device / error case will always fall here
2609 return None
2610
2611
Dan Shi4e9a2aa2014-03-24 14:28:42 -07002612 @label_decorator('servo')
2613 def get_servo(self):
2614 """Determine if the host has a servo attached.
2615
2616 If the host has a working servo attached, it should have a servo label.
2617
2618 @return: string 'servo' if the host has servo attached. Otherwise,
2619 returns None.
2620 """
2621 return 'servo' if self._servo_host else None
2622
2623
Dan Shi5beba472014-05-28 22:46:07 -07002624 @label_decorator('video_labels')
2625 def get_video_labels(self):
2626 """Run /usr/local/bin/avtest_label_detect to get a list of video labels.
2627
2628 Sample output of avtest_label_detect:
2629 Detected label: hw_video_acc_vp8
2630 Detected label: webcam
2631
2632 @return: A list of labels detected by tool avtest_label_detect.
2633 """
2634 try:
2635 result = self.run('/usr/local/bin/avtest_label_detect').stdout
2636 return re.findall('^Detected label: (\w+)$', result, re.M)
2637 except error.AutoservRunError:
2638 # The tool is not installed.
2639 return []
2640
2641
mussa584b4462014-06-20 15:13:28 -07002642 @label_decorator('video_glitch_detection')
2643 def is_video_glitch_detection_supported(self):
2644 """ Determine if a board under test is supported for video glitch
2645 detection tests.
2646
2647 @return: 'video_glitch_detection' if board is supported, None otherwise.
2648 """
Mussa5b589052015-10-26 17:55:26 -07002649 board = self.get_board().replace(ds_constants.BOARD_PREFIX, '')
mussa584b4462014-06-20 15:13:28 -07002650
Mussa5b589052015-10-26 17:55:26 -07002651 if board in video_test_constants.SUPPORTED_BOARDS:
2652 return 'video_glitch_detection'
mussa584b4462014-06-20 15:13:28 -07002653
Mussa5b589052015-10-26 17:55:26 -07002654 return None
mussa584b4462014-06-20 15:13:28 -07002655
mussa584b4462014-06-20 15:13:28 -07002656
Katherine Threlkeld7b97a9f2014-06-24 13:47:14 -07002657 @label_decorator('touch_labels')
2658 def get_touch(self):
2659 """
2660 Determine whether board under test has a touchpad or touchscreen.
2661
2662 @return: A list of some combination of 'touchscreen' and 'touchpad',
2663 depending on what is present on the device.
Katherine Threlkeldab83d392015-06-18 16:45:57 -07002664
Katherine Threlkeld7b97a9f2014-06-24 13:47:14 -07002665 """
2666 labels = []
Katherine Threlkeldab83d392015-06-18 16:45:57 -07002667 looking_for = ['touchpad', 'touchscreen']
2668 player = input_playback.InputPlayback()
2669 input_events = self.run('ls /dev/input/event*').stdout.strip().split()
2670 filename = '/tmp/touch_labels'
2671 for event in input_events:
2672 self.run('evtest %s > %s' % (event, filename), timeout=1,
2673 ignore_timeout=True)
2674 properties = self.run('cat %s' % filename).stdout
2675 input_type = player._determine_input_type(properties)
2676 if input_type in looking_for:
2677 labels.append(input_type)
2678 looking_for.remove(input_type)
2679 if len(looking_for) == 0:
2680 break
2681 self.run('rm %s' % filename)
2682
Katherine Threlkeld7b97a9f2014-06-24 13:47:14 -07002683 return labels
2684
Hung-ying Tyana39b0542015-06-30 10:36:42 +08002685
2686 @label_decorator('internal_display')
2687 def has_internal_display(self):
2688 """Determine if the device under test is equipped with an internal
2689 display.
2690
2691 @return: 'internal_display' if one is present; None otherwise.
2692 """
2693 from autotest_lib.client.cros.graphics import graphics_utils
2694 from autotest_lib.client.common_lib import utils as common_utils
2695
2696 def __system_output(cmd):
2697 return self.run(cmd).stdout
2698
2699 def __read_file(remote_path):
2700 return self.run('cat %s' % remote_path).stdout
2701
2702 # Hijack the necessary client functions so that we can take advantage
2703 # of the client lib here.
2704 # FIXME: find a less hacky way than this
2705 original_system_output = utils.system_output
2706 original_read_file = common_utils.read_file
2707 utils.system_output = __system_output
2708 common_utils.read_file = __read_file
2709 try:
2710 return ('internal_display' if graphics_utils.has_internal_display()
2711 else None)
2712 finally:
2713 utils.system_output = original_system_output
2714 common_utils.read_file = original_read_file
2715
2716
Eric Carusoee673ac2015-08-05 17:03:04 -07002717 @label_decorator('lucidsleep')
2718 def has_lucid_sleep_support(self):
2719 """Determine if the device under test has support for lucid sleep.
2720
2721 @return 'lucidsleep' if this board supports lucid sleep; None otherwise
2722 """
2723 board = self.get_board().replace(ds_constants.BOARD_PREFIX, '')
2724 return 'lucidsleep' if board in LUCID_SLEEP_BOARDS else None
2725
2726
Dan Shi85276d42014-04-08 22:11:45 -07002727 def is_boot_from_usb(self):
2728 """Check if DUT is boot from USB.
2729
2730 @return: True if DUT is boot from usb.
2731 """
2732 device = self.run('rootdev -s -d').stdout.strip()
2733 removable = int(self.run('cat /sys/block/%s/removable' %
2734 os.path.basename(device)).stdout.strip())
2735 return removable == 1
Helen Zhang17dae2b2014-11-11 09:25:52 -08002736
2737
2738 def read_from_meminfo(self, key):
Dan Shi49ca0932014-11-14 11:22:27 -08002739 """Return the memory info from /proc/meminfo
Helen Zhang17dae2b2014-11-11 09:25:52 -08002740
2741 @param key: meminfo requested
2742
2743 @return the memory value as a string
2744
2745 """
Helen Zhang17dae2b2014-11-11 09:25:52 -08002746 meminfo = self.run('grep %s /proc/meminfo' % key).stdout.strip()
2747 logging.debug('%s', meminfo)
2748 return int(re.search(r'\d+', meminfo).group(0))
Rohit Makasana8a4923c2015-08-13 17:04:26 -07002749
2750
2751 def get_board_type(self):
2752 """
2753 Get the DUT's device type from /etc/lsb-release.
Danny Chan471a8d12015-08-18 14:57:41 -07002754 DEVICETYPE can be one of CHROMEBOX, CHROMEBASE, CHROMEBOOK or more.
2755
2756 @return value of DEVICETYPE param from lsb-release.
Rohit Makasana8a4923c2015-08-13 17:04:26 -07002757 """
Danny Chan471a8d12015-08-18 14:57:41 -07002758 device_type = self.run('grep DEVICETYPE /etc/lsb-release',
2759 ignore_status=True).stdout
2760 if device_type:
Kalin Stoyanov524310b2015-08-21 16:24:04 -07002761 return device_type.split('=')[-1].strip()
Danny Chan471a8d12015-08-18 14:57:41 -07002762 return ''
Gilad Arnolda76bef02015-09-29 13:55:15 -07002763
2764
2765 def get_os_type(self):
2766 return 'cros'
Simran Basia5522a32015-10-06 11:01:24 -07002767
2768
2769 def enable_adb_testing(self):
2770 """Mark this host as an adb tester."""
Dan Shia2872172015-10-31 01:16:51 -07002771 self.run('touch %s' % constants.ANDROID_TESTER_FILEFLAG)