blob: 29bf814f43139ec647e5dd745de56bbf510f9972 [file] [log] [blame]
J. Richard Barnette24adbf42012-04-11 15:04:53 -07001# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
Dale Curtisaa5eedb2011-08-23 16:18:52 -07002# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
Aviv Keshet74c89a92013-02-04 15:18:30 -08005import functools
J. Richard Barnette1d78b012012-05-15 13:56:30 -07006import logging
Simran Basid5e5e272012-09-24 15:23:59 -07007import re
J. Richard Barnette1d78b012012-05-15 13:56:30 -07008import subprocess
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07009import time
J. Richard Barnette1d78b012012-05-15 13:56:30 -070010import xmlrpclib
J. Richard Barnette134ec2c2012-04-25 12:59:37 -070011
J. Richard Barnette45e93de2012-04-11 17:24:15 -070012from autotest_lib.client.bin import utils
Richard Barnette0c73ffc2012-11-19 15:21:18 -080013from autotest_lib.client.common_lib import error
14from autotest_lib.client.common_lib import global_config
J. Richard Barnette45e93de2012-04-11 17:24:15 -070015from autotest_lib.client.common_lib.cros import autoupdater
Richard Barnette03a0c132012-11-05 12:40:35 -080016from autotest_lib.client.common_lib.cros import dev_server
Richard Barnette82c35912012-11-20 10:09:10 -080017from autotest_lib.client.cros import constants
J. Richard Barnette45e93de2012-04-11 17:24:15 -070018from autotest_lib.server import autoserv_parser
Chris Sosaf4d43ff2012-10-30 11:21:05 -070019from autotest_lib.server import autotest
J. Richard Barnette45e93de2012-04-11 17:24:15 -070020from autotest_lib.server import site_host_attributes
J. Richard Barnette67ccb872012-04-19 16:34:56 -070021from autotest_lib.server.cros import servo
Scott Zawalski89c44dd2013-02-26 09:28:02 -050022from autotest_lib.server.cros.dynamic_suite import constants as ds_constants
23from autotest_lib.server.cros.dynamic_suite import tools
J. Richard Barnette45e93de2012-04-11 17:24:15 -070024from autotest_lib.server.hosts import remote
Simran Basidcff4252012-11-20 16:13:20 -080025from autotest_lib.site_utils.rpm_control_system import rpm_client
Simran Basid5e5e272012-09-24 15:23:59 -070026
Richard Barnette82c35912012-11-20 10:09:10 -080027# Importing frontend.afe.models requires a full Autotest
28# installation (with the Django modules), not just the source
29# repository. Most developers won't have the full installation, so
30# the imports below will fail for them.
31#
32# The fix is to catch import exceptions, and set `models` to `None`
33# on failure. This has the side effect that
34# SiteHost._get_board_from_afe() will fail: That will manifest as
35# failures during Repair jobs leaving the DUT as "Repair Failed".
36# In practice, you can't test Repair jobs without a full
37# installation, so that kind of failure isn't expected.
38try:
J. Richard Barnette7214e0b2013-02-06 15:20:49 -080039 # pylint: disable=W0611
Richard Barnette82c35912012-11-20 10:09:10 -080040 from autotest_lib.frontend import setup_django_environment
41 from autotest_lib.frontend.afe import models
42except:
43 models = None
44
Simran Basid5e5e272012-09-24 15:23:59 -070045
J. Richard Barnettebe5ebcc2013-02-11 16:03:15 -080046def _make_servo_hostname(hostname):
47 host_parts = hostname.split('.')
48 host_parts[0] = host_parts[0] + '-servo'
49 return '.'.join(host_parts)
50
51
52def _get_lab_servo(target_hostname):
53 """Instantiate a Servo for |target_hostname| in the lab.
54
55 Assuming that |target_hostname| is a device in the CrOS test
56 lab, create and return a Servo object pointed at the servo
57 attached to that DUT. The servo in the test lab is assumed
58 to already have servod up and running on it.
59
60 @param target_hostname: device whose servo we want to target.
61 @return an appropriately configured Servo instance.
62 """
63 servo_host = _make_servo_hostname(target_hostname)
64 if utils.host_is_in_lab_zone(servo_host):
65 try:
J. Richard Barnetted5f807a2013-02-11 16:51:00 -080066 return servo.Servo(servo_host=servo_host)
J. Richard Barnettebe5ebcc2013-02-11 16:03:15 -080067 except: # pylint: disable=W0702
68 # TODO(jrbarnette): Long-term, if we can't get to
69 # a servo in the lab, we want to fail, so we should
70 # pass any exceptions along. Short-term, we're not
71 # ready to rely on servo, so we ignore failures.
72 pass
73 return None
74
75
Dale Curtiscb7bfaf2011-06-07 16:21:57 -070076def make_ssh_command(user='root', port=22, opts='', hosts_file=None,
77 connect_timeout=None, alive_interval=None):
78 """Override default make_ssh_command to use options tuned for Chrome OS.
79
80 Tuning changes:
Chris Sosaf7fcd6e2011-09-27 17:30:47 -070081 - ConnectTimeout=30; maximum of 30 seconds allowed for an SSH connection
82 failure. Consistency with remote_access.sh.
Dale Curtiscb7bfaf2011-06-07 16:21:57 -070083
Dale Curtisaa5eedb2011-08-23 16:18:52 -070084 - ServerAliveInterval=180; which causes SSH to ping connection every
85 180 seconds. In conjunction with ServerAliveCountMax ensures that if the
86 connection dies, Autotest will bail out quickly. Originally tried 60 secs,
87 but saw frequent job ABORTS where the test completed successfully.
Dale Curtiscb7bfaf2011-06-07 16:21:57 -070088
Chris Sosaf7fcd6e2011-09-27 17:30:47 -070089 - ServerAliveCountMax=3; consistency with remote_access.sh.
90
91 - ConnectAttempts=4; reduce flakiness in connection errors; consistency
92 with remote_access.sh.
Dale Curtiscb7bfaf2011-06-07 16:21:57 -070093
94 - UserKnownHostsFile=/dev/null; we don't care about the keys. Host keys
95 change with every new installation, don't waste memory/space saving them.
Chris Sosaf7fcd6e2011-09-27 17:30:47 -070096
97 - SSH protocol forced to 2; needed for ServerAliveInterval.
J. Richard Barnette7214e0b2013-02-06 15:20:49 -080098
99 @param user User name to use for the ssh connection.
100 @param port Port on the target host to use for ssh connection.
101 @param opts Additional options to the ssh command.
102 @param hosts_file Ignored.
103 @param connect_timeout Ignored.
104 @param alive_interval Ignored.
Dale Curtiscb7bfaf2011-06-07 16:21:57 -0700105 """
106 base_command = ('/usr/bin/ssh -a -x %s -o StrictHostKeyChecking=no'
107 ' -o UserKnownHostsFile=/dev/null -o BatchMode=yes'
Chris Sosaf7fcd6e2011-09-27 17:30:47 -0700108 ' -o ConnectTimeout=30 -o ServerAliveInterval=180'
109 ' -o ServerAliveCountMax=3 -o ConnectionAttempts=4'
110 ' -o Protocol=2 -l %s -p %d')
Dale Curtiscb7bfaf2011-06-07 16:21:57 -0700111 return base_command % (opts, user, port)
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700112
113
J. Richard Barnette7214e0b2013-02-06 15:20:49 -0800114
Aviv Keshet74c89a92013-02-04 15:18:30 -0800115def add_label_detector(label_function_list, label_list=None, label=None):
116 """Decorator used to group functions together into the provided list.
117 @param label_function_list: List of label detecting functions to add
118 decorated function to.
119 @param label_list: List of detectable labels to add detectable labels to.
120 (Default: None)
121 @param label: Label string that is detectable by this detection function
122 (Default: None)
J. Richard Barnette7214e0b2013-02-06 15:20:49 -0800123 """
Simran Basic6f1f7a2012-10-16 10:47:46 -0700124 def add_func(func):
Aviv Keshet74c89a92013-02-04 15:18:30 -0800125 """
126 @param func: The function to be added as a detector.
127 """
128 label_function_list.append(func)
129 if label and label_list is not None:
130 label_list.append(label)
Simran Basic6f1f7a2012-10-16 10:47:46 -0700131 return func
132 return add_func
133
134
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700135class SiteHost(remote.RemoteHost):
136 """Chromium OS specific subclass of Host."""
137
138 _parser = autoserv_parser.autoserv_parser
139
Richard Barnette0c73ffc2012-11-19 15:21:18 -0800140 # Time to wait for new kernel to be marked successful after
141 # auto update.
Chris Masone163cead2012-05-16 11:49:48 -0700142 _KERNEL_UPDATE_TIMEOUT = 120
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700143
Richard Barnette03a0c132012-11-05 12:40:35 -0800144 # Timeout values (in seconds) associated with various Chrome OS
145 # state changes.
J. Richard Barnette134ec2c2012-04-25 12:59:37 -0700146 #
Richard Barnette0c73ffc2012-11-19 15:21:18 -0800147 # In general, a good rule of thumb is that the timeout can be up
148 # to twice the typical measured value on the slowest platform.
149 # The times here have not necessarily been empirically tested to
150 # meet this criterion.
J. Richard Barnetteeb69d722012-06-18 17:29:44 -0700151 #
152 # SLEEP_TIMEOUT: Time to allow for suspend to memory.
Richard Barnette0c73ffc2012-11-19 15:21:18 -0800153 # RESUME_TIMEOUT: Time to allow for resume after suspend, plus
154 # time to restart the netwowrk.
J. Richard Barnetteeb69d722012-06-18 17:29:44 -0700155 # BOOT_TIMEOUT: Time to allow for boot from power off. Among
Richard Barnette0c73ffc2012-11-19 15:21:18 -0800156 # other things, this must account for the 30 second dev-mode
157 # screen delay and time to start the network,
J. Richard Barnetteeb69d722012-06-18 17:29:44 -0700158 # USB_BOOT_TIMEOUT: Time to allow for boot from a USB device,
Richard Barnette0c73ffc2012-11-19 15:21:18 -0800159 # including the 30 second dev-mode delay and time to start the
160 # network,
161 # SHUTDOWN_TIMEOUT: Time to allow for shut down.
J. Richard Barnetteeb69d722012-06-18 17:29:44 -0700162 # REBOOT_TIMEOUT: Combination of shutdown and reboot times.
Richard Barnette03a0c132012-11-05 12:40:35 -0800163 # _INSTALL_TIMEOUT: Time to allow for chromeos-install.
J. Richard Barnetteeb69d722012-06-18 17:29:44 -0700164
165 SLEEP_TIMEOUT = 2
166 RESUME_TIMEOUT = 5
167 BOOT_TIMEOUT = 45
168 USB_BOOT_TIMEOUT = 150
169 SHUTDOWN_TIMEOUT = 5
170 REBOOT_TIMEOUT = SHUTDOWN_TIMEOUT + BOOT_TIMEOUT
Richard Barnette03a0c132012-11-05 12:40:35 -0800171 _INSTALL_TIMEOUT = 240
172
173 _DEFAULT_SERVO_URL_FORMAT = ('/static/servo-images/'
174 '%(board)s_test_image.bin')
175
176 # TODO(jrbarnette): Servo repair is restricted to x86-alex,
177 # because the existing servo client code won't work on other
178 # boards. http://crosbug.com/36973
179 _SERVO_REPAIR_WHITELIST = [ 'x86-alex' ]
Richard Barnette0c73ffc2012-11-19 15:21:18 -0800180
181
Richard Barnette82c35912012-11-20 10:09:10 -0800182 _RPM_RECOVERY_BOARDS = global_config.global_config.get_config_value('CROS',
183 'rpm_recovery_boards', type=str).split(',')
184
185 _MAX_POWER_CYCLE_ATTEMPTS = 6
186 _LAB_MACHINE_FILE = '/mnt/stateful_partition/.labmachine'
187 _RPM_HOSTNAME_REGEX = ('chromeos[0-9]+(-row[0-9]+)?-rack[0-9]+[a-z]*-'
188 'host[0-9]+')
189 _LIGHTSENSOR_FILES = ['in_illuminance0_input',
190 'in_illuminance0_raw',
191 'illuminance0_input']
192 _LIGHTSENSOR_SEARCH_DIR = '/sys/bus/iio/devices'
193 _LABEL_FUNCTIONS = []
Aviv Keshet74c89a92013-02-04 15:18:30 -0800194 _DETECTABLE_LABELS = []
195 label_decorator = functools.partial(add_label_detector, _LABEL_FUNCTIONS,
196 _DETECTABLE_LABELS)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -0700197
J. Richard Barnetteb6de7e32013-02-14 13:28:04 -0800198 # Constants used in ping_wait_up() and ping_wait_down().
199 #
200 # _PING_WAIT_COUNT is the approximate number of polling
201 # cycles to use when waiting for a host state change.
202 #
203 # _PING_STATUS_DOWN and _PING_STATUS_UP are names used
204 # for arguments to the internal _ping_wait_for_status()
205 # method.
206 _PING_WAIT_COUNT = 40
207 _PING_STATUS_DOWN = False
208 _PING_STATUS_UP = True
209
Richard Barnette0c73ffc2012-11-19 15:21:18 -0800210
J. Richard Barnette964fba02012-10-24 17:34:29 -0700211 @staticmethod
J. Richard Barnette7214e0b2013-02-06 15:20:49 -0800212 def get_servo_arguments(args_dict):
213 """Extract servo options from `args_dict` and return the result.
214
215 Take the provided dictionary of argument options and return
216 a subset that represent standard arguments needed to
217 construct a servo object for a host. The intent is to
218 provide standard argument processing from run_remote_tests
219 for tests that require a servo to operate.
220
221 Recommended usage:
222 ~~~~~~~~
223 args_dict = utils.args_to_dict(args)
224 servo_args = hosts.SiteHost.get_servo_arguments(args_dict)
225 host = hosts.create_host(machine, servo_args=servo_args)
226 ~~~~~~~~
227
228 @param args_dict Dictionary from which to extract the servo
229 arguments.
230 """
J. Richard Barnette964fba02012-10-24 17:34:29 -0700231 servo_args = {}
232 for arg in ('servo_host', 'servo_port'):
J. Richard Barnette7214e0b2013-02-06 15:20:49 -0800233 if arg in args_dict:
234 servo_args[arg] = args_dict[arg]
J. Richard Barnette964fba02012-10-24 17:34:29 -0700235 return servo_args
J. Richard Barnette134ec2c2012-04-25 12:59:37 -0700236
J. Richard Barnette964fba02012-10-24 17:34:29 -0700237
238 def _initialize(self, hostname, servo_args=None, *args, **dargs):
J. Richard Barnette67ccb872012-04-19 16:34:56 -0700239 """Initialize superclasses, and |self.servo|.
240
241 For creating the host servo object, there are three
242 possibilities: First, if the host is a lab system known to
243 have a servo board, we connect to that servo unconditionally.
244 Second, if we're called from a control file that requires
J. Richard Barnette55fb8062012-05-23 10:29:31 -0700245 servo features for testing, it will pass settings for
246 `servo_host`, `servo_port`, or both. If neither of these
247 cases apply, `self.servo` will be `None`.
J. Richard Barnette67ccb872012-04-19 16:34:56 -0700248
249 """
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700250 super(SiteHost, self)._initialize(hostname=hostname,
251 *args, **dargs)
J. Richard Barnettef0859852012-08-20 14:55:50 -0700252 # self.env is a dictionary of environment variable settings
253 # to be exported for commands run on the host.
254 # LIBC_FATAL_STDERR_ can be useful for diagnosing certain
255 # errors that might happen.
256 self.env['LIBC_FATAL_STDERR_'] = '1'
J. Richard Barnette1d78b012012-05-15 13:56:30 -0700257 self._xmlrpc_proxy_map = {}
J. Richard Barnettebe5ebcc2013-02-11 16:03:15 -0800258 self.servo = _get_lab_servo(hostname)
J. Richard Barnettead7da482012-10-30 16:46:52 -0700259 if not self.servo and servo_args is not None:
J. Richard Barnette964fba02012-10-24 17:34:29 -0700260 self.servo = servo.Servo(**servo_args)
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700261
262
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500263 def get_repair_image_name(self):
264 """Generate a image_name from variables in the global config.
265
266 @returns a str of $board-version/$BUILD.
267
268 """
269 stable_version = global_config.global_config.get_config_value(
270 'CROS', 'stable_cros_version')
271 build_pattern = global_config.global_config.get_config_value(
272 'CROS', 'stable_build_pattern')
273 board = self._get_board_from_afe()
274 if board is None:
275 raise error.AutoservError('DUT has no board attribute, '
276 'cannot be repaired.')
277 return build_pattern % (board, stable_version)
278
279
280 def clear_cros_version_labels_and_job_repo_url(self):
281 """Clear cros_version labels and host attribute job_repo_url."""
282 host_model = models.Host.objects.get(hostname=self.hostname)
283 for label in host_model.labels.iterator():
284 if not label.name.startswith(ds_constants.VERSION_PREFIX):
285 continue
286 label = models.Label.smart_get(label.name)
287 label.host_set.remove(host_model)
288
289 host_model.set_or_delete_attribute('job_repo_url', None)
290
291
Chris Sosaa3ac2152012-05-23 22:23:13 -0700292 def machine_install(self, update_url=None, force_update=False,
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500293 local_devserver=False, repair=False):
294 """Install the DUT.
295
296 @param update_url: The url to use for the update
297 pattern: http://$devserver:###/update/$build
298 If update_url is None and repair is True we will install the
299 stable image listed in global_config under
300 CROS.stable_cros_version.
301 @param force_update: Force an update even if the version installed
302 is the same. Default:False
303 @param local_devserver: Used by run_remote_test to allow people to
304 use their local devserver. Default: False
305 @param repair: Whether or not we are in repair mode. This adds special
306 cases for repairing a machine like starting update_engine.
307 Setting repair to True sets force_update to True as well.
308 default: False
309 @raises autoupdater.ChromiumOSError
310
311 """
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700312 if not update_url and self._parser.options.image:
313 update_url = self._parser.options.image
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500314 elif not update_url and not repair:
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700315 raise autoupdater.ChromiumOSError(
316 'Update failed. No update URL provided.')
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500317 elif not update_url and repair:
318 image_name = self.get_repair_image_name()
319 devserver = dev_server.ImageServer.resolve(image_name)
320 logging.info('Staging repair build: %s', image_name)
321 devserver.trigger_download(image_name, synchronous=False)
322 self.clear_cros_version_labels_and_job_repo_url()
323 update_url = tools.image_url_pattern() % (devserver.url(),
324 image_name)
325
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700326
Chris Sosafab08082013-01-04 15:21:20 -0800327 # In case the system is in a bad state, we always reboot the machine
328 # before machine_install.
329 self.reboot(timeout=60, wait=True)
330
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500331 if repair:
332 self.run('stop update-engine; start update-engine')
333 force_update = True
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700334 # Attempt to update the system.
Chris Sosaa3ac2152012-05-23 22:23:13 -0700335 updater = autoupdater.ChromiumOSUpdater(update_url, host=self,
336 local_devserver=local_devserver)
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700337 if updater.run_update(force_update):
338 # Figure out active and inactive kernel.
339 active_kernel, inactive_kernel = updater.get_kernel_state()
340
341 # Ensure inactive kernel has higher priority than active.
342 if (updater.get_kernel_priority(inactive_kernel)
343 < updater.get_kernel_priority(active_kernel)):
344 raise autoupdater.ChromiumOSError(
345 'Update failed. The priority of the inactive kernel'
346 ' partition is less than that of the active kernel'
347 ' partition.')
348
Scott Zawalski21902002012-09-19 17:57:00 -0400349 update_engine_log = '/var/log/update_engine.log'
350 logging.info('Dumping %s', update_engine_log)
351 self.run('cat %s' % update_engine_log)
Richard Barnette0c73ffc2012-11-19 15:21:18 -0800352 # Updater has returned successfully; reboot the host.
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700353 self.reboot(timeout=60, wait=True)
Chris Sosae146ed82012-09-19 17:58:36 -0700354 # Touch the lab machine file to leave a marker that distinguishes
355 # this image from other test images.
Richard Barnette82c35912012-11-20 10:09:10 -0800356 self.run('touch %s' % self._LAB_MACHINE_FILE)
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700357
358 # Following the reboot, verify the correct version.
359 updater.check_version()
360
361 # Figure out newly active kernel.
362 new_active_kernel, _ = updater.get_kernel_state()
363
364 # Ensure that previously inactive kernel is now the active kernel.
365 if new_active_kernel != inactive_kernel:
366 raise autoupdater.ChromiumOSError(
367 'Update failed. New kernel partition is not active after'
368 ' boot.')
369
370 host_attributes = site_host_attributes.HostAttributes(self.hostname)
371 if host_attributes.has_chromeos_firmware:
372 # Wait until tries == 0 and success, or until timeout.
373 utils.poll_for_condition(
374 lambda: (updater.get_kernel_tries(new_active_kernel) == 0
375 and updater.get_kernel_success(new_active_kernel)),
376 exception=autoupdater.ChromiumOSError(
377 'Update failed. Timed out waiting for system to mark'
378 ' new kernel as successful.'),
379 timeout=self._KERNEL_UPDATE_TIMEOUT, sleep_interval=5)
380
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700381 # Clean up any old autotest directories which may be lying around.
382 for path in global_config.global_config.get_config_value(
383 'AUTOSERV', 'client_autodir_paths', type=list):
384 self.run('rm -rf ' + path)
385
386
Richard Barnette82c35912012-11-20 10:09:10 -0800387 def _get_board_from_afe(self):
388 """Retrieve this host's board from its labels in the AFE.
389
390 Looks for a host label of the form "board:<board>", and
391 returns the "<board>" part of the label. `None` is returned
392 if there is not a single, unique label matching the pattern.
393
394 @returns board from label, or `None`.
395 """
396 host_model = models.Host.objects.get(hostname=self.hostname)
397 board_labels = filter(lambda l: l.name.startswith('board:'),
398 host_model.labels.all())
399 board_name = None
400 if len(board_labels) == 1:
401 board_name = board_labels[0].name.split(':', 1)[1]
402 elif len(board_labels) == 0:
403 logging.error('Host %s does not have a board label.',
404 self.hostname)
405 else:
406 logging.error('Host %s has multiple board labels.',
407 self.hostname)
408 return board_name
409
410
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500411 def _install_repair(self):
412 """Attempt to repair this host using upate-engine.
413
414 If the host is up, try installing the DUT with a stable
415 "repair" version of Chrome OS as defined in the global_config
416 under CROS.stable_cros_version.
417
418 @returns True if successful, False if update_engine failed.
419
420 """
421 if not self.is_up():
422 return False
423
424 logging.info('Attempting to reimage machine to repair image.')
425 try:
426 self.machine_install(repair=True)
427 except autoupdater.ChromiumOSError:
428 logging.info('Repair via install failed.')
429 return False
430
431 return True
432
433
Richard Barnette03a0c132012-11-05 12:40:35 -0800434 def _servo_repair(self, board):
435 """Attempt to repair this host using an attached Servo.
436
437 Re-install the OS on the DUT by 1) installing a test image
438 on a USB storage device attached to the Servo board,
439 2) booting that image in recovery mode, and then
440 3) installing the image.
441
442 """
443 server = dev_server.ImageServer.devserver_url_for_servo(board)
444 image = server + (self._DEFAULT_SERVO_URL_FORMAT %
445 { 'board': board })
446 self.servo.install_recovery_image(image)
447 if not self.wait_up(timeout=self.USB_BOOT_TIMEOUT):
448 raise error.AutoservError('DUT failed to boot from USB'
449 ' after %d seconds' %
450 self.USB_BOOT_TIMEOUT)
451 self.run('chromeos-install --yes',
452 timeout=self._INSTALL_TIMEOUT)
453 self.servo.power_long_press()
454 self.servo.set('usb_mux_sel1', 'servo_sees_usbkey')
455 self.servo.power_short_press()
456 if not self.wait_up(timeout=self.BOOT_TIMEOUT):
457 raise error.AutoservError('DUT failed to reboot installed '
458 'test image after %d seconds' %
459 self.BOOT_TIMEOUT)
460
461
Richard Barnette82c35912012-11-20 10:09:10 -0800462 def _powercycle_to_repair(self):
463 """Utilize the RPM Infrastructure to bring the host back up.
464
465 If the host is not up/repaired after the first powercycle we utilize
466 auto fallback to the last good install by powercycling and rebooting the
467 host 6 times.
468 """
469 logging.info('Attempting repair via RPM powercycle.')
470 failed_cycles = 0
471 self.power_cycle()
472 while not self.wait_up(timeout=self.BOOT_TIMEOUT):
473 failed_cycles += 1
474 if failed_cycles >= self._MAX_POWER_CYCLE_ATTEMPTS:
475 raise error.AutoservError('Powercycled host %s %d times; '
476 'device did not come back online.' %
477 (self.hostname, failed_cycles))
478 self.power_cycle()
479 if failed_cycles == 0:
480 logging.info('Powercycling was successful first time.')
481 else:
482 logging.info('Powercycling was successful after %d failures.',
483 failed_cycles)
484
485
486 def repair_full(self):
487 """Repair a host for repair level NO_PROTECTION.
488
489 This overrides the base class function for repair; it does
490 not call back to the parent class, but instead offers a
491 simplified implementation based on the capabilities in the
492 Chrome OS test lab.
493
494 Repair follows this sequence:
495 1. If the DUT passes `self.verify()`, do nothing.
496 2. If the DUT can be power-cycled via RPM, try to repair
497 by power-cycling.
498
499 As with the parent method, the last operation performed on
500 the DUT must be to call `self.verify()`; if that call fails,
501 the exception it raises is passed back to the caller.
502 """
503 try:
504 self.verify()
505 except:
506 host_board = self._get_board_from_afe()
Richard Barnette03a0c132012-11-05 12:40:35 -0800507 if host_board is None:
508 logging.error('host %s has no board; failing repair',
509 self.hostname)
Richard Barnette82c35912012-11-20 10:09:10 -0800510 raise
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500511
512 reimage_success = self._install_repair()
513 # TODO(scottz): All repair pathways should be executed until we've
514 # exhausted all options. Below we favor servo over powercycle when
515 # we really should be falling back to power if servo fails.
516 if (not reimage_success and self.servo and
Richard Barnette03a0c132012-11-05 12:40:35 -0800517 host_board in self._SERVO_REPAIR_WHITELIST):
518 self._servo_repair(host_board)
519 elif (self.has_power() and
520 host_board in self._RPM_RECOVERY_BOARDS):
521 self._powercycle_to_repair()
522 else:
523 logging.error('host %s has no servo and no RPM control; '
524 'failing repair', self.hostname)
525 raise
Richard Barnette82c35912012-11-20 10:09:10 -0800526 self.verify()
527
528
J. Richard Barnette1d78b012012-05-15 13:56:30 -0700529 def close(self):
530 super(SiteHost, self).close()
531 self.xmlrpc_disconnect_all()
532
533
Chris Sosaf4d43ff2012-10-30 11:21:05 -0700534 def cleanup(self):
Chris Sosaf4d43ff2012-10-30 11:21:05 -0700535 client_at = autotest.Autotest(self)
Richard Barnette82c35912012-11-20 10:09:10 -0800536 self.run('rm -f %s' % constants.CLEANUP_LOGS_PAUSED_FILE)
Scott Zawalskiddbc31e2012-11-15 11:29:01 -0500537 try:
538 client_at.run_static_method('autotest_lib.client.cros.cros_ui',
539 '_clear_login_prompt_state')
540 self.run('restart ui')
541 client_at.run_static_method('autotest_lib.client.cros.cros_ui',
542 '_wait_for_login_prompt')
Alex Millerf4517962013-02-25 15:03:02 -0800543 except (error.AutotestRunError, error.AutoservRunError):
Scott Zawalskiddbc31e2012-11-15 11:29:01 -0500544 logging.warn('Unable to restart ui, rebooting device.')
545 # Since restarting the UI fails fall back to normal Autotest
546 # cleanup routines, i.e. reboot the machine.
547 super(SiteHost, self).cleanup()
Chris Sosaf4d43ff2012-10-30 11:21:05 -0700548
549
Simran Basi154f5582012-10-23 16:27:11 -0700550 # TODO (sbasi) crosbug.com/35656
551 # Renamed the sitehost cleanup method so we don't go down this pathway.
552 # def cleanup(self):
553 def cleanup_poweron(self):
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700554 """Special cleanup method to make sure hosts always get power back."""
Chris Sosa9479fcd2012-10-09 13:44:22 -0700555 super(SiteHost, self).cleanup()
Simran Basid5e5e272012-09-24 15:23:59 -0700556 if self.has_power():
Simran Basifd23fb22012-10-22 17:56:22 -0700557 try:
558 self.power_on()
Chris Sosafab08082013-01-04 15:21:20 -0800559 except rpm_client.RemotePowerException:
Simran Basifd23fb22012-10-22 17:56:22 -0700560 # If cleanup has completed but there was an issue with the RPM
561 # Infrastructure, log an error message rather than fail cleanup
562 logging.error('Failed to turn Power On for this host after '
563 'cleanup through the RPM Infrastructure.')
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700564
565
Yu-Ju Honga2be94a2012-07-31 09:48:52 -0700566 def reboot(self, **dargs):
567 """
568 This function reboots the site host. The more generic
569 RemoteHost.reboot() performs sync and sleeps for 5
570 seconds. This is not necessary for Chrome OS devices as the
571 sync should be finished in a short time during the reboot
572 command.
573 """
Tom Wai-Hong Tamf5cd1d42012-08-13 12:04:08 +0800574 if 'reboot_cmd' not in dargs:
575 dargs['reboot_cmd'] = ('((reboot & sleep 10; reboot -f &)'
576 ' </dev/null >/dev/null 2>&1 &)')
Yu-Ju Honga2be94a2012-07-31 09:48:52 -0700577 # Enable fastsync to avoid running extra sync commands before reboot.
Tom Wai-Hong Tamf5cd1d42012-08-13 12:04:08 +0800578 if 'fastsync' not in dargs:
579 dargs['fastsync'] = True
Yu-Ju Honga2be94a2012-07-31 09:48:52 -0700580 super(SiteHost, self).reboot(**dargs)
581
582
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700583 def verify_software(self):
Richard Barnetteb2bc13c2013-01-08 17:32:51 -0800584 """Verify working software on a Chrome OS system.
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700585
Richard Barnetteb2bc13c2013-01-08 17:32:51 -0800586 Tests for the following conditions:
587 1. All conditions tested by the parent version of this
588 function.
589 2. Sufficient space in /mnt/stateful_partition.
590 3. update_engine answers a simple status request over DBus.
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700591
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700592 """
593 super(SiteHost, self).verify_software()
594 self.check_diskspace(
595 '/mnt/stateful_partition',
596 global_config.global_config.get_config_value(
597 'SERVER', 'gb_diskspace_required', type=int,
598 default=20))
Richard Barnetteb2bc13c2013-01-08 17:32:51 -0800599 self.run('update_engine_client --status')
J. Richard Barnette134ec2c2012-04-25 12:59:37 -0700600
601
J. Richard Barnette7214e0b2013-02-06 15:20:49 -0800602 def xmlrpc_connect(self, command, port, command_name=None):
J. Richard Barnette1d78b012012-05-15 13:56:30 -0700603 """Connect to an XMLRPC server on the host.
604
605 The `command` argument should be a simple shell command that
606 starts an XMLRPC server on the given `port`. The command
607 must not daemonize, and must terminate cleanly on SIGTERM.
608 The command is started in the background on the host, and a
609 local XMLRPC client for the server is created and returned
610 to the caller.
611
612 Note that the process of creating an XMLRPC client makes no
613 attempt to connect to the remote server; the caller is
614 responsible for determining whether the server is running
615 correctly, and is ready to serve requests.
616
617 @param command Shell command to start the server.
618 @param port Port number on which the server is expected to
619 be serving.
J. Richard Barnette7214e0b2013-02-06 15:20:49 -0800620 @param command_name String to use as input to `pkill` to
621 terminate the XMLRPC server on the host.
J. Richard Barnette1d78b012012-05-15 13:56:30 -0700622 """
623 self.xmlrpc_disconnect(port)
624
625 # Chrome OS on the target closes down most external ports
626 # for security. We could open the port, but doing that
627 # would conflict with security tests that check that only
628 # expected ports are open. So, to get to the port on the
629 # target we use an ssh tunnel.
630 local_port = utils.get_unused_port()
631 tunnel_options = '-n -N -q -L %d:localhost:%d' % (local_port, port)
632 ssh_cmd = make_ssh_command(opts=tunnel_options)
633 tunnel_cmd = '%s %s' % (ssh_cmd, self.hostname)
634 logging.debug('Full tunnel command: %s', tunnel_cmd)
635 tunnel_proc = subprocess.Popen(tunnel_cmd, shell=True, close_fds=True)
636 logging.debug('Started XMLRPC tunnel, local = %d'
637 ' remote = %d, pid = %d',
638 local_port, port, tunnel_proc.pid)
639
640 # Start the server on the host. Redirection in the command
641 # below is necessary, because 'ssh' won't terminate until
642 # background child processes close stdin, stdout, and
643 # stderr.
644 remote_cmd = '( %s ) </dev/null >/dev/null 2>&1 & echo $!' % command
645 remote_pid = self.run(remote_cmd).stdout.rstrip('\n')
646 logging.debug('Started XMLRPC server on host %s, pid = %s',
647 self.hostname, remote_pid)
648
J. Richard Barnette7214e0b2013-02-06 15:20:49 -0800649 self._xmlrpc_proxy_map[port] = (command_name, tunnel_proc)
J. Richard Barnette1d78b012012-05-15 13:56:30 -0700650 rpc_url = 'http://localhost:%d' % local_port
651 return xmlrpclib.ServerProxy(rpc_url, allow_none=True)
652
653
654 def xmlrpc_disconnect(self, port):
655 """Disconnect from an XMLRPC server on the host.
656
657 Terminates the remote XMLRPC server previously started for
658 the given `port`. Also closes the local ssh tunnel created
659 for the connection to the host. This function does not
660 directly alter the state of a previously returned XMLRPC
661 client object; however disconnection will cause all
662 subsequent calls to methods on the object to fail.
663
664 This function does nothing if requested to disconnect a port
665 that was not previously connected via `self.xmlrpc_connect()`
666
667 @param port Port number passed to a previous call to
668 `xmlrpc_connect()`
669 """
670 if port not in self._xmlrpc_proxy_map:
671 return
672 entry = self._xmlrpc_proxy_map[port]
673 remote_name = entry[0]
674 tunnel_proc = entry[1]
675 if remote_name:
676 # We use 'pkill' to find our target process rather than
677 # a PID, because the host may have rebooted since
678 # connecting, and we don't want to kill an innocent
679 # process with the same PID.
680 #
681 # 'pkill' helpfully exits with status 1 if no target
682 # process is found, for which run() will throw an
Simran Basid5e5e272012-09-24 15:23:59 -0700683 # exception. We don't want that, so we the ignore
J. Richard Barnette1d78b012012-05-15 13:56:30 -0700684 # status.
685 self.run("pkill -f '%s'" % remote_name, ignore_status=True)
686
687 if tunnel_proc.poll() is None:
688 tunnel_proc.terminate()
689 logging.debug('Terminated tunnel, pid %d', tunnel_proc.pid)
690 else:
691 logging.debug('Tunnel pid %d terminated early, status %d',
692 tunnel_proc.pid, tunnel_proc.returncode)
693 del self._xmlrpc_proxy_map[port]
694
695
696 def xmlrpc_disconnect_all(self):
697 """Disconnect all known XMLRPC proxy ports."""
698 for port in self._xmlrpc_proxy_map.keys():
699 self.xmlrpc_disconnect(port)
700
701
J. Richard Barnetteb6de7e32013-02-14 13:28:04 -0800702 def _ping_check_status(self, status):
703 """Ping the host once, and return whether it has a given status.
J. Richard Barnette134ec2c2012-04-25 12:59:37 -0700704
J. Richard Barnetteb6de7e32013-02-14 13:28:04 -0800705 @param status Check the ping status against this value.
706 @return True iff `status` and the result of ping are the same
707 (i.e. both True or both False).
708
709 """
710 ping_val = utils.ping(self.hostname, tries=1, deadline=1)
711 return not (status ^ (ping_val == 0))
712
713 def _ping_wait_for_status(self, status, timeout):
714 """Wait for the host to have a given status (UP or DOWN).
715
716 Status is checked by polling. Polling will not last longer
717 than the number of seconds in `timeout`. The polling
718 interval will be long enough that only approximately
719 _PING_WAIT_COUNT polling cycles will be executed, subject
720 to a maximum interval of about one minute.
721
722 @param status Waiting will stop immediately if `ping` of the
723 host returns this status.
724 @param timeout Poll for at most this many seconds.
725 @return True iff the host status from `ping` matched the
726 requested status at the time of return.
727
728 """
729 # _ping_check_status() takes about 1 second, hence the
730 # "- 1" in the formula below.
731 poll_interval = min(int(timeout / self._PING_WAIT_COUNT), 60) - 1
732 end_time = time.time() + timeout
733 while time.time() <= end_time:
734 if self._ping_check_status(status):
735 return True
736 if poll_interval > 0:
737 time.sleep(poll_interval)
738
739 # The last thing we did was sleep(poll_interval), so it may
740 # have been too long since the last `ping`. Check one more
741 # time, just to be sure.
742 return self._ping_check_status(status)
743
744 def ping_wait_up(self, timeout):
745 """Wait for the host to respond to `ping`.
746
747 N.B. This method is not a reliable substitute for
748 `wait_up()`, because a host that responds to ping will not
749 necessarily respond to ssh. This method should only be used
750 if the target DUT can be considered functional even if it
751 can't be reached via ssh.
752
753 @param timeout Minimum time to allow before declaring the
754 host to be non-responsive.
755 @return True iff the host answered to ping before the timeout.
756
757 """
758 return self._ping_wait_for_status(self._PING_STATUS_UP, timeout)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -0700759
Andrew Bresticker678c0c72013-01-22 10:44:09 -0800760 def ping_wait_down(self, timeout):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -0700761 """Wait until the host no longer responds to `ping`.
762
J. Richard Barnetteb6de7e32013-02-14 13:28:04 -0800763 This function can be used as a slightly faster version of
764 `wait_down()`, by avoiding potentially long ssh timeouts.
765
766 @param timeout Minimum time to allow for the host to become
767 non-responsive.
768 @return True iff the host quit answering ping before the
769 timeout.
770
J. Richard Barnette134ec2c2012-04-25 12:59:37 -0700771 """
J. Richard Barnetteb6de7e32013-02-14 13:28:04 -0800772 return self._ping_wait_for_status(self._PING_STATUS_DOWN, timeout)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -0700773
774 def test_wait_for_sleep(self):
775 """Wait for the client to enter low-power sleep mode.
776
777 The test for "is asleep" can't distinguish a system that is
778 powered off; to confirm that the unit was asleep, it is
779 necessary to force resume, and then call
780 `test_wait_for_resume()`.
781
782 This function is expected to be called from a test as part
783 of a sequence like the following:
784
785 ~~~~~~~~
786 boot_id = host.get_boot_id()
787 # trigger sleep on the host
788 host.test_wait_for_sleep()
789 # trigger resume on the host
790 host.test_wait_for_resume(boot_id)
791 ~~~~~~~~
792
793 @exception TestFail The host did not go to sleep within
794 the allowed time.
795 """
Andrew Bresticker678c0c72013-01-22 10:44:09 -0800796 if not self.ping_wait_down(timeout=self.SLEEP_TIMEOUT):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -0700797 raise error.TestFail(
798 'client failed to sleep after %d seconds' %
J. Richard Barnetteeb69d722012-06-18 17:29:44 -0700799 self.SLEEP_TIMEOUT)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -0700800
801
802 def test_wait_for_resume(self, old_boot_id):
803 """Wait for the client to resume from low-power sleep mode.
804
805 The `old_boot_id` parameter should be the value from
806 `get_boot_id()` obtained prior to entering sleep mode. A
807 `TestFail` exception is raised if the boot id changes.
808
809 See @ref test_wait_for_sleep for more on this function's
810 usage.
811
J. Richard Barnette7214e0b2013-02-06 15:20:49 -0800812 @param old_boot_id A boot id value obtained before the
J. Richard Barnette134ec2c2012-04-25 12:59:37 -0700813 target host went to sleep.
814
815 @exception TestFail The host did not respond within the
816 allowed time.
817 @exception TestFail The host responded, but the boot id test
818 indicated a reboot rather than a sleep
819 cycle.
820 """
J. Richard Barnetteeb69d722012-06-18 17:29:44 -0700821 if not self.wait_up(timeout=self.RESUME_TIMEOUT):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -0700822 raise error.TestFail(
823 'client failed to resume from sleep after %d seconds' %
J. Richard Barnetteeb69d722012-06-18 17:29:44 -0700824 self.RESUME_TIMEOUT)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -0700825 else:
826 new_boot_id = self.get_boot_id()
827 if new_boot_id != old_boot_id:
828 raise error.TestFail(
829 'client rebooted, but sleep was expected'
830 ' (old boot %s, new boot %s)'
831 % (old_boot_id, new_boot_id))
832
833
834 def test_wait_for_shutdown(self):
835 """Wait for the client to shut down.
836
837 The test for "has shut down" can't distinguish a system that
838 is merely asleep; to confirm that the unit was down, it is
839 necessary to force boot, and then call test_wait_for_boot().
840
841 This function is expected to be called from a test as part
842 of a sequence like the following:
843
844 ~~~~~~~~
845 boot_id = host.get_boot_id()
846 # trigger shutdown on the host
847 host.test_wait_for_shutdown()
848 # trigger boot on the host
849 host.test_wait_for_boot(boot_id)
850 ~~~~~~~~
851
852 @exception TestFail The host did not shut down within the
853 allowed time.
854 """
Andrew Bresticker678c0c72013-01-22 10:44:09 -0800855 if not self.ping_wait_down(timeout=self.SHUTDOWN_TIMEOUT):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -0700856 raise error.TestFail(
857 'client failed to shut down after %d seconds' %
J. Richard Barnetteeb69d722012-06-18 17:29:44 -0700858 self.SHUTDOWN_TIMEOUT)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -0700859
860
861 def test_wait_for_boot(self, old_boot_id=None):
862 """Wait for the client to boot from cold power.
863
864 The `old_boot_id` parameter should be the value from
865 `get_boot_id()` obtained prior to shutting down. A
866 `TestFail` exception is raised if the boot id does not
867 change. The boot id test is omitted if `old_boot_id` is not
868 specified.
869
870 See @ref test_wait_for_shutdown for more on this function's
871 usage.
872
J. Richard Barnette7214e0b2013-02-06 15:20:49 -0800873 @param old_boot_id A boot id value obtained before the
J. Richard Barnette134ec2c2012-04-25 12:59:37 -0700874 shut down.
875
876 @exception TestFail The host did not respond within the
877 allowed time.
878 @exception TestFail The host responded, but the boot id test
879 indicated that there was no reboot.
880 """
J. Richard Barnetteeb69d722012-06-18 17:29:44 -0700881 if not self.wait_up(timeout=self.REBOOT_TIMEOUT):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -0700882 raise error.TestFail(
883 'client failed to reboot after %d seconds' %
J. Richard Barnetteeb69d722012-06-18 17:29:44 -0700884 self.REBOOT_TIMEOUT)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -0700885 elif old_boot_id:
886 if self.get_boot_id() == old_boot_id:
887 raise error.TestFail(
888 'client is back up, but did not reboot'
889 ' (boot %s)' % old_boot_id)
Simran Basid5e5e272012-09-24 15:23:59 -0700890
891
892 @staticmethod
893 def check_for_rpm_support(hostname):
894 """For a given hostname, return whether or not it is powered by an RPM.
895
896 @return None if this host does not follows the defined naming format
897 for RPM powered DUT's in the lab. If it does follow the format,
898 it returns a regular expression MatchObject instead.
899 """
Richard Barnette82c35912012-11-20 10:09:10 -0800900 return re.match(SiteHost._RPM_HOSTNAME_REGEX, hostname)
Simran Basid5e5e272012-09-24 15:23:59 -0700901
902
903 def has_power(self):
904 """For this host, return whether or not it is powered by an RPM.
905
906 @return True if this host is in the CROS lab and follows the defined
907 naming format.
908 """
909 return SiteHost.check_for_rpm_support(self.hostname)
910
911
Simran Basid5e5e272012-09-24 15:23:59 -0700912 def power_off(self):
J. Richard Barnette7214e0b2013-02-06 15:20:49 -0800913 """Turn off power to this host via RPM."""
Simran Basidcff4252012-11-20 16:13:20 -0800914 rpm_client.set_power(self.hostname, 'OFF')
Simran Basid5e5e272012-09-24 15:23:59 -0700915
916
917 def power_on(self):
J. Richard Barnette7214e0b2013-02-06 15:20:49 -0800918 """Turn on power to this host via RPM."""
Simran Basidcff4252012-11-20 16:13:20 -0800919 rpm_client.set_power(self.hostname, 'ON')
Simran Basid5e5e272012-09-24 15:23:59 -0700920
921
922 def power_cycle(self):
J. Richard Barnette7214e0b2013-02-06 15:20:49 -0800923 """Cycle power to this host by turning it OFF, then ON."""
Simran Basidcff4252012-11-20 16:13:20 -0800924 rpm_client.set_power(self.hostname, 'CYCLE')
Simran Basic6f1f7a2012-10-16 10:47:46 -0700925
926
927 def get_platform(self):
928 """Determine the correct platform label for this host.
929
930 @returns a string representing this host's platform.
931 """
932 crossystem = utils.Crossystem(self)
933 crossystem.init()
934 # Extract fwid value and use the leading part as the platform id.
935 # fwid generally follow the format of {platform}.{firmware version}
936 # Example: Alex.X.YYY.Z or Google_Alex.X.YYY.Z
937 platform = crossystem.fwid().split('.')[0].lower()
938 # Newer platforms start with 'Google_' while the older ones do not.
939 return platform.replace('google_', '')
940
941
Aviv Keshet74c89a92013-02-04 15:18:30 -0800942 @label_decorator()
Simran Basic6f1f7a2012-10-16 10:47:46 -0700943 def get_board(self):
944 """Determine the correct board label for this host.
945
946 @returns a string representing this host's board.
947 """
948 release_info = utils.parse_cmd_output('cat /etc/lsb-release',
949 run_method=self.run)
950 board = release_info['CHROMEOS_RELEASE_BOARD']
951 # Devices in the lab generally have the correct board name but our own
952 # development devices have {board_name}-signed-{key_type}. The board
953 # name may also begin with 'x86-' which we need to keep.
954 if 'x86' not in board:
955 return 'board:%s' % board.split('-')[0]
956 return 'board:%s' % '-'.join(board.split('-')[0:2])
957
958
Aviv Keshet74c89a92013-02-04 15:18:30 -0800959 @label_decorator('lightsensor')
Simran Basic6f1f7a2012-10-16 10:47:46 -0700960 def has_lightsensor(self):
961 """Determine the correct board label for this host.
962
963 @returns the string 'lightsensor' if this host has a lightsensor or
964 None if it does not.
965 """
966 search_cmd = "find -L %s -maxdepth 4 | egrep '%s'" % (
Richard Barnette82c35912012-11-20 10:09:10 -0800967 self._LIGHTSENSOR_SEARCH_DIR, '|'.join(self._LIGHTSENSOR_FILES))
Simran Basic6f1f7a2012-10-16 10:47:46 -0700968 try:
969 # Run the search cmd following the symlinks. Stderr_tee is set to
970 # None as there can be a symlink loop, but the command will still
971 # execute correctly with a few messages printed to stderr.
972 self.run(search_cmd, stdout_tee=None, stderr_tee=None)
973 return 'lightsensor'
974 except error.AutoservRunError:
975 # egrep exited with a return code of 1 meaning none of the possible
976 # lightsensor files existed.
977 return None
978
979
Aviv Keshet74c89a92013-02-04 15:18:30 -0800980 @label_decorator('bluetooth')
Simran Basic6f1f7a2012-10-16 10:47:46 -0700981 def has_bluetooth(self):
982 """Determine the correct board label for this host.
983
984 @returns the string 'bluetooth' if this host has bluetooth or
985 None if it does not.
986 """
987 try:
988 self.run('test -d /sys/class/bluetooth/hci0')
989 # test exited with a return code of 0.
990 return 'bluetooth'
991 except error.AutoservRunError:
992 # test exited with a return code 1 meaning the directory did not
993 # exist.
994 return None
995
996
997 def get_labels(self):
998 """Return a list of labels for this given host.
999
1000 This is the main way to retrieve all the automatic labels for a host
1001 as it will run through all the currently implemented label functions.
1002 """
1003 labels = []
Richard Barnette82c35912012-11-20 10:09:10 -08001004 for label_function in self._LABEL_FUNCTIONS:
Simran Basic6f1f7a2012-10-16 10:47:46 -07001005 label = label_function(self)
1006 if label:
1007 labels.append(label)
1008 return labels