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