blob: 4aafa1b1ff8ef8db6c1e014237301457d0aec5e0 [file] [log] [blame]
beeps7583e582013-08-28 16:19:24 -07001# Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5import collections
6import httplib
7import logging
8import os
9import re
10import socket
11import time
12
13import common
14
15from autotest_lib.client.common_lib import error
16from autotest_lib.client.common_lib.cros import retry
17from autotest_lib.server import utils
18
19
20GOOFY_JSONRPC_SERVER_PORT = 0x0FAC
21GOOFY_RUNNING = 'RUNNING'
22
23
24class GoofyProxyException(Exception):
25 """Exception raised when a goofy rpc fails."""
26 pass
27
28
beeps04561352013-10-04 11:07:47 -070029class GoofyRuntimeException(Exception):
30 """Exception raised when something goes wrong while a test is running."""
31 pass
32
33
34def retry_goofy_rpc(exception_tuple, timeout_min=30):
35 """A decorator to use with goofy rpcs.
36
37 This decorator tries to recreate the goofy client proxy on
38 socket error. It will continue trying to do so until it
39 executes the method without any socket errors or till the
40 retry.retry decorator hits it's timeout.
41
42 Usage:
43 If you just want to recreate the proxy:
44 1. @retry_goofy_rpc(exception_tuple=(<exception>, socket.error),
45 timeout_min=<timeout>)
46 2. @retry_goofy_rpc(socket.error, timeout_min=<timeout>)
47 Note: you need to specify the socket.error exception because we
48 want to retry the call after recreating the proxy.
49
50 @param exception_tuple: A tuple of exceptions to pass to
51 the retry decorator. Any of these exceptions will result
52 in retries for the duration of timeout_min.
53 @param timeout_min: The timeout, in minutes, for which we should
54 retry the method ignoring any exception in exception_tuple.
55 """
56 def inner_decorator(method):
57 """Inner retry decorator applied to the method.
58
59 @param method: The method that needs to be wrapped in the decorator.
60
61 @return A wrapper function that implements the retry.
62 """
63
64 @retry.retry(exception_tuple, timeout_min=timeout_min)
65 def wrapper(*args, **kwargs):
66 """This wrapper handles socket errors.
67
68 If the method in question:
69 1. Throws an exception in exception_tuple and it is not a
70 socket.error, retry for timeout_min through retry.retry.
71 2. Throws a socket.error, recreate the client proxy, and
72 retry for timeout_min through retry.retry.
73 3. Throws an exception not in exception_tuple, fail.
74 """
75 try:
76 return method(*args, **kwargs)
77 except socket.error as e:
78 goofy_proxy = args[0]
79 if type(goofy_proxy) is GoofyProxy:
80 logging.warning('Socket error while running factory tests '
81 '%s, recreating goofy proxy.', e)
82 goofy_proxy._create_client_proxy(timeout_min=timeout_min)
83 else:
84 logging.warning('Connectivity was lost and the retry '
85 'decorator was unable to recreate a goofy '
86 'client proxy, args: %s.', args)
87 raise
88
89 return wrapper
90
91 return inner_decorator
92
93
beeps7583e582013-08-28 16:19:24 -070094class GoofyProxy(object):
95 """Client capable of making rpc calls to goofy.
96
97 Methods of this class that can cause goofy to change state
98 usually need a retry decorator. Methods that have a retry decorator
99 need to be 'pure', i.e return the same results when called multiple
100 times with the same argument.
101
102 There are 2 known exceptions this class can deal with, a socket.error
103 which happens when we try to execute an rpc when the DUT is, say, suspended
104 and a BadStatusLine, which we get when we try to execute an rpc while the
105 DUT is going through a factory_restart. Ideally we would like to handle
106 socket timeouts different from BadStatusLines as we can get connection
107 errors even when a device reboots and BadStatusLines ususally only when
108 factory restarts. crbug.com/281714.
109 """
110
111 # This timeout was arbitrarily chosen as many tests in the factory test
112 # suite run for days. Ideally we would like to split this into at least 2
113 # timeouts, one which we use for rpcs that run while no other test is,
114 # running and is smaller than the second that is designed for use with rpcs
115 # that might execute simultaneously with a test. The latter needs a longer
116 # timeout since tests could suspend,resume for a long time, and a call like
117 # GetGoofyStatus should be tolerant to these suspend/resumes. In designing
118 # the base timeout one needs to allocate time to component methods of this
119 # class (such as _set_test_list) as a multiple of the number of rpcs it
120 # executes.
121 BASE_RPC_TIMEOUT = 1440
122 POLLING_INTERVAL = 5
123 FACTORY_BUG_RE = r'.*(/tmp/factory_bug.*tar.bz2).*'
124 UNTAR_COMMAND = 'tar jxf %s -C %s'
125
126
127 def __init__(self, host):
128 """
129 @param host: The host object representing the DUT running goofy.
130 """
131 self._host = host
beeps04561352013-10-04 11:07:47 -0700132 self._raw_stop_running_tests()
133 self._create_client_proxy(timeout_min=self.BASE_RPC_TIMEOUT)
134
135
136 def _create_client_proxy(self, timeout_min=30):
137 """Create a goofy client proxy.
138
139 Ping the host till it's up, then proceed to create a goofy proxy. We
140 don't wrap this method with a retry because it's used in the retry
141 decorator itself.
142 """
143
144 # We don't ssh ping here as there is a potential dealy in O(minutes)
145 # with our ssh command against a sleeping DUT, once it wakes up, and
146 # that will lead to significant overhead incurred over many reboots.
147 self._host.ping_wait_up(timeout_min)
148 logging.info('Host is pingable, creating goofy client proxy')
149 self._client = self._host.jsonrpc_connect(GOOFY_JSONRPC_SERVER_PORT)
beeps7583e582013-08-28 16:19:24 -0700150
151
152 @retry.retry((httplib.BadStatusLine, socket.error),
153 timeout_min=BASE_RPC_TIMEOUT)
beeps04561352013-10-04 11:07:47 -0700154 def _raw_stop_running_tests(self):
155 """Stop running tests by shelling out to the DUT.
156
157 Use this method only before we have actually created the client
158 proxy, as shelling out has several pitfalls. We need to stop all
159 tests in a retry loop because tests will start executing as soon
160 as we have reimaged a DUT and trying to create the proxy while
161 the DUT is rebooting will lead to a spurious failure.
162
163 Note that we use the plain retry decorator for this method since
164 we don't need to recreate the client proxy on failure.
165 """
166 logging.info('Stopping all tests and clearing factory state')
167 self._host.run('factory clear')
168
169
170 @retry_goofy_rpc((httplib.BadStatusLine, socket.error),
171 timeout_min=BASE_RPC_TIMEOUT)
beeps7583e582013-08-28 16:19:24 -0700172 def _get_goofy_status(self):
173 """Return status of goofy, ignoring socket timeouts and http exceptions.
174 """
175 status = self._client.GetGoofyStatus().get('status')
176 return status
177
178
179 def _wait_for_goofy(self, timeout_min=BASE_RPC_TIMEOUT*2):
180 """Wait till goofy is running or a timeout occurs.
181
182 @param timeout_min: Minutes to wait before timing this call out.
183 """
184 current_time = time.time()
185 timeout_secs = timeout_min * 60
186 logging.info('Waiting on goofy')
187 while self._get_goofy_status() != GOOFY_RUNNING:
188 if time.time() - current_time > timeout_secs:
189 break
190 return
191
192
beeps04561352013-10-04 11:07:47 -0700193 @retry_goofy_rpc(socket.error, timeout_min=BASE_RPC_TIMEOUT*2)
beeps7583e582013-08-28 16:19:24 -0700194 def _set_test_list(self, next_list):
Ricky Liang74317062014-03-04 17:20:05 +0800195 """Set the given test list for execution and turn on test automation.
beeps7583e582013-08-28 16:19:24 -0700196
197 Confirm that the given test list is a test that has been baked into
198 the image, then run it. Some test lists are configured to start
199 execution automatically when we call SetTestList, while others wait
200 for a corresponding RunTest.
201
202 @param next_list: The name of the test list.
203
204 @raise jsonrpclib.ProtocolError: If the test list we're trying to switch
205 to isn't on the DUT.
206 """
207
beeps04561352013-10-04 11:07:47 -0700208 # We can get a BadStatus line on 2 occassions:
209 # 1. As part of SwitchTestList goofy performs a factory restart, which
210 # will throw a BadStatusLine because the rpc can't exit cleanly. We
211 # don't want to retry on this exception, since we've already set the
212 # right test list.
213 # 2. If we try to set a test list while goofy is already down
214 # (from a previous factory restart). In this case we wouldn't have
215 # set the new test list, because we coulnd't connect to goofy.
216 # To properly set a new test list it's important to wait till goofy is
217 # up before attempting to set the test list, while being aware that the
218 # preceding httplib error is from the rpc we just executed leading to
219 # a factory restart. Also note that if the test list is not already on
220 # the DUT this method will fail, emitting the possible test lists one
221 # can switch to.
222 self._wait_for_goofy()
223 logging.info('Switching to test list %s', next_list)
beeps7583e582013-08-28 16:19:24 -0700224 try:
Ricky Liang74317062014-03-04 17:20:05 +0800225 # Enable full factory test automation. Full test automation mode
226 # skips all manual tests and test barriers, which is what we want in
227 # the test lab. There are other automation modes: partial and none.
228 # In partial automation mode manual tests and barrier are enabled
229 # and user intervention is required; none disables automation.
230 self._client.SwitchTestList(next_list, 'full')
beeps7583e582013-08-28 16:19:24 -0700231 except httplib.BadStatusLine:
232 logging.info('Switched to list %s, goofy restarting', next_list)
beeps7583e582013-08-28 16:19:24 -0700233
234
beeps04561352013-10-04 11:07:47 -0700235 @retry_goofy_rpc((httplib.BadStatusLine, socket.error),
236 timeout_min=BASE_RPC_TIMEOUT*2)
beeps7583e582013-08-28 16:19:24 -0700237 def _stop_running_tests(self):
Ricky Liang74317062014-03-04 17:20:05 +0800238 """Stop all running tests.
beeps7583e582013-08-28 16:19:24 -0700239
Ricky Liang74317062014-03-04 17:20:05 +0800240 Wrap the StopTest rpc so we can attempt to stop tests even while a DUT
241 is suspended or rebooting.
242 """
243 logging.info('Stopping tests.')
244 self._client.StopTest()
beeps7583e582013-08-28 16:19:24 -0700245
246
247 def _get_test_map(self):
248 """Get a mapping of test suites -> tests.
249
250 Ignore entries for tests that don't have a path.
251
252 @return: A dictionary of the form
253 {'suite_name': ['suite_name.path_to_test', ...]}.
254 """
255 test_all = set([test['path'] for test in self._client.GetTests()
256 if test.get('path')])
257
258 test_map = collections.defaultdict(list)
259 for names in test_all:
260 test_map[names.split('.')[0]].append(names)
261 return test_map
262
263
264 def _log_test_results(self, test_status, current_suite):
265 """Format test status results and write them to status.log.
266
267 @param test_status: The status dictionary of a single test.
268 @param current_suite: The current suite name.
269 """
270 try:
271 self._host.job.record('INFO', None, None,
272 'suite %s, test %s, status: %s' %
273 (current_suite, test_status.get('path'),
274 test_status.get('status')))
275 except AttributeError as e:
276 logging.error('Could not gather results for current test: %s', e)
277
278
beeps04561352013-10-04 11:07:47 -0700279 @retry_goofy_rpc((httplib.BadStatusLine, socket.error),
280 timeout_min=BASE_RPC_TIMEOUT*2)
beeps7583e582013-08-28 16:19:24 -0700281 def _get_test_info(self, test_name):
282 """Get the status of one test.
283
284 @param test_name: The name of the test we need the status of.
285
286 @return: The entry for the test in the status dictionary.
287 """
288 for test in self._client.GetTests():
289 if test['path'] == test_name:
290 return test
291 raise ValueError('Could not find test_name %s in _get_test_info.' %
292 test_name)
293
294
Ricky Liang74317062014-03-04 17:20:05 +0800295 @retry_goofy_rpc((httplib.BadStatusLine, socket.error),
296 timeout_min=BASE_RPC_TIMEOUT*2)
297 def _get_test_run_info(self, run_id):
298 """Get the information about the given test run.
beeps7583e582013-08-28 16:19:24 -0700299
Ricky Liang74317062014-03-04 17:20:05 +0800300 @param run_id: The ID of the test run.
beeps7583e582013-08-28 16:19:24 -0700301
Ricky Liang74317062014-03-04 17:20:05 +0800302 @return: A dict of test run status.
beeps7583e582013-08-28 16:19:24 -0700303 """
Ricky Liang74317062014-03-04 17:20:05 +0800304 return self._client.GetTestRunStatus(run_id)
beeps7583e582013-08-28 16:19:24 -0700305
306
Ricky Liang74317062014-03-04 17:20:05 +0800307 def _wait_on_run(self, run_id):
308 """Wait until the given test run to end.
beeps7583e582013-08-28 16:19:24 -0700309
Ricky Liang74317062014-03-04 17:20:05 +0800310 @param run_id: The ID of the test run.
beeps7583e582013-08-28 16:19:24 -0700311
Ricky Liang74317062014-03-04 17:20:05 +0800312 @raises GoofyRuntimeException: If the test run does not finish
313 gracefully.
beeps7583e582013-08-28 16:19:24 -0700314 """
Ricky Liang74317062014-03-04 17:20:05 +0800315 finished_tests = set()
316 run_info = self._get_test_run_info(run_id)
317 while run_info['status'] == 'RUNNING':
318 finished = [(t['path'], t['status']) for t in
319 run_info['scheduled_tests']
320 if t['status'] in ('PASSED', 'FAILED')]
321 for t in finished:
322 if t not in finished_tests:
323 logging.info('[%s] %s', t[1], t[0])
324 finished_tests.add(t)
beeps7583e582013-08-28 16:19:24 -0700325 time.sleep(self.POLLING_INTERVAL)
Ricky Liang74317062014-03-04 17:20:05 +0800326 run_info = self._get_test_run_info(run_id)
327 if run_info['status'] != 'FINISHED':
328 raise GoofyRuntimeException(
329 'The requested test run was interrupted.')
beeps7583e582013-08-28 16:19:24 -0700330
331
Ricky Liang74317062014-03-04 17:20:05 +0800332 def _synchronous_run_suite(self, suite_name):
beeps7583e582013-08-28 16:19:24 -0700333 """Run one suite and wait for it to finish.
334
Ricky Liang74317062014-03-04 17:20:05 +0800335 Will start a test run for the specified suite_name and wait until it
336 ends.
beeps7583e582013-08-28 16:19:24 -0700337
338 @param suite_name: The name of the suite to wait for.
beeps7583e582013-08-28 16:19:24 -0700339
340 @raises GoofyProxyException: If the status of the suite
341 doesn't switch to active after we call RunTest.
342
343 @return: The result of the suite.
344 """
beeps04561352013-10-04 11:07:47 -0700345 logging.info('Starting suite: %s', suite_name)
Ricky Liang74317062014-03-04 17:20:05 +0800346 run_id = self._client.RunTest(suite_name)
347 self._wait_on_run(run_id)
348 return self._get_test_run_info(run_id)
beeps7583e582013-08-28 16:19:24 -0700349
350
351 def monitor_tests(self, test_list):
352 """Run a test list.
353
354 Will run each suite in the given list in sequence, starting each one
355 by name and waiting on its results. This method makes the following
356 assumptions:
357 - A test list is made up of self contained suites.
358 - These suites trigger several things in parallel.
359 - After a suite finishes it leaves goofy in an idle state.
360
361 It is not safe to pull results for individual tests during the suite
362 as the device could be rebooting, or goofy could be under stress.
363 Instead, this method synchronously waits on an entire suite, then
364 asks goofy for the status of each test in the suite. Since certain
365 test lists automatically start and others don't, this method stops
366 test list execution regardless, and sequentially triggers each suite.
367
368 @param test_list: The test list to run.
369 """
370 self._set_test_list(test_list)
371 self._wait_for_goofy()
372 self._stop_running_tests()
373
374 test_map = self._get_test_map()
beeps04561352013-10-04 11:07:47 -0700375 if test_map:
376 logging.info('About to execute tests: %s', test_map)
377 else:
378 raise GoofyRuntimeException('Test map is empty, you might have an '
379 'error in your test_list.')
380
381
beeps7583e582013-08-28 16:19:24 -0700382 for current_suite in test_map.keys():
383 logging.info('Processing suite %s', current_suite)
384
Ricky Liang74317062014-03-04 17:20:05 +0800385 result = self._synchronous_run_suite(current_suite)
beeps7583e582013-08-28 16:19:24 -0700386 logging.info(result)
387
388 for test_names in test_map.get(current_suite):
389 self._log_test_results(self._get_test_info(test_names),
390 current_suite)
391
392
beeps04561352013-10-04 11:07:47 -0700393 @retry_goofy_rpc((httplib.BadStatusLine, socket.error),
394 timeout_min=BASE_RPC_TIMEOUT*2)
beeps7583e582013-08-28 16:19:24 -0700395 def get_results(self, resultsdir):
396 """Copies results from the DUT to a local results directory.
397
398 Copy the tarball over to the results folder, untar, and delete the
399 tarball if everything was successful. This will effectively place
400 all the logs relevant to factory testing in the job's results folder.
401
402 @param resultsdir: The directory in which to untar the contents of the
403 tarball factory_bug generates.
404 """
405 logging.info('Getting results logs for test_list.')
406
407 try:
408 factory_bug_log = self._host.run('factory_bug').stderr
409 except error.CmdError as e:
410 logging.error('Could not execute factory_bug: %s', e)
411 return
412
413 try:
414 factory_bug_tar = re.match(self.FACTORY_BUG_RE,
415 factory_bug_log).groups(1)[0]
416 except (IndexError, AttributeError):
417 logging.error('could not collect logs for factory results, '
418 'factory bug returned %s', factory_bug_log)
419 return
420
421 factory_bug_tar_file = os.path.basename(factory_bug_tar)
422 local_factory_bug_tar = os.path.join(resultsdir, factory_bug_tar_file)
423
424 try:
425 self._host.get_file(factory_bug_tar, local_factory_bug_tar)
426 except error.AutoservRunError as e:
427 logging.error('Failed to pull back the results tarball: %s', e)
428 return
429
430 try:
431 utils.run(self.UNTAR_COMMAND % (local_factory_bug_tar, resultsdir))
432 except error.CmdError as e:
433 logging.error('Failed to untar the results tarball: %s', e)
434 return
435 finally:
436 if os.path.exists(local_factory_bug_tar):
437 os.remove(local_factory_bug_tar)