blob: f312240f0d2071bdee69cfc82ac90e8ca454fb4c [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
Christopher Wiley0ed712b2013-04-09 15:25:12 -07006import httplib
J. Richard Barnette1d78b012012-05-15 13:56:30 -07007import logging
Dan Shi0f466e82013-02-22 15:44:58 -08008import os
Simran Basid5e5e272012-09-24 15:23:59 -07009import re
Christopher Wileyd78249a2013-03-01 13:05:31 -080010import socket
J. Richard Barnette1d78b012012-05-15 13:56:30 -070011import subprocess
J. Richard Barnette134ec2c2012-04-25 12:59:37 -070012import time
J. Richard Barnette1d78b012012-05-15 13:56:30 -070013import xmlrpclib
J. Richard Barnette134ec2c2012-04-25 12:59:37 -070014
J. Richard Barnette45e93de2012-04-11 17:24:15 -070015from autotest_lib.client.bin import utils
Richard Barnette0c73ffc2012-11-19 15:21:18 -080016from autotest_lib.client.common_lib import error
17from autotest_lib.client.common_lib import global_config
J. Richard Barnette45e93de2012-04-11 17:24:15 -070018from autotest_lib.client.common_lib.cros import autoupdater
Richard Barnette03a0c132012-11-05 12:40:35 -080019from autotest_lib.client.common_lib.cros import dev_server
Christopher Wileyd78249a2013-03-01 13:05:31 -080020from autotest_lib.client.common_lib.cros import retry
Richard Barnette82c35912012-11-20 10:09:10 -080021from autotest_lib.client.cros import constants
J. Richard Barnette45e93de2012-04-11 17:24:15 -070022from autotest_lib.server import autoserv_parser
Chris Sosaf4d43ff2012-10-30 11:21:05 -070023from autotest_lib.server import autotest
Scott Zawalski89c44dd2013-02-26 09:28:02 -050024from autotest_lib.server.cros.dynamic_suite import constants as ds_constants
Simran Basi5e6339a2013-03-21 11:34:32 -070025from autotest_lib.server.cros.dynamic_suite import tools, frontend_wrappers
J. Richard Barnette75487572013-03-08 12:47:50 -080026from autotest_lib.server.cros.servo import servo
J. Richard Barnette45e93de2012-04-11 17:24:15 -070027from autotest_lib.server.hosts import remote
Simran Basidcff4252012-11-20 16:13:20 -080028from autotest_lib.site_utils.rpm_control_system import rpm_client
Simran Basid5e5e272012-09-24 15:23:59 -070029
30
J. Richard Barnettebe5ebcc2013-02-11 16:03:15 -080031def _make_servo_hostname(hostname):
32 host_parts = hostname.split('.')
33 host_parts[0] = host_parts[0] + '-servo'
34 return '.'.join(host_parts)
35
36
37def _get_lab_servo(target_hostname):
38 """Instantiate a Servo for |target_hostname| in the lab.
39
40 Assuming that |target_hostname| is a device in the CrOS test
41 lab, create and return a Servo object pointed at the servo
42 attached to that DUT. The servo in the test lab is assumed
43 to already have servod up and running on it.
44
45 @param target_hostname: device whose servo we want to target.
46 @return an appropriately configured Servo instance.
47 """
48 servo_host = _make_servo_hostname(target_hostname)
49 if utils.host_is_in_lab_zone(servo_host):
50 try:
J. Richard Barnetted5f807a2013-02-11 16:51:00 -080051 return servo.Servo(servo_host=servo_host)
J. Richard Barnettebe5ebcc2013-02-11 16:03:15 -080052 except: # pylint: disable=W0702
53 # TODO(jrbarnette): Long-term, if we can't get to
54 # a servo in the lab, we want to fail, so we should
55 # pass any exceptions along. Short-term, we're not
56 # ready to rely on servo, so we ignore failures.
57 pass
58 return None
59
60
Dale Curtiscb7bfaf2011-06-07 16:21:57 -070061def make_ssh_command(user='root', port=22, opts='', hosts_file=None,
62 connect_timeout=None, alive_interval=None):
63 """Override default make_ssh_command to use options tuned for Chrome OS.
64
65 Tuning changes:
Chris Sosaf7fcd6e2011-09-27 17:30:47 -070066 - ConnectTimeout=30; maximum of 30 seconds allowed for an SSH connection
67 failure. Consistency with remote_access.sh.
Dale Curtiscb7bfaf2011-06-07 16:21:57 -070068
Dale Curtisaa5eedb2011-08-23 16:18:52 -070069 - ServerAliveInterval=180; which causes SSH to ping connection every
70 180 seconds. In conjunction with ServerAliveCountMax ensures that if the
71 connection dies, Autotest will bail out quickly. Originally tried 60 secs,
72 but saw frequent job ABORTS where the test completed successfully.
Dale Curtiscb7bfaf2011-06-07 16:21:57 -070073
Chris Sosaf7fcd6e2011-09-27 17:30:47 -070074 - ServerAliveCountMax=3; consistency with remote_access.sh.
75
76 - ConnectAttempts=4; reduce flakiness in connection errors; consistency
77 with remote_access.sh.
Dale Curtiscb7bfaf2011-06-07 16:21:57 -070078
79 - UserKnownHostsFile=/dev/null; we don't care about the keys. Host keys
80 change with every new installation, don't waste memory/space saving them.
Chris Sosaf7fcd6e2011-09-27 17:30:47 -070081
82 - SSH protocol forced to 2; needed for ServerAliveInterval.
J. Richard Barnette7214e0b2013-02-06 15:20:49 -080083
84 @param user User name to use for the ssh connection.
85 @param port Port on the target host to use for ssh connection.
86 @param opts Additional options to the ssh command.
87 @param hosts_file Ignored.
88 @param connect_timeout Ignored.
89 @param alive_interval Ignored.
Dale Curtiscb7bfaf2011-06-07 16:21:57 -070090 """
91 base_command = ('/usr/bin/ssh -a -x %s -o StrictHostKeyChecking=no'
92 ' -o UserKnownHostsFile=/dev/null -o BatchMode=yes'
Chris Sosaf7fcd6e2011-09-27 17:30:47 -070093 ' -o ConnectTimeout=30 -o ServerAliveInterval=180'
94 ' -o ServerAliveCountMax=3 -o ConnectionAttempts=4'
95 ' -o Protocol=2 -l %s -p %d')
Dale Curtiscb7bfaf2011-06-07 16:21:57 -070096 return base_command % (opts, user, port)
J. Richard Barnette45e93de2012-04-11 17:24:15 -070097
98
J. Richard Barnette7214e0b2013-02-06 15:20:49 -080099
Aviv Keshet74c89a92013-02-04 15:18:30 -0800100def add_label_detector(label_function_list, label_list=None, label=None):
101 """Decorator used to group functions together into the provided list.
102 @param label_function_list: List of label detecting functions to add
103 decorated function to.
104 @param label_list: List of detectable labels to add detectable labels to.
105 (Default: None)
106 @param label: Label string that is detectable by this detection function
107 (Default: None)
J. Richard Barnette7214e0b2013-02-06 15:20:49 -0800108 """
Simran Basic6f1f7a2012-10-16 10:47:46 -0700109 def add_func(func):
Aviv Keshet74c89a92013-02-04 15:18:30 -0800110 """
111 @param func: The function to be added as a detector.
112 """
113 label_function_list.append(func)
114 if label and label_list is not None:
115 label_list.append(label)
Simran Basic6f1f7a2012-10-16 10:47:46 -0700116 return func
117 return add_func
118
119
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700120class SiteHost(remote.RemoteHost):
121 """Chromium OS specific subclass of Host."""
122
123 _parser = autoserv_parser.autoserv_parser
Scott Zawalski62bacae2013-03-05 10:40:32 -0500124 _AFE = frontend_wrappers.RetryingAFE(timeout_min=5, delay_sec=10)
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700125
Richard Barnette0c73ffc2012-11-19 15:21:18 -0800126 # Time to wait for new kernel to be marked successful after
127 # auto update.
Chris Masone163cead2012-05-16 11:49:48 -0700128 _KERNEL_UPDATE_TIMEOUT = 120
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700129
Richard Barnette03a0c132012-11-05 12:40:35 -0800130 # Timeout values (in seconds) associated with various Chrome OS
131 # state changes.
J. Richard Barnette134ec2c2012-04-25 12:59:37 -0700132 #
Richard Barnette0c73ffc2012-11-19 15:21:18 -0800133 # In general, a good rule of thumb is that the timeout can be up
134 # to twice the typical measured value on the slowest platform.
135 # The times here have not necessarily been empirically tested to
136 # meet this criterion.
J. Richard Barnetteeb69d722012-06-18 17:29:44 -0700137 #
138 # SLEEP_TIMEOUT: Time to allow for suspend to memory.
Richard Barnette0c73ffc2012-11-19 15:21:18 -0800139 # RESUME_TIMEOUT: Time to allow for resume after suspend, plus
140 # time to restart the netwowrk.
J. Richard Barnetteeb69d722012-06-18 17:29:44 -0700141 # BOOT_TIMEOUT: Time to allow for boot from power off. Among
Richard Barnette0c73ffc2012-11-19 15:21:18 -0800142 # other things, this must account for the 30 second dev-mode
J. Richard Barnetted4649c62013-03-06 17:42:27 -0800143 # screen delay and time to start the network.
J. Richard Barnetteeb69d722012-06-18 17:29:44 -0700144 # USB_BOOT_TIMEOUT: Time to allow for boot from a USB device,
Richard Barnette0c73ffc2012-11-19 15:21:18 -0800145 # including the 30 second dev-mode delay and time to start the
J. Richard Barnetted4649c62013-03-06 17:42:27 -0800146 # network.
Richard Barnette0c73ffc2012-11-19 15:21:18 -0800147 # SHUTDOWN_TIMEOUT: Time to allow for shut down.
Chris Sosab76e0ee2013-05-22 16:55:41 -0700148 # REBOOT_TIMEOUT: How long to wait for a reboot.
Richard Barnette03a0c132012-11-05 12:40:35 -0800149 # _INSTALL_TIMEOUT: Time to allow for chromeos-install.
J. Richard Barnetteeb69d722012-06-18 17:29:44 -0700150
151 SLEEP_TIMEOUT = 2
J. Richard Barnetted4649c62013-03-06 17:42:27 -0800152 RESUME_TIMEOUT = 10
J. Richard Barnetteeb69d722012-06-18 17:29:44 -0700153 BOOT_TIMEOUT = 45
154 USB_BOOT_TIMEOUT = 150
Chris Sosab76e0ee2013-05-22 16:55:41 -0700155
156 # We have a long timeout to ensure we don't flakily fail due to other
157 # issues. Shorter timeouts are vetted in platform_RebootAfterUpdate.
158 REBOOT_TIMEOUT = 300
159
Richard Barnette03a0c132012-11-05 12:40:35 -0800160 _INSTALL_TIMEOUT = 240
161
Ismail Noorbasha07fdb612013-02-14 14:13:31 -0800162 # _USB_POWER_TIMEOUT: Time to allow for USB to power toggle ON and OFF.
163 # _POWER_CYCLE_TIMEOUT: Time to allow for manual power cycle.
164 _USB_POWER_TIMEOUT = 5
165 _POWER_CYCLE_TIMEOUT = 10
166
Richard Barnette0c73ffc2012-11-19 15:21:18 -0800167
Richard Barnette82c35912012-11-20 10:09:10 -0800168 _RPM_RECOVERY_BOARDS = global_config.global_config.get_config_value('CROS',
169 'rpm_recovery_boards', type=str).split(',')
170
171 _MAX_POWER_CYCLE_ATTEMPTS = 6
172 _LAB_MACHINE_FILE = '/mnt/stateful_partition/.labmachine'
173 _RPM_HOSTNAME_REGEX = ('chromeos[0-9]+(-row[0-9]+)?-rack[0-9]+[a-z]*-'
174 'host[0-9]+')
175 _LIGHTSENSOR_FILES = ['in_illuminance0_input',
176 'in_illuminance0_raw',
177 'illuminance0_input']
178 _LIGHTSENSOR_SEARCH_DIR = '/sys/bus/iio/devices'
179 _LABEL_FUNCTIONS = []
Aviv Keshet74c89a92013-02-04 15:18:30 -0800180 _DETECTABLE_LABELS = []
181 label_decorator = functools.partial(add_label_detector, _LABEL_FUNCTIONS,
182 _DETECTABLE_LABELS)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -0700183
J. Richard Barnetteb6de7e32013-02-14 13:28:04 -0800184 # Constants used in ping_wait_up() and ping_wait_down().
185 #
186 # _PING_WAIT_COUNT is the approximate number of polling
187 # cycles to use when waiting for a host state change.
188 #
189 # _PING_STATUS_DOWN and _PING_STATUS_UP are names used
190 # for arguments to the internal _ping_wait_for_status()
191 # method.
192 _PING_WAIT_COUNT = 40
193 _PING_STATUS_DOWN = False
194 _PING_STATUS_UP = True
195
Ismail Noorbasha07fdb612013-02-14 14:13:31 -0800196 # Allowed values for the power_method argument.
197
198 # POWER_CONTROL_RPM: Passed as default arg for power_off/on/cycle() methods.
199 # POWER_CONTROL_SERVO: Used in set_power() and power_cycle() methods.
200 # POWER_CONTROL_MANUAL: Used in set_power() and power_cycle() methods.
201 POWER_CONTROL_RPM = 'RPM'
202 POWER_CONTROL_SERVO = 'servoj10'
203 POWER_CONTROL_MANUAL = 'manual'
204
205 POWER_CONTROL_VALID_ARGS = (POWER_CONTROL_RPM,
206 POWER_CONTROL_SERVO,
207 POWER_CONTROL_MANUAL)
Richard Barnette0c73ffc2012-11-19 15:21:18 -0800208
Simran Basi5e6339a2013-03-21 11:34:32 -0700209 _RPM_OUTLET_CHANGED = 'outlet_changed'
210
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
Scott Zawalski62bacae2013-03-05 10:40:32 -0500280 def _host_in_AFE(self):
281 """Check if the host is an object the AFE knows.
282
283 @returns the host object.
284 """
285 return self._AFE.get_hosts(hostname=self.hostname)
286
287
Chris Sosab76e0ee2013-05-22 16:55:41 -0700288 def lookup_job_repo_url(self):
289 """Looks up the job_repo_url for the host.
290
291 @returns job_repo_url from AFE or None if not found.
292
293 @raises KeyError if the host does not have a job_repo_url
294 """
295 if not self._host_in_AFE():
296 return None
297
298 hosts = self._AFE.get_hosts(hostname=self.hostname)
beepsb5efc532013-06-04 11:29:34 -0700299 if hosts and ds_constants.JOB_REPO_URL in hosts[0].attributes:
300 return hosts[0].attributes[ds_constants.JOB_REPO_URL]
Chris Sosab76e0ee2013-05-22 16:55:41 -0700301
302
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500303 def clear_cros_version_labels_and_job_repo_url(self):
304 """Clear cros_version labels and host attribute job_repo_url."""
Scott Zawalski62bacae2013-03-05 10:40:32 -0500305 if not self._host_in_AFE():
Scott Zawalskieadbf702013-03-14 09:23:06 -0400306 return
307
Scott Zawalski62bacae2013-03-05 10:40:32 -0500308 host_list = [self.hostname]
309 labels = self._AFE.get_labels(
310 name__startswith=ds_constants.VERSION_PREFIX,
311 host__hostname=self.hostname)
Dan Shi0f466e82013-02-22 15:44:58 -0800312
Scott Zawalski62bacae2013-03-05 10:40:32 -0500313 for label in labels:
314 label.remove_hosts(hosts=host_list)
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500315
beepsb5efc532013-06-04 11:29:34 -0700316 self._AFE.set_host_attribute(ds_constants.JOB_REPO_URL, None,
Scott Zawalski62bacae2013-03-05 10:40:32 -0500317 hostname=self.hostname)
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500318
319
Dan Shie9309262013-06-19 22:50:21 -0700320 def add_cros_version_labels_and_job_repo_url(self, image_name):
Scott Zawalskieadbf702013-03-14 09:23:06 -0400321 """Add cros_version labels and host attribute job_repo_url.
322
323 @param image_name: The name of the image e.g.
324 lumpy-release/R27-3837.0.0
325 """
Scott Zawalski62bacae2013-03-05 10:40:32 -0500326 if not self._host_in_AFE():
Scott Zawalskieadbf702013-03-14 09:23:06 -0400327 return
Scott Zawalski62bacae2013-03-05 10:40:32 -0500328
Scott Zawalskieadbf702013-03-14 09:23:06 -0400329 cros_label = '%s%s' % (ds_constants.VERSION_PREFIX, image_name)
Dan Shie9309262013-06-19 22:50:21 -0700330 devserver_url = dev_server.ImageServer.resolve(image_name).url()
Scott Zawalski62bacae2013-03-05 10:40:32 -0500331
332 labels = self._AFE.get_labels(name=cros_label)
333 if labels:
334 label = labels[0]
335 else:
336 label = self._AFE.create_label(name=cros_label)
337
338 label.add_hosts([self.hostname])
Scott Zawalskieadbf702013-03-14 09:23:06 -0400339 repo_url = tools.get_package_url(devserver_url, image_name)
beepsb5efc532013-06-04 11:29:34 -0700340 self._AFE.set_host_attribute(ds_constants.JOB_REPO_URL, repo_url,
Scott Zawalski62bacae2013-03-05 10:40:32 -0500341 hostname=self.hostname)
Scott Zawalskieadbf702013-03-14 09:23:06 -0400342
343
Dan Shi0f466e82013-02-22 15:44:58 -0800344 def _try_stateful_update(self, update_url, force_update, updater):
345 """Try to use stateful update to initialize DUT.
346
347 When DUT is already running the same version that machine_install
348 tries to install, stateful update is a much faster way to clean up
349 the DUT for testing, compared to a full reimage. It is implemeted
350 by calling autoupdater.run_update, but skipping updating root, as
351 updating the kernel is time consuming and not necessary.
352
353 @param update_url: url of the image.
354 @param force_update: Set to True to update the image even if the DUT
355 is running the same version.
356 @param updater: ChromiumOSUpdater instance used to update the DUT.
357 @returns: True if the DUT was updated with stateful update.
358
359 """
360 if not updater.check_version():
361 return False
362 if not force_update:
363 logging.info('Canceling stateful update because the new and '
364 'old versions are the same.')
365 return False
366 # Following folders should be rebuilt after stateful update.
367 # A test file is used to confirm each folder gets rebuilt after
368 # the stateful update.
369 folders_to_check = ['/var', '/home', '/mnt/stateful_partition']
370 test_file = '.test_file_to_be_deleted'
371 for folder in folders_to_check:
372 touch_path = os.path.join(folder, test_file)
373 self.run('touch %s' % touch_path)
374
375 if not updater.run_update(force_update=True, update_root=False):
376 return False
377
378 # Reboot to complete stateful update.
Chris Sosab76e0ee2013-05-22 16:55:41 -0700379 self.reboot(timeout=self.REBOOT_TIMEOUT, wait=True)
Dan Shi0f466e82013-02-22 15:44:58 -0800380 check_file_cmd = 'test -f %s; echo $?'
381 for folder in folders_to_check:
382 test_file_path = os.path.join(folder, test_file)
383 result = self.run(check_file_cmd % test_file_path,
384 ignore_status=True)
385 if result.exit_status == 1:
386 return False
387 return True
388
389
J. Richard Barnette7275b612013-06-04 18:13:11 -0700390 def _post_update_processing(self, updater, expected_kernel=None):
Dan Shi0f466e82013-02-22 15:44:58 -0800391 """After the DUT is updated, confirm machine_install succeeded.
392
393 @param updater: ChromiumOSUpdater instance used to update the DUT.
J. Richard Barnette7275b612013-06-04 18:13:11 -0700394 @param expected_kernel: kernel expected to be active after reboot,
395 or `None` to skip rollback checking.
Dan Shi0f466e82013-02-22 15:44:58 -0800396
397 """
J. Richard Barnette7275b612013-06-04 18:13:11 -0700398 # Touch the lab machine file to leave a marker that
399 # distinguishes this image from other test images.
400 # Afterwards, we must re-run the autoreboot script because
401 # it depends on the _LAB_MACHINE_FILE.
Dan Shi0f466e82013-02-22 15:44:58 -0800402 self.run('touch %s' % self._LAB_MACHINE_FILE)
Dan Shi0f466e82013-02-22 15:44:58 -0800403 self.run('start autoreboot')
404
J. Richard Barnette7275b612013-06-04 18:13:11 -0700405 # Figure out the newly active kernel.
406 active_kernel, _ = updater.get_kernel_state()
407
408 # Check for rollback due to a bad build.
409 if expected_kernel and active_kernel != expected_kernel:
410 # Print out some information to make it easier to debug
411 # the rollback.
Dan Shi0f466e82013-02-22 15:44:58 -0800412 logging.debug('Dumping partition table.')
Dan Shi346725f2013-03-20 15:22:38 -0700413 self.run('cgpt show $(rootdev -s -d)')
Dan Shi0f466e82013-02-22 15:44:58 -0800414 logging.debug('Dumping crossystem for firmware debugging.')
Dan Shi346725f2013-03-20 15:22:38 -0700415 self.run('crossystem --all')
Dan Shi0f466e82013-02-22 15:44:58 -0800416 raise autoupdater.ChromiumOSError(
J. Richard Barnette7275b612013-06-04 18:13:11 -0700417 'Build %s failed to boot on %s; system rolled back '
418 'to previous build' % (updater.update_version,
419 self.hostname))
Dan Shi0f466e82013-02-22 15:44:58 -0800420
J. Richard Barnette7275b612013-06-04 18:13:11 -0700421 # Check that we've got the build we meant to install.
422 if not updater.check_version_to_confirm_install():
423 raise autoupdater.ChromiumOSError(
424 'Failed to update %s to build %s; found build '
425 '%s instead' % (self.hostname,
426 updater.update_version,
427 updater.get_build_id()))
Scott Zawalski62bacae2013-03-05 10:40:32 -0500428
J. Richard Barnette7275b612013-06-04 18:13:11 -0700429 # Make sure chromeos-setgoodkernel runs.
430 try:
Dan Shi0f466e82013-02-22 15:44:58 -0800431 utils.poll_for_condition(
J. Richard Barnette7275b612013-06-04 18:13:11 -0700432 lambda: (updater.get_kernel_tries(active_kernel) == 0
433 and updater.get_kernel_success(active_kernel)),
434 exception=autoupdater.ChromiumOSError(),
Dan Shi0f466e82013-02-22 15:44:58 -0800435 timeout=self._KERNEL_UPDATE_TIMEOUT, sleep_interval=5)
J. Richard Barnette7275b612013-06-04 18:13:11 -0700436 except autoupdater.ChromiumOSError as e:
437 services_status = self.run('status system-services').stdout
438 if services_status != 'system-services start/running\n':
439 event = ('Chrome failed to reach login screen')
440 else:
441 event = ('update-engine failed to call '
442 'chromeos-setgoodkernel')
443 raise autoupdater.ChromiumOSError(
444 'After update and reboot, %s '
445 'within %d seconds' % (event,
446 self._KERNEL_UPDATE_TIMEOUT))
Dan Shi0f466e82013-02-22 15:44:58 -0800447
448
J. Richard Barnettee4af8b92013-05-01 13:16:12 -0700449 def _stage_image_for_update(self, image_name=None):
Scott Zawalskieadbf702013-03-14 09:23:06 -0400450 """Stage a build on a devserver and return the update_url.
451
452 @param image_name: a name like lumpy-release/R27-3837.0.0
453 @returns an update URL like:
454 http://172.22.50.205:8082/update/lumpy-release/R27-3837.0.0
455 """
J. Richard Barnettee4af8b92013-05-01 13:16:12 -0700456 if not image_name:
457 image_name = self.get_repair_image_name()
458 logging.info('Staging build for AU: %s', image_name)
Scott Zawalskieadbf702013-03-14 09:23:06 -0400459 devserver = dev_server.ImageServer.resolve(image_name)
460 devserver.trigger_download(image_name, synchronous=False)
461 return tools.image_url_pattern() % (devserver.url(), image_name)
462
463
J. Richard Barnettee4af8b92013-05-01 13:16:12 -0700464 def stage_image_for_servo(self, image_name=None):
465 """Stage a build on a devserver and return the update_url.
466
467 @param image_name: a name like lumpy-release/R27-3837.0.0
468 @returns an update URL like:
469 http://172.22.50.205:8082/update/lumpy-release/R27-3837.0.0
470 """
471 if not image_name:
472 image_name = self.get_repair_image_name()
473 logging.info('Staging build for servo install: %s', image_name)
474 devserver = dev_server.ImageServer.resolve(image_name)
475 devserver.stage_artifacts(image_name, ['test_image'])
476 return devserver.get_test_image_url(image_name)
477
478
Chris Sosaa3ac2152012-05-23 22:23:13 -0700479 def machine_install(self, update_url=None, force_update=False,
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500480 local_devserver=False, repair=False):
481 """Install the DUT.
482
Dan Shi0f466e82013-02-22 15:44:58 -0800483 Use stateful update if the DUT is already running the same build.
484 Stateful update does not update kernel and tends to run much faster
485 than a full reimage. If the DUT is running a different build, or it
486 failed to do a stateful update, full update, including kernel update,
487 will be applied to the DUT.
488
Scott Zawalskieadbf702013-03-14 09:23:06 -0400489 Once a host enters machine_install its cros_version label will be
490 removed as well as its host attribute job_repo_url (used for
491 package install).
492
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500493 @param update_url: The url to use for the update
494 pattern: http://$devserver:###/update/$build
495 If update_url is None and repair is True we will install the
496 stable image listed in global_config under
497 CROS.stable_cros_version.
498 @param force_update: Force an update even if the version installed
499 is the same. Default:False
500 @param local_devserver: Used by run_remote_test to allow people to
501 use their local devserver. Default: False
502 @param repair: Whether or not we are in repair mode. This adds special
503 cases for repairing a machine like starting update_engine.
504 Setting repair to True sets force_update to True as well.
505 default: False
506 @raises autoupdater.ChromiumOSError
507
508 """
J. Richard Barnettee4af8b92013-05-01 13:16:12 -0700509 if not update_url:
510 if self._parser.options.image:
511 requested_build = self._parser.options.image
512 if requested_build.startswith('http://'):
513 update_url = requested_build
514 else:
515 # Try to stage any build that does not start with
516 # http:// on the devservers defined in
517 # global_config.ini.
518 update_url = self._stage_image_for_update(
519 requested_build)
520 elif repair:
521 update_url = self._stage_image_for_update()
Scott Zawalskieadbf702013-03-14 09:23:06 -0400522 else:
J. Richard Barnettee4af8b92013-05-01 13:16:12 -0700523 raise autoupdater.ChromiumOSError(
524 'Update failed. No update URL provided.')
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500525
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500526 if repair:
Dan Shi0f466e82013-02-22 15:44:58 -0800527 # In case the system is in a bad state, we always reboot the machine
528 # before machine_install.
Chris Sosab76e0ee2013-05-22 16:55:41 -0700529 self.reboot(timeout=self.REBOOT_TIMEOUT, wait=True)
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500530 self.run('stop update-engine; start update-engine')
531 force_update = True
Dan Shi0f466e82013-02-22 15:44:58 -0800532
Chris Sosaa3ac2152012-05-23 22:23:13 -0700533 updater = autoupdater.ChromiumOSUpdater(update_url, host=self,
Chris Sosa72312602013-04-16 15:01:56 -0700534 local_devserver=local_devserver)
Dan Shi0f466e82013-02-22 15:44:58 -0800535 updated = False
Scott Zawalskieadbf702013-03-14 09:23:06 -0400536 # Remove cros-version and job_repo_url host attribute from host.
537 self.clear_cros_version_labels_and_job_repo_url()
Dan Shi0f466e82013-02-22 15:44:58 -0800538 # If the DUT is already running the same build, try stateful update
539 # first. Stateful update does not update kernel and tends to run much
540 # faster than a full reimage.
541 try:
Chris Sosab76e0ee2013-05-22 16:55:41 -0700542 updated = self._try_stateful_update(
543 update_url, force_update, updater)
Dan Shi0f466e82013-02-22 15:44:58 -0800544 if updated:
545 logging.info('DUT is updated with stateful update.')
546 except Exception as e:
547 logging.exception(e)
548 logging.warn('Failed to stateful update DUT, force to update.')
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700549
Dan Shi0f466e82013-02-22 15:44:58 -0800550 inactive_kernel = None
551 # Do a full update if stateful update is not applicable or failed.
552 if not updated:
553 # In case the system is in a bad state, we always reboot the
554 # machine before machine_install.
Chris Sosab76e0ee2013-05-22 16:55:41 -0700555 self.reboot(timeout=self.REBOOT_TIMEOUT, wait=True)
Chris Sosab7612bc2013-03-21 10:32:37 -0700556
557 # TODO(sosa): Remove temporary hack to get rid of bricked machines
558 # that can't update due to a corrupted policy.
559 self.run('rm -rf /var/lib/whitelist')
560 self.run('touch /var/lib/whitelist')
561 self.run('chmod -w /var/lib/whitelist')
Scott Zawalskib550d5a2013-03-22 09:23:59 -0400562 self.run('stop update-engine; start update-engine')
Chris Sosab7612bc2013-03-21 10:32:37 -0700563
Dan Shi0f466e82013-02-22 15:44:58 -0800564 if updater.run_update(force_update):
565 updated = True
566 # Figure out active and inactive kernel.
567 active_kernel, inactive_kernel = updater.get_kernel_state()
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700568
Dan Shi0f466e82013-02-22 15:44:58 -0800569 # Ensure inactive kernel has higher priority than active.
570 if (updater.get_kernel_priority(inactive_kernel)
571 < updater.get_kernel_priority(active_kernel)):
572 raise autoupdater.ChromiumOSError(
573 'Update failed. The priority of the inactive kernel'
574 ' partition is less than that of the active kernel'
575 ' partition.')
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700576
Dan Shi0f466e82013-02-22 15:44:58 -0800577 update_engine_log = '/var/log/update_engine.log'
578 logging.info('Dumping %s', update_engine_log)
579 self.run('cat %s' % update_engine_log)
580 # Updater has returned successfully; reboot the host.
Chris Sosab76e0ee2013-05-22 16:55:41 -0700581 self.reboot(timeout=self.REBOOT_TIMEOUT, wait=True)
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700582
Dan Shi0f466e82013-02-22 15:44:58 -0800583 if updated:
584 self._post_update_processing(updater, inactive_kernel)
Scott Zawalskieadbf702013-03-14 09:23:06 -0400585 image_name = autoupdater.url_to_image_name(update_url)
Dan Shie9309262013-06-19 22:50:21 -0700586 self.add_cros_version_labels_and_job_repo_url(image_name)
Simran Basi13fa1ba2013-03-04 10:56:47 -0800587
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700588 # Clean up any old autotest directories which may be lying around.
589 for path in global_config.global_config.get_config_value(
590 'AUTOSERV', 'client_autodir_paths', type=list):
591 self.run('rm -rf ' + path)
592
593
Simran Basi833814b2013-01-29 13:13:43 -0800594 def _get_label_from_afe(self, label_prefix):
595 """Retrieve a host's specific label from the AFE.
596
597 Looks for a host label that has the form <label_prefix>:<value>
598 and returns the "<value>" part of the label. None is returned
599 if there is not a label matching the pattern
600
601 @returns the label that matches the prefix or 'None'
602 """
Scott Zawalski62bacae2013-03-05 10:40:32 -0500603 labels = self._AFE.get_labels(name__startswith=label_prefix,
604 host__hostname__in=[self.hostname])
605 if labels and len(labels) == 1:
606 return labels[0].name.split(label_prefix, 1)[1]
Simran Basi833814b2013-01-29 13:13:43 -0800607
608
Richard Barnette82c35912012-11-20 10:09:10 -0800609 def _get_board_from_afe(self):
610 """Retrieve this host's board from its labels in the AFE.
611
612 Looks for a host label of the form "board:<board>", and
613 returns the "<board>" part of the label. `None` is returned
614 if there is not a single, unique label matching the pattern.
615
616 @returns board from label, or `None`.
617 """
Simran Basi833814b2013-01-29 13:13:43 -0800618 return self._get_label_from_afe(ds_constants.BOARD_PREFIX)
619
620
621 def get_build(self):
622 """Retrieve the current build for this Host from the AFE.
623
624 Looks through this host's labels in the AFE to determine its build.
625
626 @returns The current build or None if it could not find it or if there
627 were multiple build labels assigned to this host.
628 """
629 return self._get_label_from_afe(ds_constants.VERSION_PREFIX)
Richard Barnette82c35912012-11-20 10:09:10 -0800630
631
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500632 def _install_repair(self):
633 """Attempt to repair this host using upate-engine.
634
635 If the host is up, try installing the DUT with a stable
636 "repair" version of Chrome OS as defined in the global_config
637 under CROS.stable_cros_version.
638
Scott Zawalski62bacae2013-03-05 10:40:32 -0500639 @raises AutoservRepairMethodNA if the DUT is not reachable.
640 @raises ChromiumOSError if the install failed for some reason.
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500641
642 """
643 if not self.is_up():
Scott Zawalski62bacae2013-03-05 10:40:32 -0500644 raise error.AutoservRepairMethodNA('DUT unreachable for install.')
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500645
646 logging.info('Attempting to reimage machine to repair image.')
647 try:
648 self.machine_install(repair=True)
Fang Dengd0672f32013-03-18 17:18:09 -0700649 except autoupdater.ChromiumOSError as e:
650 logging.exception(e)
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500651 logging.info('Repair via install failed.')
Scott Zawalski62bacae2013-03-05 10:40:32 -0500652 raise
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500653
654
Scott Zawalski62bacae2013-03-05 10:40:32 -0500655 def servo_install(self, image_url=None):
656 """
657 Re-install the OS on the DUT by:
658 1) installing a test image on a USB storage device attached to the Servo
659 board,
Richard Barnette03a0c132012-11-05 12:40:35 -0800660 2) booting that image in recovery mode, and then
J. Richard Barnette31b2e312013-04-04 16:05:22 -0700661 3) installing the image with chromeos-install.
662
Scott Zawalski62bacae2013-03-05 10:40:32 -0500663 @param image_url: If specified use as the url to install on the DUT.
664 otherwise boot the currently staged image on the USB stick.
Richard Barnette03a0c132012-11-05 12:40:35 -0800665
Scott Zawalski62bacae2013-03-05 10:40:32 -0500666 @raises AutoservError if the image fails to boot.
Richard Barnette03a0c132012-11-05 12:40:35 -0800667 """
J. Richard Barnette31b2e312013-04-04 16:05:22 -0700668 self.servo.install_recovery_image(image_url)
Richard Barnette03a0c132012-11-05 12:40:35 -0800669 if not self.wait_up(timeout=self.USB_BOOT_TIMEOUT):
Scott Zawalski62bacae2013-03-05 10:40:32 -0500670 raise error.AutoservRepairFailure(
671 'DUT failed to boot from USB after %d seconds' %
672 self.USB_BOOT_TIMEOUT)
673
674 self.run('chromeos-install --yes', timeout=self._INSTALL_TIMEOUT)
Richard Barnette03a0c132012-11-05 12:40:35 -0800675 self.servo.power_long_press()
Fang Dengafb88142013-05-30 17:44:31 -0700676 self.servo.switch_usbkey('off')
Richard Barnette03a0c132012-11-05 12:40:35 -0800677 self.servo.power_short_press()
678 if not self.wait_up(timeout=self.BOOT_TIMEOUT):
679 raise error.AutoservError('DUT failed to reboot installed '
680 'test image after %d seconds' %
Scott Zawalski62bacae2013-03-05 10:40:32 -0500681 self.BOOT_TIMEOUT)
682
683
J. Richard Barnettee4af8b92013-05-01 13:16:12 -0700684 def _servo_repair_reinstall(self):
Scott Zawalski62bacae2013-03-05 10:40:32 -0500685 """Reinstall the DUT utilizing servo and a test image.
686
687 Re-install the OS on the DUT by:
688 1) installing a test image on a USB storage device attached to the Servo
689 board,
690 2) booting that image in recovery mode, and then
691 3) installing the image with chromeos-install.
692
Scott Zawalski62bacae2013-03-05 10:40:32 -0500693 @raises AutoservRepairMethodNA if the device does not have servo
694 support.
695
696 """
697 if not self.servo:
698 raise error.AutoservRepairMethodNA('Repair Reinstall NA: '
699 'DUT has no servo support.')
700
701 logging.info('Attempting to recovery servo enabled device with '
702 'servo_repair_reinstall')
703
J. Richard Barnettee4af8b92013-05-01 13:16:12 -0700704 image_url = self.stage_image_for_servo()
Scott Zawalski62bacae2013-03-05 10:40:32 -0500705 self.servo_install(image_url)
706
707
708 def _servo_repair_power(self):
709 """Attempt to repair DUT using an attached Servo.
710
711 Attempt to power on the DUT via power_long_press.
712
713 @raises AutoservRepairMethodNA if the device does not have servo
714 support.
715 @raises AutoservRepairFailure if the repair fails for any reason.
716 """
717 if not self.servo:
718 raise error.AutoservRepairMethodNA('Repair Power NA: '
719 'DUT has no servo support.')
720
721 logging.info('Attempting to recover servo enabled device by '
722 'powering it off and on.')
723 self.servo.get_power_state_controller().power_off()
724 self.servo.get_power_state_controller().power_on()
725 if self.wait_up(self.BOOT_TIMEOUT):
726 return
727
728 raise error.AutoservRepairFailure('DUT did not boot after long_press.')
Richard Barnette03a0c132012-11-05 12:40:35 -0800729
730
Richard Barnette82c35912012-11-20 10:09:10 -0800731 def _powercycle_to_repair(self):
732 """Utilize the RPM Infrastructure to bring the host back up.
733
734 If the host is not up/repaired after the first powercycle we utilize
735 auto fallback to the last good install by powercycling and rebooting the
736 host 6 times.
Scott Zawalski62bacae2013-03-05 10:40:32 -0500737
738 @raises AutoservRepairMethodNA if the device does not support remote
739 power.
740 @raises AutoservRepairFailure if the repair fails for any reason.
741
Richard Barnette82c35912012-11-20 10:09:10 -0800742 """
Scott Zawalski62bacae2013-03-05 10:40:32 -0500743 if not self.has_power():
744 raise error.AutoservRepairMethodNA('Device does not support power.')
745
Richard Barnette82c35912012-11-20 10:09:10 -0800746 logging.info('Attempting repair via RPM powercycle.')
747 failed_cycles = 0
748 self.power_cycle()
749 while not self.wait_up(timeout=self.BOOT_TIMEOUT):
750 failed_cycles += 1
751 if failed_cycles >= self._MAX_POWER_CYCLE_ATTEMPTS:
Scott Zawalski62bacae2013-03-05 10:40:32 -0500752 raise error.AutoservRepairFailure(
753 'Powercycled host %s %d times; device did not come back'
754 ' online.' % (self.hostname, failed_cycles))
Richard Barnette82c35912012-11-20 10:09:10 -0800755 self.power_cycle()
756 if failed_cycles == 0:
757 logging.info('Powercycling was successful first time.')
758 else:
759 logging.info('Powercycling was successful after %d failures.',
760 failed_cycles)
761
762
763 def repair_full(self):
764 """Repair a host for repair level NO_PROTECTION.
765
766 This overrides the base class function for repair; it does
767 not call back to the parent class, but instead offers a
768 simplified implementation based on the capabilities in the
769 Chrome OS test lab.
770
J. Richard Barnettefde55fc2013-03-15 17:47:01 -0700771 If `self.verify()` fails, the following procedures are
772 attempted:
773 1. Try to re-install to a known stable image using
774 auto-update.
Scott Zawalski62bacae2013-03-05 10:40:32 -0500775 2. If there's a servo for the DUT, try to power the DUT off and
776 on.
777 3. If there's a servo for the DUT, try to re-install via
J. Richard Barnettefde55fc2013-03-15 17:47:01 -0700778 the servo.
Scott Zawalski62bacae2013-03-05 10:40:32 -0500779 4. If the DUT can be power-cycled via RPM, try to repair
Richard Barnette82c35912012-11-20 10:09:10 -0800780 by power-cycling.
781
782 As with the parent method, the last operation performed on
783 the DUT must be to call `self.verify()`; if that call fails,
784 the exception it raises is passed back to the caller.
J. Richard Barnettefde55fc2013-03-15 17:47:01 -0700785
Scott Zawalski62bacae2013-03-05 10:40:32 -0500786 @raises AutoservRepairTotalFailure if the repair process fails to
787 fix the DUT.
Richard Barnette82c35912012-11-20 10:09:10 -0800788 """
Scott Zawalski62bacae2013-03-05 10:40:32 -0500789 # TODO(scottz): This should use something similar to label_decorator,
790 # but needs to be populated in order so DUTs are repaired with the
791 # least amount of effort.
792 repair_funcs = [self._install_repair, self._servo_repair_power,
J. Richard Barnettee4af8b92013-05-01 13:16:12 -0700793 self._servo_repair_reinstall,
Scott Zawalski62bacae2013-03-05 10:40:32 -0500794 self._powercycle_to_repair]
795 errors = []
796 for repair_func in repair_funcs:
797 try:
798 repair_func()
799 self.verify()
800 return
801 except Exception as e:
802 logging.warn('Failed to repair device: %s', e)
803 errors.append(str(e))
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500804
Scott Zawalski62bacae2013-03-05 10:40:32 -0500805 raise error.AutoservRepairTotalFailure(
806 'All attempts at repairing the device failed:\n%s' %
807 '\n'.join(errors))
Richard Barnette82c35912012-11-20 10:09:10 -0800808
809
J. Richard Barnette1d78b012012-05-15 13:56:30 -0700810 def close(self):
811 super(SiteHost, self).close()
812 self.xmlrpc_disconnect_all()
813
814
Simran Basi5e6339a2013-03-21 11:34:32 -0700815 def _cleanup_poweron(self):
816 """Special cleanup method to make sure hosts always get power back."""
817 afe = frontend_wrappers.RetryingAFE(timeout_min=5, delay_sec=10)
818 hosts = afe.get_hosts(hostname=self.hostname)
819 if not hosts or not (self._RPM_OUTLET_CHANGED in
820 hosts[0].attributes):
821 return
822 logging.debug('This host has recently interacted with the RPM'
823 ' Infrastructure. Ensuring power is on.')
824 try:
825 self.power_on()
826 except rpm_client.RemotePowerException:
827 # If cleanup has completed but there was an issue with the RPM
828 # Infrastructure, log an error message rather than fail cleanup
829 logging.error('Failed to turn Power On for this host after '
830 'cleanup through the RPM Infrastructure.')
831 afe.set_host_attribute(self._RPM_OUTLET_CHANGED, None,
832 hostname=self.hostname)
833
834
Chris Sosaf4d43ff2012-10-30 11:21:05 -0700835 def cleanup(self):
Chris Sosaf4d43ff2012-10-30 11:21:05 -0700836 client_at = autotest.Autotest(self)
Richard Barnette82c35912012-11-20 10:09:10 -0800837 self.run('rm -f %s' % constants.CLEANUP_LOGS_PAUSED_FILE)
Scott Zawalskiddbc31e2012-11-15 11:29:01 -0500838 try:
839 client_at.run_static_method('autotest_lib.client.cros.cros_ui',
840 '_clear_login_prompt_state')
841 self.run('restart ui')
842 client_at.run_static_method('autotest_lib.client.cros.cros_ui',
843 '_wait_for_login_prompt')
Alex Millerf4517962013-02-25 15:03:02 -0800844 except (error.AutotestRunError, error.AutoservRunError):
Scott Zawalskiddbc31e2012-11-15 11:29:01 -0500845 logging.warn('Unable to restart ui, rebooting device.')
846 # Since restarting the UI fails fall back to normal Autotest
847 # cleanup routines, i.e. reboot the machine.
848 super(SiteHost, self).cleanup()
Simran Basi5e6339a2013-03-21 11:34:32 -0700849 # Check if the rpm outlet was manipulated.
Simran Basid5e5e272012-09-24 15:23:59 -0700850 if self.has_power():
Simran Basi5e6339a2013-03-21 11:34:32 -0700851 self._cleanup_poweron()
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700852
853
Yu-Ju Honga2be94a2012-07-31 09:48:52 -0700854 def reboot(self, **dargs):
855 """
856 This function reboots the site host. The more generic
857 RemoteHost.reboot() performs sync and sleeps for 5
858 seconds. This is not necessary for Chrome OS devices as the
859 sync should be finished in a short time during the reboot
860 command.
861 """
Tom Wai-Hong Tamf5cd1d42012-08-13 12:04:08 +0800862 if 'reboot_cmd' not in dargs:
863 dargs['reboot_cmd'] = ('((reboot & sleep 10; reboot -f &)'
864 ' </dev/null >/dev/null 2>&1 &)')
Yu-Ju Honga2be94a2012-07-31 09:48:52 -0700865 # Enable fastsync to avoid running extra sync commands before reboot.
Tom Wai-Hong Tamf5cd1d42012-08-13 12:04:08 +0800866 if 'fastsync' not in dargs:
867 dargs['fastsync'] = True
Yu-Ju Honga2be94a2012-07-31 09:48:52 -0700868 super(SiteHost, self).reboot(**dargs)
869
870
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700871 def verify_software(self):
Richard Barnetteb2bc13c2013-01-08 17:32:51 -0800872 """Verify working software on a Chrome OS system.
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700873
Richard Barnetteb2bc13c2013-01-08 17:32:51 -0800874 Tests for the following conditions:
875 1. All conditions tested by the parent version of this
876 function.
877 2. Sufficient space in /mnt/stateful_partition.
Fang Deng6b05f5b2013-03-20 13:42:11 -0700878 3. Sufficient space in /mnt/stateful_partition/encrypted.
879 4. update_engine answers a simple status request over DBus.
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700880
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700881 """
882 super(SiteHost, self).verify_software()
883 self.check_diskspace(
884 '/mnt/stateful_partition',
885 global_config.global_config.get_config_value(
Fang Deng6b05f5b2013-03-20 13:42:11 -0700886 'SERVER', 'gb_diskspace_required', type=float,
887 default=20.0))
888 self.check_diskspace(
889 '/mnt/stateful_partition/encrypted',
890 global_config.global_config.get_config_value(
891 'SERVER', 'gb_encrypted_diskspace_required', type=float,
892 default=0.1))
Richard Barnetteb2bc13c2013-01-08 17:32:51 -0800893 self.run('update_engine_client --status')
Scott Zawalskifbca4a92013-03-04 15:56:42 -0500894 # Makes sure python is present, loads and can use built in functions.
895 # We have seen cases where importing cPickle fails with undefined
896 # symbols in cPickle.so.
897 self.run('python -c "import cPickle"')
J. Richard Barnette134ec2c2012-04-25 12:59:37 -0700898
899
Christopher Wileyd78249a2013-03-01 13:05:31 -0800900 def xmlrpc_connect(self, command, port, command_name=None,
901 ready_test_name=None, timeout_seconds=10):
J. Richard Barnette1d78b012012-05-15 13:56:30 -0700902 """Connect to an XMLRPC server on the host.
903
904 The `command` argument should be a simple shell command that
905 starts an XMLRPC server on the given `port`. The command
906 must not daemonize, and must terminate cleanly on SIGTERM.
907 The command is started in the background on the host, and a
908 local XMLRPC client for the server is created and returned
909 to the caller.
910
911 Note that the process of creating an XMLRPC client makes no
912 attempt to connect to the remote server; the caller is
913 responsible for determining whether the server is running
914 correctly, and is ready to serve requests.
915
Christopher Wileyd78249a2013-03-01 13:05:31 -0800916 Optionally, the caller can pass ready_test_name, a string
917 containing the name of a method to call on the proxy. This
918 method should take no parameters and return successfully only
919 when the server is ready to process client requests. When
920 ready_test_name is set, xmlrpc_connect will block until the
921 proxy is ready, and throw a TestError if the server isn't
922 ready by timeout_seconds.
923
J. Richard Barnette1d78b012012-05-15 13:56:30 -0700924 @param command Shell command to start the server.
925 @param port Port number on which the server is expected to
926 be serving.
J. Richard Barnette7214e0b2013-02-06 15:20:49 -0800927 @param command_name String to use as input to `pkill` to
928 terminate the XMLRPC server on the host.
Christopher Wileyd78249a2013-03-01 13:05:31 -0800929 @param ready_test_name String containing the name of a
930 method defined on the XMLRPC server.
931 @param timeout_seconds Number of seconds to wait
932 for the server to become 'ready.' Will throw a
933 TestFail error if server is not ready in time.
934
J. Richard Barnette1d78b012012-05-15 13:56:30 -0700935 """
936 self.xmlrpc_disconnect(port)
937
938 # Chrome OS on the target closes down most external ports
939 # for security. We could open the port, but doing that
940 # would conflict with security tests that check that only
941 # expected ports are open. So, to get to the port on the
942 # target we use an ssh tunnel.
943 local_port = utils.get_unused_port()
944 tunnel_options = '-n -N -q -L %d:localhost:%d' % (local_port, port)
945 ssh_cmd = make_ssh_command(opts=tunnel_options)
946 tunnel_cmd = '%s %s' % (ssh_cmd, self.hostname)
947 logging.debug('Full tunnel command: %s', tunnel_cmd)
948 tunnel_proc = subprocess.Popen(tunnel_cmd, shell=True, close_fds=True)
949 logging.debug('Started XMLRPC tunnel, local = %d'
950 ' remote = %d, pid = %d',
951 local_port, port, tunnel_proc.pid)
952
953 # Start the server on the host. Redirection in the command
954 # below is necessary, because 'ssh' won't terminate until
955 # background child processes close stdin, stdout, and
956 # stderr.
957 remote_cmd = '( %s ) </dev/null >/dev/null 2>&1 & echo $!' % command
958 remote_pid = self.run(remote_cmd).stdout.rstrip('\n')
959 logging.debug('Started XMLRPC server on host %s, pid = %s',
960 self.hostname, remote_pid)
961
J. Richard Barnette7214e0b2013-02-06 15:20:49 -0800962 self._xmlrpc_proxy_map[port] = (command_name, tunnel_proc)
J. Richard Barnette1d78b012012-05-15 13:56:30 -0700963 rpc_url = 'http://localhost:%d' % local_port
Christopher Wileyd78249a2013-03-01 13:05:31 -0800964 proxy = xmlrpclib.ServerProxy(rpc_url, allow_none=True)
965 if ready_test_name is not None:
J. Richard Barnette13eb7c02013-03-07 12:06:29 -0800966 # retry.retry logs each attempt; calculate delay_sec to
967 # keep log spam to a dull roar.
Christopher Wiley0ed712b2013-04-09 15:25:12 -0700968 @retry.retry((socket.error,
969 xmlrpclib.ProtocolError,
970 httplib.BadStatusLine),
Christopher Wileyd78249a2013-03-01 13:05:31 -0800971 timeout_min=timeout_seconds/60.0,
J. Richard Barnette13eb7c02013-03-07 12:06:29 -0800972 delay_sec=min(max(timeout_seconds/20.0, 0.1), 1))
Christopher Wileyd78249a2013-03-01 13:05:31 -0800973 def ready_test():
974 """ Call proxy.ready_test_name(). """
975 getattr(proxy, ready_test_name)()
976 successful = False
977 try:
978 logging.info('Waiting %d seconds for XMLRPC server '
979 'to start.', timeout_seconds)
980 ready_test()
981 successful = True
982 except retry.TimeoutException:
983 raise error.TestError('Unable to start XMLRPC server after '
984 '%d seconds.' % timeout_seconds)
985 finally:
986 if not successful:
987 logging.error('Failed to start XMLRPC server.')
988 self.xmlrpc_disconnect(port)
989 logging.info('XMLRPC server started successfully.')
990 return proxy
J. Richard Barnette1d78b012012-05-15 13:56:30 -0700991
992 def xmlrpc_disconnect(self, port):
993 """Disconnect from an XMLRPC server on the host.
994
995 Terminates the remote XMLRPC server previously started for
996 the given `port`. Also closes the local ssh tunnel created
997 for the connection to the host. This function does not
998 directly alter the state of a previously returned XMLRPC
999 client object; however disconnection will cause all
1000 subsequent calls to methods on the object to fail.
1001
1002 This function does nothing if requested to disconnect a port
1003 that was not previously connected via `self.xmlrpc_connect()`
1004
1005 @param port Port number passed to a previous call to
1006 `xmlrpc_connect()`
1007 """
1008 if port not in self._xmlrpc_proxy_map:
1009 return
1010 entry = self._xmlrpc_proxy_map[port]
1011 remote_name = entry[0]
1012 tunnel_proc = entry[1]
1013 if remote_name:
1014 # We use 'pkill' to find our target process rather than
1015 # a PID, because the host may have rebooted since
1016 # connecting, and we don't want to kill an innocent
1017 # process with the same PID.
1018 #
1019 # 'pkill' helpfully exits with status 1 if no target
1020 # process is found, for which run() will throw an
Simran Basid5e5e272012-09-24 15:23:59 -07001021 # exception. We don't want that, so we the ignore
J. Richard Barnette1d78b012012-05-15 13:56:30 -07001022 # status.
1023 self.run("pkill -f '%s'" % remote_name, ignore_status=True)
1024
1025 if tunnel_proc.poll() is None:
1026 tunnel_proc.terminate()
1027 logging.debug('Terminated tunnel, pid %d', tunnel_proc.pid)
1028 else:
1029 logging.debug('Tunnel pid %d terminated early, status %d',
1030 tunnel_proc.pid, tunnel_proc.returncode)
1031 del self._xmlrpc_proxy_map[port]
1032
1033
1034 def xmlrpc_disconnect_all(self):
1035 """Disconnect all known XMLRPC proxy ports."""
1036 for port in self._xmlrpc_proxy_map.keys():
1037 self.xmlrpc_disconnect(port)
1038
1039
J. Richard Barnetteb6de7e32013-02-14 13:28:04 -08001040 def _ping_check_status(self, status):
1041 """Ping the host once, and return whether it has a given status.
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001042
J. Richard Barnetteb6de7e32013-02-14 13:28:04 -08001043 @param status Check the ping status against this value.
1044 @return True iff `status` and the result of ping are the same
1045 (i.e. both True or both False).
1046
1047 """
1048 ping_val = utils.ping(self.hostname, tries=1, deadline=1)
1049 return not (status ^ (ping_val == 0))
1050
1051 def _ping_wait_for_status(self, status, timeout):
1052 """Wait for the host to have a given status (UP or DOWN).
1053
1054 Status is checked by polling. Polling will not last longer
1055 than the number of seconds in `timeout`. The polling
1056 interval will be long enough that only approximately
1057 _PING_WAIT_COUNT polling cycles will be executed, subject
1058 to a maximum interval of about one minute.
1059
1060 @param status Waiting will stop immediately if `ping` of the
1061 host returns this status.
1062 @param timeout Poll for at most this many seconds.
1063 @return True iff the host status from `ping` matched the
1064 requested status at the time of return.
1065
1066 """
1067 # _ping_check_status() takes about 1 second, hence the
1068 # "- 1" in the formula below.
1069 poll_interval = min(int(timeout / self._PING_WAIT_COUNT), 60) - 1
1070 end_time = time.time() + timeout
1071 while time.time() <= end_time:
1072 if self._ping_check_status(status):
1073 return True
1074 if poll_interval > 0:
1075 time.sleep(poll_interval)
1076
1077 # The last thing we did was sleep(poll_interval), so it may
1078 # have been too long since the last `ping`. Check one more
1079 # time, just to be sure.
1080 return self._ping_check_status(status)
1081
1082 def ping_wait_up(self, timeout):
1083 """Wait for the host to respond to `ping`.
1084
1085 N.B. This method is not a reliable substitute for
1086 `wait_up()`, because a host that responds to ping will not
1087 necessarily respond to ssh. This method should only be used
1088 if the target DUT can be considered functional even if it
1089 can't be reached via ssh.
1090
1091 @param timeout Minimum time to allow before declaring the
1092 host to be non-responsive.
1093 @return True iff the host answered to ping before the timeout.
1094
1095 """
1096 return self._ping_wait_for_status(self._PING_STATUS_UP, timeout)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001097
Andrew Bresticker678c0c72013-01-22 10:44:09 -08001098 def ping_wait_down(self, timeout):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001099 """Wait until the host no longer responds to `ping`.
1100
J. Richard Barnetteb6de7e32013-02-14 13:28:04 -08001101 This function can be used as a slightly faster version of
1102 `wait_down()`, by avoiding potentially long ssh timeouts.
1103
1104 @param timeout Minimum time to allow for the host to become
1105 non-responsive.
1106 @return True iff the host quit answering ping before the
1107 timeout.
1108
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001109 """
J. Richard Barnetteb6de7e32013-02-14 13:28:04 -08001110 return self._ping_wait_for_status(self._PING_STATUS_DOWN, timeout)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001111
1112 def test_wait_for_sleep(self):
1113 """Wait for the client to enter low-power sleep mode.
1114
1115 The test for "is asleep" can't distinguish a system that is
1116 powered off; to confirm that the unit was asleep, it is
1117 necessary to force resume, and then call
1118 `test_wait_for_resume()`.
1119
1120 This function is expected to be called from a test as part
1121 of a sequence like the following:
1122
1123 ~~~~~~~~
1124 boot_id = host.get_boot_id()
1125 # trigger sleep on the host
1126 host.test_wait_for_sleep()
1127 # trigger resume on the host
1128 host.test_wait_for_resume(boot_id)
1129 ~~~~~~~~
1130
1131 @exception TestFail The host did not go to sleep within
1132 the allowed time.
1133 """
Andrew Bresticker678c0c72013-01-22 10:44:09 -08001134 if not self.ping_wait_down(timeout=self.SLEEP_TIMEOUT):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001135 raise error.TestFail(
1136 'client failed to sleep after %d seconds' %
J. Richard Barnetteeb69d722012-06-18 17:29:44 -07001137 self.SLEEP_TIMEOUT)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001138
1139
1140 def test_wait_for_resume(self, old_boot_id):
1141 """Wait for the client to resume from low-power sleep mode.
1142
1143 The `old_boot_id` parameter should be the value from
1144 `get_boot_id()` obtained prior to entering sleep mode. A
1145 `TestFail` exception is raised if the boot id changes.
1146
1147 See @ref test_wait_for_sleep for more on this function's
1148 usage.
1149
J. Richard Barnette7214e0b2013-02-06 15:20:49 -08001150 @param old_boot_id A boot id value obtained before the
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001151 target host went to sleep.
1152
1153 @exception TestFail The host did not respond within the
1154 allowed time.
1155 @exception TestFail The host responded, but the boot id test
1156 indicated a reboot rather than a sleep
1157 cycle.
1158 """
J. Richard Barnetteeb69d722012-06-18 17:29:44 -07001159 if not self.wait_up(timeout=self.RESUME_TIMEOUT):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001160 raise error.TestFail(
1161 'client failed to resume from sleep after %d seconds' %
J. Richard Barnetteeb69d722012-06-18 17:29:44 -07001162 self.RESUME_TIMEOUT)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001163 else:
1164 new_boot_id = self.get_boot_id()
1165 if new_boot_id != old_boot_id:
1166 raise error.TestFail(
1167 'client rebooted, but sleep was expected'
1168 ' (old boot %s, new boot %s)'
1169 % (old_boot_id, new_boot_id))
1170
1171
1172 def test_wait_for_shutdown(self):
1173 """Wait for the client to shut down.
1174
1175 The test for "has shut down" can't distinguish a system that
1176 is merely asleep; to confirm that the unit was down, it is
1177 necessary to force boot, and then call test_wait_for_boot().
1178
1179 This function is expected to be called from a test as part
1180 of a sequence like the following:
1181
1182 ~~~~~~~~
1183 boot_id = host.get_boot_id()
1184 # trigger shutdown on the host
1185 host.test_wait_for_shutdown()
1186 # trigger boot on the host
1187 host.test_wait_for_boot(boot_id)
1188 ~~~~~~~~
1189
1190 @exception TestFail The host did not shut down within the
1191 allowed time.
1192 """
Andrew Bresticker678c0c72013-01-22 10:44:09 -08001193 if not self.ping_wait_down(timeout=self.SHUTDOWN_TIMEOUT):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001194 raise error.TestFail(
1195 'client failed to shut down after %d seconds' %
J. Richard Barnetteeb69d722012-06-18 17:29:44 -07001196 self.SHUTDOWN_TIMEOUT)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001197
1198
1199 def test_wait_for_boot(self, old_boot_id=None):
1200 """Wait for the client to boot from cold power.
1201
1202 The `old_boot_id` parameter should be the value from
1203 `get_boot_id()` obtained prior to shutting down. A
1204 `TestFail` exception is raised if the boot id does not
1205 change. The boot id test is omitted if `old_boot_id` is not
1206 specified.
1207
1208 See @ref test_wait_for_shutdown for more on this function's
1209 usage.
1210
J. Richard Barnette7214e0b2013-02-06 15:20:49 -08001211 @param old_boot_id A boot id value obtained before the
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001212 shut down.
1213
1214 @exception TestFail The host did not respond within the
1215 allowed time.
1216 @exception TestFail The host responded, but the boot id test
1217 indicated that there was no reboot.
1218 """
J. Richard Barnetteeb69d722012-06-18 17:29:44 -07001219 if not self.wait_up(timeout=self.REBOOT_TIMEOUT):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001220 raise error.TestFail(
1221 'client failed to reboot after %d seconds' %
J. Richard Barnetteeb69d722012-06-18 17:29:44 -07001222 self.REBOOT_TIMEOUT)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001223 elif old_boot_id:
1224 if self.get_boot_id() == old_boot_id:
1225 raise error.TestFail(
1226 'client is back up, but did not reboot'
1227 ' (boot %s)' % old_boot_id)
Simran Basid5e5e272012-09-24 15:23:59 -07001228
1229
1230 @staticmethod
1231 def check_for_rpm_support(hostname):
1232 """For a given hostname, return whether or not it is powered by an RPM.
1233
1234 @return None if this host does not follows the defined naming format
1235 for RPM powered DUT's in the lab. If it does follow the format,
1236 it returns a regular expression MatchObject instead.
1237 """
Richard Barnette82c35912012-11-20 10:09:10 -08001238 return re.match(SiteHost._RPM_HOSTNAME_REGEX, hostname)
Simran Basid5e5e272012-09-24 15:23:59 -07001239
1240
1241 def has_power(self):
1242 """For this host, return whether or not it is powered by an RPM.
1243
1244 @return True if this host is in the CROS lab and follows the defined
1245 naming format.
1246 """
1247 return SiteHost.check_for_rpm_support(self.hostname)
1248
1249
Ismail Noorbasha07fdb612013-02-14 14:13:31 -08001250 def _set_power(self, state, power_method):
1251 """Sets the power to the host via RPM, Servo or manual.
1252
1253 @param state Specifies which power state to set to DUT
1254 @param power_method Specifies which method of power control to
1255 use. By default "RPM" will be used. Valid values
1256 are the strings "RPM", "manual", "servoj10".
1257
1258 """
1259 ACCEPTABLE_STATES = ['ON', 'OFF']
1260
1261 if state.upper() not in ACCEPTABLE_STATES:
1262 raise error.TestError('State must be one of: %s.'
1263 % (ACCEPTABLE_STATES,))
1264
1265 if power_method == self.POWER_CONTROL_SERVO:
1266 logging.info('Setting servo port J10 to %s', state)
1267 self.servo.set('prtctl3_pwren', state.lower())
1268 time.sleep(self._USB_POWER_TIMEOUT)
1269 elif power_method == self.POWER_CONTROL_MANUAL:
1270 logging.info('You have %d seconds to set the AC power to %s.',
1271 self._POWER_CYCLE_TIMEOUT, state)
1272 time.sleep(self._POWER_CYCLE_TIMEOUT)
1273 else:
1274 if not self.has_power():
1275 raise error.TestFail('DUT does not have RPM connected.')
Simran Basi5e6339a2013-03-21 11:34:32 -07001276 afe = frontend_wrappers.RetryingAFE(timeout_min=5, delay_sec=10)
1277 afe.set_host_attribute(self._RPM_OUTLET_CHANGED, True,
1278 hostname=self.hostname)
Ismail Noorbasha07fdb612013-02-14 14:13:31 -08001279 rpm_client.set_power(self.hostname, state.upper())
Simran Basid5e5e272012-09-24 15:23:59 -07001280
1281
Ismail Noorbasha07fdb612013-02-14 14:13:31 -08001282 def power_off(self, power_method=POWER_CONTROL_RPM):
1283 """Turn off power to this host via RPM, Servo or manual.
1284
1285 @param power_method Specifies which method of power control to
1286 use. By default "RPM" will be used. Valid values
1287 are the strings "RPM", "manual", "servoj10".
1288
1289 """
1290 self._set_power('OFF', power_method)
Simran Basid5e5e272012-09-24 15:23:59 -07001291
1292
Ismail Noorbasha07fdb612013-02-14 14:13:31 -08001293 def power_on(self, power_method=POWER_CONTROL_RPM):
1294 """Turn on power to this host via RPM, Servo or manual.
1295
1296 @param power_method Specifies which method of power control to
1297 use. By default "RPM" will be used. Valid values
1298 are the strings "RPM", "manual", "servoj10".
1299
1300 """
1301 self._set_power('ON', power_method)
1302
1303
1304 def power_cycle(self, power_method=POWER_CONTROL_RPM):
1305 """Cycle power to this host by turning it OFF, then ON.
1306
1307 @param power_method Specifies which method of power control to
1308 use. By default "RPM" will be used. Valid values
1309 are the strings "RPM", "manual", "servoj10".
1310
1311 """
1312 if power_method in (self.POWER_CONTROL_SERVO,
1313 self.POWER_CONTROL_MANUAL):
1314 self.power_off(power_method=power_method)
1315 time.sleep(self._POWER_CYCLE_TIMEOUT)
1316 self.power_on(power_method=power_method)
1317 else:
1318 rpm_client.set_power(self.hostname, 'CYCLE')
Simran Basic6f1f7a2012-10-16 10:47:46 -07001319
1320
1321 def get_platform(self):
1322 """Determine the correct platform label for this host.
1323
1324 @returns a string representing this host's platform.
1325 """
1326 crossystem = utils.Crossystem(self)
1327 crossystem.init()
1328 # Extract fwid value and use the leading part as the platform id.
1329 # fwid generally follow the format of {platform}.{firmware version}
1330 # Example: Alex.X.YYY.Z or Google_Alex.X.YYY.Z
1331 platform = crossystem.fwid().split('.')[0].lower()
1332 # Newer platforms start with 'Google_' while the older ones do not.
1333 return platform.replace('google_', '')
1334
1335
Aviv Keshet74c89a92013-02-04 15:18:30 -08001336 @label_decorator()
Simran Basic6f1f7a2012-10-16 10:47:46 -07001337 def get_board(self):
1338 """Determine the correct board label for this host.
1339
1340 @returns a string representing this host's board.
1341 """
1342 release_info = utils.parse_cmd_output('cat /etc/lsb-release',
1343 run_method=self.run)
1344 board = release_info['CHROMEOS_RELEASE_BOARD']
1345 # Devices in the lab generally have the correct board name but our own
1346 # development devices have {board_name}-signed-{key_type}. The board
1347 # name may also begin with 'x86-' which we need to keep.
Simran Basi833814b2013-01-29 13:13:43 -08001348 board_format_string = ds_constants.BOARD_PREFIX + '%s'
Simran Basic6f1f7a2012-10-16 10:47:46 -07001349 if 'x86' not in board:
Simran Basi833814b2013-01-29 13:13:43 -08001350 return board_format_string % board.split('-')[0]
1351 return board_format_string % '-'.join(board.split('-')[0:2])
Simran Basic6f1f7a2012-10-16 10:47:46 -07001352
1353
Aviv Keshet74c89a92013-02-04 15:18:30 -08001354 @label_decorator('lightsensor')
Simran Basic6f1f7a2012-10-16 10:47:46 -07001355 def has_lightsensor(self):
1356 """Determine the correct board label for this host.
1357
1358 @returns the string 'lightsensor' if this host has a lightsensor or
1359 None if it does not.
1360 """
1361 search_cmd = "find -L %s -maxdepth 4 | egrep '%s'" % (
Richard Barnette82c35912012-11-20 10:09:10 -08001362 self._LIGHTSENSOR_SEARCH_DIR, '|'.join(self._LIGHTSENSOR_FILES))
Simran Basic6f1f7a2012-10-16 10:47:46 -07001363 try:
1364 # Run the search cmd following the symlinks. Stderr_tee is set to
1365 # None as there can be a symlink loop, but the command will still
1366 # execute correctly with a few messages printed to stderr.
1367 self.run(search_cmd, stdout_tee=None, stderr_tee=None)
1368 return 'lightsensor'
1369 except error.AutoservRunError:
1370 # egrep exited with a return code of 1 meaning none of the possible
1371 # lightsensor files existed.
1372 return None
1373
1374
Aviv Keshet74c89a92013-02-04 15:18:30 -08001375 @label_decorator('bluetooth')
Simran Basic6f1f7a2012-10-16 10:47:46 -07001376 def has_bluetooth(self):
1377 """Determine the correct board label for this host.
1378
1379 @returns the string 'bluetooth' if this host has bluetooth or
1380 None if it does not.
1381 """
1382 try:
1383 self.run('test -d /sys/class/bluetooth/hci0')
1384 # test exited with a return code of 0.
1385 return 'bluetooth'
1386 except error.AutoservRunError:
1387 # test exited with a return code 1 meaning the directory did not
1388 # exist.
1389 return None
1390
1391
1392 def get_labels(self):
1393 """Return a list of labels for this given host.
1394
1395 This is the main way to retrieve all the automatic labels for a host
1396 as it will run through all the currently implemented label functions.
1397 """
1398 labels = []
Richard Barnette82c35912012-11-20 10:09:10 -08001399 for label_function in self._LABEL_FUNCTIONS:
Simran Basic6f1f7a2012-10-16 10:47:46 -07001400 label = label_function(self)
1401 if label:
1402 labels.append(label)
1403 return labels