blob: 1c334fc95840ccb7b8247fd9f7e8c097220686d0 [file] [log] [blame]
Garry Wangebc015b2019-06-06 17:45:06 -07001# Copyright (c) 2019 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 is a base host class for servohost and labstation."""
10
11
12import httplib
13import logging
14import socket
Gregory Nisbet8e2fbb22019-12-05 11:36:37 -080015import traceback
Garry Wangebc015b2019-06-06 17:45:06 -070016import xmlrpclib
17
18from autotest_lib.client.bin import utils
19from autotest_lib.client.common_lib import error
20from autotest_lib.client.common_lib import hosts
21from autotest_lib.client.common_lib import lsbrelease_utils
22from autotest_lib.client.common_lib.cros import dev_server
23from autotest_lib.client.cros import constants as client_constants
24from autotest_lib.server import afe_utils
25from autotest_lib.server import site_utils as server_utils
26from autotest_lib.server.cros import autoupdater
27from autotest_lib.server.hosts import ssh_host
28from autotest_lib.site_utils.rpm_control_system import rpm_client
29
30try:
31 from chromite.lib import metrics
32except ImportError:
33 metrics = utils.metrics_mock
34
35
36class BaseServoHost(ssh_host.SSHHost):
37 """Base host class for a host that manage servo(s).
38 E.g. beaglebone, labstation.
39 """
Garry Wang3d84a162020-01-24 13:29:43 +000040 REBOOT_CMD = 'sleep 5; reboot & sleep 10; reboot -f'
Garry Wangebc015b2019-06-06 17:45:06 -070041
Garry Wang79e9af62019-06-12 15:19:19 -070042 TEMP_FILE_DIR = '/var/lib/servod/'
43
44 LOCK_FILE_POSTFIX = '_in_use'
45 REBOOT_FILE_POSTFIX = '_reboot'
Garry Wangebc015b2019-06-06 17:45:06 -070046
Garry Wang5715ee52019-12-23 11:00:47 -080047 # Time to wait a rebooting servohost, in seconds.
Garry Wangfb253432019-09-11 17:08:38 -070048 REBOOT_TIMEOUT = 240
Garry Wangebc015b2019-06-06 17:45:06 -070049
Garry Wang5715ee52019-12-23 11:00:47 -080050 # Timeout value to power cycle a servohost, in seconds.
51 BOOT_TIMEOUT = 240
52
Garry Wangebc015b2019-06-06 17:45:06 -070053
54 def _initialize(self, hostname, is_in_lab=None, *args, **dargs):
55 """Construct a BaseServoHost object.
56
57 @param is_in_lab: True if the servo host is in Cros Lab. Default is set
58 to None, for which utils.host_is_in_lab_zone will be
59 called to check if the servo host is in Cros lab.
60
61 """
62 super(BaseServoHost, self)._initialize(hostname=hostname,
63 *args, **dargs)
64 self._is_localhost = (self.hostname == 'localhost')
65 if self._is_localhost:
66 self._is_in_lab = False
67 elif is_in_lab is None:
68 self._is_in_lab = utils.host_is_in_lab_zone(self.hostname)
69 else:
70 self._is_in_lab = is_in_lab
71
72 # Commands on the servo host must be run by the superuser.
73 # Our account on a remote host is root, but if our target is
74 # localhost then we might be running unprivileged. If so,
75 # `sudo` will have to be added to the commands.
76 if self._is_localhost:
77 self._sudo_required = utils.system_output('id -u') != '0'
78 else:
79 self._sudo_required = False
80
81 self._is_labstation = None
Gregory Nisbet8e2fbb22019-12-05 11:36:37 -080082 self._dut_host_info = None
Garry Wangebc015b2019-06-06 17:45:06 -070083
84
85 def get_board(self):
86 """Determine the board for this servo host. E.g. fizz-labstation
87
Garry Wang5e118c02019-09-25 14:24:57 -070088 @returns a string representing this labstation's board or None if
89 target host is not using a ChromeOS image(e.g. test in chroot).
Garry Wangebc015b2019-06-06 17:45:06 -070090 """
Garry Wang5e118c02019-09-25 14:24:57 -070091 output = self.run('cat /etc/lsb-release', ignore_status=True).stdout
92 return lsbrelease_utils.get_current_board(lsb_release_content=output)
Garry Wangebc015b2019-06-06 17:45:06 -070093
94
Garry Wangd7367482020-02-27 13:52:40 -080095 def set_dut_host_info(self, dut_host_info):
96 """
97 @param dut_host_info: A HostInfo object.
98 """
99 logging.info('setting dut_host_info field to (%s)', dut_host_info)
100 self._dut_host_info = dut_host_info
101
102
103 def get_dut_host_info(self):
104 """
105 @return A HostInfo object.
106 """
107 return self._dut_host_info
Gregory Nisbet8e2fbb22019-12-05 11:36:37 -0800108
109
Garry Wangebc015b2019-06-06 17:45:06 -0700110 def is_labstation(self):
111 """Determine if the host is a labstation
112
113 @returns True if ths host is a labstation otherwise False.
114 """
115 if self._is_labstation is None:
116 board = self.get_board()
Garry Wang88dc8632019-07-24 16:53:50 -0700117 self._is_labstation = board is not None and 'labstation' in board
Garry Wangebc015b2019-06-06 17:45:06 -0700118
119 return self._is_labstation
120
121
122 def _get_release_version(self):
123 """Get the value of attribute CHROMEOS_RELEASE_VERSION from lsb-release.
124
125 @returns The version string in lsb-release, under attribute
126 CHROMEOS_RELEASE_VERSION.
127 """
128 lsb_release_content = self.run(
129 'cat "%s"' % client_constants.LSB_RELEASE).stdout.strip()
130 return lsbrelease_utils.get_chromeos_release_version(
131 lsb_release_content=lsb_release_content)
132
133
134 def _check_update_status(self):
135 dummy_updater = autoupdater.ChromiumOSUpdater(update_url="", host=self)
136 return dummy_updater.check_update_status()
137
138
139 def is_in_lab(self):
140 """Check whether the servo host is a lab device.
141
142 @returns: True if the servo host is in Cros Lab, otherwise False.
143
144 """
145 return self._is_in_lab
146
147
148 def is_localhost(self):
149 """Checks whether the servo host points to localhost.
150
151 @returns: True if it points to localhost, otherwise False.
152
153 """
154 return self._is_localhost
155
156
157 def is_cros_host(self):
158 """Check if a servo host is running chromeos.
159
160 @return: True if the servo host is running chromeos.
161 False if it isn't, or we don't have enough information.
162 """
163 try:
164 result = self.run('grep -q CHROMEOS /etc/lsb-release',
165 ignore_status=True, timeout=10)
166 except (error.AutoservRunError, error.AutoservSSHTimeout):
167 return False
168 return result.exit_status == 0
169
170
171 def reboot(self, *args, **dargs):
172 """Reboot using special servo host reboot command."""
173 super(BaseServoHost, self).reboot(reboot_cmd=self.REBOOT_CMD,
174 *args, **dargs)
175
176
177 def update_image(self, wait_for_update=False):
178 """Update the image on the servo host, if needed.
179
180 This method recognizes the following cases:
181 * If the Host is not running Chrome OS, do nothing.
182 * If a previously triggered update is now complete, reboot
183 to the new version.
184 * If the host is processing a previously triggered update,
185 do nothing.
186 * If the host is running a version of Chrome OS different
187 from the default for servo Hosts, trigger an update, but
188 don't wait for it to complete.
189
190 @param wait_for_update If an update needs to be applied and
191 this is true, then don't return until the update is
192 downloaded and finalized, and the host rebooted.
193 @raises dev_server.DevServerException: If all the devservers are down.
194 @raises site_utils.ParseBuildNameException: If the devserver returns
195 an invalid build name.
196 @raises AutoservRunError: If the update_engine_client isn't present on
197 the host, and the host is a cros_host.
198
199 """
200 # servod could be running in a Ubuntu workstation.
201 if not self.is_cros_host():
202 logging.info('Not attempting an update, either %s is not running '
203 'chromeos or we cannot find enough information about '
204 'the host.', self.hostname)
205 return
206
207 if lsbrelease_utils.is_moblab():
208 logging.info('Not attempting an update, %s is running moblab.',
209 self.hostname)
210 return
211
Garry Wangd7367482020-02-27 13:52:40 -0800212 stable_version = None
213 logging.debug("BaseServoHost::update_image attempted to get"
214 " servo cros stable version")
Gregory Nisbet8e2fbb22019-12-05 11:36:37 -0800215 try:
Garry Wangd7367482020-02-27 13:52:40 -0800216 stable_version = self.get_dut_host_info().servo_cros_stable_version
Gregory Nisbet8e2fbb22019-12-05 11:36:37 -0800217 except Exception:
Garry Wangd7367482020-02-27 13:52:40 -0800218 logging.error("BaseServoHost::update_image failed to get servo"
219 " cros stable version (%s)", traceback.format_exc())
Gregory Nisbet8e2fbb22019-12-05 11:36:37 -0800220
221 target_build = afe_utils.get_stable_servo_cros_image_name_v2(
Garry Wangd7367482020-02-27 13:52:40 -0800222 servo_version_from_hi=stable_version,
Gregory Nisbet8e2fbb22019-12-05 11:36:37 -0800223 board=self.get_board(),
224 )
Garry Wangebc015b2019-06-06 17:45:06 -0700225 target_build_number = server_utils.ParseBuildName(
226 target_build)[3]
227 current_build_number = self._get_release_version()
228
229 if current_build_number == target_build_number:
230 logging.info('servo host %s does not require an update.',
231 self.hostname)
232 return
233
234 status = self._check_update_status()
235 if status in autoupdater.UPDATER_PROCESSING_UPDATE:
236 logging.info('servo host %s already processing an update, update '
237 'engine client status=%s', self.hostname, status)
238 elif status == autoupdater.UPDATER_NEED_REBOOT:
239 logging.info('An update has been completed and pending reboot now.')
240 # Labstation reboot is handled separately here as it require
241 # synchronized reboot among all managed DUTs.
242 if not self.is_labstation():
243 self._servo_host_reboot()
244 else:
245 # For servo image staging, we want it as more widely distributed as
246 # possible, so that devservers' load can be evenly distributed.
247 # So use hostname instead of target_build as hash.
248 ds = dev_server.ImageServer.resolve(self.hostname,
249 hostname=self.hostname)
250 url = ds.get_update_url(target_build)
251
252 updater = autoupdater.ChromiumOSUpdater(update_url=url, host=self)
253
254 logging.info('Using devserver url: %s to trigger update on '
255 'servo host %s, from %s to %s', url, self.hostname,
256 current_build_number, target_build_number)
257 try:
258 ds.stage_artifacts(target_build,
259 artifacts=['full_payload'])
260 except Exception as e:
261 logging.error('Staging artifacts failed: %s', str(e))
262 logging.error('Abandoning update for this cycle.')
263 else:
264 try:
265 updater.trigger_update()
266 except autoupdater.RootFSUpdateError as e:
267 trigger_download_status = 'failed with %s' % str(e)
268 metrics.Counter('chromeos/autotest/servo/'
269 'rootfs_update_failed').increment()
270 else:
271 trigger_download_status = 'passed'
272 logging.info('Triggered download and update %s for %s, '
273 'update engine currently in status %s',
274 trigger_download_status, self.hostname,
275 updater.check_update_status())
276
277 if wait_for_update:
278 logging.info('Waiting for servo update to complete.')
279 self.run('update_engine_client --follow', ignore_status=True)
280
281
282 def has_power(self):
283 """Return whether or not the servo host is powered by PoE or RPM."""
284 # TODO(fdeng): See crbug.com/302791
285 # For now, assume all servo hosts in the lab have power.
286 return self.is_in_lab()
287
288
289 def power_cycle(self):
290 """Cycle power to this host via PoE(servo v3) or RPM(labstation)
291 if it is a lab device.
292
293 @raises AutoservRepairError if it fails to power cycle the
294 servo host.
295
296 """
297 if self.has_power():
298 try:
299 rpm_client.set_power(self, 'CYCLE')
300 except (socket.error, xmlrpclib.Error,
301 httplib.BadStatusLine,
302 rpm_client.RemotePowerException) as e:
303 raise hosts.AutoservRepairError(
304 'Power cycling %s failed: %s' % (self.hostname, e),
305 'power_cycle_via_rpm_failed'
306 )
307 else:
308 logging.info('Skipping power cycling, not a lab device.')
309
310
311 def _servo_host_reboot(self):
312 """Reboot this servo host because a reboot is requested."""
313 logging.info('Rebooting servo host %s from build %s', self.hostname,
314 self._get_release_version())
315 # Tell the reboot() call not to wait for completion.
316 # Otherwise, the call will log reboot failure if servo does
317 # not come back. The logged reboot failure will lead to
318 # test job failure. If the test does not require servo, we
319 # don't want servo failure to fail the test with error:
320 # `Host did not return from reboot` in status.log.
321 self.reboot(fastsync=True, wait=False)
322
323 # We told the reboot() call not to wait, but we need to wait
324 # for the reboot before we continue. Alas. The code from
325 # here below is basically a copy of Host.wait_for_restart(),
326 # with the logging bits ripped out, so that they can't cause
327 # the failure logging problem described above.
328 #
329 # The black stain that this has left on my soul can never be
330 # erased.
331 old_boot_id = self.get_boot_id()
332 if not self.wait_down(timeout=self.WAIT_DOWN_REBOOT_TIMEOUT,
333 warning_timer=self.WAIT_DOWN_REBOOT_WARNING,
334 old_boot_id=old_boot_id):
335 raise error.AutoservHostError(
336 'servo host %s failed to shut down.' %
337 self.hostname)
Garry Wang79e9af62019-06-12 15:19:19 -0700338 if self.wait_up(timeout=self.REBOOT_TIMEOUT):
Garry Wangebc015b2019-06-06 17:45:06 -0700339 logging.info('servo host %s back from reboot, with build %s',
340 self.hostname, self._get_release_version())
341 else:
342 raise error.AutoservHostError(
343 'servo host %s failed to come back from reboot.' %
344 self.hostname)
345
346
347 def make_ssh_command(self, user='root', port=22, opts='', hosts_file=None,
348 connect_timeout=None, alive_interval=None, alive_count_max=None,
349 connection_attempts=None):
350 """Override default make_ssh_command to use tuned options.
351
352 Tuning changes:
353 - ConnectTimeout=30; maximum of 30 seconds allowed for an SSH
354 connection failure. Consistency with remote_access.py.
355
356 - ServerAliveInterval=180; which causes SSH to ping connection every
357 180 seconds. In conjunction with ServerAliveCountMax ensures
358 that if the connection dies, Autotest will bail out quickly.
359
360 - ServerAliveCountMax=3; consistency with remote_access.py.
361
362 - ConnectAttempts=4; reduce flakiness in connection errors;
363 consistency with remote_access.py.
364
365 - UserKnownHostsFile=/dev/null; we don't care about the keys.
366
367 - SSH protocol forced to 2; needed for ServerAliveInterval.
368
369 @param user User name to use for the ssh connection.
370 @param port Port on the target host to use for ssh connection.
371 @param opts Additional options to the ssh command.
372 @param hosts_file Ignored.
373 @param connect_timeout Ignored.
374 @param alive_interval Ignored.
375 @param alive_count_max Ignored.
376 @param connection_attempts Ignored.
377
378 @returns: An ssh command with the requested settings.
379
380 """
381 options = ' '.join([opts, '-o Protocol=2'])
382 return super(BaseServoHost, self).make_ssh_command(
383 user=user, port=port, opts=options, hosts_file='/dev/null',
384 connect_timeout=30, alive_interval=180, alive_count_max=3,
385 connection_attempts=4)
386
387
388 def _make_scp_cmd(self, sources, dest):
389 """Format scp command.
390
391 Given a list of source paths and a destination path, produces the
392 appropriate scp command for encoding it. Remote paths must be
393 pre-encoded. Overrides _make_scp_cmd in AbstractSSHHost
394 to allow additional ssh options.
395
396 @param sources: A list of source paths to copy from.
397 @param dest: Destination path to copy to.
398
399 @returns: An scp command that copies |sources| on local machine to
400 |dest| on the remote servo host.
401
402 """
403 command = ('scp -rq %s -o BatchMode=yes -o StrictHostKeyChecking=no '
404 '-o UserKnownHostsFile=/dev/null -P %d %s "%s"')
405 return command % (self._master_ssh.ssh_option,
406 self.port, sources, dest)
407
408
409 def run(self, command, timeout=3600, ignore_status=False,
410 stdout_tee=utils.TEE_TO_LOGS, stderr_tee=utils.TEE_TO_LOGS,
411 connect_timeout=30, ssh_failure_retry_ok=False,
412 options='', stdin=None, verbose=True, args=()):
413 """Run a command on the servo host.
414
415 Extends method `run` in SSHHost. If the servo host is a remote device,
416 it will call `run` in SSHost without changing anything.
417 If the servo host is 'localhost', it will call utils.system_output.
418
419 @param command: The command line string.
420 @param timeout: Time limit in seconds before attempting to
421 kill the running process. The run() function
422 will take a few seconds longer than 'timeout'
423 to complete if it has to kill the process.
424 @param ignore_status: Do not raise an exception, no matter
425 what the exit code of the command is.
426 @param stdout_tee/stderr_tee: Where to tee the stdout/stderr.
427 @param connect_timeout: SSH connection timeout (in seconds)
428 Ignored if host is 'localhost'.
429 @param options: String with additional ssh command options
430 Ignored if host is 'localhost'.
431 @param ssh_failure_retry_ok: when True and ssh connection failure is
432 suspected, OK to retry command (but not
433 compulsory, and likely not needed here)
434 @param stdin: Stdin to pass (a string) to the executed command.
435 @param verbose: Log the commands.
436 @param args: Sequence of strings to pass as arguments to command by
437 quoting them in " and escaping their contents if necessary.
438
439 @returns: A utils.CmdResult object.
440
441 @raises AutoservRunError if the command failed.
442 @raises AutoservSSHTimeout SSH connection has timed out. Only applies
443 when servo host is not 'localhost'.
444
445 """
446 run_args = {'command': command, 'timeout': timeout,
447 'ignore_status': ignore_status, 'stdout_tee': stdout_tee,
448 'stderr_tee': stderr_tee, 'stdin': stdin,
449 'verbose': verbose, 'args': args}
450 if self.is_localhost():
451 if self._sudo_required:
452 run_args['command'] = 'sudo -n sh -c "%s"' % utils.sh_escape(
453 command)
454 try:
455 return utils.run(**run_args)
456 except error.CmdError as e:
457 logging.error(e)
458 raise error.AutoservRunError('command execution error',
459 e.result_obj)
460 else:
461 run_args['connect_timeout'] = connect_timeout
462 run_args['options'] = options
463 return super(BaseServoHost, self).run(**run_args)