blob: b4728ba956f2f5d2cb561c783a97e27e1c62f225 [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
Prashanth B4d8184f2014-05-05 12:22:02 -07001056 If `self.check_device()` fails, the following procedures are
J. Richard Barnettefde55fc2013-03-15 17:47:01 -07001057 attempted:
1058 1. Try to re-install to a known stable image using
1059 auto-update.
Scott Zawalski62bacae2013-03-05 10:40:32 -05001060 2. If there's a servo for the DUT, try to power the DUT off and
1061 on.
1062 3. If there's a servo for the DUT, try to re-install via
J. Richard Barnettefde55fc2013-03-15 17:47:01 -07001063 the servo.
Scott Zawalski62bacae2013-03-05 10:40:32 -05001064 4. If the DUT can be power-cycled via RPM, try to repair
Richard Barnette82c35912012-11-20 10:09:10 -08001065 by power-cycling.
1066
1067 As with the parent method, the last operation performed on
Prashanth B4d8184f2014-05-05 12:22:02 -07001068 the DUT must be to call `self.check_device()`; If that call fails the
1069 exception it raises is passed back to the caller.
J. Richard Barnettefde55fc2013-03-15 17:47:01 -07001070
Scott Zawalski62bacae2013-03-05 10:40:32 -05001071 @raises AutoservRepairTotalFailure if the repair process fails to
1072 fix the DUT.
Fang Deng5d518f42013-08-02 14:04:32 -07001073 @raises ServoHostRepairTotalFailure if the repair process fails to
1074 fix the servo host if one is attached to the DUT.
1075 @raises AutoservSshPermissionDeniedError if it is unable
1076 to ssh to the servo host due to permission error.
1077
Richard Barnette82c35912012-11-20 10:09:10 -08001078 """
Dan Shi4d478522014-02-14 13:46:32 -08001079 if self._servo_host and not self.servo:
Fang Deng03590af2013-10-07 17:34:20 -07001080 try:
Dan Shi4d478522014-02-14 13:46:32 -08001081 self._servo_host.repair_full()
Fang Deng03590af2013-10-07 17:34:20 -07001082 except Exception as e:
Fang Deng03590af2013-10-07 17:34:20 -07001083 logging.error('Could not create a healthy servo: %s', e)
Dan Shi4d478522014-02-14 13:46:32 -08001084 self.servo = self._servo_host.get_servo()
Fang Deng5d518f42013-08-02 14:04:32 -07001085
Scott Zawalski62bacae2013-03-05 10:40:32 -05001086 # TODO(scottz): This should use something similar to label_decorator,
1087 # but needs to be populated in order so DUTs are repaired with the
1088 # least amount of effort.
Dan Shi849a1c42014-03-05 11:10:43 -08001089 repair_funcs = [self._servo_repair_power,
1090 self._install_repair,
Dan Shi2c88eed2013-11-12 10:18:38 -08001091 self._install_repair_with_powerwash,
J. Richard Barnettee4af8b92013-05-01 13:16:12 -07001092 self._servo_repair_reinstall,
Scott Zawalski62bacae2013-03-05 10:40:32 -05001093 self._powercycle_to_repair]
1094 errors = []
Simran Basie6130932013-10-01 14:07:52 -07001095 board = self._get_board_from_afe()
Scott Zawalski62bacae2013-03-05 10:40:32 -05001096 for repair_func in repair_funcs:
1097 try:
1098 repair_func()
Prashanth B4d8184f2014-05-05 12:22:02 -07001099 self.check_device()
Simran Basie6130932013-10-01 14:07:52 -07001100 stats.Counter(
1101 '%s.SUCCEEDED' % repair_func.__name__).increment()
1102 if board:
1103 stats.Counter(
Dan Shib87c3aa2014-02-12 15:40:31 -08001104 '%s.%s.SUCCEEDED' % (repair_func.__name__,
Simran Basie6130932013-10-01 14:07:52 -07001105 board)).increment()
Scott Zawalski62bacae2013-03-05 10:40:32 -05001106 return
Simran Basie6130932013-10-01 14:07:52 -07001107 except error.AutoservRepairMethodNA as e:
1108 stats.Counter(
1109 '%s.RepairNA' % repair_func.__name__).increment()
1110 if board:
1111 stats.Counter(
Dan Shib87c3aa2014-02-12 15:40:31 -08001112 '%s.%s.RepairNA' % (repair_func.__name__,
Simran Basie6130932013-10-01 14:07:52 -07001113 board)).increment()
Ilja H. Friedel04be2bd2014-05-07 21:29:59 -07001114 logging.warning('Repair function NA: %s', e)
Simran Basie6130932013-10-01 14:07:52 -07001115 errors.append(str(e))
Scott Zawalski62bacae2013-03-05 10:40:32 -05001116 except Exception as e:
Simran Basie6130932013-10-01 14:07:52 -07001117 stats.Counter(
1118 '%s.FAILED' % repair_func.__name__).increment()
1119 if board:
1120 stats.Counter(
Dan Shib87c3aa2014-02-12 15:40:31 -08001121 '%s.%s.FAILED' % (repair_func.__name__,
Simran Basie6130932013-10-01 14:07:52 -07001122 board)).increment()
Ilja H. Friedel04be2bd2014-05-07 21:29:59 -07001123 logging.warning('Failed to repair device: %s', e)
Scott Zawalski62bacae2013-03-05 10:40:32 -05001124 errors.append(str(e))
Scott Zawalski89c44dd2013-02-26 09:28:02 -05001125
Simran Basie6130932013-10-01 14:07:52 -07001126 stats.Counter('Full_Repair_Failed').increment()
1127 if board:
1128 stats.Counter(
1129 'Full_Repair_Failed.%s' % board).increment()
Scott Zawalski62bacae2013-03-05 10:40:32 -05001130 raise error.AutoservRepairTotalFailure(
1131 'All attempts at repairing the device failed:\n%s' %
1132 '\n'.join(errors))
Richard Barnette82c35912012-11-20 10:09:10 -08001133
1134
J. Richard Barnette1d78b012012-05-15 13:56:30 -07001135 def close(self):
beeps32a63082013-08-22 14:02:29 -07001136 self.rpc_disconnect_all()
Fang Deng0ca40e22013-08-27 17:47:44 -07001137 super(CrosHost, self).close()
J. Richard Barnette1d78b012012-05-15 13:56:30 -07001138
1139
Simran Basi5e6339a2013-03-21 11:34:32 -07001140 def _cleanup_poweron(self):
1141 """Special cleanup method to make sure hosts always get power back."""
1142 afe = frontend_wrappers.RetryingAFE(timeout_min=5, delay_sec=10)
1143 hosts = afe.get_hosts(hostname=self.hostname)
1144 if not hosts or not (self._RPM_OUTLET_CHANGED in
1145 hosts[0].attributes):
1146 return
1147 logging.debug('This host has recently interacted with the RPM'
1148 ' Infrastructure. Ensuring power is on.')
1149 try:
1150 self.power_on()
1151 except rpm_client.RemotePowerException:
1152 # If cleanup has completed but there was an issue with the RPM
1153 # Infrastructure, log an error message rather than fail cleanup
1154 logging.error('Failed to turn Power On for this host after '
1155 'cleanup through the RPM Infrastructure.')
1156 afe.set_host_attribute(self._RPM_OUTLET_CHANGED, None,
1157 hostname=self.hostname)
1158
1159
beepsc87ff602013-07-31 21:53:00 -07001160 def _is_factory_image(self):
1161 """Checks if the image on the DUT is a factory image.
1162
1163 @return: True if the image on the DUT is a factory image.
1164 False otherwise.
1165 """
1166 result = self.run('[ -f /root/.factory_test ]', ignore_status=True)
1167 return result.exit_status == 0
1168
1169
1170 def _restart_ui(self):
J. Richard Barnette84890bd2014-02-21 11:05:47 -08001171 """Restart the Chrome UI.
beepsc87ff602013-07-31 21:53:00 -07001172
1173 @raises: FactoryImageCheckerException for factory images, since
1174 we cannot attempt to restart ui on them.
1175 error.AutoservRunError for any other type of error that
1176 occurs while restarting ui.
1177 """
1178 if self._is_factory_image():
1179 raise FactoryImageCheckerException('Cannot restart ui on factory '
1180 'images')
1181
J. Richard Barnette84890bd2014-02-21 11:05:47 -08001182 # TODO(jrbarnette): The command to stop/start the ui job
1183 # should live inside cros_ui, too. However that would seem
1184 # to imply interface changes to the existing start()/restart()
1185 # functions, which is a bridge too far (for now).
1186 prompt = cros_ui.get_login_prompt_state(self)
1187 self.run('stop ui; start ui')
1188 cros_ui.wait_for_chrome_ready(prompt, self)
beepsc87ff602013-07-31 21:53:00 -07001189
1190
1191 def cleanup(self):
Richard Barnette82c35912012-11-20 10:09:10 -08001192 self.run('rm -f %s' % constants.CLEANUP_LOGS_PAUSED_FILE)
Scott Zawalskiddbc31e2012-11-15 11:29:01 -05001193 try:
beepsc87ff602013-07-31 21:53:00 -07001194 self._restart_ui()
1195 except (error.AutotestRunError, error.AutoservRunError,
1196 FactoryImageCheckerException):
Ilja H. Friedel04be2bd2014-05-07 21:29:59 -07001197 logging.warning('Unable to restart ui, rebooting device.')
Scott Zawalskiddbc31e2012-11-15 11:29:01 -05001198 # Since restarting the UI fails fall back to normal Autotest
1199 # cleanup routines, i.e. reboot the machine.
Fang Deng0ca40e22013-08-27 17:47:44 -07001200 super(CrosHost, self).cleanup()
Simran Basi5e6339a2013-03-21 11:34:32 -07001201 # Check if the rpm outlet was manipulated.
Simran Basid5e5e272012-09-24 15:23:59 -07001202 if self.has_power():
Simran Basi5e6339a2013-03-21 11:34:32 -07001203 self._cleanup_poweron()
J. Richard Barnette45e93de2012-04-11 17:24:15 -07001204
1205
Yu-Ju Honga2be94a2012-07-31 09:48:52 -07001206 def reboot(self, **dargs):
1207 """
1208 This function reboots the site host. The more generic
1209 RemoteHost.reboot() performs sync and sleeps for 5
1210 seconds. This is not necessary for Chrome OS devices as the
1211 sync should be finished in a short time during the reboot
1212 command.
1213 """
Tom Wai-Hong Tamf5cd1d42012-08-13 12:04:08 +08001214 if 'reboot_cmd' not in dargs:
Doug Anderson7d5aeb22014-02-27 15:12:17 -08001215 reboot_timeout = dargs.get('reboot_timeout', 10)
1216 dargs['reboot_cmd'] = ('((reboot & sleep %d; reboot -f &)'
1217 ' </dev/null >/dev/null 2>&1 &)' %
1218 reboot_timeout)
Yu-Ju Honga2be94a2012-07-31 09:48:52 -07001219 # Enable fastsync to avoid running extra sync commands before reboot.
Tom Wai-Hong Tamf5cd1d42012-08-13 12:04:08 +08001220 if 'fastsync' not in dargs:
1221 dargs['fastsync'] = True
Michael Liangda8c60a2014-06-03 13:24:51 -07001222
Charlie Mooneya8e6dab2014-05-29 14:37:55 -07001223 # For purposes of logging reboot times:
1224 # Get the board name i.e. 'daisy_spring'
Michael Liangca4f5a62014-07-10 15:45:13 -07001225 board_fullname = self.get_board()
1226
1227 # Strip the prefix and add it to dargs.
1228 dargs['board'] = board_fullname[board_fullname.find(':')+1:]
Fang Deng0ca40e22013-08-27 17:47:44 -07001229 super(CrosHost, self).reboot(**dargs)
Yu-Ju Honga2be94a2012-07-31 09:48:52 -07001230
1231
Gwendal Grignou7a61d2f2014-05-23 11:05:51 -07001232 def suspend(self, **dargs):
1233 """
1234 This function suspends the site host.
1235 """
1236 suspend_time = dargs.get('suspend_time', 60)
1237 dargs['timeout'] = suspend_time
1238 if 'suspend_cmd' not in dargs:
1239 cmd = ' && '.join(['echo 0 > /sys/class/rtc/rtc0/wakealarm',
1240 'echo +%d > /sys/class/rtc/rtc0/wakealarm' % suspend_time,
1241 'powerd_dbus_suspend --delay=0 &'])
1242 dargs['suspend_cmd'] = ('(( %s )'
1243 '< /dev/null >/dev/null 2>&1 &)' % cmd)
1244 super(CrosHost, self).suspend(**dargs)
1245
1246
Simran Basiec564392014-08-25 16:48:09 -07001247 def upstart_status(self, service_name):
1248 """Check the status of an upstart init script.
1249
1250 @param service_name: Service to look up.
1251
1252 @returns True if the service is running, False otherwise.
1253 """
1254 return self.run('status %s | grep start/running' %
1255 service_name).stdout.strip() != ''
1256
1257
J. Richard Barnette45e93de2012-04-11 17:24:15 -07001258 def verify_software(self):
Richard Barnetteb2bc13c2013-01-08 17:32:51 -08001259 """Verify working software on a Chrome OS system.
J. Richard Barnette45e93de2012-04-11 17:24:15 -07001260
Richard Barnetteb2bc13c2013-01-08 17:32:51 -08001261 Tests for the following conditions:
1262 1. All conditions tested by the parent version of this
1263 function.
1264 2. Sufficient space in /mnt/stateful_partition.
Fang Deng6b05f5b2013-03-20 13:42:11 -07001265 3. Sufficient space in /mnt/stateful_partition/encrypted.
1266 4. update_engine answers a simple status request over DBus.
J. Richard Barnette45e93de2012-04-11 17:24:15 -07001267
J. Richard Barnette45e93de2012-04-11 17:24:15 -07001268 """
Fang Deng0ca40e22013-08-27 17:47:44 -07001269 super(CrosHost, self).verify_software()
J. Richard Barnette45e93de2012-04-11 17:24:15 -07001270 self.check_diskspace(
1271 '/mnt/stateful_partition',
1272 global_config.global_config.get_config_value(
Fang Deng6b05f5b2013-03-20 13:42:11 -07001273 'SERVER', 'gb_diskspace_required', type=float,
1274 default=20.0))
Gaurav Shahe448af82014-06-19 15:18:59 -07001275 encrypted_stateful_path = '/mnt/stateful_partition/encrypted'
1276 # Not all targets build with encrypted stateful support.
1277 if self.path_exists(encrypted_stateful_path):
1278 self.check_diskspace(
1279 encrypted_stateful_path,
1280 global_config.global_config.get_config_value(
1281 'SERVER', 'gb_encrypted_diskspace_required', type=float,
1282 default=0.1))
beepsc87ff602013-07-31 21:53:00 -07001283
Simran Basiec564392014-08-25 16:48:09 -07001284 if not self.upstart_status('system-services'):
Prashanth B5d0a0512014-04-25 12:26:08 -07001285 raise error.AutoservError('Chrome failed to reach login. '
1286 'System services not running.')
1287
beepsc87ff602013-07-31 21:53:00 -07001288 # Factory images don't run update engine,
1289 # goofy controls dbus on these DUTs.
1290 if not self._is_factory_image():
1291 self.run('update_engine_client --status')
Scott Zawalskifbca4a92013-03-04 15:56:42 -05001292 # Makes sure python is present, loads and can use built in functions.
1293 # We have seen cases where importing cPickle fails with undefined
1294 # symbols in cPickle.so.
1295 self.run('python -c "import cPickle"')
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001296
1297
Fang Deng96667ca2013-08-01 17:46:18 -07001298 def make_ssh_command(self, user='root', port=22, opts='', hosts_file=None,
1299 connect_timeout=None, alive_interval=None):
1300 """Override default make_ssh_command to use options tuned for Chrome OS.
1301
1302 Tuning changes:
1303 - ConnectTimeout=30; maximum of 30 seconds allowed for an SSH
1304 connection failure. Consistency with remote_access.sh.
1305
1306 - ServerAliveInterval=180; which causes SSH to ping connection every
1307 180 seconds. In conjunction with ServerAliveCountMax ensures
1308 that if the connection dies, Autotest will bail out quickly.
1309 Originally tried 60 secs, but saw frequent job ABORTS where
1310 the test completed successfully.
1311
1312 - ServerAliveCountMax=3; consistency with remote_access.sh.
1313
1314 - ConnectAttempts=4; reduce flakiness in connection errors;
1315 consistency with remote_access.sh.
1316
1317 - UserKnownHostsFile=/dev/null; we don't care about the keys.
1318 Host keys change with every new installation, don't waste
1319 memory/space saving them.
1320
1321 - SSH protocol forced to 2; needed for ServerAliveInterval.
1322
1323 @param user User name to use for the ssh connection.
1324 @param port Port on the target host to use for ssh connection.
1325 @param opts Additional options to the ssh command.
1326 @param hosts_file Ignored.
1327 @param connect_timeout Ignored.
1328 @param alive_interval Ignored.
1329 """
Aviv Keshetc5947fa2013-09-04 14:06:29 -07001330 base_command = ('/usr/bin/ssh -a -x %s %s %s'
1331 ' -o StrictHostKeyChecking=no'
Fang Deng96667ca2013-08-01 17:46:18 -07001332 ' -o UserKnownHostsFile=/dev/null -o BatchMode=yes'
1333 ' -o ConnectTimeout=30 -o ServerAliveInterval=180'
1334 ' -o ServerAliveCountMax=3 -o ConnectionAttempts=4'
1335 ' -o Protocol=2 -l %s -p %d')
Aviv Keshetc5947fa2013-09-04 14:06:29 -07001336 return base_command % (self._ssh_verbosity_flag, self._ssh_options,
1337 opts, user, port)
Fang Deng96667ca2013-08-01 17:46:18 -07001338
1339
beeps32a63082013-08-22 14:02:29 -07001340 def _create_ssh_tunnel(self, port, local_port):
1341 """Create an ssh tunnel from local_port to port.
1342
1343 @param port: remote port on the host.
1344 @param local_port: local forwarding port.
1345
1346 @return: the tunnel process.
1347 """
1348 # Chrome OS on the target closes down most external ports
1349 # for security. We could open the port, but doing that
1350 # would conflict with security tests that check that only
1351 # expected ports are open. So, to get to the port on the
1352 # target we use an ssh tunnel.
1353 tunnel_options = '-n -N -q -L %d:localhost:%d' % (local_port, port)
1354 ssh_cmd = self.make_ssh_command(opts=tunnel_options)
1355 tunnel_cmd = '%s %s' % (ssh_cmd, self.hostname)
1356 logging.debug('Full tunnel command: %s', tunnel_cmd)
1357 tunnel_proc = subprocess.Popen(tunnel_cmd, shell=True, close_fds=True)
1358 logging.debug('Started ssh tunnel, local = %d'
1359 ' remote = %d, pid = %d',
1360 local_port, port, tunnel_proc.pid)
1361 return tunnel_proc
1362
1363
Christopher Wileydd181852013-10-10 19:56:58 -07001364 def _setup_rpc(self, port, command_name, remote_pid=None):
beeps32a63082013-08-22 14:02:29 -07001365 """Sets up a tunnel process and performs rpc connection book keeping.
1366
1367 This method assumes that xmlrpc and jsonrpc never conflict, since
1368 we can only either have an xmlrpc or a jsonrpc server listening on
1369 a remote port. As such, it enforces a single proxy->remote port
1370 policy, i.e if one starts a jsonrpc proxy/server from port A->B,
1371 and then tries to start an xmlrpc proxy forwarded to the same port,
1372 the xmlrpc proxy will override the jsonrpc tunnel process, however:
1373
1374 1. None of the methods on the xmlrpc proxy will work because
1375 the server listening on B is jsonrpc.
1376
1377 2. The xmlrpc client cannot initiate a termination of the JsonRPC
1378 server, as the only use case currently is goofy, which is tied to
1379 the factory image. It is much easier to handle a failed xmlrpc
1380 call on the client than it is to terminate goofy in this scenario,
1381 as doing the latter might leave the DUT in a hard to recover state.
1382
1383 With the current implementation newer rpc proxy connections will
1384 terminate the tunnel processes of older rpc connections tunneling
1385 to the same remote port. If methods are invoked on the client
1386 after this has happened they will fail with connection closed errors.
1387
1388 @param port: The remote forwarding port.
1389 @param command_name: The name of the remote process, to terminate
1390 using pkill.
1391
1392 @return A url that we can use to initiate the rpc connection.
1393 """
1394 self.rpc_disconnect(port)
1395 local_port = utils.get_unused_port()
1396 tunnel_proc = self._create_ssh_tunnel(port, local_port)
Christopher Wileydd181852013-10-10 19:56:58 -07001397 self._rpc_proxy_map[port] = (command_name, tunnel_proc, remote_pid)
beeps32a63082013-08-22 14:02:29 -07001398 return self._RPC_PROXY_URL % local_port
1399
1400
Christopher Wileyd78249a2013-03-01 13:05:31 -08001401 def xmlrpc_connect(self, command, port, command_name=None,
Yusuf Mohsinallyfff89d62013-11-18 16:34:07 -08001402 ready_test_name=None, timeout_seconds=10,
1403 logfile='/dev/null'):
J. Richard Barnette1d78b012012-05-15 13:56:30 -07001404 """Connect to an XMLRPC server on the host.
1405
1406 The `command` argument should be a simple shell command that
1407 starts an XMLRPC server on the given `port`. The command
1408 must not daemonize, and must terminate cleanly on SIGTERM.
1409 The command is started in the background on the host, and a
1410 local XMLRPC client for the server is created and returned
1411 to the caller.
1412
1413 Note that the process of creating an XMLRPC client makes no
1414 attempt to connect to the remote server; the caller is
1415 responsible for determining whether the server is running
1416 correctly, and is ready to serve requests.
1417
Christopher Wileyd78249a2013-03-01 13:05:31 -08001418 Optionally, the caller can pass ready_test_name, a string
1419 containing the name of a method to call on the proxy. This
1420 method should take no parameters and return successfully only
1421 when the server is ready to process client requests. When
1422 ready_test_name is set, xmlrpc_connect will block until the
1423 proxy is ready, and throw a TestError if the server isn't
1424 ready by timeout_seconds.
1425
beeps32a63082013-08-22 14:02:29 -07001426 If a server is already running on the remote port, this
1427 method will kill it and disconnect the tunnel process
1428 associated with the connection before establishing a new one,
1429 by consulting the rpc_proxy_map in rpc_disconnect.
1430
J. Richard Barnette1d78b012012-05-15 13:56:30 -07001431 @param command Shell command to start the server.
1432 @param port Port number on which the server is expected to
1433 be serving.
J. Richard Barnette7214e0b2013-02-06 15:20:49 -08001434 @param command_name String to use as input to `pkill` to
1435 terminate the XMLRPC server on the host.
Christopher Wileyd78249a2013-03-01 13:05:31 -08001436 @param ready_test_name String containing the name of a
1437 method defined on the XMLRPC server.
1438 @param timeout_seconds Number of seconds to wait
1439 for the server to become 'ready.' Will throw a
1440 TestFail error if server is not ready in time.
Yusuf Mohsinallyfff89d62013-11-18 16:34:07 -08001441 @param logfile Logfile to send output when running
1442 'command' argument.
Yusuf Mohsinally8d19e3c2013-11-21 14:25:45 -08001443
J. Richard Barnette1d78b012012-05-15 13:56:30 -07001444 """
Christopher Wileyc14f06a2013-10-16 13:55:39 -07001445 # Clean up any existing state. If the caller is willing
1446 # to believe their server is down, we ought to clean up
1447 # any tunnels we might have sitting around.
1448 self.rpc_disconnect(port)
J. Richard Barnette1d78b012012-05-15 13:56:30 -07001449 # Start the server on the host. Redirection in the command
1450 # below is necessary, because 'ssh' won't terminate until
1451 # background child processes close stdin, stdout, and
1452 # stderr.
Yusuf Mohsinallyfff89d62013-11-18 16:34:07 -08001453 remote_cmd = '%s </dev/null >%s 2>&1 & echo $!' % (command, logfile)
Christopher Wileydd181852013-10-10 19:56:58 -07001454 remote_pid = self.run(remote_cmd).stdout.rstrip('\n')
J. Richard Barnette1d78b012012-05-15 13:56:30 -07001455 logging.debug('Started XMLRPC server on host %s, pid = %s',
1456 self.hostname, remote_pid)
1457
Christopher Wileydd181852013-10-10 19:56:58 -07001458 # Tunnel through SSH to be able to reach that remote port.
1459 rpc_url = self._setup_rpc(port, command_name, remote_pid=remote_pid)
Christopher Wileyd78249a2013-03-01 13:05:31 -08001460 proxy = xmlrpclib.ServerProxy(rpc_url, allow_none=True)
Christopher Wileydd181852013-10-10 19:56:58 -07001461
Christopher Wileyd78249a2013-03-01 13:05:31 -08001462 if ready_test_name is not None:
J. Richard Barnette13eb7c02013-03-07 12:06:29 -08001463 # retry.retry logs each attempt; calculate delay_sec to
1464 # keep log spam to a dull roar.
Christopher Wiley0ed712b2013-04-09 15:25:12 -07001465 @retry.retry((socket.error,
1466 xmlrpclib.ProtocolError,
1467 httplib.BadStatusLine),
Chris Sosa65425082013-10-16 13:26:22 -07001468 timeout_min=timeout_seconds / 60.0,
1469 delay_sec=min(max(timeout_seconds / 20.0, 0.1), 1))
Christopher Wileyd78249a2013-03-01 13:05:31 -08001470 def ready_test():
1471 """ Call proxy.ready_test_name(). """
1472 getattr(proxy, ready_test_name)()
1473 successful = False
1474 try:
1475 logging.info('Waiting %d seconds for XMLRPC server '
1476 'to start.', timeout_seconds)
1477 ready_test()
1478 successful = True
Christopher Wileyd78249a2013-03-01 13:05:31 -08001479 finally:
1480 if not successful:
1481 logging.error('Failed to start XMLRPC server.')
beeps32a63082013-08-22 14:02:29 -07001482 self.rpc_disconnect(port)
Christopher Wileyd78249a2013-03-01 13:05:31 -08001483 logging.info('XMLRPC server started successfully.')
1484 return proxy
J. Richard Barnette1d78b012012-05-15 13:56:30 -07001485
J. Richard Barnette1d78b012012-05-15 13:56:30 -07001486
Jason Abeleb6f924f2013-11-13 16:01:54 -08001487 def syslog(self, message, tag='autotest'):
1488 """Logs a message to syslog on host.
1489
1490 @param message String message to log into syslog
1491 @param tag String tag prefix for syslog
1492
1493 """
1494 self.run('logger -t "%s" "%s"' % (tag, message))
1495
1496
beeps32a63082013-08-22 14:02:29 -07001497 def jsonrpc_connect(self, port):
1498 """Creates a jsonrpc proxy connection through an ssh tunnel.
1499
1500 This method exists to facilitate communication with goofy (which is
1501 the default system manager on all factory images) and as such, leaves
1502 most of the rpc server sanity checking to the caller. Unlike
1503 xmlrpc_connect, this method does not facilitate the creation of a remote
1504 jsonrpc server, as the only clients of this code are factory tests,
1505 for which the goofy system manager is built in to the image and starts
1506 when the target boots.
1507
1508 One can theoretically create multiple jsonrpc proxies all forwarded
1509 to the same remote port, provided the remote port has an rpc server
1510 listening. However, in doing so we stand the risk of leaking an
1511 existing tunnel process, so we always disconnect any older tunnels
1512 we might have through rpc_disconnect.
1513
1514 @param port: port on the remote host that is serving this proxy.
1515
1516 @return: The client proxy.
1517 """
1518 if not jsonrpclib:
1519 logging.warning('Jsonrpclib could not be imported. Check that '
1520 'site-packages contains jsonrpclib.')
1521 return None
1522
1523 proxy = jsonrpclib.jsonrpc.ServerProxy(self._setup_rpc(port, None))
1524
1525 logging.info('Established a jsonrpc connection through port %s.', port)
1526 return proxy
1527
1528
1529 def rpc_disconnect(self, port):
1530 """Disconnect from an RPC server on the host.
1531
1532 Terminates the remote RPC server previously started for
J. Richard Barnette1d78b012012-05-15 13:56:30 -07001533 the given `port`. Also closes the local ssh tunnel created
1534 for the connection to the host. This function does not
beeps32a63082013-08-22 14:02:29 -07001535 directly alter the state of a previously returned RPC
J. Richard Barnette1d78b012012-05-15 13:56:30 -07001536 client object; however disconnection will cause all
1537 subsequent calls to methods on the object to fail.
1538
1539 This function does nothing if requested to disconnect a port
beeps32a63082013-08-22 14:02:29 -07001540 that was not previously connected via _setup_rpc.
J. Richard Barnette1d78b012012-05-15 13:56:30 -07001541
1542 @param port Port number passed to a previous call to
beeps32a63082013-08-22 14:02:29 -07001543 `_setup_rpc()`.
J. Richard Barnette1d78b012012-05-15 13:56:30 -07001544 """
beeps32a63082013-08-22 14:02:29 -07001545 if port not in self._rpc_proxy_map:
J. Richard Barnette1d78b012012-05-15 13:56:30 -07001546 return
Christopher Wileydd181852013-10-10 19:56:58 -07001547 remote_name, tunnel_proc, remote_pid = self._rpc_proxy_map[port]
J. Richard Barnette1d78b012012-05-15 13:56:30 -07001548 if remote_name:
1549 # We use 'pkill' to find our target process rather than
1550 # a PID, because the host may have rebooted since
1551 # connecting, and we don't want to kill an innocent
1552 # process with the same PID.
1553 #
1554 # 'pkill' helpfully exits with status 1 if no target
1555 # process is found, for which run() will throw an
Simran Basid5e5e272012-09-24 15:23:59 -07001556 # exception. We don't want that, so we the ignore
J. Richard Barnette1d78b012012-05-15 13:56:30 -07001557 # status.
1558 self.run("pkill -f '%s'" % remote_name, ignore_status=True)
Christopher Wileydd181852013-10-10 19:56:58 -07001559 if remote_pid:
1560 logging.info('Waiting for RPC server "%s" shutdown',
1561 remote_name)
1562 start_time = time.time()
1563 while (time.time() - start_time <
1564 self._RPC_SHUTDOWN_TIMEOUT_SECONDS):
1565 running_processes = self.run(
1566 "pgrep -f '%s'" % remote_name,
1567 ignore_status=True).stdout.split()
1568 if not remote_pid in running_processes:
1569 logging.info('Shut down RPC server.')
1570 break
1571 time.sleep(self._RPC_SHUTDOWN_POLLING_PERIOD_SECONDS)
1572 else:
1573 raise error.TestError('Failed to shutdown RPC server %s' %
1574 remote_name)
J. Richard Barnette1d78b012012-05-15 13:56:30 -07001575
1576 if tunnel_proc.poll() is None:
1577 tunnel_proc.terminate()
1578 logging.debug('Terminated tunnel, pid %d', tunnel_proc.pid)
1579 else:
1580 logging.debug('Tunnel pid %d terminated early, status %d',
1581 tunnel_proc.pid, tunnel_proc.returncode)
beeps32a63082013-08-22 14:02:29 -07001582 del self._rpc_proxy_map[port]
J. Richard Barnette1d78b012012-05-15 13:56:30 -07001583
1584
beeps32a63082013-08-22 14:02:29 -07001585 def rpc_disconnect_all(self):
1586 """Disconnect all known RPC proxy ports."""
1587 for port in self._rpc_proxy_map.keys():
1588 self.rpc_disconnect(port)
J. Richard Barnette1d78b012012-05-15 13:56:30 -07001589
1590
Ilja H. Friedel1232e8a2014-06-17 21:30:48 -07001591 def poor_mans_rpc(self, fun):
1592 """
1593 Calls a function from client utils on the host and returns a string.
1594
1595 @param fun function in client utils namespace.
1596 @return output string from calling fun.
1597 """
Simran Basi263a9d32014-08-19 11:16:51 -07001598 script = 'cd %s/bin; ' % autotest.Autotest.get_installed_autodir(self)
Ilja H. Friedel1232e8a2014-06-17 21:30:48 -07001599 script += 'python -c "import common; import utils;'
1600 script += 'print utils.%s"' % fun
1601 return script
1602
1603
J. Richard Barnetteb6de7e32013-02-14 13:28:04 -08001604 def _ping_check_status(self, status):
1605 """Ping the host once, and return whether it has a given status.
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001606
J. Richard Barnetteb6de7e32013-02-14 13:28:04 -08001607 @param status Check the ping status against this value.
1608 @return True iff `status` and the result of ping are the same
1609 (i.e. both True or both False).
1610
1611 """
1612 ping_val = utils.ping(self.hostname, tries=1, deadline=1)
1613 return not (status ^ (ping_val == 0))
1614
1615 def _ping_wait_for_status(self, status, timeout):
1616 """Wait for the host to have a given status (UP or DOWN).
1617
1618 Status is checked by polling. Polling will not last longer
1619 than the number of seconds in `timeout`. The polling
1620 interval will be long enough that only approximately
1621 _PING_WAIT_COUNT polling cycles will be executed, subject
1622 to a maximum interval of about one minute.
1623
1624 @param status Waiting will stop immediately if `ping` of the
1625 host returns this status.
1626 @param timeout Poll for at most this many seconds.
1627 @return True iff the host status from `ping` matched the
1628 requested status at the time of return.
1629
1630 """
1631 # _ping_check_status() takes about 1 second, hence the
1632 # "- 1" in the formula below.
1633 poll_interval = min(int(timeout / self._PING_WAIT_COUNT), 60) - 1
1634 end_time = time.time() + timeout
1635 while time.time() <= end_time:
1636 if self._ping_check_status(status):
1637 return True
1638 if poll_interval > 0:
1639 time.sleep(poll_interval)
1640
1641 # The last thing we did was sleep(poll_interval), so it may
1642 # have been too long since the last `ping`. Check one more
1643 # time, just to be sure.
1644 return self._ping_check_status(status)
1645
1646 def ping_wait_up(self, timeout):
1647 """Wait for the host to respond to `ping`.
1648
1649 N.B. This method is not a reliable substitute for
1650 `wait_up()`, because a host that responds to ping will not
1651 necessarily respond to ssh. This method should only be used
1652 if the target DUT can be considered functional even if it
1653 can't be reached via ssh.
1654
1655 @param timeout Minimum time to allow before declaring the
1656 host to be non-responsive.
1657 @return True iff the host answered to ping before the timeout.
1658
1659 """
1660 return self._ping_wait_for_status(self._PING_STATUS_UP, timeout)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001661
Andrew Bresticker678c0c72013-01-22 10:44:09 -08001662 def ping_wait_down(self, timeout):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001663 """Wait until the host no longer responds to `ping`.
1664
J. Richard Barnetteb6de7e32013-02-14 13:28:04 -08001665 This function can be used as a slightly faster version of
1666 `wait_down()`, by avoiding potentially long ssh timeouts.
1667
1668 @param timeout Minimum time to allow for the host to become
1669 non-responsive.
1670 @return True iff the host quit answering ping before the
1671 timeout.
1672
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001673 """
J. Richard Barnetteb6de7e32013-02-14 13:28:04 -08001674 return self._ping_wait_for_status(self._PING_STATUS_DOWN, timeout)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001675
Tom Wai-Hong Tamfced4f62014-04-17 10:56:30 +08001676 def test_wait_for_sleep(self, sleep_timeout=None):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001677 """Wait for the client to enter low-power sleep mode.
1678
1679 The test for "is asleep" can't distinguish a system that is
1680 powered off; to confirm that the unit was asleep, it is
1681 necessary to force resume, and then call
1682 `test_wait_for_resume()`.
1683
1684 This function is expected to be called from a test as part
1685 of a sequence like the following:
1686
1687 ~~~~~~~~
1688 boot_id = host.get_boot_id()
1689 # trigger sleep on the host
1690 host.test_wait_for_sleep()
1691 # trigger resume on the host
1692 host.test_wait_for_resume(boot_id)
1693 ~~~~~~~~
1694
Tom Wai-Hong Tamfced4f62014-04-17 10:56:30 +08001695 @param sleep_timeout time limit in seconds to allow the host sleep.
1696
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001697 @exception TestFail The host did not go to sleep within
1698 the allowed time.
1699 """
Tom Wai-Hong Tamfced4f62014-04-17 10:56:30 +08001700 if sleep_timeout is None:
1701 sleep_timeout = self.SLEEP_TIMEOUT
1702
1703 if not self.ping_wait_down(timeout=sleep_timeout):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001704 raise error.TestFail(
Tom Wai-Hong Tamfced4f62014-04-17 10:56:30 +08001705 'client failed to sleep after %d seconds' % sleep_timeout)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001706
1707
Tom Wai-Hong Tamfced4f62014-04-17 10:56:30 +08001708 def test_wait_for_resume(self, old_boot_id, resume_timeout=None):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001709 """Wait for the client to resume from low-power sleep mode.
1710
1711 The `old_boot_id` parameter should be the value from
1712 `get_boot_id()` obtained prior to entering sleep mode. A
1713 `TestFail` exception is raised if the boot id changes.
1714
1715 See @ref test_wait_for_sleep for more on this function's
1716 usage.
1717
J. Richard Barnette7214e0b2013-02-06 15:20:49 -08001718 @param old_boot_id A boot id value obtained before the
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001719 target host went to sleep.
Tom Wai-Hong Tamfced4f62014-04-17 10:56:30 +08001720 @param resume_timeout time limit in seconds to allow the host up.
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001721
1722 @exception TestFail The host did not respond within the
1723 allowed time.
1724 @exception TestFail The host responded, but the boot id test
1725 indicated a reboot rather than a sleep
1726 cycle.
1727 """
Tom Wai-Hong Tamfced4f62014-04-17 10:56:30 +08001728 if resume_timeout is None:
1729 resume_timeout = self.RESUME_TIMEOUT
1730
1731 if not self.wait_up(timeout=resume_timeout):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001732 raise error.TestFail(
1733 'client failed to resume from sleep after %d seconds' %
Tom Wai-Hong Tamfced4f62014-04-17 10:56:30 +08001734 resume_timeout)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001735 else:
1736 new_boot_id = self.get_boot_id()
1737 if new_boot_id != old_boot_id:
1738 raise error.TestFail(
1739 'client rebooted, but sleep was expected'
1740 ' (old boot %s, new boot %s)'
1741 % (old_boot_id, new_boot_id))
1742
1743
1744 def test_wait_for_shutdown(self):
1745 """Wait for the client to shut down.
1746
1747 The test for "has shut down" can't distinguish a system that
1748 is merely asleep; to confirm that the unit was down, it is
1749 necessary to force boot, and then call test_wait_for_boot().
1750
1751 This function is expected to be called from a test as part
1752 of a sequence like the following:
1753
1754 ~~~~~~~~
1755 boot_id = host.get_boot_id()
1756 # trigger shutdown on the host
1757 host.test_wait_for_shutdown()
1758 # trigger boot on the host
1759 host.test_wait_for_boot(boot_id)
1760 ~~~~~~~~
1761
1762 @exception TestFail The host did not shut down within the
1763 allowed time.
1764 """
Andrew Bresticker678c0c72013-01-22 10:44:09 -08001765 if not self.ping_wait_down(timeout=self.SHUTDOWN_TIMEOUT):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001766 raise error.TestFail(
1767 'client failed to shut down after %d seconds' %
J. Richard Barnetteeb69d722012-06-18 17:29:44 -07001768 self.SHUTDOWN_TIMEOUT)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001769
1770
1771 def test_wait_for_boot(self, old_boot_id=None):
1772 """Wait for the client to boot from cold power.
1773
1774 The `old_boot_id` parameter should be the value from
1775 `get_boot_id()` obtained prior to shutting down. A
1776 `TestFail` exception is raised if the boot id does not
1777 change. The boot id test is omitted if `old_boot_id` is not
1778 specified.
1779
1780 See @ref test_wait_for_shutdown for more on this function's
1781 usage.
1782
J. Richard Barnette7214e0b2013-02-06 15:20:49 -08001783 @param old_boot_id A boot id value obtained before the
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001784 shut down.
1785
1786 @exception TestFail The host did not respond within the
1787 allowed time.
1788 @exception TestFail The host responded, but the boot id test
1789 indicated that there was no reboot.
1790 """
J. Richard Barnetteeb69d722012-06-18 17:29:44 -07001791 if not self.wait_up(timeout=self.REBOOT_TIMEOUT):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001792 raise error.TestFail(
1793 'client failed to reboot after %d seconds' %
J. Richard Barnetteeb69d722012-06-18 17:29:44 -07001794 self.REBOOT_TIMEOUT)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001795 elif old_boot_id:
1796 if self.get_boot_id() == old_boot_id:
1797 raise error.TestFail(
1798 'client is back up, but did not reboot'
1799 ' (boot %s)' % old_boot_id)
Simran Basid5e5e272012-09-24 15:23:59 -07001800
1801
1802 @staticmethod
1803 def check_for_rpm_support(hostname):
1804 """For a given hostname, return whether or not it is powered by an RPM.
1805
Simran Basi1df55112013-09-06 11:25:09 -07001806 @param hostname: hostname to check for rpm support.
1807
Simran Basid5e5e272012-09-24 15:23:59 -07001808 @return None if this host does not follows the defined naming format
1809 for RPM powered DUT's in the lab. If it does follow the format,
1810 it returns a regular expression MatchObject instead.
1811 """
Fang Deng0ca40e22013-08-27 17:47:44 -07001812 return re.match(CrosHost._RPM_HOSTNAME_REGEX, hostname)
Simran Basid5e5e272012-09-24 15:23:59 -07001813
1814
1815 def has_power(self):
1816 """For this host, return whether or not it is powered by an RPM.
1817
1818 @return True if this host is in the CROS lab and follows the defined
1819 naming format.
1820 """
Fang Deng0ca40e22013-08-27 17:47:44 -07001821 return CrosHost.check_for_rpm_support(self.hostname)
Simran Basid5e5e272012-09-24 15:23:59 -07001822
1823
Ismail Noorbasha07fdb612013-02-14 14:13:31 -08001824 def _set_power(self, state, power_method):
1825 """Sets the power to the host via RPM, Servo or manual.
1826
1827 @param state Specifies which power state to set to DUT
1828 @param power_method Specifies which method of power control to
1829 use. By default "RPM" will be used. Valid values
1830 are the strings "RPM", "manual", "servoj10".
1831
1832 """
1833 ACCEPTABLE_STATES = ['ON', 'OFF']
1834
1835 if state.upper() not in ACCEPTABLE_STATES:
1836 raise error.TestError('State must be one of: %s.'
1837 % (ACCEPTABLE_STATES,))
1838
1839 if power_method == self.POWER_CONTROL_SERVO:
1840 logging.info('Setting servo port J10 to %s', state)
1841 self.servo.set('prtctl3_pwren', state.lower())
1842 time.sleep(self._USB_POWER_TIMEOUT)
1843 elif power_method == self.POWER_CONTROL_MANUAL:
1844 logging.info('You have %d seconds to set the AC power to %s.',
1845 self._POWER_CYCLE_TIMEOUT, state)
1846 time.sleep(self._POWER_CYCLE_TIMEOUT)
1847 else:
1848 if not self.has_power():
1849 raise error.TestFail('DUT does not have RPM connected.')
Simran Basi5e6339a2013-03-21 11:34:32 -07001850 afe = frontend_wrappers.RetryingAFE(timeout_min=5, delay_sec=10)
1851 afe.set_host_attribute(self._RPM_OUTLET_CHANGED, True,
1852 hostname=self.hostname)
Simran Basi1df55112013-09-06 11:25:09 -07001853 rpm_client.set_power(self.hostname, state.upper(), timeout_mins=5)
Simran Basid5e5e272012-09-24 15:23:59 -07001854
1855
Ismail Noorbasha07fdb612013-02-14 14:13:31 -08001856 def power_off(self, power_method=POWER_CONTROL_RPM):
1857 """Turn off power to this host via RPM, Servo or manual.
1858
1859 @param power_method Specifies which method of power control to
1860 use. By default "RPM" will be used. Valid values
1861 are the strings "RPM", "manual", "servoj10".
1862
1863 """
1864 self._set_power('OFF', power_method)
Simran Basid5e5e272012-09-24 15:23:59 -07001865
1866
Ismail Noorbasha07fdb612013-02-14 14:13:31 -08001867 def power_on(self, power_method=POWER_CONTROL_RPM):
1868 """Turn on power to this host via RPM, Servo or manual.
1869
1870 @param power_method Specifies which method of power control to
1871 use. By default "RPM" will be used. Valid values
1872 are the strings "RPM", "manual", "servoj10".
1873
1874 """
1875 self._set_power('ON', power_method)
1876
1877
1878 def power_cycle(self, power_method=POWER_CONTROL_RPM):
1879 """Cycle power to this host by turning it OFF, then ON.
1880
1881 @param power_method Specifies which method of power control to
1882 use. By default "RPM" will be used. Valid values
1883 are the strings "RPM", "manual", "servoj10".
1884
1885 """
1886 if power_method in (self.POWER_CONTROL_SERVO,
1887 self.POWER_CONTROL_MANUAL):
1888 self.power_off(power_method=power_method)
1889 time.sleep(self._POWER_CYCLE_TIMEOUT)
1890 self.power_on(power_method=power_method)
1891 else:
1892 rpm_client.set_power(self.hostname, 'CYCLE')
Simran Basic6f1f7a2012-10-16 10:47:46 -07001893
1894
1895 def get_platform(self):
1896 """Determine the correct platform label for this host.
1897
1898 @returns a string representing this host's platform.
1899 """
1900 crossystem = utils.Crossystem(self)
1901 crossystem.init()
1902 # Extract fwid value and use the leading part as the platform id.
1903 # fwid generally follow the format of {platform}.{firmware version}
1904 # Example: Alex.X.YYY.Z or Google_Alex.X.YYY.Z
1905 platform = crossystem.fwid().split('.')[0].lower()
1906 # Newer platforms start with 'Google_' while the older ones do not.
1907 return platform.replace('google_', '')
1908
1909
Hung-ying Tyanb1328032014-04-01 14:18:54 +08001910 def get_architecture(self):
1911 """Determine the correct architecture label for this host.
1912
1913 @returns a string representing this host's architecture.
1914 """
1915 crossystem = utils.Crossystem(self)
1916 crossystem.init()
1917 return crossystem.arch()
1918
1919
Luis Lozano40b7d0d2014-01-17 15:12:06 -08001920 def get_chrome_version(self):
1921 """Gets the Chrome version number and milestone as strings.
1922
1923 Invokes "chrome --version" to get the version number and milestone.
1924
1925 @return A tuple (chrome_ver, milestone) where "chrome_ver" is the
1926 current Chrome version number as a string (in the form "W.X.Y.Z")
1927 and "milestone" is the first component of the version number
1928 (the "W" from "W.X.Y.Z"). If the version number cannot be parsed
1929 in the "W.X.Y.Z" format, the "chrome_ver" will be the full output
1930 of "chrome --version" and the milestone will be the empty string.
1931
1932 """
1933 version_string = self.run(constants.CHROME_VERSION_COMMAND).stdout
1934 return utils.parse_chrome_version(version_string)
1935
Aviv Keshet74c89a92013-02-04 15:18:30 -08001936 @label_decorator()
Simran Basic6f1f7a2012-10-16 10:47:46 -07001937 def get_board(self):
1938 """Determine the correct board label for this host.
1939
1940 @returns a string representing this host's board.
1941 """
1942 release_info = utils.parse_cmd_output('cat /etc/lsb-release',
1943 run_method=self.run)
1944 board = release_info['CHROMEOS_RELEASE_BOARD']
1945 # Devices in the lab generally have the correct board name but our own
1946 # development devices have {board_name}-signed-{key_type}. The board
1947 # name may also begin with 'x86-' which we need to keep.
Simran Basi833814b2013-01-29 13:13:43 -08001948 board_format_string = ds_constants.BOARD_PREFIX + '%s'
Simran Basic6f1f7a2012-10-16 10:47:46 -07001949 if 'x86' not in board:
Simran Basi833814b2013-01-29 13:13:43 -08001950 return board_format_string % board.split('-')[0]
1951 return board_format_string % '-'.join(board.split('-')[0:2])
Simran Basic6f1f7a2012-10-16 10:47:46 -07001952
1953
Ilja H. Friedel1232e8a2014-06-17 21:30:48 -07001954 @label_decorator('board_freq_mem')
1955 def get_board_with_frequency_and_memory(self):
1956 """
1957 Determines the board name with frequency and memory.
1958
1959 @returns a more detailed string representing the board. Examples are
1960 butterfly_1.1GHz_2GB, link_1.8GHz_4GB, x86-zgb_1.7GHz_2GB
1961 """
1962 board = self.run(self.poor_mans_rpc(
1963 'get_board_with_frequency_and_memory()')).stdout
1964 return 'board_freq_mem:%s' % str.strip(board)
1965
1966
Aviv Keshet74c89a92013-02-04 15:18:30 -08001967 @label_decorator('lightsensor')
Simran Basic6f1f7a2012-10-16 10:47:46 -07001968 def has_lightsensor(self):
1969 """Determine the correct board label for this host.
1970
1971 @returns the string 'lightsensor' if this host has a lightsensor or
1972 None if it does not.
1973 """
1974 search_cmd = "find -L %s -maxdepth 4 | egrep '%s'" % (
Richard Barnette82c35912012-11-20 10:09:10 -08001975 self._LIGHTSENSOR_SEARCH_DIR, '|'.join(self._LIGHTSENSOR_FILES))
Simran Basic6f1f7a2012-10-16 10:47:46 -07001976 try:
1977 # Run the search cmd following the symlinks. Stderr_tee is set to
1978 # None as there can be a symlink loop, but the command will still
1979 # execute correctly with a few messages printed to stderr.
1980 self.run(search_cmd, stdout_tee=None, stderr_tee=None)
1981 return 'lightsensor'
1982 except error.AutoservRunError:
1983 # egrep exited with a return code of 1 meaning none of the possible
1984 # lightsensor files existed.
1985 return None
1986
1987
Aviv Keshet74c89a92013-02-04 15:18:30 -08001988 @label_decorator('bluetooth')
Simran Basic6f1f7a2012-10-16 10:47:46 -07001989 def has_bluetooth(self):
1990 """Determine the correct board label for this host.
1991
1992 @returns the string 'bluetooth' if this host has bluetooth or
1993 None if it does not.
1994 """
1995 try:
1996 self.run('test -d /sys/class/bluetooth/hci0')
1997 # test exited with a return code of 0.
1998 return 'bluetooth'
1999 except error.AutoservRunError:
2000 # test exited with a return code 1 meaning the directory did not
2001 # exist.
2002 return None
2003
2004
Ilja H. Friedel1232e8a2014-06-17 21:30:48 -07002005 @label_decorator('gpu_family')
2006 def get_gpu_family(self):
2007 """
2008 Determine GPU family.
2009
2010 @returns a string representing the gpu family. Examples are mali, tegra,
2011 pinetrail, sandybridge, ivybridge, haswell and baytrail.
2012 """
2013 gpu_family = self.run(self.poor_mans_rpc('get_gpu_family()')).stdout
2014 return 'gpu_family:%s' % str.strip(gpu_family)
2015
2016
Ilja Friedel0ce0b602013-08-15 18:45:27 -07002017 @label_decorator('graphics')
2018 def get_graphics(self):
2019 """
2020 Determine the correct board label for this host.
2021
2022 @returns a string representing this host's graphics. For now ARM boards
2023 return graphics:gles while all other boards return graphics:gl. This
2024 may change over time, but for robustness reasons this should avoid
2025 executing code in actual graphics libraries (which may not be ready and
2026 is tested by graphics_GLAPICheck).
2027 """
2028 uname = self.run('uname -a').stdout.lower()
2029 if 'arm' in uname:
2030 return 'graphics:gles'
2031 return 'graphics:gl'
2032
2033
Bill Richardson4f595f52014-02-13 16:20:26 -08002034 @label_decorator('ec')
2035 def get_ec(self):
2036 """
2037 Determine the type of EC on this host.
2038
2039 @returns a string representing this host's embedded controller type.
2040 At present, it only returns "ec:cros", for Chrome OS ECs. Other types
2041 of EC (or none) don't return any strings, since no tests depend on
2042 those.
2043 """
2044 cmd = 'mosys ec info'
2045 # The output should look like these, so that the last field should
2046 # match our EC version scheme:
2047 #
2048 # stm | stm32f100 | snow_v1.3.139-375eb9f
2049 # ti | Unknown-10de | peppy_v1.5.114-5d52788
2050 #
2051 # Non-Chrome OS ECs will look like these:
2052 #
2053 # ENE | KB932 | 00BE107A00
2054 # ite | it8518 | 3.08
2055 #
2056 # And some systems don't have ECs at all (Lumpy, for example).
2057 regexp = r'^.*\|\s*(\S+_v\d+\.\d+\.\d+-[0-9a-f]+)\s*$'
2058
2059 ecinfo = self.run(command=cmd, ignore_status=True)
2060 if ecinfo.exit_status == 0:
2061 res = re.search(regexp, ecinfo.stdout)
2062 if res:
2063 logging.info("EC version is %s", res.groups()[0])
2064 return 'ec:cros'
2065 logging.info("%s got: %s", cmd, ecinfo.stdout)
2066 # Has an EC, but it's not a Chrome OS EC
2067 return None
2068 logging.info("%s exited with status %d", cmd, ecinfo.exit_status)
2069 # No EC present
2070 return None
2071
2072
Alec Berg31b932b2014-04-04 16:09:11 -07002073 @label_decorator('accels')
2074 def get_accels(self):
2075 """
2076 Determine the type of accelerometers on this host.
2077
2078 @returns a string representing this host's accelerometer type.
2079 At present, it only returns "accel:cros-ec", for accelerometers
2080 attached to a Chrome OS EC, or none, if no accelerometers.
2081 """
2082 # Check to make sure we have ectool
2083 rv = self.run('which ectool', ignore_status=True)
2084 if rv.exit_status:
2085 logging.info("No ectool cmd found, assuming no EC accelerometers")
2086 return None
2087
2088 # Check that the EC supports the motionsense command
2089 rv = self.run('ectool motionsense', ignore_status=True)
2090 if rv.exit_status:
2091 logging.info("EC does not support motionsense command "
2092 "assuming no EC accelerometers")
2093 return None
2094
2095 # Check that EC motion sensors are active
2096 active = self.run('ectool motionsense active').stdout.split('\n')
2097 if active[0] == "0":
2098 logging.info("Motion sense inactive, assuming no EC accelerometers")
2099 return None
2100
2101 logging.info("EC accelerometers found")
2102 return 'accel:cros-ec'
2103
2104
Tom Wai-Hong Tam3d6790d2014-04-14 16:15:47 +08002105 @label_decorator('chameleon')
2106 def has_chameleon(self):
2107 """Determine if a Chameleon connected to this host.
2108
Tom Wai-Hong Tam3d75ebc2014-08-12 08:57:25 +08002109 @returns the string 'chameleon:' + label, e.g. 'chameleon:hdmi',
2110 if this host has a Chameleon or None if it has not.
Tom Wai-Hong Tam3d6790d2014-04-14 16:15:47 +08002111 """
2112 if self._chameleon_host:
Tom Wai-Hong Tam3d75ebc2014-08-12 08:57:25 +08002113 return 'chameleon:' + self.chameleon.get_label()
Tom Wai-Hong Tam3d6790d2014-04-14 16:15:47 +08002114 else:
2115 return None
2116
2117
Derek Basehorec71ff622014-07-07 15:18:40 -07002118 @label_decorator('power_supply')
2119 def get_power_supply(self):
2120 """
2121 Determine what type of power supply the host has
2122
2123 @returns a string representing this host's power supply.
2124 'power:battery' when the device has a battery intended for
2125 extended use
2126 'power:AC_primary' when the device has a battery not intended
2127 for extended use (for moving the machine, etc)
2128 'power:AC_only' when the device has no battery at all.
2129 """
2130 psu = self.run(command='mosys psu type', ignore_status=True)
2131 if psu.exit_status:
2132 # The psu command for mosys is not included for all platforms. The
2133 # assumption is that the device will have a battery if the command
2134 # is not found.
2135 return 'power:battery'
2136
2137 psu_str = psu.stdout.strip()
2138 if psu_str == 'unknown':
2139 return None
2140
2141 return 'power:%s' % psu_str
2142
2143
Puthikorn Voravootivatfa011242014-03-14 18:45:11 -07002144 @label_decorator('storage')
2145 def get_storage(self):
2146 """
2147 Determine the type of boot device for this host.
2148
2149 Determine if the internal device is SCSI or dw_mmc device.
2150 Then check that it is SSD or HDD or eMMC or something else.
2151
2152 @returns a string representing this host's internal device type.
2153 'storage:ssd' when internal device is solid state drive
2154 'storage:hdd' when internal device is hard disk drive
2155 'storage:mmc' when internal device is mmc drive
2156 None When internal device is something else or
2157 when we are unable to determine the type
2158 """
2159 # The output should be /dev/mmcblk* for SD/eMMC or /dev/sd* for scsi
2160 rootdev_cmd = ' '.join(['. /usr/sbin/write_gpt.sh;',
2161 '. /usr/share/misc/chromeos-common.sh;',
2162 'load_base_vars;',
2163 'get_fixed_dst_drive'])
Puthikorn Voravootivat03c51682014-04-24 13:52:12 -07002164 rootdev = self.run(command=rootdev_cmd, ignore_status=True)
2165 if rootdev.exit_status:
2166 logging.info("Fail to run %s", rootdev_cmd)
2167 return None
Puthikorn Voravootivatfa011242014-03-14 18:45:11 -07002168 rootdev_str = rootdev.stdout.strip()
2169
2170 if not rootdev_str:
2171 return None
2172
2173 rootdev_base = os.path.basename(rootdev_str)
2174
2175 mmc_pattern = '/dev/mmcblk[0-9]'
2176 if re.match(mmc_pattern, rootdev_str):
2177 # Use type to determine if the internal device is eMMC or somthing
2178 # else. We can assume that MMC is always an internal device.
2179 type_cmd = 'cat /sys/block/%s/device/type' % rootdev_base
Puthikorn Voravootivat03c51682014-04-24 13:52:12 -07002180 type = self.run(command=type_cmd, ignore_status=True)
2181 if type.exit_status:
2182 logging.info("Fail to run %s", type_cmd)
2183 return None
Puthikorn Voravootivatfa011242014-03-14 18:45:11 -07002184 type_str = type.stdout.strip()
2185
2186 if type_str == 'MMC':
2187 return 'storage:mmc'
2188
2189 scsi_pattern = '/dev/sd[a-z]+'
2190 if re.match(scsi_pattern, rootdev.stdout):
2191 # Read symlink for /sys/block/sd* to determine if the internal
2192 # device is connected via ata or usb.
2193 link_cmd = 'readlink /sys/block/%s' % rootdev_base
Puthikorn Voravootivat03c51682014-04-24 13:52:12 -07002194 link = self.run(command=link_cmd, ignore_status=True)
2195 if link.exit_status:
2196 logging.info("Fail to run %s", link_cmd)
2197 return None
Puthikorn Voravootivatfa011242014-03-14 18:45:11 -07002198 link_str = link.stdout.strip()
2199 if 'usb' in link_str:
2200 return None
2201
2202 # Read rotation to determine if the internal device is ssd or hdd.
2203 rotate_cmd = str('cat /sys/block/%s/queue/rotational'
2204 % rootdev_base)
Puthikorn Voravootivat03c51682014-04-24 13:52:12 -07002205 rotate = self.run(command=rotate_cmd, ignore_status=True)
2206 if rotate.exit_status:
2207 logging.info("Fail to run %s", rotate_cmd)
2208 return None
Puthikorn Voravootivatfa011242014-03-14 18:45:11 -07002209 rotate_str = rotate.stdout.strip()
2210
2211 rotate_dict = {'0':'storage:ssd', '1':'storage:hdd'}
2212 return rotate_dict.get(rotate_str)
2213
2214 # All other internal device / error case will always fall here
2215 return None
2216
2217
Dan Shi4e9a2aa2014-03-24 14:28:42 -07002218 @label_decorator('servo')
2219 def get_servo(self):
2220 """Determine if the host has a servo attached.
2221
2222 If the host has a working servo attached, it should have a servo label.
2223
2224 @return: string 'servo' if the host has servo attached. Otherwise,
2225 returns None.
2226 """
2227 return 'servo' if self._servo_host else None
2228
2229
Dan Shi5beba472014-05-28 22:46:07 -07002230 @label_decorator('video_labels')
2231 def get_video_labels(self):
2232 """Run /usr/local/bin/avtest_label_detect to get a list of video labels.
2233
2234 Sample output of avtest_label_detect:
2235 Detected label: hw_video_acc_vp8
2236 Detected label: webcam
2237
2238 @return: A list of labels detected by tool avtest_label_detect.
2239 """
2240 try:
Simran Basi40ca8182014-07-17 18:41:20 -07002241 # TODO (sbasi) crbug.com/391081 - Remove once the proper fix has
2242 # landed and supporting images older than the fix is no longer
2243 # necessary.
2244 # Change back to VT1 so avtest_label_detect does not get stuck.
2245 self.run('chvt 1')
Dan Shi5beba472014-05-28 22:46:07 -07002246 result = self.run('/usr/local/bin/avtest_label_detect').stdout
2247 return re.findall('^Detected label: (\w+)$', result, re.M)
2248 except error.AutoservRunError:
2249 # The tool is not installed.
2250 return []
2251
2252
mussa584b4462014-06-20 15:13:28 -07002253 @label_decorator('video_glitch_detection')
2254 def is_video_glitch_detection_supported(self):
2255 """ Determine if a board under test is supported for video glitch
2256 detection tests.
2257
2258 @return: 'video_glitch_detection' if board is supported, None otherwise.
2259 """
2260 parser = ConfigParser.SafeConfigParser()
2261 filename = os.path.join(
2262 common.autotest_dir, 'client/cros/video/device_spec.conf')
2263
2264 dut = self.get_board().replace(ds_constants.BOARD_PREFIX, '')
2265
2266 try:
2267 parser.read(filename)
mussa584b4462014-06-20 15:13:28 -07002268 supported_boards = parser.sections()
2269
Mussa2cba43a2014-07-24 10:38:08 -07002270 # Some boards have multiple resolutions. e.g: nyan_big has standard
2271 # and high definitions. The conf file has something like nyan_big_sd
2272
2273 for board in supported_boards:
2274 if board.startswith(dut):
2275 return 'video_glitch_detection'
2276
2277 return None
mussa584b4462014-06-20 15:13:28 -07002278
2279 except ConfigParser.error:
2280 # something went wrong while parsing the conf file
2281 return None
2282
Katherine Threlkeld7b97a9f2014-06-24 13:47:14 -07002283 @label_decorator('touch_labels')
2284 def get_touch(self):
2285 """
2286 Determine whether board under test has a touchpad or touchscreen.
2287
2288 @return: A list of some combination of 'touchscreen' and 'touchpad',
2289 depending on what is present on the device.
2290 """
2291 labels = []
2292 input_cmd = '/opt/google/input/inputcontrol --names -t %s'
2293 for elt in ['touchpad', 'touchscreen']:
2294 if self.run(input_cmd % elt).stdout:
2295 labels.append(elt)
2296 return labels
2297
2298
mussa584b4462014-06-20 15:13:28 -07002299
Simran Basic6f1f7a2012-10-16 10:47:46 -07002300 def get_labels(self):
2301 """Return a list of labels for this given host.
2302
2303 This is the main way to retrieve all the automatic labels for a host
2304 as it will run through all the currently implemented label functions.
2305 """
2306 labels = []
Richard Barnette82c35912012-11-20 10:09:10 -08002307 for label_function in self._LABEL_FUNCTIONS:
J. Richard Barnetteb869b222014-09-03 17:55:44 -07002308 try:
2309 label = label_function(self)
2310 except Exception as e:
2311 logging.error('Label function %s failed; ignoring it.',
2312 label_function.__name__)
2313 logging.exception(e)
2314 label = None
Simran Basic6f1f7a2012-10-16 10:47:46 -07002315 if label:
Dan Shi5beba472014-05-28 22:46:07 -07002316 if type(label) is str:
2317 labels.append(label)
2318 elif type(label) is list:
2319 labels.extend(label)
Simran Basic6f1f7a2012-10-16 10:47:46 -07002320 return labels
Dan Shi85276d42014-04-08 22:11:45 -07002321
2322
2323 def is_boot_from_usb(self):
2324 """Check if DUT is boot from USB.
2325
2326 @return: True if DUT is boot from usb.
2327 """
2328 device = self.run('rootdev -s -d').stdout.strip()
2329 removable = int(self.run('cat /sys/block/%s/removable' %
2330 os.path.basename(device)).stdout.strip())
2331 return removable == 1