blob: 54ab68b690b861b1316f411f367552215dbd2ed7 [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.
J. Richard Barnette2f83d712012-04-23 14:31:45 -070043 'client_test': 'desktopui_PyAutoInstall',
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +080044 # 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
Todd Broch0edf7e12012-06-14 09:36:15 -0700110 self.servo = servo.Servo()
J. Richard Barnette67ccb872012-04-19 16:34:56 -0700111 self._servo_is_local = True
112
113
114 def _release_servo(self):
115 """Clean up `self.servo` if it is locally attached."""
J. Richard Barnette67ccb872012-04-19 16:34:56 -0700116 self._servo_is_local = False
117
118
119 def initialize(self, host, cmdline_args, use_pyauto=False, use_faft=False):
120 """Create a Servo object and install the dependency.
121
122 If use_pyauto/use_faft is True the PyAuto/FAFTClient dependency is
123 installed on the client and a remote PyAuto/FAFTClient server is
124 launched and connected.
125 """
Chris Sosa33320a82011-10-24 14:28:32 -0700126 # Initialize servotest args.
127 self._client = host;
128 self._remote_infos['pyauto']['used'] = use_pyauto
129 self._remote_infos['faft']['used'] = use_faft
130
J. Richard Barnette67ccb872012-04-19 16:34:56 -0700131 self._init_servo(host, cmdline_args)
132
Chrome Bot9a1137d2011-07-19 14:35:00 -0700133 # Initializes dut, may raise AssertionError if pre-defined gpio
134 # sequence to set GPIO's fail. Autotest does not handle exception
135 # throwing in initialize and will cause a test to hang.
136 try:
137 self.servo.initialize_dut()
Chris Sosa33320a82011-10-24 14:28:32 -0700138 except (AssertionError, xmlrpclib.Fault) as e:
J. Richard Barnette67ccb872012-04-19 16:34:56 -0700139 self._release_servo()
Chrome Bot9a1137d2011-07-19 14:35:00 -0700140 raise error.TestFail(e)
141
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800142 # Install PyAuto/FAFTClient dependency.
143 for info in self._remote_infos.itervalues():
144 if info['used']:
145 if not self._autotest_client:
146 self._autotest_client = autotest.Autotest(self._client)
147 self._autotest_client.run_test(info['client_test'])
148 self.launch_client(info)
Craig Harrison2b6c6fc2011-06-23 10:34:02 -0700149
150
J. Richard Barnette134ec2c2012-04-25 12:59:37 -0700151 def _ping_test(self, hostname, timeout=5):
Craig Harrison2b6c6fc2011-06-23 10:34:02 -0700152 """Verify whether a host responds to a ping.
153
154 Args:
155 hostname: Hostname to ping.
156 timeout: Time in seconds to wait for a response.
157 """
Tom Wai-Hong Tam4a257e52011-11-12 08:36:22 +0800158 with open(os.devnull, 'w') as fnull:
159 return subprocess.call(
160 ['ping', '-c', '1', '-W', str(timeout), hostname],
161 stdout=fnull, stderr=fnull) == 0
Craig Harrison2b6c6fc2011-06-23 10:34:02 -0700162
163
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800164 def launch_client(self, info):
165 """Launch a remote process on client and set up an xmlrpc connection.
166
167 Args:
168 info: A dict of remote info, see the definition of self._remote_infos.
169 """
170 assert info['used'], \
171 'Remote %s dependency not installed.' % info['ref_name']
172 if not info['ssh_tunnel'] or info['ssh_tunnel'].poll() is not None:
173 self._launch_ssh_tunnel(info)
174 assert info['ssh_tunnel'] and info['ssh_tunnel'].poll() is None, \
Craig Harrison91944552011-08-04 14:09:55 -0700175 'The SSH tunnel is not up.'
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800176
177 # Launch RPC server remotely.
178 self._kill_remote_process(info)
179 logging.info('Client command: %s' % info['remote_command'])
180 info['remote_process'] = subprocess.Popen([
Tom Wai-Hong Tam4a257e52011-11-12 08:36:22 +0800181 'ssh -n -q %s root@%s \'%s\'' % (info['ssh_config'],
Tom Wai-Hong Tame2c66122011-10-25 17:21:35 +0800182 self._client.ip, info['remote_command'])], shell=True)
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800183
184 # Connect to RPC object.
185 logging.info('Connecting to client RPC server...')
186 remote_url = 'http://localhost:%s' % info['port']
187 setattr(self, info['ref_name'],
188 xmlrpclib.ServerProxy(remote_url, allow_none=True))
189 logging.info('Server proxy: %s' % remote_url)
190
Craig Harrison91944552011-08-04 14:09:55 -0700191 # Poll for client RPC server to come online.
192 timeout = 10
193 succeed = False
194 while timeout > 0 and not succeed:
195 time.sleep(2)
196 try:
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800197 remote_object = getattr(self, info['ref_name'])
198 polling_rpc = getattr(remote_object, info['polling_rpc'])
199 polling_rpc()
Craig Harrison91944552011-08-04 14:09:55 -0700200 succeed = True
201 except:
202 timeout -= 1
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800203 assert succeed, 'Timed out connecting to client RPC server.'
Craig Harrison91944552011-08-04 14:09:55 -0700204
205
Tom Wai-Hong Tam7c17ff22011-10-26 09:44:09 +0800206 def wait_for_client(self, install_deps=False):
Craig Harrison91944552011-08-04 14:09:55 -0700207 """Wait for the client to come back online.
208
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800209 New remote processes will be launched if their used flags are enabled.
Tom Wai-Hong Tam7c17ff22011-10-26 09:44:09 +0800210
211 Args:
212 install_deps: If True, install the Autotest dependency when ready.
Craig Harrison91944552011-08-04 14:09:55 -0700213 """
214 timeout = 10
215 # Ensure old ssh connections are terminated.
216 self._terminate_all_ssh()
217 # Wait for the client to come up.
J. Richard Barnette134ec2c2012-04-25 12:59:37 -0700218 while timeout > 0 and not self._ping_test(self._client.ip):
Craig Harrison91944552011-08-04 14:09:55 -0700219 time.sleep(5)
220 timeout -= 1
221 assert timeout, 'Timed out waiting for client to reboot.'
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800222 logging.info('Server: Client machine is up.')
223 # Relaunch remote clients.
224 for name, info in self._remote_infos.iteritems():
225 if info['used']:
Tom Wai-Hong Tambf6aad72011-10-26 09:50:41 +0800226 # This 5s delay to ensure sshd launched after network is up.
227 # TODO(waihong) Investigate pinging port via netcat or nmap
228 # to interrogate client for when sshd has launched.
229 time.sleep(5)
Tom Wai-Hong Tam7c17ff22011-10-26 09:44:09 +0800230 if install_deps:
231 if not self._autotest_client:
232 self._autotest_client = autotest.Autotest(self._client)
233 self._autotest_client.run_test(info['client_test'])
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800234 self.launch_client(info)
235 logging.info('Server: Relaunched remote %s.' % name)
Craig Harrison91944552011-08-04 14:09:55 -0700236
237
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800238 def wait_for_client_offline(self, timeout=30):
239 """Wait for the client to come offline.
240
241 Args:
242 timeout: Time in seconds to wait the client to come offline.
243 """
244 # Wait for the client to come offline.
J. Richard Barnette134ec2c2012-04-25 12:59:37 -0700245 while timeout > 0 and self._ping_test(self._client.ip, timeout=1):
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800246 time.sleep(1)
247 timeout -= 1
248 assert timeout, 'Timed out waiting for client offline.'
249 logging.info('Server: Client machine is offline.')
250
251
Vic Yang4e0d1f72012-05-24 15:11:11 +0800252 def kill_remote(self):
253 """Call remote cleanup and kill ssh."""
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800254 for info in self._remote_infos.itervalues():
255 if info['remote_process'] and info['remote_process'].poll() is None:
256 remote_object = getattr(self, info['ref_name'])
257 remote_object.cleanup()
Craig Harrison91944552011-08-04 14:09:55 -0700258 self._terminate_all_ssh()
259
260
Vic Yang4e0d1f72012-05-24 15:11:11 +0800261 def cleanup(self):
262 """Delete the Servo object, call remote cleanup, and kill ssh."""
263 self._release_servo()
264 self.kill_remote()
265
266
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800267 def _launch_ssh_tunnel(self, info):
268 """Establish an ssh tunnel for connecting to the remote RPC server.
269
270 Args:
271 info: A dict of remote info, see the definition of self._remote_infos.
272 """
273 if not info['ssh_tunnel'] or info['ssh_tunnel'].poll() is not None:
Tom Wai-Hong Tame2c66122011-10-25 17:21:35 +0800274 info['ssh_tunnel'] = subprocess.Popen([
Tom Wai-Hong Tam4a257e52011-11-12 08:36:22 +0800275 'ssh -N -n -q %s -L %s:localhost:%s root@%s' %
Tom Wai-Hong Tame2c66122011-10-25 17:21:35 +0800276 (info['ssh_config'], info['port'], info['port'],
277 self._client.ip)], shell=True)
Craig Harrison91944552011-08-04 14:09:55 -0700278
279
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800280 def _kill_remote_process(self, info):
281 """Ensure the remote process and local ssh process are terminated.
282
283 Args:
284 info: A dict of remote info, see the definition of self._remote_infos.
285 """
286 kill_cmd = 'pkill -f %s' % info['remote_command_short']
Tom Wai-Hong Tam4a257e52011-11-12 08:36:22 +0800287 subprocess.call(['ssh -n -q %s root@%s \'%s\'' %
Tom Wai-Hong Tame2c66122011-10-25 17:21:35 +0800288 (info['ssh_config'], self._client.ip, kill_cmd)],
Craig Harrison91944552011-08-04 14:09:55 -0700289 shell=True)
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800290 if info['remote_process'] and info['remote_process'].poll() is None:
291 info['remote_process'].terminate()
Craig Harrison91944552011-08-04 14:09:55 -0700292
293
294 def _terminate_all_ssh(self):
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800295 """Terminate all ssh connections associated with remote processes."""
296 for info in self._remote_infos.itervalues():
297 if info['ssh_tunnel'] and info['ssh_tunnel'].poll() is None:
298 info['ssh_tunnel'].terminate()
299 self._kill_remote_process(info)