blob: 380499d335e7e9bdf09e726c34563645689e6620 [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
ctchang74816ac2012-08-31 11:12:43 +08007import socket
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
Vadim Bendeburybb731952012-12-05 17:30:36 -080013from autotest_lib.server import autotest, test
Chris Sosa8ee1d592011-08-14 16:50:31 -070014from 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,
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +080042 # The remote command to be run.
Scott Zawalski9a985562012-04-03 17:47:30 -040043 'remote_command': 'python /usr/local/autotest/cros/remote_pyauto.py'
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +080044 ' --no-http-server',
45 # The short form of remote command, used by pkill.
Scott Zawalski9a985562012-04-03 17:47:30 -040046 'remote_command_short': 'remote_pyauto',
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +080047 # The remote process info.
48 'remote_process': None,
49 # The ssh tunnel process info.
50 'ssh_tunnel': None,
51 # Polling RPC function name for testing the server availability.
52 'polling_rpc': 'IsLinux',
Tom Wai-Hong Tame2c66122011-10-25 17:21:35 +080053 # Additional SSH options.
54 'ssh_config': '-o StrictHostKeyChecking=no ',
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +080055 },
56 'faft': {
57 'used': False,
58 'ref_name': 'faft_client',
59 'port': 9990,
Tom Wai-Hong Tamc1e0b9a2012-11-01 13:52:39 +080060 'remote_command': '/usr/local/autotest/cros/faft_client.py',
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +080061 'remote_command_short': 'faft_client',
Vic Yangf8fd4542012-08-01 11:37:46 +080062 'remote_log_file': '/tmp/faft_client.log',
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +080063 'remote_process': None,
64 'ssh_tunnel': None,
Chun-ting Changd43aa9b2012-11-16 10:12:05 +080065 'polling_rpc': 'system.is_available',
Tom Wai-Hong Tame2c66122011-10-25 17:21:35 +080066 'ssh_config': '-o StrictHostKeyChecking=no '
67 '-o UserKnownHostsFile=/dev/null ',
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +080068 },
69 }
Craig Harrison2b6c6fc2011-06-23 10:34:02 -070070
Vadim Bendeburybb731952012-12-05 17:30:36 -080071 def _init_servo(self, host):
J. Richard Barnette67ccb872012-04-19 16:34:56 -070072 """Initialize `self.servo`.
Craig Harrison91944552011-08-04 14:09:55 -070073
J. Richard Barnette67ccb872012-04-19 16:34:56 -070074 If the host has an attached servo object, use that.
75 Otherwise assume that there's a locally attached servo
Vadim Bendeburybb731952012-12-05 17:30:36 -080076 device, and use it.
J. Richard Barnette67ccb872012-04-19 16:34:56 -070077
Todd Brochf24d2782011-08-19 10:55:41 -070078 """
J. Richard Barnette67ccb872012-04-19 16:34:56 -070079 if host.servo:
80 self.servo = host.servo
Vadim Bendeburybb731952012-12-05 17:30:36 -080081 else:
82 self.servo = servo.Servo()
J. Richard Barnette67ccb872012-04-19 16:34:56 -070083
84
Vadim Bendeburybb731952012-12-05 17:30:36 -080085 def initialize(self, host, _, use_pyauto=False, use_faft=False):
J. Richard Barnette67ccb872012-04-19 16:34:56 -070086 """Create a Servo object and install the dependency.
87
88 If use_pyauto/use_faft is True the PyAuto/FAFTClient dependency is
89 installed on the client and a remote PyAuto/FAFTClient server is
90 launched and connected.
91 """
Chris Sosa33320a82011-10-24 14:28:32 -070092 # Initialize servotest args.
Vic Yang3a7cf602012-11-07 17:28:39 +080093 self._client = host
Chris Sosa33320a82011-10-24 14:28:32 -070094 self._remote_infos['pyauto']['used'] = use_pyauto
95 self._remote_infos['faft']['used'] = use_faft
96
Vadim Bendeburybb731952012-12-05 17:30:36 -080097 self._init_servo(host)
J. Richard Barnette67ccb872012-04-19 16:34:56 -070098
Chrome Bot9a1137d2011-07-19 14:35:00 -070099 # Initializes dut, may raise AssertionError if pre-defined gpio
100 # sequence to set GPIO's fail. Autotest does not handle exception
101 # throwing in initialize and will cause a test to hang.
102 try:
103 self.servo.initialize_dut()
Chris Sosa33320a82011-10-24 14:28:32 -0700104 except (AssertionError, xmlrpclib.Fault) as e:
Chrome Bot9a1137d2011-07-19 14:35:00 -0700105 raise error.TestFail(e)
106
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800107 # Install PyAuto/FAFTClient dependency.
108 for info in self._remote_infos.itervalues():
109 if info['used']:
110 if not self._autotest_client:
111 self._autotest_client = autotest.Autotest(self._client)
Tom Wai-Hong Tam00d10512012-11-09 15:37:51 +0800112 self._autotest_client.install()
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800113 self.launch_client(info)
Craig Harrison2b6c6fc2011-06-23 10:34:02 -0700114
115
J. Richard Barnette134ec2c2012-04-25 12:59:37 -0700116 def _ping_test(self, hostname, timeout=5):
Craig Harrison2b6c6fc2011-06-23 10:34:02 -0700117 """Verify whether a host responds to a ping.
118
119 Args:
120 hostname: Hostname to ping.
121 timeout: Time in seconds to wait for a response.
122 """
Tom Wai-Hong Tam4a257e52011-11-12 08:36:22 +0800123 with open(os.devnull, 'w') as fnull:
124 return subprocess.call(
125 ['ping', '-c', '1', '-W', str(timeout), hostname],
126 stdout=fnull, stderr=fnull) == 0
Craig Harrison2b6c6fc2011-06-23 10:34:02 -0700127
128
ctchang74816ac2012-08-31 11:12:43 +0800129 def _sshd_test(self, hostname, timeout=5):
130 """Verify whether sshd is running in host.
131
132 Args:
133 hostname: Hostname to verify.
134 timeout: Time in seconds to wait for a response.
135 """
136 try:
137 sock = socket.create_connection((hostname, 22), timeout=timeout)
138 sock.close()
139 return True
Tom Wai-Hong Tam711a7aa2012-09-18 10:30:43 +0800140 except socket.timeout:
141 return False
ctchang74816ac2012-08-31 11:12:43 +0800142 except socket.error:
Tom Wai-Hong Tam711a7aa2012-09-18 10:30:43 +0800143 time.sleep(timeout)
ctchang74816ac2012-08-31 11:12:43 +0800144 return False
145
146
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800147 def launch_client(self, info):
Tom Wai-Hong Tame97cb4a2012-11-22 09:52:46 +0800148 """Launch a remote XML RPC connection on client with retrials.
149
150 Args:
151 info: A dict of remote info, see the definition of self._remote_infos.
152 """
153 retry = 3
Tom Wai-Hong Tamb3db3b22012-12-04 11:59:54 +0800154 while retry:
155 try:
156 self._launch_client_once(info)
157 break
158 except AssertionError:
Tom Wai-Hong Tame97cb4a2012-11-22 09:52:46 +0800159 retry -= 1
Tom Wai-Hong Tamb3db3b22012-12-04 11:59:54 +0800160 if retry:
161 logging.info('Retry again...')
162 time.sleep(5)
163 else:
164 raise
Tom Wai-Hong Tame97cb4a2012-11-22 09:52:46 +0800165
166
167 def _launch_client_once(self, info):
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800168 """Launch a remote process on client and set up an xmlrpc connection.
169
170 Args:
171 info: A dict of remote info, see the definition of self._remote_infos.
172 """
173 assert info['used'], \
174 'Remote %s dependency not installed.' % info['ref_name']
175 if not info['ssh_tunnel'] or info['ssh_tunnel'].poll() is not None:
176 self._launch_ssh_tunnel(info)
177 assert info['ssh_tunnel'] and info['ssh_tunnel'].poll() is None, \
Craig Harrison91944552011-08-04 14:09:55 -0700178 'The SSH tunnel is not up.'
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800179
180 # Launch RPC server remotely.
181 self._kill_remote_process(info)
Vic Yang3a7cf602012-11-07 17:28:39 +0800182 logging.info('Client command: %s', info['remote_command'])
Vic Yangf8fd4542012-08-01 11:37:46 +0800183 if 'remote_log_file' in info:
Vic Yang3a7cf602012-11-07 17:28:39 +0800184 log_file = info['remote_log_file']
Vic Yangf8fd4542012-08-01 11:37:46 +0800185 else:
Vic Yang3a7cf602012-11-07 17:28:39 +0800186 log_file = '/dev/null'
Vic Yangf8fd4542012-08-01 11:37:46 +0800187 logging.info("Logging to %s", log_file)
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800188 info['remote_process'] = subprocess.Popen([
Vic Yangf8fd4542012-08-01 11:37:46 +0800189 'ssh -n -q %s root@%s \'%s &> %s\'' % (info['ssh_config'],
190 self._client.ip, info['remote_command'], log_file)],
191 shell=True)
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800192
193 # Connect to RPC object.
194 logging.info('Connecting to client RPC server...')
195 remote_url = 'http://localhost:%s' % info['port']
196 setattr(self, info['ref_name'],
197 xmlrpclib.ServerProxy(remote_url, allow_none=True))
Vic Yang3a7cf602012-11-07 17:28:39 +0800198 logging.info('Server proxy: %s', remote_url)
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800199
Craig Harrison91944552011-08-04 14:09:55 -0700200 # Poll for client RPC server to come online.
Vic Yang6c1dc152012-09-13 14:56:11 +0800201 timeout = 20
Craig Harrison91944552011-08-04 14:09:55 -0700202 succeed = False
Vic Yang3a7cf602012-11-07 17:28:39 +0800203 rpc_error = None
Craig Harrison91944552011-08-04 14:09:55 -0700204 while timeout > 0 and not succeed:
Vic Yang6c1dc152012-09-13 14:56:11 +0800205 time.sleep(1)
Craig Harrison91944552011-08-04 14:09:55 -0700206 try:
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800207 remote_object = getattr(self, info['ref_name'])
208 polling_rpc = getattr(remote_object, info['polling_rpc'])
209 polling_rpc()
Craig Harrison91944552011-08-04 14:09:55 -0700210 succeed = True
Tom Wai-Hong Tamac35f082012-11-06 15:00:35 +0800211 except (socket.error, xmlrpclib.ProtocolError) as e:
212 # The client RPC server may not come online fast enough. Retry.
Craig Harrison91944552011-08-04 14:09:55 -0700213 timeout -= 1
Vic Yang3a7cf602012-11-07 17:28:39 +0800214 rpc_error = e
Vic Yangf8fd4542012-08-01 11:37:46 +0800215
216 if not succeed:
Vic Yang3a7cf602012-11-07 17:28:39 +0800217 if isinstance(rpc_error, xmlrpclib.ProtocolError):
Tom Wai-Hong Tamac35f082012-11-06 15:00:35 +0800218 logging.info("A protocol error occurred")
Vic Yang3a7cf602012-11-07 17:28:39 +0800219 logging.info("URL: %s", rpc_error.url)
220 logging.info("HTTP/HTTPS headers: %s", rpc_error.headers)
221 logging.info("Error code: %d", rpc_error.errcode)
222 logging.info("Error message: %s", rpc_error.errmsg)
Vic Yangf8fd4542012-08-01 11:37:46 +0800223 if 'remote_log_file' in info:
224 p = subprocess.Popen([
225 'ssh -n -q %s root@%s \'cat %s\'' % (info['ssh_config'],
226 self._client.ip, info['remote_log_file'])], shell=True,
227 stdout=subprocess.PIPE)
Tom Wai-Hong Tamc1e0b9a2012-11-01 13:52:39 +0800228 logging.info('Log of running remote %s:', info['ref_name'])
Vic Yangf8fd4542012-08-01 11:37:46 +0800229 logging.info(p.communicate()[0])
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800230 assert succeed, 'Timed out connecting to client RPC server.'
Craig Harrison91944552011-08-04 14:09:55 -0700231
232
Vic Yang8bbc1c32012-09-13 11:47:44 +0800233 def wait_for_client(self, install_deps=False, timeout=100):
Craig Harrison91944552011-08-04 14:09:55 -0700234 """Wait for the client to come back online.
235
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800236 New remote processes will be launched if their used flags are enabled.
Tom Wai-Hong Tam7c17ff22011-10-26 09:44:09 +0800237
238 Args:
239 install_deps: If True, install the Autotest dependency when ready.
Vic Yang8bbc1c32012-09-13 11:47:44 +0800240 timeout: Time in seconds to wait for the client SSH daemon to
241 come up.
Craig Harrison91944552011-08-04 14:09:55 -0700242 """
Craig Harrison91944552011-08-04 14:09:55 -0700243 # Ensure old ssh connections are terminated.
244 self._terminate_all_ssh()
245 # Wait for the client to come up.
Vic Yang6c1dc152012-09-13 14:56:11 +0800246 while timeout > 0 and not self._sshd_test(self._client.ip, timeout=2):
247 timeout -= 2
Vadim Bendebury69f047c2012-10-11 15:20:31 -0700248 assert (timeout > 0), 'Timed out waiting for client to reboot.'
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800249 logging.info('Server: Client machine is up.')
250 # Relaunch remote clients.
251 for name, info in self._remote_infos.iteritems():
252 if info['used']:
Tom Wai-Hong Tam7c17ff22011-10-26 09:44:09 +0800253 if install_deps:
254 if not self._autotest_client:
255 self._autotest_client = autotest.Autotest(self._client)
Tom Wai-Hong Tam00d10512012-11-09 15:37:51 +0800256 self._autotest_client.install()
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800257 self.launch_client(info)
Vic Yang3a7cf602012-11-07 17:28:39 +0800258 logging.info('Server: Relaunched remote %s.', name)
Craig Harrison91944552011-08-04 14:09:55 -0700259
260
Vic Yang8bbc1c32012-09-13 11:47:44 +0800261 def wait_for_client_offline(self, timeout=60):
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800262 """Wait for the client to come offline.
263
264 Args:
265 timeout: Time in seconds to wait the client to come offline.
266 """
267 # Wait for the client to come offline.
J. Richard Barnette134ec2c2012-04-25 12:59:37 -0700268 while timeout > 0 and self._ping_test(self._client.ip, timeout=1):
Vic Yangcf5d6fc2012-09-14 15:22:44 +0800269 time.sleep(1)
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800270 timeout -= 1
271 assert timeout, 'Timed out waiting for client offline.'
272 logging.info('Server: Client machine is offline.')
273
274
Vic Yang4e0d1f72012-05-24 15:11:11 +0800275 def kill_remote(self):
276 """Call remote cleanup and kill ssh."""
Tom Wai-Hong Tambea57b32011-09-02 18:27:47 +0800277 for info in self._remote_infos.itervalues():
278 if info['remote_process'] and info['remote_process'].poll() is None:
279 remote_object = getattr(self, info['ref_name'])
Vadim Bendebury5b82cc52012-10-09 19:05:01 -0700280 try:
281 remote_object.cleanup()
282 logging.info('Cleanup succeeded.')
283 except xmlrpclib.ProtocolError, e:
284 logging.info('Cleanup returned protocol error: ' + str(e))
Craig Harrison91944552011-08-04 14:09:55 -0700285 self._terminate_all_ssh()
286
287
Vic Yang4e0d1f72012-05-24 15:11:11 +0800288 def cleanup(self):
289 """Delete the Servo object, call remote cleanup, and kill ssh."""
Vic Yang4e0d1f72012-05-24 15:11:11 +0800290 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)