blob: d0afc6841f367f5e928aebf65a826c1c86e646ae [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
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
J. Richard Barnette134ec2c2012-04-25 12:59:37 -0700155 def _ping_test(self, hostname, timeout=5):
Craig Harrison2b6c6fc2011-06-23 10:34:02 -0700156 """Verify whether a host responds to a ping.
157
158 Args:
159 hostname: Hostname to ping.
160 timeout: Time in seconds to wait for a response.
161 """
Tom Wai-Hong Tam4a257e52011-11-12 08:36:22 +0800162 with open(os.devnull, 'w') as fnull:
163 return subprocess.call(
164 ['ping', '-c', '1', '-W', str(timeout), hostname],
165 stdout=fnull, stderr=fnull) == 0
Craig Harrison2b6c6fc2011-06-23 10:34:02 -0700166
167
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800168 def launch_client(self, info):
169 """Launch a remote process on client and set up an xmlrpc connection.
170
171 Args:
172 info: A dict of remote info, see the definition of self._remote_infos.
173 """
174 assert info['used'], \
175 'Remote %s dependency not installed.' % info['ref_name']
176 if not info['ssh_tunnel'] or info['ssh_tunnel'].poll() is not None:
177 self._launch_ssh_tunnel(info)
178 assert info['ssh_tunnel'] and info['ssh_tunnel'].poll() is None, \
Craig Harrison91944552011-08-04 14:09:55 -0700179 'The SSH tunnel is not up.'
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800180
181 # Launch RPC server remotely.
182 self._kill_remote_process(info)
183 logging.info('Client command: %s' % info['remote_command'])
184 info['remote_process'] = subprocess.Popen([
Tom Wai-Hong Tam4a257e52011-11-12 08:36:22 +0800185 'ssh -n -q %s root@%s \'%s\'' % (info['ssh_config'],
Tom Wai-Hong Tame2c66122011-10-25 17:21:35 +0800186 self._client.ip, info['remote_command'])], shell=True)
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800187
188 # Connect to RPC object.
189 logging.info('Connecting to client RPC server...')
190 remote_url = 'http://localhost:%s' % info['port']
191 setattr(self, info['ref_name'],
192 xmlrpclib.ServerProxy(remote_url, allow_none=True))
193 logging.info('Server proxy: %s' % remote_url)
194
Craig Harrison91944552011-08-04 14:09:55 -0700195 # Poll for client RPC server to come online.
196 timeout = 10
197 succeed = False
198 while timeout > 0 and not succeed:
199 time.sleep(2)
200 try:
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800201 remote_object = getattr(self, info['ref_name'])
202 polling_rpc = getattr(remote_object, info['polling_rpc'])
203 polling_rpc()
Craig Harrison91944552011-08-04 14:09:55 -0700204 succeed = True
205 except:
206 timeout -= 1
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800207 assert succeed, 'Timed out connecting to client RPC server.'
Craig Harrison91944552011-08-04 14:09:55 -0700208
209
Tom Wai-Hong Tam7c17ff22011-10-26 09:44:09 +0800210 def wait_for_client(self, install_deps=False):
Craig Harrison91944552011-08-04 14:09:55 -0700211 """Wait for the client to come back online.
212
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800213 New remote processes will be launched if their used flags are enabled.
Tom Wai-Hong Tam7c17ff22011-10-26 09:44:09 +0800214
215 Args:
216 install_deps: If True, install the Autotest dependency when ready.
Craig Harrison91944552011-08-04 14:09:55 -0700217 """
218 timeout = 10
219 # Ensure old ssh connections are terminated.
220 self._terminate_all_ssh()
221 # Wait for the client to come up.
J. Richard Barnette134ec2c2012-04-25 12:59:37 -0700222 while timeout > 0 and not self._ping_test(self._client.ip):
Craig Harrison91944552011-08-04 14:09:55 -0700223 time.sleep(5)
224 timeout -= 1
225 assert timeout, 'Timed out waiting for client to reboot.'
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800226 logging.info('Server: Client machine is up.')
227 # Relaunch remote clients.
228 for name, info in self._remote_infos.iteritems():
229 if info['used']:
Tom Wai-Hong Tambf6aad72011-10-26 09:50:41 +0800230 # This 5s delay to ensure sshd launched after network is up.
231 # TODO(waihong) Investigate pinging port via netcat or nmap
232 # to interrogate client for when sshd has launched.
233 time.sleep(5)
Tom Wai-Hong Tam7c17ff22011-10-26 09:44:09 +0800234 if install_deps:
235 if not self._autotest_client:
236 self._autotest_client = autotest.Autotest(self._client)
237 self._autotest_client.run_test(info['client_test'])
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800238 self.launch_client(info)
239 logging.info('Server: Relaunched remote %s.' % name)
Craig Harrison91944552011-08-04 14:09:55 -0700240
241
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800242 def wait_for_client_offline(self, timeout=30):
243 """Wait for the client to come offline.
244
245 Args:
246 timeout: Time in seconds to wait the client to come offline.
247 """
248 # Wait for the client to come offline.
J. Richard Barnette134ec2c2012-04-25 12:59:37 -0700249 while timeout > 0 and self._ping_test(self._client.ip, timeout=1):
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800250 time.sleep(1)
251 timeout -= 1
252 assert timeout, 'Timed out waiting for client offline.'
253 logging.info('Server: Client machine is offline.')
254
255
Craig Harrison2b6c6fc2011-06-23 10:34:02 -0700256 def cleanup(self):
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800257 """Delete the Servo object, call remote cleanup, and kill ssh."""
J. Richard Barnette67ccb872012-04-19 16:34:56 -0700258 self._release_servo()
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800259 for info in self._remote_infos.itervalues():
260 if info['remote_process'] and info['remote_process'].poll() is None:
261 remote_object = getattr(self, info['ref_name'])
262 remote_object.cleanup()
Craig Harrison91944552011-08-04 14:09:55 -0700263 self._terminate_all_ssh()
264
265
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800266 def _launch_ssh_tunnel(self, info):
267 """Establish an ssh tunnel for connecting to the remote RPC server.
268
269 Args:
270 info: A dict of remote info, see the definition of self._remote_infos.
271 """
272 if not info['ssh_tunnel'] or info['ssh_tunnel'].poll() is not None:
Tom Wai-Hong Tame2c66122011-10-25 17:21:35 +0800273 info['ssh_tunnel'] = subprocess.Popen([
Tom Wai-Hong Tam4a257e52011-11-12 08:36:22 +0800274 'ssh -N -n -q %s -L %s:localhost:%s root@%s' %
Tom Wai-Hong Tame2c66122011-10-25 17:21:35 +0800275 (info['ssh_config'], info['port'], info['port'],
276 self._client.ip)], shell=True)
Craig Harrison91944552011-08-04 14:09:55 -0700277
278
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800279 def _kill_remote_process(self, info):
280 """Ensure the remote process and local ssh process are terminated.
281
282 Args:
283 info: A dict of remote info, see the definition of self._remote_infos.
284 """
285 kill_cmd = 'pkill -f %s' % info['remote_command_short']
Tom Wai-Hong Tam4a257e52011-11-12 08:36:22 +0800286 subprocess.call(['ssh -n -q %s root@%s \'%s\'' %
Tom Wai-Hong Tame2c66122011-10-25 17:21:35 +0800287 (info['ssh_config'], self._client.ip, kill_cmd)],
Craig Harrison91944552011-08-04 14:09:55 -0700288 shell=True)
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800289 if info['remote_process'] and info['remote_process'].poll() is None:
290 info['remote_process'].terminate()
Craig Harrison91944552011-08-04 14:09:55 -0700291
292
293 def _terminate_all_ssh(self):
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800294 """Terminate all ssh connections associated with remote processes."""
295 for info in self._remote_infos.itervalues():
296 if info['ssh_tunnel'] and info['ssh_tunnel'].poll() is None:
297 info['ssh_tunnel'].terminate()
298 self._kill_remote_process(info)