blob: bc39aca5cfe71d372ef8e8af2c8f5d49dbfbe0d8 [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')
Scott Zawalskifbca4a92013-03-04 15:56:42 -0500600 # Makes sure python is present, loads and can use built in functions.
601 # We have seen cases where importing cPickle fails with undefined
602 # symbols in cPickle.so.
603 self.run('python -c "import cPickle"')
J. Richard Barnette134ec2c2012-04-25 12:59:37 -0700604
605
J. Richard Barnette7214e0b2013-02-06 15:20:49 -0800606 def xmlrpc_connect(self, command, port, command_name=None):
J. Richard Barnette1d78b012012-05-15 13:56:30 -0700607 """Connect to an XMLRPC server on the host.
608
609 The `command` argument should be a simple shell command that
610 starts an XMLRPC server on the given `port`. The command
611 must not daemonize, and must terminate cleanly on SIGTERM.
612 The command is started in the background on the host, and a
613 local XMLRPC client for the server is created and returned
614 to the caller.
615
616 Note that the process of creating an XMLRPC client makes no
617 attempt to connect to the remote server; the caller is
618 responsible for determining whether the server is running
619 correctly, and is ready to serve requests.
620
621 @param command Shell command to start the server.
622 @param port Port number on which the server is expected to
623 be serving.
J. Richard Barnette7214e0b2013-02-06 15:20:49 -0800624 @param command_name String to use as input to `pkill` to
625 terminate the XMLRPC server on the host.
J. Richard Barnette1d78b012012-05-15 13:56:30 -0700626 """
627 self.xmlrpc_disconnect(port)
628
629 # Chrome OS on the target closes down most external ports
630 # for security. We could open the port, but doing that
631 # would conflict with security tests that check that only
632 # expected ports are open. So, to get to the port on the
633 # target we use an ssh tunnel.
634 local_port = utils.get_unused_port()
635 tunnel_options = '-n -N -q -L %d:localhost:%d' % (local_port, port)
636 ssh_cmd = make_ssh_command(opts=tunnel_options)
637 tunnel_cmd = '%s %s' % (ssh_cmd, self.hostname)
638 logging.debug('Full tunnel command: %s', tunnel_cmd)
639 tunnel_proc = subprocess.Popen(tunnel_cmd, shell=True, close_fds=True)
640 logging.debug('Started XMLRPC tunnel, local = %d'
641 ' remote = %d, pid = %d',
642 local_port, port, tunnel_proc.pid)
643
644 # Start the server on the host. Redirection in the command
645 # below is necessary, because 'ssh' won't terminate until
646 # background child processes close stdin, stdout, and
647 # stderr.
648 remote_cmd = '( %s ) </dev/null >/dev/null 2>&1 & echo $!' % command
649 remote_pid = self.run(remote_cmd).stdout.rstrip('\n')
650 logging.debug('Started XMLRPC server on host %s, pid = %s',
651 self.hostname, remote_pid)
652
J. Richard Barnette7214e0b2013-02-06 15:20:49 -0800653 self._xmlrpc_proxy_map[port] = (command_name, tunnel_proc)
J. Richard Barnette1d78b012012-05-15 13:56:30 -0700654 rpc_url = 'http://localhost:%d' % local_port
655 return xmlrpclib.ServerProxy(rpc_url, allow_none=True)
656
657
658 def xmlrpc_disconnect(self, port):
659 """Disconnect from an XMLRPC server on the host.
660
661 Terminates the remote XMLRPC server previously started for
662 the given `port`. Also closes the local ssh tunnel created
663 for the connection to the host. This function does not
664 directly alter the state of a previously returned XMLRPC
665 client object; however disconnection will cause all
666 subsequent calls to methods on the object to fail.
667
668 This function does nothing if requested to disconnect a port
669 that was not previously connected via `self.xmlrpc_connect()`
670
671 @param port Port number passed to a previous call to
672 `xmlrpc_connect()`
673 """
674 if port not in self._xmlrpc_proxy_map:
675 return
676 entry = self._xmlrpc_proxy_map[port]
677 remote_name = entry[0]
678 tunnel_proc = entry[1]
679 if remote_name:
680 # We use 'pkill' to find our target process rather than
681 # a PID, because the host may have rebooted since
682 # connecting, and we don't want to kill an innocent
683 # process with the same PID.
684 #
685 # 'pkill' helpfully exits with status 1 if no target
686 # process is found, for which run() will throw an
Simran Basid5e5e272012-09-24 15:23:59 -0700687 # exception. We don't want that, so we the ignore
J. Richard Barnette1d78b012012-05-15 13:56:30 -0700688 # status.
689 self.run("pkill -f '%s'" % remote_name, ignore_status=True)
690
691 if tunnel_proc.poll() is None:
692 tunnel_proc.terminate()
693 logging.debug('Terminated tunnel, pid %d', tunnel_proc.pid)
694 else:
695 logging.debug('Tunnel pid %d terminated early, status %d',
696 tunnel_proc.pid, tunnel_proc.returncode)
697 del self._xmlrpc_proxy_map[port]
698
699
700 def xmlrpc_disconnect_all(self):
701 """Disconnect all known XMLRPC proxy ports."""
702 for port in self._xmlrpc_proxy_map.keys():
703 self.xmlrpc_disconnect(port)
704
705
J. Richard Barnetteb6de7e32013-02-14 13:28:04 -0800706 def _ping_check_status(self, status):
707 """Ping the host once, and return whether it has a given status.
J. Richard Barnette134ec2c2012-04-25 12:59:37 -0700708
J. Richard Barnetteb6de7e32013-02-14 13:28:04 -0800709 @param status Check the ping status against this value.
710 @return True iff `status` and the result of ping are the same
711 (i.e. both True or both False).
712
713 """
714 ping_val = utils.ping(self.hostname, tries=1, deadline=1)
715 return not (status ^ (ping_val == 0))
716
717 def _ping_wait_for_status(self, status, timeout):
718 """Wait for the host to have a given status (UP or DOWN).
719
720 Status is checked by polling. Polling will not last longer
721 than the number of seconds in `timeout`. The polling
722 interval will be long enough that only approximately
723 _PING_WAIT_COUNT polling cycles will be executed, subject
724 to a maximum interval of about one minute.
725
726 @param status Waiting will stop immediately if `ping` of the
727 host returns this status.
728 @param timeout Poll for at most this many seconds.
729 @return True iff the host status from `ping` matched the
730 requested status at the time of return.
731
732 """
733 # _ping_check_status() takes about 1 second, hence the
734 # "- 1" in the formula below.
735 poll_interval = min(int(timeout / self._PING_WAIT_COUNT), 60) - 1
736 end_time = time.time() + timeout
737 while time.time() <= end_time:
738 if self._ping_check_status(status):
739 return True
740 if poll_interval > 0:
741 time.sleep(poll_interval)
742
743 # The last thing we did was sleep(poll_interval), so it may
744 # have been too long since the last `ping`. Check one more
745 # time, just to be sure.
746 return self._ping_check_status(status)
747
748 def ping_wait_up(self, timeout):
749 """Wait for the host to respond to `ping`.
750
751 N.B. This method is not a reliable substitute for
752 `wait_up()`, because a host that responds to ping will not
753 necessarily respond to ssh. This method should only be used
754 if the target DUT can be considered functional even if it
755 can't be reached via ssh.
756
757 @param timeout Minimum time to allow before declaring the
758 host to be non-responsive.
759 @return True iff the host answered to ping before the timeout.
760
761 """
762 return self._ping_wait_for_status(self._PING_STATUS_UP, timeout)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -0700763
Andrew Bresticker678c0c72013-01-22 10:44:09 -0800764 def ping_wait_down(self, timeout):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -0700765 """Wait until the host no longer responds to `ping`.
766
J. Richard Barnetteb6de7e32013-02-14 13:28:04 -0800767 This function can be used as a slightly faster version of
768 `wait_down()`, by avoiding potentially long ssh timeouts.
769
770 @param timeout Minimum time to allow for the host to become
771 non-responsive.
772 @return True iff the host quit answering ping before the
773 timeout.
774
J. Richard Barnette134ec2c2012-04-25 12:59:37 -0700775 """
J. Richard Barnetteb6de7e32013-02-14 13:28:04 -0800776 return self._ping_wait_for_status(self._PING_STATUS_DOWN, timeout)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -0700777
778 def test_wait_for_sleep(self):
779 """Wait for the client to enter low-power sleep mode.
780
781 The test for "is asleep" can't distinguish a system that is
782 powered off; to confirm that the unit was asleep, it is
783 necessary to force resume, and then call
784 `test_wait_for_resume()`.
785
786 This function is expected to be called from a test as part
787 of a sequence like the following:
788
789 ~~~~~~~~
790 boot_id = host.get_boot_id()
791 # trigger sleep on the host
792 host.test_wait_for_sleep()
793 # trigger resume on the host
794 host.test_wait_for_resume(boot_id)
795 ~~~~~~~~
796
797 @exception TestFail The host did not go to sleep within
798 the allowed time.
799 """
Andrew Bresticker678c0c72013-01-22 10:44:09 -0800800 if not self.ping_wait_down(timeout=self.SLEEP_TIMEOUT):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -0700801 raise error.TestFail(
802 'client failed to sleep after %d seconds' %
J. Richard Barnetteeb69d722012-06-18 17:29:44 -0700803 self.SLEEP_TIMEOUT)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -0700804
805
806 def test_wait_for_resume(self, old_boot_id):
807 """Wait for the client to resume from low-power sleep mode.
808
809 The `old_boot_id` parameter should be the value from
810 `get_boot_id()` obtained prior to entering sleep mode. A
811 `TestFail` exception is raised if the boot id changes.
812
813 See @ref test_wait_for_sleep for more on this function's
814 usage.
815
J. Richard Barnette7214e0b2013-02-06 15:20:49 -0800816 @param old_boot_id A boot id value obtained before the
J. Richard Barnette134ec2c2012-04-25 12:59:37 -0700817 target host went to sleep.
818
819 @exception TestFail The host did not respond within the
820 allowed time.
821 @exception TestFail The host responded, but the boot id test
822 indicated a reboot rather than a sleep
823 cycle.
824 """
J. Richard Barnetteeb69d722012-06-18 17:29:44 -0700825 if not self.wait_up(timeout=self.RESUME_TIMEOUT):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -0700826 raise error.TestFail(
827 'client failed to resume from sleep after %d seconds' %
J. Richard Barnetteeb69d722012-06-18 17:29:44 -0700828 self.RESUME_TIMEOUT)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -0700829 else:
830 new_boot_id = self.get_boot_id()
831 if new_boot_id != old_boot_id:
832 raise error.TestFail(
833 'client rebooted, but sleep was expected'
834 ' (old boot %s, new boot %s)'
835 % (old_boot_id, new_boot_id))
836
837
838 def test_wait_for_shutdown(self):
839 """Wait for the client to shut down.
840
841 The test for "has shut down" can't distinguish a system that
842 is merely asleep; to confirm that the unit was down, it is
843 necessary to force boot, and then call test_wait_for_boot().
844
845 This function is expected to be called from a test as part
846 of a sequence like the following:
847
848 ~~~~~~~~
849 boot_id = host.get_boot_id()
850 # trigger shutdown on the host
851 host.test_wait_for_shutdown()
852 # trigger boot on the host
853 host.test_wait_for_boot(boot_id)
854 ~~~~~~~~
855
856 @exception TestFail The host did not shut down within the
857 allowed time.
858 """
Andrew Bresticker678c0c72013-01-22 10:44:09 -0800859 if not self.ping_wait_down(timeout=self.SHUTDOWN_TIMEOUT):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -0700860 raise error.TestFail(
861 'client failed to shut down after %d seconds' %
J. Richard Barnetteeb69d722012-06-18 17:29:44 -0700862 self.SHUTDOWN_TIMEOUT)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -0700863
864
865 def test_wait_for_boot(self, old_boot_id=None):
866 """Wait for the client to boot from cold power.
867
868 The `old_boot_id` parameter should be the value from
869 `get_boot_id()` obtained prior to shutting down. A
870 `TestFail` exception is raised if the boot id does not
871 change. The boot id test is omitted if `old_boot_id` is not
872 specified.
873
874 See @ref test_wait_for_shutdown for more on this function's
875 usage.
876
J. Richard Barnette7214e0b2013-02-06 15:20:49 -0800877 @param old_boot_id A boot id value obtained before the
J. Richard Barnette134ec2c2012-04-25 12:59:37 -0700878 shut down.
879
880 @exception TestFail The host did not respond within the
881 allowed time.
882 @exception TestFail The host responded, but the boot id test
883 indicated that there was no reboot.
884 """
J. Richard Barnetteeb69d722012-06-18 17:29:44 -0700885 if not self.wait_up(timeout=self.REBOOT_TIMEOUT):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -0700886 raise error.TestFail(
887 'client failed to reboot after %d seconds' %
J. Richard Barnetteeb69d722012-06-18 17:29:44 -0700888 self.REBOOT_TIMEOUT)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -0700889 elif old_boot_id:
890 if self.get_boot_id() == old_boot_id:
891 raise error.TestFail(
892 'client is back up, but did not reboot'
893 ' (boot %s)' % old_boot_id)
Simran Basid5e5e272012-09-24 15:23:59 -0700894
895
896 @staticmethod
897 def check_for_rpm_support(hostname):
898 """For a given hostname, return whether or not it is powered by an RPM.
899
900 @return None if this host does not follows the defined naming format
901 for RPM powered DUT's in the lab. If it does follow the format,
902 it returns a regular expression MatchObject instead.
903 """
Richard Barnette82c35912012-11-20 10:09:10 -0800904 return re.match(SiteHost._RPM_HOSTNAME_REGEX, hostname)
Simran Basid5e5e272012-09-24 15:23:59 -0700905
906
907 def has_power(self):
908 """For this host, return whether or not it is powered by an RPM.
909
910 @return True if this host is in the CROS lab and follows the defined
911 naming format.
912 """
913 return SiteHost.check_for_rpm_support(self.hostname)
914
915
Simran Basid5e5e272012-09-24 15:23:59 -0700916 def power_off(self):
J. Richard Barnette7214e0b2013-02-06 15:20:49 -0800917 """Turn off power to this host via RPM."""
Simran Basidcff4252012-11-20 16:13:20 -0800918 rpm_client.set_power(self.hostname, 'OFF')
Simran Basid5e5e272012-09-24 15:23:59 -0700919
920
921 def power_on(self):
J. Richard Barnette7214e0b2013-02-06 15:20:49 -0800922 """Turn on power to this host via RPM."""
Simran Basidcff4252012-11-20 16:13:20 -0800923 rpm_client.set_power(self.hostname, 'ON')
Simran Basid5e5e272012-09-24 15:23:59 -0700924
925
926 def power_cycle(self):
J. Richard Barnette7214e0b2013-02-06 15:20:49 -0800927 """Cycle power to this host by turning it OFF, then ON."""
Simran Basidcff4252012-11-20 16:13:20 -0800928 rpm_client.set_power(self.hostname, 'CYCLE')
Simran Basic6f1f7a2012-10-16 10:47:46 -0700929
930
931 def get_platform(self):
932 """Determine the correct platform label for this host.
933
934 @returns a string representing this host's platform.
935 """
936 crossystem = utils.Crossystem(self)
937 crossystem.init()
938 # Extract fwid value and use the leading part as the platform id.
939 # fwid generally follow the format of {platform}.{firmware version}
940 # Example: Alex.X.YYY.Z or Google_Alex.X.YYY.Z
941 platform = crossystem.fwid().split('.')[0].lower()
942 # Newer platforms start with 'Google_' while the older ones do not.
943 return platform.replace('google_', '')
944
945
Aviv Keshet74c89a92013-02-04 15:18:30 -0800946 @label_decorator()
Simran Basic6f1f7a2012-10-16 10:47:46 -0700947 def get_board(self):
948 """Determine the correct board label for this host.
949
950 @returns a string representing this host's board.
951 """
952 release_info = utils.parse_cmd_output('cat /etc/lsb-release',
953 run_method=self.run)
954 board = release_info['CHROMEOS_RELEASE_BOARD']
955 # Devices in the lab generally have the correct board name but our own
956 # development devices have {board_name}-signed-{key_type}. The board
957 # name may also begin with 'x86-' which we need to keep.
958 if 'x86' not in board:
959 return 'board:%s' % board.split('-')[0]
960 return 'board:%s' % '-'.join(board.split('-')[0:2])
961
962
Aviv Keshet74c89a92013-02-04 15:18:30 -0800963 @label_decorator('lightsensor')
Simran Basic6f1f7a2012-10-16 10:47:46 -0700964 def has_lightsensor(self):
965 """Determine the correct board label for this host.
966
967 @returns the string 'lightsensor' if this host has a lightsensor or
968 None if it does not.
969 """
970 search_cmd = "find -L %s -maxdepth 4 | egrep '%s'" % (
Richard Barnette82c35912012-11-20 10:09:10 -0800971 self._LIGHTSENSOR_SEARCH_DIR, '|'.join(self._LIGHTSENSOR_FILES))
Simran Basic6f1f7a2012-10-16 10:47:46 -0700972 try:
973 # Run the search cmd following the symlinks. Stderr_tee is set to
974 # None as there can be a symlink loop, but the command will still
975 # execute correctly with a few messages printed to stderr.
976 self.run(search_cmd, stdout_tee=None, stderr_tee=None)
977 return 'lightsensor'
978 except error.AutoservRunError:
979 # egrep exited with a return code of 1 meaning none of the possible
980 # lightsensor files existed.
981 return None
982
983
Aviv Keshet74c89a92013-02-04 15:18:30 -0800984 @label_decorator('bluetooth')
Simran Basic6f1f7a2012-10-16 10:47:46 -0700985 def has_bluetooth(self):
986 """Determine the correct board label for this host.
987
988 @returns the string 'bluetooth' if this host has bluetooth or
989 None if it does not.
990 """
991 try:
992 self.run('test -d /sys/class/bluetooth/hci0')
993 # test exited with a return code of 0.
994 return 'bluetooth'
995 except error.AutoservRunError:
996 # test exited with a return code 1 meaning the directory did not
997 # exist.
998 return None
999
1000
1001 def get_labels(self):
1002 """Return a list of labels for this given host.
1003
1004 This is the main way to retrieve all the automatic labels for a host
1005 as it will run through all the currently implemented label functions.
1006 """
1007 labels = []
Richard Barnette82c35912012-11-20 10:09:10 -08001008 for label_function in self._LABEL_FUNCTIONS:
Simran Basic6f1f7a2012-10-16 10:47:46 -07001009 label = label_function(self)
1010 if label:
1011 labels.append(label)
1012 return labels