blob: b01dcdcb02f1fefdcb8b2560a33e05b94e4c21b5 [file] [log] [blame]
Fang Deng5d518f42013-08-02 14:04:32 -07001# Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4#
5# Expects to be run in an environment with sudo and no interactive password
6# prompt, such as within the Chromium OS development chroot.
7
8
9"""This file provides core logic for servo verify/repair process."""
10
11
12import httplib
13import logging
14import socket
Fang Deng5d518f42013-08-02 14:04:32 -070015import xmlrpclib
16
17from autotest_lib.client.bin import utils
Kevin Cheng5f2ba6c2016-09-28 10:20:05 -070018from autotest_lib.client.common_lib import control_data
Fang Deng5d518f42013-08-02 14:04:32 -070019from autotest_lib.client.common_lib import error
beeps5e8c45a2013-12-17 22:05:11 -080020from autotest_lib.client.common_lib import global_config
Kevin Cheng5f2ba6c2016-09-28 10:20:05 -070021from autotest_lib.client.common_lib import host_states
Richard Barnette9a26ad62016-06-10 12:03:08 -070022from autotest_lib.client.common_lib import hosts
Dan Shi0942b1d2015-03-31 11:07:00 -070023from autotest_lib.client.common_lib import lsbrelease_utils
Kevin Cheng5f2ba6c2016-09-28 10:20:05 -070024from autotest_lib.client.common_lib import priorities
beeps5e8c45a2013-12-17 22:05:11 -080025from autotest_lib.client.common_lib.cros import autoupdater
26from autotest_lib.client.common_lib.cros import dev_server
Fang Deng5d518f42013-08-02 14:04:32 -070027from autotest_lib.client.common_lib.cros import retry
Gabe Black1e1c41b2015-02-04 23:55:15 -080028from autotest_lib.client.common_lib.cros.graphite import autotest_stats
Christopher Wileycef1f902014-06-19 11:11:23 -070029from autotest_lib.client.common_lib.cros.network import ping_runner
Hsinyu Chaoe0b08e62015-08-11 10:50:37 +000030from autotest_lib.client.cros import constants as client_constants
Richard Barnettee519dcd2016-08-15 17:37:17 -070031from autotest_lib.server import afe_utils
beeps5e8c45a2013-12-17 22:05:11 -080032from autotest_lib.server import site_utils as server_site_utils
Cheng-Yi Chiang22612862015-08-20 20:39:57 +080033from autotest_lib.server.cros import dnsname_mangler
Simran Basi0739d682015-02-25 16:22:56 -080034from autotest_lib.server.cros.dynamic_suite import frontend_wrappers
Kevin Cheng5f2ba6c2016-09-28 10:20:05 -070035from autotest_lib.server.cros.dynamic_suite import control_file_getter
Richard Barnette9a26ad62016-06-10 12:03:08 -070036from autotest_lib.server.cros.servo import servo
37from autotest_lib.server.hosts import servo_repair
Fang Deng5d518f42013-08-02 14:04:32 -070038from autotest_lib.server.hosts import ssh_host
Fang Dengd4fe7392013-09-20 12:18:21 -070039from autotest_lib.site_utils.rpm_control_system import rpm_client
Fang Deng5d518f42013-08-02 14:04:32 -070040
41
Simran Basi0739d682015-02-25 16:22:56 -080042# Names of the host attributes in the database that represent the values for
43# the servo_host and servo_port for a servo connected to the DUT.
44SERVO_HOST_ATTR = 'servo_host'
45SERVO_PORT_ATTR = 'servo_port'
Richard Barnettee519dcd2016-08-15 17:37:17 -070046SERVO_BOARD_ATTR = 'servo_board'
Kevin Cheng643ce8a2016-09-15 15:42:12 -070047SERVO_SERIAL_ATTR = 'servo_serial'
Simran Basi0739d682015-02-25 16:22:56 -080048
Dan Shi3b2adf62015-09-02 17:46:54 -070049_CONFIG = global_config.global_config
xixuan6cf6d2f2016-01-29 15:29:00 -080050ENABLE_SSH_TUNNEL_FOR_SERVO = _CONFIG.get_config_value(
51 'CROS', 'enable_ssh_tunnel_for_servo', type=bool, default=False)
Simran Basi0739d682015-02-25 16:22:56 -080052
Kevin Cheng5f2ba6c2016-09-28 10:20:05 -070053AUTOTEST_BASE = _CONFIG.get_config_value(
54 'SCHEDULER', 'drone_installation_directory',
55 default='/usr/local/autotest')
56
57_SERVO_HOST_REBOOT_TEST_NAME = 'servohost_Reboot'
Fang Deng5d518f42013-08-02 14:04:32 -070058
Fang Deng5d518f42013-08-02 14:04:32 -070059class ServoHost(ssh_host.SSHHost):
60 """Host class for a host that controls a servo, e.g. beaglebone."""
61
Richard Barnette9a26ad62016-06-10 12:03:08 -070062 DEFAULT_PORT = 9999
63
Dan Shie5b3c512014-08-21 12:12:09 -070064 # Timeout for initializing servo signals.
65 INITIALIZE_SERVO_TIMEOUT_SECS = 30
Richard Barnette9a26ad62016-06-10 12:03:08 -070066
xixuan6cf6d2f2016-01-29 15:29:00 -080067 # Ready test function
68 SERVO_READY_METHOD = 'get_version'
Fang Deng5d518f42013-08-02 14:04:32 -070069
Gabe Black1e1c41b2015-02-04 23:55:15 -080070 _timer = autotest_stats.Timer('servo_host')
Fang Dengd4fe7392013-09-20 12:18:21 -070071
Kevin Cheng5f2ba6c2016-09-28 10:20:05 -070072 REBOOT_CMD = 'sleep 1; reboot & sleep 10; reboot -f'
73
Fang Deng5d518f42013-08-02 14:04:32 -070074
Richard Barnette17bfc6c2016-08-04 18:41:43 -070075 def _initialize(self, servo_host='localhost',
Richard Barnettee519dcd2016-08-15 17:37:17 -070076 servo_port=DEFAULT_PORT, servo_board=None,
Kevin Cheng643ce8a2016-09-15 15:42:12 -070077 servo_serial=None, is_in_lab=None, *args, **dargs):
Fang Deng5d518f42013-08-02 14:04:32 -070078 """Initialize a ServoHost instance.
79
80 A ServoHost instance represents a host that controls a servo.
81
82 @param servo_host: Name of the host where the servod process
83 is running.
84 @param servo_port: Port the servod process is listening on.
Kevin Cheng5f2ba6c2016-09-28 10:20:05 -070085 @param servo_board: Board that the servo is connected to.
Dan Shi4d478522014-02-14 13:46:32 -080086 @param is_in_lab: True if the servo host is in Cros Lab. Default is set
87 to None, for which utils.host_is_in_lab_zone will be
88 called to check if the servo host is in Cros lab.
Fang Deng5d518f42013-08-02 14:04:32 -070089
90 """
91 super(ServoHost, self)._initialize(hostname=servo_host,
92 *args, **dargs)
Richard Barnettee519dcd2016-08-15 17:37:17 -070093 self.servo_port = servo_port
94 self.servo_board = servo_board
Kevin Cheng643ce8a2016-09-15 15:42:12 -070095 self.servo_serial = servo_serial
Richard Barnettee519dcd2016-08-15 17:37:17 -070096 self._servo = None
Richard Barnette9a26ad62016-06-10 12:03:08 -070097 self._repair_strategy = (
98 servo_repair.create_servo_repair_strategy())
Richard Barnettee519dcd2016-08-15 17:37:17 -070099 self._is_localhost = (self.hostname == 'localhost')
100 if self._is_localhost:
101 self._is_in_lab = False
102 elif is_in_lab is None:
Dan Shi4d478522014-02-14 13:46:32 -0800103 self._is_in_lab = utils.host_is_in_lab_zone(self.hostname)
104 else:
105 self._is_in_lab = is_in_lab
xixuan6cf6d2f2016-01-29 15:29:00 -0800106
Richard Barnettee519dcd2016-08-15 17:37:17 -0700107 # Commands on the servo host must be run by the superuser.
108 # Our account on a remote host is root, but if our target is
109 # localhost then we might be running unprivileged. If so,
110 # `sudo` will have to be added to the commands.
Fang Deng5d518f42013-08-02 14:04:32 -0700111 if self._is_localhost:
112 self._sudo_required = utils.system_output('id -u') != '0'
113 else:
114 self._sudo_required = False
Richard Barnettee519dcd2016-08-15 17:37:17 -0700115
Richard Barnette9a26ad62016-06-10 12:03:08 -0700116
117 def connect_servo(self):
Kevin Cheng5f2ba6c2016-09-28 10:20:05 -0700118 """Establish a connection to the servod server on this host.
Richard Barnette9a26ad62016-06-10 12:03:08 -0700119
120 Initializes `self._servo` and then verifies that all network
121 connections are working. This will create an ssh tunnel if
122 it's required.
123
124 As a side effect of testing the connection, all signals on the
125 target servo are reset to default values, and the USB stick is
126 set to the neutral (off) position.
127 """
Kevin Cheng643ce8a2016-09-15 15:42:12 -0700128 servo_obj = servo.Servo(servo_host=self, servo_serial=self.servo_serial)
Richard Barnette9a26ad62016-06-10 12:03:08 -0700129 timeout, _ = retry.timeout(
130 servo_obj.initialize_dut,
131 timeout_sec=self.INITIALIZE_SERVO_TIMEOUT_SECS)
132 if timeout:
133 raise hosts.AutoservVerifyError(
134 'Servo initialize timed out.')
135 self._servo = servo_obj
136
137
138 def disconnect_servo(self):
Kevin Cheng5f2ba6c2016-09-28 10:20:05 -0700139 """Disconnect our servo if it exists.
Richard Barnette9a26ad62016-06-10 12:03:08 -0700140
141 If we've previously successfully connected to our servo,
142 disconnect any established ssh tunnel, and set `self._servo`
143 back to `None`.
144 """
145 if self._servo:
146 # N.B. This call is safe even without a tunnel:
147 # rpc_server_tracker.disconnect() silently ignores
148 # unknown ports.
149 self.rpc_server_tracker.disconnect(self.servo_port)
150 self._servo = None
Fang Deng5d518f42013-08-02 14:04:32 -0700151
152
153 def is_in_lab(self):
154 """Check whether the servo host is a lab device.
155
156 @returns: True if the servo host is in Cros Lab, otherwise False.
157
158 """
159 return self._is_in_lab
160
161
162 def is_localhost(self):
163 """Checks whether the servo host points to localhost.
164
165 @returns: True if it points to localhost, otherwise False.
166
167 """
168 return self._is_localhost
169
170
171 def get_servod_server_proxy(self):
Kevin Cheng5f2ba6c2016-09-28 10:20:05 -0700172 """Return a proxy that can be used to communicate with servod server.
Fang Deng5d518f42013-08-02 14:04:32 -0700173
174 @returns: An xmlrpclib.ServerProxy that is connected to the servod
175 server on the host.
Fang Deng5d518f42013-08-02 14:04:32 -0700176 """
Richard Barnette9a26ad62016-06-10 12:03:08 -0700177 if ENABLE_SSH_TUNNEL_FOR_SERVO and not self.is_localhost():
178 return self.rpc_server_tracker.xmlrpc_connect(
179 None, self.servo_port,
180 ready_test_name=self.SERVO_READY_METHOD,
181 timeout_seconds=60)
182 else:
183 remote = 'http://%s:%s' % (self.hostname, self.servo_port)
184 return xmlrpclib.ServerProxy(remote)
Fang Deng5d518f42013-08-02 14:04:32 -0700185
186
Richard Barnette9a26ad62016-06-10 12:03:08 -0700187 def is_cros_host(self):
beeps5e8c45a2013-12-17 22:05:11 -0800188 """Check if a servo host is running chromeos.
189
190 @return: True if the servo host is running chromeos.
191 False if it isn't, or we don't have enough information.
192 """
193 try:
194 result = self.run('grep -q CHROMEOS /etc/lsb-release',
195 ignore_status=True, timeout=10)
196 except (error.AutoservRunError, error.AutoservSSHTimeout):
197 return False
198 return result.exit_status == 0
199
200
Fang Deng5d518f42013-08-02 14:04:32 -0700201 def make_ssh_command(self, user='root', port=22, opts='', hosts_file=None,
202 connect_timeout=None, alive_interval=None):
203 """Override default make_ssh_command to use tuned options.
204
205 Tuning changes:
206 - ConnectTimeout=30; maximum of 30 seconds allowed for an SSH
207 connection failure. Consistency with remote_access.py.
208
209 - ServerAliveInterval=180; which causes SSH to ping connection every
210 180 seconds. In conjunction with ServerAliveCountMax ensures
211 that if the connection dies, Autotest will bail out quickly.
212
213 - ServerAliveCountMax=3; consistency with remote_access.py.
214
215 - ConnectAttempts=4; reduce flakiness in connection errors;
216 consistency with remote_access.py.
217
218 - UserKnownHostsFile=/dev/null; we don't care about the keys.
219
220 - SSH protocol forced to 2; needed for ServerAliveInterval.
221
222 @param user User name to use for the ssh connection.
223 @param port Port on the target host to use for ssh connection.
224 @param opts Additional options to the ssh command.
225 @param hosts_file Ignored.
226 @param connect_timeout Ignored.
227 @param alive_interval Ignored.
228
229 @returns: An ssh command with the requested settings.
230
231 """
232 base_command = ('/usr/bin/ssh -a -x %s -o StrictHostKeyChecking=no'
233 ' -o UserKnownHostsFile=/dev/null -o BatchMode=yes'
234 ' -o ConnectTimeout=30 -o ServerAliveInterval=180'
235 ' -o ServerAliveCountMax=3 -o ConnectionAttempts=4'
236 ' -o Protocol=2 -l %s -p %d')
237 return base_command % (opts, user, port)
238
239
240 def _make_scp_cmd(self, sources, dest):
241 """Format scp command.
242
243 Given a list of source paths and a destination path, produces the
244 appropriate scp command for encoding it. Remote paths must be
245 pre-encoded. Overrides _make_scp_cmd in AbstractSSHHost
246 to allow additional ssh options.
247
248 @param sources: A list of source paths to copy from.
249 @param dest: Destination path to copy to.
250
251 @returns: An scp command that copies |sources| on local machine to
252 |dest| on the remote servo host.
253
254 """
255 command = ('scp -rq %s -o BatchMode=yes -o StrictHostKeyChecking=no '
256 '-o UserKnownHostsFile=/dev/null -P %d %s "%s"')
257 return command % (self.master_ssh_option,
258 self.port, ' '.join(sources), dest)
259
260
261 def run(self, command, timeout=3600, ignore_status=False,
262 stdout_tee=utils.TEE_TO_LOGS, stderr_tee=utils.TEE_TO_LOGS,
263 connect_timeout=30, options='', stdin=None, verbose=True, args=()):
264 """Run a command on the servo host.
265
266 Extends method `run` in SSHHost. If the servo host is a remote device,
267 it will call `run` in SSHost without changing anything.
268 If the servo host is 'localhost', it will call utils.system_output.
269
270 @param command: The command line string.
271 @param timeout: Time limit in seconds before attempting to
272 kill the running process. The run() function
273 will take a few seconds longer than 'timeout'
274 to complete if it has to kill the process.
275 @param ignore_status: Do not raise an exception, no matter
276 what the exit code of the command is.
277 @param stdout_tee/stderr_tee: Where to tee the stdout/stderr.
278 @param connect_timeout: SSH connection timeout (in seconds)
279 Ignored if host is 'localhost'.
280 @param options: String with additional ssh command options
281 Ignored if host is 'localhost'.
282 @param stdin: Stdin to pass (a string) to the executed command.
283 @param verbose: Log the commands.
284 @param args: Sequence of strings to pass as arguments to command by
285 quoting them in " and escaping their contents if necessary.
286
287 @returns: A utils.CmdResult object.
288
289 @raises AutoservRunError if the command failed.
290 @raises AutoservSSHTimeout SSH connection has timed out. Only applies
291 when servo host is not 'localhost'.
292
293 """
294 run_args = {'command': command, 'timeout': timeout,
295 'ignore_status': ignore_status, 'stdout_tee': stdout_tee,
296 'stderr_tee': stderr_tee, 'stdin': stdin,
297 'verbose': verbose, 'args': args}
298 if self.is_localhost():
299 if self._sudo_required:
300 run_args['command'] = 'sudo -n %s' % command
301 try:
302 return utils.run(**run_args)
303 except error.CmdError as e:
304 logging.error(e)
305 raise error.AutoservRunError('command execution error',
306 e.result_obj)
307 else:
308 run_args['connect_timeout'] = connect_timeout
309 run_args['options'] = options
310 return super(ServoHost, self).run(**run_args)
311
312
Richard Barnette9a26ad62016-06-10 12:03:08 -0700313 def _get_release_version(self):
Dan Shi0942b1d2015-03-31 11:07:00 -0700314 """Get the value of attribute CHROMEOS_RELEASE_VERSION from lsb-release.
315
316 @returns The version string in lsb-release, under attribute
317 CHROMEOS_RELEASE_VERSION.
318 """
319 lsb_release_content = self.run(
320 'cat "%s"' % client_constants.LSB_RELEASE).stdout.strip()
321 return lsbrelease_utils.get_chromeos_release_version(
322 lsb_release_content=lsb_release_content)
323
324
Kevin Cheng5f2ba6c2016-09-28 10:20:05 -0700325 def get_attached_duts(self, afe):
326 """Gather a list of duts that use this servo host.
327
328 @param afe: afe instance.
329
330 @returns list of duts.
Richard Barnette3a7697f2016-04-20 11:33:27 -0700331 """
Kevin Cheng5f2ba6c2016-09-28 10:20:05 -0700332 return afe.get_hosts_by_attribute(
333 attribute=SERVO_HOST_ATTR, value=self.hostname)
334
335
336 def get_board(self):
337 """Determine the board for this servo host.
338
339 @returns a string representing this servo host's board.
340 """
341 return lsbrelease_utils.get_current_board(
342 lsb_release_content=self.run('cat /etc/lsb-release').stdout)
343
344
345 def _choose_dut_for_synchronized_reboot(self, dut_list, afe):
346 """Choose which dut to schedule servo host reboot job.
347
348 We'll want a semi-deterministic way of selecting which host should be
349 scheduled for the servo host reboot job. For now we'll sort the
350 list with the expectation the dut list will stay consistent.
351 From there we'll grab the first dut that is available so we
352 don't schedule a job on a dut that will never run.
353
354 @param dut_list: List of the dut hostnames to choose from.
355 @param afe: Instance of the AFE.
356
357 @return hostname of dut to schedule job on.
358 """
359 afe_hosts = afe.get_hosts(dut_list)
360 afe_hosts.sort()
361 for afe_host in afe_hosts:
362 if afe_host.status not in host_states.UNAVAILABLE_STATES:
363 return afe_host.hostname
364 # If they're all unavailable, just return the first sorted dut.
365 dut_list.sort()
366 return dut_list[0]
367
368
369 def _sync_job_scheduled_for_duts(self, dut_list, afe):
370 """Checks if a synchronized reboot has been scheduled for these duts.
371
372 Grab all the host queue entries that aren't completed for the duts and
373 see if any of them have the expected job name.
374
375 @param dut_list: List of duts to check on.
376 @param afe: Instance of the AFE.
377
378 @returns True if the job is scheduled, False otherwise.
379 """
380 afe_hosts = afe.get_hosts(dut_list)
381 for afe_host in afe_hosts:
382 hqes = afe.get_host_queue_entries(host=afe_host.id, complete=0)
383 for hqe in hqes:
384 job = afe.get_jobs(id=hqe.job.id)
385 if job and job[0].name == _SERVO_HOST_REBOOT_TEST_NAME:
386 return True
387 return False
388
389
390 def schedule_synchronized_reboot(self, dut_list, afe):
391 """Schedule a job to reboot the servo host.
392
393 When we schedule a job, it will create a ServoHost object which will
394 go through this entire flow of checking if a reboot is needed and
395 trying to schedule it. There is probably a better approach to setting
396 up a synchronized reboot but I'm coming up short on better ideas so I
397 apologize for this circus show.
398
399 @param dut_list: List of duts that need to be locked.
400 @param afe: Instance of afe.
401 """
402 # If we've already scheduled job on a dut, we're done here.
403 if self._sync_job_scheduled_for_duts(dut_list, afe):
404 return
405
406 # Looks like we haven't scheduled a job yet.
407 dut = self._choose_dut_for_synchronized_reboot(dut_list, afe)
408 getter = control_file_getter.FileSystemGetter([AUTOTEST_BASE])
409 control_file = getter.get_control_file_contents_by_name(
410 _SERVO_HOST_REBOOT_TEST_NAME)
411 control_type = control_data.CONTROL_TYPE_NAMES.SERVER
412 priority = priorities.Priority.SUPER
413 afe.create_job(control_file=control_file,
414 name=_SERVO_HOST_REBOOT_TEST_NAME,
415 control_type=control_type, hosts=[dut])
416
417
418 def reboot(self, *args, **dargs):
419 """Reboot using special servo host reboot command."""
420 super(ServoHost, self).reboot(reboot_cmd=self.REBOOT_CMD,
421 *args, **dargs)
422
423
424 def _check_for_reboot(self, updater):
425 """Reboot this servo host if an upgrade is waiting.
Richard Barnette3a7697f2016-04-20 11:33:27 -0700426
427 If the host has successfully downloaded and finalized a new
428 build, reboot.
429
430 @param updater: a ChromiumOSUpdater instance for checking
431 whether reboot is needed.
432 @return Return a (status, build) tuple reflecting the
433 update_engine status and current build of the host
434 at the end of the call.
435 """
Richard Barnette9a26ad62016-06-10 12:03:08 -0700436 current_build_number = self._get_release_version()
Richard Barnette3a7697f2016-04-20 11:33:27 -0700437 status = updater.check_update_status()
438 if status == autoupdater.UPDATER_NEED_REBOOT:
Kevin Cheng5f2ba6c2016-09-28 10:20:05 -0700439 # Check if we need to schedule an organized reboot.
440 afe = frontend_wrappers.RetryingAFE(timeout_min=5, delay_sec=10)
441 dut_list = self.get_attached_duts(afe)
442 logging.info('servo host has the following duts: %s', dut_list)
443 if len(dut_list) > 1:
444 logging.info('servo host has multiple duts, scheduling '
445 'synchronized reboot')
446 self.schedule_synchronized_reboot(dut_list, afe)
447 return status, current_build_number
448
449 logging.info('Rebooting servo host %s from build %s',
Richard Barnette3a7697f2016-04-20 11:33:27 -0700450 self.hostname, current_build_number)
451 # Tell the reboot() call not to wait for completion.
452 # Otherwise, the call will log reboot failure if servo does
453 # not come back. The logged reboot failure will lead to
454 # test job failure. If the test does not require servo, we
455 # don't want servo failure to fail the test with error:
456 # `Host did not return from reboot` in status.log.
Kevin Cheng5f2ba6c2016-09-28 10:20:05 -0700457 self.reboot(fastsync=True, wait=False)
Richard Barnette3a7697f2016-04-20 11:33:27 -0700458
459 # We told the reboot() call not to wait, but we need to wait
460 # for the reboot before we continue. Alas. The code from
461 # here below is basically a copy of Host.wait_for_restart(),
462 # with the logging bits ripped out, so that they can't cause
463 # the failure logging problem described above.
464 #
465 # The black stain that this has left on my soul can never be
466 # erased.
467 old_boot_id = self.get_boot_id()
468 if not self.wait_down(timeout=self.WAIT_DOWN_REBOOT_TIMEOUT,
469 warning_timer=self.WAIT_DOWN_REBOOT_WARNING,
470 old_boot_id=old_boot_id):
471 raise error.AutoservHostError(
Kevin Cheng5f2ba6c2016-09-28 10:20:05 -0700472 'servo host %s failed to shut down.' %
473 self.hostname)
Richard Barnette3a7697f2016-04-20 11:33:27 -0700474 if self.wait_up(timeout=120):
Richard Barnette9a26ad62016-06-10 12:03:08 -0700475 current_build_number = self._get_release_version()
Richard Barnette3a7697f2016-04-20 11:33:27 -0700476 status = updater.check_update_status()
477 logging.info('servo host %s back from reboot, with build %s',
478 self.hostname, current_build_number)
479 else:
480 raise error.AutoservHostError(
Kevin Cheng5f2ba6c2016-09-28 10:20:05 -0700481 'servo host %s failed to come back from reboot.' %
482 self.hostname)
Richard Barnette3a7697f2016-04-20 11:33:27 -0700483 return status, current_build_number
484
485
beeps5e8c45a2013-12-17 22:05:11 -0800486 @_timer.decorate
Richard Barnette3a7697f2016-04-20 11:33:27 -0700487 def update_image(self, wait_for_update=False):
beeps5e8c45a2013-12-17 22:05:11 -0800488 """Update the image on the servo host, if needed.
489
J. Richard Barnette84895392015-04-30 12:31:01 -0700490 This method recognizes the following cases:
491 * If the Host is not running Chrome OS, do nothing.
492 * If a previously triggered update is now complete, reboot
493 to the new version.
494 * If the host is processing a previously triggered update,
495 do nothing.
496 * If the host is running a version of Chrome OS different
497 from the default for servo Hosts, trigger an update, but
498 don't wait for it to complete.
beeps5e8c45a2013-12-17 22:05:11 -0800499
Richard Barnette3a7697f2016-04-20 11:33:27 -0700500 @param wait_for_update If an update needs to be applied and
501 this is true, then don't return until the update is
502 downloaded and finalized, and the host rebooted.
beeps5e8c45a2013-12-17 22:05:11 -0800503 @raises dev_server.DevServerException: If all the devservers are down.
504 @raises site_utils.ParseBuildNameException: If the devserver returns
505 an invalid build name.
506 @raises autoupdater.ChromiumOSError: If something goes wrong in the
507 checking update engine client status or applying an update.
508 @raises AutoservRunError: If the update_engine_client isn't present on
509 the host, and the host is a cros_host.
J. Richard Barnette84895392015-04-30 12:31:01 -0700510
beeps5e8c45a2013-12-17 22:05:11 -0800511 """
Dan Shib795b5a2015-09-24 13:26:35 -0700512 # servod could be running in a Ubuntu workstation.
Richard Barnette9a26ad62016-06-10 12:03:08 -0700513 if not self.is_cros_host():
beeps5e8c45a2013-12-17 22:05:11 -0800514 logging.info('Not attempting an update, either %s is not running '
515 'chromeos or we cannot find enough information about '
516 'the host.', self.hostname)
517 return
518
Dan Shib795b5a2015-09-24 13:26:35 -0700519 if lsbrelease_utils.is_moblab():
520 logging.info('Not attempting an update, %s is running moblab.',
521 self.hostname)
522 return
523
Richard Barnette260cbd02016-10-06 12:23:28 -0700524 target_build = afe_utils.get_stable_cros_version(self.get_board())
J. Richard Barnette84895392015-04-30 12:31:01 -0700525 target_build_number = server_site_utils.ParseBuildName(
526 target_build)[3]
beeps5e8c45a2013-12-17 22:05:11 -0800527 ds = dev_server.ImageServer.resolve(self.hostname)
J. Richard Barnette84895392015-04-30 12:31:01 -0700528 url = ds.get_update_url(target_build)
beeps5e8c45a2013-12-17 22:05:11 -0800529
530 updater = autoupdater.ChromiumOSUpdater(update_url=url, host=self)
Richard Barnette3a7697f2016-04-20 11:33:27 -0700531 status, current_build_number = self._check_for_reboot(updater)
532 update_pending = True
beeps5e8c45a2013-12-17 22:05:11 -0800533 if status in autoupdater.UPDATER_PROCESSING_UPDATE:
534 logging.info('servo host %s already processing an update, update '
535 'engine client status=%s', self.hostname, status)
J. Richard Barnette84895392015-04-30 12:31:01 -0700536 elif current_build_number != target_build_number:
beeps5e8c45a2013-12-17 22:05:11 -0800537 logging.info('Using devserver url: %s to trigger update on '
538 'servo host %s, from %s to %s', url, self.hostname,
J. Richard Barnette84895392015-04-30 12:31:01 -0700539 current_build_number, target_build_number)
beeps5e8c45a2013-12-17 22:05:11 -0800540 try:
J. Richard Barnette84895392015-04-30 12:31:01 -0700541 ds.stage_artifacts(target_build,
542 artifacts=['full_payload'])
543 except Exception as e:
544 logging.error('Staging artifacts failed: %s', str(e))
545 logging.error('Abandoning update for this cycle.')
beeps5e8c45a2013-12-17 22:05:11 -0800546 else:
J. Richard Barnette84895392015-04-30 12:31:01 -0700547 try:
Richard Barnette7e53aa02016-05-20 10:49:40 -0700548 # TODO(jrbarnette): This 'touch' is a gross hack
549 # to get us past crbug.com/613603. Once that
550 # bug is resolved, we should remove this code.
551 self.run('touch /home/chronos/.oobe_completed')
J. Richard Barnette84895392015-04-30 12:31:01 -0700552 updater.trigger_update()
553 except autoupdater.RootFSUpdateError as e:
554 trigger_download_status = 'failed with %s' % str(e)
555 autotest_stats.Counter(
556 'servo_host.RootFSUpdateError').increment()
557 else:
558 trigger_download_status = 'passed'
559 logging.info('Triggered download and update %s for %s, '
560 'update engine currently in status %s',
561 trigger_download_status, self.hostname,
562 updater.check_update_status())
beeps5e8c45a2013-12-17 22:05:11 -0800563 else:
564 logging.info('servo host %s does not require an update.',
565 self.hostname)
Richard Barnette3a7697f2016-04-20 11:33:27 -0700566 update_pending = False
567
568 if update_pending and wait_for_update:
569 logging.info('Waiting for servo update to complete.')
570 self.run('update_engine_client --follow', ignore_status=True)
beeps5e8c45a2013-12-17 22:05:11 -0800571
572
Richard Barnette9a26ad62016-06-10 12:03:08 -0700573 def verify(self):
574 """Update the servo host and verify it's in a good state."""
Richard Barnette79d78c42016-05-25 09:31:21 -0700575 # TODO(jrbarnette) Old versions of beaglebone_servo include
Richard Barnette9a26ad62016-06-10 12:03:08 -0700576 # the powerd package. If you touch the .oobe_completed file
577 # (as we do to work around an update_engine problem), then
578 # powerd will eventually shut down the beaglebone for lack
579 # of (apparent) activity. Current versions of
Richard Barnette79d78c42016-05-25 09:31:21 -0700580 # beaglebone_servo don't have powerd, but until we can purge
581 # the lab of the old images, we need to make sure powerd
582 # isn't running.
583 self.run('stop powerd', ignore_status=True)
Richard Barnette9a26ad62016-06-10 12:03:08 -0700584 try:
585 self._repair_strategy.verify(self)
586 except:
587 self.disconnect_servo()
588 raise
Fang Deng5d518f42013-08-02 14:04:32 -0700589
590
Richard Barnette9a26ad62016-06-10 12:03:08 -0700591 def repair(self):
592 """Attempt to repair servo host."""
593 try:
594 self._repair_strategy.repair(self)
595 except:
596 self.disconnect_servo()
597 raise
Fang Deng5d518f42013-08-02 14:04:32 -0700598
599
Fang Dengd4fe7392013-09-20 12:18:21 -0700600 def has_power(self):
601 """Return whether or not the servo host is powered by PoE."""
602 # TODO(fdeng): See crbug.com/302791
603 # For now, assume all servo hosts in the lab have power.
604 return self.is_in_lab()
605
606
607 def power_cycle(self):
608 """Cycle power to this host via PoE if it is a lab device.
609
Richard Barnette9a26ad62016-06-10 12:03:08 -0700610 @raises AutoservRepairError if it fails to power cycle the
Fang Dengd4fe7392013-09-20 12:18:21 -0700611 servo host.
612
613 """
614 if self.has_power():
615 try:
616 rpm_client.set_power(self.hostname, 'CYCLE')
617 except (socket.error, xmlrpclib.Error,
618 httplib.BadStatusLine,
619 rpm_client.RemotePowerException) as e:
Richard Barnette9a26ad62016-06-10 12:03:08 -0700620 raise hosts.AutoservRepairError(
Fang Dengd4fe7392013-09-20 12:18:21 -0700621 'Power cycling %s failed: %s' % (self.hostname, e))
622 else:
623 logging.info('Skipping power cycling, not a lab device.')
624
625
Dan Shi4d478522014-02-14 13:46:32 -0800626 def get_servo(self):
627 """Get the cached servo.Servo object.
Fang Deng5d518f42013-08-02 14:04:32 -0700628
Dan Shi4d478522014-02-14 13:46:32 -0800629 @return: a servo.Servo object.
Fang Deng5d518f42013-08-02 14:04:32 -0700630 """
Dan Shi4d478522014-02-14 13:46:32 -0800631 return self._servo
632
633
Richard Barnetteea3e4602016-06-10 12:36:41 -0700634def make_servo_hostname(dut_hostname):
635 """Given a DUT's hostname, return the hostname of its servo.
636
637 @param dut_hostname: hostname of a DUT.
638
639 @return hostname of the DUT's servo.
640
641 """
642 host_parts = dut_hostname.split('.')
643 host_parts[0] = host_parts[0] + '-servo'
644 return '.'.join(host_parts)
645
646
647def servo_host_is_up(servo_hostname):
Kevin Cheng5f2ba6c2016-09-28 10:20:05 -0700648 """Given a servo host name, return if it's up or not.
Richard Barnetteea3e4602016-06-10 12:36:41 -0700649
650 @param servo_hostname: hostname of the servo host.
651
652 @return True if it's up, False otherwise
653 """
654 # Technically, this duplicates the SSH ping done early in the servo
655 # proxy initialization code. However, this ping ends in a couple
656 # seconds when if fails, rather than the 60 seconds it takes to decide
657 # that an SSH ping has timed out. Specifically, that timeout happens
658 # when our servo DNS name resolves, but there is no host at that IP.
659 logging.info('Pinging servo host at %s', servo_hostname)
660 ping_config = ping_runner.PingConfig(
661 servo_hostname, count=3,
662 ignore_result=True, ignore_status=True)
663 return ping_runner.PingRunner().ping(ping_config).received > 0
664
665
Richard Barnettee519dcd2016-08-15 17:37:17 -0700666def _map_afe_board_to_servo_board(afe_board):
667 """Map a board we get from the AFE to a servo appropriate value.
668
669 Many boards are identical to other boards for servo's purposes.
670 This function makes that mapping.
671
672 @param afe_board string board name received from AFE.
673 @return board we expect servo to have.
674
675 """
676 KNOWN_SUFFIXES = ['-freon', '_freon', '_moblab', '-cheets']
677 BOARD_MAP = {'gizmo': 'panther'}
678 mapped_board = afe_board
679 if afe_board in BOARD_MAP:
680 mapped_board = BOARD_MAP[afe_board]
681 else:
682 for suffix in KNOWN_SUFFIXES:
683 if afe_board.endswith(suffix):
684 mapped_board = afe_board[0:-len(suffix)]
685 break
686 if mapped_board != afe_board:
687 logging.info('Mapping AFE board=%s to %s', afe_board, mapped_board)
688 return mapped_board
689
690
Richard Barnetteea3e4602016-06-10 12:36:41 -0700691def _get_standard_servo_args(dut_host):
Kevin Cheng5f2ba6c2016-09-28 10:20:05 -0700692 """Return servo data associated with a given DUT.
Richard Barnetteea3e4602016-06-10 12:36:41 -0700693
694 This checks for the presence of servo host and port attached to the
695 given `dut_host`. This data should be stored in the
Kevin Cheng05ae2a42016-06-06 10:12:48 -0700696 `_afe_host.attributes` field in the provided `dut_host` parameter.
Richard Barnetteea3e4602016-06-10 12:36:41 -0700697
698 @param dut_host Instance of `Host` on which to find the servo
699 attributes.
700 @return A tuple of `servo_args` dict with host and an option port,
701 plus an `is_in_lab` flag indicating whether this in the CrOS
702 test lab, or some different environment.
703 """
704 servo_args = None
705 is_in_lab = False
706 is_ssp_moblab = False
707 if utils.is_in_container():
708 is_moblab = _CONFIG.get_config_value(
709 'SSP', 'is_moblab', type=bool, default=False)
710 is_ssp_moblab = is_moblab
711 else:
712 is_moblab = utils.is_moblab()
Kevin Cheng05ae2a42016-06-06 10:12:48 -0700713 attrs = dut_host._afe_host.attributes
Richard Barnetteea3e4602016-06-10 12:36:41 -0700714 if attrs and SERVO_HOST_ATTR in attrs:
715 servo_host = attrs[SERVO_HOST_ATTR]
716 if (is_ssp_moblab and servo_host in ['localhost', '127.0.0.1']):
717 servo_host = _CONFIG.get_config_value(
718 'SSP', 'host_container_ip', type=str, default=None)
719 servo_args = {SERVO_HOST_ATTR: servo_host}
720 if SERVO_PORT_ATTR in attrs:
Kevin Cheng692e5292016-08-14 00:23:24 -0700721 try:
722 servo_port = attrs[SERVO_PORT_ATTR]
723 servo_args[SERVO_PORT_ATTR] = int(servo_port)
724 except ValueError:
725 logging.error('servo port is not an int: %s', servo_port)
726 # Let's set the servo args to None since we're not creating
727 # the ServoHost object with the proper port now.
728 servo_args = None
Kevin Cheng643ce8a2016-09-15 15:42:12 -0700729 if SERVO_SERIAL_ATTR in attrs:
730 servo_args[SERVO_SERIAL_ATTR] = attrs[SERVO_SERIAL_ATTR]
Richard Barnetteea3e4602016-06-10 12:36:41 -0700731 is_in_lab = (not is_moblab
732 and utils.host_is_in_lab_zone(servo_host))
733
734 # TODO(jrbarnette): This test to use the default lab servo hostname
735 # is a legacy that we need only until every host in the DB has
736 # proper attributes.
737 elif (not is_moblab and
738 not dnsname_mangler.is_ip_address(dut_host.hostname)):
739 servo_host = make_servo_hostname(dut_host.hostname)
740 is_in_lab = utils.host_is_in_lab_zone(servo_host)
741 if is_in_lab:
742 servo_args = {SERVO_HOST_ATTR: servo_host}
Richard Barnette9a26ad62016-06-10 12:03:08 -0700743 if servo_args is not None:
744 servo_board = afe_utils.get_board(dut_host)
745 if servo_board is not None:
746 servo_board = _map_afe_board_to_servo_board(servo_board)
747 servo_args[SERVO_BOARD_ATTR] = servo_board
Richard Barnetteea3e4602016-06-10 12:36:41 -0700748 return servo_args, is_in_lab
749
750
Dan Shi023aae32016-05-25 11:13:01 -0700751def create_servo_host(dut, servo_args, try_lab_servo=False,
Richard Barnette9a26ad62016-06-10 12:03:08 -0700752 try_servo_repair=False):
Kevin Cheng5f2ba6c2016-09-28 10:20:05 -0700753 """Create a ServoHost object for a given DUT, if appropriate.
Dan Shi4d478522014-02-14 13:46:32 -0800754
Richard Barnette9a26ad62016-06-10 12:03:08 -0700755 This function attempts to create and verify or repair a `ServoHost`
756 object for a servo connected to the given `dut`, subject to various
757 constraints imposed by the parameters:
758 * When the `servo_args` parameter is not `None`, a servo
759 host must be created, and must be checked with `repair()`.
760 * Otherwise, if a servo exists in the lab and `try_lab_servo` is
761 true:
762 * If `try_servo_repair` is true, then create a servo host and
763 check it with `repair()`.
764 * Otherwise, if the servo responds to `ping` then create a
765 servo host and check it with `verify()`.
Fang Denge545abb2014-12-30 18:43:47 -0800766
Richard Barnette9a26ad62016-06-10 12:03:08 -0700767 In cases where `servo_args` was not `None`, repair failure
768 exceptions are passed back to the caller; otherwise, exceptions
769 are logged and then discarded.
770
771 Parameters for a servo host consist of a host name, port number, and
772 DUT board, and are determined from one of these sources, in order of
773 priority:
Richard Barnetteea3e4602016-06-10 12:36:41 -0700774 * Servo attributes from the `dut` parameter take precedence over
775 all other sources of information.
776 * If a DNS entry for the servo based on the DUT hostname exists in
777 the CrOS lab network, that hostname is used with the default
Richard Barnette9a26ad62016-06-10 12:03:08 -0700778 port and the DUT's board.
Richard Barnetteea3e4602016-06-10 12:36:41 -0700779 * If no other options are found, the parameters will be taken
Richard Barnette9a26ad62016-06-10 12:03:08 -0700780 from the `servo_args` dict passed in from the caller.
Richard Barnetteea3e4602016-06-10 12:36:41 -0700781
782 @param dut An instance of `Host` from which to take
783 servo parameters (if available).
784 @param servo_args A dictionary with servo parameters to use if
785 they can't be found from `dut`. If this
786 argument is supplied, unrepaired exceptions
787 from `verify()` will be passed back to the
788 caller.
789 @param try_lab_servo If not true, servo host creation will be
790 skipped unless otherwise required by the
791 caller.
Richard Barnette9a26ad62016-06-10 12:03:08 -0700792 @param try_servo_repair If true, check a servo host with
793 `repair()` instead of `verify()`.
Dan Shi4d478522014-02-14 13:46:32 -0800794
795 @returns: A ServoHost object or None. See comments above.
796
797 """
Richard Barnette9a26ad62016-06-10 12:03:08 -0700798 require_repair = servo_args is not None
Richard Barnetteea3e4602016-06-10 12:36:41 -0700799 is_in_lab = False
Richard Barnette9a26ad62016-06-10 12:03:08 -0700800 if dut is not None and (try_lab_servo or require_repair):
Richard Barnetteea3e4602016-06-10 12:36:41 -0700801 servo_args_override, is_in_lab = _get_standard_servo_args(dut)
802 if servo_args_override is not None:
803 servo_args = servo_args_override
804 if servo_args is None:
805 return None
Richard Barnette9a26ad62016-06-10 12:03:08 -0700806 if (not require_repair and not try_servo_repair and
807 not servo_host_is_up(servo_args[SERVO_HOST_ATTR])):
Dan Shibbb0cb62014-03-24 17:50:57 -0700808 return None
Richard Barnette9a26ad62016-06-10 12:03:08 -0700809 newhost = ServoHost(is_in_lab=is_in_lab, **servo_args)
810 # Note that the logic of repair() includes everything done
811 # by verify(). It's sufficient to call one or the other;
812 # we don't need both.
813 if require_repair:
814 newhost.repair()
815 else:
816 try:
817 if try_servo_repair:
818 newhost.repair()
819 else:
820 newhost.verify()
Kevin Cheng5f2ba6c2016-09-28 10:20:05 -0700821 except Exception:
Richard Barnette9a26ad62016-06-10 12:03:08 -0700822 operation = 'repair' if try_servo_repair else 'verification'
823 logging.exception('Servo %s failed for %s',
824 operation, newhost.hostname)
825 return newhost