blob: 2138b1a38799bc37f8d38cfb7fc6920a181b1838 [file] [log] [blame]
J. Richard Barnette67ccb872012-04-19 16:34:56 -07001# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
Craig Harrison2b6c6fc2011-06-23 10:34:02 -07002# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
Craig Harrison91944552011-08-04 14:09:55 -07005import logging
Tom Wai-Hong Tam4a257e52011-11-12 08:36:22 +08006import os
Todd Brochf24d2782011-08-19 10:55:41 -07007import re
Craig Harrison2b6c6fc2011-06-23 10:34:02 -07008import subprocess
Craig Harrison91944552011-08-04 14:09:55 -07009import time
10import xmlrpclib
Craig Harrison2b6c6fc2011-06-23 10:34:02 -070011
Chrome Bot9a1137d2011-07-19 14:35:00 -070012from autotest_lib.client.common_lib import error
Chris Sosa8ee1d592011-08-14 16:50:31 -070013from autotest_lib.server import autotest, site_host_attributes, test, utils
14from autotest_lib.server.cros import servo
Craig Harrison91944552011-08-04 14:09:55 -070015
Craig Harrison2b6c6fc2011-06-23 10:34:02 -070016class ServoTest(test.test):
17 """AutoTest test class that creates and destroys a servo object.
18
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +080019 Servo-based server side AutoTests can inherit from this object.
20 There are 2 remote clients supported:
21 If use_pyauto flag is True, a remote PyAuto client will be launched;
22 If use_faft flag is Ture, a remote FAFT client will be launched.
Craig Harrison2b6c6fc2011-06-23 10:34:02 -070023 """
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +080024 version = 2
J. Richard Barnette67ccb872012-04-19 16:34:56 -070025
Craig Harrison91944552011-08-04 14:09:55 -070026 # Exposes RPC access to a remote PyAuto client.
27 pyauto = None
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +080028 # Exposes RPC access to a remote FAFT client.
29 faft_client = None
30
Craig Harrison91944552011-08-04 14:09:55 -070031 # Autotest references to the client.
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +080032 _autotest_client = None
33 # Remote client info list.
34 _remote_infos = {
35 'pyauto': {
36 # Used or not.
37 'used': False,
38 # Reference name of RPC object in this class.
39 'ref_name': 'pyauto',
40 # Port number of the remote RPC.
41 'port': 9988,
42 # Client test for installing dependency.
43 'client_test': 'desktopui_ServoPyAuto',
44 # The remote command to be run.
Scott Zawalski9a985562012-04-03 17:47:30 -040045 'remote_command': 'python /usr/local/autotest/cros/remote_pyauto.py'
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +080046 ' --no-http-server',
47 # The short form of remote command, used by pkill.
Scott Zawalski9a985562012-04-03 17:47:30 -040048 'remote_command_short': 'remote_pyauto',
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +080049 # The remote process info.
50 'remote_process': None,
51 # The ssh tunnel process info.
52 'ssh_tunnel': None,
53 # Polling RPC function name for testing the server availability.
54 'polling_rpc': 'IsLinux',
Tom Wai-Hong Tame2c66122011-10-25 17:21:35 +080055 # Additional SSH options.
56 'ssh_config': '-o StrictHostKeyChecking=no ',
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +080057 },
58 'faft': {
59 'used': False,
60 'ref_name': 'faft_client',
61 'port': 9990,
62 'client_test': 'firmware_FAFTClient',
63 'remote_command': 'python /usr/local/autotest/cros/faft_client.py',
64 'remote_command_short': 'faft_client',
65 'remote_process': None,
66 'ssh_tunnel': None,
67 'polling_rpc': 'is_available',
Tom Wai-Hong Tame2c66122011-10-25 17:21:35 +080068 'ssh_config': '-o StrictHostKeyChecking=no '
69 '-o UserKnownHostsFile=/dev/null ',
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +080070 },
71 }
Craig Harrison2b6c6fc2011-06-23 10:34:02 -070072
J. Richard Barnette67ccb872012-04-19 16:34:56 -070073 def _init_servo(self, host, cmdline_args):
74 """Initialize `self.servo`.
Craig Harrison91944552011-08-04 14:09:55 -070075
J. Richard Barnette67ccb872012-04-19 16:34:56 -070076 If the host has an attached servo object, use that.
77 Otherwise assume that there's a locally attached servo
78 device, and start servod on localhost.
79
Todd Brochf24d2782011-08-19 10:55:41 -070080 """
J. Richard Barnette67ccb872012-04-19 16:34:56 -070081 if host.servo:
82 self.servo = host.servo
83 self._servo_is_local = False
84 return
85
Todd Brochf24d2782011-08-19 10:55:41 -070086 # Assign default arguments for servo invocation.
87 args = {
88 'servo_host': 'localhost', 'servo_port': 9999,
Todd Brochd50ac042012-03-19 16:58:02 -070089 'xml_config': [], 'servo_vid': None, 'servo_pid': None,
Todd Brochf24d2782011-08-19 10:55:41 -070090 'servo_serial': None, 'use_pyauto': False}
91
92 # Parse arguments from AFE and override servo defaults above.
93 client_attributes = site_host_attributes.HostAttributes(host.hostname)
94 if hasattr(site_host_attributes, 'servo_serial'):
95 args['servo_serial'] = client_attributes.servo_serial
96
97 # Parse arguments from command line and override previous AFE or servo
98 # defaults
99 for arg in cmdline_args:
100 match = re.search("^(\w+)=(.+)", arg)
101 if match:
Tom Wai-Hong Tam5fc2c792011-11-03 13:05:39 +0800102 key = match.group(1)
103 val = match.group(2)
104 # Support multiple xml_config by appending it to a list.
105 if key == 'xml_config':
106 args[key].append(val)
107 else:
108 args[key] = val
Todd Brochf24d2782011-08-19 10:55:41 -0700109
J. Richard Barnette67ccb872012-04-19 16:34:56 -0700110 self.servo = servo.Servo(
111 args['servo_host'], args['servo_port'], args['xml_config'],
112 args['servo_vid'], args['servo_pid'], args['servo_serial'])
113 self._servo_is_local = True
114
115
116 def _release_servo(self):
117 """Clean up `self.servo` if it is locally attached."""
118 if self._servo_is_local:
119 del self.servo
120 self._servo_is_local = False
121
122
123 def initialize(self, host, cmdline_args, use_pyauto=False, use_faft=False):
124 """Create a Servo object and install the dependency.
125
126 If use_pyauto/use_faft is True the PyAuto/FAFTClient dependency is
127 installed on the client and a remote PyAuto/FAFTClient server is
128 launched and connected.
129 """
Chris Sosa33320a82011-10-24 14:28:32 -0700130 # Initialize servotest args.
131 self._client = host;
132 self._remote_infos['pyauto']['used'] = use_pyauto
133 self._remote_infos['faft']['used'] = use_faft
134
J. Richard Barnette67ccb872012-04-19 16:34:56 -0700135 self._init_servo(host, cmdline_args)
136
Chrome Bot9a1137d2011-07-19 14:35:00 -0700137 # Initializes dut, may raise AssertionError if pre-defined gpio
138 # sequence to set GPIO's fail. Autotest does not handle exception
139 # throwing in initialize and will cause a test to hang.
140 try:
141 self.servo.initialize_dut()
Chris Sosa33320a82011-10-24 14:28:32 -0700142 except (AssertionError, xmlrpclib.Fault) as e:
J. Richard Barnette67ccb872012-04-19 16:34:56 -0700143 self._release_servo()
Chrome Bot9a1137d2011-07-19 14:35:00 -0700144 raise error.TestFail(e)
145
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800146 # Install PyAuto/FAFTClient dependency.
147 for info in self._remote_infos.itervalues():
148 if info['used']:
149 if not self._autotest_client:
150 self._autotest_client = autotest.Autotest(self._client)
151 self._autotest_client.run_test(info['client_test'])
152 self.launch_client(info)
Craig Harrison2b6c6fc2011-06-23 10:34:02 -0700153
154
155 def assert_ping(self):
156 """Ping to assert that the device is up."""
Craig Harrison91944552011-08-04 14:09:55 -0700157 assert self.ping_test(self._client.ip)
Craig Harrison2b6c6fc2011-06-23 10:34:02 -0700158
159
160 def assert_pingfail(self):
161 """Ping to assert that the device is down."""
Craig Harrison91944552011-08-04 14:09:55 -0700162 assert not self.ping_test(self._client.ip)
Craig Harrison2b6c6fc2011-06-23 10:34:02 -0700163
164
165 def ping_test(self, hostname, timeout=5):
166 """Verify whether a host responds to a ping.
167
168 Args:
169 hostname: Hostname to ping.
170 timeout: Time in seconds to wait for a response.
171 """
Tom Wai-Hong Tam4a257e52011-11-12 08:36:22 +0800172 with open(os.devnull, 'w') as fnull:
173 return subprocess.call(
174 ['ping', '-c', '1', '-W', str(timeout), hostname],
175 stdout=fnull, stderr=fnull) == 0
Craig Harrison2b6c6fc2011-06-23 10:34:02 -0700176
177
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800178 def launch_client(self, info):
179 """Launch a remote process on client and set up an xmlrpc connection.
180
181 Args:
182 info: A dict of remote info, see the definition of self._remote_infos.
183 """
184 assert info['used'], \
185 'Remote %s dependency not installed.' % info['ref_name']
186 if not info['ssh_tunnel'] or info['ssh_tunnel'].poll() is not None:
187 self._launch_ssh_tunnel(info)
188 assert info['ssh_tunnel'] and info['ssh_tunnel'].poll() is None, \
Craig Harrison91944552011-08-04 14:09:55 -0700189 'The SSH tunnel is not up.'
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800190
191 # Launch RPC server remotely.
192 self._kill_remote_process(info)
193 logging.info('Client command: %s' % info['remote_command'])
194 info['remote_process'] = subprocess.Popen([
Tom Wai-Hong Tam4a257e52011-11-12 08:36:22 +0800195 'ssh -n -q %s root@%s \'%s\'' % (info['ssh_config'],
Tom Wai-Hong Tame2c66122011-10-25 17:21:35 +0800196 self._client.ip, info['remote_command'])], shell=True)
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800197
198 # Connect to RPC object.
199 logging.info('Connecting to client RPC server...')
200 remote_url = 'http://localhost:%s' % info['port']
201 setattr(self, info['ref_name'],
202 xmlrpclib.ServerProxy(remote_url, allow_none=True))
203 logging.info('Server proxy: %s' % remote_url)
204
Craig Harrison91944552011-08-04 14:09:55 -0700205 # Poll for client RPC server to come online.
206 timeout = 10
207 succeed = False
208 while timeout > 0 and not succeed:
209 time.sleep(2)
210 try:
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800211 remote_object = getattr(self, info['ref_name'])
212 polling_rpc = getattr(remote_object, info['polling_rpc'])
213 polling_rpc()
Craig Harrison91944552011-08-04 14:09:55 -0700214 succeed = True
215 except:
216 timeout -= 1
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800217 assert succeed, 'Timed out connecting to client RPC server.'
Craig Harrison91944552011-08-04 14:09:55 -0700218
219
Tom Wai-Hong Tam7c17ff22011-10-26 09:44:09 +0800220 def wait_for_client(self, install_deps=False):
Craig Harrison91944552011-08-04 14:09:55 -0700221 """Wait for the client to come back online.
222
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800223 New remote processes will be launched if their used flags are enabled.
Tom Wai-Hong Tam7c17ff22011-10-26 09:44:09 +0800224
225 Args:
226 install_deps: If True, install the Autotest dependency when ready.
Craig Harrison91944552011-08-04 14:09:55 -0700227 """
228 timeout = 10
229 # Ensure old ssh connections are terminated.
230 self._terminate_all_ssh()
231 # Wait for the client to come up.
232 while timeout > 0 and not self.ping_test(self._client.ip):
233 time.sleep(5)
234 timeout -= 1
235 assert timeout, 'Timed out waiting for client to reboot.'
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800236 logging.info('Server: Client machine is up.')
237 # Relaunch remote clients.
238 for name, info in self._remote_infos.iteritems():
239 if info['used']:
Tom Wai-Hong Tambf6aad72011-10-26 09:50:41 +0800240 # This 5s delay to ensure sshd launched after network is up.
241 # TODO(waihong) Investigate pinging port via netcat or nmap
242 # to interrogate client for when sshd has launched.
243 time.sleep(5)
Tom Wai-Hong Tam7c17ff22011-10-26 09:44:09 +0800244 if install_deps:
245 if not self._autotest_client:
246 self._autotest_client = autotest.Autotest(self._client)
247 self._autotest_client.run_test(info['client_test'])
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800248 self.launch_client(info)
249 logging.info('Server: Relaunched remote %s.' % name)
Craig Harrison91944552011-08-04 14:09:55 -0700250
251
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800252 def wait_for_client_offline(self, timeout=30):
253 """Wait for the client to come offline.
254
255 Args:
256 timeout: Time in seconds to wait the client to come offline.
257 """
258 # Wait for the client to come offline.
259 while timeout > 0 and self.ping_test(self._client.ip, timeout=1):
260 time.sleep(1)
261 timeout -= 1
262 assert timeout, 'Timed out waiting for client offline.'
263 logging.info('Server: Client machine is offline.')
264
265
Craig Harrison2b6c6fc2011-06-23 10:34:02 -0700266 def cleanup(self):
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800267 """Delete the Servo object, call remote cleanup, and kill ssh."""
J. Richard Barnette67ccb872012-04-19 16:34:56 -0700268 self._release_servo()
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800269 for info in self._remote_infos.itervalues():
270 if info['remote_process'] and info['remote_process'].poll() is None:
271 remote_object = getattr(self, info['ref_name'])
272 remote_object.cleanup()
Craig Harrison91944552011-08-04 14:09:55 -0700273 self._terminate_all_ssh()
274
275
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800276 def _launch_ssh_tunnel(self, info):
277 """Establish an ssh tunnel for connecting to the remote RPC server.
278
279 Args:
280 info: A dict of remote info, see the definition of self._remote_infos.
281 """
282 if not info['ssh_tunnel'] or info['ssh_tunnel'].poll() is not None:
Tom Wai-Hong Tame2c66122011-10-25 17:21:35 +0800283 info['ssh_tunnel'] = subprocess.Popen([
Tom Wai-Hong Tam4a257e52011-11-12 08:36:22 +0800284 'ssh -N -n -q %s -L %s:localhost:%s root@%s' %
Tom Wai-Hong Tame2c66122011-10-25 17:21:35 +0800285 (info['ssh_config'], info['port'], info['port'],
286 self._client.ip)], shell=True)
Craig Harrison91944552011-08-04 14:09:55 -0700287
288
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800289 def _kill_remote_process(self, info):
290 """Ensure the remote process and local ssh process are terminated.
291
292 Args:
293 info: A dict of remote info, see the definition of self._remote_infos.
294 """
295 kill_cmd = 'pkill -f %s' % info['remote_command_short']
Tom Wai-Hong Tam4a257e52011-11-12 08:36:22 +0800296 subprocess.call(['ssh -n -q %s root@%s \'%s\'' %
Tom Wai-Hong Tame2c66122011-10-25 17:21:35 +0800297 (info['ssh_config'], self._client.ip, kill_cmd)],
Craig Harrison91944552011-08-04 14:09:55 -0700298 shell=True)
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800299 if info['remote_process'] and info['remote_process'].poll() is None:
300 info['remote_process'].terminate()
Craig Harrison91944552011-08-04 14:09:55 -0700301
302
303 def _terminate_all_ssh(self):
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800304 """Terminate all ssh connections associated with remote processes."""
305 for info in self._remote_infos.itervalues():
306 if info['ssh_tunnel'] and info['ssh_tunnel'].poll() is None:
307 info['ssh_tunnel'].terminate()
308 self._kill_remote_process(info)