blob: 315caf6855b85f1cccaa101e6a1f2be308ff75d8 [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
mussa584b4462014-06-20 15:13:28 -07005import ConfigParser
Aviv Keshet74c89a92013-02-04 15:18:30 -08006import functools
Christopher Wiley0ed712b2013-04-09 15:25:12 -07007import httplib
J. Richard Barnette1d78b012012-05-15 13:56:30 -07008import logging
Dan Shi0f466e82013-02-22 15:44:58 -08009import os
Simran Basid5e5e272012-09-24 15:23:59 -070010import re
Christopher Wileyd78249a2013-03-01 13:05:31 -080011import socket
J. Richard Barnette1d78b012012-05-15 13:56:30 -070012import subprocess
J. Richard Barnette134ec2c2012-04-25 12:59:37 -070013import time
J. Richard Barnette1d78b012012-05-15 13:56:30 -070014import xmlrpclib
J. Richard Barnette134ec2c2012-04-25 12:59:37 -070015
mussa584b4462014-06-20 15:13:28 -070016import common
J. Richard Barnette45e93de2012-04-11 17:24:15 -070017from autotest_lib.client.bin import utils
Dan Shi9cb0eec2014-06-03 09:04:50 -070018from autotest_lib.client.common_lib import autotemp
Richard Barnette0c73ffc2012-11-19 15:21:18 -080019from autotest_lib.client.common_lib import error
20from autotest_lib.client.common_lib import global_config
J. Richard Barnette45e93de2012-04-11 17:24:15 -070021from autotest_lib.client.common_lib.cros import autoupdater
Richard Barnette03a0c132012-11-05 12:40:35 -080022from autotest_lib.client.common_lib.cros import dev_server
Christopher Wileyd78249a2013-03-01 13:05:31 -080023from autotest_lib.client.common_lib.cros import retry
Michael Liangda8c60a2014-06-03 13:24:51 -070024from autotest_lib.client.common_lib.cros.graphite import stats
Richard Barnette82c35912012-11-20 10:09:10 -080025from autotest_lib.client.cros import constants
J. Richard Barnette84890bd2014-02-21 11:05:47 -080026from autotest_lib.client.cros import cros_ui
Simran Basi263a9d32014-08-19 11:16:51 -070027from autotest_lib.server import autoserv_parser, autotest
Dan Shia1ecd5c2013-06-06 11:21:31 -070028from autotest_lib.server import utils as server_utils
Dan Shi9cb0eec2014-06-03 09:04:50 -070029from autotest_lib.server.cros import provision
Scott Zawalski89c44dd2013-02-26 09:28:02 -050030from autotest_lib.server.cros.dynamic_suite import constants as ds_constants
Simran Basi5e6339a2013-03-21 11:34:32 -070031from autotest_lib.server.cros.dynamic_suite import tools, frontend_wrappers
Dan Shi9cb0eec2014-06-03 09:04:50 -070032from autotest_lib.server.cros.faft.config.config import Config as FAFTConfig
Fang Deng96667ca2013-08-01 17:46:18 -070033from autotest_lib.server.hosts import abstract_ssh
Tom Wai-Hong Tamefe1c7f2014-01-02 14:00:11 +080034from autotest_lib.server.hosts import chameleon_host
Fang Deng5d518f42013-08-02 14:04:32 -070035from autotest_lib.server.hosts import servo_host
Simran Basidcff4252012-11-20 16:13:20 -080036from autotest_lib.site_utils.rpm_control_system import rpm_client
Simran Basid5e5e272012-09-24 15:23:59 -070037
38
beeps32a63082013-08-22 14:02:29 -070039try:
40 import jsonrpclib
41except ImportError:
42 jsonrpclib = None
Fang Deng96667ca2013-08-01 17:46:18 -070043
Fang Dengd1c2b732013-08-20 12:59:46 -070044
beepsc87ff602013-07-31 21:53:00 -070045class FactoryImageCheckerException(error.AutoservError):
46 """Exception raised when an image is a factory image."""
47 pass
48
49
Aviv Keshet74c89a92013-02-04 15:18:30 -080050def add_label_detector(label_function_list, label_list=None, label=None):
51 """Decorator used to group functions together into the provided list.
52 @param label_function_list: List of label detecting functions to add
53 decorated function to.
54 @param label_list: List of detectable labels to add detectable labels to.
55 (Default: None)
56 @param label: Label string that is detectable by this detection function
57 (Default: None)
J. Richard Barnette7214e0b2013-02-06 15:20:49 -080058 """
Simran Basic6f1f7a2012-10-16 10:47:46 -070059 def add_func(func):
Aviv Keshet74c89a92013-02-04 15:18:30 -080060 """
61 @param func: The function to be added as a detector.
62 """
63 label_function_list.append(func)
64 if label and label_list is not None:
65 label_list.append(label)
Simran Basic6f1f7a2012-10-16 10:47:46 -070066 return func
67 return add_func
68
69
Fang Deng0ca40e22013-08-27 17:47:44 -070070class CrosHost(abstract_ssh.AbstractSSHHost):
J. Richard Barnette45e93de2012-04-11 17:24:15 -070071 """Chromium OS specific subclass of Host."""
72
73 _parser = autoserv_parser.autoserv_parser
Scott Zawalski62bacae2013-03-05 10:40:32 -050074 _AFE = frontend_wrappers.RetryingAFE(timeout_min=5, delay_sec=10)
J. Richard Barnette45e93de2012-04-11 17:24:15 -070075
Richard Barnette03a0c132012-11-05 12:40:35 -080076 # Timeout values (in seconds) associated with various Chrome OS
77 # state changes.
J. Richard Barnette134ec2c2012-04-25 12:59:37 -070078 #
Richard Barnette0c73ffc2012-11-19 15:21:18 -080079 # In general, a good rule of thumb is that the timeout can be up
80 # to twice the typical measured value on the slowest platform.
81 # The times here have not necessarily been empirically tested to
82 # meet this criterion.
J. Richard Barnetteeb69d722012-06-18 17:29:44 -070083 #
84 # SLEEP_TIMEOUT: Time to allow for suspend to memory.
Richard Barnette0c73ffc2012-11-19 15:21:18 -080085 # RESUME_TIMEOUT: Time to allow for resume after suspend, plus
86 # time to restart the netwowrk.
J. Richard Barnette84890bd2014-02-21 11:05:47 -080087 # SHUTDOWN_TIMEOUT: Time to allow for shut down.
J. Richard Barnetteeb69d722012-06-18 17:29:44 -070088 # BOOT_TIMEOUT: Time to allow for boot from power off. Among
Richard Barnette0c73ffc2012-11-19 15:21:18 -080089 # other things, this must account for the 30 second dev-mode
J. Richard Barnetted4649c62013-03-06 17:42:27 -080090 # screen delay and time to start the network.
J. Richard Barnetteeb69d722012-06-18 17:29:44 -070091 # USB_BOOT_TIMEOUT: Time to allow for boot from a USB device,
Richard Barnette0c73ffc2012-11-19 15:21:18 -080092 # including the 30 second dev-mode delay and time to start the
J. Richard Barnetted4649c62013-03-06 17:42:27 -080093 # network.
beepsf079cfb2013-09-18 17:49:51 -070094 # INSTALL_TIMEOUT: Time to allow for chromeos-install.
J. Richard Barnette84890bd2014-02-21 11:05:47 -080095 # POWERWASH_BOOT_TIMEOUT: Time to allow for a reboot that
96 # includes powerwash.
J. Richard Barnetteeb69d722012-06-18 17:29:44 -070097
98 SLEEP_TIMEOUT = 2
J. Richard Barnetted4649c62013-03-06 17:42:27 -080099 RESUME_TIMEOUT = 10
Tom Wai-Hong Tam4d169ed2014-02-14 11:05:40 +0800100 SHUTDOWN_TIMEOUT = 5
J. Richard Barnettefbcc7122013-07-24 18:24:59 -0700101 BOOT_TIMEOUT = 60
J. Richard Barnetteeb69d722012-06-18 17:29:44 -0700102 USB_BOOT_TIMEOUT = 150
J. Richard Barnette7817b052014-08-28 09:47:29 -0700103 INSTALL_TIMEOUT = 480
Dan Shi2c88eed2013-11-12 10:18:38 -0800104 POWERWASH_BOOT_TIMEOUT = 60
Chris Sosab76e0ee2013-05-22 16:55:41 -0700105
J. Richard Barnette84890bd2014-02-21 11:05:47 -0800106 # REBOOT_TIMEOUT: How long to wait for a reboot.
107 #
Chris Sosab76e0ee2013-05-22 16:55:41 -0700108 # We have a long timeout to ensure we don't flakily fail due to other
109 # issues. Shorter timeouts are vetted in platform_RebootAfterUpdate.
Simran Basi1160e2c2013-10-04 16:00:24 -0700110 # TODO(sbasi - crbug.com/276094) Restore to 5 mins once the 'host did not
111 # return from reboot' bug is solved.
112 REBOOT_TIMEOUT = 480
Chris Sosab76e0ee2013-05-22 16:55:41 -0700113
Ismail Noorbasha07fdb612013-02-14 14:13:31 -0800114 # _USB_POWER_TIMEOUT: Time to allow for USB to power toggle ON and OFF.
115 # _POWER_CYCLE_TIMEOUT: Time to allow for manual power cycle.
116 _USB_POWER_TIMEOUT = 5
117 _POWER_CYCLE_TIMEOUT = 10
118
beeps32a63082013-08-22 14:02:29 -0700119 _RPC_PROXY_URL = 'http://localhost:%d'
Christopher Wileydd181852013-10-10 19:56:58 -0700120 _RPC_SHUTDOWN_POLLING_PERIOD_SECONDS = 2
Peter Qiu4410db72014-06-05 10:32:41 -0700121 # Set shutdown timeout to account for the time for restarting the UI.
122 _RPC_SHUTDOWN_TIMEOUT_SECONDS = cros_ui.RESTART_UI_TIMEOUT
Richard Barnette0c73ffc2012-11-19 15:21:18 -0800123
Richard Barnette82c35912012-11-20 10:09:10 -0800124 _RPM_RECOVERY_BOARDS = global_config.global_config.get_config_value('CROS',
125 'rpm_recovery_boards', type=str).split(',')
126
127 _MAX_POWER_CYCLE_ATTEMPTS = 6
128 _LAB_MACHINE_FILE = '/mnt/stateful_partition/.labmachine'
Simran Basi9a479b22014-07-09 11:18:40 -0700129 # TODO (sbasi) crbug.com/392548 - renable support for chromeos 4 once the
130 # rpm work is done.
131 _RPM_HOSTNAME_REGEX = ('chromeos[0-3|5-9]+(-row[0-9]+)?-rack[0-9]+[a-z]*-'
Richard Barnette82c35912012-11-20 10:09:10 -0800132 'host[0-9]+')
133 _LIGHTSENSOR_FILES = ['in_illuminance0_input',
134 'in_illuminance0_raw',
135 'illuminance0_input']
136 _LIGHTSENSOR_SEARCH_DIR = '/sys/bus/iio/devices'
137 _LABEL_FUNCTIONS = []
Aviv Keshet74c89a92013-02-04 15:18:30 -0800138 _DETECTABLE_LABELS = []
139 label_decorator = functools.partial(add_label_detector, _LABEL_FUNCTIONS,
140 _DETECTABLE_LABELS)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -0700141
J. Richard Barnetteb6de7e32013-02-14 13:28:04 -0800142 # Constants used in ping_wait_up() and ping_wait_down().
143 #
144 # _PING_WAIT_COUNT is the approximate number of polling
145 # cycles to use when waiting for a host state change.
146 #
147 # _PING_STATUS_DOWN and _PING_STATUS_UP are names used
148 # for arguments to the internal _ping_wait_for_status()
149 # method.
150 _PING_WAIT_COUNT = 40
151 _PING_STATUS_DOWN = False
152 _PING_STATUS_UP = True
153
Ismail Noorbasha07fdb612013-02-14 14:13:31 -0800154 # Allowed values for the power_method argument.
155
156 # POWER_CONTROL_RPM: Passed as default arg for power_off/on/cycle() methods.
157 # POWER_CONTROL_SERVO: Used in set_power() and power_cycle() methods.
158 # POWER_CONTROL_MANUAL: Used in set_power() and power_cycle() methods.
159 POWER_CONTROL_RPM = 'RPM'
160 POWER_CONTROL_SERVO = 'servoj10'
161 POWER_CONTROL_MANUAL = 'manual'
162
163 POWER_CONTROL_VALID_ARGS = (POWER_CONTROL_RPM,
164 POWER_CONTROL_SERVO,
165 POWER_CONTROL_MANUAL)
Richard Barnette0c73ffc2012-11-19 15:21:18 -0800166
Simran Basi5e6339a2013-03-21 11:34:32 -0700167 _RPM_OUTLET_CHANGED = 'outlet_changed'
168
Dan Shi9cb0eec2014-06-03 09:04:50 -0700169 # URL pattern to download firmware image.
170 _FW_IMAGE_URL_PATTERN = global_config.global_config.get_config_value(
171 'CROS', 'firmware_url_pattern', type=str)
beeps687243d2013-07-18 15:29:27 -0700172
J. Richard Barnette964fba02012-10-24 17:34:29 -0700173 @staticmethod
beeps46dadc92013-11-07 14:07:10 -0800174 def check_host(host, timeout=10):
175 """
176 Check if the given host is a chrome-os host.
177
178 @param host: An ssh host representing a device.
179 @param timeout: The timeout for the run command.
180
181 @return: True if the host device is chromeos.
182
beeps46dadc92013-11-07 14:07:10 -0800183 """
184 try:
Christopher Wiley1ea80942014-02-26 16:45:08 -0800185 result = host.run('grep -q CHROMEOS /etc/lsb-release && '
Simran Basie5f7ae42014-06-26 15:44:06 -0700186 '! which adb >/dev/null 2>&1 && '
187 '! grep -q moblab /etc/lsb-release',
Christopher Wileyfc3eac02013-11-21 16:24:57 -0800188 ignore_status=True, timeout=timeout)
beeps46dadc92013-11-07 14:07:10 -0800189 except (error.AutoservRunError, error.AutoservSSHTimeout):
190 return False
191 return result.exit_status == 0
192
193
194 @staticmethod
Tom Wai-Hong Tamefe1c7f2014-01-02 14:00:11 +0800195 def _extract_arguments(args_dict, key_subset):
196 """Extract options from `args_dict` and return a subset result.
J. Richard Barnette7214e0b2013-02-06 15:20:49 -0800197
198 Take the provided dictionary of argument options and return
Tom Wai-Hong Tamefe1c7f2014-01-02 14:00:11 +0800199 a subset that represent standard arguments needed to construct
200 a test-assistant object (chameleon or servo) for a host. The
201 intent is to provide standard argument processing from
202 run_remote_tests for tests that require a test-assistant board
203 to operate.
204
205 @param args_dict Dictionary from which to extract the arguments.
206 @param key_subset Tuple of keys to extract from the args_dict, e.g.
207 ('servo_host', 'servo_port').
208 """
209 result = {}
210 for arg in key_subset:
211 if arg in args_dict:
212 result[arg] = args_dict[arg]
213 return result
214
215
216 @staticmethod
217 def get_chameleon_arguments(args_dict):
218 """Extract chameleon options from `args_dict` and return the result.
219
220 Recommended usage:
221 ~~~~~~~~
222 args_dict = utils.args_to_dict(args)
223 chameleon_args = hosts.CrosHost.get_chameleon_arguments(args_dict)
224 host = hosts.create_host(machine, chameleon_args=chameleon_args)
225 ~~~~~~~~
226
227 @param args_dict Dictionary from which to extract the chameleon
228 arguments.
229 """
230 return CrosHost._extract_arguments(
231 args_dict, ('chameleon_host', 'chameleon_port'))
232
233
234 @staticmethod
235 def get_servo_arguments(args_dict):
236 """Extract servo options from `args_dict` and return the result.
J. Richard Barnette7214e0b2013-02-06 15:20:49 -0800237
238 Recommended usage:
239 ~~~~~~~~
240 args_dict = utils.args_to_dict(args)
Fang Deng0ca40e22013-08-27 17:47:44 -0700241 servo_args = hosts.CrosHost.get_servo_arguments(args_dict)
J. Richard Barnette7214e0b2013-02-06 15:20:49 -0800242 host = hosts.create_host(machine, servo_args=servo_args)
243 ~~~~~~~~
244
245 @param args_dict Dictionary from which to extract the servo
246 arguments.
247 """
Tom Wai-Hong Tamefe1c7f2014-01-02 14:00:11 +0800248 return CrosHost._extract_arguments(
249 args_dict, ('servo_host', 'servo_port'))
J. Richard Barnette134ec2c2012-04-25 12:59:37 -0700250
J. Richard Barnette964fba02012-10-24 17:34:29 -0700251
Tom Wai-Hong Tamefe1c7f2014-01-02 14:00:11 +0800252 def _initialize(self, hostname, chameleon_args=None, servo_args=None,
253 ssh_verbosity_flag='', ssh_options='',
Fang Dengd1c2b732013-08-20 12:59:46 -0700254 *args, **dargs):
Tom Wai-Hong Tamefe1c7f2014-01-02 14:00:11 +0800255 """Initialize superclasses, |self.chameleon|, and |self.servo|.
J. Richard Barnette67ccb872012-04-19 16:34:56 -0700256
Tom Wai-Hong Tamefe1c7f2014-01-02 14:00:11 +0800257 This method checks whether a chameleon/servo (aka
258 test-assistant objects) is required by checking whether
259 chameleon_args/servo_args is None. This method will only
260 attempt to create the test-assistant object when it is
261 required by the test.
Fang Deng5d518f42013-08-02 14:04:32 -0700262
Tom Wai-Hong Tamefe1c7f2014-01-02 14:00:11 +0800263 For creating the test-assistant object, there are three
264 possibilities: First, if the host is a lab system known to have
265 a test-assistant board, we connect to that board unconditionally.
J. Richard Barnette67ccb872012-04-19 16:34:56 -0700266 Second, if we're called from a control file that requires
Tom Wai-Hong Tamefe1c7f2014-01-02 14:00:11 +0800267 test-assistant features for testing, it will pass settings from
268 the arguments, like `servo_host`, `servo_port`. If neither of
269 these cases apply, the test-assistant object will be `None`.
J. Richard Barnette67ccb872012-04-19 16:34:56 -0700270
271 """
Fang Deng0ca40e22013-08-27 17:47:44 -0700272 super(CrosHost, self)._initialize(hostname=hostname,
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700273 *args, **dargs)
J. Richard Barnettef0859852012-08-20 14:55:50 -0700274 # self.env is a dictionary of environment variable settings
275 # to be exported for commands run on the host.
276 # LIBC_FATAL_STDERR_ can be useful for diagnosing certain
277 # errors that might happen.
278 self.env['LIBC_FATAL_STDERR_'] = '1'
beeps32a63082013-08-22 14:02:29 -0700279 self._rpc_proxy_map = {}
Fang Dengd1c2b732013-08-20 12:59:46 -0700280 self._ssh_verbosity_flag = ssh_verbosity_flag
Aviv Keshetc5947fa2013-09-04 14:06:29 -0700281 self._ssh_options = ssh_options
Fang Deng5d518f42013-08-02 14:04:32 -0700282 # TODO(fdeng): We need to simplify the
283 # process of servo and servo_host initialization.
284 # crbug.com/298432
Dan Shi4d478522014-02-14 13:46:32 -0800285 self._servo_host = servo_host.create_servo_host(dut=self.hostname,
286 servo_args=servo_args)
Tom Wai-Hong Tamefe1c7f2014-01-02 14:00:11 +0800287 # TODO(waihong): Do the simplication on Chameleon too.
Tom Wai-Hong Tam3d6790d2014-04-14 16:15:47 +0800288 self._chameleon_host = chameleon_host.create_chameleon_host(
289 dut=self.hostname, chameleon_args=chameleon_args)
290
Dan Shi4d478522014-02-14 13:46:32 -0800291 if self._servo_host is not None:
292 self.servo = self._servo_host.get_servo()
293 else:
294 self.servo = None
295
Tom Wai-Hong Tam3d6790d2014-04-14 16:15:47 +0800296 if self._chameleon_host:
Tom Wai-Hong Tameaee3402014-01-22 08:52:10 +0800297 self.chameleon = self._chameleon_host.create_chameleon_board()
Tom Wai-Hong Tamefe1c7f2014-01-02 14:00:11 +0800298 else:
Tom Wai-Hong Tam3d6790d2014-04-14 16:15:47 +0800299 self.chameleon = None
Fang Deng5d518f42013-08-02 14:04:32 -0700300
301
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500302 def get_repair_image_name(self):
303 """Generate a image_name from variables in the global config.
304
305 @returns a str of $board-version/$BUILD.
306
307 """
308 stable_version = global_config.global_config.get_config_value(
309 'CROS', 'stable_cros_version')
310 build_pattern = global_config.global_config.get_config_value(
311 'CROS', 'stable_build_pattern')
312 board = self._get_board_from_afe()
313 if board is None:
314 raise error.AutoservError('DUT has no board attribute, '
315 'cannot be repaired.')
316 return build_pattern % (board, stable_version)
317
318
Scott Zawalski62bacae2013-03-05 10:40:32 -0500319 def _host_in_AFE(self):
320 """Check if the host is an object the AFE knows.
321
322 @returns the host object.
323 """
324 return self._AFE.get_hosts(hostname=self.hostname)
325
326
Chris Sosab76e0ee2013-05-22 16:55:41 -0700327 def lookup_job_repo_url(self):
328 """Looks up the job_repo_url for the host.
329
330 @returns job_repo_url from AFE or None if not found.
331
332 @raises KeyError if the host does not have a job_repo_url
333 """
334 if not self._host_in_AFE():
335 return None
336
337 hosts = self._AFE.get_hosts(hostname=self.hostname)
beepsb5efc532013-06-04 11:29:34 -0700338 if hosts and ds_constants.JOB_REPO_URL in hosts[0].attributes:
339 return hosts[0].attributes[ds_constants.JOB_REPO_URL]
Chris Sosab76e0ee2013-05-22 16:55:41 -0700340
341
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500342 def clear_cros_version_labels_and_job_repo_url(self):
343 """Clear cros_version labels and host attribute job_repo_url."""
Scott Zawalski62bacae2013-03-05 10:40:32 -0500344 if not self._host_in_AFE():
Scott Zawalskieadbf702013-03-14 09:23:06 -0400345 return
346
Scott Zawalski62bacae2013-03-05 10:40:32 -0500347 host_list = [self.hostname]
348 labels = self._AFE.get_labels(
349 name__startswith=ds_constants.VERSION_PREFIX,
350 host__hostname=self.hostname)
Dan Shi0f466e82013-02-22 15:44:58 -0800351
Scott Zawalski62bacae2013-03-05 10:40:32 -0500352 for label in labels:
353 label.remove_hosts(hosts=host_list)
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500354
beepscb6f1e22013-06-28 19:14:10 -0700355 self.update_job_repo_url(None, None)
356
357
358 def update_job_repo_url(self, devserver_url, image_name):
359 """
360 Updates the job_repo_url host attribute and asserts it's value.
361
362 @param devserver_url: The devserver to use in the job_repo_url.
363 @param image_name: The name of the image to use in the job_repo_url.
364
365 @raises AutoservError: If we failed to update the job_repo_url.
366 """
367 repo_url = None
368 if devserver_url and image_name:
369 repo_url = tools.get_package_url(devserver_url, image_name)
370 self._AFE.set_host_attribute(ds_constants.JOB_REPO_URL, repo_url,
Scott Zawalski62bacae2013-03-05 10:40:32 -0500371 hostname=self.hostname)
beepscb6f1e22013-06-28 19:14:10 -0700372 if self.lookup_job_repo_url() != repo_url:
373 raise error.AutoservError('Failed to update job_repo_url with %s, '
374 'host %s' % (repo_url, self.hostname))
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500375
376
Dan Shie9309262013-06-19 22:50:21 -0700377 def add_cros_version_labels_and_job_repo_url(self, image_name):
Scott Zawalskieadbf702013-03-14 09:23:06 -0400378 """Add cros_version labels and host attribute job_repo_url.
379
380 @param image_name: The name of the image e.g.
381 lumpy-release/R27-3837.0.0
Dan Shi7458bf62013-06-10 12:50:16 -0700382
Scott Zawalskieadbf702013-03-14 09:23:06 -0400383 """
Scott Zawalski62bacae2013-03-05 10:40:32 -0500384 if not self._host_in_AFE():
Scott Zawalskieadbf702013-03-14 09:23:06 -0400385 return
Scott Zawalski62bacae2013-03-05 10:40:32 -0500386
Scott Zawalskieadbf702013-03-14 09:23:06 -0400387 cros_label = '%s%s' % (ds_constants.VERSION_PREFIX, image_name)
Dan Shie9309262013-06-19 22:50:21 -0700388 devserver_url = dev_server.ImageServer.resolve(image_name).url()
Scott Zawalski62bacae2013-03-05 10:40:32 -0500389
390 labels = self._AFE.get_labels(name=cros_label)
391 if labels:
392 label = labels[0]
393 else:
394 label = self._AFE.create_label(name=cros_label)
395
396 label.add_hosts([self.hostname])
beepscb6f1e22013-06-28 19:14:10 -0700397 self.update_job_repo_url(devserver_url, image_name)
398
399
beepsdae65fd2013-07-26 16:24:41 -0700400 def verify_job_repo_url(self, tag=''):
beepscb6f1e22013-06-28 19:14:10 -0700401 """
402 Make sure job_repo_url of this host is valid.
403
joychen03eaad92013-06-26 09:55:21 -0700404 Eg: The job_repo_url "http://lmn.cd.ab.xyx:8080/static/\
beepscb6f1e22013-06-28 19:14:10 -0700405 lumpy-release/R29-4279.0.0/autotest/packages" claims to have the
406 autotest package for lumpy-release/R29-4279.0.0. If this isn't the case,
407 download and extract it. If the devserver embedded in the url is
408 unresponsive, update the job_repo_url of the host after staging it on
409 another devserver.
410
411 @param job_repo_url: A url pointing to the devserver where the autotest
412 package for this build should be staged.
beepsdae65fd2013-07-26 16:24:41 -0700413 @param tag: The tag from the server job, in the format
414 <job_id>-<user>/<hostname>, or <hostless> for a server job.
beepscb6f1e22013-06-28 19:14:10 -0700415
416 @raises DevServerException: If we could not resolve a devserver.
417 @raises AutoservError: If we're unable to save the new job_repo_url as
418 a result of choosing a new devserver because the old one failed to
419 respond to a health check.
beeps0c865032013-07-30 11:37:06 -0700420 @raises urllib2.URLError: If the devserver embedded in job_repo_url
421 doesn't respond within the timeout.
beepscb6f1e22013-06-28 19:14:10 -0700422 """
423 job_repo_url = self.lookup_job_repo_url()
424 if not job_repo_url:
425 logging.warning('No job repo url set on host %s', self.hostname)
426 return
427
428 logging.info('Verifying job repo url %s', job_repo_url)
429 devserver_url, image_name = tools.get_devserver_build_from_package_url(
430 job_repo_url)
431
beeps0c865032013-07-30 11:37:06 -0700432 ds = dev_server.ImageServer(devserver_url)
beepscb6f1e22013-06-28 19:14:10 -0700433
434 logging.info('Staging autotest artifacts for %s on devserver %s',
435 image_name, ds.url())
beeps687243d2013-07-18 15:29:27 -0700436
437 start_time = time.time()
beepscb6f1e22013-06-28 19:14:10 -0700438 ds.stage_artifacts(image_name, ['autotest'])
beeps687243d2013-07-18 15:29:27 -0700439 stage_time = time.time() - start_time
440
441 # Record how much of the verification time comes from a devserver
442 # restage. If we're doing things right we should not see multiple
443 # devservers for a given board/build/branch path.
444 try:
J. Richard Barnette3cbd76b2013-11-27 12:11:25 -0800445 board, build_type, branch = server_utils.ParseBuildName(
beeps687243d2013-07-18 15:29:27 -0700446 image_name)[:3]
J. Richard Barnette3cbd76b2013-11-27 12:11:25 -0800447 except server_utils.ParseBuildNameException:
beeps687243d2013-07-18 15:29:27 -0700448 pass
449 else:
beeps0c865032013-07-30 11:37:06 -0700450 devserver = devserver_url[
Chris Sosa65425082013-10-16 13:26:22 -0700451 devserver_url.find('/') + 2:devserver_url.rfind(':')]
beeps687243d2013-07-18 15:29:27 -0700452 stats_key = {
453 'board': board,
454 'build_type': build_type,
455 'branch': branch,
beeps0c865032013-07-30 11:37:06 -0700456 'devserver': devserver.replace('.', '_'),
beeps687243d2013-07-18 15:29:27 -0700457 }
458 stats.Gauge('verify_job_repo_url').send(
459 '%(board)s.%(build_type)s.%(branch)s.%(devserver)s' % stats_key,
460 stage_time)
beepscb6f1e22013-06-28 19:14:10 -0700461
Scott Zawalskieadbf702013-03-14 09:23:06 -0400462
Dan Shi0f466e82013-02-22 15:44:58 -0800463 def _try_stateful_update(self, update_url, force_update, updater):
464 """Try to use stateful update to initialize DUT.
465
466 When DUT is already running the same version that machine_install
467 tries to install, stateful update is a much faster way to clean up
468 the DUT for testing, compared to a full reimage. It is implemeted
469 by calling autoupdater.run_update, but skipping updating root, as
470 updating the kernel is time consuming and not necessary.
471
472 @param update_url: url of the image.
473 @param force_update: Set to True to update the image even if the DUT
474 is running the same version.
475 @param updater: ChromiumOSUpdater instance used to update the DUT.
476 @returns: True if the DUT was updated with stateful update.
477
478 """
J. Richard Barnette3f731032014-04-07 17:42:59 -0700479 # TODO(jrbarnette): Yes, I hate this re.match() test case.
480 # It's better than the alternative: see crbug.com/360944.
481 image_name = autoupdater.url_to_image_name(update_url)
482 release_pattern = r'^.*-release/R[0-9]+-[0-9]+\.[0-9]+\.0$'
483 if not re.match(release_pattern, image_name):
484 return False
Dan Shi0f466e82013-02-22 15:44:58 -0800485 if not updater.check_version():
486 return False
487 if not force_update:
488 logging.info('Canceling stateful update because the new and '
489 'old versions are the same.')
490 return False
491 # Following folders should be rebuilt after stateful update.
492 # A test file is used to confirm each folder gets rebuilt after
493 # the stateful update.
494 folders_to_check = ['/var', '/home', '/mnt/stateful_partition']
495 test_file = '.test_file_to_be_deleted'
496 for folder in folders_to_check:
497 touch_path = os.path.join(folder, test_file)
498 self.run('touch %s' % touch_path)
499
500 if not updater.run_update(force_update=True, update_root=False):
501 return False
502
503 # Reboot to complete stateful update.
Chris Sosab76e0ee2013-05-22 16:55:41 -0700504 self.reboot(timeout=self.REBOOT_TIMEOUT, wait=True)
Dan Shi0f466e82013-02-22 15:44:58 -0800505 check_file_cmd = 'test -f %s; echo $?'
506 for folder in folders_to_check:
507 test_file_path = os.path.join(folder, test_file)
508 result = self.run(check_file_cmd % test_file_path,
509 ignore_status=True)
510 if result.exit_status == 1:
511 return False
512 return True
513
514
J. Richard Barnette7275b612013-06-04 18:13:11 -0700515 def _post_update_processing(self, updater, expected_kernel=None):
Dan Shi0f466e82013-02-22 15:44:58 -0800516 """After the DUT is updated, confirm machine_install succeeded.
517
518 @param updater: ChromiumOSUpdater instance used to update the DUT.
J. Richard Barnette7275b612013-06-04 18:13:11 -0700519 @param expected_kernel: kernel expected to be active after reboot,
520 or `None` to skip rollback checking.
Dan Shi0f466e82013-02-22 15:44:58 -0800521
522 """
J. Richard Barnette7275b612013-06-04 18:13:11 -0700523 # Touch the lab machine file to leave a marker that
524 # distinguishes this image from other test images.
525 # Afterwards, we must re-run the autoreboot script because
526 # it depends on the _LAB_MACHINE_FILE.
Dan Shi0f466e82013-02-22 15:44:58 -0800527 self.run('touch %s' % self._LAB_MACHINE_FILE)
Dan Shi0f466e82013-02-22 15:44:58 -0800528 self.run('start autoreboot')
Chris Sosa65425082013-10-16 13:26:22 -0700529 updater.verify_boot_expectations(
530 expected_kernel, rollback_message=
531 'Build %s failed to boot on %s; system rolled back to previous'
532 'build' % (updater.update_version, self.hostname))
J. Richard Barnette7275b612013-06-04 18:13:11 -0700533 # Check that we've got the build we meant to install.
534 if not updater.check_version_to_confirm_install():
535 raise autoupdater.ChromiumOSError(
536 'Failed to update %s to build %s; found build '
537 '%s instead' % (self.hostname,
Chris Sosa65425082013-10-16 13:26:22 -0700538 updater.update_version,
539 updater.get_build_id()))
Dan Shi0f466e82013-02-22 15:44:58 -0800540
541
J. Richard Barnettee4af8b92013-05-01 13:16:12 -0700542 def _stage_image_for_update(self, image_name=None):
Scott Zawalskieadbf702013-03-14 09:23:06 -0400543 """Stage a build on a devserver and return the update_url.
544
545 @param image_name: a name like lumpy-release/R27-3837.0.0
546 @returns an update URL like:
547 http://172.22.50.205:8082/update/lumpy-release/R27-3837.0.0
548 """
J. Richard Barnettee4af8b92013-05-01 13:16:12 -0700549 if not image_name:
550 image_name = self.get_repair_image_name()
551 logging.info('Staging build for AU: %s', image_name)
Scott Zawalskieadbf702013-03-14 09:23:06 -0400552 devserver = dev_server.ImageServer.resolve(image_name)
553 devserver.trigger_download(image_name, synchronous=False)
554 return tools.image_url_pattern() % (devserver.url(), image_name)
555
556
J. Richard Barnettee4af8b92013-05-01 13:16:12 -0700557 def stage_image_for_servo(self, image_name=None):
558 """Stage a build on a devserver and return the update_url.
559
560 @param image_name: a name like lumpy-release/R27-3837.0.0
561 @returns an update URL like:
562 http://172.22.50.205:8082/update/lumpy-release/R27-3837.0.0
563 """
564 if not image_name:
565 image_name = self.get_repair_image_name()
566 logging.info('Staging build for servo install: %s', image_name)
567 devserver = dev_server.ImageServer.resolve(image_name)
568 devserver.stage_artifacts(image_name, ['test_image'])
569 return devserver.get_test_image_url(image_name)
570
571
beepse539be02013-07-31 21:57:39 -0700572 def stage_factory_image_for_servo(self, image_name):
573 """Stage a build on a devserver and return the update_url.
574
575 @param image_name: a name like <baord>/4262.204.0
beeps12c0a3c2013-09-03 11:58:27 -0700576
beepse539be02013-07-31 21:57:39 -0700577 @return: An update URL, eg:
578 http://<devserver>/static/canary-channel/\
579 <board>/4262.204.0/factory_test/chromiumos_factory_image.bin
beeps12c0a3c2013-09-03 11:58:27 -0700580
581 @raises: ValueError if the factory artifact name is missing from
582 the config.
583
beepse539be02013-07-31 21:57:39 -0700584 """
585 if not image_name:
586 logging.error('Need an image_name to stage a factory image.')
587 return
588
beeps12c0a3c2013-09-03 11:58:27 -0700589 factory_artifact = global_config.global_config.get_config_value(
590 'CROS', 'factory_artifact', type=str, default='')
591 if not factory_artifact:
592 raise ValueError('Cannot retrieve the factory artifact name from '
593 'autotest config, and hence cannot stage factory '
594 'artifacts.')
595
beepse539be02013-07-31 21:57:39 -0700596 logging.info('Staging build for servo install: %s', image_name)
597 devserver = dev_server.ImageServer.resolve(image_name)
598 devserver.stage_artifacts(
599 image_name,
beeps12c0a3c2013-09-03 11:58:27 -0700600 [factory_artifact],
601 archive_url=None)
beepse539be02013-07-31 21:57:39 -0700602
603 return tools.factory_image_url_pattern() % (devserver.url(), image_name)
604
605
Chris Sosaa3ac2152012-05-23 22:23:13 -0700606 def machine_install(self, update_url=None, force_update=False,
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500607 local_devserver=False, repair=False):
608 """Install the DUT.
609
Dan Shi0f466e82013-02-22 15:44:58 -0800610 Use stateful update if the DUT is already running the same build.
611 Stateful update does not update kernel and tends to run much faster
612 than a full reimage. If the DUT is running a different build, or it
613 failed to do a stateful update, full update, including kernel update,
614 will be applied to the DUT.
615
Scott Zawalskieadbf702013-03-14 09:23:06 -0400616 Once a host enters machine_install its cros_version label will be
617 removed as well as its host attribute job_repo_url (used for
618 package install).
619
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500620 @param update_url: The url to use for the update
621 pattern: http://$devserver:###/update/$build
622 If update_url is None and repair is True we will install the
623 stable image listed in global_config under
624 CROS.stable_cros_version.
625 @param force_update: Force an update even if the version installed
626 is the same. Default:False
627 @param local_devserver: Used by run_remote_test to allow people to
628 use their local devserver. Default: False
629 @param repair: Whether or not we are in repair mode. This adds special
630 cases for repairing a machine like starting update_engine.
631 Setting repair to True sets force_update to True as well.
632 default: False
633 @raises autoupdater.ChromiumOSError
634
635 """
Dan Shi7458bf62013-06-10 12:50:16 -0700636 if update_url:
637 logging.debug('update url is set to %s', update_url)
638 else:
639 logging.debug('update url is not set, resolving...')
J. Richard Barnettee4af8b92013-05-01 13:16:12 -0700640 if self._parser.options.image:
641 requested_build = self._parser.options.image
642 if requested_build.startswith('http://'):
643 update_url = requested_build
Dan Shi7458bf62013-06-10 12:50:16 -0700644 logging.debug('update url is retrieved from requested_build'
645 ': %s', update_url)
J. Richard Barnettee4af8b92013-05-01 13:16:12 -0700646 else:
647 # Try to stage any build that does not start with
648 # http:// on the devservers defined in
649 # global_config.ini.
Dan Shi7458bf62013-06-10 12:50:16 -0700650 update_url = self._stage_image_for_update(requested_build)
651 logging.debug('Build staged, and update_url is set to: %s',
652 update_url)
J. Richard Barnettee4af8b92013-05-01 13:16:12 -0700653 elif repair:
654 update_url = self._stage_image_for_update()
Dan Shi7458bf62013-06-10 12:50:16 -0700655 logging.debug('Build staged, and update_url is set to: %s',
656 update_url)
Scott Zawalskieadbf702013-03-14 09:23:06 -0400657 else:
J. Richard Barnettee4af8b92013-05-01 13:16:12 -0700658 raise autoupdater.ChromiumOSError(
659 'Update failed. No update URL provided.')
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500660
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500661 if repair:
Dan Shi0f466e82013-02-22 15:44:58 -0800662 # In case the system is in a bad state, we always reboot the machine
663 # before machine_install.
Chris Sosab76e0ee2013-05-22 16:55:41 -0700664 self.reboot(timeout=self.REBOOT_TIMEOUT, wait=True)
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500665 self.run('stop update-engine; start update-engine')
666 force_update = True
Dan Shi0f466e82013-02-22 15:44:58 -0800667
Chris Sosaa3ac2152012-05-23 22:23:13 -0700668 updater = autoupdater.ChromiumOSUpdater(update_url, host=self,
Chris Sosa72312602013-04-16 15:01:56 -0700669 local_devserver=local_devserver)
Dan Shi0f466e82013-02-22 15:44:58 -0800670 updated = False
Scott Zawalskieadbf702013-03-14 09:23:06 -0400671 # Remove cros-version and job_repo_url host attribute from host.
672 self.clear_cros_version_labels_and_job_repo_url()
Dan Shi0f466e82013-02-22 15:44:58 -0800673 # If the DUT is already running the same build, try stateful update
674 # first. Stateful update does not update kernel and tends to run much
675 # faster than a full reimage.
676 try:
Chris Sosab76e0ee2013-05-22 16:55:41 -0700677 updated = self._try_stateful_update(
678 update_url, force_update, updater)
Dan Shi0f466e82013-02-22 15:44:58 -0800679 if updated:
680 logging.info('DUT is updated with stateful update.')
681 except Exception as e:
682 logging.exception(e)
Ilja H. Friedel04be2bd2014-05-07 21:29:59 -0700683 logging.warning('Failed to stateful update DUT, force to update.')
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700684
Dan Shi0f466e82013-02-22 15:44:58 -0800685 inactive_kernel = None
686 # Do a full update if stateful update is not applicable or failed.
687 if not updated:
688 # In case the system is in a bad state, we always reboot the
689 # machine before machine_install.
Chris Sosab76e0ee2013-05-22 16:55:41 -0700690 self.reboot(timeout=self.REBOOT_TIMEOUT, wait=True)
Chris Sosab7612bc2013-03-21 10:32:37 -0700691
692 # TODO(sosa): Remove temporary hack to get rid of bricked machines
693 # that can't update due to a corrupted policy.
694 self.run('rm -rf /var/lib/whitelist')
695 self.run('touch /var/lib/whitelist')
696 self.run('chmod -w /var/lib/whitelist')
Scott Zawalskib550d5a2013-03-22 09:23:59 -0400697 self.run('stop update-engine; start update-engine')
Chris Sosab7612bc2013-03-21 10:32:37 -0700698
Dan Shi0f466e82013-02-22 15:44:58 -0800699 if updater.run_update(force_update):
700 updated = True
701 # Figure out active and inactive kernel.
702 active_kernel, inactive_kernel = updater.get_kernel_state()
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700703
Dan Shi0f466e82013-02-22 15:44:58 -0800704 # Ensure inactive kernel has higher priority than active.
705 if (updater.get_kernel_priority(inactive_kernel)
706 < updater.get_kernel_priority(active_kernel)):
707 raise autoupdater.ChromiumOSError(
708 'Update failed. The priority of the inactive kernel'
709 ' partition is less than that of the active kernel'
710 ' partition.')
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700711
Dan Shi0f466e82013-02-22 15:44:58 -0800712 # Updater has returned successfully; reboot the host.
Chris Sosab76e0ee2013-05-22 16:55:41 -0700713 self.reboot(timeout=self.REBOOT_TIMEOUT, wait=True)
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700714
Dan Shi0f466e82013-02-22 15:44:58 -0800715 if updated:
716 self._post_update_processing(updater, inactive_kernel)
Scott Zawalskieadbf702013-03-14 09:23:06 -0400717 image_name = autoupdater.url_to_image_name(update_url)
Dan Shie9309262013-06-19 22:50:21 -0700718 self.add_cros_version_labels_and_job_repo_url(image_name)
Simran Basi13fa1ba2013-03-04 10:56:47 -0800719
Simran Basiae08c8c2014-09-02 11:17:26 -0700720 logging.debug('Cleaning up old autotest directories.')
721 try:
722 installed_autodir = autotest.Autotest.get_installed_autodir(self)
723 self.run('rm -rf ' + installed_autodir)
724 except autotest.AutodirNotFoundError:
725 logging.debug('No autotest installed directory found.')
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700726
727
Dan Shi9cb0eec2014-06-03 09:04:50 -0700728 def _clear_fw_version_labels(self):
729 """Clear firmware version labels from the machine."""
730 labels = self._AFE.get_labels(
731 name__startswith=provision.FW_VERSION_PREFIX,
732 host__hostname=self.hostname)
733 for label in labels:
734 label.remove_hosts(hosts=[self.hostname])
735
736
737 def _add_fw_version_label(self, build):
738 """Add firmware version label to the machine.
739
740 @param build: Build of firmware.
741
742 """
743 fw_label = provision.fw_version_to_label(build)
744 provision.ensure_label_exists(fw_label)
745 label = self._AFE.get_labels(name__startswith=fw_label)[0]
746 label.add_hosts([self.hostname])
747
748
749 def firmware_install(self, build=None):
750 """Install firmware to the DUT.
751
752 Use stateful update if the DUT is already running the same build.
753 Stateful update does not update kernel and tends to run much faster
754 than a full reimage. If the DUT is running a different build, or it
755 failed to do a stateful update, full update, including kernel update,
756 will be applied to the DUT.
757
758 Once a host enters firmware_install its fw_version label will be
759 removed. After the firmware is updated successfully, a new fw_version
760 label will be added to the host.
761
762 @param build: The build version to which we want to provision the
763 firmware of the machine,
764 e.g. 'link-firmware/R22-2695.1.144'.
765
766 TODO(dshi): After bug 381718 is fixed, update here with corresponding
767 exceptions that could be raised.
768
769 """
770 if not self.servo:
771 raise error.TestError('Host %s does not have servo.' %
772 self.hostname)
773
774 # TODO(fdeng): use host.get_board() after
775 # crbug.com/271834 is fixed.
776 board = self._get_board_from_afe()
777
778 # If build is not set, assume it's repair mode and try to install
779 # firmware from stable CrOS.
780 if not build:
781 build = self.get_repair_image_name()
782
783 config = FAFTConfig(board)
784 if config.use_u_boot:
785 ap_image = 'image-%s.bin' % board
786 else: # Depthcharge platform
787 ap_image = 'image.bin'
788 ec_image = 'ec.bin'
789 ds = dev_server.ImageServer.resolve(build)
790 ds.stage_artifacts(build, ['firmware'])
791
792 tmpd = autotemp.tempdir(unique_id='fwimage')
793 try:
794 fwurl = self._FW_IMAGE_URL_PATTERN % (ds.url(), build)
795 local_tarball = os.path.join(tmpd.name, os.path.basename(fwurl))
796 server_utils.system('wget -O %s %s' % (local_tarball, fwurl),
797 timeout=60)
798 server_utils.system('tar xf %s -C %s %s %s' %
799 (local_tarball, tmpd.name, ap_image, ec_image),
800 timeout=60)
801 server_utils.system('tar xf %s --wildcards -C %s "dts/*"' %
802 (local_tarball, tmpd.name),
803 timeout=60, ignore_status=True)
804
805 self._clear_fw_version_labels()
806 logging.info('Will re-program EC now')
807 self.servo.program_ec(os.path.join(tmpd.name, ec_image))
808 logging.info('Will re-program BIOS now')
809 self.servo.program_bios(os.path.join(tmpd.name, ap_image))
810 self.servo.get_power_state_controller().reset()
811 time.sleep(self.servo.BOOT_DELAY)
812 self._add_fw_version_label()
813 finally:
814 tmpd.clean()
815
816
Dan Shi10e992b2013-08-30 11:02:59 -0700817 def show_update_engine_log(self):
818 """Output update engine log."""
819 logging.debug('Dumping %s', constants.UPDATE_ENGINE_LOG)
820 self.run('cat %s' % constants.UPDATE_ENGINE_LOG)
821
822
Richard Barnette82c35912012-11-20 10:09:10 -0800823 def _get_board_from_afe(self):
824 """Retrieve this host's board from its labels in the AFE.
825
826 Looks for a host label of the form "board:<board>", and
827 returns the "<board>" part of the label. `None` is returned
828 if there is not a single, unique label matching the pattern.
829
830 @returns board from label, or `None`.
831 """
Dan Shia1ecd5c2013-06-06 11:21:31 -0700832 return server_utils.get_board_from_afe(self.hostname, self._AFE)
Simran Basi833814b2013-01-29 13:13:43 -0800833
834
835 def get_build(self):
836 """Retrieve the current build for this Host from the AFE.
837
838 Looks through this host's labels in the AFE to determine its build.
839
840 @returns The current build or None if it could not find it or if there
841 were multiple build labels assigned to this host.
842 """
Dan Shia1ecd5c2013-06-06 11:21:31 -0700843 return server_utils.get_build_from_afe(self.hostname, self._AFE)
Richard Barnette82c35912012-11-20 10:09:10 -0800844
845
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500846 def _install_repair(self):
847 """Attempt to repair this host using upate-engine.
848
849 If the host is up, try installing the DUT with a stable
850 "repair" version of Chrome OS as defined in the global_config
851 under CROS.stable_cros_version.
852
Scott Zawalski62bacae2013-03-05 10:40:32 -0500853 @raises AutoservRepairMethodNA if the DUT is not reachable.
854 @raises ChromiumOSError if the install failed for some reason.
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500855
856 """
857 if not self.is_up():
Scott Zawalski62bacae2013-03-05 10:40:32 -0500858 raise error.AutoservRepairMethodNA('DUT unreachable for install.')
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500859 logging.info('Attempting to reimage machine to repair image.')
860 try:
861 self.machine_install(repair=True)
Fang Dengd0672f32013-03-18 17:18:09 -0700862 except autoupdater.ChromiumOSError as e:
863 logging.exception(e)
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500864 logging.info('Repair via install failed.')
Scott Zawalski62bacae2013-03-05 10:40:32 -0500865 raise
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500866
867
Dan Shi2c88eed2013-11-12 10:18:38 -0800868 def _install_repair_with_powerwash(self):
Dan Shi9cc48452013-11-12 12:39:26 -0800869 """Attempt to powerwash first then repair this host using update-engine.
Dan Shi2c88eed2013-11-12 10:18:38 -0800870
Dan Shi9cc48452013-11-12 12:39:26 -0800871 update-engine may fail due to a bad image. In such case, powerwash
872 may help to cleanup the DUT for update-engine to work again.
Dan Shi2c88eed2013-11-12 10:18:38 -0800873
874 @raises AutoservRepairMethodNA if the DUT is not reachable.
875 @raises ChromiumOSError if the install failed for some reason.
876
877 """
878 if not self.is_up():
879 raise error.AutoservRepairMethodNA('DUT unreachable for install.')
880
881 logging.info('Attempting to powerwash the DUT.')
882 self.run('echo "fast safe" > '
883 '/mnt/stateful_partition/factory_install_reset')
884 self.reboot(timeout=self.POWERWASH_BOOT_TIMEOUT, wait=True)
885 if not self.is_up():
Dan Shi9cc48452013-11-12 12:39:26 -0800886 logging.error('Powerwash failed. DUT did not come back after '
Dan Shi2c88eed2013-11-12 10:18:38 -0800887 'reboot.')
888 raise error.AutoservRepairFailure(
889 'DUT failed to boot from powerwash after %d seconds' %
890 self.POWERWASH_BOOT_TIMEOUT)
891
892 logging.info('Powerwash succeeded.')
893 self._install_repair()
894
895
beepsf079cfb2013-09-18 17:49:51 -0700896 def servo_install(self, image_url=None, usb_boot_timeout=USB_BOOT_TIMEOUT,
897 install_timeout=INSTALL_TIMEOUT):
Scott Zawalski62bacae2013-03-05 10:40:32 -0500898 """
899 Re-install the OS on the DUT by:
900 1) installing a test image on a USB storage device attached to the Servo
901 board,
Richard Barnette03a0c132012-11-05 12:40:35 -0800902 2) booting that image in recovery mode, and then
J. Richard Barnette31b2e312013-04-04 16:05:22 -0700903 3) installing the image with chromeos-install.
904
Scott Zawalski62bacae2013-03-05 10:40:32 -0500905 @param image_url: If specified use as the url to install on the DUT.
906 otherwise boot the currently staged image on the USB stick.
beepsf079cfb2013-09-18 17:49:51 -0700907 @param usb_boot_timeout: The usb_boot_timeout to use during reimage.
908 Factory images need a longer usb_boot_timeout than regular
909 cros images.
910 @param install_timeout: The timeout to use when installing the chromeos
911 image. Factory images need a longer install_timeout.
Richard Barnette03a0c132012-11-05 12:40:35 -0800912
Scott Zawalski62bacae2013-03-05 10:40:32 -0500913 @raises AutoservError if the image fails to boot.
Richard Barnette03a0c132012-11-05 12:40:35 -0800914 """
beepsf079cfb2013-09-18 17:49:51 -0700915
916 usb_boot_timer_key = ('servo_install.usb_boot_timeout_%s'
917 % usb_boot_timeout)
918 logging.info('Downloading image to USB, then booting from it. Usb boot '
919 'timeout = %s', usb_boot_timeout)
920 timer = stats.Timer(usb_boot_timer_key)
921 timer.start()
J. Richard Barnette31b2e312013-04-04 16:05:22 -0700922 self.servo.install_recovery_image(image_url)
beepsf079cfb2013-09-18 17:49:51 -0700923 if not self.wait_up(timeout=usb_boot_timeout):
Scott Zawalski62bacae2013-03-05 10:40:32 -0500924 raise error.AutoservRepairFailure(
925 'DUT failed to boot from USB after %d seconds' %
beepsf079cfb2013-09-18 17:49:51 -0700926 usb_boot_timeout)
927 timer.stop()
Scott Zawalski62bacae2013-03-05 10:40:32 -0500928
beepsf079cfb2013-09-18 17:49:51 -0700929 install_timer_key = ('servo_install.install_timeout_%s'
930 % install_timeout)
931 timer = stats.Timer(install_timer_key)
932 timer.start()
933 logging.info('Installing image through chromeos-install.')
934 self.run('chromeos-install --yes', timeout=install_timeout)
935 timer.stop()
936
937 logging.info('Power cycling DUT through servo.')
Richard Barnette03a0c132012-11-05 12:40:35 -0800938 self.servo.power_long_press()
Fang Dengafb88142013-05-30 17:44:31 -0700939 self.servo.switch_usbkey('off')
J. Richard Barnettefbcc7122013-07-24 18:24:59 -0700940 # We *must* use power_on() here; on Parrot it's how we get
941 # out of recovery mode.
942 self.servo.get_power_state_controller().power_on()
beepsf079cfb2013-09-18 17:49:51 -0700943
944 logging.info('Waiting for DUT to come back up.')
Richard Barnette03a0c132012-11-05 12:40:35 -0800945 if not self.wait_up(timeout=self.BOOT_TIMEOUT):
946 raise error.AutoservError('DUT failed to reboot installed '
947 'test image after %d seconds' %
Scott Zawalski62bacae2013-03-05 10:40:32 -0500948 self.BOOT_TIMEOUT)
949
950
J. Richard Barnettee4af8b92013-05-01 13:16:12 -0700951 def _servo_repair_reinstall(self):
Scott Zawalski62bacae2013-03-05 10:40:32 -0500952 """Reinstall the DUT utilizing servo and a test image.
953
954 Re-install the OS on the DUT by:
955 1) installing a test image on a USB storage device attached to the Servo
956 board,
957 2) booting that image in recovery mode, and then
958 3) installing the image with chromeos-install.
959
Scott Zawalski62bacae2013-03-05 10:40:32 -0500960 @raises AutoservRepairMethodNA if the device does not have servo
961 support.
962
963 """
964 if not self.servo:
965 raise error.AutoservRepairMethodNA('Repair Reinstall NA: '
966 'DUT has no servo support.')
967
968 logging.info('Attempting to recovery servo enabled device with '
969 'servo_repair_reinstall')
970
J. Richard Barnettee4af8b92013-05-01 13:16:12 -0700971 image_url = self.stage_image_for_servo()
Scott Zawalski62bacae2013-03-05 10:40:32 -0500972 self.servo_install(image_url)
973
974
975 def _servo_repair_power(self):
976 """Attempt to repair DUT using an attached Servo.
977
978 Attempt to power on the DUT via power_long_press.
979
980 @raises AutoservRepairMethodNA if the device does not have servo
981 support.
982 @raises AutoservRepairFailure if the repair fails for any reason.
983 """
984 if not self.servo:
985 raise error.AutoservRepairMethodNA('Repair Power NA: '
986 'DUT has no servo support.')
987
988 logging.info('Attempting to recover servo enabled device by '
989 'powering it off and on.')
990 self.servo.get_power_state_controller().power_off()
991 self.servo.get_power_state_controller().power_on()
992 if self.wait_up(self.BOOT_TIMEOUT):
993 return
994
995 raise error.AutoservRepairFailure('DUT did not boot after long_press.')
Richard Barnette03a0c132012-11-05 12:40:35 -0800996
997
Richard Barnette82c35912012-11-20 10:09:10 -0800998 def _powercycle_to_repair(self):
999 """Utilize the RPM Infrastructure to bring the host back up.
1000
1001 If the host is not up/repaired after the first powercycle we utilize
1002 auto fallback to the last good install by powercycling and rebooting the
1003 host 6 times.
Scott Zawalski62bacae2013-03-05 10:40:32 -05001004
1005 @raises AutoservRepairMethodNA if the device does not support remote
1006 power.
1007 @raises AutoservRepairFailure if the repair fails for any reason.
1008
Richard Barnette82c35912012-11-20 10:09:10 -08001009 """
Scott Zawalski62bacae2013-03-05 10:40:32 -05001010 if not self.has_power():
1011 raise error.AutoservRepairMethodNA('Device does not support power.')
1012
Richard Barnette82c35912012-11-20 10:09:10 -08001013 logging.info('Attempting repair via RPM powercycle.')
1014 failed_cycles = 0
1015 self.power_cycle()
1016 while not self.wait_up(timeout=self.BOOT_TIMEOUT):
1017 failed_cycles += 1
1018 if failed_cycles >= self._MAX_POWER_CYCLE_ATTEMPTS:
Scott Zawalski62bacae2013-03-05 10:40:32 -05001019 raise error.AutoservRepairFailure(
1020 'Powercycled host %s %d times; device did not come back'
1021 ' online.' % (self.hostname, failed_cycles))
Richard Barnette82c35912012-11-20 10:09:10 -08001022 self.power_cycle()
1023 if failed_cycles == 0:
1024 logging.info('Powercycling was successful first time.')
1025 else:
1026 logging.info('Powercycling was successful after %d failures.',
1027 failed_cycles)
1028
1029
Prashanth B4d8184f2014-05-05 12:22:02 -07001030 def check_device(self):
1031 """Check if a device is ssh-able, and if so, clean and verify it.
1032
1033 @raise AutoservSSHTimeout: If the ssh ping times out.
1034 @raise AutoservSshPermissionDeniedError: If ssh ping fails due to
1035 permissions.
1036 @raise AutoservSshPingHostError: For other AutoservRunErrors during
1037 ssh_ping.
1038 @raises AutoservError: As appropriate, during cleanup and verify.
1039 """
1040 self.ssh_ping()
1041 self.cleanup()
1042 self.verify()
1043
1044
Richard Barnette82c35912012-11-20 10:09:10 -08001045 def repair_full(self):
1046 """Repair a host for repair level NO_PROTECTION.
1047
1048 This overrides the base class function for repair; it does
1049 not call back to the parent class, but instead offers a
1050 simplified implementation based on the capabilities in the
1051 Chrome OS test lab.
1052
Fang Deng5d518f42013-08-02 14:04:32 -07001053 It first verifies and repairs servo if it is a DUT in CrOS
Fang Deng03590af2013-10-07 17:34:20 -07001054 lab and a servo is attached.
Fang Deng5d518f42013-08-02 14:04:32 -07001055
Jakob Juelich82b7d1c2014-09-15 16:10:57 -07001056 This escalates in order through the following procedures and verifies
1057 the status using `self.check_device()` after each of them. This is done
1058 until both the repair and the veryfing step succeed.
1059
1060 Escalation order of repair procedures:
J. Richard Barnettefde55fc2013-03-15 17:47:01 -07001061 1. Try to re-install to a known stable image using
1062 auto-update.
Scott Zawalski62bacae2013-03-05 10:40:32 -05001063 2. If there's a servo for the DUT, try to power the DUT off and
1064 on.
1065 3. If there's a servo for the DUT, try to re-install via
J. Richard Barnettefde55fc2013-03-15 17:47:01 -07001066 the servo.
Scott Zawalski62bacae2013-03-05 10:40:32 -05001067 4. If the DUT can be power-cycled via RPM, try to repair
Richard Barnette82c35912012-11-20 10:09:10 -08001068 by power-cycling.
1069
1070 As with the parent method, the last operation performed on
Prashanth B4d8184f2014-05-05 12:22:02 -07001071 the DUT must be to call `self.check_device()`; If that call fails the
1072 exception it raises is passed back to the caller.
J. Richard Barnettefde55fc2013-03-15 17:47:01 -07001073
Scott Zawalski62bacae2013-03-05 10:40:32 -05001074 @raises AutoservRepairTotalFailure if the repair process fails to
1075 fix the DUT.
Fang Deng5d518f42013-08-02 14:04:32 -07001076 @raises ServoHostRepairTotalFailure if the repair process fails to
1077 fix the servo host if one is attached to the DUT.
1078 @raises AutoservSshPermissionDeniedError if it is unable
1079 to ssh to the servo host due to permission error.
1080
Richard Barnette82c35912012-11-20 10:09:10 -08001081 """
Jakob Juelich82b7d1c2014-09-15 16:10:57 -07001082 # Caution: Deleting shards relies on repair to always reboot the DUT.
1083
Dan Shi4d478522014-02-14 13:46:32 -08001084 if self._servo_host and not self.servo:
Fang Deng03590af2013-10-07 17:34:20 -07001085 try:
Dan Shi4d478522014-02-14 13:46:32 -08001086 self._servo_host.repair_full()
Fang Deng03590af2013-10-07 17:34:20 -07001087 except Exception as e:
Fang Deng03590af2013-10-07 17:34:20 -07001088 logging.error('Could not create a healthy servo: %s', e)
Dan Shi4d478522014-02-14 13:46:32 -08001089 self.servo = self._servo_host.get_servo()
Fang Deng5d518f42013-08-02 14:04:32 -07001090
Scott Zawalski62bacae2013-03-05 10:40:32 -05001091 # TODO(scottz): This should use something similar to label_decorator,
1092 # but needs to be populated in order so DUTs are repaired with the
1093 # least amount of effort.
Dan Shi849a1c42014-03-05 11:10:43 -08001094 repair_funcs = [self._servo_repair_power,
1095 self._install_repair,
Dan Shi2c88eed2013-11-12 10:18:38 -08001096 self._install_repair_with_powerwash,
J. Richard Barnettee4af8b92013-05-01 13:16:12 -07001097 self._servo_repair_reinstall,
Scott Zawalski62bacae2013-03-05 10:40:32 -05001098 self._powercycle_to_repair]
1099 errors = []
Simran Basie6130932013-10-01 14:07:52 -07001100 board = self._get_board_from_afe()
Scott Zawalski62bacae2013-03-05 10:40:32 -05001101 for repair_func in repair_funcs:
1102 try:
1103 repair_func()
Prashanth B4d8184f2014-05-05 12:22:02 -07001104 self.check_device()
Simran Basie6130932013-10-01 14:07:52 -07001105 stats.Counter(
1106 '%s.SUCCEEDED' % repair_func.__name__).increment()
1107 if board:
1108 stats.Counter(
Dan Shib87c3aa2014-02-12 15:40:31 -08001109 '%s.%s.SUCCEEDED' % (repair_func.__name__,
Simran Basie6130932013-10-01 14:07:52 -07001110 board)).increment()
Scott Zawalski62bacae2013-03-05 10:40:32 -05001111 return
Simran Basie6130932013-10-01 14:07:52 -07001112 except error.AutoservRepairMethodNA as e:
1113 stats.Counter(
1114 '%s.RepairNA' % repair_func.__name__).increment()
1115 if board:
1116 stats.Counter(
Dan Shib87c3aa2014-02-12 15:40:31 -08001117 '%s.%s.RepairNA' % (repair_func.__name__,
Simran Basie6130932013-10-01 14:07:52 -07001118 board)).increment()
Ilja H. Friedel04be2bd2014-05-07 21:29:59 -07001119 logging.warning('Repair function NA: %s', e)
Simran Basie6130932013-10-01 14:07:52 -07001120 errors.append(str(e))
Scott Zawalski62bacae2013-03-05 10:40:32 -05001121 except Exception as e:
Simran Basie6130932013-10-01 14:07:52 -07001122 stats.Counter(
1123 '%s.FAILED' % repair_func.__name__).increment()
1124 if board:
1125 stats.Counter(
Dan Shib87c3aa2014-02-12 15:40:31 -08001126 '%s.%s.FAILED' % (repair_func.__name__,
Simran Basie6130932013-10-01 14:07:52 -07001127 board)).increment()
Ilja H. Friedel04be2bd2014-05-07 21:29:59 -07001128 logging.warning('Failed to repair device: %s', e)
Scott Zawalski62bacae2013-03-05 10:40:32 -05001129 errors.append(str(e))
Scott Zawalski89c44dd2013-02-26 09:28:02 -05001130
Simran Basie6130932013-10-01 14:07:52 -07001131 stats.Counter('Full_Repair_Failed').increment()
1132 if board:
1133 stats.Counter(
1134 'Full_Repair_Failed.%s' % board).increment()
Scott Zawalski62bacae2013-03-05 10:40:32 -05001135 raise error.AutoservRepairTotalFailure(
1136 'All attempts at repairing the device failed:\n%s' %
1137 '\n'.join(errors))
Richard Barnette82c35912012-11-20 10:09:10 -08001138
1139
J. Richard Barnette1d78b012012-05-15 13:56:30 -07001140 def close(self):
beeps32a63082013-08-22 14:02:29 -07001141 self.rpc_disconnect_all()
Fang Deng0ca40e22013-08-27 17:47:44 -07001142 super(CrosHost, self).close()
J. Richard Barnette1d78b012012-05-15 13:56:30 -07001143
1144
Simran Basi5e6339a2013-03-21 11:34:32 -07001145 def _cleanup_poweron(self):
1146 """Special cleanup method to make sure hosts always get power back."""
1147 afe = frontend_wrappers.RetryingAFE(timeout_min=5, delay_sec=10)
1148 hosts = afe.get_hosts(hostname=self.hostname)
1149 if not hosts or not (self._RPM_OUTLET_CHANGED in
1150 hosts[0].attributes):
1151 return
1152 logging.debug('This host has recently interacted with the RPM'
1153 ' Infrastructure. Ensuring power is on.')
1154 try:
1155 self.power_on()
1156 except rpm_client.RemotePowerException:
1157 # If cleanup has completed but there was an issue with the RPM
1158 # Infrastructure, log an error message rather than fail cleanup
1159 logging.error('Failed to turn Power On for this host after '
1160 'cleanup through the RPM Infrastructure.')
1161 afe.set_host_attribute(self._RPM_OUTLET_CHANGED, None,
1162 hostname=self.hostname)
1163
1164
beepsc87ff602013-07-31 21:53:00 -07001165 def _is_factory_image(self):
1166 """Checks if the image on the DUT is a factory image.
1167
1168 @return: True if the image on the DUT is a factory image.
1169 False otherwise.
1170 """
1171 result = self.run('[ -f /root/.factory_test ]', ignore_status=True)
1172 return result.exit_status == 0
1173
1174
1175 def _restart_ui(self):
J. Richard Barnette84890bd2014-02-21 11:05:47 -08001176 """Restart the Chrome UI.
beepsc87ff602013-07-31 21:53:00 -07001177
1178 @raises: FactoryImageCheckerException for factory images, since
1179 we cannot attempt to restart ui on them.
1180 error.AutoservRunError for any other type of error that
1181 occurs while restarting ui.
1182 """
1183 if self._is_factory_image():
1184 raise FactoryImageCheckerException('Cannot restart ui on factory '
1185 'images')
1186
J. Richard Barnette84890bd2014-02-21 11:05:47 -08001187 # TODO(jrbarnette): The command to stop/start the ui job
1188 # should live inside cros_ui, too. However that would seem
1189 # to imply interface changes to the existing start()/restart()
1190 # functions, which is a bridge too far (for now).
1191 prompt = cros_ui.get_login_prompt_state(self)
1192 self.run('stop ui; start ui')
1193 cros_ui.wait_for_chrome_ready(prompt, self)
beepsc87ff602013-07-31 21:53:00 -07001194
1195
1196 def cleanup(self):
Richard Barnette82c35912012-11-20 10:09:10 -08001197 self.run('rm -f %s' % constants.CLEANUP_LOGS_PAUSED_FILE)
Scott Zawalskiddbc31e2012-11-15 11:29:01 -05001198 try:
beepsc87ff602013-07-31 21:53:00 -07001199 self._restart_ui()
1200 except (error.AutotestRunError, error.AutoservRunError,
1201 FactoryImageCheckerException):
Ilja H. Friedel04be2bd2014-05-07 21:29:59 -07001202 logging.warning('Unable to restart ui, rebooting device.')
Scott Zawalskiddbc31e2012-11-15 11:29:01 -05001203 # Since restarting the UI fails fall back to normal Autotest
1204 # cleanup routines, i.e. reboot the machine.
Fang Deng0ca40e22013-08-27 17:47:44 -07001205 super(CrosHost, self).cleanup()
Simran Basi5e6339a2013-03-21 11:34:32 -07001206 # Check if the rpm outlet was manipulated.
Simran Basid5e5e272012-09-24 15:23:59 -07001207 if self.has_power():
Simran Basi5e6339a2013-03-21 11:34:32 -07001208 self._cleanup_poweron()
J. Richard Barnette45e93de2012-04-11 17:24:15 -07001209
1210
Yu-Ju Honga2be94a2012-07-31 09:48:52 -07001211 def reboot(self, **dargs):
1212 """
1213 This function reboots the site host. The more generic
1214 RemoteHost.reboot() performs sync and sleeps for 5
1215 seconds. This is not necessary for Chrome OS devices as the
1216 sync should be finished in a short time during the reboot
1217 command.
1218 """
Tom Wai-Hong Tamf5cd1d42012-08-13 12:04:08 +08001219 if 'reboot_cmd' not in dargs:
Doug Anderson7d5aeb22014-02-27 15:12:17 -08001220 reboot_timeout = dargs.get('reboot_timeout', 10)
1221 dargs['reboot_cmd'] = ('((reboot & sleep %d; reboot -f &)'
1222 ' </dev/null >/dev/null 2>&1 &)' %
1223 reboot_timeout)
Yu-Ju Honga2be94a2012-07-31 09:48:52 -07001224 # Enable fastsync to avoid running extra sync commands before reboot.
Tom Wai-Hong Tamf5cd1d42012-08-13 12:04:08 +08001225 if 'fastsync' not in dargs:
1226 dargs['fastsync'] = True
Michael Liangda8c60a2014-06-03 13:24:51 -07001227
Charlie Mooneya8e6dab2014-05-29 14:37:55 -07001228 # For purposes of logging reboot times:
1229 # Get the board name i.e. 'daisy_spring'
Michael Liangca4f5a62014-07-10 15:45:13 -07001230 board_fullname = self.get_board()
1231
1232 # Strip the prefix and add it to dargs.
1233 dargs['board'] = board_fullname[board_fullname.find(':')+1:]
Fang Deng0ca40e22013-08-27 17:47:44 -07001234 super(CrosHost, self).reboot(**dargs)
Yu-Ju Honga2be94a2012-07-31 09:48:52 -07001235
1236
Gwendal Grignou7a61d2f2014-05-23 11:05:51 -07001237 def suspend(self, **dargs):
1238 """
1239 This function suspends the site host.
1240 """
1241 suspend_time = dargs.get('suspend_time', 60)
1242 dargs['timeout'] = suspend_time
1243 if 'suspend_cmd' not in dargs:
1244 cmd = ' && '.join(['echo 0 > /sys/class/rtc/rtc0/wakealarm',
1245 'echo +%d > /sys/class/rtc/rtc0/wakealarm' % suspend_time,
1246 'powerd_dbus_suspend --delay=0 &'])
1247 dargs['suspend_cmd'] = ('(( %s )'
1248 '< /dev/null >/dev/null 2>&1 &)' % cmd)
1249 super(CrosHost, self).suspend(**dargs)
1250
1251
Simran Basiec564392014-08-25 16:48:09 -07001252 def upstart_status(self, service_name):
1253 """Check the status of an upstart init script.
1254
1255 @param service_name: Service to look up.
1256
1257 @returns True if the service is running, False otherwise.
1258 """
1259 return self.run('status %s | grep start/running' %
1260 service_name).stdout.strip() != ''
1261
1262
J. Richard Barnette45e93de2012-04-11 17:24:15 -07001263 def verify_software(self):
Richard Barnetteb2bc13c2013-01-08 17:32:51 -08001264 """Verify working software on a Chrome OS system.
J. Richard Barnette45e93de2012-04-11 17:24:15 -07001265
Richard Barnetteb2bc13c2013-01-08 17:32:51 -08001266 Tests for the following conditions:
1267 1. All conditions tested by the parent version of this
1268 function.
1269 2. Sufficient space in /mnt/stateful_partition.
Fang Deng6b05f5b2013-03-20 13:42:11 -07001270 3. Sufficient space in /mnt/stateful_partition/encrypted.
1271 4. update_engine answers a simple status request over DBus.
J. Richard Barnette45e93de2012-04-11 17:24:15 -07001272
J. Richard Barnette45e93de2012-04-11 17:24:15 -07001273 """
Fang Deng0ca40e22013-08-27 17:47:44 -07001274 super(CrosHost, self).verify_software()
J. Richard Barnette45e93de2012-04-11 17:24:15 -07001275 self.check_diskspace(
1276 '/mnt/stateful_partition',
1277 global_config.global_config.get_config_value(
Fang Deng6b05f5b2013-03-20 13:42:11 -07001278 'SERVER', 'gb_diskspace_required', type=float,
1279 default=20.0))
Gaurav Shahe448af82014-06-19 15:18:59 -07001280 encrypted_stateful_path = '/mnt/stateful_partition/encrypted'
1281 # Not all targets build with encrypted stateful support.
1282 if self.path_exists(encrypted_stateful_path):
1283 self.check_diskspace(
1284 encrypted_stateful_path,
1285 global_config.global_config.get_config_value(
1286 'SERVER', 'gb_encrypted_diskspace_required', type=float,
1287 default=0.1))
beepsc87ff602013-07-31 21:53:00 -07001288
Simran Basiec564392014-08-25 16:48:09 -07001289 if not self.upstart_status('system-services'):
Prashanth B5d0a0512014-04-25 12:26:08 -07001290 raise error.AutoservError('Chrome failed to reach login. '
1291 'System services not running.')
1292
beepsc87ff602013-07-31 21:53:00 -07001293 # Factory images don't run update engine,
1294 # goofy controls dbus on these DUTs.
1295 if not self._is_factory_image():
1296 self.run('update_engine_client --status')
Scott Zawalskifbca4a92013-03-04 15:56:42 -05001297 # Makes sure python is present, loads and can use built in functions.
1298 # We have seen cases where importing cPickle fails with undefined
1299 # symbols in cPickle.so.
1300 self.run('python -c "import cPickle"')
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001301
1302
Fang Deng96667ca2013-08-01 17:46:18 -07001303 def make_ssh_command(self, user='root', port=22, opts='', hosts_file=None,
1304 connect_timeout=None, alive_interval=None):
1305 """Override default make_ssh_command to use options tuned for Chrome OS.
1306
1307 Tuning changes:
1308 - ConnectTimeout=30; maximum of 30 seconds allowed for an SSH
1309 connection failure. Consistency with remote_access.sh.
1310
1311 - ServerAliveInterval=180; which causes SSH to ping connection every
1312 180 seconds. In conjunction with ServerAliveCountMax ensures
1313 that if the connection dies, Autotest will bail out quickly.
1314 Originally tried 60 secs, but saw frequent job ABORTS where
1315 the test completed successfully.
1316
1317 - ServerAliveCountMax=3; consistency with remote_access.sh.
1318
1319 - ConnectAttempts=4; reduce flakiness in connection errors;
1320 consistency with remote_access.sh.
1321
1322 - UserKnownHostsFile=/dev/null; we don't care about the keys.
1323 Host keys change with every new installation, don't waste
1324 memory/space saving them.
1325
1326 - SSH protocol forced to 2; needed for ServerAliveInterval.
1327
1328 @param user User name to use for the ssh connection.
1329 @param port Port on the target host to use for ssh connection.
1330 @param opts Additional options to the ssh command.
1331 @param hosts_file Ignored.
1332 @param connect_timeout Ignored.
1333 @param alive_interval Ignored.
1334 """
Aviv Keshetc5947fa2013-09-04 14:06:29 -07001335 base_command = ('/usr/bin/ssh -a -x %s %s %s'
1336 ' -o StrictHostKeyChecking=no'
Fang Deng96667ca2013-08-01 17:46:18 -07001337 ' -o UserKnownHostsFile=/dev/null -o BatchMode=yes'
1338 ' -o ConnectTimeout=30 -o ServerAliveInterval=180'
1339 ' -o ServerAliveCountMax=3 -o ConnectionAttempts=4'
1340 ' -o Protocol=2 -l %s -p %d')
Aviv Keshetc5947fa2013-09-04 14:06:29 -07001341 return base_command % (self._ssh_verbosity_flag, self._ssh_options,
1342 opts, user, port)
Fang Deng96667ca2013-08-01 17:46:18 -07001343
1344
beeps32a63082013-08-22 14:02:29 -07001345 def _create_ssh_tunnel(self, port, local_port):
1346 """Create an ssh tunnel from local_port to port.
1347
1348 @param port: remote port on the host.
1349 @param local_port: local forwarding port.
1350
1351 @return: the tunnel process.
1352 """
1353 # Chrome OS on the target closes down most external ports
1354 # for security. We could open the port, but doing that
1355 # would conflict with security tests that check that only
1356 # expected ports are open. So, to get to the port on the
1357 # target we use an ssh tunnel.
1358 tunnel_options = '-n -N -q -L %d:localhost:%d' % (local_port, port)
1359 ssh_cmd = self.make_ssh_command(opts=tunnel_options)
1360 tunnel_cmd = '%s %s' % (ssh_cmd, self.hostname)
1361 logging.debug('Full tunnel command: %s', tunnel_cmd)
1362 tunnel_proc = subprocess.Popen(tunnel_cmd, shell=True, close_fds=True)
1363 logging.debug('Started ssh tunnel, local = %d'
1364 ' remote = %d, pid = %d',
1365 local_port, port, tunnel_proc.pid)
1366 return tunnel_proc
1367
1368
Christopher Wileydd181852013-10-10 19:56:58 -07001369 def _setup_rpc(self, port, command_name, remote_pid=None):
beeps32a63082013-08-22 14:02:29 -07001370 """Sets up a tunnel process and performs rpc connection book keeping.
1371
1372 This method assumes that xmlrpc and jsonrpc never conflict, since
1373 we can only either have an xmlrpc or a jsonrpc server listening on
1374 a remote port. As such, it enforces a single proxy->remote port
1375 policy, i.e if one starts a jsonrpc proxy/server from port A->B,
1376 and then tries to start an xmlrpc proxy forwarded to the same port,
1377 the xmlrpc proxy will override the jsonrpc tunnel process, however:
1378
1379 1. None of the methods on the xmlrpc proxy will work because
1380 the server listening on B is jsonrpc.
1381
1382 2. The xmlrpc client cannot initiate a termination of the JsonRPC
1383 server, as the only use case currently is goofy, which is tied to
1384 the factory image. It is much easier to handle a failed xmlrpc
1385 call on the client than it is to terminate goofy in this scenario,
1386 as doing the latter might leave the DUT in a hard to recover state.
1387
1388 With the current implementation newer rpc proxy connections will
1389 terminate the tunnel processes of older rpc connections tunneling
1390 to the same remote port. If methods are invoked on the client
1391 after this has happened they will fail with connection closed errors.
1392
1393 @param port: The remote forwarding port.
1394 @param command_name: The name of the remote process, to terminate
1395 using pkill.
1396
1397 @return A url that we can use to initiate the rpc connection.
1398 """
1399 self.rpc_disconnect(port)
1400 local_port = utils.get_unused_port()
1401 tunnel_proc = self._create_ssh_tunnel(port, local_port)
Christopher Wileydd181852013-10-10 19:56:58 -07001402 self._rpc_proxy_map[port] = (command_name, tunnel_proc, remote_pid)
beeps32a63082013-08-22 14:02:29 -07001403 return self._RPC_PROXY_URL % local_port
1404
1405
Christopher Wileyd78249a2013-03-01 13:05:31 -08001406 def xmlrpc_connect(self, command, port, command_name=None,
Yusuf Mohsinallyfff89d62013-11-18 16:34:07 -08001407 ready_test_name=None, timeout_seconds=10,
1408 logfile='/dev/null'):
J. Richard Barnette1d78b012012-05-15 13:56:30 -07001409 """Connect to an XMLRPC server on the host.
1410
1411 The `command` argument should be a simple shell command that
1412 starts an XMLRPC server on the given `port`. The command
1413 must not daemonize, and must terminate cleanly on SIGTERM.
1414 The command is started in the background on the host, and a
1415 local XMLRPC client for the server is created and returned
1416 to the caller.
1417
1418 Note that the process of creating an XMLRPC client makes no
1419 attempt to connect to the remote server; the caller is
1420 responsible for determining whether the server is running
1421 correctly, and is ready to serve requests.
1422
Christopher Wileyd78249a2013-03-01 13:05:31 -08001423 Optionally, the caller can pass ready_test_name, a string
1424 containing the name of a method to call on the proxy. This
1425 method should take no parameters and return successfully only
1426 when the server is ready to process client requests. When
1427 ready_test_name is set, xmlrpc_connect will block until the
1428 proxy is ready, and throw a TestError if the server isn't
1429 ready by timeout_seconds.
1430
beeps32a63082013-08-22 14:02:29 -07001431 If a server is already running on the remote port, this
1432 method will kill it and disconnect the tunnel process
1433 associated with the connection before establishing a new one,
1434 by consulting the rpc_proxy_map in rpc_disconnect.
1435
J. Richard Barnette1d78b012012-05-15 13:56:30 -07001436 @param command Shell command to start the server.
1437 @param port Port number on which the server is expected to
1438 be serving.
J. Richard Barnette7214e0b2013-02-06 15:20:49 -08001439 @param command_name String to use as input to `pkill` to
1440 terminate the XMLRPC server on the host.
Christopher Wileyd78249a2013-03-01 13:05:31 -08001441 @param ready_test_name String containing the name of a
1442 method defined on the XMLRPC server.
1443 @param timeout_seconds Number of seconds to wait
1444 for the server to become 'ready.' Will throw a
1445 TestFail error if server is not ready in time.
Yusuf Mohsinallyfff89d62013-11-18 16:34:07 -08001446 @param logfile Logfile to send output when running
1447 'command' argument.
Yusuf Mohsinally8d19e3c2013-11-21 14:25:45 -08001448
J. Richard Barnette1d78b012012-05-15 13:56:30 -07001449 """
Christopher Wileyc14f06a2013-10-16 13:55:39 -07001450 # Clean up any existing state. If the caller is willing
1451 # to believe their server is down, we ought to clean up
1452 # any tunnels we might have sitting around.
1453 self.rpc_disconnect(port)
J. Richard Barnette1d78b012012-05-15 13:56:30 -07001454 # Start the server on the host. Redirection in the command
1455 # below is necessary, because 'ssh' won't terminate until
1456 # background child processes close stdin, stdout, and
1457 # stderr.
Yusuf Mohsinallyfff89d62013-11-18 16:34:07 -08001458 remote_cmd = '%s </dev/null >%s 2>&1 & echo $!' % (command, logfile)
Christopher Wileydd181852013-10-10 19:56:58 -07001459 remote_pid = self.run(remote_cmd).stdout.rstrip('\n')
J. Richard Barnette1d78b012012-05-15 13:56:30 -07001460 logging.debug('Started XMLRPC server on host %s, pid = %s',
1461 self.hostname, remote_pid)
1462
Christopher Wileydd181852013-10-10 19:56:58 -07001463 # Tunnel through SSH to be able to reach that remote port.
1464 rpc_url = self._setup_rpc(port, command_name, remote_pid=remote_pid)
Christopher Wileyd78249a2013-03-01 13:05:31 -08001465 proxy = xmlrpclib.ServerProxy(rpc_url, allow_none=True)
Christopher Wileydd181852013-10-10 19:56:58 -07001466
Christopher Wileyd78249a2013-03-01 13:05:31 -08001467 if ready_test_name is not None:
J. Richard Barnette13eb7c02013-03-07 12:06:29 -08001468 # retry.retry logs each attempt; calculate delay_sec to
1469 # keep log spam to a dull roar.
Christopher Wiley0ed712b2013-04-09 15:25:12 -07001470 @retry.retry((socket.error,
1471 xmlrpclib.ProtocolError,
1472 httplib.BadStatusLine),
Chris Sosa65425082013-10-16 13:26:22 -07001473 timeout_min=timeout_seconds / 60.0,
1474 delay_sec=min(max(timeout_seconds / 20.0, 0.1), 1))
Christopher Wileyd78249a2013-03-01 13:05:31 -08001475 def ready_test():
1476 """ Call proxy.ready_test_name(). """
1477 getattr(proxy, ready_test_name)()
1478 successful = False
1479 try:
1480 logging.info('Waiting %d seconds for XMLRPC server '
1481 'to start.', timeout_seconds)
1482 ready_test()
1483 successful = True
Christopher Wileyd78249a2013-03-01 13:05:31 -08001484 finally:
1485 if not successful:
1486 logging.error('Failed to start XMLRPC server.')
beeps32a63082013-08-22 14:02:29 -07001487 self.rpc_disconnect(port)
Christopher Wileyd78249a2013-03-01 13:05:31 -08001488 logging.info('XMLRPC server started successfully.')
1489 return proxy
J. Richard Barnette1d78b012012-05-15 13:56:30 -07001490
J. Richard Barnette1d78b012012-05-15 13:56:30 -07001491
Jason Abeleb6f924f2013-11-13 16:01:54 -08001492 def syslog(self, message, tag='autotest'):
1493 """Logs a message to syslog on host.
1494
1495 @param message String message to log into syslog
1496 @param tag String tag prefix for syslog
1497
1498 """
1499 self.run('logger -t "%s" "%s"' % (tag, message))
1500
1501
beeps32a63082013-08-22 14:02:29 -07001502 def jsonrpc_connect(self, port):
1503 """Creates a jsonrpc proxy connection through an ssh tunnel.
1504
1505 This method exists to facilitate communication with goofy (which is
1506 the default system manager on all factory images) and as such, leaves
1507 most of the rpc server sanity checking to the caller. Unlike
1508 xmlrpc_connect, this method does not facilitate the creation of a remote
1509 jsonrpc server, as the only clients of this code are factory tests,
1510 for which the goofy system manager is built in to the image and starts
1511 when the target boots.
1512
1513 One can theoretically create multiple jsonrpc proxies all forwarded
1514 to the same remote port, provided the remote port has an rpc server
1515 listening. However, in doing so we stand the risk of leaking an
1516 existing tunnel process, so we always disconnect any older tunnels
1517 we might have through rpc_disconnect.
1518
1519 @param port: port on the remote host that is serving this proxy.
1520
1521 @return: The client proxy.
1522 """
1523 if not jsonrpclib:
1524 logging.warning('Jsonrpclib could not be imported. Check that '
1525 'site-packages contains jsonrpclib.')
1526 return None
1527
1528 proxy = jsonrpclib.jsonrpc.ServerProxy(self._setup_rpc(port, None))
1529
1530 logging.info('Established a jsonrpc connection through port %s.', port)
1531 return proxy
1532
1533
1534 def rpc_disconnect(self, port):
1535 """Disconnect from an RPC server on the host.
1536
1537 Terminates the remote RPC server previously started for
J. Richard Barnette1d78b012012-05-15 13:56:30 -07001538 the given `port`. Also closes the local ssh tunnel created
1539 for the connection to the host. This function does not
beeps32a63082013-08-22 14:02:29 -07001540 directly alter the state of a previously returned RPC
J. Richard Barnette1d78b012012-05-15 13:56:30 -07001541 client object; however disconnection will cause all
1542 subsequent calls to methods on the object to fail.
1543
1544 This function does nothing if requested to disconnect a port
beeps32a63082013-08-22 14:02:29 -07001545 that was not previously connected via _setup_rpc.
J. Richard Barnette1d78b012012-05-15 13:56:30 -07001546
1547 @param port Port number passed to a previous call to
beeps32a63082013-08-22 14:02:29 -07001548 `_setup_rpc()`.
J. Richard Barnette1d78b012012-05-15 13:56:30 -07001549 """
beeps32a63082013-08-22 14:02:29 -07001550 if port not in self._rpc_proxy_map:
J. Richard Barnette1d78b012012-05-15 13:56:30 -07001551 return
Christopher Wileydd181852013-10-10 19:56:58 -07001552 remote_name, tunnel_proc, remote_pid = self._rpc_proxy_map[port]
J. Richard Barnette1d78b012012-05-15 13:56:30 -07001553 if remote_name:
1554 # We use 'pkill' to find our target process rather than
1555 # a PID, because the host may have rebooted since
1556 # connecting, and we don't want to kill an innocent
1557 # process with the same PID.
1558 #
1559 # 'pkill' helpfully exits with status 1 if no target
1560 # process is found, for which run() will throw an
Simran Basid5e5e272012-09-24 15:23:59 -07001561 # exception. We don't want that, so we the ignore
J. Richard Barnette1d78b012012-05-15 13:56:30 -07001562 # status.
1563 self.run("pkill -f '%s'" % remote_name, ignore_status=True)
Christopher Wileydd181852013-10-10 19:56:58 -07001564 if remote_pid:
1565 logging.info('Waiting for RPC server "%s" shutdown',
1566 remote_name)
1567 start_time = time.time()
1568 while (time.time() - start_time <
1569 self._RPC_SHUTDOWN_TIMEOUT_SECONDS):
1570 running_processes = self.run(
1571 "pgrep -f '%s'" % remote_name,
1572 ignore_status=True).stdout.split()
1573 if not remote_pid in running_processes:
1574 logging.info('Shut down RPC server.')
1575 break
1576 time.sleep(self._RPC_SHUTDOWN_POLLING_PERIOD_SECONDS)
1577 else:
1578 raise error.TestError('Failed to shutdown RPC server %s' %
1579 remote_name)
J. Richard Barnette1d78b012012-05-15 13:56:30 -07001580
1581 if tunnel_proc.poll() is None:
1582 tunnel_proc.terminate()
1583 logging.debug('Terminated tunnel, pid %d', tunnel_proc.pid)
1584 else:
1585 logging.debug('Tunnel pid %d terminated early, status %d',
1586 tunnel_proc.pid, tunnel_proc.returncode)
beeps32a63082013-08-22 14:02:29 -07001587 del self._rpc_proxy_map[port]
J. Richard Barnette1d78b012012-05-15 13:56:30 -07001588
1589
beeps32a63082013-08-22 14:02:29 -07001590 def rpc_disconnect_all(self):
1591 """Disconnect all known RPC proxy ports."""
1592 for port in self._rpc_proxy_map.keys():
1593 self.rpc_disconnect(port)
J. Richard Barnette1d78b012012-05-15 13:56:30 -07001594
1595
Ilja H. Friedel1232e8a2014-06-17 21:30:48 -07001596 def poor_mans_rpc(self, fun):
1597 """
1598 Calls a function from client utils on the host and returns a string.
1599
1600 @param fun function in client utils namespace.
1601 @return output string from calling fun.
1602 """
Simran Basi263a9d32014-08-19 11:16:51 -07001603 script = 'cd %s/bin; ' % autotest.Autotest.get_installed_autodir(self)
Ilja H. Friedel1232e8a2014-06-17 21:30:48 -07001604 script += 'python -c "import common; import utils;'
1605 script += 'print utils.%s"' % fun
1606 return script
1607
1608
J. Richard Barnetteb6de7e32013-02-14 13:28:04 -08001609 def _ping_check_status(self, status):
1610 """Ping the host once, and return whether it has a given status.
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001611
J. Richard Barnetteb6de7e32013-02-14 13:28:04 -08001612 @param status Check the ping status against this value.
1613 @return True iff `status` and the result of ping are the same
1614 (i.e. both True or both False).
1615
1616 """
1617 ping_val = utils.ping(self.hostname, tries=1, deadline=1)
1618 return not (status ^ (ping_val == 0))
1619
1620 def _ping_wait_for_status(self, status, timeout):
1621 """Wait for the host to have a given status (UP or DOWN).
1622
1623 Status is checked by polling. Polling will not last longer
1624 than the number of seconds in `timeout`. The polling
1625 interval will be long enough that only approximately
1626 _PING_WAIT_COUNT polling cycles will be executed, subject
1627 to a maximum interval of about one minute.
1628
1629 @param status Waiting will stop immediately if `ping` of the
1630 host returns this status.
1631 @param timeout Poll for at most this many seconds.
1632 @return True iff the host status from `ping` matched the
1633 requested status at the time of return.
1634
1635 """
1636 # _ping_check_status() takes about 1 second, hence the
1637 # "- 1" in the formula below.
1638 poll_interval = min(int(timeout / self._PING_WAIT_COUNT), 60) - 1
1639 end_time = time.time() + timeout
1640 while time.time() <= end_time:
1641 if self._ping_check_status(status):
1642 return True
1643 if poll_interval > 0:
1644 time.sleep(poll_interval)
1645
1646 # The last thing we did was sleep(poll_interval), so it may
1647 # have been too long since the last `ping`. Check one more
1648 # time, just to be sure.
1649 return self._ping_check_status(status)
1650
1651 def ping_wait_up(self, timeout):
1652 """Wait for the host to respond to `ping`.
1653
1654 N.B. This method is not a reliable substitute for
1655 `wait_up()`, because a host that responds to ping will not
1656 necessarily respond to ssh. This method should only be used
1657 if the target DUT can be considered functional even if it
1658 can't be reached via ssh.
1659
1660 @param timeout Minimum time to allow before declaring the
1661 host to be non-responsive.
1662 @return True iff the host answered to ping before the timeout.
1663
1664 """
1665 return self._ping_wait_for_status(self._PING_STATUS_UP, timeout)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001666
Andrew Bresticker678c0c72013-01-22 10:44:09 -08001667 def ping_wait_down(self, timeout):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001668 """Wait until the host no longer responds to `ping`.
1669
J. Richard Barnetteb6de7e32013-02-14 13:28:04 -08001670 This function can be used as a slightly faster version of
1671 `wait_down()`, by avoiding potentially long ssh timeouts.
1672
1673 @param timeout Minimum time to allow for the host to become
1674 non-responsive.
1675 @return True iff the host quit answering ping before the
1676 timeout.
1677
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001678 """
J. Richard Barnetteb6de7e32013-02-14 13:28:04 -08001679 return self._ping_wait_for_status(self._PING_STATUS_DOWN, timeout)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001680
Tom Wai-Hong Tamfced4f62014-04-17 10:56:30 +08001681 def test_wait_for_sleep(self, sleep_timeout=None):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001682 """Wait for the client to enter low-power sleep mode.
1683
1684 The test for "is asleep" can't distinguish a system that is
1685 powered off; to confirm that the unit was asleep, it is
1686 necessary to force resume, and then call
1687 `test_wait_for_resume()`.
1688
1689 This function is expected to be called from a test as part
1690 of a sequence like the following:
1691
1692 ~~~~~~~~
1693 boot_id = host.get_boot_id()
1694 # trigger sleep on the host
1695 host.test_wait_for_sleep()
1696 # trigger resume on the host
1697 host.test_wait_for_resume(boot_id)
1698 ~~~~~~~~
1699
Tom Wai-Hong Tamfced4f62014-04-17 10:56:30 +08001700 @param sleep_timeout time limit in seconds to allow the host sleep.
1701
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001702 @exception TestFail The host did not go to sleep within
1703 the allowed time.
1704 """
Tom Wai-Hong Tamfced4f62014-04-17 10:56:30 +08001705 if sleep_timeout is None:
1706 sleep_timeout = self.SLEEP_TIMEOUT
1707
1708 if not self.ping_wait_down(timeout=sleep_timeout):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001709 raise error.TestFail(
Tom Wai-Hong Tamfced4f62014-04-17 10:56:30 +08001710 'client failed to sleep after %d seconds' % sleep_timeout)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001711
1712
Tom Wai-Hong Tamfced4f62014-04-17 10:56:30 +08001713 def test_wait_for_resume(self, old_boot_id, resume_timeout=None):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001714 """Wait for the client to resume from low-power sleep mode.
1715
1716 The `old_boot_id` parameter should be the value from
1717 `get_boot_id()` obtained prior to entering sleep mode. A
1718 `TestFail` exception is raised if the boot id changes.
1719
1720 See @ref test_wait_for_sleep for more on this function's
1721 usage.
1722
J. Richard Barnette7214e0b2013-02-06 15:20:49 -08001723 @param old_boot_id A boot id value obtained before the
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001724 target host went to sleep.
Tom Wai-Hong Tamfced4f62014-04-17 10:56:30 +08001725 @param resume_timeout time limit in seconds to allow the host up.
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001726
1727 @exception TestFail The host did not respond within the
1728 allowed time.
1729 @exception TestFail The host responded, but the boot id test
1730 indicated a reboot rather than a sleep
1731 cycle.
1732 """
Tom Wai-Hong Tamfced4f62014-04-17 10:56:30 +08001733 if resume_timeout is None:
1734 resume_timeout = self.RESUME_TIMEOUT
1735
1736 if not self.wait_up(timeout=resume_timeout):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001737 raise error.TestFail(
1738 'client failed to resume from sleep after %d seconds' %
Tom Wai-Hong Tamfced4f62014-04-17 10:56:30 +08001739 resume_timeout)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001740 else:
1741 new_boot_id = self.get_boot_id()
1742 if new_boot_id != old_boot_id:
1743 raise error.TestFail(
1744 'client rebooted, but sleep was expected'
1745 ' (old boot %s, new boot %s)'
1746 % (old_boot_id, new_boot_id))
1747
1748
1749 def test_wait_for_shutdown(self):
1750 """Wait for the client to shut down.
1751
1752 The test for "has shut down" can't distinguish a system that
1753 is merely asleep; to confirm that the unit was down, it is
1754 necessary to force boot, and then call test_wait_for_boot().
1755
1756 This function is expected to be called from a test as part
1757 of a sequence like the following:
1758
1759 ~~~~~~~~
1760 boot_id = host.get_boot_id()
1761 # trigger shutdown on the host
1762 host.test_wait_for_shutdown()
1763 # trigger boot on the host
1764 host.test_wait_for_boot(boot_id)
1765 ~~~~~~~~
1766
1767 @exception TestFail The host did not shut down within the
1768 allowed time.
1769 """
Andrew Bresticker678c0c72013-01-22 10:44:09 -08001770 if not self.ping_wait_down(timeout=self.SHUTDOWN_TIMEOUT):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001771 raise error.TestFail(
1772 'client failed to shut down after %d seconds' %
J. Richard Barnetteeb69d722012-06-18 17:29:44 -07001773 self.SHUTDOWN_TIMEOUT)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001774
1775
1776 def test_wait_for_boot(self, old_boot_id=None):
1777 """Wait for the client to boot from cold power.
1778
1779 The `old_boot_id` parameter should be the value from
1780 `get_boot_id()` obtained prior to shutting down. A
1781 `TestFail` exception is raised if the boot id does not
1782 change. The boot id test is omitted if `old_boot_id` is not
1783 specified.
1784
1785 See @ref test_wait_for_shutdown for more on this function's
1786 usage.
1787
J. Richard Barnette7214e0b2013-02-06 15:20:49 -08001788 @param old_boot_id A boot id value obtained before the
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001789 shut down.
1790
1791 @exception TestFail The host did not respond within the
1792 allowed time.
1793 @exception TestFail The host responded, but the boot id test
1794 indicated that there was no reboot.
1795 """
J. Richard Barnetteeb69d722012-06-18 17:29:44 -07001796 if not self.wait_up(timeout=self.REBOOT_TIMEOUT):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001797 raise error.TestFail(
1798 'client failed to reboot after %d seconds' %
J. Richard Barnetteeb69d722012-06-18 17:29:44 -07001799 self.REBOOT_TIMEOUT)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001800 elif old_boot_id:
1801 if self.get_boot_id() == old_boot_id:
1802 raise error.TestFail(
1803 'client is back up, but did not reboot'
1804 ' (boot %s)' % old_boot_id)
Simran Basid5e5e272012-09-24 15:23:59 -07001805
1806
1807 @staticmethod
1808 def check_for_rpm_support(hostname):
1809 """For a given hostname, return whether or not it is powered by an RPM.
1810
Simran Basi1df55112013-09-06 11:25:09 -07001811 @param hostname: hostname to check for rpm support.
1812
Simran Basid5e5e272012-09-24 15:23:59 -07001813 @return None if this host does not follows the defined naming format
1814 for RPM powered DUT's in the lab. If it does follow the format,
1815 it returns a regular expression MatchObject instead.
1816 """
Fang Deng0ca40e22013-08-27 17:47:44 -07001817 return re.match(CrosHost._RPM_HOSTNAME_REGEX, hostname)
Simran Basid5e5e272012-09-24 15:23:59 -07001818
1819
1820 def has_power(self):
1821 """For this host, return whether or not it is powered by an RPM.
1822
1823 @return True if this host is in the CROS lab and follows the defined
1824 naming format.
1825 """
Fang Deng0ca40e22013-08-27 17:47:44 -07001826 return CrosHost.check_for_rpm_support(self.hostname)
Simran Basid5e5e272012-09-24 15:23:59 -07001827
1828
Ismail Noorbasha07fdb612013-02-14 14:13:31 -08001829 def _set_power(self, state, power_method):
1830 """Sets the power to the host via RPM, Servo or manual.
1831
1832 @param state Specifies which power state to set to DUT
1833 @param power_method Specifies which method of power control to
1834 use. By default "RPM" will be used. Valid values
1835 are the strings "RPM", "manual", "servoj10".
1836
1837 """
1838 ACCEPTABLE_STATES = ['ON', 'OFF']
1839
1840 if state.upper() not in ACCEPTABLE_STATES:
1841 raise error.TestError('State must be one of: %s.'
1842 % (ACCEPTABLE_STATES,))
1843
1844 if power_method == self.POWER_CONTROL_SERVO:
1845 logging.info('Setting servo port J10 to %s', state)
1846 self.servo.set('prtctl3_pwren', state.lower())
1847 time.sleep(self._USB_POWER_TIMEOUT)
1848 elif power_method == self.POWER_CONTROL_MANUAL:
1849 logging.info('You have %d seconds to set the AC power to %s.',
1850 self._POWER_CYCLE_TIMEOUT, state)
1851 time.sleep(self._POWER_CYCLE_TIMEOUT)
1852 else:
1853 if not self.has_power():
1854 raise error.TestFail('DUT does not have RPM connected.')
Simran Basi5e6339a2013-03-21 11:34:32 -07001855 afe = frontend_wrappers.RetryingAFE(timeout_min=5, delay_sec=10)
1856 afe.set_host_attribute(self._RPM_OUTLET_CHANGED, True,
1857 hostname=self.hostname)
Simran Basi1df55112013-09-06 11:25:09 -07001858 rpm_client.set_power(self.hostname, state.upper(), timeout_mins=5)
Simran Basid5e5e272012-09-24 15:23:59 -07001859
1860
Ismail Noorbasha07fdb612013-02-14 14:13:31 -08001861 def power_off(self, power_method=POWER_CONTROL_RPM):
1862 """Turn off power to this host via RPM, Servo or manual.
1863
1864 @param power_method Specifies which method of power control to
1865 use. By default "RPM" will be used. Valid values
1866 are the strings "RPM", "manual", "servoj10".
1867
1868 """
1869 self._set_power('OFF', power_method)
Simran Basid5e5e272012-09-24 15:23:59 -07001870
1871
Ismail Noorbasha07fdb612013-02-14 14:13:31 -08001872 def power_on(self, power_method=POWER_CONTROL_RPM):
1873 """Turn on power to this host via RPM, Servo or manual.
1874
1875 @param power_method Specifies which method of power control to
1876 use. By default "RPM" will be used. Valid values
1877 are the strings "RPM", "manual", "servoj10".
1878
1879 """
1880 self._set_power('ON', power_method)
1881
1882
1883 def power_cycle(self, power_method=POWER_CONTROL_RPM):
1884 """Cycle power to this host by turning it OFF, then ON.
1885
1886 @param power_method Specifies which method of power control to
1887 use. By default "RPM" will be used. Valid values
1888 are the strings "RPM", "manual", "servoj10".
1889
1890 """
1891 if power_method in (self.POWER_CONTROL_SERVO,
1892 self.POWER_CONTROL_MANUAL):
1893 self.power_off(power_method=power_method)
1894 time.sleep(self._POWER_CYCLE_TIMEOUT)
1895 self.power_on(power_method=power_method)
1896 else:
1897 rpm_client.set_power(self.hostname, 'CYCLE')
Simran Basic6f1f7a2012-10-16 10:47:46 -07001898
1899
1900 def get_platform(self):
1901 """Determine the correct platform label for this host.
1902
1903 @returns a string representing this host's platform.
1904 """
1905 crossystem = utils.Crossystem(self)
1906 crossystem.init()
1907 # Extract fwid value and use the leading part as the platform id.
1908 # fwid generally follow the format of {platform}.{firmware version}
1909 # Example: Alex.X.YYY.Z or Google_Alex.X.YYY.Z
1910 platform = crossystem.fwid().split('.')[0].lower()
1911 # Newer platforms start with 'Google_' while the older ones do not.
1912 return platform.replace('google_', '')
1913
1914
Hung-ying Tyanb1328032014-04-01 14:18:54 +08001915 def get_architecture(self):
1916 """Determine the correct architecture label for this host.
1917
1918 @returns a string representing this host's architecture.
1919 """
1920 crossystem = utils.Crossystem(self)
1921 crossystem.init()
1922 return crossystem.arch()
1923
1924
Luis Lozano40b7d0d2014-01-17 15:12:06 -08001925 def get_chrome_version(self):
1926 """Gets the Chrome version number and milestone as strings.
1927
1928 Invokes "chrome --version" to get the version number and milestone.
1929
1930 @return A tuple (chrome_ver, milestone) where "chrome_ver" is the
1931 current Chrome version number as a string (in the form "W.X.Y.Z")
1932 and "milestone" is the first component of the version number
1933 (the "W" from "W.X.Y.Z"). If the version number cannot be parsed
1934 in the "W.X.Y.Z" format, the "chrome_ver" will be the full output
1935 of "chrome --version" and the milestone will be the empty string.
1936
1937 """
1938 version_string = self.run(constants.CHROME_VERSION_COMMAND).stdout
1939 return utils.parse_chrome_version(version_string)
1940
Aviv Keshet74c89a92013-02-04 15:18:30 -08001941 @label_decorator()
Simran Basic6f1f7a2012-10-16 10:47:46 -07001942 def get_board(self):
1943 """Determine the correct board label for this host.
1944
1945 @returns a string representing this host's board.
1946 """
1947 release_info = utils.parse_cmd_output('cat /etc/lsb-release',
1948 run_method=self.run)
1949 board = release_info['CHROMEOS_RELEASE_BOARD']
1950 # Devices in the lab generally have the correct board name but our own
1951 # development devices have {board_name}-signed-{key_type}. The board
1952 # name may also begin with 'x86-' which we need to keep.
Simran Basi833814b2013-01-29 13:13:43 -08001953 board_format_string = ds_constants.BOARD_PREFIX + '%s'
Simran Basic6f1f7a2012-10-16 10:47:46 -07001954 if 'x86' not in board:
Simran Basi833814b2013-01-29 13:13:43 -08001955 return board_format_string % board.split('-')[0]
1956 return board_format_string % '-'.join(board.split('-')[0:2])
Simran Basic6f1f7a2012-10-16 10:47:46 -07001957
1958
Ilja H. Friedel1232e8a2014-06-17 21:30:48 -07001959 @label_decorator('board_freq_mem')
1960 def get_board_with_frequency_and_memory(self):
1961 """
1962 Determines the board name with frequency and memory.
1963
1964 @returns a more detailed string representing the board. Examples are
1965 butterfly_1.1GHz_2GB, link_1.8GHz_4GB, x86-zgb_1.7GHz_2GB
1966 """
1967 board = self.run(self.poor_mans_rpc(
1968 'get_board_with_frequency_and_memory()')).stdout
1969 return 'board_freq_mem:%s' % str.strip(board)
1970
1971
Aviv Keshet74c89a92013-02-04 15:18:30 -08001972 @label_decorator('lightsensor')
Simran Basic6f1f7a2012-10-16 10:47:46 -07001973 def has_lightsensor(self):
1974 """Determine the correct board label for this host.
1975
1976 @returns the string 'lightsensor' if this host has a lightsensor or
1977 None if it does not.
1978 """
1979 search_cmd = "find -L %s -maxdepth 4 | egrep '%s'" % (
Richard Barnette82c35912012-11-20 10:09:10 -08001980 self._LIGHTSENSOR_SEARCH_DIR, '|'.join(self._LIGHTSENSOR_FILES))
Simran Basic6f1f7a2012-10-16 10:47:46 -07001981 try:
1982 # Run the search cmd following the symlinks. Stderr_tee is set to
1983 # None as there can be a symlink loop, but the command will still
1984 # execute correctly with a few messages printed to stderr.
1985 self.run(search_cmd, stdout_tee=None, stderr_tee=None)
1986 return 'lightsensor'
1987 except error.AutoservRunError:
1988 # egrep exited with a return code of 1 meaning none of the possible
1989 # lightsensor files existed.
1990 return None
1991
1992
Aviv Keshet74c89a92013-02-04 15:18:30 -08001993 @label_decorator('bluetooth')
Simran Basic6f1f7a2012-10-16 10:47:46 -07001994 def has_bluetooth(self):
1995 """Determine the correct board label for this host.
1996
1997 @returns the string 'bluetooth' if this host has bluetooth or
1998 None if it does not.
1999 """
2000 try:
2001 self.run('test -d /sys/class/bluetooth/hci0')
2002 # test exited with a return code of 0.
2003 return 'bluetooth'
2004 except error.AutoservRunError:
2005 # test exited with a return code 1 meaning the directory did not
2006 # exist.
2007 return None
2008
2009
Ilja H. Friedel1232e8a2014-06-17 21:30:48 -07002010 @label_decorator('gpu_family')
2011 def get_gpu_family(self):
2012 """
2013 Determine GPU family.
2014
2015 @returns a string representing the gpu family. Examples are mali, tegra,
2016 pinetrail, sandybridge, ivybridge, haswell and baytrail.
2017 """
2018 gpu_family = self.run(self.poor_mans_rpc('get_gpu_family()')).stdout
2019 return 'gpu_family:%s' % str.strip(gpu_family)
2020
2021
Ilja Friedel0ce0b602013-08-15 18:45:27 -07002022 @label_decorator('graphics')
2023 def get_graphics(self):
2024 """
2025 Determine the correct board label for this host.
2026
2027 @returns a string representing this host's graphics. For now ARM boards
2028 return graphics:gles while all other boards return graphics:gl. This
2029 may change over time, but for robustness reasons this should avoid
2030 executing code in actual graphics libraries (which may not be ready and
2031 is tested by graphics_GLAPICheck).
2032 """
2033 uname = self.run('uname -a').stdout.lower()
2034 if 'arm' in uname:
2035 return 'graphics:gles'
2036 return 'graphics:gl'
2037
2038
Bill Richardson4f595f52014-02-13 16:20:26 -08002039 @label_decorator('ec')
2040 def get_ec(self):
2041 """
2042 Determine the type of EC on this host.
2043
2044 @returns a string representing this host's embedded controller type.
2045 At present, it only returns "ec:cros", for Chrome OS ECs. Other types
2046 of EC (or none) don't return any strings, since no tests depend on
2047 those.
2048 """
2049 cmd = 'mosys ec info'
2050 # The output should look like these, so that the last field should
2051 # match our EC version scheme:
2052 #
2053 # stm | stm32f100 | snow_v1.3.139-375eb9f
2054 # ti | Unknown-10de | peppy_v1.5.114-5d52788
2055 #
2056 # Non-Chrome OS ECs will look like these:
2057 #
2058 # ENE | KB932 | 00BE107A00
2059 # ite | it8518 | 3.08
2060 #
2061 # And some systems don't have ECs at all (Lumpy, for example).
2062 regexp = r'^.*\|\s*(\S+_v\d+\.\d+\.\d+-[0-9a-f]+)\s*$'
2063
2064 ecinfo = self.run(command=cmd, ignore_status=True)
2065 if ecinfo.exit_status == 0:
2066 res = re.search(regexp, ecinfo.stdout)
2067 if res:
2068 logging.info("EC version is %s", res.groups()[0])
2069 return 'ec:cros'
2070 logging.info("%s got: %s", cmd, ecinfo.stdout)
2071 # Has an EC, but it's not a Chrome OS EC
2072 return None
2073 logging.info("%s exited with status %d", cmd, ecinfo.exit_status)
2074 # No EC present
2075 return None
2076
2077
Alec Berg31b932b2014-04-04 16:09:11 -07002078 @label_decorator('accels')
2079 def get_accels(self):
2080 """
2081 Determine the type of accelerometers on this host.
2082
2083 @returns a string representing this host's accelerometer type.
2084 At present, it only returns "accel:cros-ec", for accelerometers
2085 attached to a Chrome OS EC, or none, if no accelerometers.
2086 """
2087 # Check to make sure we have ectool
2088 rv = self.run('which ectool', ignore_status=True)
2089 if rv.exit_status:
2090 logging.info("No ectool cmd found, assuming no EC accelerometers")
2091 return None
2092
2093 # Check that the EC supports the motionsense command
2094 rv = self.run('ectool motionsense', ignore_status=True)
2095 if rv.exit_status:
2096 logging.info("EC does not support motionsense command "
2097 "assuming no EC accelerometers")
2098 return None
2099
2100 # Check that EC motion sensors are active
2101 active = self.run('ectool motionsense active').stdout.split('\n')
2102 if active[0] == "0":
2103 logging.info("Motion sense inactive, assuming no EC accelerometers")
2104 return None
2105
2106 logging.info("EC accelerometers found")
2107 return 'accel:cros-ec'
2108
2109
Tom Wai-Hong Tam3d6790d2014-04-14 16:15:47 +08002110 @label_decorator('chameleon')
2111 def has_chameleon(self):
2112 """Determine if a Chameleon connected to this host.
2113
Tom Wai-Hong Tambadbb332014-10-10 02:59:41 +08002114 @returns a list containing two strings ('chameleon' and
2115 'chameleon:' + label, e.g. 'chameleon:hdmi') if this host
2116 has a Chameleon or None if it has not.
Tom Wai-Hong Tam3d6790d2014-04-14 16:15:47 +08002117 """
2118 if self._chameleon_host:
Tom Wai-Hong Tambadbb332014-10-10 02:59:41 +08002119 return ['chameleon', 'chameleon:' + self.chameleon.get_label()]
Tom Wai-Hong Tam3d6790d2014-04-14 16:15:47 +08002120 else:
2121 return None
2122
2123
Derek Basehorec71ff622014-07-07 15:18:40 -07002124 @label_decorator('power_supply')
2125 def get_power_supply(self):
2126 """
2127 Determine what type of power supply the host has
2128
2129 @returns a string representing this host's power supply.
2130 'power:battery' when the device has a battery intended for
2131 extended use
2132 'power:AC_primary' when the device has a battery not intended
2133 for extended use (for moving the machine, etc)
2134 'power:AC_only' when the device has no battery at all.
2135 """
2136 psu = self.run(command='mosys psu type', ignore_status=True)
2137 if psu.exit_status:
2138 # The psu command for mosys is not included for all platforms. The
2139 # assumption is that the device will have a battery if the command
2140 # is not found.
2141 return 'power:battery'
2142
2143 psu_str = psu.stdout.strip()
2144 if psu_str == 'unknown':
2145 return None
2146
2147 return 'power:%s' % psu_str
2148
2149
Puthikorn Voravootivatfa011242014-03-14 18:45:11 -07002150 @label_decorator('storage')
2151 def get_storage(self):
2152 """
2153 Determine the type of boot device for this host.
2154
2155 Determine if the internal device is SCSI or dw_mmc device.
2156 Then check that it is SSD or HDD or eMMC or something else.
2157
2158 @returns a string representing this host's internal device type.
2159 'storage:ssd' when internal device is solid state drive
2160 'storage:hdd' when internal device is hard disk drive
2161 'storage:mmc' when internal device is mmc drive
2162 None When internal device is something else or
2163 when we are unable to determine the type
2164 """
2165 # The output should be /dev/mmcblk* for SD/eMMC or /dev/sd* for scsi
2166 rootdev_cmd = ' '.join(['. /usr/sbin/write_gpt.sh;',
2167 '. /usr/share/misc/chromeos-common.sh;',
2168 'load_base_vars;',
2169 'get_fixed_dst_drive'])
Puthikorn Voravootivat03c51682014-04-24 13:52:12 -07002170 rootdev = self.run(command=rootdev_cmd, ignore_status=True)
2171 if rootdev.exit_status:
2172 logging.info("Fail to run %s", rootdev_cmd)
2173 return None
Puthikorn Voravootivatfa011242014-03-14 18:45:11 -07002174 rootdev_str = rootdev.stdout.strip()
2175
2176 if not rootdev_str:
2177 return None
2178
2179 rootdev_base = os.path.basename(rootdev_str)
2180
2181 mmc_pattern = '/dev/mmcblk[0-9]'
2182 if re.match(mmc_pattern, rootdev_str):
2183 # Use type to determine if the internal device is eMMC or somthing
2184 # else. We can assume that MMC is always an internal device.
2185 type_cmd = 'cat /sys/block/%s/device/type' % rootdev_base
Puthikorn Voravootivat03c51682014-04-24 13:52:12 -07002186 type = self.run(command=type_cmd, ignore_status=True)
2187 if type.exit_status:
2188 logging.info("Fail to run %s", type_cmd)
2189 return None
Puthikorn Voravootivatfa011242014-03-14 18:45:11 -07002190 type_str = type.stdout.strip()
2191
2192 if type_str == 'MMC':
2193 return 'storage:mmc'
2194
2195 scsi_pattern = '/dev/sd[a-z]+'
2196 if re.match(scsi_pattern, rootdev.stdout):
2197 # Read symlink for /sys/block/sd* to determine if the internal
2198 # device is connected via ata or usb.
2199 link_cmd = 'readlink /sys/block/%s' % rootdev_base
Puthikorn Voravootivat03c51682014-04-24 13:52:12 -07002200 link = self.run(command=link_cmd, ignore_status=True)
2201 if link.exit_status:
2202 logging.info("Fail to run %s", link_cmd)
2203 return None
Puthikorn Voravootivatfa011242014-03-14 18:45:11 -07002204 link_str = link.stdout.strip()
2205 if 'usb' in link_str:
2206 return None
2207
2208 # Read rotation to determine if the internal device is ssd or hdd.
2209 rotate_cmd = str('cat /sys/block/%s/queue/rotational'
2210 % rootdev_base)
Puthikorn Voravootivat03c51682014-04-24 13:52:12 -07002211 rotate = self.run(command=rotate_cmd, ignore_status=True)
2212 if rotate.exit_status:
2213 logging.info("Fail to run %s", rotate_cmd)
2214 return None
Puthikorn Voravootivatfa011242014-03-14 18:45:11 -07002215 rotate_str = rotate.stdout.strip()
2216
2217 rotate_dict = {'0':'storage:ssd', '1':'storage:hdd'}
2218 return rotate_dict.get(rotate_str)
2219
2220 # All other internal device / error case will always fall here
2221 return None
2222
2223
Dan Shi4e9a2aa2014-03-24 14:28:42 -07002224 @label_decorator('servo')
2225 def get_servo(self):
2226 """Determine if the host has a servo attached.
2227
2228 If the host has a working servo attached, it should have a servo label.
2229
2230 @return: string 'servo' if the host has servo attached. Otherwise,
2231 returns None.
2232 """
2233 return 'servo' if self._servo_host else None
2234
2235
Dan Shi5beba472014-05-28 22:46:07 -07002236 @label_decorator('video_labels')
2237 def get_video_labels(self):
2238 """Run /usr/local/bin/avtest_label_detect to get a list of video labels.
2239
2240 Sample output of avtest_label_detect:
2241 Detected label: hw_video_acc_vp8
2242 Detected label: webcam
2243
2244 @return: A list of labels detected by tool avtest_label_detect.
2245 """
2246 try:
Simran Basi40ca8182014-07-17 18:41:20 -07002247 # TODO (sbasi) crbug.com/391081 - Remove once the proper fix has
2248 # landed and supporting images older than the fix is no longer
2249 # necessary.
2250 # Change back to VT1 so avtest_label_detect does not get stuck.
2251 self.run('chvt 1')
Dan Shi5beba472014-05-28 22:46:07 -07002252 result = self.run('/usr/local/bin/avtest_label_detect').stdout
2253 return re.findall('^Detected label: (\w+)$', result, re.M)
2254 except error.AutoservRunError:
2255 # The tool is not installed.
2256 return []
2257
2258
mussa584b4462014-06-20 15:13:28 -07002259 @label_decorator('video_glitch_detection')
2260 def is_video_glitch_detection_supported(self):
2261 """ Determine if a board under test is supported for video glitch
2262 detection tests.
2263
2264 @return: 'video_glitch_detection' if board is supported, None otherwise.
2265 """
2266 parser = ConfigParser.SafeConfigParser()
2267 filename = os.path.join(
2268 common.autotest_dir, 'client/cros/video/device_spec.conf')
2269
2270 dut = self.get_board().replace(ds_constants.BOARD_PREFIX, '')
2271
2272 try:
2273 parser.read(filename)
mussa584b4462014-06-20 15:13:28 -07002274 supported_boards = parser.sections()
2275
Mussa83c84d62014-10-02 12:11:28 -07002276 return 'video_glitch_detection' if dut in supported_boards else None
mussa584b4462014-06-20 15:13:28 -07002277
2278 except ConfigParser.error:
2279 # something went wrong while parsing the conf file
2280 return None
2281
Katherine Threlkeld7b97a9f2014-06-24 13:47:14 -07002282 @label_decorator('touch_labels')
2283 def get_touch(self):
2284 """
2285 Determine whether board under test has a touchpad or touchscreen.
2286
2287 @return: A list of some combination of 'touchscreen' and 'touchpad',
2288 depending on what is present on the device.
2289 """
2290 labels = []
2291 input_cmd = '/opt/google/input/inputcontrol --names -t %s'
2292 for elt in ['touchpad', 'touchscreen']:
2293 if self.run(input_cmd % elt).stdout:
2294 labels.append(elt)
2295 return labels
2296
2297
mussa584b4462014-06-20 15:13:28 -07002298
Simran Basic6f1f7a2012-10-16 10:47:46 -07002299 def get_labels(self):
2300 """Return a list of labels for this given host.
2301
2302 This is the main way to retrieve all the automatic labels for a host
2303 as it will run through all the currently implemented label functions.
2304 """
2305 labels = []
Richard Barnette82c35912012-11-20 10:09:10 -08002306 for label_function in self._LABEL_FUNCTIONS:
J. Richard Barnetteb869b222014-09-03 17:55:44 -07002307 try:
2308 label = label_function(self)
2309 except Exception as e:
2310 logging.error('Label function %s failed; ignoring it.',
2311 label_function.__name__)
2312 logging.exception(e)
2313 label = None
Simran Basic6f1f7a2012-10-16 10:47:46 -07002314 if label:
Dan Shi5beba472014-05-28 22:46:07 -07002315 if type(label) is str:
2316 labels.append(label)
2317 elif type(label) is list:
2318 labels.extend(label)
Simran Basic6f1f7a2012-10-16 10:47:46 -07002319 return labels
Dan Shi85276d42014-04-08 22:11:45 -07002320
2321
2322 def is_boot_from_usb(self):
2323 """Check if DUT is boot from USB.
2324
2325 @return: True if DUT is boot from usb.
2326 """
2327 device = self.run('rootdev -s -d').stdout.strip()
2328 removable = int(self.run('cat /sys/block/%s/removable' %
2329 os.path.basename(device)).stdout.strip())
2330 return removable == 1