blob: a96b8c093b7500ab723b945ac68826d22d4a38ca [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
beepscb6f1e22013-06-28 19:14:10 -0700316 self.update_job_repo_url(None, None)
317
318
319 def update_job_repo_url(self, devserver_url, image_name):
320 """
321 Updates the job_repo_url host attribute and asserts it's value.
322
323 @param devserver_url: The devserver to use in the job_repo_url.
324 @param image_name: The name of the image to use in the job_repo_url.
325
326 @raises AutoservError: If we failed to update the job_repo_url.
327 """
328 repo_url = None
329 if devserver_url and image_name:
330 repo_url = tools.get_package_url(devserver_url, image_name)
331 self._AFE.set_host_attribute(ds_constants.JOB_REPO_URL, repo_url,
Scott Zawalski62bacae2013-03-05 10:40:32 -0500332 hostname=self.hostname)
beepscb6f1e22013-06-28 19:14:10 -0700333 if self.lookup_job_repo_url() != repo_url:
334 raise error.AutoservError('Failed to update job_repo_url with %s, '
335 'host %s' % (repo_url, self.hostname))
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500336
337
Dan Shie9309262013-06-19 22:50:21 -0700338 def add_cros_version_labels_and_job_repo_url(self, image_name):
Scott Zawalskieadbf702013-03-14 09:23:06 -0400339 """Add cros_version labels and host attribute job_repo_url.
340
341 @param image_name: The name of the image e.g.
342 lumpy-release/R27-3837.0.0
343 """
Scott Zawalski62bacae2013-03-05 10:40:32 -0500344 if not self._host_in_AFE():
Scott Zawalskieadbf702013-03-14 09:23:06 -0400345 return
Scott Zawalski62bacae2013-03-05 10:40:32 -0500346
Scott Zawalskieadbf702013-03-14 09:23:06 -0400347 cros_label = '%s%s' % (ds_constants.VERSION_PREFIX, image_name)
Dan Shie9309262013-06-19 22:50:21 -0700348 devserver_url = dev_server.ImageServer.resolve(image_name).url()
Scott Zawalski62bacae2013-03-05 10:40:32 -0500349
350 labels = self._AFE.get_labels(name=cros_label)
351 if labels:
352 label = labels[0]
353 else:
354 label = self._AFE.create_label(name=cros_label)
355
356 label.add_hosts([self.hostname])
beepscb6f1e22013-06-28 19:14:10 -0700357 self.update_job_repo_url(devserver_url, image_name)
358
359
360 def verify_job_repo_url(self):
361 """
362 Make sure job_repo_url of this host is valid.
363
364 Eg: The job_repo_url "http://lmn.cd.ab.xyx:8080/static/archive/\
365 lumpy-release/R29-4279.0.0/autotest/packages" claims to have the
366 autotest package for lumpy-release/R29-4279.0.0. If this isn't the case,
367 download and extract it. If the devserver embedded in the url is
368 unresponsive, update the job_repo_url of the host after staging it on
369 another devserver.
370
371 @param job_repo_url: A url pointing to the devserver where the autotest
372 package for this build should be staged.
373
374 @raises DevServerException: If we could not resolve a devserver.
375 @raises AutoservError: If we're unable to save the new job_repo_url as
376 a result of choosing a new devserver because the old one failed to
377 respond to a health check.
378 """
379 job_repo_url = self.lookup_job_repo_url()
380 if not job_repo_url:
381 logging.warning('No job repo url set on host %s', self.hostname)
382 return
383
384 logging.info('Verifying job repo url %s', job_repo_url)
385 devserver_url, image_name = tools.get_devserver_build_from_package_url(
386 job_repo_url)
387
388 ds = dev_server.ImageServer.resolve(image_name)
389
390 logging.info('Staging autotest artifacts for %s on devserver %s',
391 image_name, ds.url())
392 ds.stage_artifacts(image_name, ['autotest'])
393
394 if ds.url() != devserver_url:
395 logging.info('Devserver url changed, new devserver is %s'
396 'old devserver was %s',
397 ds.url(), devserver_url)
398 self.update_job_repo_url(ds.url(), image_name)
Scott Zawalskieadbf702013-03-14 09:23:06 -0400399
400
Dan Shi0f466e82013-02-22 15:44:58 -0800401 def _try_stateful_update(self, update_url, force_update, updater):
402 """Try to use stateful update to initialize DUT.
403
404 When DUT is already running the same version that machine_install
405 tries to install, stateful update is a much faster way to clean up
406 the DUT for testing, compared to a full reimage. It is implemeted
407 by calling autoupdater.run_update, but skipping updating root, as
408 updating the kernel is time consuming and not necessary.
409
410 @param update_url: url of the image.
411 @param force_update: Set to True to update the image even if the DUT
412 is running the same version.
413 @param updater: ChromiumOSUpdater instance used to update the DUT.
414 @returns: True if the DUT was updated with stateful update.
415
416 """
417 if not updater.check_version():
418 return False
419 if not force_update:
420 logging.info('Canceling stateful update because the new and '
421 'old versions are the same.')
422 return False
423 # Following folders should be rebuilt after stateful update.
424 # A test file is used to confirm each folder gets rebuilt after
425 # the stateful update.
426 folders_to_check = ['/var', '/home', '/mnt/stateful_partition']
427 test_file = '.test_file_to_be_deleted'
428 for folder in folders_to_check:
429 touch_path = os.path.join(folder, test_file)
430 self.run('touch %s' % touch_path)
431
432 if not updater.run_update(force_update=True, update_root=False):
433 return False
434
435 # Reboot to complete stateful update.
Chris Sosab76e0ee2013-05-22 16:55:41 -0700436 self.reboot(timeout=self.REBOOT_TIMEOUT, wait=True)
Dan Shi0f466e82013-02-22 15:44:58 -0800437 check_file_cmd = 'test -f %s; echo $?'
438 for folder in folders_to_check:
439 test_file_path = os.path.join(folder, test_file)
440 result = self.run(check_file_cmd % test_file_path,
441 ignore_status=True)
442 if result.exit_status == 1:
443 return False
444 return True
445
446
J. Richard Barnette7275b612013-06-04 18:13:11 -0700447 def _post_update_processing(self, updater, expected_kernel=None):
Dan Shi0f466e82013-02-22 15:44:58 -0800448 """After the DUT is updated, confirm machine_install succeeded.
449
450 @param updater: ChromiumOSUpdater instance used to update the DUT.
J. Richard Barnette7275b612013-06-04 18:13:11 -0700451 @param expected_kernel: kernel expected to be active after reboot,
452 or `None` to skip rollback checking.
Dan Shi0f466e82013-02-22 15:44:58 -0800453
454 """
J. Richard Barnette7275b612013-06-04 18:13:11 -0700455 # Touch the lab machine file to leave a marker that
456 # distinguishes this image from other test images.
457 # Afterwards, we must re-run the autoreboot script because
458 # it depends on the _LAB_MACHINE_FILE.
Dan Shi0f466e82013-02-22 15:44:58 -0800459 self.run('touch %s' % self._LAB_MACHINE_FILE)
Dan Shi0f466e82013-02-22 15:44:58 -0800460 self.run('start autoreboot')
461
J. Richard Barnette7275b612013-06-04 18:13:11 -0700462 # Figure out the newly active kernel.
463 active_kernel, _ = updater.get_kernel_state()
464
465 # Check for rollback due to a bad build.
466 if expected_kernel and active_kernel != expected_kernel:
467 # Print out some information to make it easier to debug
468 # the rollback.
Dan Shi0f466e82013-02-22 15:44:58 -0800469 logging.debug('Dumping partition table.')
Dan Shi346725f2013-03-20 15:22:38 -0700470 self.run('cgpt show $(rootdev -s -d)')
Dan Shi0f466e82013-02-22 15:44:58 -0800471 logging.debug('Dumping crossystem for firmware debugging.')
Dan Shi346725f2013-03-20 15:22:38 -0700472 self.run('crossystem --all')
Dan Shi0f466e82013-02-22 15:44:58 -0800473 raise autoupdater.ChromiumOSError(
J. Richard Barnette7275b612013-06-04 18:13:11 -0700474 'Build %s failed to boot on %s; system rolled back '
475 'to previous build' % (updater.update_version,
476 self.hostname))
Dan Shi0f466e82013-02-22 15:44:58 -0800477
J. Richard Barnette7275b612013-06-04 18:13:11 -0700478 # Check that we've got the build we meant to install.
479 if not updater.check_version_to_confirm_install():
480 raise autoupdater.ChromiumOSError(
481 'Failed to update %s to build %s; found build '
482 '%s instead' % (self.hostname,
483 updater.update_version,
484 updater.get_build_id()))
Scott Zawalski62bacae2013-03-05 10:40:32 -0500485
J. Richard Barnette7275b612013-06-04 18:13:11 -0700486 # Make sure chromeos-setgoodkernel runs.
487 try:
Dan Shi0f466e82013-02-22 15:44:58 -0800488 utils.poll_for_condition(
J. Richard Barnette7275b612013-06-04 18:13:11 -0700489 lambda: (updater.get_kernel_tries(active_kernel) == 0
490 and updater.get_kernel_success(active_kernel)),
491 exception=autoupdater.ChromiumOSError(),
Dan Shi0f466e82013-02-22 15:44:58 -0800492 timeout=self._KERNEL_UPDATE_TIMEOUT, sleep_interval=5)
J. Richard Barnette7275b612013-06-04 18:13:11 -0700493 except autoupdater.ChromiumOSError as e:
494 services_status = self.run('status system-services').stdout
495 if services_status != 'system-services start/running\n':
496 event = ('Chrome failed to reach login screen')
497 else:
498 event = ('update-engine failed to call '
499 'chromeos-setgoodkernel')
500 raise autoupdater.ChromiumOSError(
501 'After update and reboot, %s '
502 'within %d seconds' % (event,
503 self._KERNEL_UPDATE_TIMEOUT))
Dan Shi0f466e82013-02-22 15:44:58 -0800504
505
J. Richard Barnettee4af8b92013-05-01 13:16:12 -0700506 def _stage_image_for_update(self, image_name=None):
Scott Zawalskieadbf702013-03-14 09:23:06 -0400507 """Stage a build on a devserver and return the update_url.
508
509 @param image_name: a name like lumpy-release/R27-3837.0.0
510 @returns an update URL like:
511 http://172.22.50.205:8082/update/lumpy-release/R27-3837.0.0
512 """
J. Richard Barnettee4af8b92013-05-01 13:16:12 -0700513 if not image_name:
514 image_name = self.get_repair_image_name()
515 logging.info('Staging build for AU: %s', image_name)
Scott Zawalskieadbf702013-03-14 09:23:06 -0400516 devserver = dev_server.ImageServer.resolve(image_name)
517 devserver.trigger_download(image_name, synchronous=False)
518 return tools.image_url_pattern() % (devserver.url(), image_name)
519
520
J. Richard Barnettee4af8b92013-05-01 13:16:12 -0700521 def stage_image_for_servo(self, image_name=None):
522 """Stage a build on a devserver and return the update_url.
523
524 @param image_name: a name like lumpy-release/R27-3837.0.0
525 @returns an update URL like:
526 http://172.22.50.205:8082/update/lumpy-release/R27-3837.0.0
527 """
528 if not image_name:
529 image_name = self.get_repair_image_name()
530 logging.info('Staging build for servo install: %s', image_name)
531 devserver = dev_server.ImageServer.resolve(image_name)
532 devserver.stage_artifacts(image_name, ['test_image'])
533 return devserver.get_test_image_url(image_name)
534
535
Chris Sosaa3ac2152012-05-23 22:23:13 -0700536 def machine_install(self, update_url=None, force_update=False,
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500537 local_devserver=False, repair=False):
538 """Install the DUT.
539
Dan Shi0f466e82013-02-22 15:44:58 -0800540 Use stateful update if the DUT is already running the same build.
541 Stateful update does not update kernel and tends to run much faster
542 than a full reimage. If the DUT is running a different build, or it
543 failed to do a stateful update, full update, including kernel update,
544 will be applied to the DUT.
545
Scott Zawalskieadbf702013-03-14 09:23:06 -0400546 Once a host enters machine_install its cros_version label will be
547 removed as well as its host attribute job_repo_url (used for
548 package install).
549
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500550 @param update_url: The url to use for the update
551 pattern: http://$devserver:###/update/$build
552 If update_url is None and repair is True we will install the
553 stable image listed in global_config under
554 CROS.stable_cros_version.
555 @param force_update: Force an update even if the version installed
556 is the same. Default:False
557 @param local_devserver: Used by run_remote_test to allow people to
558 use their local devserver. Default: False
559 @param repair: Whether or not we are in repair mode. This adds special
560 cases for repairing a machine like starting update_engine.
561 Setting repair to True sets force_update to True as well.
562 default: False
563 @raises autoupdater.ChromiumOSError
564
565 """
J. Richard Barnettee4af8b92013-05-01 13:16:12 -0700566 if not update_url:
567 if self._parser.options.image:
568 requested_build = self._parser.options.image
569 if requested_build.startswith('http://'):
570 update_url = requested_build
571 else:
572 # Try to stage any build that does not start with
573 # http:// on the devservers defined in
574 # global_config.ini.
575 update_url = self._stage_image_for_update(
576 requested_build)
577 elif repair:
578 update_url = self._stage_image_for_update()
Scott Zawalskieadbf702013-03-14 09:23:06 -0400579 else:
J. Richard Barnettee4af8b92013-05-01 13:16:12 -0700580 raise autoupdater.ChromiumOSError(
581 'Update failed. No update URL provided.')
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500582
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500583 if repair:
Dan Shi0f466e82013-02-22 15:44:58 -0800584 # In case the system is in a bad state, we always reboot the machine
585 # before machine_install.
Chris Sosab76e0ee2013-05-22 16:55:41 -0700586 self.reboot(timeout=self.REBOOT_TIMEOUT, wait=True)
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500587 self.run('stop update-engine; start update-engine')
588 force_update = True
Dan Shi0f466e82013-02-22 15:44:58 -0800589
Chris Sosaa3ac2152012-05-23 22:23:13 -0700590 updater = autoupdater.ChromiumOSUpdater(update_url, host=self,
Chris Sosa72312602013-04-16 15:01:56 -0700591 local_devserver=local_devserver)
Dan Shi0f466e82013-02-22 15:44:58 -0800592 updated = False
Scott Zawalskieadbf702013-03-14 09:23:06 -0400593 # Remove cros-version and job_repo_url host attribute from host.
594 self.clear_cros_version_labels_and_job_repo_url()
Dan Shi0f466e82013-02-22 15:44:58 -0800595 # If the DUT is already running the same build, try stateful update
596 # first. Stateful update does not update kernel and tends to run much
597 # faster than a full reimage.
598 try:
Chris Sosab76e0ee2013-05-22 16:55:41 -0700599 updated = self._try_stateful_update(
600 update_url, force_update, updater)
Dan Shi0f466e82013-02-22 15:44:58 -0800601 if updated:
602 logging.info('DUT is updated with stateful update.')
603 except Exception as e:
604 logging.exception(e)
605 logging.warn('Failed to stateful update DUT, force to update.')
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700606
Dan Shi0f466e82013-02-22 15:44:58 -0800607 inactive_kernel = None
608 # Do a full update if stateful update is not applicable or failed.
609 if not updated:
610 # In case the system is in a bad state, we always reboot the
611 # machine before machine_install.
Chris Sosab76e0ee2013-05-22 16:55:41 -0700612 self.reboot(timeout=self.REBOOT_TIMEOUT, wait=True)
Chris Sosab7612bc2013-03-21 10:32:37 -0700613
614 # TODO(sosa): Remove temporary hack to get rid of bricked machines
615 # that can't update due to a corrupted policy.
616 self.run('rm -rf /var/lib/whitelist')
617 self.run('touch /var/lib/whitelist')
618 self.run('chmod -w /var/lib/whitelist')
Scott Zawalskib550d5a2013-03-22 09:23:59 -0400619 self.run('stop update-engine; start update-engine')
Chris Sosab7612bc2013-03-21 10:32:37 -0700620
Dan Shi0f466e82013-02-22 15:44:58 -0800621 if updater.run_update(force_update):
622 updated = True
623 # Figure out active and inactive kernel.
624 active_kernel, inactive_kernel = updater.get_kernel_state()
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700625
Dan Shi0f466e82013-02-22 15:44:58 -0800626 # Ensure inactive kernel has higher priority than active.
627 if (updater.get_kernel_priority(inactive_kernel)
628 < updater.get_kernel_priority(active_kernel)):
629 raise autoupdater.ChromiumOSError(
630 'Update failed. The priority of the inactive kernel'
631 ' partition is less than that of the active kernel'
632 ' partition.')
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700633
Dan Shi0f466e82013-02-22 15:44:58 -0800634 update_engine_log = '/var/log/update_engine.log'
635 logging.info('Dumping %s', update_engine_log)
636 self.run('cat %s' % update_engine_log)
637 # Updater has returned successfully; reboot the host.
Chris Sosab76e0ee2013-05-22 16:55:41 -0700638 self.reboot(timeout=self.REBOOT_TIMEOUT, wait=True)
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700639
Dan Shi0f466e82013-02-22 15:44:58 -0800640 if updated:
641 self._post_update_processing(updater, inactive_kernel)
Scott Zawalskieadbf702013-03-14 09:23:06 -0400642 image_name = autoupdater.url_to_image_name(update_url)
Dan Shie9309262013-06-19 22:50:21 -0700643 self.add_cros_version_labels_and_job_repo_url(image_name)
Simran Basi13fa1ba2013-03-04 10:56:47 -0800644
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700645 # Clean up any old autotest directories which may be lying around.
646 for path in global_config.global_config.get_config_value(
647 'AUTOSERV', 'client_autodir_paths', type=list):
648 self.run('rm -rf ' + path)
649
650
Simran Basi833814b2013-01-29 13:13:43 -0800651 def _get_label_from_afe(self, label_prefix):
652 """Retrieve a host's specific label from the AFE.
653
654 Looks for a host label that has the form <label_prefix>:<value>
655 and returns the "<value>" part of the label. None is returned
656 if there is not a label matching the pattern
657
658 @returns the label that matches the prefix or 'None'
659 """
Scott Zawalski62bacae2013-03-05 10:40:32 -0500660 labels = self._AFE.get_labels(name__startswith=label_prefix,
661 host__hostname__in=[self.hostname])
662 if labels and len(labels) == 1:
663 return labels[0].name.split(label_prefix, 1)[1]
Simran Basi833814b2013-01-29 13:13:43 -0800664
665
Richard Barnette82c35912012-11-20 10:09:10 -0800666 def _get_board_from_afe(self):
667 """Retrieve this host's board from its labels in the AFE.
668
669 Looks for a host label of the form "board:<board>", and
670 returns the "<board>" part of the label. `None` is returned
671 if there is not a single, unique label matching the pattern.
672
673 @returns board from label, or `None`.
674 """
Simran Basi833814b2013-01-29 13:13:43 -0800675 return self._get_label_from_afe(ds_constants.BOARD_PREFIX)
676
677
678 def get_build(self):
679 """Retrieve the current build for this Host from the AFE.
680
681 Looks through this host's labels in the AFE to determine its build.
682
683 @returns The current build or None if it could not find it or if there
684 were multiple build labels assigned to this host.
685 """
686 return self._get_label_from_afe(ds_constants.VERSION_PREFIX)
Richard Barnette82c35912012-11-20 10:09:10 -0800687
688
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500689 def _install_repair(self):
690 """Attempt to repair this host using upate-engine.
691
692 If the host is up, try installing the DUT with a stable
693 "repair" version of Chrome OS as defined in the global_config
694 under CROS.stable_cros_version.
695
Scott Zawalski62bacae2013-03-05 10:40:32 -0500696 @raises AutoservRepairMethodNA if the DUT is not reachable.
697 @raises ChromiumOSError if the install failed for some reason.
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500698
699 """
700 if not self.is_up():
Scott Zawalski62bacae2013-03-05 10:40:32 -0500701 raise error.AutoservRepairMethodNA('DUT unreachable for install.')
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500702
703 logging.info('Attempting to reimage machine to repair image.')
704 try:
705 self.machine_install(repair=True)
Fang Dengd0672f32013-03-18 17:18:09 -0700706 except autoupdater.ChromiumOSError as e:
707 logging.exception(e)
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500708 logging.info('Repair via install failed.')
Scott Zawalski62bacae2013-03-05 10:40:32 -0500709 raise
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500710
711
Scott Zawalski62bacae2013-03-05 10:40:32 -0500712 def servo_install(self, image_url=None):
713 """
714 Re-install the OS on the DUT by:
715 1) installing a test image on a USB storage device attached to the Servo
716 board,
Richard Barnette03a0c132012-11-05 12:40:35 -0800717 2) booting that image in recovery mode, and then
J. Richard Barnette31b2e312013-04-04 16:05:22 -0700718 3) installing the image with chromeos-install.
719
Scott Zawalski62bacae2013-03-05 10:40:32 -0500720 @param image_url: If specified use as the url to install on the DUT.
721 otherwise boot the currently staged image on the USB stick.
Richard Barnette03a0c132012-11-05 12:40:35 -0800722
Scott Zawalski62bacae2013-03-05 10:40:32 -0500723 @raises AutoservError if the image fails to boot.
Richard Barnette03a0c132012-11-05 12:40:35 -0800724 """
J. Richard Barnette31b2e312013-04-04 16:05:22 -0700725 self.servo.install_recovery_image(image_url)
Richard Barnette03a0c132012-11-05 12:40:35 -0800726 if not self.wait_up(timeout=self.USB_BOOT_TIMEOUT):
Scott Zawalski62bacae2013-03-05 10:40:32 -0500727 raise error.AutoservRepairFailure(
728 'DUT failed to boot from USB after %d seconds' %
729 self.USB_BOOT_TIMEOUT)
730
731 self.run('chromeos-install --yes', timeout=self._INSTALL_TIMEOUT)
Richard Barnette03a0c132012-11-05 12:40:35 -0800732 self.servo.power_long_press()
Fang Dengafb88142013-05-30 17:44:31 -0700733 self.servo.switch_usbkey('off')
Richard Barnette03a0c132012-11-05 12:40:35 -0800734 self.servo.power_short_press()
735 if not self.wait_up(timeout=self.BOOT_TIMEOUT):
736 raise error.AutoservError('DUT failed to reboot installed '
737 'test image after %d seconds' %
Scott Zawalski62bacae2013-03-05 10:40:32 -0500738 self.BOOT_TIMEOUT)
739
740
J. Richard Barnettee4af8b92013-05-01 13:16:12 -0700741 def _servo_repair_reinstall(self):
Scott Zawalski62bacae2013-03-05 10:40:32 -0500742 """Reinstall the DUT utilizing servo and a test image.
743
744 Re-install the OS on the DUT by:
745 1) installing a test image on a USB storage device attached to the Servo
746 board,
747 2) booting that image in recovery mode, and then
748 3) installing the image with chromeos-install.
749
Scott Zawalski62bacae2013-03-05 10:40:32 -0500750 @raises AutoservRepairMethodNA if the device does not have servo
751 support.
752
753 """
754 if not self.servo:
755 raise error.AutoservRepairMethodNA('Repair Reinstall NA: '
756 'DUT has no servo support.')
757
758 logging.info('Attempting to recovery servo enabled device with '
759 'servo_repair_reinstall')
760
J. Richard Barnettee4af8b92013-05-01 13:16:12 -0700761 image_url = self.stage_image_for_servo()
Scott Zawalski62bacae2013-03-05 10:40:32 -0500762 self.servo_install(image_url)
763
764
765 def _servo_repair_power(self):
766 """Attempt to repair DUT using an attached Servo.
767
768 Attempt to power on the DUT via power_long_press.
769
770 @raises AutoservRepairMethodNA if the device does not have servo
771 support.
772 @raises AutoservRepairFailure if the repair fails for any reason.
773 """
774 if not self.servo:
775 raise error.AutoservRepairMethodNA('Repair Power NA: '
776 'DUT has no servo support.')
777
778 logging.info('Attempting to recover servo enabled device by '
779 'powering it off and on.')
780 self.servo.get_power_state_controller().power_off()
781 self.servo.get_power_state_controller().power_on()
782 if self.wait_up(self.BOOT_TIMEOUT):
783 return
784
785 raise error.AutoservRepairFailure('DUT did not boot after long_press.')
Richard Barnette03a0c132012-11-05 12:40:35 -0800786
787
Richard Barnette82c35912012-11-20 10:09:10 -0800788 def _powercycle_to_repair(self):
789 """Utilize the RPM Infrastructure to bring the host back up.
790
791 If the host is not up/repaired after the first powercycle we utilize
792 auto fallback to the last good install by powercycling and rebooting the
793 host 6 times.
Scott Zawalski62bacae2013-03-05 10:40:32 -0500794
795 @raises AutoservRepairMethodNA if the device does not support remote
796 power.
797 @raises AutoservRepairFailure if the repair fails for any reason.
798
Richard Barnette82c35912012-11-20 10:09:10 -0800799 """
Scott Zawalski62bacae2013-03-05 10:40:32 -0500800 if not self.has_power():
801 raise error.AutoservRepairMethodNA('Device does not support power.')
802
Richard Barnette82c35912012-11-20 10:09:10 -0800803 logging.info('Attempting repair via RPM powercycle.')
804 failed_cycles = 0
805 self.power_cycle()
806 while not self.wait_up(timeout=self.BOOT_TIMEOUT):
807 failed_cycles += 1
808 if failed_cycles >= self._MAX_POWER_CYCLE_ATTEMPTS:
Scott Zawalski62bacae2013-03-05 10:40:32 -0500809 raise error.AutoservRepairFailure(
810 'Powercycled host %s %d times; device did not come back'
811 ' online.' % (self.hostname, failed_cycles))
Richard Barnette82c35912012-11-20 10:09:10 -0800812 self.power_cycle()
813 if failed_cycles == 0:
814 logging.info('Powercycling was successful first time.')
815 else:
816 logging.info('Powercycling was successful after %d failures.',
817 failed_cycles)
818
819
820 def repair_full(self):
821 """Repair a host for repair level NO_PROTECTION.
822
823 This overrides the base class function for repair; it does
824 not call back to the parent class, but instead offers a
825 simplified implementation based on the capabilities in the
826 Chrome OS test lab.
827
J. Richard Barnettefde55fc2013-03-15 17:47:01 -0700828 If `self.verify()` fails, the following procedures are
829 attempted:
830 1. Try to re-install to a known stable image using
831 auto-update.
Scott Zawalski62bacae2013-03-05 10:40:32 -0500832 2. If there's a servo for the DUT, try to power the DUT off and
833 on.
834 3. If there's a servo for the DUT, try to re-install via
J. Richard Barnettefde55fc2013-03-15 17:47:01 -0700835 the servo.
Scott Zawalski62bacae2013-03-05 10:40:32 -0500836 4. If the DUT can be power-cycled via RPM, try to repair
Richard Barnette82c35912012-11-20 10:09:10 -0800837 by power-cycling.
838
839 As with the parent method, the last operation performed on
840 the DUT must be to call `self.verify()`; if that call fails,
841 the exception it raises is passed back to the caller.
J. Richard Barnettefde55fc2013-03-15 17:47:01 -0700842
Scott Zawalski62bacae2013-03-05 10:40:32 -0500843 @raises AutoservRepairTotalFailure if the repair process fails to
844 fix the DUT.
Richard Barnette82c35912012-11-20 10:09:10 -0800845 """
Scott Zawalski62bacae2013-03-05 10:40:32 -0500846 # TODO(scottz): This should use something similar to label_decorator,
847 # but needs to be populated in order so DUTs are repaired with the
848 # least amount of effort.
849 repair_funcs = [self._install_repair, self._servo_repair_power,
J. Richard Barnettee4af8b92013-05-01 13:16:12 -0700850 self._servo_repair_reinstall,
Scott Zawalski62bacae2013-03-05 10:40:32 -0500851 self._powercycle_to_repair]
852 errors = []
853 for repair_func in repair_funcs:
854 try:
855 repair_func()
856 self.verify()
857 return
858 except Exception as e:
859 logging.warn('Failed to repair device: %s', e)
860 errors.append(str(e))
Scott Zawalski89c44dd2013-02-26 09:28:02 -0500861
Scott Zawalski62bacae2013-03-05 10:40:32 -0500862 raise error.AutoservRepairTotalFailure(
863 'All attempts at repairing the device failed:\n%s' %
864 '\n'.join(errors))
Richard Barnette82c35912012-11-20 10:09:10 -0800865
866
J. Richard Barnette1d78b012012-05-15 13:56:30 -0700867 def close(self):
868 super(SiteHost, self).close()
869 self.xmlrpc_disconnect_all()
870
871
Simran Basi5e6339a2013-03-21 11:34:32 -0700872 def _cleanup_poweron(self):
873 """Special cleanup method to make sure hosts always get power back."""
874 afe = frontend_wrappers.RetryingAFE(timeout_min=5, delay_sec=10)
875 hosts = afe.get_hosts(hostname=self.hostname)
876 if not hosts or not (self._RPM_OUTLET_CHANGED in
877 hosts[0].attributes):
878 return
879 logging.debug('This host has recently interacted with the RPM'
880 ' Infrastructure. Ensuring power is on.')
881 try:
882 self.power_on()
883 except rpm_client.RemotePowerException:
884 # If cleanup has completed but there was an issue with the RPM
885 # Infrastructure, log an error message rather than fail cleanup
886 logging.error('Failed to turn Power On for this host after '
887 'cleanup through the RPM Infrastructure.')
888 afe.set_host_attribute(self._RPM_OUTLET_CHANGED, None,
889 hostname=self.hostname)
890
891
Chris Sosaf4d43ff2012-10-30 11:21:05 -0700892 def cleanup(self):
Chris Sosaf4d43ff2012-10-30 11:21:05 -0700893 client_at = autotest.Autotest(self)
Richard Barnette82c35912012-11-20 10:09:10 -0800894 self.run('rm -f %s' % constants.CLEANUP_LOGS_PAUSED_FILE)
Scott Zawalskiddbc31e2012-11-15 11:29:01 -0500895 try:
896 client_at.run_static_method('autotest_lib.client.cros.cros_ui',
897 '_clear_login_prompt_state')
898 self.run('restart ui')
899 client_at.run_static_method('autotest_lib.client.cros.cros_ui',
900 '_wait_for_login_prompt')
Alex Millerf4517962013-02-25 15:03:02 -0800901 except (error.AutotestRunError, error.AutoservRunError):
Scott Zawalskiddbc31e2012-11-15 11:29:01 -0500902 logging.warn('Unable to restart ui, rebooting device.')
903 # Since restarting the UI fails fall back to normal Autotest
904 # cleanup routines, i.e. reboot the machine.
905 super(SiteHost, self).cleanup()
Simran Basi5e6339a2013-03-21 11:34:32 -0700906 # Check if the rpm outlet was manipulated.
Simran Basid5e5e272012-09-24 15:23:59 -0700907 if self.has_power():
Simran Basi5e6339a2013-03-21 11:34:32 -0700908 self._cleanup_poweron()
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700909
910
Yu-Ju Honga2be94a2012-07-31 09:48:52 -0700911 def reboot(self, **dargs):
912 """
913 This function reboots the site host. The more generic
914 RemoteHost.reboot() performs sync and sleeps for 5
915 seconds. This is not necessary for Chrome OS devices as the
916 sync should be finished in a short time during the reboot
917 command.
918 """
Tom Wai-Hong Tamf5cd1d42012-08-13 12:04:08 +0800919 if 'reboot_cmd' not in dargs:
920 dargs['reboot_cmd'] = ('((reboot & sleep 10; reboot -f &)'
921 ' </dev/null >/dev/null 2>&1 &)')
Yu-Ju Honga2be94a2012-07-31 09:48:52 -0700922 # Enable fastsync to avoid running extra sync commands before reboot.
Tom Wai-Hong Tamf5cd1d42012-08-13 12:04:08 +0800923 if 'fastsync' not in dargs:
924 dargs['fastsync'] = True
Yu-Ju Honga2be94a2012-07-31 09:48:52 -0700925 super(SiteHost, self).reboot(**dargs)
926
927
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700928 def verify_software(self):
Richard Barnetteb2bc13c2013-01-08 17:32:51 -0800929 """Verify working software on a Chrome OS system.
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700930
Richard Barnetteb2bc13c2013-01-08 17:32:51 -0800931 Tests for the following conditions:
932 1. All conditions tested by the parent version of this
933 function.
934 2. Sufficient space in /mnt/stateful_partition.
Fang Deng6b05f5b2013-03-20 13:42:11 -0700935 3. Sufficient space in /mnt/stateful_partition/encrypted.
936 4. update_engine answers a simple status request over DBus.
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700937
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700938 """
939 super(SiteHost, self).verify_software()
940 self.check_diskspace(
941 '/mnt/stateful_partition',
942 global_config.global_config.get_config_value(
Fang Deng6b05f5b2013-03-20 13:42:11 -0700943 'SERVER', 'gb_diskspace_required', type=float,
944 default=20.0))
945 self.check_diskspace(
946 '/mnt/stateful_partition/encrypted',
947 global_config.global_config.get_config_value(
948 'SERVER', 'gb_encrypted_diskspace_required', type=float,
949 default=0.1))
Richard Barnetteb2bc13c2013-01-08 17:32:51 -0800950 self.run('update_engine_client --status')
Scott Zawalskifbca4a92013-03-04 15:56:42 -0500951 # Makes sure python is present, loads and can use built in functions.
952 # We have seen cases where importing cPickle fails with undefined
953 # symbols in cPickle.so.
954 self.run('python -c "import cPickle"')
J. Richard Barnette134ec2c2012-04-25 12:59:37 -0700955
956
Christopher Wileyd78249a2013-03-01 13:05:31 -0800957 def xmlrpc_connect(self, command, port, command_name=None,
958 ready_test_name=None, timeout_seconds=10):
J. Richard Barnette1d78b012012-05-15 13:56:30 -0700959 """Connect to an XMLRPC server on the host.
960
961 The `command` argument should be a simple shell command that
962 starts an XMLRPC server on the given `port`. The command
963 must not daemonize, and must terminate cleanly on SIGTERM.
964 The command is started in the background on the host, and a
965 local XMLRPC client for the server is created and returned
966 to the caller.
967
968 Note that the process of creating an XMLRPC client makes no
969 attempt to connect to the remote server; the caller is
970 responsible for determining whether the server is running
971 correctly, and is ready to serve requests.
972
Christopher Wileyd78249a2013-03-01 13:05:31 -0800973 Optionally, the caller can pass ready_test_name, a string
974 containing the name of a method to call on the proxy. This
975 method should take no parameters and return successfully only
976 when the server is ready to process client requests. When
977 ready_test_name is set, xmlrpc_connect will block until the
978 proxy is ready, and throw a TestError if the server isn't
979 ready by timeout_seconds.
980
J. Richard Barnette1d78b012012-05-15 13:56:30 -0700981 @param command Shell command to start the server.
982 @param port Port number on which the server is expected to
983 be serving.
J. Richard Barnette7214e0b2013-02-06 15:20:49 -0800984 @param command_name String to use as input to `pkill` to
985 terminate the XMLRPC server on the host.
Christopher Wileyd78249a2013-03-01 13:05:31 -0800986 @param ready_test_name String containing the name of a
987 method defined on the XMLRPC server.
988 @param timeout_seconds Number of seconds to wait
989 for the server to become 'ready.' Will throw a
990 TestFail error if server is not ready in time.
991
J. Richard Barnette1d78b012012-05-15 13:56:30 -0700992 """
993 self.xmlrpc_disconnect(port)
994
995 # Chrome OS on the target closes down most external ports
996 # for security. We could open the port, but doing that
997 # would conflict with security tests that check that only
998 # expected ports are open. So, to get to the port on the
999 # target we use an ssh tunnel.
1000 local_port = utils.get_unused_port()
1001 tunnel_options = '-n -N -q -L %d:localhost:%d' % (local_port, port)
1002 ssh_cmd = make_ssh_command(opts=tunnel_options)
1003 tunnel_cmd = '%s %s' % (ssh_cmd, self.hostname)
1004 logging.debug('Full tunnel command: %s', tunnel_cmd)
1005 tunnel_proc = subprocess.Popen(tunnel_cmd, shell=True, close_fds=True)
1006 logging.debug('Started XMLRPC tunnel, local = %d'
1007 ' remote = %d, pid = %d',
1008 local_port, port, tunnel_proc.pid)
1009
1010 # Start the server on the host. Redirection in the command
1011 # below is necessary, because 'ssh' won't terminate until
1012 # background child processes close stdin, stdout, and
1013 # stderr.
1014 remote_cmd = '( %s ) </dev/null >/dev/null 2>&1 & echo $!' % command
1015 remote_pid = self.run(remote_cmd).stdout.rstrip('\n')
1016 logging.debug('Started XMLRPC server on host %s, pid = %s',
1017 self.hostname, remote_pid)
1018
J. Richard Barnette7214e0b2013-02-06 15:20:49 -08001019 self._xmlrpc_proxy_map[port] = (command_name, tunnel_proc)
J. Richard Barnette1d78b012012-05-15 13:56:30 -07001020 rpc_url = 'http://localhost:%d' % local_port
Christopher Wileyd78249a2013-03-01 13:05:31 -08001021 proxy = xmlrpclib.ServerProxy(rpc_url, allow_none=True)
1022 if ready_test_name is not None:
J. Richard Barnette13eb7c02013-03-07 12:06:29 -08001023 # retry.retry logs each attempt; calculate delay_sec to
1024 # keep log spam to a dull roar.
Christopher Wiley0ed712b2013-04-09 15:25:12 -07001025 @retry.retry((socket.error,
1026 xmlrpclib.ProtocolError,
1027 httplib.BadStatusLine),
Christopher Wileyd78249a2013-03-01 13:05:31 -08001028 timeout_min=timeout_seconds/60.0,
J. Richard Barnette13eb7c02013-03-07 12:06:29 -08001029 delay_sec=min(max(timeout_seconds/20.0, 0.1), 1))
Christopher Wileyd78249a2013-03-01 13:05:31 -08001030 def ready_test():
1031 """ Call proxy.ready_test_name(). """
1032 getattr(proxy, ready_test_name)()
1033 successful = False
1034 try:
1035 logging.info('Waiting %d seconds for XMLRPC server '
1036 'to start.', timeout_seconds)
1037 ready_test()
1038 successful = True
1039 except retry.TimeoutException:
1040 raise error.TestError('Unable to start XMLRPC server after '
1041 '%d seconds.' % timeout_seconds)
1042 finally:
1043 if not successful:
1044 logging.error('Failed to start XMLRPC server.')
1045 self.xmlrpc_disconnect(port)
1046 logging.info('XMLRPC server started successfully.')
1047 return proxy
J. Richard Barnette1d78b012012-05-15 13:56:30 -07001048
1049 def xmlrpc_disconnect(self, port):
1050 """Disconnect from an XMLRPC server on the host.
1051
1052 Terminates the remote XMLRPC server previously started for
1053 the given `port`. Also closes the local ssh tunnel created
1054 for the connection to the host. This function does not
1055 directly alter the state of a previously returned XMLRPC
1056 client object; however disconnection will cause all
1057 subsequent calls to methods on the object to fail.
1058
1059 This function does nothing if requested to disconnect a port
1060 that was not previously connected via `self.xmlrpc_connect()`
1061
1062 @param port Port number passed to a previous call to
1063 `xmlrpc_connect()`
1064 """
1065 if port not in self._xmlrpc_proxy_map:
1066 return
1067 entry = self._xmlrpc_proxy_map[port]
1068 remote_name = entry[0]
1069 tunnel_proc = entry[1]
1070 if remote_name:
1071 # We use 'pkill' to find our target process rather than
1072 # a PID, because the host may have rebooted since
1073 # connecting, and we don't want to kill an innocent
1074 # process with the same PID.
1075 #
1076 # 'pkill' helpfully exits with status 1 if no target
1077 # process is found, for which run() will throw an
Simran Basid5e5e272012-09-24 15:23:59 -07001078 # exception. We don't want that, so we the ignore
J. Richard Barnette1d78b012012-05-15 13:56:30 -07001079 # status.
1080 self.run("pkill -f '%s'" % remote_name, ignore_status=True)
1081
1082 if tunnel_proc.poll() is None:
1083 tunnel_proc.terminate()
1084 logging.debug('Terminated tunnel, pid %d', tunnel_proc.pid)
1085 else:
1086 logging.debug('Tunnel pid %d terminated early, status %d',
1087 tunnel_proc.pid, tunnel_proc.returncode)
1088 del self._xmlrpc_proxy_map[port]
1089
1090
1091 def xmlrpc_disconnect_all(self):
1092 """Disconnect all known XMLRPC proxy ports."""
1093 for port in self._xmlrpc_proxy_map.keys():
1094 self.xmlrpc_disconnect(port)
1095
1096
J. Richard Barnetteb6de7e32013-02-14 13:28:04 -08001097 def _ping_check_status(self, status):
1098 """Ping the host once, and return whether it has a given status.
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001099
J. Richard Barnetteb6de7e32013-02-14 13:28:04 -08001100 @param status Check the ping status against this value.
1101 @return True iff `status` and the result of ping are the same
1102 (i.e. both True or both False).
1103
1104 """
1105 ping_val = utils.ping(self.hostname, tries=1, deadline=1)
1106 return not (status ^ (ping_val == 0))
1107
1108 def _ping_wait_for_status(self, status, timeout):
1109 """Wait for the host to have a given status (UP or DOWN).
1110
1111 Status is checked by polling. Polling will not last longer
1112 than the number of seconds in `timeout`. The polling
1113 interval will be long enough that only approximately
1114 _PING_WAIT_COUNT polling cycles will be executed, subject
1115 to a maximum interval of about one minute.
1116
1117 @param status Waiting will stop immediately if `ping` of the
1118 host returns this status.
1119 @param timeout Poll for at most this many seconds.
1120 @return True iff the host status from `ping` matched the
1121 requested status at the time of return.
1122
1123 """
1124 # _ping_check_status() takes about 1 second, hence the
1125 # "- 1" in the formula below.
1126 poll_interval = min(int(timeout / self._PING_WAIT_COUNT), 60) - 1
1127 end_time = time.time() + timeout
1128 while time.time() <= end_time:
1129 if self._ping_check_status(status):
1130 return True
1131 if poll_interval > 0:
1132 time.sleep(poll_interval)
1133
1134 # The last thing we did was sleep(poll_interval), so it may
1135 # have been too long since the last `ping`. Check one more
1136 # time, just to be sure.
1137 return self._ping_check_status(status)
1138
1139 def ping_wait_up(self, timeout):
1140 """Wait for the host to respond to `ping`.
1141
1142 N.B. This method is not a reliable substitute for
1143 `wait_up()`, because a host that responds to ping will not
1144 necessarily respond to ssh. This method should only be used
1145 if the target DUT can be considered functional even if it
1146 can't be reached via ssh.
1147
1148 @param timeout Minimum time to allow before declaring the
1149 host to be non-responsive.
1150 @return True iff the host answered to ping before the timeout.
1151
1152 """
1153 return self._ping_wait_for_status(self._PING_STATUS_UP, timeout)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001154
Andrew Bresticker678c0c72013-01-22 10:44:09 -08001155 def ping_wait_down(self, timeout):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001156 """Wait until the host no longer responds to `ping`.
1157
J. Richard Barnetteb6de7e32013-02-14 13:28:04 -08001158 This function can be used as a slightly faster version of
1159 `wait_down()`, by avoiding potentially long ssh timeouts.
1160
1161 @param timeout Minimum time to allow for the host to become
1162 non-responsive.
1163 @return True iff the host quit answering ping before the
1164 timeout.
1165
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001166 """
J. Richard Barnetteb6de7e32013-02-14 13:28:04 -08001167 return self._ping_wait_for_status(self._PING_STATUS_DOWN, timeout)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001168
1169 def test_wait_for_sleep(self):
1170 """Wait for the client to enter low-power sleep mode.
1171
1172 The test for "is asleep" can't distinguish a system that is
1173 powered off; to confirm that the unit was asleep, it is
1174 necessary to force resume, and then call
1175 `test_wait_for_resume()`.
1176
1177 This function is expected to be called from a test as part
1178 of a sequence like the following:
1179
1180 ~~~~~~~~
1181 boot_id = host.get_boot_id()
1182 # trigger sleep on the host
1183 host.test_wait_for_sleep()
1184 # trigger resume on the host
1185 host.test_wait_for_resume(boot_id)
1186 ~~~~~~~~
1187
1188 @exception TestFail The host did not go to sleep within
1189 the allowed time.
1190 """
Andrew Bresticker678c0c72013-01-22 10:44:09 -08001191 if not self.ping_wait_down(timeout=self.SLEEP_TIMEOUT):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001192 raise error.TestFail(
1193 'client failed to sleep after %d seconds' %
J. Richard Barnetteeb69d722012-06-18 17:29:44 -07001194 self.SLEEP_TIMEOUT)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001195
1196
1197 def test_wait_for_resume(self, old_boot_id):
1198 """Wait for the client to resume from low-power sleep mode.
1199
1200 The `old_boot_id` parameter should be the value from
1201 `get_boot_id()` obtained prior to entering sleep mode. A
1202 `TestFail` exception is raised if the boot id changes.
1203
1204 See @ref test_wait_for_sleep for more on this function's
1205 usage.
1206
J. Richard Barnette7214e0b2013-02-06 15:20:49 -08001207 @param old_boot_id A boot id value obtained before the
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001208 target host went to sleep.
1209
1210 @exception TestFail The host did not respond within the
1211 allowed time.
1212 @exception TestFail The host responded, but the boot id test
1213 indicated a reboot rather than a sleep
1214 cycle.
1215 """
J. Richard Barnetteeb69d722012-06-18 17:29:44 -07001216 if not self.wait_up(timeout=self.RESUME_TIMEOUT):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001217 raise error.TestFail(
1218 'client failed to resume from sleep after %d seconds' %
J. Richard Barnetteeb69d722012-06-18 17:29:44 -07001219 self.RESUME_TIMEOUT)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001220 else:
1221 new_boot_id = self.get_boot_id()
1222 if new_boot_id != old_boot_id:
1223 raise error.TestFail(
1224 'client rebooted, but sleep was expected'
1225 ' (old boot %s, new boot %s)'
1226 % (old_boot_id, new_boot_id))
1227
1228
1229 def test_wait_for_shutdown(self):
1230 """Wait for the client to shut down.
1231
1232 The test for "has shut down" can't distinguish a system that
1233 is merely asleep; to confirm that the unit was down, it is
1234 necessary to force boot, and then call test_wait_for_boot().
1235
1236 This function is expected to be called from a test as part
1237 of a sequence like the following:
1238
1239 ~~~~~~~~
1240 boot_id = host.get_boot_id()
1241 # trigger shutdown on the host
1242 host.test_wait_for_shutdown()
1243 # trigger boot on the host
1244 host.test_wait_for_boot(boot_id)
1245 ~~~~~~~~
1246
1247 @exception TestFail The host did not shut down within the
1248 allowed time.
1249 """
Andrew Bresticker678c0c72013-01-22 10:44:09 -08001250 if not self.ping_wait_down(timeout=self.SHUTDOWN_TIMEOUT):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001251 raise error.TestFail(
1252 'client failed to shut down after %d seconds' %
J. Richard Barnetteeb69d722012-06-18 17:29:44 -07001253 self.SHUTDOWN_TIMEOUT)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001254
1255
1256 def test_wait_for_boot(self, old_boot_id=None):
1257 """Wait for the client to boot from cold power.
1258
1259 The `old_boot_id` parameter should be the value from
1260 `get_boot_id()` obtained prior to shutting down. A
1261 `TestFail` exception is raised if the boot id does not
1262 change. The boot id test is omitted if `old_boot_id` is not
1263 specified.
1264
1265 See @ref test_wait_for_shutdown for more on this function's
1266 usage.
1267
J. Richard Barnette7214e0b2013-02-06 15:20:49 -08001268 @param old_boot_id A boot id value obtained before the
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001269 shut down.
1270
1271 @exception TestFail The host did not respond within the
1272 allowed time.
1273 @exception TestFail The host responded, but the boot id test
1274 indicated that there was no reboot.
1275 """
J. Richard Barnetteeb69d722012-06-18 17:29:44 -07001276 if not self.wait_up(timeout=self.REBOOT_TIMEOUT):
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001277 raise error.TestFail(
1278 'client failed to reboot after %d seconds' %
J. Richard Barnetteeb69d722012-06-18 17:29:44 -07001279 self.REBOOT_TIMEOUT)
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07001280 elif old_boot_id:
1281 if self.get_boot_id() == old_boot_id:
1282 raise error.TestFail(
1283 'client is back up, but did not reboot'
1284 ' (boot %s)' % old_boot_id)
Simran Basid5e5e272012-09-24 15:23:59 -07001285
1286
1287 @staticmethod
1288 def check_for_rpm_support(hostname):
1289 """For a given hostname, return whether or not it is powered by an RPM.
1290
1291 @return None if this host does not follows the defined naming format
1292 for RPM powered DUT's in the lab. If it does follow the format,
1293 it returns a regular expression MatchObject instead.
1294 """
Richard Barnette82c35912012-11-20 10:09:10 -08001295 return re.match(SiteHost._RPM_HOSTNAME_REGEX, hostname)
Simran Basid5e5e272012-09-24 15:23:59 -07001296
1297
1298 def has_power(self):
1299 """For this host, return whether or not it is powered by an RPM.
1300
1301 @return True if this host is in the CROS lab and follows the defined
1302 naming format.
1303 """
1304 return SiteHost.check_for_rpm_support(self.hostname)
1305
1306
Ismail Noorbasha07fdb612013-02-14 14:13:31 -08001307 def _set_power(self, state, power_method):
1308 """Sets the power to the host via RPM, Servo or manual.
1309
1310 @param state Specifies which power state to set to DUT
1311 @param power_method Specifies which method of power control to
1312 use. By default "RPM" will be used. Valid values
1313 are the strings "RPM", "manual", "servoj10".
1314
1315 """
1316 ACCEPTABLE_STATES = ['ON', 'OFF']
1317
1318 if state.upper() not in ACCEPTABLE_STATES:
1319 raise error.TestError('State must be one of: %s.'
1320 % (ACCEPTABLE_STATES,))
1321
1322 if power_method == self.POWER_CONTROL_SERVO:
1323 logging.info('Setting servo port J10 to %s', state)
1324 self.servo.set('prtctl3_pwren', state.lower())
1325 time.sleep(self._USB_POWER_TIMEOUT)
1326 elif power_method == self.POWER_CONTROL_MANUAL:
1327 logging.info('You have %d seconds to set the AC power to %s.',
1328 self._POWER_CYCLE_TIMEOUT, state)
1329 time.sleep(self._POWER_CYCLE_TIMEOUT)
1330 else:
1331 if not self.has_power():
1332 raise error.TestFail('DUT does not have RPM connected.')
Simran Basi5e6339a2013-03-21 11:34:32 -07001333 afe = frontend_wrappers.RetryingAFE(timeout_min=5, delay_sec=10)
1334 afe.set_host_attribute(self._RPM_OUTLET_CHANGED, True,
1335 hostname=self.hostname)
Ismail Noorbasha07fdb612013-02-14 14:13:31 -08001336 rpm_client.set_power(self.hostname, state.upper())
Simran Basid5e5e272012-09-24 15:23:59 -07001337
1338
Ismail Noorbasha07fdb612013-02-14 14:13:31 -08001339 def power_off(self, power_method=POWER_CONTROL_RPM):
1340 """Turn off power to this host via RPM, Servo or manual.
1341
1342 @param power_method Specifies which method of power control to
1343 use. By default "RPM" will be used. Valid values
1344 are the strings "RPM", "manual", "servoj10".
1345
1346 """
1347 self._set_power('OFF', power_method)
Simran Basid5e5e272012-09-24 15:23:59 -07001348
1349
Ismail Noorbasha07fdb612013-02-14 14:13:31 -08001350 def power_on(self, power_method=POWER_CONTROL_RPM):
1351 """Turn on power to this host via RPM, Servo or manual.
1352
1353 @param power_method Specifies which method of power control to
1354 use. By default "RPM" will be used. Valid values
1355 are the strings "RPM", "manual", "servoj10".
1356
1357 """
1358 self._set_power('ON', power_method)
1359
1360
1361 def power_cycle(self, power_method=POWER_CONTROL_RPM):
1362 """Cycle power to this host by turning it OFF, then ON.
1363
1364 @param power_method Specifies which method of power control to
1365 use. By default "RPM" will be used. Valid values
1366 are the strings "RPM", "manual", "servoj10".
1367
1368 """
1369 if power_method in (self.POWER_CONTROL_SERVO,
1370 self.POWER_CONTROL_MANUAL):
1371 self.power_off(power_method=power_method)
1372 time.sleep(self._POWER_CYCLE_TIMEOUT)
1373 self.power_on(power_method=power_method)
1374 else:
1375 rpm_client.set_power(self.hostname, 'CYCLE')
Simran Basic6f1f7a2012-10-16 10:47:46 -07001376
1377
1378 def get_platform(self):
1379 """Determine the correct platform label for this host.
1380
1381 @returns a string representing this host's platform.
1382 """
1383 crossystem = utils.Crossystem(self)
1384 crossystem.init()
1385 # Extract fwid value and use the leading part as the platform id.
1386 # fwid generally follow the format of {platform}.{firmware version}
1387 # Example: Alex.X.YYY.Z or Google_Alex.X.YYY.Z
1388 platform = crossystem.fwid().split('.')[0].lower()
1389 # Newer platforms start with 'Google_' while the older ones do not.
1390 return platform.replace('google_', '')
1391
1392
Aviv Keshet74c89a92013-02-04 15:18:30 -08001393 @label_decorator()
Simran Basic6f1f7a2012-10-16 10:47:46 -07001394 def get_board(self):
1395 """Determine the correct board label for this host.
1396
1397 @returns a string representing this host's board.
1398 """
1399 release_info = utils.parse_cmd_output('cat /etc/lsb-release',
1400 run_method=self.run)
1401 board = release_info['CHROMEOS_RELEASE_BOARD']
1402 # Devices in the lab generally have the correct board name but our own
1403 # development devices have {board_name}-signed-{key_type}. The board
1404 # name may also begin with 'x86-' which we need to keep.
Simran Basi833814b2013-01-29 13:13:43 -08001405 board_format_string = ds_constants.BOARD_PREFIX + '%s'
Simran Basic6f1f7a2012-10-16 10:47:46 -07001406 if 'x86' not in board:
Simran Basi833814b2013-01-29 13:13:43 -08001407 return board_format_string % board.split('-')[0]
1408 return board_format_string % '-'.join(board.split('-')[0:2])
Simran Basic6f1f7a2012-10-16 10:47:46 -07001409
1410
Aviv Keshet74c89a92013-02-04 15:18:30 -08001411 @label_decorator('lightsensor')
Simran Basic6f1f7a2012-10-16 10:47:46 -07001412 def has_lightsensor(self):
1413 """Determine the correct board label for this host.
1414
1415 @returns the string 'lightsensor' if this host has a lightsensor or
1416 None if it does not.
1417 """
1418 search_cmd = "find -L %s -maxdepth 4 | egrep '%s'" % (
Richard Barnette82c35912012-11-20 10:09:10 -08001419 self._LIGHTSENSOR_SEARCH_DIR, '|'.join(self._LIGHTSENSOR_FILES))
Simran Basic6f1f7a2012-10-16 10:47:46 -07001420 try:
1421 # Run the search cmd following the symlinks. Stderr_tee is set to
1422 # None as there can be a symlink loop, but the command will still
1423 # execute correctly with a few messages printed to stderr.
1424 self.run(search_cmd, stdout_tee=None, stderr_tee=None)
1425 return 'lightsensor'
1426 except error.AutoservRunError:
1427 # egrep exited with a return code of 1 meaning none of the possible
1428 # lightsensor files existed.
1429 return None
1430
1431
Aviv Keshet74c89a92013-02-04 15:18:30 -08001432 @label_decorator('bluetooth')
Simran Basic6f1f7a2012-10-16 10:47:46 -07001433 def has_bluetooth(self):
1434 """Determine the correct board label for this host.
1435
1436 @returns the string 'bluetooth' if this host has bluetooth or
1437 None if it does not.
1438 """
1439 try:
1440 self.run('test -d /sys/class/bluetooth/hci0')
1441 # test exited with a return code of 0.
1442 return 'bluetooth'
1443 except error.AutoservRunError:
1444 # test exited with a return code 1 meaning the directory did not
1445 # exist.
1446 return None
1447
1448
1449 def get_labels(self):
1450 """Return a list of labels for this given host.
1451
1452 This is the main way to retrieve all the automatic labels for a host
1453 as it will run through all the currently implemented label functions.
1454 """
1455 labels = []
Richard Barnette82c35912012-11-20 10:09:10 -08001456 for label_function in self._LABEL_FUNCTIONS:
Simran Basic6f1f7a2012-10-16 10:47:46 -07001457 label = label_function(self)
1458 if label:
1459 labels.append(label)
1460 return labels