blob: f179a07a777bf5c3509186373a61901316d73cb6 [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
ctchang74816ac2012-08-31 11:12:43 +08008import socket
Craig Harrison2b6c6fc2011-06-23 10:34:02 -07009import subprocess
Craig Harrison91944552011-08-04 14:09:55 -070010import time
11import xmlrpclib
Craig Harrison2b6c6fc2011-06-23 10:34:02 -070012
Chrome Bot9a1137d2011-07-19 14:35:00 -070013from autotest_lib.client.common_lib import error
Chris Sosa8ee1d592011-08-14 16:50:31 -070014from autotest_lib.server import autotest, site_host_attributes, test, utils
15from autotest_lib.server.cros import servo
Craig Harrison91944552011-08-04 14:09:55 -070016
Craig Harrison2b6c6fc2011-06-23 10:34:02 -070017class ServoTest(test.test):
18 """AutoTest test class that creates and destroys a servo object.
19
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +080020 Servo-based server side AutoTests can inherit from this object.
21 There are 2 remote clients supported:
22 If use_pyauto flag is True, a remote PyAuto client will be launched;
23 If use_faft flag is Ture, a remote FAFT client will be launched.
Craig Harrison2b6c6fc2011-06-23 10:34:02 -070024 """
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +080025 version = 2
J. Richard Barnette67ccb872012-04-19 16:34:56 -070026
Craig Harrison91944552011-08-04 14:09:55 -070027 # Exposes RPC access to a remote PyAuto client.
28 pyauto = None
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +080029 # Exposes RPC access to a remote FAFT client.
30 faft_client = None
31
Craig Harrison91944552011-08-04 14:09:55 -070032 # Autotest references to the client.
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +080033 _autotest_client = None
34 # Remote client info list.
35 _remote_infos = {
36 'pyauto': {
37 # Used or not.
38 'used': False,
39 # Reference name of RPC object in this class.
40 'ref_name': 'pyauto',
41 # Port number of the remote RPC.
42 'port': 9988,
43 # Client test for installing dependency.
J. Richard Barnette2f83d712012-04-23 14:31:45 -070044 'client_test': 'desktopui_PyAutoInstall',
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +080045 # The remote command to be run.
Scott Zawalski9a985562012-04-03 17:47:30 -040046 'remote_command': 'python /usr/local/autotest/cros/remote_pyauto.py'
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +080047 ' --no-http-server',
48 # The short form of remote command, used by pkill.
Scott Zawalski9a985562012-04-03 17:47:30 -040049 'remote_command_short': 'remote_pyauto',
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +080050 # The remote process info.
51 'remote_process': None,
52 # The ssh tunnel process info.
53 'ssh_tunnel': None,
54 # Polling RPC function name for testing the server availability.
55 'polling_rpc': 'IsLinux',
Tom Wai-Hong Tame2c66122011-10-25 17:21:35 +080056 # Additional SSH options.
57 'ssh_config': '-o StrictHostKeyChecking=no ',
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +080058 },
59 'faft': {
60 'used': False,
61 'ref_name': 'faft_client',
62 'port': 9990,
63 'client_test': 'firmware_FAFTClient',
64 'remote_command': 'python /usr/local/autotest/cros/faft_client.py',
65 'remote_command_short': 'faft_client',
Vic Yangf8fd4542012-08-01 11:37:46 +080066 'remote_log_file': '/tmp/faft_client.log',
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +080067 'remote_process': None,
68 'ssh_tunnel': None,
69 'polling_rpc': 'is_available',
Tom Wai-Hong Tame2c66122011-10-25 17:21:35 +080070 'ssh_config': '-o StrictHostKeyChecking=no '
71 '-o UserKnownHostsFile=/dev/null ',
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +080072 },
73 }
Craig Harrison2b6c6fc2011-06-23 10:34:02 -070074
J. Richard Barnette67ccb872012-04-19 16:34:56 -070075 def _init_servo(self, host, cmdline_args):
76 """Initialize `self.servo`.
Craig Harrison91944552011-08-04 14:09:55 -070077
J. Richard Barnette67ccb872012-04-19 16:34:56 -070078 If the host has an attached servo object, use that.
79 Otherwise assume that there's a locally attached servo
80 device, and start servod on localhost.
81
Todd Brochf24d2782011-08-19 10:55:41 -070082 """
J. Richard Barnette67ccb872012-04-19 16:34:56 -070083 if host.servo:
84 self.servo = host.servo
85 self._servo_is_local = False
86 return
87
Todd Brochf24d2782011-08-19 10:55:41 -070088 # Assign default arguments for servo invocation.
89 args = {
90 'servo_host': 'localhost', 'servo_port': 9999,
Todd Brochd50ac042012-03-19 16:58:02 -070091 'xml_config': [], 'servo_vid': None, 'servo_pid': None,
Todd Brochf24d2782011-08-19 10:55:41 -070092 'servo_serial': None, 'use_pyauto': False}
93
94 # Parse arguments from AFE and override servo defaults above.
95 client_attributes = site_host_attributes.HostAttributes(host.hostname)
96 if hasattr(site_host_attributes, 'servo_serial'):
97 args['servo_serial'] = client_attributes.servo_serial
98
99 # Parse arguments from command line and override previous AFE or servo
100 # defaults
101 for arg in cmdline_args:
102 match = re.search("^(\w+)=(.+)", arg)
103 if match:
Tom Wai-Hong Tam5fc2c792011-11-03 13:05:39 +0800104 key = match.group(1)
105 val = match.group(2)
106 # Support multiple xml_config by appending it to a list.
107 if key == 'xml_config':
108 args[key].append(val)
109 else:
110 args[key] = val
Todd Brochf24d2782011-08-19 10:55:41 -0700111
Todd Broch0edf7e12012-06-14 09:36:15 -0700112 self.servo = servo.Servo()
J. Richard Barnette67ccb872012-04-19 16:34:56 -0700113 self._servo_is_local = True
114
115
116 def _release_servo(self):
117 """Clean up `self.servo` if it is locally attached."""
J. Richard Barnette67ccb872012-04-19 16:34:56 -0700118 self._servo_is_local = False
119
120
121 def initialize(self, host, cmdline_args, use_pyauto=False, use_faft=False):
122 """Create a Servo object and install the dependency.
123
124 If use_pyauto/use_faft is True the PyAuto/FAFTClient dependency is
125 installed on the client and a remote PyAuto/FAFTClient server is
126 launched and connected.
127 """
Chris Sosa33320a82011-10-24 14:28:32 -0700128 # Initialize servotest args.
129 self._client = host;
130 self._remote_infos['pyauto']['used'] = use_pyauto
131 self._remote_infos['faft']['used'] = use_faft
132
J. Richard Barnette67ccb872012-04-19 16:34:56 -0700133 self._init_servo(host, cmdline_args)
134
Chrome Bot9a1137d2011-07-19 14:35:00 -0700135 # Initializes dut, may raise AssertionError if pre-defined gpio
136 # sequence to set GPIO's fail. Autotest does not handle exception
137 # throwing in initialize and will cause a test to hang.
138 try:
139 self.servo.initialize_dut()
Chris Sosa33320a82011-10-24 14:28:32 -0700140 except (AssertionError, xmlrpclib.Fault) as e:
J. Richard Barnette67ccb872012-04-19 16:34:56 -0700141 self._release_servo()
Chrome Bot9a1137d2011-07-19 14:35:00 -0700142 raise error.TestFail(e)
143
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800144 # Install PyAuto/FAFTClient dependency.
145 for info in self._remote_infos.itervalues():
146 if info['used']:
147 if not self._autotest_client:
148 self._autotest_client = autotest.Autotest(self._client)
149 self._autotest_client.run_test(info['client_test'])
150 self.launch_client(info)
Craig Harrison2b6c6fc2011-06-23 10:34:02 -0700151
152
J. Richard Barnette134ec2c2012-04-25 12:59:37 -0700153 def _ping_test(self, hostname, timeout=5):
Craig Harrison2b6c6fc2011-06-23 10:34:02 -0700154 """Verify whether a host responds to a ping.
155
156 Args:
157 hostname: Hostname to ping.
158 timeout: Time in seconds to wait for a response.
159 """
Tom Wai-Hong Tam4a257e52011-11-12 08:36:22 +0800160 with open(os.devnull, 'w') as fnull:
161 return subprocess.call(
162 ['ping', '-c', '1', '-W', str(timeout), hostname],
163 stdout=fnull, stderr=fnull) == 0
Craig Harrison2b6c6fc2011-06-23 10:34:02 -0700164
165
ctchang74816ac2012-08-31 11:12:43 +0800166 def _sshd_test(self, hostname, timeout=5):
167 """Verify whether sshd is running in host.
168
169 Args:
170 hostname: Hostname to verify.
171 timeout: Time in seconds to wait for a response.
172 """
173 try:
174 sock = socket.create_connection((hostname, 22), timeout=timeout)
175 sock.close()
176 return True
177 except socket.error:
178 return False
179
180
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800181 def launch_client(self, info):
182 """Launch a remote process on client and set up an xmlrpc connection.
183
184 Args:
185 info: A dict of remote info, see the definition of self._remote_infos.
186 """
187 assert info['used'], \
188 'Remote %s dependency not installed.' % info['ref_name']
189 if not info['ssh_tunnel'] or info['ssh_tunnel'].poll() is not None:
190 self._launch_ssh_tunnel(info)
191 assert info['ssh_tunnel'] and info['ssh_tunnel'].poll() is None, \
Craig Harrison91944552011-08-04 14:09:55 -0700192 'The SSH tunnel is not up.'
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800193
194 # Launch RPC server remotely.
195 self._kill_remote_process(info)
196 logging.info('Client command: %s' % info['remote_command'])
Vic Yangf8fd4542012-08-01 11:37:46 +0800197 if 'remote_log_file' in info:
198 log_file = info['remote_log_file']
199 else:
200 log_file = '/dev/null'
201 logging.info("Logging to %s", log_file)
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800202 info['remote_process'] = subprocess.Popen([
Vic Yangf8fd4542012-08-01 11:37:46 +0800203 'ssh -n -q %s root@%s \'%s &> %s\'' % (info['ssh_config'],
204 self._client.ip, info['remote_command'], log_file)],
205 shell=True)
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800206
207 # Connect to RPC object.
208 logging.info('Connecting to client RPC server...')
209 remote_url = 'http://localhost:%s' % info['port']
210 setattr(self, info['ref_name'],
211 xmlrpclib.ServerProxy(remote_url, allow_none=True))
212 logging.info('Server proxy: %s' % remote_url)
213
Craig Harrison91944552011-08-04 14:09:55 -0700214 # Poll for client RPC server to come online.
215 timeout = 10
216 succeed = False
217 while timeout > 0 and not succeed:
218 time.sleep(2)
219 try:
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800220 remote_object = getattr(self, info['ref_name'])
221 polling_rpc = getattr(remote_object, info['polling_rpc'])
222 polling_rpc()
Craig Harrison91944552011-08-04 14:09:55 -0700223 succeed = True
224 except:
225 timeout -= 1
Vic Yangf8fd4542012-08-01 11:37:46 +0800226
227 if not succeed:
228 if 'remote_log_file' in info:
229 p = subprocess.Popen([
230 'ssh -n -q %s root@%s \'cat %s\'' % (info['ssh_config'],
231 self._client.ip, info['remote_log_file'])], shell=True,
232 stdout=subprocess.PIPE)
233 logging.info(p.communicate()[0])
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800234 assert succeed, 'Timed out connecting to client RPC server.'
Craig Harrison91944552011-08-04 14:09:55 -0700235
236
Vic Yang8bbc1c32012-09-13 11:47:44 +0800237 def wait_for_client(self, install_deps=False, timeout=100):
Craig Harrison91944552011-08-04 14:09:55 -0700238 """Wait for the client to come back online.
239
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800240 New remote processes will be launched if their used flags are enabled.
Tom Wai-Hong Tam7c17ff22011-10-26 09:44:09 +0800241
242 Args:
243 install_deps: If True, install the Autotest dependency when ready.
Vic Yang8bbc1c32012-09-13 11:47:44 +0800244 timeout: Time in seconds to wait for the client SSH daemon to
245 come up.
Craig Harrison91944552011-08-04 14:09:55 -0700246 """
Craig Harrison91944552011-08-04 14:09:55 -0700247 # Ensure old ssh connections are terminated.
248 self._terminate_all_ssh()
249 # Wait for the client to come up.
Vic Yang8bbc1c32012-09-13 11:47:44 +0800250 while timeout > 0 and not self._sshd_test(self._client.ip, timeout=5):
251 timeout -= 5
Craig Harrison91944552011-08-04 14:09:55 -0700252 assert timeout, 'Timed out waiting for client to reboot.'
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800253 logging.info('Server: Client machine is up.')
254 # Relaunch remote clients.
255 for name, info in self._remote_infos.iteritems():
256 if info['used']:
Tom Wai-Hong Tam7c17ff22011-10-26 09:44:09 +0800257 if install_deps:
258 if not self._autotest_client:
259 self._autotest_client = autotest.Autotest(self._client)
260 self._autotest_client.run_test(info['client_test'])
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800261 self.launch_client(info)
262 logging.info('Server: Relaunched remote %s.' % name)
Craig Harrison91944552011-08-04 14:09:55 -0700263
264
Vic Yang8bbc1c32012-09-13 11:47:44 +0800265 def wait_for_client_offline(self, timeout=60):
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800266 """Wait for the client to come offline.
267
268 Args:
269 timeout: Time in seconds to wait the client to come offline.
270 """
271 # Wait for the client to come offline.
J. Richard Barnette134ec2c2012-04-25 12:59:37 -0700272 while timeout > 0 and self._ping_test(self._client.ip, timeout=1):
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800273 timeout -= 1
274 assert timeout, 'Timed out waiting for client offline.'
275 logging.info('Server: Client machine is offline.')
276
277
Vic Yang4e0d1f72012-05-24 15:11:11 +0800278 def kill_remote(self):
279 """Call remote cleanup and kill ssh."""
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800280 for info in self._remote_infos.itervalues():
281 if info['remote_process'] and info['remote_process'].poll() is None:
282 remote_object = getattr(self, info['ref_name'])
283 remote_object.cleanup()
Craig Harrison91944552011-08-04 14:09:55 -0700284 self._terminate_all_ssh()
285
286
Vic Yang4e0d1f72012-05-24 15:11:11 +0800287 def cleanup(self):
288 """Delete the Servo object, call remote cleanup, and kill ssh."""
289 self._release_servo()
290 self.kill_remote()
291
292
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800293 def _launch_ssh_tunnel(self, info):
294 """Establish an ssh tunnel for connecting to the remote RPC server.
295
296 Args:
297 info: A dict of remote info, see the definition of self._remote_infos.
298 """
299 if not info['ssh_tunnel'] or info['ssh_tunnel'].poll() is not None:
Tom Wai-Hong Tame2c66122011-10-25 17:21:35 +0800300 info['ssh_tunnel'] = subprocess.Popen([
Tom Wai-Hong Tam4a257e52011-11-12 08:36:22 +0800301 'ssh -N -n -q %s -L %s:localhost:%s root@%s' %
Tom Wai-Hong Tame2c66122011-10-25 17:21:35 +0800302 (info['ssh_config'], info['port'], info['port'],
303 self._client.ip)], shell=True)
Craig Harrison91944552011-08-04 14:09:55 -0700304
305
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800306 def _kill_remote_process(self, info):
307 """Ensure the remote process and local ssh process are terminated.
308
309 Args:
310 info: A dict of remote info, see the definition of self._remote_infos.
311 """
312 kill_cmd = 'pkill -f %s' % info['remote_command_short']
Tom Wai-Hong Tam4a257e52011-11-12 08:36:22 +0800313 subprocess.call(['ssh -n -q %s root@%s \'%s\'' %
Tom Wai-Hong Tame2c66122011-10-25 17:21:35 +0800314 (info['ssh_config'], self._client.ip, kill_cmd)],
Craig Harrison91944552011-08-04 14:09:55 -0700315 shell=True)
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800316 if info['remote_process'] and info['remote_process'].poll() is None:
317 info['remote_process'].terminate()
Craig Harrison91944552011-08-04 14:09:55 -0700318
319
320 def _terminate_all_ssh(self):
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800321 """Terminate all ssh connections associated with remote processes."""
322 for info in self._remote_infos.itervalues():
323 if info['ssh_tunnel'] and info['ssh_tunnel'].poll() is None:
324 info['ssh_tunnel'].terminate()
325 self._kill_remote_process(info)