blob: 2b3f7a39c1eb795850210470b8e24d10ef44b1c7 [file] [log] [blame]
J. Richard Barnette24adbf42012-04-11 15:04:53 -07001# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
Dale Curtisaa5eedb2011-08-23 16:18:52 -07002# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
J. Richard Barnette1d78b012012-05-15 13:56:30 -07005import logging
6import subprocess
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07007import time
J. Richard Barnette1d78b012012-05-15 13:56:30 -07008import xmlrpclib
J. Richard Barnette134ec2c2012-04-25 12:59:37 -07009
J. Richard Barnette45e93de2012-04-11 17:24:15 -070010from autotest_lib.client.bin import utils
J. Richard Barnette134ec2c2012-04-25 12:59:37 -070011from autotest_lib.client.common_lib import global_config, error
J. Richard Barnette45e93de2012-04-11 17:24:15 -070012from autotest_lib.client.common_lib.cros import autoupdater
13from autotest_lib.server import autoserv_parser
14from autotest_lib.server import site_host_attributes
15from autotest_lib.server import site_remote_power
J. Richard Barnette67ccb872012-04-19 16:34:56 -070016from autotest_lib.server.cros import servo
J. Richard Barnette45e93de2012-04-11 17:24:15 -070017from autotest_lib.server.hosts import remote
J. Richard Barnette24adbf42012-04-11 15:04:53 -070018
19
Dale Curtiscb7bfaf2011-06-07 16:21:57 -070020def make_ssh_command(user='root', port=22, opts='', hosts_file=None,
21 connect_timeout=None, alive_interval=None):
22 """Override default make_ssh_command to use options tuned for Chrome OS.
23
24 Tuning changes:
Chris Sosaf7fcd6e2011-09-27 17:30:47 -070025 - ConnectTimeout=30; maximum of 30 seconds allowed for an SSH connection
26 failure. Consistency with remote_access.sh.
Dale Curtiscb7bfaf2011-06-07 16:21:57 -070027
Dale Curtisaa5eedb2011-08-23 16:18:52 -070028 - ServerAliveInterval=180; which causes SSH to ping connection every
29 180 seconds. In conjunction with ServerAliveCountMax ensures that if the
30 connection dies, Autotest will bail out quickly. Originally tried 60 secs,
31 but saw frequent job ABORTS where the test completed successfully.
Dale Curtiscb7bfaf2011-06-07 16:21:57 -070032
Chris Sosaf7fcd6e2011-09-27 17:30:47 -070033 - ServerAliveCountMax=3; consistency with remote_access.sh.
34
35 - ConnectAttempts=4; reduce flakiness in connection errors; consistency
36 with remote_access.sh.
Dale Curtiscb7bfaf2011-06-07 16:21:57 -070037
38 - UserKnownHostsFile=/dev/null; we don't care about the keys. Host keys
39 change with every new installation, don't waste memory/space saving them.
Chris Sosaf7fcd6e2011-09-27 17:30:47 -070040
41 - SSH protocol forced to 2; needed for ServerAliveInterval.
Dale Curtiscb7bfaf2011-06-07 16:21:57 -070042 """
43 base_command = ('/usr/bin/ssh -a -x %s -o StrictHostKeyChecking=no'
44 ' -o UserKnownHostsFile=/dev/null -o BatchMode=yes'
Chris Sosaf7fcd6e2011-09-27 17:30:47 -070045 ' -o ConnectTimeout=30 -o ServerAliveInterval=180'
46 ' -o ServerAliveCountMax=3 -o ConnectionAttempts=4'
47 ' -o Protocol=2 -l %s -p %d')
Dale Curtiscb7bfaf2011-06-07 16:21:57 -070048 return base_command % (opts, user, port)
J. Richard Barnette45e93de2012-04-11 17:24:15 -070049
50
51class SiteHost(remote.RemoteHost):
52 """Chromium OS specific subclass of Host."""
53
54 _parser = autoserv_parser.autoserv_parser
55
56 # Time to wait for new kernel to be marked successful.
Chris Masone163cead2012-05-16 11:49:48 -070057 _KERNEL_UPDATE_TIMEOUT = 120
J. Richard Barnette45e93de2012-04-11 17:24:15 -070058
59 # Ephemeral file to indicate that an update has just occurred.
60 _JUST_UPDATED_FLAG = '/tmp/just_updated'
61
J. Richard Barnette134ec2c2012-04-25 12:59:37 -070062 # Timeout values used in test_wait_for_sleep(), et al.
63 #
64 # _RESUME_TIMEOUT has to be big enough to allow time for WiFi
65 # reconnection.
66 #
67 # _REBOOT_TIMEOUT has to be big enough to allow time for the 30
68 # second dev-mode screen delay _and_ time for network startup,
69 # which takes several seconds longer than boot.
70 #
71 # TODO(jrbarnette): None of these times have been thoroughly
72 # tested empirically; if timeouts are a problem, increasing the
73 # time limit really might be the right answer.
74 _SLEEP_TIMEOUT = 2
75 _RESUME_TIMEOUT = 5
76 _SHUTDOWN_TIMEOUT = 5
77 _REBOOT_TIMEOUT = 45
78
79
J. Richard Barnette55fb8062012-05-23 10:29:31 -070080 def _initialize(self, hostname, servo_host=None, servo_port=None,
81 *args, **dargs):
J. Richard Barnette67ccb872012-04-19 16:34:56 -070082 """Initialize superclasses, and |self.servo|.
83
84 For creating the host servo object, there are three
85 possibilities: First, if the host is a lab system known to
86 have a servo board, we connect to that servo unconditionally.
87 Second, if we're called from a control file that requires
J. Richard Barnette55fb8062012-05-23 10:29:31 -070088 servo features for testing, it will pass settings for
89 `servo_host`, `servo_port`, or both. If neither of these
90 cases apply, `self.servo` will be `None`.
J. Richard Barnette67ccb872012-04-19 16:34:56 -070091
92 """
J. Richard Barnette45e93de2012-04-11 17:24:15 -070093 super(SiteHost, self)._initialize(hostname=hostname,
94 *args, **dargs)
J. Richard Barnette1d78b012012-05-15 13:56:30 -070095 self._xmlrpc_proxy_map = {}
J. Richard Barnette67ccb872012-04-19 16:34:56 -070096 self.servo = servo.Servo.get_lab_servo(hostname)
J. Richard Barnette55fb8062012-05-23 10:29:31 -070097 if not self.servo:
98 # The Servo constructor generally doesn't accept 'None'
99 # for its parameters.
100 if servo_host is not None:
101 if servo_port is not None:
102 self.servo = servo.Servo(servo_host=servo_host,
103 servo_port=servo_port)
104 else:
105 self.servo = servo.Servo(servo_host=servo_host)
106 elif servo_port is not None:
107 self.servo = servo.Servo(servo_port=servo_port)
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700108
109
110 def machine_install(self, update_url=None, force_update=False):
111 if not update_url and self._parser.options.image:
112 update_url = self._parser.options.image
113 elif not update_url:
114 raise autoupdater.ChromiumOSError(
115 'Update failed. No update URL provided.')
116
117 # Attempt to update the system.
118 updater = autoupdater.ChromiumOSUpdater(update_url, host=self)
119 if updater.run_update(force_update):
120 # Figure out active and inactive kernel.
121 active_kernel, inactive_kernel = updater.get_kernel_state()
122
123 # Ensure inactive kernel has higher priority than active.
124 if (updater.get_kernel_priority(inactive_kernel)
125 < updater.get_kernel_priority(active_kernel)):
126 raise autoupdater.ChromiumOSError(
127 'Update failed. The priority of the inactive kernel'
128 ' partition is less than that of the active kernel'
129 ' partition.')
130
131 # Updater has returned, successfully, reboot the host.
132 self.reboot(timeout=60, wait=True)
133
134 # Following the reboot, verify the correct version.
135 updater.check_version()
136
137 # Figure out newly active kernel.
138 new_active_kernel, _ = updater.get_kernel_state()
139
140 # Ensure that previously inactive kernel is now the active kernel.
141 if new_active_kernel != inactive_kernel:
142 raise autoupdater.ChromiumOSError(
143 'Update failed. New kernel partition is not active after'
144 ' boot.')
145
146 host_attributes = site_host_attributes.HostAttributes(self.hostname)
147 if host_attributes.has_chromeos_firmware:
148 # Wait until tries == 0 and success, or until timeout.
149 utils.poll_for_condition(
150 lambda: (updater.get_kernel_tries(new_active_kernel) == 0
151 and updater.get_kernel_success(new_active_kernel)),
152 exception=autoupdater.ChromiumOSError(
153 'Update failed. Timed out waiting for system to mark'
154 ' new kernel as successful.'),
155 timeout=self._KERNEL_UPDATE_TIMEOUT, sleep_interval=5)
156
157 # TODO(dalecurtis): Hack for R12 builds to make sure BVT runs of
158 # platform_Shutdown pass correctly.
159 if updater.update_version.startswith('0.12'):
160 self.reboot(timeout=60, wait=True)
161
162 # Mark host as recently updated. Hosts are rebooted at the end of
163 # every test cycle which will remove the file.
164 self.run('touch %s' % self._JUST_UPDATED_FLAG)
165
166 # Clean up any old autotest directories which may be lying around.
167 for path in global_config.global_config.get_config_value(
168 'AUTOSERV', 'client_autodir_paths', type=list):
169 self.run('rm -rf ' + path)
170
171
172 def has_just_updated(self):
173 """Indicates whether the host was updated within this boot."""
174 # Check for the existence of the just updated flag file.
175 return self.run(
176 '[ -f %s ] && echo T || echo F'
177 % self._JUST_UPDATED_FLAG).stdout.strip() == 'T'
178
179
J. Richard Barnette1d78b012012-05-15 13:56:30 -0700180 def close(self):
181 super(SiteHost, self).close()
182 self.xmlrpc_disconnect_all()
183
184
J. Richard Barnette45e93de2012-04-11 17:24:15 -0700185 def cleanup(self):
186 """Special cleanup method to make sure hosts always get power back."""
187 super(SiteHost, self).cleanup()
188 remote_power = site_remote_power.RemotePower(self.hostname)
189 if remote_power:
190 remote_power.set_power_on()
191
192
193 def verify_software(self):
194 """Ensure the stateful partition has space for Autotest and updates.
195
196 Similar to what is done by AbstractSSH, except instead of checking the
197 Autotest installation path, just check the stateful partition.
198
199 Checking the stateful partition is preferable in case it has been wiped,
200 resulting in an Autotest installation path which doesn't exist and isn't
201 writable. We still want to pass verify in this state since the partition
202 will be recovered with the next install.
203 """
204 super(SiteHost, self).verify_software()
205 self.check_diskspace(
206 '/mnt/stateful_partition',
207 global_config.global_config.get_config_value(
208 'SERVER', 'gb_diskspace_required', type=int,
209 default=20))
J. Richard Barnette134ec2c2012-04-25 12:59:37 -0700210
211
J. Richard Barnette1d78b012012-05-15 13:56:30 -0700212 def xmlrpc_connect(self, command, port, cleanup=None):
213 """Connect to an XMLRPC server on the host.
214
215 The `command` argument should be a simple shell command that
216 starts an XMLRPC server on the given `port`. The command
217 must not daemonize, and must terminate cleanly on SIGTERM.
218 The command is started in the background on the host, and a
219 local XMLRPC client for the server is created and returned
220 to the caller.
221
222 Note that the process of creating an XMLRPC client makes no
223 attempt to connect to the remote server; the caller is
224 responsible for determining whether the server is running
225 correctly, and is ready to serve requests.
226
227 @param command Shell command to start the server.
228 @param port Port number on which the server is expected to
229 be serving.
230 """
231 self.xmlrpc_disconnect(port)
232
233 # Chrome OS on the target closes down most external ports
234 # for security. We could open the port, but doing that
235 # would conflict with security tests that check that only
236 # expected ports are open. So, to get to the port on the
237 # target we use an ssh tunnel.
238 local_port = utils.get_unused_port()
239 tunnel_options = '-n -N -q -L %d:localhost:%d' % (local_port, port)
240 ssh_cmd = make_ssh_command(opts=tunnel_options)
241 tunnel_cmd = '%s %s' % (ssh_cmd, self.hostname)
242 logging.debug('Full tunnel command: %s', tunnel_cmd)
243 tunnel_proc = subprocess.Popen(tunnel_cmd, shell=True, close_fds=True)
244 logging.debug('Started XMLRPC tunnel, local = %d'
245 ' remote = %d, pid = %d',
246 local_port, port, tunnel_proc.pid)
247
248 # Start the server on the host. Redirection in the command
249 # below is necessary, because 'ssh' won't terminate until
250 # background child processes close stdin, stdout, and
251 # stderr.
252 remote_cmd = '( %s ) </dev/null >/dev/null 2>&1 & echo $!' % command
253 remote_pid = self.run(remote_cmd).stdout.rstrip('\n')
254 logging.debug('Started XMLRPC server on host %s, pid = %s',
255 self.hostname, remote_pid)
256
257 self._xmlrpc_proxy_map[port] = (cleanup, tunnel_proc)
258 rpc_url = 'http://localhost:%d' % local_port
259 return xmlrpclib.ServerProxy(rpc_url, allow_none=True)
260
261
262 def xmlrpc_disconnect(self, port):
263 """Disconnect from an XMLRPC server on the host.
264
265 Terminates the remote XMLRPC server previously started for
266 the given `port`. Also closes the local ssh tunnel created
267 for the connection to the host. This function does not
268 directly alter the state of a previously returned XMLRPC
269 client object; however disconnection will cause all
270 subsequent calls to methods on the object to fail.
271
272 This function does nothing if requested to disconnect a port
273 that was not previously connected via `self.xmlrpc_connect()`
274
275 @param port Port number passed to a previous call to
276 `xmlrpc_connect()`
277 """
278 if port not in self._xmlrpc_proxy_map:
279 return
280 entry = self._xmlrpc_proxy_map[port]
281 remote_name = entry[0]
282 tunnel_proc = entry[1]
283 if remote_name:
284 # We use 'pkill' to find our target process rather than
285 # a PID, because the host may have rebooted since
286 # connecting, and we don't want to kill an innocent
287 # process with the same PID.
288 #
289 # 'pkill' helpfully exits with status 1 if no target
290 # process is found, for which run() will throw an
291 # exception. We don't want that, so we ignore the
292 # status.
293 self.run("pkill -f '%s'" % remote_name, ignore_status=True)
294
295 if tunnel_proc.poll() is None:
296 tunnel_proc.terminate()
297 logging.debug('Terminated tunnel, pid %d', tunnel_proc.pid)
298 else:
299 logging.debug('Tunnel pid %d terminated early, status %d',
300 tunnel_proc.pid, tunnel_proc.returncode)
301 del self._xmlrpc_proxy_map[port]
302
303
304 def xmlrpc_disconnect_all(self):
305 """Disconnect all known XMLRPC proxy ports."""
306 for port in self._xmlrpc_proxy_map.keys():
307 self.xmlrpc_disconnect(port)
308
309
J. Richard Barnette134ec2c2012-04-25 12:59:37 -0700310 def _ping_is_up(self):
311 """Ping the host once, and return whether it responded."""
312 return utils.ping(self.hostname, tries=1, deadline=1) == 0
313
314
315 def _ping_wait_down(self, timeout):
316 """Wait until the host no longer responds to `ping`.
317
318 @param timeout Minimum time to allow before declaring the
319 host to be non-responsive.
320 """
321
322 # This function is a slightly faster version of wait_down().
323 #
324 # In AbstractSSHHost.wait_down(), `ssh` is used to determine
325 # whether the host is down. In some situations (mine, at
326 # least), `ssh` can take over a minute to determine that the
327 # host is down. The `ping` command answers the question
328 # faster, so we use that here instead.
329 #
330 # There is no equivalent for wait_up(), because a target that
331 # answers to `ping` won't necessarily respond to `ssh`.
332 end_time = time.time() + timeout
333 while time.time() <= end_time:
334 if not self._ping_is_up():
335 return True
336
337 # If the timeout is short relative to the run time of
338 # _ping_is_up(), we might be prone to false failures for
339 # lack of checking frequently enough. To be safe, we make
340 # one last check _after_ the deadline.
341 return not self._ping_is_up()
342
343
344 def test_wait_for_sleep(self):
345 """Wait for the client to enter low-power sleep mode.
346
347 The test for "is asleep" can't distinguish a system that is
348 powered off; to confirm that the unit was asleep, it is
349 necessary to force resume, and then call
350 `test_wait_for_resume()`.
351
352 This function is expected to be called from a test as part
353 of a sequence like the following:
354
355 ~~~~~~~~
356 boot_id = host.get_boot_id()
357 # trigger sleep on the host
358 host.test_wait_for_sleep()
359 # trigger resume on the host
360 host.test_wait_for_resume(boot_id)
361 ~~~~~~~~
362
363 @exception TestFail The host did not go to sleep within
364 the allowed time.
365 """
366 if not self._ping_wait_down(timeout=self._SLEEP_TIMEOUT):
367 raise error.TestFail(
368 'client failed to sleep after %d seconds' %
369 self._SLEEP_TIMEOUT)
370
371
372 def test_wait_for_resume(self, old_boot_id):
373 """Wait for the client to resume from low-power sleep mode.
374
375 The `old_boot_id` parameter should be the value from
376 `get_boot_id()` obtained prior to entering sleep mode. A
377 `TestFail` exception is raised if the boot id changes.
378
379 See @ref test_wait_for_sleep for more on this function's
380 usage.
381
382 @param[in] old_boot_id A boot id value obtained before the
383 target host went to sleep.
384
385 @exception TestFail The host did not respond within the
386 allowed time.
387 @exception TestFail The host responded, but the boot id test
388 indicated a reboot rather than a sleep
389 cycle.
390 """
391 if not self.wait_up(timeout=self._RESUME_TIMEOUT):
392 raise error.TestFail(
393 'client failed to resume from sleep after %d seconds' %
394 self._RESUME_TIMEOUT)
395 else:
396 new_boot_id = self.get_boot_id()
397 if new_boot_id != old_boot_id:
398 raise error.TestFail(
399 'client rebooted, but sleep was expected'
400 ' (old boot %s, new boot %s)'
401 % (old_boot_id, new_boot_id))
402
403
404 def test_wait_for_shutdown(self):
405 """Wait for the client to shut down.
406
407 The test for "has shut down" can't distinguish a system that
408 is merely asleep; to confirm that the unit was down, it is
409 necessary to force boot, and then call test_wait_for_boot().
410
411 This function is expected to be called from a test as part
412 of a sequence like the following:
413
414 ~~~~~~~~
415 boot_id = host.get_boot_id()
416 # trigger shutdown on the host
417 host.test_wait_for_shutdown()
418 # trigger boot on the host
419 host.test_wait_for_boot(boot_id)
420 ~~~~~~~~
421
422 @exception TestFail The host did not shut down within the
423 allowed time.
424 """
425 if not self._ping_wait_down(timeout=self._SHUTDOWN_TIMEOUT):
426 raise error.TestFail(
427 'client failed to shut down after %d seconds' %
428 self._SHUTDOWN_TIMEOUT)
429
430
431 def test_wait_for_boot(self, old_boot_id=None):
432 """Wait for the client to boot from cold power.
433
434 The `old_boot_id` parameter should be the value from
435 `get_boot_id()` obtained prior to shutting down. A
436 `TestFail` exception is raised if the boot id does not
437 change. The boot id test is omitted if `old_boot_id` is not
438 specified.
439
440 See @ref test_wait_for_shutdown for more on this function's
441 usage.
442
443 @param[in] old_boot_id A boot id value obtained before the
444 shut down.
445
446 @exception TestFail The host did not respond within the
447 allowed time.
448 @exception TestFail The host responded, but the boot id test
449 indicated that there was no reboot.
450 """
451 if not self.wait_up(timeout=self._REBOOT_TIMEOUT):
452 raise error.TestFail(
453 'client failed to reboot after %d seconds' %
454 self._REBOOT_TIMEOUT)
455 elif old_boot_id:
456 if self.get_boot_id() == old_boot_id:
457 raise error.TestFail(
458 'client is back up, but did not reboot'
459 ' (boot %s)' % old_boot_id)