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