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