blob: 987673720f17540ff5a648a893a88a66dcedafcf [file] [log] [blame]
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001#!/usr/bin/python -u
Hung-Te Linf2f78f72012-02-08 19:27:11 +08002# -*- coding: utf-8 -*-
3#
Jon Salz37eccbd2012-05-25 16:06:52 +08004# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
Hung-Te Linf2f78f72012-02-08 19:27:11 +08005# Use of this source code is governed by a BSD-style license that can be
6# found in the LICENSE file.
7
8'''
9The main factory flow that runs the factory test and finalizes a device.
10'''
11
Jon Salz0405ab52012-03-16 15:26:52 +080012import logging
13import os
Jon Salz73e0fd02012-04-04 11:46:38 +080014import Queue
Jon Salz77c151e2012-08-28 07:20:37 +080015import signal
Jon Salz0405ab52012-03-16 15:26:52 +080016import sys
Jon Salz0405ab52012-03-16 15:26:52 +080017import threading
18import time
19import traceback
Jon Salz258a40c2012-04-19 12:34:01 +080020import uuid
Jon Salzb10cf512012-08-09 17:29:21 +080021from xmlrpclib import Binary
Hung-Te Linf2f78f72012-02-08 19:27:11 +080022from collections import deque
23from optparse import OptionParser
Hung-Te Linf2f78f72012-02-08 19:27:11 +080024
Jon Salz0697cbf2012-07-04 15:14:04 +080025import factory_common # pylint: disable=W0611
jcliangcd688182012-08-20 21:01:26 +080026from cros.factory import event_log
27from cros.factory import system
28from cros.factory.event_log import EventLog
29from cros.factory.goofy import test_environment
30from cros.factory.goofy import time_sanitizer
Jon Salz83591782012-06-26 11:09:58 +080031from cros.factory.goofy import updater
Jon Salz51528e12012-07-02 18:54:45 +080032from cros.factory.goofy.event_log_watcher import EventLogWatcher
jcliangcd688182012-08-20 21:01:26 +080033from cros.factory.goofy.goofy_rpc import GoofyRPC
34from cros.factory.goofy.invocation import TestInvocation
35from cros.factory.goofy.prespawner import Prespawner
36from cros.factory.goofy.web_socket_manager import WebSocketManager
37from cros.factory.system.charge_manager import ChargeManager
Jon Salzb92c5112012-09-21 15:40:11 +080038from cros.factory.system import disk_space
jcliangcd688182012-08-20 21:01:26 +080039from cros.factory.test import factory
40from cros.factory.test import state
Jon Salz51528e12012-07-02 18:54:45 +080041from cros.factory.test import shopfloor
Jon Salz83591782012-06-26 11:09:58 +080042from cros.factory.test import utils
43from cros.factory.test.event import Event
44from cros.factory.test.event import EventClient
45from cros.factory.test.event import EventServer
jcliangcd688182012-08-20 21:01:26 +080046from cros.factory.test.factory import TestState
Jon Salz78c32392012-07-25 14:18:29 +080047from cros.factory.utils.process_utils import Spawn
Hung-Te Linf2f78f72012-02-08 19:27:11 +080048
49
Jon Salz2f757d42012-06-27 17:06:42 +080050DEFAULT_TEST_LISTS_DIR = os.path.join(factory.FACTORY_PATH, 'test_lists')
51CUSTOM_DIR = os.path.join(factory.FACTORY_PATH, 'custom')
Hung-Te Linf2f78f72012-02-08 19:27:11 +080052HWID_CFG_PATH = '/usr/local/share/chromeos-hwid/cfg'
53
Jon Salz8796e362012-05-24 11:39:09 +080054# File that suppresses reboot if present (e.g., for development).
55NO_REBOOT_FILE = '/var/log/factory.noreboot'
56
Jon Salz5c344f62012-07-13 14:31:16 +080057# Value for tests_after_shutdown that forces auto-run (e.g., after
58# a factory update, when the available set of tests might change).
59FORCE_AUTO_RUN = 'force_auto_run'
60
cychiang21886742012-07-05 15:16:32 +080061RUN_QUEUE_TIMEOUT_SECS = 10
62
Jon Salz758e6cc2012-04-03 15:47:07 +080063GOOFY_IN_CHROOT_WARNING = '\n' + ('*' * 70) + '''
64You are running Goofy inside the chroot. Autotests are not supported.
65
66To use Goofy in the chroot, first install an Xvnc server:
67
Jon Salz0697cbf2012-07-04 15:14:04 +080068 sudo apt-get install tightvncserver
Jon Salz758e6cc2012-04-03 15:47:07 +080069
70...and then start a VNC X server outside the chroot:
71
Jon Salz0697cbf2012-07-04 15:14:04 +080072 vncserver :10 &
73 vncviewer :10
Jon Salz758e6cc2012-04-03 15:47:07 +080074
75...and run Goofy as follows:
76
Jon Salz0697cbf2012-07-04 15:14:04 +080077 env --unset=XAUTHORITY DISPLAY=localhost:10 python goofy.py
Jon Salz758e6cc2012-04-03 15:47:07 +080078''' + ('*' * 70)
Jon Salz73e0fd02012-04-04 11:46:38 +080079suppress_chroot_warning = False
Hung-Te Linf2f78f72012-02-08 19:27:11 +080080
81def get_hwid_cfg():
Jon Salz0697cbf2012-07-04 15:14:04 +080082 '''
83 Returns the HWID config tag, or an empty string if none can be found.
84 '''
85 if 'CROS_HWID' in os.environ:
86 return os.environ['CROS_HWID']
87 if os.path.exists(HWID_CFG_PATH):
88 with open(HWID_CFG_PATH, 'rt') as hwid_cfg_handle:
89 return hwid_cfg_handle.read().strip()
90 return ''
Hung-Te Linf2f78f72012-02-08 19:27:11 +080091
92
93def find_test_list():
Jon Salz0697cbf2012-07-04 15:14:04 +080094 '''
95 Returns the path to the active test list, based on the HWID config tag.
96 '''
97 hwid_cfg = get_hwid_cfg()
Hung-Te Linf2f78f72012-02-08 19:27:11 +080098
Jon Salz4be56b02012-12-22 07:30:46 +080099 search_dirs = [DEFAULT_TEST_LISTS_DIR]
100 if not utils.in_chroot():
101 # Also look in suite_Factory. For backward compatibility only;
102 # new boards should just put the test list in the "test_lists"
103 # directory.
104 search_dirs.insert(0, os.path.join(
105 os.path.dirname(factory.FACTORY_PATH),
106 'autotest', 'site_tests', 'suite_Factory'))
Jon Salz2f757d42012-06-27 17:06:42 +0800107
Jon Salz0697cbf2012-07-04 15:14:04 +0800108 # Try in order: test_list_${hwid_cfg}, test_list, test_list.all
109 search_files = ['test_list', 'test_list.all']
110 if hwid_cfg:
111 search_files.insert(0, hwid_cfg)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800112
Jon Salz0697cbf2012-07-04 15:14:04 +0800113 for d in search_dirs:
114 for f in search_files:
115 test_list = os.path.join(d, f)
116 if os.path.exists(test_list):
117 return test_list
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800118
Jon Salz0697cbf2012-07-04 15:14:04 +0800119 logging.warn('Cannot find test lists named any of %s in any of %s',
120 search_files, search_dirs)
121 return None
Jon Salz73e0fd02012-04-04 11:46:38 +0800122
Jon Salz73e0fd02012-04-04 11:46:38 +0800123_inited_logging = False
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800124
125class Goofy(object):
Jon Salz0697cbf2012-07-04 15:14:04 +0800126 '''
127 The main factory flow.
128
129 Note that all methods in this class must be invoked from the main
130 (event) thread. Other threads, such as callbacks and TestInvocation
131 methods, should instead post events on the run queue.
132
133 TODO: Unit tests. (chrome-os-partner:7409)
134
135 Properties:
136 uuid: A unique UUID for this invocation of Goofy.
137 state_instance: An instance of FactoryState.
138 state_server: The FactoryState XML/RPC server.
139 state_server_thread: A thread running state_server.
140 event_server: The EventServer socket server.
141 event_server_thread: A thread running event_server.
142 event_client: A client to the event server.
143 connection_manager: The connection_manager object.
Jon Salz0697cbf2012-07-04 15:14:04 +0800144 ui_process: The factory ui process object.
145 run_queue: A queue of callbacks to invoke from the main thread.
146 invocations: A map from FactoryTest objects to the corresponding
147 TestInvocations objects representing active tests.
148 tests_to_run: A deque of tests that should be run when the current
149 test(s) complete.
150 options: Command-line options.
151 args: Command-line args.
152 test_list: The test list.
153 event_handlers: Map of Event.Type to the method used to handle that
154 event. If the method has an 'event' argument, the event is passed
155 to the handler.
156 exceptions: Exceptions encountered in invocation threads.
157 '''
158 def __init__(self):
159 self.uuid = str(uuid.uuid4())
160 self.state_instance = None
161 self.state_server = None
162 self.state_server_thread = None
Jon Salz16d10542012-07-23 12:18:45 +0800163 self.goofy_rpc = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800164 self.event_server = None
165 self.event_server_thread = None
166 self.event_client = None
167 self.connection_manager = None
Vic Yang4953fc12012-07-26 16:19:53 +0800168 self.charge_manager = None
Jon Salz8fa8e832012-07-13 19:04:09 +0800169 self.time_sanitizer = None
170 self.time_synced = False
Jon Salz0697cbf2012-07-04 15:14:04 +0800171 self.log_watcher = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800172 self.event_log = None
173 self.prespawner = None
174 self.ui_process = None
Jon Salzc79a9982012-08-30 04:42:01 +0800175 self.dummy_shopfloor = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800176 self.run_queue = Queue.Queue()
177 self.invocations = {}
178 self.tests_to_run = deque()
179 self.visible_test = None
180 self.chrome = None
181
182 self.options = None
183 self.args = None
184 self.test_list = None
185 self.on_ui_startup = []
186 self.env = None
Jon Salzb22d1172012-08-06 10:38:57 +0800187 self.last_idle = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800188 self.last_shutdown_time = None
cychiang21886742012-07-05 15:16:32 +0800189 self.last_update_check = None
Jon Salz8fa8e832012-07-13 19:04:09 +0800190 self.last_sync_time = None
Jon Salzb92c5112012-09-21 15:40:11 +0800191 self.last_log_disk_space_time = None
Vic Yang311ddb82012-09-26 12:08:28 +0800192 self.exclusive_items = set()
Jon Salz0f996602012-10-03 15:26:48 +0800193 self.event_log = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800194
Jon Salz85a39882012-07-05 16:45:04 +0800195 def test_or_root(event, parent_or_group=True):
196 '''Returns the test affected by a particular event.
197
198 Args:
199 event: The event containing an optional 'path' attribute.
200 parent_on_group: If True, returns the top-level parent for a test (the
201 root node of the tests that need to be run together if the given test
202 path is to be run).
203 '''
Jon Salz0697cbf2012-07-04 15:14:04 +0800204 try:
205 path = event.path
206 except AttributeError:
207 path = None
208
209 if path:
Jon Salz85a39882012-07-05 16:45:04 +0800210 test = self.test_list.lookup_path(path)
211 if parent_or_group:
212 test = test.get_top_level_parent_or_group()
213 return test
Jon Salz0697cbf2012-07-04 15:14:04 +0800214 else:
215 return self.test_list
216
217 self.event_handlers = {
218 Event.Type.SWITCH_TEST: self.handle_switch_test,
219 Event.Type.SHOW_NEXT_ACTIVE_TEST:
220 lambda event: self.show_next_active_test(),
221 Event.Type.RESTART_TESTS:
222 lambda event: self.restart_tests(root=test_or_root(event)),
223 Event.Type.AUTO_RUN:
224 lambda event: self.auto_run(root=test_or_root(event)),
225 Event.Type.RE_RUN_FAILED:
226 lambda event: self.re_run_failed(root=test_or_root(event)),
227 Event.Type.RUN_TESTS_WITH_STATUS:
228 lambda event: self.run_tests_with_status(
229 event.status,
230 root=test_or_root(event)),
231 Event.Type.REVIEW:
232 lambda event: self.show_review_information(),
233 Event.Type.UPDATE_SYSTEM_INFO:
234 lambda event: self.update_system_info(),
Jon Salz0697cbf2012-07-04 15:14:04 +0800235 Event.Type.STOP:
Jon Salz85a39882012-07-05 16:45:04 +0800236 lambda event: self.stop(root=test_or_root(event, False),
237 fail=getattr(event, 'fail', False)),
Jon Salz36fbbb52012-07-05 13:45:06 +0800238 Event.Type.SET_VISIBLE_TEST:
239 lambda event: self.set_visible_test(
240 self.test_list.lookup_path(event.path)),
Jon Salz0697cbf2012-07-04 15:14:04 +0800241 }
242
243 self.exceptions = []
244 self.web_socket_manager = None
245
246 def destroy(self):
247 if self.chrome:
248 self.chrome.kill()
249 self.chrome = None
Jon Salzc79a9982012-08-30 04:42:01 +0800250 if self.dummy_shopfloor:
251 self.dummy_shopfloor.kill()
252 self.dummy_shopfloor = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800253 if self.ui_process:
254 utils.kill_process_tree(self.ui_process, 'ui')
255 self.ui_process = None
256 if self.web_socket_manager:
257 logging.info('Stopping web sockets')
258 self.web_socket_manager.close()
259 self.web_socket_manager = None
260 if self.state_server_thread:
261 logging.info('Stopping state server')
262 self.state_server.shutdown()
263 self.state_server_thread.join()
264 self.state_server.server_close()
265 self.state_server_thread = None
266 if self.state_instance:
267 self.state_instance.close()
268 if self.event_server_thread:
269 logging.info('Stopping event server')
270 self.event_server.shutdown() # pylint: disable=E1101
271 self.event_server_thread.join()
272 self.event_server.server_close()
273 self.event_server_thread = None
274 if self.log_watcher:
275 if self.log_watcher.IsThreadStarted():
276 self.log_watcher.StopWatchThread()
277 self.log_watcher = None
278 if self.prespawner:
279 logging.info('Stopping prespawner')
280 self.prespawner.stop()
281 self.prespawner = None
282 if self.event_client:
283 logging.info('Closing event client')
284 self.event_client.close()
285 self.event_client = None
286 if self.event_log:
287 self.event_log.Close()
288 self.event_log = None
289 self.check_exceptions()
290 logging.info('Done destroying Goofy')
291
292 def start_state_server(self):
293 self.state_instance, self.state_server = (
294 state.create_server(bind_address='0.0.0.0'))
Jon Salz16d10542012-07-23 12:18:45 +0800295 self.goofy_rpc = GoofyRPC(self)
296 self.goofy_rpc.RegisterMethods(self.state_instance)
Jon Salz0697cbf2012-07-04 15:14:04 +0800297 logging.info('Starting state server')
298 self.state_server_thread = threading.Thread(
299 target=self.state_server.serve_forever,
300 name='StateServer')
301 self.state_server_thread.start()
302
303 def start_event_server(self):
304 self.event_server = EventServer()
305 logging.info('Starting factory event server')
306 self.event_server_thread = threading.Thread(
307 target=self.event_server.serve_forever,
308 name='EventServer') # pylint: disable=E1101
309 self.event_server_thread.start()
310
311 self.event_client = EventClient(
312 callback=self.handle_event, event_loop=self.run_queue)
313
314 self.web_socket_manager = WebSocketManager(self.uuid)
315 self.state_server.add_handler("/event",
316 self.web_socket_manager.handle_web_socket)
317
318 def start_ui(self):
319 ui_proc_args = [
320 os.path.join(factory.FACTORY_PACKAGE_PATH, 'test', 'ui.py'),
321 self.options.test_list]
322 if self.options.verbose:
323 ui_proc_args.append('-v')
324 logging.info('Starting ui %s', ui_proc_args)
Jon Salz78c32392012-07-25 14:18:29 +0800325 self.ui_process = Spawn(ui_proc_args)
Jon Salz0697cbf2012-07-04 15:14:04 +0800326 logging.info('Waiting for UI to come up...')
327 self.event_client.wait(
328 lambda event: event.type == Event.Type.UI_READY)
329 logging.info('UI has started')
330
331 def set_visible_test(self, test):
332 if self.visible_test == test:
333 return
Jon Salz2f2d42c2012-07-30 12:30:34 +0800334 if test and not test.has_ui:
335 return
Jon Salz0697cbf2012-07-04 15:14:04 +0800336
337 if test:
338 test.update_state(visible=True)
339 if self.visible_test:
340 self.visible_test.update_state(visible=False)
341 self.visible_test = test
342
343 def handle_shutdown_complete(self, test, test_state):
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800344 '''
Jon Salz0697cbf2012-07-04 15:14:04 +0800345 Handles the case where a shutdown was detected during a shutdown step.
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800346
Jon Salz0697cbf2012-07-04 15:14:04 +0800347 @param test: The ShutdownStep.
348 @param test_state: The test state.
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800349 '''
Jon Salz0697cbf2012-07-04 15:14:04 +0800350 test_state = test.update_state(increment_shutdown_count=1)
351 logging.info('Detected shutdown (%d of %d)',
352 test_state.shutdown_count, test.iterations)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800353
Jon Salz0697cbf2012-07-04 15:14:04 +0800354 def log_and_update_state(status, error_msg, **kw):
355 self.event_log.Log('rebooted',
356 status=status, error_msg=error_msg, **kw)
357 test.update_state(status=status, error_msg=error_msg)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800358
Jon Salz0697cbf2012-07-04 15:14:04 +0800359 if not self.last_shutdown_time:
360 log_and_update_state(status=TestState.FAILED,
361 error_msg='Unable to read shutdown_time')
362 return
Jon Salz258a40c2012-04-19 12:34:01 +0800363
Jon Salz0697cbf2012-07-04 15:14:04 +0800364 now = time.time()
365 logging.info('%.03f s passed since reboot',
366 now - self.last_shutdown_time)
Jon Salz258a40c2012-04-19 12:34:01 +0800367
Jon Salz0697cbf2012-07-04 15:14:04 +0800368 if self.last_shutdown_time > now:
369 test.update_state(status=TestState.FAILED,
370 error_msg='Time moved backward during reboot')
371 elif (isinstance(test, factory.RebootStep) and
372 self.test_list.options.max_reboot_time_secs and
373 (now - self.last_shutdown_time >
374 self.test_list.options.max_reboot_time_secs)):
375 # A reboot took too long; fail. (We don't check this for
376 # HaltSteps, because the machine could be halted for a
377 # very long time, and even unplugged with battery backup,
378 # thus hosing the clock.)
379 log_and_update_state(
380 status=TestState.FAILED,
381 error_msg=('More than %d s elapsed during reboot '
382 '(%.03f s, from %s to %s)' % (
383 self.test_list.options.max_reboot_time_secs,
384 now - self.last_shutdown_time,
385 utils.TimeString(self.last_shutdown_time),
386 utils.TimeString(now))),
387 duration=(now-self.last_shutdown_time))
388 elif test_state.shutdown_count == test.iterations:
389 # Good!
390 log_and_update_state(status=TestState.PASSED,
391 duration=(now - self.last_shutdown_time),
392 error_msg='')
393 elif test_state.shutdown_count > test.iterations:
394 # Shut down too many times
395 log_and_update_state(status=TestState.FAILED,
396 error_msg='Too many shutdowns')
397 elif utils.are_shift_keys_depressed():
398 logging.info('Shift keys are depressed; cancelling restarts')
399 # Abort shutdown
400 log_and_update_state(
401 status=TestState.FAILED,
402 error_msg='Shutdown aborted with double shift keys')
Jon Salza6711d72012-07-18 14:33:03 +0800403 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +0800404 else:
405 def handler():
406 if self._prompt_cancel_shutdown(
407 test, test_state.shutdown_count + 1):
Jon Salza6711d72012-07-18 14:33:03 +0800408 factory.console.info('Shutdown aborted by operator')
Jon Salz0697cbf2012-07-04 15:14:04 +0800409 log_and_update_state(
410 status=TestState.FAILED,
411 error_msg='Shutdown aborted by operator')
Jon Salza6711d72012-07-18 14:33:03 +0800412 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +0800413 return
Jon Salz0405ab52012-03-16 15:26:52 +0800414
Jon Salz0697cbf2012-07-04 15:14:04 +0800415 # Time to shutdown again
416 log_and_update_state(
417 status=TestState.ACTIVE,
418 error_msg='',
419 iteration=test_state.shutdown_count)
Jon Salz73e0fd02012-04-04 11:46:38 +0800420
Jon Salz0697cbf2012-07-04 15:14:04 +0800421 self.event_log.Log('shutdown', operation='reboot')
422 self.state_instance.set_shared_data('shutdown_time',
423 time.time())
424 self.env.shutdown('reboot')
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800425
Jon Salz0697cbf2012-07-04 15:14:04 +0800426 self.on_ui_startup.append(handler)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800427
Jon Salz0697cbf2012-07-04 15:14:04 +0800428 def _prompt_cancel_shutdown(self, test, iteration):
429 if self.options.ui != 'chrome':
430 return False
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800431
Jon Salz0697cbf2012-07-04 15:14:04 +0800432 pending_shutdown_data = {
433 'delay_secs': test.delay_secs,
434 'time': time.time() + test.delay_secs,
435 'operation': test.operation,
436 'iteration': iteration,
437 'iterations': test.iterations,
438 }
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800439
Jon Salz0697cbf2012-07-04 15:14:04 +0800440 # Create a new (threaded) event client since we
441 # don't want to use the event loop for this.
442 with EventClient() as event_client:
443 event_client.post_event(Event(Event.Type.PENDING_SHUTDOWN,
444 **pending_shutdown_data))
445 aborted = event_client.wait(
446 lambda event: event.type == Event.Type.CANCEL_SHUTDOWN,
447 timeout=test.delay_secs) is not None
448 if aborted:
449 event_client.post_event(Event(Event.Type.PENDING_SHUTDOWN))
450 return aborted
Jon Salz258a40c2012-04-19 12:34:01 +0800451
Jon Salz0697cbf2012-07-04 15:14:04 +0800452 def init_states(self):
453 '''
454 Initializes all states on startup.
455 '''
456 for test in self.test_list.get_all_tests():
457 # Make sure the state server knows about all the tests,
458 # defaulting to an untested state.
459 test.update_state(update_parent=False, visible=False)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800460
Jon Salz0697cbf2012-07-04 15:14:04 +0800461 var_log_messages = None
Vic Yanga9c32212012-08-16 20:07:54 +0800462 mosys_log = None
Vic Yange4c275d2012-08-28 01:50:20 +0800463 ec_console_log = None
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800464
Jon Salz0697cbf2012-07-04 15:14:04 +0800465 # Any 'active' tests should be marked as failed now.
466 for test in self.test_list.walk():
Jon Salza6711d72012-07-18 14:33:03 +0800467 if not test.is_leaf():
468 # Don't bother with parents; they will be updated when their
469 # children are updated.
470 continue
471
Jon Salz0697cbf2012-07-04 15:14:04 +0800472 test_state = test.get_state()
473 if test_state.status != TestState.ACTIVE:
474 continue
475 if isinstance(test, factory.ShutdownStep):
476 # Shutdown while the test was active - that's good.
477 self.handle_shutdown_complete(test, test_state)
478 else:
479 # Unexpected shutdown. Grab /var/log/messages for context.
480 if var_log_messages is None:
481 try:
482 var_log_messages = (
483 utils.var_log_messages_before_reboot())
484 # Write it to the log, to make it easier to
485 # correlate with /var/log/messages.
486 logging.info(
487 'Unexpected shutdown. '
488 'Tail of /var/log/messages before last reboot:\n'
489 '%s', ('\n'.join(
490 ' ' + x for x in var_log_messages)))
491 except: # pylint: disable=W0702
492 logging.exception('Unable to grok /var/log/messages')
493 var_log_messages = []
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800494
Jon Salz008f4ea2012-08-28 05:39:45 +0800495 if mosys_log is None and not utils.in_chroot():
496 try:
497 mosys_log = utils.Spawn(
498 ['mosys', 'eventlog', 'list'],
499 read_stdout=True, log_stderr_on_error=True).stdout_data
500 # Write it to the log also.
501 logging.info('System eventlog from mosys:\n%s\n', mosys_log)
502 except: # pylint: disable=W0702
503 logging.exception('Unable to read mosys eventlog')
Vic Yanga9c32212012-08-16 20:07:54 +0800504
Vic Yange4c275d2012-08-28 01:50:20 +0800505 if ec_console_log is None:
506 try:
507 ec = system.GetEC()
508 ec_console_log = ec.GetConsoleLog()
509 logging.info('EC console log after reboot:\n%s\n', ec_console_log)
Jon Salzfe1f6652012-09-07 05:40:14 +0800510 except: # pylint: disable=W0702
Vic Yange4c275d2012-08-28 01:50:20 +0800511 logging.exception('Error retrieving EC console log')
512
Jon Salz0697cbf2012-07-04 15:14:04 +0800513 error_msg = 'Unexpected shutdown while test was running'
514 self.event_log.Log('end_test',
515 path=test.path,
516 status=TestState.FAILED,
517 invocation=test.get_state().invocation,
518 error_msg=error_msg,
Vic Yanga9c32212012-08-16 20:07:54 +0800519 var_log_messages='\n'.join(var_log_messages),
520 mosys_log=mosys_log)
Jon Salz0697cbf2012-07-04 15:14:04 +0800521 test.update_state(
522 status=TestState.FAILED,
523 error_msg=error_msg)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800524
Jon Salz50efe942012-07-26 11:54:10 +0800525 if not test.never_fails:
526 # For "never_fails" tests (such as "Start"), don't cancel
527 # pending tests, since reboot is expected.
528 factory.console.info('Unexpected shutdown while test %s '
529 'running; cancelling any pending tests',
530 test.path)
531 self.state_instance.set_shared_data('tests_after_shutdown', [])
Jon Salz69806bb2012-07-20 18:05:02 +0800532
Jon Salz008f4ea2012-08-28 05:39:45 +0800533 self.update_skipped_tests()
534
535 def update_skipped_tests(self):
536 '''
537 Updates skipped states based on run_if.
538 '''
539 for t in self.test_list.walk():
540 if t.is_leaf() and t.run_if_table_name:
541 skip = False
542 try:
543 aux = shopfloor.get_selected_aux_data(t.run_if_table_name)
544 value = aux.get(t.run_if_col)
545 if value is not None:
546 skip = (not value) ^ t.run_if_not
547 except ValueError:
548 # Not available; assume it shouldn't be skipped
549 pass
550
551 test_state = t.get_state()
552 if ((not skip) and
553 (test_state.status == TestState.PASSED) and
554 (test_state.error_msg == TestState.SKIPPED_MSG)):
555 # It was marked as skipped before, but now we need to run it.
556 # Mark as untested.
557 t.update_state(skip=skip, status=TestState.UNTESTED, error_msg='')
558 else:
559 t.update_state(skip=skip)
560
Jon Salz0697cbf2012-07-04 15:14:04 +0800561 def show_next_active_test(self):
562 '''
563 Rotates to the next visible active test.
564 '''
565 self.reap_completed_tests()
566 active_tests = [
567 t for t in self.test_list.walk()
568 if t.is_leaf() and t.get_state().status == TestState.ACTIVE]
569 if not active_tests:
570 return
Jon Salz4f6c7172012-06-11 20:45:36 +0800571
Jon Salz0697cbf2012-07-04 15:14:04 +0800572 try:
573 next_test = active_tests[
574 (active_tests.index(self.visible_test) + 1) % len(active_tests)]
575 except ValueError: # visible_test not present in active_tests
576 next_test = active_tests[0]
Jon Salz4f6c7172012-06-11 20:45:36 +0800577
Jon Salz0697cbf2012-07-04 15:14:04 +0800578 self.set_visible_test(next_test)
Jon Salz4f6c7172012-06-11 20:45:36 +0800579
Jon Salz0697cbf2012-07-04 15:14:04 +0800580 def handle_event(self, event):
581 '''
582 Handles an event from the event server.
583 '''
584 handler = self.event_handlers.get(event.type)
585 if handler:
586 handler(event)
587 else:
588 # We don't register handlers for all event types - just ignore
589 # this event.
590 logging.debug('Unbound event type %s', event.type)
Jon Salz4f6c7172012-06-11 20:45:36 +0800591
Jon Salz0697cbf2012-07-04 15:14:04 +0800592 def run_next_test(self):
593 '''
594 Runs the next eligible test (or tests) in self.tests_to_run.
595 '''
596 self.reap_completed_tests()
597 while self.tests_to_run:
598 logging.debug('Tests to run: %s',
599 [x.path for x in self.tests_to_run])
Jon Salz94eb56f2012-06-12 18:01:12 +0800600
Jon Salz0697cbf2012-07-04 15:14:04 +0800601 test = self.tests_to_run[0]
Jon Salz94eb56f2012-06-12 18:01:12 +0800602
Jon Salz0697cbf2012-07-04 15:14:04 +0800603 if test in self.invocations:
604 logging.info('Next test %s is already running', test.path)
605 self.tests_to_run.popleft()
606 return
Jon Salz94eb56f2012-06-12 18:01:12 +0800607
Jon Salza1412922012-07-23 16:04:17 +0800608 for requirement in test.require_run:
609 for i in requirement.test.walk():
610 if i.get_state().status == TestState.ACTIVE:
Jon Salz304a75d2012-07-06 11:14:15 +0800611 logging.info('Waiting for active test %s to complete '
Jon Salza1412922012-07-23 16:04:17 +0800612 'before running %s', i.path, test.path)
Jon Salz304a75d2012-07-06 11:14:15 +0800613 return
614
Jon Salz0697cbf2012-07-04 15:14:04 +0800615 if self.invocations and not (test.backgroundable and all(
616 [x.backgroundable for x in self.invocations])):
617 logging.debug('Waiting for non-backgroundable tests to '
618 'complete before running %s', test.path)
619 return
Jon Salz94eb56f2012-06-12 18:01:12 +0800620
Jon Salz3e6f5202012-10-15 15:08:29 +0800621 if test.get_state().skip:
622 factory.console.info('Skipping test %s', test.path)
623 test.update_state(status=TestState.PASSED,
624 error_msg=TestState.SKIPPED_MSG)
625 self.tests_to_run.popleft()
626 continue
627
Jon Salz0697cbf2012-07-04 15:14:04 +0800628 self.tests_to_run.popleft()
Jon Salz94eb56f2012-06-12 18:01:12 +0800629
Jon Salz304a75d2012-07-06 11:14:15 +0800630 untested = set()
Jon Salza1412922012-07-23 16:04:17 +0800631 for requirement in test.require_run:
632 for i in requirement.test.walk():
633 if i == test:
Jon Salz304a75d2012-07-06 11:14:15 +0800634 # We've hit this test itself; stop checking
635 break
Jon Salza1412922012-07-23 16:04:17 +0800636 if ((i.get_state().status == TestState.UNTESTED) or
637 (requirement.passed and i.get_state().status !=
638 TestState.PASSED)):
Jon Salz304a75d2012-07-06 11:14:15 +0800639 # Found an untested test; move on to the next
640 # element in require_run.
Jon Salza1412922012-07-23 16:04:17 +0800641 untested.add(i)
Jon Salz304a75d2012-07-06 11:14:15 +0800642 break
643
644 if untested:
645 untested_paths = ', '.join(sorted([x.path for x in untested]))
646 if self.state_instance.get_shared_data('engineering_mode',
647 optional=True):
648 # In engineering mode, we'll let it go.
649 factory.console.warn('In engineering mode; running '
650 '%s even though required tests '
651 '[%s] have not completed',
652 test.path, untested_paths)
653 else:
654 # Not in engineering mode; mark it failed.
655 error_msg = ('Required tests [%s] have not been run yet'
656 % untested_paths)
657 factory.console.error('Not running %s: %s',
658 test.path, error_msg)
659 test.update_state(status=TestState.FAILED,
660 error_msg=error_msg)
661 continue
662
Jon Salz0697cbf2012-07-04 15:14:04 +0800663 if isinstance(test, factory.ShutdownStep):
664 if os.path.exists(NO_REBOOT_FILE):
665 test.update_state(
666 status=TestState.FAILED, increment_count=1,
667 error_msg=('Skipped shutdown since %s is present' %
Jon Salz304a75d2012-07-06 11:14:15 +0800668 NO_REBOOT_FILE))
Jon Salz0697cbf2012-07-04 15:14:04 +0800669 continue
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800670
Jon Salz0697cbf2012-07-04 15:14:04 +0800671 test.update_state(status=TestState.ACTIVE, increment_count=1,
672 error_msg='', shutdown_count=0)
673 if self._prompt_cancel_shutdown(test, 1):
674 self.event_log.Log('reboot_cancelled')
675 test.update_state(
676 status=TestState.FAILED, increment_count=1,
677 error_msg='Shutdown aborted by operator',
678 shutdown_count=0)
chungyiafe8f772012-08-15 19:36:29 +0800679 continue
Jon Salz2f757d42012-06-27 17:06:42 +0800680
Jon Salz0697cbf2012-07-04 15:14:04 +0800681 # Save pending test list in the state server
Jon Salzdbf398f2012-06-14 17:30:01 +0800682 self.state_instance.set_shared_data(
Jon Salz0697cbf2012-07-04 15:14:04 +0800683 'tests_after_shutdown',
684 [t.path for t in self.tests_to_run])
685 # Save shutdown time
686 self.state_instance.set_shared_data('shutdown_time',
687 time.time())
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800688
Jon Salz0697cbf2012-07-04 15:14:04 +0800689 with self.env.lock:
690 self.event_log.Log('shutdown', operation=test.operation)
691 shutdown_result = self.env.shutdown(test.operation)
692 if shutdown_result:
693 # That's all, folks!
694 self.run_queue.put(None)
695 return
696 else:
697 # Just pass (e.g., in the chroot).
698 test.update_state(status=TestState.PASSED)
699 self.state_instance.set_shared_data(
700 'tests_after_shutdown', None)
701 # Send event with no fields to indicate that there is no
702 # longer a pending shutdown.
703 self.event_client.post_event(Event(
704 Event.Type.PENDING_SHUTDOWN))
705 continue
Jon Salz258a40c2012-04-19 12:34:01 +0800706
Jon Salz1acc8742012-07-17 17:45:55 +0800707 self._run_test(test, test.iterations)
708
709 def _run_test(self, test, iterations_left=None):
710 invoc = TestInvocation(self, test, on_completion=self.run_next_test)
711 new_state = test.update_state(
712 status=TestState.ACTIVE, increment_count=1, error_msg='',
Jon Salzbd42ce12012-09-18 08:03:59 +0800713 invocation=invoc.uuid, iterations_left=iterations_left,
714 visible=(self.visible_test == test))
Jon Salz1acc8742012-07-17 17:45:55 +0800715 invoc.count = new_state.count
716
717 self.invocations[test] = invoc
718 if self.visible_test is None and test.has_ui:
719 self.set_visible_test(test)
Vic Yang311ddb82012-09-26 12:08:28 +0800720 self.check_exclusive()
Jon Salz1acc8742012-07-17 17:45:55 +0800721 invoc.start()
Jon Salz5f2a0672012-05-22 17:14:06 +0800722
Vic Yang311ddb82012-09-26 12:08:28 +0800723 def check_exclusive(self):
724 current_exclusive_items = set([
725 item
726 for item in factory.FactoryTest.EXCLUSIVE_OPTIONS
727 if any([test.is_exclusive(item) for test in self.invocations])])
728
729 new_exclusive_items = current_exclusive_items - self.exclusive_items
730 if factory.FactoryTest.EXCLUSIVE_OPTIONS.NETWORKING in new_exclusive_items:
731 logging.info('Disabling network')
732 self.connection_manager.DisableNetworking()
733 if factory.FactoryTest.EXCLUSIVE_OPTIONS.CHARGER in new_exclusive_items:
734 logging.info('Stop controlling charger')
735
736 new_non_exclusive_items = self.exclusive_items - current_exclusive_items
737 if (factory.FactoryTest.EXCLUSIVE_OPTIONS.NETWORKING in
738 new_non_exclusive_items):
739 logging.info('Re-enabling network')
740 self.connection_manager.EnableNetworking()
741 if factory.FactoryTest.EXCLUSIVE_OPTIONS.CHARGER in new_non_exclusive_items:
742 logging.info('Start controlling charger')
743
744 # Only adjust charge state if not excluded
745 if (self.charge_manager and
746 not factory.FactoryTest.EXCLUSIVE_OPTIONS.CHARGER in
747 current_exclusive_items):
748 self.charge_manager.AdjustChargeState()
749
750 self.exclusive_items = current_exclusive_items
Jon Salz5da61e62012-05-31 13:06:22 +0800751
cychiang21886742012-07-05 15:16:32 +0800752 def check_for_updates(self):
753 '''
754 Schedules an asynchronous check for updates if necessary.
755 '''
756 if not self.test_list.options.update_period_secs:
757 # Not enabled.
758 return
759
760 now = time.time()
761 if self.last_update_check and (
762 now - self.last_update_check <
763 self.test_list.options.update_period_secs):
764 # Not yet time for another check.
765 return
766
767 self.last_update_check = now
768
769 def handle_check_for_update(reached_shopfloor, md5sum, needs_update):
770 if reached_shopfloor:
771 new_update_md5sum = md5sum if needs_update else None
772 if system.SystemInfo.update_md5sum != new_update_md5sum:
773 logging.info('Received new update MD5SUM: %s', new_update_md5sum)
774 system.SystemInfo.update_md5sum = new_update_md5sum
775 self.run_queue.put(self.update_system_info)
776
777 updater.CheckForUpdateAsync(
778 handle_check_for_update,
779 self.test_list.options.shopfloor_timeout_secs)
780
Jon Salza6711d72012-07-18 14:33:03 +0800781 def cancel_pending_tests(self):
782 '''Cancels any tests in the run queue.'''
783 self.run_tests([])
784
Jon Salz0697cbf2012-07-04 15:14:04 +0800785 def run_tests(self, subtrees, untested_only=False):
786 '''
787 Runs tests under subtree.
Jon Salz258a40c2012-04-19 12:34:01 +0800788
Jon Salz0697cbf2012-07-04 15:14:04 +0800789 The tests are run in order unless one fails (then stops).
790 Backgroundable tests are run simultaneously; when a foreground test is
791 encountered, we wait for all active tests to finish before continuing.
Jon Salzb1b39092012-05-03 02:05:09 +0800792
Jon Salz0697cbf2012-07-04 15:14:04 +0800793 @param subtrees: Node or nodes containing tests to run (may either be
794 a single test or a list). Duplicates will be ignored.
795 '''
796 if type(subtrees) != list:
797 subtrees = [subtrees]
Jon Salz258a40c2012-04-19 12:34:01 +0800798
Jon Salz0697cbf2012-07-04 15:14:04 +0800799 # Nodes we've seen so far, to avoid duplicates.
800 seen = set()
Jon Salz94eb56f2012-06-12 18:01:12 +0800801
Jon Salz0697cbf2012-07-04 15:14:04 +0800802 self.tests_to_run = deque()
803 for subtree in subtrees:
804 for test in subtree.walk():
805 if test in seen:
806 continue
807 seen.add(test)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800808
Jon Salz0697cbf2012-07-04 15:14:04 +0800809 if not test.is_leaf():
810 continue
811 if (untested_only and
812 test.get_state().status != TestState.UNTESTED):
813 continue
814 self.tests_to_run.append(test)
815 self.run_next_test()
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800816
Jon Salz0697cbf2012-07-04 15:14:04 +0800817 def reap_completed_tests(self):
818 '''
819 Removes completed tests from the set of active tests.
820
821 Also updates the visible test if it was reaped.
822 '''
823 for t, v in dict(self.invocations).iteritems():
824 if v.is_completed():
Jon Salz1acc8742012-07-17 17:45:55 +0800825 new_state = t.update_state(**v.update_state_on_completion)
Jon Salz0697cbf2012-07-04 15:14:04 +0800826 del self.invocations[t]
827
Chun-Ta Lin54e17e42012-09-06 22:05:13 +0800828 # Stop on failure if flag is true.
829 if (self.test_list.options.stop_on_failure and
830 new_state.status == TestState.FAILED):
831 # Clean all the tests to cause goofy to stop.
832 self.tests_to_run = []
833 factory.console.info("Stop on failure triggered. Empty the queue.")
834
Jon Salz1acc8742012-07-17 17:45:55 +0800835 if new_state.iterations_left and new_state.status == TestState.PASSED:
836 # Play it again, Sam!
837 self._run_test(t)
838
Jon Salz0697cbf2012-07-04 15:14:04 +0800839 if (self.visible_test is None or
Jon Salz85a39882012-07-05 16:45:04 +0800840 self.visible_test not in self.invocations):
Jon Salz0697cbf2012-07-04 15:14:04 +0800841 self.set_visible_test(None)
842 # Make the first running test, if any, the visible test
843 for t in self.test_list.walk():
844 if t in self.invocations:
845 self.set_visible_test(t)
846 break
847
Jon Salz85a39882012-07-05 16:45:04 +0800848 def kill_active_tests(self, abort, root=None):
Jon Salz0697cbf2012-07-04 15:14:04 +0800849 '''
850 Kills and waits for all active tests.
851
Jon Salz85a39882012-07-05 16:45:04 +0800852 Args:
853 abort: True to change state of killed tests to FAILED, False for
Jon Salz0697cbf2012-07-04 15:14:04 +0800854 UNTESTED.
Jon Salz85a39882012-07-05 16:45:04 +0800855 root: If set, only kills tests with root as an ancestor.
Jon Salz0697cbf2012-07-04 15:14:04 +0800856 '''
857 self.reap_completed_tests()
858 for test, invoc in self.invocations.items():
Jon Salz85a39882012-07-05 16:45:04 +0800859 if root and not test.has_ancestor(root):
860 continue
861
Jon Salz0697cbf2012-07-04 15:14:04 +0800862 factory.console.info('Killing active test %s...' % test.path)
863 invoc.abort_and_join()
864 factory.console.info('Killed %s' % test.path)
Jon Salz1acc8742012-07-17 17:45:55 +0800865 test.update_state(**invoc.update_state_on_completion)
Jon Salz0697cbf2012-07-04 15:14:04 +0800866 del self.invocations[test]
Jon Salz1acc8742012-07-17 17:45:55 +0800867
Jon Salz0697cbf2012-07-04 15:14:04 +0800868 if not abort:
869 test.update_state(status=TestState.UNTESTED)
870 self.reap_completed_tests()
871
Jon Salz85a39882012-07-05 16:45:04 +0800872 def stop(self, root=None, fail=False):
873 self.kill_active_tests(fail, root)
874 # Remove any tests in the run queue under the root.
875 self.tests_to_run = deque([x for x in self.tests_to_run
876 if root and not x.has_ancestor(root)])
877 self.run_next_test()
Jon Salz0697cbf2012-07-04 15:14:04 +0800878
879 def abort_active_tests(self):
880 self.kill_active_tests(True)
881
882 def main(self):
883 try:
884 self.init()
885 self.event_log.Log('goofy_init',
886 success=True)
887 except:
888 if self.event_log:
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800889 try:
Jon Salz0697cbf2012-07-04 15:14:04 +0800890 self.event_log.Log('goofy_init',
891 success=False,
892 trace=traceback.format_exc())
893 except: # pylint: disable=W0702
894 pass
895 raise
896
897 self.run()
898
899 def update_system_info(self):
900 '''Updates system info.'''
901 system_info = system.SystemInfo()
902 self.state_instance.set_shared_data('system_info', system_info.__dict__)
903 self.event_client.post_event(Event(Event.Type.SYSTEM_INFO,
904 system_info=system_info.__dict__))
905 logging.info('System info: %r', system_info.__dict__)
906
Jon Salzeb42f0d2012-07-27 19:14:04 +0800907 def update_factory(self, auto_run_on_restart=False, post_update_hook=None):
908 '''Commences updating factory software.
909
910 Args:
911 auto_run_on_restart: Auto-run when the machine comes back up.
912 post_update_hook: Code to call after update but immediately before
913 restart.
914
915 Returns:
916 Never if the update was successful (we just reboot).
917 False if the update was unnecessary (no update available).
918 '''
Jon Salz0697cbf2012-07-04 15:14:04 +0800919 self.kill_active_tests(False)
Jon Salza6711d72012-07-18 14:33:03 +0800920 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +0800921
Jon Salz5c344f62012-07-13 14:31:16 +0800922 def pre_update_hook():
923 if auto_run_on_restart:
924 self.state_instance.set_shared_data('tests_after_shutdown',
925 FORCE_AUTO_RUN)
926 self.state_instance.close()
927
Jon Salzeb42f0d2012-07-27 19:14:04 +0800928 if updater.TryUpdate(pre_update_hook=pre_update_hook):
929 if post_update_hook:
930 post_update_hook()
931 self.env.shutdown('reboot')
Jon Salz0697cbf2012-07-04 15:14:04 +0800932
Jon Salzcef132a2012-08-30 04:58:08 +0800933 def handle_sigint(self, dummy_signum, dummy_frame):
Jon Salz77c151e2012-08-28 07:20:37 +0800934 logging.error('Received SIGINT')
935 self.run_queue.put(None)
936 raise KeyboardInterrupt()
937
Jon Salz0697cbf2012-07-04 15:14:04 +0800938 def init(self, args=None, env=None):
939 '''Initializes Goofy.
940
941 Args:
942 args: A list of command-line arguments. Uses sys.argv if
943 args is None.
944 env: An Environment instance to use (or None to choose
945 FakeChrootEnvironment or DUTEnvironment as appropriate).
946 '''
Jon Salz77c151e2012-08-28 07:20:37 +0800947 signal.signal(signal.SIGINT, self.handle_sigint)
948
Jon Salz0697cbf2012-07-04 15:14:04 +0800949 parser = OptionParser()
950 parser.add_option('-v', '--verbose', dest='verbose',
Jon Salz8fa8e832012-07-13 19:04:09 +0800951 action='store_true',
952 help='Enable debug logging')
Jon Salz0697cbf2012-07-04 15:14:04 +0800953 parser.add_option('--print_test_list', dest='print_test_list',
Jon Salz8fa8e832012-07-13 19:04:09 +0800954 metavar='FILE',
955 help='Read and print test list FILE, and exit')
Jon Salz0697cbf2012-07-04 15:14:04 +0800956 parser.add_option('--restart', dest='restart',
Jon Salz8fa8e832012-07-13 19:04:09 +0800957 action='store_true',
958 help='Clear all test state')
Jon Salz0697cbf2012-07-04 15:14:04 +0800959 parser.add_option('--ui', dest='ui', type='choice',
Jon Salz8fa8e832012-07-13 19:04:09 +0800960 choices=['none', 'gtk', 'chrome'],
961 default=('chrome' if utils.in_chroot() else 'gtk'),
962 help='UI to use')
Jon Salz0697cbf2012-07-04 15:14:04 +0800963 parser.add_option('--ui_scale_factor', dest='ui_scale_factor',
Jon Salz8fa8e832012-07-13 19:04:09 +0800964 type='int', default=1,
965 help=('Factor by which to scale UI '
966 '(Chrome UI only)'))
Jon Salz0697cbf2012-07-04 15:14:04 +0800967 parser.add_option('--test_list', dest='test_list',
Jon Salz8fa8e832012-07-13 19:04:09 +0800968 metavar='FILE',
969 help='Use FILE as test list')
Jon Salzc79a9982012-08-30 04:42:01 +0800970 parser.add_option('--dummy_shopfloor', action='store_true',
971 help='Use a dummy shopfloor server')
chungyiafe8f772012-08-15 19:36:29 +0800972 parser.add_option('--automation', dest='automation',
973 action='store_true',
974 help='Enable automation on running factory test')
Jon Salz0697cbf2012-07-04 15:14:04 +0800975 (self.options, self.args) = parser.parse_args(args)
976
Jon Salz46b89562012-07-05 11:49:22 +0800977 # Make sure factory directories exist.
978 factory.get_log_root()
979 factory.get_state_root()
980 factory.get_test_data_root()
981
Jon Salz0697cbf2012-07-04 15:14:04 +0800982 global _inited_logging # pylint: disable=W0603
983 if not _inited_logging:
984 factory.init_logging('goofy', verbose=self.options.verbose)
985 _inited_logging = True
Jon Salz8fa8e832012-07-13 19:04:09 +0800986
Jon Salz0f996602012-10-03 15:26:48 +0800987 if self.options.print_test_list:
988 print factory.read_test_list(
989 self.options.print_test_list).__repr__(recursive=True)
990 sys.exit(0)
991
Jon Salzee85d522012-07-17 14:34:46 +0800992 event_log.IncrementBootSequence()
Jon Salz0697cbf2012-07-04 15:14:04 +0800993 self.event_log = EventLog('goofy')
994
995 if (not suppress_chroot_warning and
996 factory.in_chroot() and
997 self.options.ui == 'gtk' and
998 os.environ.get('DISPLAY') in [None, '', ':0', ':0.0']):
999 # That's not going to work! Tell the user how to run
1000 # this way.
1001 logging.warn(GOOFY_IN_CHROOT_WARNING)
1002 time.sleep(1)
1003
1004 if env:
1005 self.env = env
1006 elif factory.in_chroot():
1007 self.env = test_environment.FakeChrootEnvironment()
1008 logging.warn(
1009 'Using chroot environment: will not actually run autotests')
1010 else:
1011 self.env = test_environment.DUTEnvironment()
1012 self.env.goofy = self
1013
1014 if self.options.restart:
1015 state.clear_state()
1016
Jon Salz0697cbf2012-07-04 15:14:04 +08001017 if self.options.ui_scale_factor != 1 and utils.in_qemu():
1018 logging.warn(
1019 'In QEMU; ignoring ui_scale_factor argument')
1020 self.options.ui_scale_factor = 1
1021
1022 logging.info('Started')
1023
1024 self.start_state_server()
1025 self.state_instance.set_shared_data('hwid_cfg', get_hwid_cfg())
1026 self.state_instance.set_shared_data('ui_scale_factor',
1027 self.options.ui_scale_factor)
1028 self.last_shutdown_time = (
1029 self.state_instance.get_shared_data('shutdown_time', optional=True))
1030 self.state_instance.del_shared_data('shutdown_time', optional=True)
1031
1032 if not self.options.test_list:
1033 self.options.test_list = find_test_list()
1034 if not self.options.test_list:
1035 logging.error('No test list. Aborting.')
1036 sys.exit(1)
1037 logging.info('Using test list %s', self.options.test_list)
1038
1039 self.test_list = factory.read_test_list(
1040 self.options.test_list,
Jon Salzeb42f0d2012-07-27 19:14:04 +08001041 self.state_instance)
Jon Salz0697cbf2012-07-04 15:14:04 +08001042 if not self.state_instance.has_shared_data('ui_lang'):
1043 self.state_instance.set_shared_data('ui_lang',
1044 self.test_list.options.ui_lang)
1045 self.state_instance.set_shared_data(
1046 'test_list_options',
1047 self.test_list.options.__dict__)
1048 self.state_instance.test_list = self.test_list
1049
Jon Salz83ef34b2012-11-01 19:46:35 +08001050 if not utils.in_chroot() and self.test_list.options.disable_log_rotation:
1051 open('/var/lib/cleanup_logs_paused', 'w').close()
1052
Jon Salz23926422012-09-01 03:38:13 +08001053 if self.options.dummy_shopfloor:
1054 os.environ[shopfloor.SHOPFLOOR_SERVER_ENV_VAR_NAME] = (
1055 'http://localhost:%d/' % shopfloor.DEFAULT_SERVER_PORT)
1056 self.dummy_shopfloor = Spawn(
1057 [os.path.join(factory.FACTORY_PATH, 'bin', 'shopfloor_server'),
1058 '--dummy'])
1059 elif self.test_list.options.shopfloor_server_url:
1060 shopfloor.set_server_url(self.test_list.options.shopfloor_server_url)
1061
Jon Salz0f996602012-10-03 15:26:48 +08001062 if self.test_list.options.time_sanitizer and not utils.in_chroot():
Jon Salz8fa8e832012-07-13 19:04:09 +08001063 self.time_sanitizer = time_sanitizer.TimeSanitizer(
1064 base_time=time_sanitizer.GetBaseTimeFromFile(
1065 # lsb-factory is written by the factory install shim during
1066 # installation, so it should have a good time obtained from
Jon Salz54882d02012-08-31 01:57:54 +08001067 # the mini-Omaha server. If it's not available, we'll use
1068 # /etc/lsb-factory (which will be much older, but reasonably
1069 # sane) and rely on a shopfloor sync to set a more accurate
1070 # time.
1071 '/usr/local/etc/lsb-factory',
1072 '/etc/lsb-release'))
Jon Salz8fa8e832012-07-13 19:04:09 +08001073 self.time_sanitizer.RunOnce()
1074
Jon Salz0697cbf2012-07-04 15:14:04 +08001075 self.init_states()
1076 self.start_event_server()
1077 self.connection_manager = self.env.create_connection_manager(
Tai-Hsu Lin371351a2012-08-27 14:17:14 +08001078 self.test_list.options.wlans,
1079 self.test_list.options.scan_wifi_period_secs)
Jon Salz0697cbf2012-07-04 15:14:04 +08001080 # Note that we create a log watcher even if
1081 # sync_event_log_period_secs isn't set (no background
1082 # syncing), since we may use it to flush event logs as well.
1083 self.log_watcher = EventLogWatcher(
1084 self.test_list.options.sync_event_log_period_secs,
Jon Salz16d10542012-07-23 12:18:45 +08001085 handle_event_logs_callback=self.handle_event_logs)
Jon Salz0697cbf2012-07-04 15:14:04 +08001086 if self.test_list.options.sync_event_log_period_secs:
1087 self.log_watcher.StartWatchThread()
1088
1089 self.update_system_info()
1090
Vic Yang4953fc12012-07-26 16:19:53 +08001091 assert ((self.test_list.options.min_charge_pct is None) ==
1092 (self.test_list.options.max_charge_pct is None))
Jon Salzad7353b2012-10-15 16:22:46 +08001093 if self.test_list.options.min_charge_pct is not None:
Vic Yang4953fc12012-07-26 16:19:53 +08001094 self.charge_manager = ChargeManager(self.test_list.options.min_charge_pct,
1095 self.test_list.options.max_charge_pct)
Jon Salzad7353b2012-10-15 16:22:46 +08001096 system.SystemStatus.charge_manager = self.charge_manager
Vic Yang4953fc12012-07-26 16:19:53 +08001097
Jon Salz0697cbf2012-07-04 15:14:04 +08001098 os.environ['CROS_FACTORY'] = '1'
1099 os.environ['CROS_DISABLE_SITE_SYSINFO'] = '1'
1100
1101 # Set CROS_UI since some behaviors in ui.py depend on the
1102 # particular UI in use. TODO(jsalz): Remove this (and all
1103 # places it is used) when the GTK UI is removed.
1104 os.environ['CROS_UI'] = self.options.ui
1105
1106 if self.options.ui == 'chrome':
1107 self.env.launch_chrome()
1108 logging.info('Waiting for a web socket connection')
1109 self.web_socket_manager.wait()
1110
1111 # Wait for the test widget size to be set; this is done in
1112 # an asynchronous RPC so there is a small chance that the
1113 # web socket might be opened first.
1114 for _ in range(100): # 10 s
1115 try:
1116 if self.state_instance.get_shared_data('test_widget_size'):
1117 break
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001118 except KeyError:
Jon Salz0697cbf2012-07-04 15:14:04 +08001119 pass # Retry
1120 time.sleep(0.1) # 100 ms
1121 else:
1122 logging.warn('Never received test_widget_size from UI')
1123 elif self.options.ui == 'gtk':
1124 self.start_ui()
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001125
Ricky Liang650f6bf2012-09-28 13:22:54 +08001126 # Create download path for autotest beforehand or autotests run at
1127 # the same time might fail due to race condition.
1128 if not factory.in_chroot():
1129 utils.TryMakeDirs(os.path.join('/usr/local/autotest', 'tests',
1130 'download'))
1131
Jon Salz0697cbf2012-07-04 15:14:04 +08001132 def state_change_callback(test, test_state):
1133 self.event_client.post_event(
1134 Event(Event.Type.STATE_CHANGE,
1135 path=test.path, state=test_state))
1136 self.test_list.state_change_callback = state_change_callback
Jon Salz73e0fd02012-04-04 11:46:38 +08001137
Jon Salza6711d72012-07-18 14:33:03 +08001138 for handler in self.on_ui_startup:
1139 handler()
1140
1141 self.prespawner = Prespawner()
1142 self.prespawner.start()
1143
Jon Salz0697cbf2012-07-04 15:14:04 +08001144 try:
1145 tests_after_shutdown = self.state_instance.get_shared_data(
1146 'tests_after_shutdown')
1147 except KeyError:
1148 tests_after_shutdown = None
Jon Salz57717ca2012-04-04 16:47:25 +08001149
Jon Salz5c344f62012-07-13 14:31:16 +08001150 force_auto_run = (tests_after_shutdown == FORCE_AUTO_RUN)
1151 if not force_auto_run and tests_after_shutdown is not None:
Jon Salz0697cbf2012-07-04 15:14:04 +08001152 logging.info('Resuming tests after shutdown: %s',
1153 tests_after_shutdown)
Jon Salz0697cbf2012-07-04 15:14:04 +08001154 self.tests_to_run.extend(
1155 self.test_list.lookup_path(t) for t in tests_after_shutdown)
1156 self.run_queue.put(self.run_next_test)
1157 else:
Jon Salz5c344f62012-07-13 14:31:16 +08001158 if force_auto_run or self.test_list.options.auto_run_on_start:
Jon Salz0697cbf2012-07-04 15:14:04 +08001159 self.run_queue.put(
1160 lambda: self.run_tests(self.test_list, untested_only=True))
Jon Salz5c344f62012-07-13 14:31:16 +08001161 self.state_instance.set_shared_data('tests_after_shutdown', None)
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001162
Jon Salz0697cbf2012-07-04 15:14:04 +08001163 def run(self):
1164 '''Runs Goofy.'''
1165 # Process events forever.
1166 while self.run_once(True):
1167 pass
Jon Salz73e0fd02012-04-04 11:46:38 +08001168
Jon Salz0697cbf2012-07-04 15:14:04 +08001169 def run_once(self, block=False):
1170 '''Runs all items pending in the event loop.
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001171
Jon Salz0697cbf2012-07-04 15:14:04 +08001172 Args:
1173 block: If true, block until at least one event is processed.
Jon Salz7c15e8b2012-06-19 17:10:37 +08001174
Jon Salz0697cbf2012-07-04 15:14:04 +08001175 Returns:
1176 True to keep going or False to shut down.
1177 '''
1178 events = utils.DrainQueue(self.run_queue)
cychiang21886742012-07-05 15:16:32 +08001179 while not events:
Jon Salz0697cbf2012-07-04 15:14:04 +08001180 # Nothing on the run queue.
1181 self._run_queue_idle()
1182 if block:
1183 # Block for at least one event...
cychiang21886742012-07-05 15:16:32 +08001184 try:
1185 events.append(self.run_queue.get(timeout=RUN_QUEUE_TIMEOUT_SECS))
1186 except Queue.Empty:
1187 # Keep going (calling _run_queue_idle() again at the top of
1188 # the loop)
1189 continue
Jon Salz0697cbf2012-07-04 15:14:04 +08001190 # ...and grab anything else that showed up at the same
1191 # time.
1192 events.extend(utils.DrainQueue(self.run_queue))
cychiang21886742012-07-05 15:16:32 +08001193 else:
1194 break
Jon Salz51528e12012-07-02 18:54:45 +08001195
Jon Salz0697cbf2012-07-04 15:14:04 +08001196 for event in events:
1197 if not event:
1198 # Shutdown request.
1199 self.run_queue.task_done()
1200 return False
Jon Salz51528e12012-07-02 18:54:45 +08001201
Jon Salz0697cbf2012-07-04 15:14:04 +08001202 try:
1203 event()
Jon Salz85a39882012-07-05 16:45:04 +08001204 except: # pylint: disable=W0702
1205 logging.exception('Error in event loop')
Jon Salz0697cbf2012-07-04 15:14:04 +08001206 self.record_exception(traceback.format_exception_only(
1207 *sys.exc_info()[:2]))
1208 # But keep going
1209 finally:
1210 self.run_queue.task_done()
1211 return True
Jon Salz0405ab52012-03-16 15:26:52 +08001212
Jon Salz0e6532d2012-10-25 16:30:11 +08001213 def _should_sync_time(self, foreground=False):
1214 '''Returns True if we should attempt syncing time with shopfloor.
1215
1216 Args:
1217 foreground: If True, synchronizes even if background syncing
1218 is disabled (e.g., in explicit sync requests from the
1219 SyncShopfloor test).
1220 '''
1221 return ((foreground or
1222 self.test_list.options.sync_time_period_secs) and
Jon Salz54882d02012-08-31 01:57:54 +08001223 self.time_sanitizer and
1224 (not self.time_synced) and
1225 (not factory.in_chroot()))
1226
Jon Salz0e6532d2012-10-25 16:30:11 +08001227 def sync_time_with_shopfloor_server(self, foreground=False):
Jon Salz54882d02012-08-31 01:57:54 +08001228 '''Syncs time with shopfloor server, if not yet synced.
1229
Jon Salz0e6532d2012-10-25 16:30:11 +08001230 Args:
1231 foreground: If True, synchronizes even if background syncing
1232 is disabled (e.g., in explicit sync requests from the
1233 SyncShopfloor test).
1234
Jon Salz54882d02012-08-31 01:57:54 +08001235 Returns:
1236 False if no time sanitizer is available, or True if this sync (or a
1237 previous sync) succeeded.
1238
1239 Raises:
1240 Exception if unable to contact the shopfloor server.
1241 '''
Jon Salz0e6532d2012-10-25 16:30:11 +08001242 if self._should_sync_time(foreground):
Jon Salz54882d02012-08-31 01:57:54 +08001243 self.time_sanitizer.SyncWithShopfloor()
1244 self.time_synced = True
1245 return self.time_synced
1246
Jon Salzb92c5112012-09-21 15:40:11 +08001247 def log_disk_space_stats(self):
1248 if not self.test_list.options.log_disk_space_period_secs:
1249 return
1250
1251 now = time.time()
1252 if (self.last_log_disk_space_time and
1253 now - self.last_log_disk_space_time <
1254 self.test_list.options.log_disk_space_period_secs):
1255 return
1256 self.last_log_disk_space_time = now
1257
1258 try:
1259 logging.info(disk_space.FormatSpaceUsedAll())
1260 except: # pylint: disable=W0702
1261 logging.exception('Unable to get disk space used')
1262
Jon Salz8fa8e832012-07-13 19:04:09 +08001263 def sync_time_in_background(self):
Jon Salzb22d1172012-08-06 10:38:57 +08001264 '''Writes out current time and tries to sync with shopfloor server.'''
1265 if not self.time_sanitizer:
1266 return
1267
1268 # Write out the current time.
1269 self.time_sanitizer.SaveTime()
1270
Jon Salz54882d02012-08-31 01:57:54 +08001271 if not self._should_sync_time():
Jon Salz8fa8e832012-07-13 19:04:09 +08001272 return
1273
1274 now = time.time()
1275 if self.last_sync_time and (
1276 now - self.last_sync_time <
1277 self.test_list.options.sync_time_period_secs):
1278 # Not yet time for another check.
1279 return
1280 self.last_sync_time = now
1281
1282 def target():
1283 try:
Jon Salz54882d02012-08-31 01:57:54 +08001284 self.sync_time_with_shopfloor_server()
Jon Salz8fa8e832012-07-13 19:04:09 +08001285 except: # pylint: disable=W0702
1286 # Oh well. Log an error (but no trace)
1287 logging.info(
1288 'Unable to get time from shopfloor server: %s',
1289 utils.FormatExceptionOnly())
1290
1291 thread = threading.Thread(target=target)
1292 thread.daemon = True
1293 thread.start()
1294
Jon Salz0697cbf2012-07-04 15:14:04 +08001295 def _run_queue_idle(self):
Vic Yang4953fc12012-07-26 16:19:53 +08001296 '''Invoked when the run queue has no events.
1297
1298 This method must not raise exception.
1299 '''
Jon Salzb22d1172012-08-06 10:38:57 +08001300 now = time.time()
1301 if (self.last_idle and
1302 now < (self.last_idle + RUN_QUEUE_TIMEOUT_SECS - 1)):
1303 # Don't run more often than once every (RUN_QUEUE_TIMEOUT_SECS -
1304 # 1) seconds.
1305 return
1306
1307 self.last_idle = now
1308
Vic Yang311ddb82012-09-26 12:08:28 +08001309 self.check_exclusive()
cychiang21886742012-07-05 15:16:32 +08001310 self.check_for_updates()
Jon Salz8fa8e832012-07-13 19:04:09 +08001311 self.sync_time_in_background()
Jon Salzb92c5112012-09-21 15:40:11 +08001312 self.log_disk_space_stats()
Jon Salz57717ca2012-04-04 16:47:25 +08001313
Jon Salz16d10542012-07-23 12:18:45 +08001314 def handle_event_logs(self, log_name, chunk):
Jon Salz0697cbf2012-07-04 15:14:04 +08001315 '''Callback for event watcher.
Jon Salz258a40c2012-04-19 12:34:01 +08001316
Jon Salz0697cbf2012-07-04 15:14:04 +08001317 Attempts to upload the event logs to the shopfloor server.
1318 '''
1319 description = 'event logs (%s, %d bytes)' % (log_name, len(chunk))
1320 start_time = time.time()
Jon Salz0697cbf2012-07-04 15:14:04 +08001321 shopfloor_client = shopfloor.get_instance(
1322 detect=True,
1323 timeout=self.test_list.options.shopfloor_timeout_secs)
Jon Salzb10cf512012-08-09 17:29:21 +08001324 shopfloor_client.UploadEvent(log_name, Binary(chunk))
Jon Salz0697cbf2012-07-04 15:14:04 +08001325 logging.info(
1326 'Successfully synced %s in %.03f s',
1327 description, time.time() - start_time)
Jon Salz57717ca2012-04-04 16:47:25 +08001328
Jon Salz0697cbf2012-07-04 15:14:04 +08001329 def run_tests_with_status(self, statuses_to_run, starting_at=None,
1330 root=None):
1331 '''Runs all top-level tests with a particular status.
Jon Salz0405ab52012-03-16 15:26:52 +08001332
Jon Salz0697cbf2012-07-04 15:14:04 +08001333 All active tests, plus any tests to re-run, are reset.
Jon Salz57717ca2012-04-04 16:47:25 +08001334
Jon Salz0697cbf2012-07-04 15:14:04 +08001335 Args:
1336 starting_at: If provided, only auto-runs tests beginning with
1337 this test.
1338 '''
1339 root = root or self.test_list
Jon Salz57717ca2012-04-04 16:47:25 +08001340
Jon Salz0697cbf2012-07-04 15:14:04 +08001341 if starting_at:
1342 # Make sure they passed a test, not a string.
1343 assert isinstance(starting_at, factory.FactoryTest)
Jon Salz0405ab52012-03-16 15:26:52 +08001344
Jon Salz0697cbf2012-07-04 15:14:04 +08001345 tests_to_reset = []
1346 tests_to_run = []
Jon Salz0405ab52012-03-16 15:26:52 +08001347
Jon Salz0697cbf2012-07-04 15:14:04 +08001348 found_starting_at = False
Jon Salz0405ab52012-03-16 15:26:52 +08001349
Jon Salz0697cbf2012-07-04 15:14:04 +08001350 for test in root.get_top_level_tests():
1351 if starting_at:
1352 if test == starting_at:
1353 # We've found starting_at; do auto-run on all
1354 # subsequent tests.
1355 found_starting_at = True
1356 if not found_starting_at:
1357 # Don't start this guy yet
1358 continue
Jon Salz0405ab52012-03-16 15:26:52 +08001359
Jon Salz0697cbf2012-07-04 15:14:04 +08001360 status = test.get_state().status
1361 if status == TestState.ACTIVE or status in statuses_to_run:
1362 # Reset the test (later; we will need to abort
1363 # all active tests first).
1364 tests_to_reset.append(test)
1365 if status in statuses_to_run:
1366 tests_to_run.append(test)
Jon Salz0405ab52012-03-16 15:26:52 +08001367
Jon Salz0697cbf2012-07-04 15:14:04 +08001368 self.abort_active_tests()
Jon Salz258a40c2012-04-19 12:34:01 +08001369
Jon Salz0697cbf2012-07-04 15:14:04 +08001370 # Reset all statuses of the tests to run (in case any tests were active;
1371 # we want them to be run again).
1372 for test_to_reset in tests_to_reset:
1373 for test in test_to_reset.walk():
1374 test.update_state(status=TestState.UNTESTED)
Jon Salz57717ca2012-04-04 16:47:25 +08001375
Jon Salz0697cbf2012-07-04 15:14:04 +08001376 self.run_tests(tests_to_run, untested_only=True)
Jon Salz0405ab52012-03-16 15:26:52 +08001377
Jon Salz0697cbf2012-07-04 15:14:04 +08001378 def restart_tests(self, root=None):
1379 '''Restarts all tests.'''
1380 root = root or self.test_list
Jon Salz0405ab52012-03-16 15:26:52 +08001381
Jon Salz0697cbf2012-07-04 15:14:04 +08001382 self.abort_active_tests()
1383 for test in root.walk():
1384 test.update_state(status=TestState.UNTESTED)
1385 self.run_tests(root)
Hung-Te Lin96632362012-03-20 21:14:18 +08001386
Jon Salz0697cbf2012-07-04 15:14:04 +08001387 def auto_run(self, starting_at=None, root=None):
1388 '''"Auto-runs" tests that have not been run yet.
Hung-Te Lin96632362012-03-20 21:14:18 +08001389
Jon Salz0697cbf2012-07-04 15:14:04 +08001390 Args:
1391 starting_at: If provide, only auto-runs tests beginning with
1392 this test.
1393 '''
1394 root = root or self.test_list
1395 self.run_tests_with_status([TestState.UNTESTED, TestState.ACTIVE],
1396 starting_at=starting_at,
1397 root=root)
Jon Salz968e90b2012-03-18 16:12:43 +08001398
Jon Salz0697cbf2012-07-04 15:14:04 +08001399 def re_run_failed(self, root=None):
1400 '''Re-runs failed tests.'''
1401 root = root or self.test_list
1402 self.run_tests_with_status([TestState.FAILED], root=root)
Jon Salz57717ca2012-04-04 16:47:25 +08001403
Jon Salz0697cbf2012-07-04 15:14:04 +08001404 def show_review_information(self):
1405 '''Event handler for showing review information screen.
Jon Salz57717ca2012-04-04 16:47:25 +08001406
Jon Salz0697cbf2012-07-04 15:14:04 +08001407 The information screene is rendered by main UI program (ui.py), so in
1408 goofy we only need to kill all active tests, set them as untested, and
1409 clear remaining tests.
1410 '''
1411 self.kill_active_tests(False)
Jon Salza6711d72012-07-18 14:33:03 +08001412 self.cancel_pending_tests()
Jon Salz57717ca2012-04-04 16:47:25 +08001413
Jon Salz0697cbf2012-07-04 15:14:04 +08001414 def handle_switch_test(self, event):
1415 '''Switches to a particular test.
Jon Salz0405ab52012-03-16 15:26:52 +08001416
Jon Salz0697cbf2012-07-04 15:14:04 +08001417 @param event: The SWITCH_TEST event.
1418 '''
1419 test = self.test_list.lookup_path(event.path)
1420 if not test:
1421 logging.error('Unknown test %r', event.key)
1422 return
Jon Salz73e0fd02012-04-04 11:46:38 +08001423
Jon Salz0697cbf2012-07-04 15:14:04 +08001424 invoc = self.invocations.get(test)
1425 if invoc and test.backgroundable:
1426 # Already running: just bring to the front if it
1427 # has a UI.
1428 logging.info('Setting visible test to %s', test.path)
Jon Salz36fbbb52012-07-05 13:45:06 +08001429 self.set_visible_test(test)
Jon Salz0697cbf2012-07-04 15:14:04 +08001430 return
Jon Salz73e0fd02012-04-04 11:46:38 +08001431
Jon Salz0697cbf2012-07-04 15:14:04 +08001432 self.abort_active_tests()
1433 for t in test.walk():
1434 t.update_state(status=TestState.UNTESTED)
Jon Salz73e0fd02012-04-04 11:46:38 +08001435
Jon Salz0697cbf2012-07-04 15:14:04 +08001436 if self.test_list.options.auto_run_on_keypress:
1437 self.auto_run(starting_at=test)
1438 else:
1439 self.run_tests(test)
Jon Salz73e0fd02012-04-04 11:46:38 +08001440
Jon Salz0697cbf2012-07-04 15:14:04 +08001441 def wait(self):
1442 '''Waits for all pending invocations.
1443
1444 Useful for testing.
1445 '''
Jon Salz1acc8742012-07-17 17:45:55 +08001446 while self.invocations:
1447 for k, v in self.invocations.iteritems():
1448 logging.info('Waiting for %s to complete...', k)
1449 v.thread.join()
1450 self.reap_completed_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +08001451
1452 def check_exceptions(self):
1453 '''Raises an error if any exceptions have occurred in
1454 invocation threads.'''
1455 if self.exceptions:
1456 raise RuntimeError('Exception in invocation thread: %r' %
1457 self.exceptions)
1458
1459 def record_exception(self, msg):
1460 '''Records an exception in an invocation thread.
1461
1462 An exception with the given message will be rethrown when
1463 Goofy is destroyed.'''
1464 self.exceptions.append(msg)
Jon Salz73e0fd02012-04-04 11:46:38 +08001465
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001466
1467if __name__ == '__main__':
Jon Salz77c151e2012-08-28 07:20:37 +08001468 goofy = Goofy()
1469 try:
1470 goofy.main()
Jon Salz0f996602012-10-03 15:26:48 +08001471 except SystemExit:
1472 # Propagate SystemExit without logging.
1473 raise
Jon Salz31373eb2012-09-21 16:19:49 +08001474 except:
Jon Salz0f996602012-10-03 15:26:48 +08001475 # Log the error before trying to shut down (unless it's a graceful
1476 # exit).
Jon Salz31373eb2012-09-21 16:19:49 +08001477 logging.exception('Error in main loop')
1478 raise
Jon Salz77c151e2012-08-28 07:20:37 +08001479 finally:
1480 goofy.destroy()