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