blob: 6d20eaa4cdc4ab7daa02df68a0a6f482409d3d0e [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
Dan Shi0f466e82013-02-22 15:44:58 -08007import os
Simran Basid5e5e272012-09-24 15:23:59 -07008import re
Christopher Wileyd78249a2013-03-01 13:05:31 -08009import socket
J. Richard Barnette1d78b012012-05-15 13:56:30 -070010import subprocess
J. Richard Barnette134ec2c2012-04-25 12:59:37 -070011import time
J. Richard Barnette1d78b012012-05-15 13:56:30 -070012import xmlrpclib
J. Richard Barnette134ec2c2012-04-25 12:59:37 -070013
J. Richard Barnette45e93de2012-04-11 17:24:15 -070014from autotest_lib.client.bin import utils
Richard Barnette0c73ffc2012-11-19 15:21:18 -080015from autotest_lib.client.common_lib import error
16from autotest_lib.client.common_lib import global_config
J. Richard Barnette45e93de2012-04-11 17:24:15 -070017from autotest_lib.client.common_lib.cros import autoupdater
Richard Barnette03a0c132012-11-05 12:40:35 -080018from autotest_lib.client.common_lib.cros import dev_server
Christopher Wileyd78249a2013-03-01 13:05:31 -080019from autotest_lib.client.common_lib.cros import retry
Richard Barnette82c35912012-11-20 10:09:10 -080020from autotest_lib.client.cros import constants
J. Richard Barnette45e93de2012-04-11 17:24:15 -070021from autotest_lib.server import autoserv_parser
Chris Sosaf4d43ff2012-10-30 11:21:05 -070022from autotest_lib.server import autotest
J. Richard Barnette45e93de2012-04-11 17:24:15 -070023from autotest_lib.server import site_host_attributes
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
Richard Barnette82c35912012-11-20 10:09:10 -080030# Importing frontend.afe.models requires a full Autotest
31# installation (with the Django modules), not just the source
32# repository. Most developers won't have the full installation, so
33# the imports below will fail for them.
34#
35# The fix is to catch import exceptions, and set `models` to `None`
36# on failure. This has the side effect that
37# SiteHost._get_board_from_afe() will fail: That will manifest as
38# failures during Repair jobs leaving the DUT as "Repair Failed".
39# In practice, you can't test Repair jobs without a full
40# installation, so that kind of failure isn't expected.
41try:
J. Richard Barnette7214e0b2013-02-06 15:20:49 -080042 # pylint: disable=W0611
Richard Barnette82c35912012-11-20 10:09:10 -080043 from autotest_lib.frontend import setup_django_environment
44 from autotest_lib.frontend.afe import models
45except:
46 models = None
47
Simran Basid5e5e272012-09-24 15:23:59 -070048
J. Richard Barnettebe5ebcc2013-02-11 16:03:15 -080049def _make_servo_hostname(hostname):
50 host_parts = hostname.split('.')
51 host_parts[0] = host_parts[0] + '-servo'
52 return '.'.join(host_parts)
53
54
55def _get_lab_servo(target_hostname):
56 """Instantiate a Servo for |target_hostname| in the lab.
57
58 Assuming that |target_hostname| is a device in the CrOS test
59 lab, create and return a Servo object pointed at the servo
60 attached to that DUT. The servo in the test lab is assumed
61 to already have servod up and running on it.
62
63 @param target_hostname: device whose servo we want to target.
64 @return an appropriately configured Servo instance.
65 """
66 servo_host = _make_servo_hostname(target_hostname)
67 if utils.host_is_in_lab_zone(servo_host):
68 try:
J. Richard Barnetted5f807a2013-02-11 16:51:00 -080069 return servo.Servo(servo_host=servo_host)
J. Richard Barnettebe5ebcc2013-02-11 16:03:15 -080070 except: # pylint: disable=W0702
71 # TODO(jrbarnette): Long-term, if we can't get to
72 # a servo in the lab, we want to fail, so we should
73 # pass any exceptions along. Short-term, we're not
74 # ready to rely on servo, so we ignore failures.
75 pass
76 return None
77
78
Dale Curtiscb7bfaf2011-06-07 16:21:57 -070079def make_ssh_command(user='root', port=22, opts='', hosts_file=None,
80 connect_timeout=None, alive_interval=None):
81 """Override default make_ssh_command to use options tuned for Chrome OS.
82
83 Tuning changes:
Chris Sosaf7fcd6e2011-09-27 17:30:47 -070084 - ConnectTimeout=30; maximum of 30 seconds allowed for an SSH connection
85 failure. Consistency with remote_access.sh.
Dale Curtiscb7bfaf2011-06-07 16:21:57 -070086
Dale Curtisaa5eedb2011-08-23 16:18:52 -070087 - ServerAliveInterval=180; which causes SSH to ping connection every
88 180 seconds. In conjunction with ServerAliveCountMax ensures that if the
89 connection dies, Autotest will bail out quickly. Originally tried 60 secs,
90 but saw frequent job ABORTS where the test completed successfully.
Dale Curtiscb7bfaf2011-06-07 16:21:57 -070091
Chris Sosaf7fcd6e2011-09-27 17:30:47 -070092 - ServerAliveCountMax=3; consistency with remote_access.sh.
93
94 - ConnectAttempts=4; reduce flakiness in connection errors; consistency
95 with remote_access.sh.
Dale Curtiscb7bfaf2011-06-07 16:21:57 -070096
97 - UserKnownHostsFile=/dev/null; we don't care about the keys. Host keys
98 change with every new installation, don't waste memory/space saving them.
Chris Sosaf7fcd6e2011-09-27 17:30:47 -070099
100 - SSH protocol forced to 2; needed for ServerAliveInterval.
J. Richard Barnette7214e0b2013-02-06 15:20:49 -0800101
102 @param user User name to use for the ssh connection.
103 @param port Port on the target host to use for ssh connection.
104 @param opts Additional options to the ssh command.
105 @param hosts_file Ignored.
106 @param connect_timeout Ignored.
107 @param alive_interval Ignored.
Dale Curtiscb7bfaf2011-06-07 16:21:57 -0700108 """
109 base_command = ('/usr/bin/ssh -a -x %s -o StrictHostKeyChecking=no'
110 ' -o UserKnownHostsFile=/dev/null -o BatchMode=yes'
Chris Sosaf7fcd6e2011-09-27 17:30:47 -0700111 ' -o ConnectTimeout=30 -o ServerAliveInterval=180'
112 ' -o ServerAliveCountMax=3 -o ConnectionAttempts=4'
113 ' -o Protocol=2 -l %s -p %d')
Dale Curtiscb7bfaf2011-06-07 16:21:57 -0700114 return base_command % (opts, user, port)
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700115
116
J. Richard Barnette7214e0b2013-02-06 15:20:49 -0800117
Aviv Keshet74c89a92013-02-04 15:18:30 -0800118def add_label_detector(label_function_list, label_list=None, label=None):
119 """Decorator used to group functions together into the provided list.
120 @param label_function_list: List of label detecting functions to add
121 decorated function to.
122 @param label_list: List of detectable labels to add detectable labels to.
123 (Default: None)
124 @param label: Label string that is detectable by this detection function
125 (Default: None)
J. Richard Barnette7214e0b2013-02-06 15:20:49 -0800126 """
Simran Basic6f1f7a2012-10-16 10:47:46 -0700127 def add_func(func):
Aviv Keshet74c89a92013-02-04 15:18:30 -0800128 """
129 @param func: The function to be added as a detector.
130 """
131 label_function_list.append(func)
132 if label and label_list is not None:
133 label_list.append(label)
Simran Basic6f1f7a2012-10-16 10:47:46 -0700134 return func
135 return add_func
136
137
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700138class SiteHost(remote.RemoteHost):
139 """Chromium OS specific subclass of Host."""
140
141 _parser = autoserv_parser.autoserv_parser
142
Richard Barnette0c73ffc2012-11-19 15:21:18 -0800143 # Time to wait for new kernel to be marked successful after
144 # auto update.
Chris Masone163cead2012-05-16 11:49:48 -0700145 _KERNEL_UPDATE_TIMEOUT = 120
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700146
Richard Barnette03a0c132012-11-05 12:40:35 -0800147 # Timeout values (in seconds) associated with various Chrome OS
148 # state changes.
J. Richard Barnette134ec2c2012-04-25 12:59:37 -0700149 #
Richard Barnette0c73ffc2012-11-19 15:21:18 -0800150 # In general, a good rule of thumb is that the timeout can be up
151 # to twice the typical measured value on the slowest platform.
152 # The times here have not necessarily been empirically tested to
153 # meet this criterion.
J. Richard Barnetteeb69d722012-06-18 17:29:44 -0700154 #
155 # SLEEP_TIMEOUT: Time to allow for suspend to memory.
Richard Barnette0c73ffc2012-11-19 15:21:18 -0800156 # RESUME_TIMEOUT: Time to allow for resume after suspend, plus
157 # time to restart the netwowrk.
J. Richard Barnetteeb69d722012-06-18 17:29:44 -0700158 # BOOT_TIMEOUT: Time to allow for boot from power off. Among
Richard Barnette0c73ffc2012-11-19 15:21:18 -0800159 # other things, this must account for the 30 second dev-mode
J. Richard Barnetted4649c62013-03-06 17:42:27 -0800160 # screen delay and time to start the network.
J. Richard Barnetteeb69d722012-06-18 17:29:44 -0700161 # USB_BOOT_TIMEOUT: Time to allow for boot from a USB device,
Richard Barnette0c73ffc2012-11-19 15:21:18 -0800162 # including the 30 second dev-mode delay and time to start the
J. Richard Barnetted4649c62013-03-06 17:42:27 -0800163 # network.
Richard Barnette0c73ffc2012-11-19 15:21:18 -0800164 # SHUTDOWN_TIMEOUT: Time to allow for shut down.
J. Richard Barnetteeb69d722012-06-18 17:29:44 -0700165 # REBOOT_TIMEOUT: Combination of shutdown and reboot times.
Richard Barnette03a0c132012-11-05 12:40:35 -0800166 # _INSTALL_TIMEOUT: Time to allow for chromeos-install.
J. Richard Barnetteeb69d722012-06-18 17:29:44 -0700167
168 SLEEP_TIMEOUT = 2
J. Richard Barnetted4649c62013-03-06 17:42:27 -0800169 RESUME_TIMEOUT = 10
J. Richard Barnetteeb69d722012-06-18 17:29:44 -0700170 BOOT_TIMEOUT = 45
171 USB_BOOT_TIMEOUT = 150
172 SHUTDOWN_TIMEOUT = 5
173 REBOOT_TIMEOUT = SHUTDOWN_TIMEOUT + BOOT_TIMEOUT
Richard Barnette03a0c132012-11-05 12:40:35 -0800174 _INSTALL_TIMEOUT = 240
175
Ismail Noorbasha07fdb612013-02-14 14:13:31 -0800176 # _USB_POWER_TIMEOUT: Time to allow for USB to power toggle ON and OFF.
177 # _POWER_CYCLE_TIMEOUT: Time to allow for manual power cycle.
178 _USB_POWER_TIMEOUT = 5
179 _POWER_CYCLE_TIMEOUT = 10
180
Richard Barnette03a0c132012-11-05 12:40:35 -0800181 _DEFAULT_SERVO_URL_FORMAT = ('/static/servo-images/'
182 '%(board)s_test_image.bin')
183
Richard Barnette0c73ffc2012-11-19 15:21:18 -0800184
Richard Barnette82c35912012-11-20 10:09:10 -0800185 _RPM_RECOVERY_BOARDS = global_config.global_config.get_config_value('CROS',
186 'rpm_recovery_boards', type=str).split(',')
187
188 _MAX_POWER_CYCLE_ATTEMPTS = 6
189 _LAB_MACHINE_FILE = '/mnt/stateful_partition/.labmachine'
190 _RPM_HOSTNAME_REGEX = ('chromeos[0-9]+(-row[0-9]+)?-rack[0-9]+[a-z]*-'
191 'host[0-9]+')
192 _LIGHTSENSOR_FILES = ['in_illuminance0_input',
193 'in_illuminance0_raw',
194 'illuminance0_input']
195 _LIGHTSENSOR_SEARCH_DIR = '/sys/bus/iio/devices'
196 _LABEL_FUNCTIONS = []
Aviv Keshet74c89a92013-02-04 15:18:30 -0800197 _DETECTABLE_LABELS = []
198 label_decorator = functools.partial(add_label_detector, _LABEL_FUNCTIONS,
199 _DETECTABLE_LABELS)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -0700200
J. Richard Barnetteb6de7e32013-02-14 13:28:04 -0800201 # Constants used in ping_wait_up() and ping_wait_down().
202 #
203 # _PING_WAIT_COUNT is the approximate number of polling
204 # cycles to use when waiting for a host state change.
205 #
206 # _PING_STATUS_DOWN and _PING_STATUS_UP are names used
207 # for arguments to the internal _ping_wait_for_status()
208 # method.
209 _PING_WAIT_COUNT = 40
210 _PING_STATUS_DOWN = False
211 _PING_STATUS_UP = True
212
Ismail Noorbasha07fdb612013-02-14 14:13:31 -0800213 # Allowed values for the power_method argument.
214
215 # POWER_CONTROL_RPM: Passed as default arg for power_off/on/cycle() methods.
216 # POWER_CONTROL_SERVO: Used in set_power() and power_cycle() methods.
217 # POWER_CONTROL_MANUAL: Used in set_power() and power_cycle() methods.
218 POWER_CONTROL_RPM = 'RPM'
219 POWER_CONTROL_SERVO = 'servoj10'
220 POWER_CONTROL_MANUAL = 'manual'
221
222 POWER_CONTROL_VALID_ARGS = (POWER_CONTROL_RPM,
223 POWER_CONTROL_SERVO,
224 POWER_CONTROL_MANUAL)
Richard Barnette0c73ffc2012-11-19 15:21:18 -0800225
Simran Basi5e6339a2013-03-21 11:34:32 -0700226 _RPM_OUTLET_CHANGED = 'outlet_changed'
227
J. Richard Barnette964fba02012-10-24 17:34:29 -0700228 @staticmethod
J. Richard Barnette7214e0b2013-02-06 15:20:49 -0800229 def get_servo_arguments(args_dict):
230 """Extract servo options from `args_dict` and return the result.
231
232 Take the provided dictionary of argument options and return
233 a subset that represent standard arguments needed to
234 construct a servo object for a host. The intent is to
235 provide standard argument processing from run_remote_tests
236 for tests that require a servo to operate.
237
238 Recommended usage:
239 ~~~~~~~~
240 args_dict = utils.args_to_dict(args)
241 servo_args = hosts.SiteHost.get_servo_arguments(args_dict)
242 host = hosts.create_host(machine, servo_args=servo_args)
243 ~~~~~~~~
244
245 @param args_dict Dictionary from which to extract the servo
246 arguments.
247 """
J. Richard Barnette964fba02012-10-24 17:34:29 -0700248 servo_args = {}
249 for arg in ('servo_host', 'servo_port'):
J. Richard Barnette7214e0b2013-02-06 15:20:49 -0800250 if arg in args_dict:
251 servo_args[arg] = args_dict[arg]
J. Richard Barnette964fba02012-10-24 17:34:29 -0700252 return servo_args
J. Richard Barnette134ec2c2012-04-25 12:59:37 -0700253
J. Richard Barnette964fba02012-10-24 17:34:29 -0700254
255 def _initialize(self, hostname, servo_args=None, *args, **dargs):
J. Richard Barnette67ccb872012-04-19 16:34:56 -0700256 """Initialize superclasses, and |self.servo|.
257
258 For creating the host servo object, there are three
259 possibilities: First, if the host is a lab system known to
260 have a servo board, we connect to that servo unconditionally.
261 Second, if we're called from a control file that requires
J. Richard Barnette55fb8062012-05-23 10:29:31 -0700262 servo features for testing, it will pass settings for
263 `servo_host`, `servo_port`, or both. If neither of these
264 cases apply, `self.servo` will be `None`.
J. Richard Barnette67ccb872012-04-19 16:34:56 -0700265
266 """
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700267 super(SiteHost, self)._initialize(hostname=hostname,
268 *args, **dargs)
J. Richard Barnettef0859852012-08-20 14:55:50 -0700269 # self.env is a dictionary of environment variable settings
270 # to be exported for commands run on the host.
271 # LIBC_FATAL_STDERR_ can be useful for diagnosing certain
272 # errors that might happen.
273 self.env['LIBC_FATAL_STDERR_'] = '1'
J. Richard Barnette1d78b012012-05-15 13:56:30 -0700274 self._xmlrpc_proxy_map = {}
J. Richard Barnettebe5ebcc2013-02-11 16:03:15 -0800275 self.servo = _get_lab_servo(hostname)
J. Richard Barnettead7da482012-10-30 16:46:52 -0700276 if not self.servo and servo_args is not None:
J. Richard Barnette964fba02012-10-24 17:34:29 -0700277 self.servo = servo.Servo(**servo_args)
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700278
279
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500280 def get_repair_image_name(self):
281 """Generate a image_name from variables in the global config.
282
283 @returns a str of $board-version/$BUILD.
284
285 """
286 stable_version = global_config.global_config.get_config_value(
287 'CROS', 'stable_cros_version')
288 build_pattern = global_config.global_config.get_config_value(
289 'CROS', 'stable_build_pattern')
290 board = self._get_board_from_afe()
291 if board is None:
292 raise error.AutoservError('DUT has no board attribute, '
293 'cannot be repaired.')
294 return build_pattern % (board, stable_version)
295
296
297 def clear_cros_version_labels_and_job_repo_url(self):
298 """Clear cros_version labels and host attribute job_repo_url."""
Scott Zawalskieadbf702013-03-14 09:23:06 -0400299 try:
300 host_model = models.Host.objects.get(hostname=self.hostname)
301 except models.Host.DoesNotExist:
302 return
303
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500304 for label in host_model.labels.iterator():
305 if not label.name.startswith(ds_constants.VERSION_PREFIX):
306 continue
Dan Shi0f466e82013-02-22 15:44:58 -0800307
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500308 label.host_set.remove(host_model)
309
310 host_model.set_or_delete_attribute('job_repo_url', None)
311
312
Scott Zawalskieadbf702013-03-14 09:23:06 -0400313 def add_cros_version_labels_and_job_repo_url(self, image_name):
314 """Add cros_version labels and host attribute job_repo_url.
315
316 @param image_name: The name of the image e.g.
317 lumpy-release/R27-3837.0.0
318 """
319 try:
320 host_model = models.Host.objects.get(hostname=self.hostname)
321 except models.Host.DoesNotExist:
322 return
323 cros_label = '%s%s' % (ds_constants.VERSION_PREFIX, image_name)
324 devserver_url = dev_server.ImageServer.resolve(image_name).url()
325 try:
326 label_model = models.Label.objects.get(name=cros_label)
327 except models.Label.DoesNotExist:
328 label_model = models.Label.objects.create(name=cros_label)
329 host_model.labels.add(label_model)
330 repo_url = tools.get_package_url(devserver_url, image_name)
331 host_model.set_or_delete_attribute('job_repo_url', repo_url)
332
333
Dan Shi0f466e82013-02-22 15:44:58 -0800334 def _try_stateful_update(self, update_url, force_update, updater):
335 """Try to use stateful update to initialize DUT.
336
337 When DUT is already running the same version that machine_install
338 tries to install, stateful update is a much faster way to clean up
339 the DUT for testing, compared to a full reimage. It is implemeted
340 by calling autoupdater.run_update, but skipping updating root, as
341 updating the kernel is time consuming and not necessary.
342
343 @param update_url: url of the image.
344 @param force_update: Set to True to update the image even if the DUT
345 is running the same version.
346 @param updater: ChromiumOSUpdater instance used to update the DUT.
347 @returns: True if the DUT was updated with stateful update.
348
349 """
350 if not updater.check_version():
351 return False
352 if not force_update:
353 logging.info('Canceling stateful update because the new and '
354 'old versions are the same.')
355 return False
356 # Following folders should be rebuilt after stateful update.
357 # A test file is used to confirm each folder gets rebuilt after
358 # the stateful update.
359 folders_to_check = ['/var', '/home', '/mnt/stateful_partition']
360 test_file = '.test_file_to_be_deleted'
361 for folder in folders_to_check:
362 touch_path = os.path.join(folder, test_file)
363 self.run('touch %s' % touch_path)
364
365 if not updater.run_update(force_update=True, update_root=False):
366 return False
367
368 # Reboot to complete stateful update.
369 self.reboot(timeout=60, wait=True)
370 check_file_cmd = 'test -f %s; echo $?'
371 for folder in folders_to_check:
372 test_file_path = os.path.join(folder, test_file)
373 result = self.run(check_file_cmd % test_file_path,
374 ignore_status=True)
375 if result.exit_status == 1:
376 return False
377 return True
378
379
380 def _post_update_processing(self, updater, inactive_kernel=None):
381 """After the DUT is updated, confirm machine_install succeeded.
382
383 @param updater: ChromiumOSUpdater instance used to update the DUT.
384 @param inactive_kernel: kernel state of inactive kernel before reboot.
385
386 """
387
388 # Touch the lab machine file to leave a marker that distinguishes
389 # this image from other test images.
390 self.run('touch %s' % self._LAB_MACHINE_FILE)
391
392 # Kick off the autoreboot script as the _LAB_MACHINE_FILE was
393 # missing on the first boot.
394 self.run('start autoreboot')
395
396 # Following the reboot, verify the correct version.
Dan Shib95bb862013-03-22 16:29:28 -0700397 if not updater.check_version_to_confirm_install():
Dan Shi0f466e82013-02-22 15:44:58 -0800398 # Print out crossystem to make it easier to debug the rollback.
399 logging.debug('Dumping partition table.')
Dan Shi346725f2013-03-20 15:22:38 -0700400 self.run('cgpt show $(rootdev -s -d)')
Dan Shi0f466e82013-02-22 15:44:58 -0800401 logging.debug('Dumping crossystem for firmware debugging.')
Dan Shi346725f2013-03-20 15:22:38 -0700402 self.run('crossystem --all')
Dan Shi0f466e82013-02-22 15:44:58 -0800403 logging.error('Expected Chromium OS version: %s. '
404 'Found Chromium OS %s',
Dan Shi346725f2013-03-20 15:22:38 -0700405 updater.update_version, updater.get_build_id())
406 raise autoupdater.ChromiumOSError('Updater failed on host %s' %
407 self.hostname)
Dan Shi0f466e82013-02-22 15:44:58 -0800408
409 # Figure out newly active kernel.
410 new_active_kernel, _ = updater.get_kernel_state()
411
412 # Ensure that previously inactive kernel is now the active kernel.
413 if inactive_kernel and new_active_kernel != inactive_kernel:
414 raise autoupdater.ChromiumOSError(
415 'Update failed. New kernel partition is not active after'
416 ' boot.')
417
Scott Zawalskieadbf702013-03-14 09:23:06 -0400418 try:
419 host_attributes = site_host_attributes.HostAttributes(self.hostname)
420 except models.Host.DoesNotExist:
421 host_attributes = None
422 if host_attributes and host_attributes.has_chromeos_firmware:
Dan Shi0f466e82013-02-22 15:44:58 -0800423 # Wait until tries == 0 and success, or until timeout.
424 utils.poll_for_condition(
425 lambda: (updater.get_kernel_tries(new_active_kernel) == 0
426 and updater.get_kernel_success(new_active_kernel)),
427 exception=autoupdater.ChromiumOSError(
428 'Update failed. Timed out waiting for system to mark'
429 ' new kernel as successful.'),
430 timeout=self._KERNEL_UPDATE_TIMEOUT, sleep_interval=5)
431
432
Scott Zawalskieadbf702013-03-14 09:23:06 -0400433 def _stage_build_and_return_update_url(self, image_name):
434 """Stage a build on a devserver and return the update_url.
435
436 @param image_name: a name like lumpy-release/R27-3837.0.0
437 @returns an update URL like:
438 http://172.22.50.205:8082/update/lumpy-release/R27-3837.0.0
439 """
440 logging.info('Staging requested build: %s', image_name)
441 devserver = dev_server.ImageServer.resolve(image_name)
442 devserver.trigger_download(image_name, synchronous=False)
443 return tools.image_url_pattern() % (devserver.url(), image_name)
444
445
Chris Sosaa3ac2152012-05-23 22:23:13 -0700446 def machine_install(self, update_url=None, force_update=False,
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500447 local_devserver=False, repair=False):
448 """Install the DUT.
449
Dan Shi0f466e82013-02-22 15:44:58 -0800450 Use stateful update if the DUT is already running the same build.
451 Stateful update does not update kernel and tends to run much faster
452 than a full reimage. If the DUT is running a different build, or it
453 failed to do a stateful update, full update, including kernel update,
454 will be applied to the DUT.
455
Scott Zawalskieadbf702013-03-14 09:23:06 -0400456 Once a host enters machine_install its cros_version label will be
457 removed as well as its host attribute job_repo_url (used for
458 package install).
459
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500460 @param update_url: The url to use for the update
461 pattern: http://$devserver:###/update/$build
462 If update_url is None and repair is True we will install the
463 stable image listed in global_config under
464 CROS.stable_cros_version.
465 @param force_update: Force an update even if the version installed
466 is the same. Default:False
467 @param local_devserver: Used by run_remote_test to allow people to
468 use their local devserver. Default: False
469 @param repair: Whether or not we are in repair mode. This adds special
470 cases for repairing a machine like starting update_engine.
471 Setting repair to True sets force_update to True as well.
472 default: False
473 @raises autoupdater.ChromiumOSError
474
475 """
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700476 if not update_url and self._parser.options.image:
Scott Zawalskieadbf702013-03-14 09:23:06 -0400477 requested_build = self._parser.options.image
478 if requested_build.startswith('http://'):
479 update_url = requested_build
480 else:
481 # Try to stage any build that does not start with http:// on
482 # the devservers defined in global_config.ini.
483 update_url = self._stage_build_and_return_update_url(
484 requested_build)
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500485 elif not update_url and not repair:
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700486 raise autoupdater.ChromiumOSError(
487 'Update failed. No update URL provided.')
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500488 elif not update_url and repair:
Scott Zawalskieadbf702013-03-14 09:23:06 -0400489 update_url = self._stage_build_and_return_update_url(
490 self.get_repair_image_name())
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500491
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500492 if repair:
Dan Shi0f466e82013-02-22 15:44:58 -0800493 # In case the system is in a bad state, we always reboot the machine
494 # before machine_install.
495 self.reboot(timeout=60, wait=True)
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500496 self.run('stop update-engine; start update-engine')
497 force_update = True
Dan Shi0f466e82013-02-22 15:44:58 -0800498
Chris Sosaa3ac2152012-05-23 22:23:13 -0700499 updater = autoupdater.ChromiumOSUpdater(update_url, host=self,
Dan Shi0f466e82013-02-22 15:44:58 -0800500 local_devserver=local_devserver)
501 updated = False
Scott Zawalskieadbf702013-03-14 09:23:06 -0400502 # Remove cros-version and job_repo_url host attribute from host.
503 self.clear_cros_version_labels_and_job_repo_url()
Dan Shi0f466e82013-02-22 15:44:58 -0800504 # If the DUT is already running the same build, try stateful update
505 # first. Stateful update does not update kernel and tends to run much
506 # faster than a full reimage.
507 try:
508 updated = self._try_stateful_update(update_url, force_update,
509 updater)
510 if updated:
511 logging.info('DUT is updated with stateful update.')
512 except Exception as e:
513 logging.exception(e)
514 logging.warn('Failed to stateful update DUT, force to update.')
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700515
Dan Shi0f466e82013-02-22 15:44:58 -0800516 inactive_kernel = None
517 # Do a full update if stateful update is not applicable or failed.
518 if not updated:
519 # In case the system is in a bad state, we always reboot the
520 # machine before machine_install.
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700521 self.reboot(timeout=60, wait=True)
Chris Sosab7612bc2013-03-21 10:32:37 -0700522
523 # TODO(sosa): Remove temporary hack to get rid of bricked machines
524 # that can't update due to a corrupted policy.
525 self.run('rm -rf /var/lib/whitelist')
526 self.run('touch /var/lib/whitelist')
527 self.run('chmod -w /var/lib/whitelist')
Scott Zawalskib550d5a2013-03-22 09:23:59 -0400528 self.run('stop update-engine; start update-engine')
Chris Sosab7612bc2013-03-21 10:32:37 -0700529
Dan Shi0f466e82013-02-22 15:44:58 -0800530 if updater.run_update(force_update):
531 updated = True
532 # Figure out active and inactive kernel.
533 active_kernel, inactive_kernel = updater.get_kernel_state()
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700534
Dan Shi0f466e82013-02-22 15:44:58 -0800535 # Ensure inactive kernel has higher priority than active.
536 if (updater.get_kernel_priority(inactive_kernel)
537 < updater.get_kernel_priority(active_kernel)):
538 raise autoupdater.ChromiumOSError(
539 'Update failed. The priority of the inactive kernel'
540 ' partition is less than that of the active kernel'
541 ' partition.')
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700542
Dan Shi0f466e82013-02-22 15:44:58 -0800543 update_engine_log = '/var/log/update_engine.log'
544 logging.info('Dumping %s', update_engine_log)
545 self.run('cat %s' % update_engine_log)
546 # Updater has returned successfully; reboot the host.
547 self.reboot(timeout=60, wait=True)
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700548
Dan Shi0f466e82013-02-22 15:44:58 -0800549 if updated:
550 self._post_update_processing(updater, inactive_kernel)
Scott Zawalskieadbf702013-03-14 09:23:06 -0400551 image_name = autoupdater.url_to_image_name(update_url)
552 self.add_cros_version_labels_and_job_repo_url(image_name)
Simran Basi13fa1ba2013-03-04 10:56:47 -0800553
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700554 # Clean up any old autotest directories which may be lying around.
555 for path in global_config.global_config.get_config_value(
556 'AUTOSERV', 'client_autodir_paths', type=list):
557 self.run('rm -rf ' + path)
558
559
Simran Basi833814b2013-01-29 13:13:43 -0800560 def _get_label_from_afe(self, label_prefix):
561 """Retrieve a host's specific label from the AFE.
562
563 Looks for a host label that has the form <label_prefix>:<value>
564 and returns the "<value>" part of the label. None is returned
565 if there is not a label matching the pattern
566
567 @returns the label that matches the prefix or 'None'
568 """
569 host_model = models.Host.objects.get(hostname=self.hostname)
570 host_label = host_model.labels.get(name__startswith=label_prefix)
571 if not host_label:
572 return None
573 return host_label.name.split(label_prefix, 1)[1]
574
575
Richard Barnette82c35912012-11-20 10:09:10 -0800576 def _get_board_from_afe(self):
577 """Retrieve this host's board from its labels in the AFE.
578
579 Looks for a host label of the form "board:<board>", and
580 returns the "<board>" part of the label. `None` is returned
581 if there is not a single, unique label matching the pattern.
582
583 @returns board from label, or `None`.
584 """
Simran Basi833814b2013-01-29 13:13:43 -0800585 return self._get_label_from_afe(ds_constants.BOARD_PREFIX)
586
587
588 def get_build(self):
589 """Retrieve the current build for this Host from the AFE.
590
591 Looks through this host's labels in the AFE to determine its build.
592
593 @returns The current build or None if it could not find it or if there
594 were multiple build labels assigned to this host.
595 """
596 return self._get_label_from_afe(ds_constants.VERSION_PREFIX)
Richard Barnette82c35912012-11-20 10:09:10 -0800597
598
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500599 def _install_repair(self):
600 """Attempt to repair this host using upate-engine.
601
602 If the host is up, try installing the DUT with a stable
603 "repair" version of Chrome OS as defined in the global_config
604 under CROS.stable_cros_version.
605
606 @returns True if successful, False if update_engine failed.
607
608 """
609 if not self.is_up():
610 return False
611
612 logging.info('Attempting to reimage machine to repair image.')
613 try:
614 self.machine_install(repair=True)
Fang Dengd0672f32013-03-18 17:18:09 -0700615 except autoupdater.ChromiumOSError as e:
616 logging.exception(e)
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500617 logging.info('Repair via install failed.')
618 return False
619
620 return True
621
622
Richard Barnette03a0c132012-11-05 12:40:35 -0800623 def _servo_repair(self, board):
624 """Attempt to repair this host using an attached Servo.
625
626 Re-install the OS on the DUT by 1) installing a test image
627 on a USB storage device attached to the Servo board,
628 2) booting that image in recovery mode, and then
629 3) installing the image.
630
631 """
632 server = dev_server.ImageServer.devserver_url_for_servo(board)
633 image = server + (self._DEFAULT_SERVO_URL_FORMAT %
634 { 'board': board })
635 self.servo.install_recovery_image(image)
636 if not self.wait_up(timeout=self.USB_BOOT_TIMEOUT):
637 raise error.AutoservError('DUT failed to boot from USB'
638 ' after %d seconds' %
639 self.USB_BOOT_TIMEOUT)
640 self.run('chromeos-install --yes',
641 timeout=self._INSTALL_TIMEOUT)
642 self.servo.power_long_press()
643 self.servo.set('usb_mux_sel1', 'servo_sees_usbkey')
644 self.servo.power_short_press()
645 if not self.wait_up(timeout=self.BOOT_TIMEOUT):
646 raise error.AutoservError('DUT failed to reboot installed '
647 'test image after %d seconds' %
648 self.BOOT_TIMEOUT)
649
650
Richard Barnette82c35912012-11-20 10:09:10 -0800651 def _powercycle_to_repair(self):
652 """Utilize the RPM Infrastructure to bring the host back up.
653
654 If the host is not up/repaired after the first powercycle we utilize
655 auto fallback to the last good install by powercycling and rebooting the
656 host 6 times.
657 """
658 logging.info('Attempting repair via RPM powercycle.')
659 failed_cycles = 0
660 self.power_cycle()
661 while not self.wait_up(timeout=self.BOOT_TIMEOUT):
662 failed_cycles += 1
663 if failed_cycles >= self._MAX_POWER_CYCLE_ATTEMPTS:
664 raise error.AutoservError('Powercycled host %s %d times; '
665 'device did not come back online.' %
666 (self.hostname, failed_cycles))
667 self.power_cycle()
668 if failed_cycles == 0:
669 logging.info('Powercycling was successful first time.')
670 else:
671 logging.info('Powercycling was successful after %d failures.',
672 failed_cycles)
673
674
675 def repair_full(self):
676 """Repair a host for repair level NO_PROTECTION.
677
678 This overrides the base class function for repair; it does
679 not call back to the parent class, but instead offers a
680 simplified implementation based on the capabilities in the
681 Chrome OS test lab.
682
J. Richard Barnettefde55fc2013-03-15 17:47:01 -0700683 If `self.verify()` fails, the following procedures are
684 attempted:
685 1. Try to re-install to a known stable image using
686 auto-update.
687 2. If there's a servo for the DUT, try to re-install via
688 the servo.
689 3. If the DUT can be power-cycled via RPM, try to repair
Richard Barnette82c35912012-11-20 10:09:10 -0800690 by power-cycling.
691
692 As with the parent method, the last operation performed on
693 the DUT must be to call `self.verify()`; if that call fails,
694 the exception it raises is passed back to the caller.
J. Richard Barnettefde55fc2013-03-15 17:47:01 -0700695
Richard Barnette82c35912012-11-20 10:09:10 -0800696 """
Scott Zawalskib550d5a2013-03-22 09:23:59 -0400697 host_board = self._get_board_from_afe()
698 if host_board is None:
699 logging.error('host %s has no board; failing repair',
700 self.hostname)
701 raise
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500702
Scott Zawalskib550d5a2013-03-22 09:23:59 -0400703 if not self._install_repair():
704 # TODO(scottz): All repair pathways should be
705 # executed until we've exhausted all options. Below
706 # we favor servo over powercycle when we really
707 # should be falling back to power if servo fails.
J. Richard Barnette69929a52013-03-15 13:22:11 -0700708 if (self.servo and self.servo.recovery_supported()):
Scott Zawalskib550d5a2013-03-22 09:23:59 -0400709 self._servo_repair(host_board)
710 elif (self.has_power() and
711 host_board in self._RPM_RECOVERY_BOARDS):
712 self._powercycle_to_repair()
713 else:
714 logging.error('host %s has no servo and no RPM control; '
715 'failing repair', self.hostname)
716 raise
717 self.verify()
Richard Barnette82c35912012-11-20 10:09:10 -0800718
719
J. Richard Barnette1d78b012012-05-15 13:56:30 -0700720 def close(self):
721 super(SiteHost, self).close()
722 self.xmlrpc_disconnect_all()
723
724
Simran Basi5e6339a2013-03-21 11:34:32 -0700725 def _cleanup_poweron(self):
726 """Special cleanup method to make sure hosts always get power back."""
727 afe = frontend_wrappers.RetryingAFE(timeout_min=5, delay_sec=10)
728 hosts = afe.get_hosts(hostname=self.hostname)
729 if not hosts or not (self._RPM_OUTLET_CHANGED in
730 hosts[0].attributes):
731 return
732 logging.debug('This host has recently interacted with the RPM'
733 ' Infrastructure. Ensuring power is on.')
734 try:
735 self.power_on()
736 except rpm_client.RemotePowerException:
737 # If cleanup has completed but there was an issue with the RPM
738 # Infrastructure, log an error message rather than fail cleanup
739 logging.error('Failed to turn Power On for this host after '
740 'cleanup through the RPM Infrastructure.')
741 afe.set_host_attribute(self._RPM_OUTLET_CHANGED, None,
742 hostname=self.hostname)
743
744
Chris Sosaf4d43ff2012-10-30 11:21:05 -0700745 def cleanup(self):
Chris Sosaf4d43ff2012-10-30 11:21:05 -0700746 client_at = autotest.Autotest(self)
Richard Barnette82c35912012-11-20 10:09:10 -0800747 self.run('rm -f %s' % constants.CLEANUP_LOGS_PAUSED_FILE)
Scott Zawalskiddbc31e2012-11-15 11:29:01 -0500748 try:
749 client_at.run_static_method('autotest_lib.client.cros.cros_ui',
750 '_clear_login_prompt_state')
751 self.run('restart ui')
752 client_at.run_static_method('autotest_lib.client.cros.cros_ui',
753 '_wait_for_login_prompt')
Alex Millerf4517962013-02-25 15:03:02 -0800754 except (error.AutotestRunError, error.AutoservRunError):
Scott Zawalskiddbc31e2012-11-15 11:29:01 -0500755 logging.warn('Unable to restart ui, rebooting device.')
756 # Since restarting the UI fails fall back to normal Autotest
757 # cleanup routines, i.e. reboot the machine.
758 super(SiteHost, self).cleanup()
Simran Basi5e6339a2013-03-21 11:34:32 -0700759 # Check if the rpm outlet was manipulated.
Simran Basid5e5e272012-09-24 15:23:59 -0700760 if self.has_power():
Simran Basi5e6339a2013-03-21 11:34:32 -0700761 self._cleanup_poweron()
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700762
763
Yu-Ju Honga2be94a2012-07-31 09:48:52 -0700764 def reboot(self, **dargs):
765 """
766 This function reboots the site host. The more generic
767 RemoteHost.reboot() performs sync and sleeps for 5
768 seconds. This is not necessary for Chrome OS devices as the
769 sync should be finished in a short time during the reboot
770 command.
771 """
Tom Wai-Hong Tamf5cd1d42012-08-13 12:04:08 +0800772 if 'reboot_cmd' not in dargs:
773 dargs['reboot_cmd'] = ('((reboot & sleep 10; reboot -f &)'
774 ' </dev/null >/dev/null 2>&1 &)')
Yu-Ju Honga2be94a2012-07-31 09:48:52 -0700775 # Enable fastsync to avoid running extra sync commands before reboot.
Tom Wai-Hong Tamf5cd1d42012-08-13 12:04:08 +0800776 if 'fastsync' not in dargs:
777 dargs['fastsync'] = True
Yu-Ju Honga2be94a2012-07-31 09:48:52 -0700778 super(SiteHost, self).reboot(**dargs)
779
780
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700781 def verify_software(self):
Richard Barnetteb2bc13c2013-01-08 17:32:51 -0800782 """Verify working software on a Chrome OS system.
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700783
Richard Barnetteb2bc13c2013-01-08 17:32:51 -0800784 Tests for the following conditions:
785 1. All conditions tested by the parent version of this
786 function.
787 2. Sufficient space in /mnt/stateful_partition.
Fang Deng6b05f5b2013-03-20 13:42:11 -0700788 3. Sufficient space in /mnt/stateful_partition/encrypted.
789 4. update_engine answers a simple status request over DBus.
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700790
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700791 """
792 super(SiteHost, self).verify_software()
793 self.check_diskspace(
794 '/mnt/stateful_partition',
795 global_config.global_config.get_config_value(
Fang Deng6b05f5b2013-03-20 13:42:11 -0700796 'SERVER', 'gb_diskspace_required', type=float,
797 default=20.0))
798 self.check_diskspace(
799 '/mnt/stateful_partition/encrypted',
800 global_config.global_config.get_config_value(
801 'SERVER', 'gb_encrypted_diskspace_required', type=float,
802 default=0.1))
Richard Barnetteb2bc13c2013-01-08 17:32:51 -0800803 self.run('update_engine_client --status')
Scott Zawalskifbca4a92013-03-04 15:56:42 -0500804 # Makes sure python is present, loads and can use built in functions.
805 # We have seen cases where importing cPickle fails with undefined
806 # symbols in cPickle.so.
807 self.run('python -c "import cPickle"')
J. Richard Barnette134ec2c2012-04-25 12:59:37 -0700808
809
Christopher Wileyd78249a2013-03-01 13:05:31 -0800810 def xmlrpc_connect(self, command, port, command_name=None,
811 ready_test_name=None, timeout_seconds=10):
J. Richard Barnette1d78b012012-05-15 13:56:30 -0700812 """Connect to an XMLRPC server on the host.
813
814 The `command` argument should be a simple shell command that
815 starts an XMLRPC server on the given `port`. The command
816 must not daemonize, and must terminate cleanly on SIGTERM.
817 The command is started in the background on the host, and a
818 local XMLRPC client for the server is created and returned
819 to the caller.
820
821 Note that the process of creating an XMLRPC client makes no
822 attempt to connect to the remote server; the caller is
823 responsible for determining whether the server is running
824 correctly, and is ready to serve requests.
825
Christopher Wileyd78249a2013-03-01 13:05:31 -0800826 Optionally, the caller can pass ready_test_name, a string
827 containing the name of a method to call on the proxy. This
828 method should take no parameters and return successfully only
829 when the server is ready to process client requests. When
830 ready_test_name is set, xmlrpc_connect will block until the
831 proxy is ready, and throw a TestError if the server isn't
832 ready by timeout_seconds.
833
J. Richard Barnette1d78b012012-05-15 13:56:30 -0700834 @param command Shell command to start the server.
835 @param port Port number on which the server is expected to
836 be serving.
J. Richard Barnette7214e0b2013-02-06 15:20:49 -0800837 @param command_name String to use as input to `pkill` to
838 terminate the XMLRPC server on the host.
Christopher Wileyd78249a2013-03-01 13:05:31 -0800839 @param ready_test_name String containing the name of a
840 method defined on the XMLRPC server.
841 @param timeout_seconds Number of seconds to wait
842 for the server to become 'ready.' Will throw a
843 TestFail error if server is not ready in time.
844
J. Richard Barnette1d78b012012-05-15 13:56:30 -0700845 """
846 self.xmlrpc_disconnect(port)
847
848 # Chrome OS on the target closes down most external ports
849 # for security. We could open the port, but doing that
850 # would conflict with security tests that check that only
851 # expected ports are open. So, to get to the port on the
852 # target we use an ssh tunnel.
853 local_port = utils.get_unused_port()
854 tunnel_options = '-n -N -q -L %d:localhost:%d' % (local_port, port)
855 ssh_cmd = make_ssh_command(opts=tunnel_options)
856 tunnel_cmd = '%s %s' % (ssh_cmd, self.hostname)
857 logging.debug('Full tunnel command: %s', tunnel_cmd)
858 tunnel_proc = subprocess.Popen(tunnel_cmd, shell=True, close_fds=True)
859 logging.debug('Started XMLRPC tunnel, local = %d'
860 ' remote = %d, pid = %d',
861 local_port, port, tunnel_proc.pid)
862
863 # Start the server on the host. Redirection in the command
864 # below is necessary, because 'ssh' won't terminate until
865 # background child processes close stdin, stdout, and
866 # stderr.
867 remote_cmd = '( %s ) </dev/null >/dev/null 2>&1 & echo $!' % command
868 remote_pid = self.run(remote_cmd).stdout.rstrip('\n')
869 logging.debug('Started XMLRPC server on host %s, pid = %s',
870 self.hostname, remote_pid)
871
J. Richard Barnette7214e0b2013-02-06 15:20:49 -0800872 self._xmlrpc_proxy_map[port] = (command_name, tunnel_proc)
J. Richard Barnette1d78b012012-05-15 13:56:30 -0700873 rpc_url = 'http://localhost:%d' % local_port
Christopher Wileyd78249a2013-03-01 13:05:31 -0800874 proxy = xmlrpclib.ServerProxy(rpc_url, allow_none=True)
875 if ready_test_name is not None:
J. Richard Barnette13eb7c02013-03-07 12:06:29 -0800876 # retry.retry logs each attempt; calculate delay_sec to
877 # keep log spam to a dull roar.
Christopher Wileyd78249a2013-03-01 13:05:31 -0800878 @retry.retry((socket.error, xmlrpclib.ProtocolError),
879 timeout_min=timeout_seconds/60.0,
J. Richard Barnette13eb7c02013-03-07 12:06:29 -0800880 delay_sec=min(max(timeout_seconds/20.0, 0.1), 1))
Christopher Wileyd78249a2013-03-01 13:05:31 -0800881 def ready_test():
882 """ Call proxy.ready_test_name(). """
883 getattr(proxy, ready_test_name)()
884 successful = False
885 try:
886 logging.info('Waiting %d seconds for XMLRPC server '
887 'to start.', timeout_seconds)
888 ready_test()
889 successful = True
890 except retry.TimeoutException:
891 raise error.TestError('Unable to start XMLRPC server after '
892 '%d seconds.' % timeout_seconds)
893 finally:
894 if not successful:
895 logging.error('Failed to start XMLRPC server.')
896 self.xmlrpc_disconnect(port)
897 logging.info('XMLRPC server started successfully.')
898 return proxy
J. Richard Barnette1d78b012012-05-15 13:56:30 -0700899
900 def xmlrpc_disconnect(self, port):
901 """Disconnect from an XMLRPC server on the host.
902
903 Terminates the remote XMLRPC server previously started for
904 the given `port`. Also closes the local ssh tunnel created
905 for the connection to the host. This function does not
906 directly alter the state of a previously returned XMLRPC
907 client object; however disconnection will cause all
908 subsequent calls to methods on the object to fail.
909
910 This function does nothing if requested to disconnect a port
911 that was not previously connected via `self.xmlrpc_connect()`
912
913 @param port Port number passed to a previous call to
914 `xmlrpc_connect()`
915 """
916 if port not in self._xmlrpc_proxy_map:
917 return
918 entry = self._xmlrpc_proxy_map[port]
919 remote_name = entry[0]
920 tunnel_proc = entry[1]
921 if remote_name:
922 # We use 'pkill' to find our target process rather than
923 # a PID, because the host may have rebooted since
924 # connecting, and we don't want to kill an innocent
925 # process with the same PID.
926 #
927 # 'pkill' helpfully exits with status 1 if no target
928 # process is found, for which run() will throw an
Simran Basid5e5e272012-09-24 15:23:59 -0700929 # exception. We don't want that, so we the ignore
J. Richard Barnette1d78b012012-05-15 13:56:30 -0700930 # status.
931 self.run("pkill -f '%s'" % remote_name, ignore_status=True)
932
933 if tunnel_proc.poll() is None:
934 tunnel_proc.terminate()
935 logging.debug('Terminated tunnel, pid %d', tunnel_proc.pid)
936 else:
937 logging.debug('Tunnel pid %d terminated early, status %d',
938 tunnel_proc.pid, tunnel_proc.returncode)
939 del self._xmlrpc_proxy_map[port]
940
941
942 def xmlrpc_disconnect_all(self):
943 """Disconnect all known XMLRPC proxy ports."""
944 for port in self._xmlrpc_proxy_map.keys():
945 self.xmlrpc_disconnect(port)
946
947
J. Richard Barnetteb6de7e32013-02-14 13:28:04 -0800948 def _ping_check_status(self, status):
949 """Ping the host once, and return whether it has a given status.
J. Richard Barnette134ec2c2012-04-25 12:59:37 -0700950
J. Richard Barnetteb6de7e32013-02-14 13:28:04 -0800951 @param status Check the ping status against this value.
952 @return True iff `status` and the result of ping are the same
953 (i.e. both True or both False).
954
955 """
956 ping_val = utils.ping(self.hostname, tries=1, deadline=1)
957 return not (status ^ (ping_val == 0))
958
959 def _ping_wait_for_status(self, status, timeout):
960 """Wait for the host to have a given status (UP or DOWN).
961
962 Status is checked by polling. Polling will not last longer
963 than the number of seconds in `timeout`. The polling
964 interval will be long enough that only approximately
965 _PING_WAIT_COUNT polling cycles will be executed, subject
966 to a maximum interval of about one minute.
967
968 @param status Waiting will stop immediately if `ping` of the
969 host returns this status.
970 @param timeout Poll for at most this many seconds.
971 @return True iff the host status from `ping` matched the
972 requested status at the time of return.
973
974 """
975 # _ping_check_status() takes about 1 second, hence the
976 # "- 1" in the formula below.
977 poll_interval = min(int(timeout / self._PING_WAIT_COUNT), 60) - 1
978 end_time = time.time() + timeout
979 while time.time() <= end_time:
980 if self._ping_check_status(status):
981 return True
982 if poll_interval > 0:
983 time.sleep(poll_interval)
984
985 # The last thing we did was sleep(poll_interval), so it may
986 # have been too long since the last `ping`. Check one more
987 # time, just to be sure.
988 return self._ping_check_status(status)
989
990 def ping_wait_up(self, timeout):
991 """Wait for the host to respond to `ping`.
992
993 N.B. This method is not a reliable substitute for
994 `wait_up()`, because a host that responds to ping will not
995 necessarily respond to ssh. This method should only be used
996 if the target DUT can be considered functional even if it
997 can't be reached via ssh.
998
999 @param timeout Minimum time to allow before declaring the
1000 host to be non-responsive.
1001 @return True iff the host answered to ping before the timeout.
1002
1003 """
1004 return self._ping_wait_for_status(self._PING_STATUS_UP, timeout)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001005
Andrew Bresticker678c0c72013-01-22 10:44:09 -08001006 def ping_wait_down(self, timeout):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001007 """Wait until the host no longer responds to `ping`.
1008
J. Richard Barnetteb6de7e32013-02-14 13:28:04 -08001009 This function can be used as a slightly faster version of
1010 `wait_down()`, by avoiding potentially long ssh timeouts.
1011
1012 @param timeout Minimum time to allow for the host to become
1013 non-responsive.
1014 @return True iff the host quit answering ping before the
1015 timeout.
1016
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001017 """
J. Richard Barnetteb6de7e32013-02-14 13:28:04 -08001018 return self._ping_wait_for_status(self._PING_STATUS_DOWN, timeout)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001019
1020 def test_wait_for_sleep(self):
1021 """Wait for the client to enter low-power sleep mode.
1022
1023 The test for "is asleep" can't distinguish a system that is
1024 powered off; to confirm that the unit was asleep, it is
1025 necessary to force resume, and then call
1026 `test_wait_for_resume()`.
1027
1028 This function is expected to be called from a test as part
1029 of a sequence like the following:
1030
1031 ~~~~~~~~
1032 boot_id = host.get_boot_id()
1033 # trigger sleep on the host
1034 host.test_wait_for_sleep()
1035 # trigger resume on the host
1036 host.test_wait_for_resume(boot_id)
1037 ~~~~~~~~
1038
1039 @exception TestFail The host did not go to sleep within
1040 the allowed time.
1041 """
Andrew Bresticker678c0c72013-01-22 10:44:09 -08001042 if not self.ping_wait_down(timeout=self.SLEEP_TIMEOUT):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001043 raise error.TestFail(
1044 'client failed to sleep after %d seconds' %
J. Richard Barnetteeb69d722012-06-18 17:29:44 -07001045 self.SLEEP_TIMEOUT)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001046
1047
1048 def test_wait_for_resume(self, old_boot_id):
1049 """Wait for the client to resume from low-power sleep mode.
1050
1051 The `old_boot_id` parameter should be the value from
1052 `get_boot_id()` obtained prior to entering sleep mode. A
1053 `TestFail` exception is raised if the boot id changes.
1054
1055 See @ref test_wait_for_sleep for more on this function's
1056 usage.
1057
J. Richard Barnette7214e0b2013-02-06 15:20:49 -08001058 @param old_boot_id A boot id value obtained before the
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001059 target host went to sleep.
1060
1061 @exception TestFail The host did not respond within the
1062 allowed time.
1063 @exception TestFail The host responded, but the boot id test
1064 indicated a reboot rather than a sleep
1065 cycle.
1066 """
J. Richard Barnetteeb69d722012-06-18 17:29:44 -07001067 if not self.wait_up(timeout=self.RESUME_TIMEOUT):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001068 raise error.TestFail(
1069 'client failed to resume from sleep after %d seconds' %
J. Richard Barnetteeb69d722012-06-18 17:29:44 -07001070 self.RESUME_TIMEOUT)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001071 else:
1072 new_boot_id = self.get_boot_id()
1073 if new_boot_id != old_boot_id:
1074 raise error.TestFail(
1075 'client rebooted, but sleep was expected'
1076 ' (old boot %s, new boot %s)'
1077 % (old_boot_id, new_boot_id))
1078
1079
1080 def test_wait_for_shutdown(self):
1081 """Wait for the client to shut down.
1082
1083 The test for "has shut down" can't distinguish a system that
1084 is merely asleep; to confirm that the unit was down, it is
1085 necessary to force boot, and then call test_wait_for_boot().
1086
1087 This function is expected to be called from a test as part
1088 of a sequence like the following:
1089
1090 ~~~~~~~~
1091 boot_id = host.get_boot_id()
1092 # trigger shutdown on the host
1093 host.test_wait_for_shutdown()
1094 # trigger boot on the host
1095 host.test_wait_for_boot(boot_id)
1096 ~~~~~~~~
1097
1098 @exception TestFail The host did not shut down within the
1099 allowed time.
1100 """
Andrew Bresticker678c0c72013-01-22 10:44:09 -08001101 if not self.ping_wait_down(timeout=self.SHUTDOWN_TIMEOUT):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001102 raise error.TestFail(
1103 'client failed to shut down after %d seconds' %
J. Richard Barnetteeb69d722012-06-18 17:29:44 -07001104 self.SHUTDOWN_TIMEOUT)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001105
1106
1107 def test_wait_for_boot(self, old_boot_id=None):
1108 """Wait for the client to boot from cold power.
1109
1110 The `old_boot_id` parameter should be the value from
1111 `get_boot_id()` obtained prior to shutting down. A
1112 `TestFail` exception is raised if the boot id does not
1113 change. The boot id test is omitted if `old_boot_id` is not
1114 specified.
1115
1116 See @ref test_wait_for_shutdown for more on this function's
1117 usage.
1118
J. Richard Barnette7214e0b2013-02-06 15:20:49 -08001119 @param old_boot_id A boot id value obtained before the
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001120 shut down.
1121
1122 @exception TestFail The host did not respond within the
1123 allowed time.
1124 @exception TestFail The host responded, but the boot id test
1125 indicated that there was no reboot.
1126 """
J. Richard Barnetteeb69d722012-06-18 17:29:44 -07001127 if not self.wait_up(timeout=self.REBOOT_TIMEOUT):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001128 raise error.TestFail(
1129 'client failed to reboot after %d seconds' %
J. Richard Barnetteeb69d722012-06-18 17:29:44 -07001130 self.REBOOT_TIMEOUT)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001131 elif old_boot_id:
1132 if self.get_boot_id() == old_boot_id:
1133 raise error.TestFail(
1134 'client is back up, but did not reboot'
1135 ' (boot %s)' % old_boot_id)
Simran Basid5e5e272012-09-24 15:23:59 -07001136
1137
1138 @staticmethod
1139 def check_for_rpm_support(hostname):
1140 """For a given hostname, return whether or not it is powered by an RPM.
1141
1142 @return None if this host does not follows the defined naming format
1143 for RPM powered DUT's in the lab. If it does follow the format,
1144 it returns a regular expression MatchObject instead.
1145 """
Richard Barnette82c35912012-11-20 10:09:10 -08001146 return re.match(SiteHost._RPM_HOSTNAME_REGEX, hostname)
Simran Basid5e5e272012-09-24 15:23:59 -07001147
1148
1149 def has_power(self):
1150 """For this host, return whether or not it is powered by an RPM.
1151
1152 @return True if this host is in the CROS lab and follows the defined
1153 naming format.
1154 """
1155 return SiteHost.check_for_rpm_support(self.hostname)
1156
1157
Ismail Noorbasha07fdb612013-02-14 14:13:31 -08001158 def _set_power(self, state, power_method):
1159 """Sets the power to the host via RPM, Servo or manual.
1160
1161 @param state Specifies which power state to set to DUT
1162 @param power_method Specifies which method of power control to
1163 use. By default "RPM" will be used. Valid values
1164 are the strings "RPM", "manual", "servoj10".
1165
1166 """
1167 ACCEPTABLE_STATES = ['ON', 'OFF']
1168
1169 if state.upper() not in ACCEPTABLE_STATES:
1170 raise error.TestError('State must be one of: %s.'
1171 % (ACCEPTABLE_STATES,))
1172
1173 if power_method == self.POWER_CONTROL_SERVO:
1174 logging.info('Setting servo port J10 to %s', state)
1175 self.servo.set('prtctl3_pwren', state.lower())
1176 time.sleep(self._USB_POWER_TIMEOUT)
1177 elif power_method == self.POWER_CONTROL_MANUAL:
1178 logging.info('You have %d seconds to set the AC power to %s.',
1179 self._POWER_CYCLE_TIMEOUT, state)
1180 time.sleep(self._POWER_CYCLE_TIMEOUT)
1181 else:
1182 if not self.has_power():
1183 raise error.TestFail('DUT does not have RPM connected.')
Simran Basi5e6339a2013-03-21 11:34:32 -07001184 afe = frontend_wrappers.RetryingAFE(timeout_min=5, delay_sec=10)
1185 afe.set_host_attribute(self._RPM_OUTLET_CHANGED, True,
1186 hostname=self.hostname)
Ismail Noorbasha07fdb612013-02-14 14:13:31 -08001187 rpm_client.set_power(self.hostname, state.upper())
Simran Basid5e5e272012-09-24 15:23:59 -07001188
1189
Ismail Noorbasha07fdb612013-02-14 14:13:31 -08001190 def power_off(self, power_method=POWER_CONTROL_RPM):
1191 """Turn off power to this host via RPM, Servo or manual.
1192
1193 @param power_method Specifies which method of power control to
1194 use. By default "RPM" will be used. Valid values
1195 are the strings "RPM", "manual", "servoj10".
1196
1197 """
1198 self._set_power('OFF', power_method)
Simran Basid5e5e272012-09-24 15:23:59 -07001199
1200
Ismail Noorbasha07fdb612013-02-14 14:13:31 -08001201 def power_on(self, power_method=POWER_CONTROL_RPM):
1202 """Turn on power to this host via RPM, Servo or manual.
1203
1204 @param power_method Specifies which method of power control to
1205 use. By default "RPM" will be used. Valid values
1206 are the strings "RPM", "manual", "servoj10".
1207
1208 """
1209 self._set_power('ON', power_method)
1210
1211
1212 def power_cycle(self, power_method=POWER_CONTROL_RPM):
1213 """Cycle power to this host by turning it OFF, then ON.
1214
1215 @param power_method Specifies which method of power control to
1216 use. By default "RPM" will be used. Valid values
1217 are the strings "RPM", "manual", "servoj10".
1218
1219 """
1220 if power_method in (self.POWER_CONTROL_SERVO,
1221 self.POWER_CONTROL_MANUAL):
1222 self.power_off(power_method=power_method)
1223 time.sleep(self._POWER_CYCLE_TIMEOUT)
1224 self.power_on(power_method=power_method)
1225 else:
1226 rpm_client.set_power(self.hostname, 'CYCLE')
Simran Basic6f1f7a2012-10-16 10:47:46 -07001227
1228
1229 def get_platform(self):
1230 """Determine the correct platform label for this host.
1231
1232 @returns a string representing this host's platform.
1233 """
1234 crossystem = utils.Crossystem(self)
1235 crossystem.init()
1236 # Extract fwid value and use the leading part as the platform id.
1237 # fwid generally follow the format of {platform}.{firmware version}
1238 # Example: Alex.X.YYY.Z or Google_Alex.X.YYY.Z
1239 platform = crossystem.fwid().split('.')[0].lower()
1240 # Newer platforms start with 'Google_' while the older ones do not.
1241 return platform.replace('google_', '')
1242
1243
Aviv Keshet74c89a92013-02-04 15:18:30 -08001244 @label_decorator()
Simran Basic6f1f7a2012-10-16 10:47:46 -07001245 def get_board(self):
1246 """Determine the correct board label for this host.
1247
1248 @returns a string representing this host's board.
1249 """
1250 release_info = utils.parse_cmd_output('cat /etc/lsb-release',
1251 run_method=self.run)
1252 board = release_info['CHROMEOS_RELEASE_BOARD']
1253 # Devices in the lab generally have the correct board name but our own
1254 # development devices have {board_name}-signed-{key_type}. The board
1255 # name may also begin with 'x86-' which we need to keep.
Simran Basi833814b2013-01-29 13:13:43 -08001256 board_format_string = ds_constants.BOARD_PREFIX + '%s'
Simran Basic6f1f7a2012-10-16 10:47:46 -07001257 if 'x86' not in board:
Simran Basi833814b2013-01-29 13:13:43 -08001258 return board_format_string % board.split('-')[0]
1259 return board_format_string % '-'.join(board.split('-')[0:2])
Simran Basic6f1f7a2012-10-16 10:47:46 -07001260
1261
Aviv Keshet74c89a92013-02-04 15:18:30 -08001262 @label_decorator('lightsensor')
Simran Basic6f1f7a2012-10-16 10:47:46 -07001263 def has_lightsensor(self):
1264 """Determine the correct board label for this host.
1265
1266 @returns the string 'lightsensor' if this host has a lightsensor or
1267 None if it does not.
1268 """
1269 search_cmd = "find -L %s -maxdepth 4 | egrep '%s'" % (
Richard Barnette82c35912012-11-20 10:09:10 -08001270 self._LIGHTSENSOR_SEARCH_DIR, '|'.join(self._LIGHTSENSOR_FILES))
Simran Basic6f1f7a2012-10-16 10:47:46 -07001271 try:
1272 # Run the search cmd following the symlinks. Stderr_tee is set to
1273 # None as there can be a symlink loop, but the command will still
1274 # execute correctly with a few messages printed to stderr.
1275 self.run(search_cmd, stdout_tee=None, stderr_tee=None)
1276 return 'lightsensor'
1277 except error.AutoservRunError:
1278 # egrep exited with a return code of 1 meaning none of the possible
1279 # lightsensor files existed.
1280 return None
1281
1282
Aviv Keshet74c89a92013-02-04 15:18:30 -08001283 @label_decorator('bluetooth')
Simran Basic6f1f7a2012-10-16 10:47:46 -07001284 def has_bluetooth(self):
1285 """Determine the correct board label for this host.
1286
1287 @returns the string 'bluetooth' if this host has bluetooth or
1288 None if it does not.
1289 """
1290 try:
1291 self.run('test -d /sys/class/bluetooth/hci0')
1292 # test exited with a return code of 0.
1293 return 'bluetooth'
1294 except error.AutoservRunError:
1295 # test exited with a return code 1 meaning the directory did not
1296 # exist.
1297 return None
1298
1299
1300 def get_labels(self):
1301 """Return a list of labels for this given host.
1302
1303 This is the main way to retrieve all the automatic labels for a host
1304 as it will run through all the currently implemented label functions.
1305 """
1306 labels = []
Richard Barnette82c35912012-11-20 10:09:10 -08001307 for label_function in self._LABEL_FUNCTIONS:
Simran Basic6f1f7a2012-10-16 10:47:46 -07001308 label = label_function(self)
1309 if label:
1310 labels.append(label)
1311 return labels