blob: c5fc57b27f7680c9c3b981f81a886f6bd082f5cc [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 Salz0697cbf2012-07-04 15:14:04 +080099 search_dirs = [CUSTOM_DIR, DEFAULT_TEST_LISTS_DIR]
Jon Salz2f757d42012-06-27 17:06:42 +0800100
Jon Salz0697cbf2012-07-04 15:14:04 +0800101 # Try in order: test_list_${hwid_cfg}, test_list, test_list.all
102 search_files = ['test_list', 'test_list.all']
103 if hwid_cfg:
104 search_files.insert(0, hwid_cfg)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800105
Jon Salz0697cbf2012-07-04 15:14:04 +0800106 for d in search_dirs:
107 for f in search_files:
108 test_list = os.path.join(d, f)
109 if os.path.exists(test_list):
110 return test_list
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800111
Jon Salz0697cbf2012-07-04 15:14:04 +0800112 logging.warn('Cannot find test lists named any of %s in any of %s',
113 search_files, search_dirs)
114 return None
Jon Salz73e0fd02012-04-04 11:46:38 +0800115
Jon Salz73e0fd02012-04-04 11:46:38 +0800116_inited_logging = False
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800117
118class Goofy(object):
Jon Salz0697cbf2012-07-04 15:14:04 +0800119 '''
120 The main factory flow.
121
122 Note that all methods in this class must be invoked from the main
123 (event) thread. Other threads, such as callbacks and TestInvocation
124 methods, should instead post events on the run queue.
125
126 TODO: Unit tests. (chrome-os-partner:7409)
127
128 Properties:
129 uuid: A unique UUID for this invocation of Goofy.
130 state_instance: An instance of FactoryState.
131 state_server: The FactoryState XML/RPC server.
132 state_server_thread: A thread running state_server.
133 event_server: The EventServer socket server.
134 event_server_thread: A thread running event_server.
135 event_client: A client to the event server.
136 connection_manager: The connection_manager object.
Jon Salz0697cbf2012-07-04 15:14:04 +0800137 ui_process: The factory ui process object.
138 run_queue: A queue of callbacks to invoke from the main thread.
139 invocations: A map from FactoryTest objects to the corresponding
140 TestInvocations objects representing active tests.
141 tests_to_run: A deque of tests that should be run when the current
142 test(s) complete.
143 options: Command-line options.
144 args: Command-line args.
145 test_list: The test list.
146 event_handlers: Map of Event.Type to the method used to handle that
147 event. If the method has an 'event' argument, the event is passed
148 to the handler.
149 exceptions: Exceptions encountered in invocation threads.
150 '''
151 def __init__(self):
152 self.uuid = str(uuid.uuid4())
153 self.state_instance = None
154 self.state_server = None
155 self.state_server_thread = None
Jon Salz16d10542012-07-23 12:18:45 +0800156 self.goofy_rpc = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800157 self.event_server = None
158 self.event_server_thread = None
159 self.event_client = None
160 self.connection_manager = None
Vic Yang4953fc12012-07-26 16:19:53 +0800161 self.charge_manager = None
Jon Salz8fa8e832012-07-13 19:04:09 +0800162 self.time_sanitizer = None
163 self.time_synced = False
Jon Salz0697cbf2012-07-04 15:14:04 +0800164 self.log_watcher = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800165 self.event_log = None
166 self.prespawner = None
167 self.ui_process = None
Jon Salzc79a9982012-08-30 04:42:01 +0800168 self.dummy_shopfloor = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800169 self.run_queue = Queue.Queue()
170 self.invocations = {}
171 self.tests_to_run = deque()
172 self.visible_test = None
173 self.chrome = None
174
175 self.options = None
176 self.args = None
177 self.test_list = None
178 self.on_ui_startup = []
179 self.env = None
Jon Salzb22d1172012-08-06 10:38:57 +0800180 self.last_idle = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800181 self.last_shutdown_time = None
cychiang21886742012-07-05 15:16:32 +0800182 self.last_update_check = None
Jon Salz8fa8e832012-07-13 19:04:09 +0800183 self.last_sync_time = None
Jon Salzb92c5112012-09-21 15:40:11 +0800184 self.last_log_disk_space_time = None
Vic Yang311ddb82012-09-26 12:08:28 +0800185 self.exclusive_items = set()
Jon Salz0f996602012-10-03 15:26:48 +0800186 self.event_log = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800187
Jon Salz85a39882012-07-05 16:45:04 +0800188 def test_or_root(event, parent_or_group=True):
189 '''Returns the test affected by a particular event.
190
191 Args:
192 event: The event containing an optional 'path' attribute.
193 parent_on_group: If True, returns the top-level parent for a test (the
194 root node of the tests that need to be run together if the given test
195 path is to be run).
196 '''
Jon Salz0697cbf2012-07-04 15:14:04 +0800197 try:
198 path = event.path
199 except AttributeError:
200 path = None
201
202 if path:
Jon Salz85a39882012-07-05 16:45:04 +0800203 test = self.test_list.lookup_path(path)
204 if parent_or_group:
205 test = test.get_top_level_parent_or_group()
206 return test
Jon Salz0697cbf2012-07-04 15:14:04 +0800207 else:
208 return self.test_list
209
210 self.event_handlers = {
211 Event.Type.SWITCH_TEST: self.handle_switch_test,
212 Event.Type.SHOW_NEXT_ACTIVE_TEST:
213 lambda event: self.show_next_active_test(),
214 Event.Type.RESTART_TESTS:
215 lambda event: self.restart_tests(root=test_or_root(event)),
216 Event.Type.AUTO_RUN:
217 lambda event: self.auto_run(root=test_or_root(event)),
218 Event.Type.RE_RUN_FAILED:
219 lambda event: self.re_run_failed(root=test_or_root(event)),
220 Event.Type.RUN_TESTS_WITH_STATUS:
221 lambda event: self.run_tests_with_status(
222 event.status,
223 root=test_or_root(event)),
224 Event.Type.REVIEW:
225 lambda event: self.show_review_information(),
226 Event.Type.UPDATE_SYSTEM_INFO:
227 lambda event: self.update_system_info(),
Jon Salz0697cbf2012-07-04 15:14:04 +0800228 Event.Type.STOP:
Jon Salz85a39882012-07-05 16:45:04 +0800229 lambda event: self.stop(root=test_or_root(event, False),
230 fail=getattr(event, 'fail', False)),
Jon Salz36fbbb52012-07-05 13:45:06 +0800231 Event.Type.SET_VISIBLE_TEST:
232 lambda event: self.set_visible_test(
233 self.test_list.lookup_path(event.path)),
Jon Salz0697cbf2012-07-04 15:14:04 +0800234 }
235
236 self.exceptions = []
237 self.web_socket_manager = None
238
239 def destroy(self):
240 if self.chrome:
241 self.chrome.kill()
242 self.chrome = None
Jon Salzc79a9982012-08-30 04:42:01 +0800243 if self.dummy_shopfloor:
244 self.dummy_shopfloor.kill()
245 self.dummy_shopfloor = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800246 if self.ui_process:
247 utils.kill_process_tree(self.ui_process, 'ui')
248 self.ui_process = None
249 if self.web_socket_manager:
250 logging.info('Stopping web sockets')
251 self.web_socket_manager.close()
252 self.web_socket_manager = None
253 if self.state_server_thread:
254 logging.info('Stopping state server')
255 self.state_server.shutdown()
256 self.state_server_thread.join()
257 self.state_server.server_close()
258 self.state_server_thread = None
259 if self.state_instance:
260 self.state_instance.close()
261 if self.event_server_thread:
262 logging.info('Stopping event server')
263 self.event_server.shutdown() # pylint: disable=E1101
264 self.event_server_thread.join()
265 self.event_server.server_close()
266 self.event_server_thread = None
267 if self.log_watcher:
268 if self.log_watcher.IsThreadStarted():
269 self.log_watcher.StopWatchThread()
270 self.log_watcher = None
271 if self.prespawner:
272 logging.info('Stopping prespawner')
273 self.prespawner.stop()
274 self.prespawner = None
275 if self.event_client:
276 logging.info('Closing event client')
277 self.event_client.close()
278 self.event_client = None
279 if self.event_log:
280 self.event_log.Close()
281 self.event_log = None
282 self.check_exceptions()
283 logging.info('Done destroying Goofy')
284
285 def start_state_server(self):
286 self.state_instance, self.state_server = (
287 state.create_server(bind_address='0.0.0.0'))
Jon Salz16d10542012-07-23 12:18:45 +0800288 self.goofy_rpc = GoofyRPC(self)
289 self.goofy_rpc.RegisterMethods(self.state_instance)
Jon Salz0697cbf2012-07-04 15:14:04 +0800290 logging.info('Starting state server')
291 self.state_server_thread = threading.Thread(
292 target=self.state_server.serve_forever,
293 name='StateServer')
294 self.state_server_thread.start()
295
296 def start_event_server(self):
297 self.event_server = EventServer()
298 logging.info('Starting factory event server')
299 self.event_server_thread = threading.Thread(
300 target=self.event_server.serve_forever,
301 name='EventServer') # pylint: disable=E1101
302 self.event_server_thread.start()
303
304 self.event_client = EventClient(
305 callback=self.handle_event, event_loop=self.run_queue)
306
307 self.web_socket_manager = WebSocketManager(self.uuid)
308 self.state_server.add_handler("/event",
309 self.web_socket_manager.handle_web_socket)
310
311 def start_ui(self):
312 ui_proc_args = [
313 os.path.join(factory.FACTORY_PACKAGE_PATH, 'test', 'ui.py'),
314 self.options.test_list]
315 if self.options.verbose:
316 ui_proc_args.append('-v')
317 logging.info('Starting ui %s', ui_proc_args)
Jon Salz78c32392012-07-25 14:18:29 +0800318 self.ui_process = Spawn(ui_proc_args)
Jon Salz0697cbf2012-07-04 15:14:04 +0800319 logging.info('Waiting for UI to come up...')
320 self.event_client.wait(
321 lambda event: event.type == Event.Type.UI_READY)
322 logging.info('UI has started')
323
324 def set_visible_test(self, test):
325 if self.visible_test == test:
326 return
Jon Salz2f2d42c2012-07-30 12:30:34 +0800327 if test and not test.has_ui:
328 return
Jon Salz0697cbf2012-07-04 15:14:04 +0800329
330 if test:
331 test.update_state(visible=True)
332 if self.visible_test:
333 self.visible_test.update_state(visible=False)
334 self.visible_test = test
335
336 def handle_shutdown_complete(self, test, test_state):
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800337 '''
Jon Salz0697cbf2012-07-04 15:14:04 +0800338 Handles the case where a shutdown was detected during a shutdown step.
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800339
Jon Salz0697cbf2012-07-04 15:14:04 +0800340 @param test: The ShutdownStep.
341 @param test_state: The test state.
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800342 '''
Jon Salz0697cbf2012-07-04 15:14:04 +0800343 test_state = test.update_state(increment_shutdown_count=1)
344 logging.info('Detected shutdown (%d of %d)',
345 test_state.shutdown_count, test.iterations)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800346
Jon Salz0697cbf2012-07-04 15:14:04 +0800347 def log_and_update_state(status, error_msg, **kw):
348 self.event_log.Log('rebooted',
349 status=status, error_msg=error_msg, **kw)
350 test.update_state(status=status, error_msg=error_msg)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800351
Jon Salz0697cbf2012-07-04 15:14:04 +0800352 if not self.last_shutdown_time:
353 log_and_update_state(status=TestState.FAILED,
354 error_msg='Unable to read shutdown_time')
355 return
Jon Salz258a40c2012-04-19 12:34:01 +0800356
Jon Salz0697cbf2012-07-04 15:14:04 +0800357 now = time.time()
358 logging.info('%.03f s passed since reboot',
359 now - self.last_shutdown_time)
Jon Salz258a40c2012-04-19 12:34:01 +0800360
Jon Salz0697cbf2012-07-04 15:14:04 +0800361 if self.last_shutdown_time > now:
362 test.update_state(status=TestState.FAILED,
363 error_msg='Time moved backward during reboot')
364 elif (isinstance(test, factory.RebootStep) and
365 self.test_list.options.max_reboot_time_secs and
366 (now - self.last_shutdown_time >
367 self.test_list.options.max_reboot_time_secs)):
368 # A reboot took too long; fail. (We don't check this for
369 # HaltSteps, because the machine could be halted for a
370 # very long time, and even unplugged with battery backup,
371 # thus hosing the clock.)
372 log_and_update_state(
373 status=TestState.FAILED,
374 error_msg=('More than %d s elapsed during reboot '
375 '(%.03f s, from %s to %s)' % (
376 self.test_list.options.max_reboot_time_secs,
377 now - self.last_shutdown_time,
378 utils.TimeString(self.last_shutdown_time),
379 utils.TimeString(now))),
380 duration=(now-self.last_shutdown_time))
381 elif test_state.shutdown_count == test.iterations:
382 # Good!
383 log_and_update_state(status=TestState.PASSED,
384 duration=(now - self.last_shutdown_time),
385 error_msg='')
386 elif test_state.shutdown_count > test.iterations:
387 # Shut down too many times
388 log_and_update_state(status=TestState.FAILED,
389 error_msg='Too many shutdowns')
390 elif utils.are_shift_keys_depressed():
391 logging.info('Shift keys are depressed; cancelling restarts')
392 # Abort shutdown
393 log_and_update_state(
394 status=TestState.FAILED,
395 error_msg='Shutdown aborted with double shift keys')
Jon Salza6711d72012-07-18 14:33:03 +0800396 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +0800397 else:
398 def handler():
399 if self._prompt_cancel_shutdown(
400 test, test_state.shutdown_count + 1):
Jon Salza6711d72012-07-18 14:33:03 +0800401 factory.console.info('Shutdown aborted by operator')
Jon Salz0697cbf2012-07-04 15:14:04 +0800402 log_and_update_state(
403 status=TestState.FAILED,
404 error_msg='Shutdown aborted by operator')
Jon Salza6711d72012-07-18 14:33:03 +0800405 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +0800406 return
Jon Salz0405ab52012-03-16 15:26:52 +0800407
Jon Salz0697cbf2012-07-04 15:14:04 +0800408 # Time to shutdown again
409 log_and_update_state(
410 status=TestState.ACTIVE,
411 error_msg='',
412 iteration=test_state.shutdown_count)
Jon Salz73e0fd02012-04-04 11:46:38 +0800413
Jon Salz0697cbf2012-07-04 15:14:04 +0800414 self.event_log.Log('shutdown', operation='reboot')
415 self.state_instance.set_shared_data('shutdown_time',
416 time.time())
417 self.env.shutdown('reboot')
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800418
Jon Salz0697cbf2012-07-04 15:14:04 +0800419 self.on_ui_startup.append(handler)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800420
Jon Salz0697cbf2012-07-04 15:14:04 +0800421 def _prompt_cancel_shutdown(self, test, iteration):
422 if self.options.ui != 'chrome':
423 return False
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800424
Jon Salz0697cbf2012-07-04 15:14:04 +0800425 pending_shutdown_data = {
426 'delay_secs': test.delay_secs,
427 'time': time.time() + test.delay_secs,
428 'operation': test.operation,
429 'iteration': iteration,
430 'iterations': test.iterations,
431 }
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800432
Jon Salz0697cbf2012-07-04 15:14:04 +0800433 # Create a new (threaded) event client since we
434 # don't want to use the event loop for this.
435 with EventClient() as event_client:
436 event_client.post_event(Event(Event.Type.PENDING_SHUTDOWN,
437 **pending_shutdown_data))
438 aborted = event_client.wait(
439 lambda event: event.type == Event.Type.CANCEL_SHUTDOWN,
440 timeout=test.delay_secs) is not None
441 if aborted:
442 event_client.post_event(Event(Event.Type.PENDING_SHUTDOWN))
443 return aborted
Jon Salz258a40c2012-04-19 12:34:01 +0800444
Jon Salz0697cbf2012-07-04 15:14:04 +0800445 def init_states(self):
446 '''
447 Initializes all states on startup.
448 '''
449 for test in self.test_list.get_all_tests():
450 # Make sure the state server knows about all the tests,
451 # defaulting to an untested state.
452 test.update_state(update_parent=False, visible=False)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800453
Jon Salz0697cbf2012-07-04 15:14:04 +0800454 var_log_messages = None
Vic Yanga9c32212012-08-16 20:07:54 +0800455 mosys_log = None
Vic Yange4c275d2012-08-28 01:50:20 +0800456 ec_console_log = None
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800457
Jon Salz0697cbf2012-07-04 15:14:04 +0800458 # Any 'active' tests should be marked as failed now.
459 for test in self.test_list.walk():
Jon Salza6711d72012-07-18 14:33:03 +0800460 if not test.is_leaf():
461 # Don't bother with parents; they will be updated when their
462 # children are updated.
463 continue
464
Jon Salz0697cbf2012-07-04 15:14:04 +0800465 test_state = test.get_state()
466 if test_state.status != TestState.ACTIVE:
467 continue
468 if isinstance(test, factory.ShutdownStep):
469 # Shutdown while the test was active - that's good.
470 self.handle_shutdown_complete(test, test_state)
471 else:
472 # Unexpected shutdown. Grab /var/log/messages for context.
473 if var_log_messages is None:
474 try:
475 var_log_messages = (
476 utils.var_log_messages_before_reboot())
477 # Write it to the log, to make it easier to
478 # correlate with /var/log/messages.
479 logging.info(
480 'Unexpected shutdown. '
481 'Tail of /var/log/messages before last reboot:\n'
482 '%s', ('\n'.join(
483 ' ' + x for x in var_log_messages)))
484 except: # pylint: disable=W0702
485 logging.exception('Unable to grok /var/log/messages')
486 var_log_messages = []
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800487
Jon Salz008f4ea2012-08-28 05:39:45 +0800488 if mosys_log is None and not utils.in_chroot():
489 try:
490 mosys_log = utils.Spawn(
491 ['mosys', 'eventlog', 'list'],
492 read_stdout=True, log_stderr_on_error=True).stdout_data
493 # Write it to the log also.
494 logging.info('System eventlog from mosys:\n%s\n', mosys_log)
495 except: # pylint: disable=W0702
496 logging.exception('Unable to read mosys eventlog')
Vic Yanga9c32212012-08-16 20:07:54 +0800497
Vic Yange4c275d2012-08-28 01:50:20 +0800498 if ec_console_log is None:
499 try:
500 ec = system.GetEC()
501 ec_console_log = ec.GetConsoleLog()
502 logging.info('EC console log after reboot:\n%s\n', ec_console_log)
Jon Salzfe1f6652012-09-07 05:40:14 +0800503 except: # pylint: disable=W0702
Vic Yange4c275d2012-08-28 01:50:20 +0800504 logging.exception('Error retrieving EC console log')
505
Jon Salz0697cbf2012-07-04 15:14:04 +0800506 error_msg = 'Unexpected shutdown while test was running'
507 self.event_log.Log('end_test',
508 path=test.path,
509 status=TestState.FAILED,
510 invocation=test.get_state().invocation,
511 error_msg=error_msg,
Vic Yanga9c32212012-08-16 20:07:54 +0800512 var_log_messages='\n'.join(var_log_messages),
513 mosys_log=mosys_log)
Jon Salz0697cbf2012-07-04 15:14:04 +0800514 test.update_state(
515 status=TestState.FAILED,
516 error_msg=error_msg)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800517
Jon Salz50efe942012-07-26 11:54:10 +0800518 if not test.never_fails:
519 # For "never_fails" tests (such as "Start"), don't cancel
520 # pending tests, since reboot is expected.
521 factory.console.info('Unexpected shutdown while test %s '
522 'running; cancelling any pending tests',
523 test.path)
524 self.state_instance.set_shared_data('tests_after_shutdown', [])
Jon Salz69806bb2012-07-20 18:05:02 +0800525
Jon Salz008f4ea2012-08-28 05:39:45 +0800526 self.update_skipped_tests()
527
528 def update_skipped_tests(self):
529 '''
530 Updates skipped states based on run_if.
531 '''
532 for t in self.test_list.walk():
533 if t.is_leaf() and t.run_if_table_name:
534 skip = False
535 try:
536 aux = shopfloor.get_selected_aux_data(t.run_if_table_name)
537 value = aux.get(t.run_if_col)
538 if value is not None:
539 skip = (not value) ^ t.run_if_not
540 except ValueError:
541 # Not available; assume it shouldn't be skipped
542 pass
543
544 test_state = t.get_state()
545 if ((not skip) and
546 (test_state.status == TestState.PASSED) and
547 (test_state.error_msg == TestState.SKIPPED_MSG)):
548 # It was marked as skipped before, but now we need to run it.
549 # Mark as untested.
550 t.update_state(skip=skip, status=TestState.UNTESTED, error_msg='')
551 else:
552 t.update_state(skip=skip)
553
Jon Salz0697cbf2012-07-04 15:14:04 +0800554 def show_next_active_test(self):
555 '''
556 Rotates to the next visible active test.
557 '''
558 self.reap_completed_tests()
559 active_tests = [
560 t for t in self.test_list.walk()
561 if t.is_leaf() and t.get_state().status == TestState.ACTIVE]
562 if not active_tests:
563 return
Jon Salz4f6c7172012-06-11 20:45:36 +0800564
Jon Salz0697cbf2012-07-04 15:14:04 +0800565 try:
566 next_test = active_tests[
567 (active_tests.index(self.visible_test) + 1) % len(active_tests)]
568 except ValueError: # visible_test not present in active_tests
569 next_test = active_tests[0]
Jon Salz4f6c7172012-06-11 20:45:36 +0800570
Jon Salz0697cbf2012-07-04 15:14:04 +0800571 self.set_visible_test(next_test)
Jon Salz4f6c7172012-06-11 20:45:36 +0800572
Jon Salz0697cbf2012-07-04 15:14:04 +0800573 def handle_event(self, event):
574 '''
575 Handles an event from the event server.
576 '''
577 handler = self.event_handlers.get(event.type)
578 if handler:
579 handler(event)
580 else:
581 # We don't register handlers for all event types - just ignore
582 # this event.
583 logging.debug('Unbound event type %s', event.type)
Jon Salz4f6c7172012-06-11 20:45:36 +0800584
Jon Salz0697cbf2012-07-04 15:14:04 +0800585 def run_next_test(self):
586 '''
587 Runs the next eligible test (or tests) in self.tests_to_run.
588 '''
589 self.reap_completed_tests()
590 while self.tests_to_run:
591 logging.debug('Tests to run: %s',
592 [x.path for x in self.tests_to_run])
Jon Salz94eb56f2012-06-12 18:01:12 +0800593
Jon Salz0697cbf2012-07-04 15:14:04 +0800594 test = self.tests_to_run[0]
Jon Salz94eb56f2012-06-12 18:01:12 +0800595
Jon Salz0697cbf2012-07-04 15:14:04 +0800596 if test in self.invocations:
597 logging.info('Next test %s is already running', test.path)
598 self.tests_to_run.popleft()
599 return
Jon Salz94eb56f2012-06-12 18:01:12 +0800600
Jon Salza1412922012-07-23 16:04:17 +0800601 for requirement in test.require_run:
602 for i in requirement.test.walk():
603 if i.get_state().status == TestState.ACTIVE:
Jon Salz304a75d2012-07-06 11:14:15 +0800604 logging.info('Waiting for active test %s to complete '
Jon Salza1412922012-07-23 16:04:17 +0800605 'before running %s', i.path, test.path)
Jon Salz304a75d2012-07-06 11:14:15 +0800606 return
607
Jon Salz0697cbf2012-07-04 15:14:04 +0800608 if self.invocations and not (test.backgroundable and all(
609 [x.backgroundable for x in self.invocations])):
610 logging.debug('Waiting for non-backgroundable tests to '
611 'complete before running %s', test.path)
612 return
Jon Salz94eb56f2012-06-12 18:01:12 +0800613
Jon Salz3e6f5202012-10-15 15:08:29 +0800614 if test.get_state().skip:
615 factory.console.info('Skipping test %s', test.path)
616 test.update_state(status=TestState.PASSED,
617 error_msg=TestState.SKIPPED_MSG)
618 self.tests_to_run.popleft()
619 continue
620
Jon Salz0697cbf2012-07-04 15:14:04 +0800621 self.tests_to_run.popleft()
Jon Salz94eb56f2012-06-12 18:01:12 +0800622
Jon Salz304a75d2012-07-06 11:14:15 +0800623 untested = set()
Jon Salza1412922012-07-23 16:04:17 +0800624 for requirement in test.require_run:
625 for i in requirement.test.walk():
626 if i == test:
Jon Salz304a75d2012-07-06 11:14:15 +0800627 # We've hit this test itself; stop checking
628 break
Jon Salza1412922012-07-23 16:04:17 +0800629 if ((i.get_state().status == TestState.UNTESTED) or
630 (requirement.passed and i.get_state().status !=
631 TestState.PASSED)):
Jon Salz304a75d2012-07-06 11:14:15 +0800632 # Found an untested test; move on to the next
633 # element in require_run.
Jon Salza1412922012-07-23 16:04:17 +0800634 untested.add(i)
Jon Salz304a75d2012-07-06 11:14:15 +0800635 break
636
637 if untested:
638 untested_paths = ', '.join(sorted([x.path for x in untested]))
639 if self.state_instance.get_shared_data('engineering_mode',
640 optional=True):
641 # In engineering mode, we'll let it go.
642 factory.console.warn('In engineering mode; running '
643 '%s even though required tests '
644 '[%s] have not completed',
645 test.path, untested_paths)
646 else:
647 # Not in engineering mode; mark it failed.
648 error_msg = ('Required tests [%s] have not been run yet'
649 % untested_paths)
650 factory.console.error('Not running %s: %s',
651 test.path, error_msg)
652 test.update_state(status=TestState.FAILED,
653 error_msg=error_msg)
654 continue
655
Jon Salz0697cbf2012-07-04 15:14:04 +0800656 if isinstance(test, factory.ShutdownStep):
657 if os.path.exists(NO_REBOOT_FILE):
658 test.update_state(
659 status=TestState.FAILED, increment_count=1,
660 error_msg=('Skipped shutdown since %s is present' %
Jon Salz304a75d2012-07-06 11:14:15 +0800661 NO_REBOOT_FILE))
Jon Salz0697cbf2012-07-04 15:14:04 +0800662 continue
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800663
Jon Salz0697cbf2012-07-04 15:14:04 +0800664 test.update_state(status=TestState.ACTIVE, increment_count=1,
665 error_msg='', shutdown_count=0)
666 if self._prompt_cancel_shutdown(test, 1):
667 self.event_log.Log('reboot_cancelled')
668 test.update_state(
669 status=TestState.FAILED, increment_count=1,
670 error_msg='Shutdown aborted by operator',
671 shutdown_count=0)
chungyiafe8f772012-08-15 19:36:29 +0800672 continue
Jon Salz2f757d42012-06-27 17:06:42 +0800673
Jon Salz0697cbf2012-07-04 15:14:04 +0800674 # Save pending test list in the state server
Jon Salzdbf398f2012-06-14 17:30:01 +0800675 self.state_instance.set_shared_data(
Jon Salz0697cbf2012-07-04 15:14:04 +0800676 'tests_after_shutdown',
677 [t.path for t in self.tests_to_run])
678 # Save shutdown time
679 self.state_instance.set_shared_data('shutdown_time',
680 time.time())
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800681
Jon Salz0697cbf2012-07-04 15:14:04 +0800682 with self.env.lock:
683 self.event_log.Log('shutdown', operation=test.operation)
684 shutdown_result = self.env.shutdown(test.operation)
685 if shutdown_result:
686 # That's all, folks!
687 self.run_queue.put(None)
688 return
689 else:
690 # Just pass (e.g., in the chroot).
691 test.update_state(status=TestState.PASSED)
692 self.state_instance.set_shared_data(
693 'tests_after_shutdown', None)
694 # Send event with no fields to indicate that there is no
695 # longer a pending shutdown.
696 self.event_client.post_event(Event(
697 Event.Type.PENDING_SHUTDOWN))
698 continue
Jon Salz258a40c2012-04-19 12:34:01 +0800699
Jon Salz1acc8742012-07-17 17:45:55 +0800700 self._run_test(test, test.iterations)
701
702 def _run_test(self, test, iterations_left=None):
703 invoc = TestInvocation(self, test, on_completion=self.run_next_test)
704 new_state = test.update_state(
705 status=TestState.ACTIVE, increment_count=1, error_msg='',
Jon Salzbd42ce12012-09-18 08:03:59 +0800706 invocation=invoc.uuid, iterations_left=iterations_left,
707 visible=(self.visible_test == test))
Jon Salz1acc8742012-07-17 17:45:55 +0800708 invoc.count = new_state.count
709
710 self.invocations[test] = invoc
711 if self.visible_test is None and test.has_ui:
712 self.set_visible_test(test)
Vic Yang311ddb82012-09-26 12:08:28 +0800713 self.check_exclusive()
Jon Salz1acc8742012-07-17 17:45:55 +0800714 invoc.start()
Jon Salz5f2a0672012-05-22 17:14:06 +0800715
Vic Yang311ddb82012-09-26 12:08:28 +0800716 def check_exclusive(self):
717 current_exclusive_items = set([
718 item
719 for item in factory.FactoryTest.EXCLUSIVE_OPTIONS
720 if any([test.is_exclusive(item) for test in self.invocations])])
721
722 new_exclusive_items = current_exclusive_items - self.exclusive_items
723 if factory.FactoryTest.EXCLUSIVE_OPTIONS.NETWORKING in new_exclusive_items:
724 logging.info('Disabling network')
725 self.connection_manager.DisableNetworking()
726 if factory.FactoryTest.EXCLUSIVE_OPTIONS.CHARGER in new_exclusive_items:
727 logging.info('Stop controlling charger')
728
729 new_non_exclusive_items = self.exclusive_items - current_exclusive_items
730 if (factory.FactoryTest.EXCLUSIVE_OPTIONS.NETWORKING in
731 new_non_exclusive_items):
732 logging.info('Re-enabling network')
733 self.connection_manager.EnableNetworking()
734 if factory.FactoryTest.EXCLUSIVE_OPTIONS.CHARGER in new_non_exclusive_items:
735 logging.info('Start controlling charger')
736
737 # Only adjust charge state if not excluded
738 if (self.charge_manager and
739 not factory.FactoryTest.EXCLUSIVE_OPTIONS.CHARGER in
740 current_exclusive_items):
741 self.charge_manager.AdjustChargeState()
742
743 self.exclusive_items = current_exclusive_items
Jon Salz5da61e62012-05-31 13:06:22 +0800744
cychiang21886742012-07-05 15:16:32 +0800745 def check_for_updates(self):
746 '''
747 Schedules an asynchronous check for updates if necessary.
748 '''
749 if not self.test_list.options.update_period_secs:
750 # Not enabled.
751 return
752
753 now = time.time()
754 if self.last_update_check and (
755 now - self.last_update_check <
756 self.test_list.options.update_period_secs):
757 # Not yet time for another check.
758 return
759
760 self.last_update_check = now
761
762 def handle_check_for_update(reached_shopfloor, md5sum, needs_update):
763 if reached_shopfloor:
764 new_update_md5sum = md5sum if needs_update else None
765 if system.SystemInfo.update_md5sum != new_update_md5sum:
766 logging.info('Received new update MD5SUM: %s', new_update_md5sum)
767 system.SystemInfo.update_md5sum = new_update_md5sum
768 self.run_queue.put(self.update_system_info)
769
770 updater.CheckForUpdateAsync(
771 handle_check_for_update,
772 self.test_list.options.shopfloor_timeout_secs)
773
Jon Salza6711d72012-07-18 14:33:03 +0800774 def cancel_pending_tests(self):
775 '''Cancels any tests in the run queue.'''
776 self.run_tests([])
777
Jon Salz0697cbf2012-07-04 15:14:04 +0800778 def run_tests(self, subtrees, untested_only=False):
779 '''
780 Runs tests under subtree.
Jon Salz258a40c2012-04-19 12:34:01 +0800781
Jon Salz0697cbf2012-07-04 15:14:04 +0800782 The tests are run in order unless one fails (then stops).
783 Backgroundable tests are run simultaneously; when a foreground test is
784 encountered, we wait for all active tests to finish before continuing.
Jon Salzb1b39092012-05-03 02:05:09 +0800785
Jon Salz0697cbf2012-07-04 15:14:04 +0800786 @param subtrees: Node or nodes containing tests to run (may either be
787 a single test or a list). Duplicates will be ignored.
788 '''
789 if type(subtrees) != list:
790 subtrees = [subtrees]
Jon Salz258a40c2012-04-19 12:34:01 +0800791
Jon Salz0697cbf2012-07-04 15:14:04 +0800792 # Nodes we've seen so far, to avoid duplicates.
793 seen = set()
Jon Salz94eb56f2012-06-12 18:01:12 +0800794
Jon Salz0697cbf2012-07-04 15:14:04 +0800795 self.tests_to_run = deque()
796 for subtree in subtrees:
797 for test in subtree.walk():
798 if test in seen:
799 continue
800 seen.add(test)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800801
Jon Salz0697cbf2012-07-04 15:14:04 +0800802 if not test.is_leaf():
803 continue
804 if (untested_only and
805 test.get_state().status != TestState.UNTESTED):
806 continue
807 self.tests_to_run.append(test)
808 self.run_next_test()
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800809
Jon Salz0697cbf2012-07-04 15:14:04 +0800810 def reap_completed_tests(self):
811 '''
812 Removes completed tests from the set of active tests.
813
814 Also updates the visible test if it was reaped.
815 '''
816 for t, v in dict(self.invocations).iteritems():
817 if v.is_completed():
Jon Salz1acc8742012-07-17 17:45:55 +0800818 new_state = t.update_state(**v.update_state_on_completion)
Jon Salz0697cbf2012-07-04 15:14:04 +0800819 del self.invocations[t]
820
Chun-Ta Lin54e17e42012-09-06 22:05:13 +0800821 # Stop on failure if flag is true.
822 if (self.test_list.options.stop_on_failure and
823 new_state.status == TestState.FAILED):
824 # Clean all the tests to cause goofy to stop.
825 self.tests_to_run = []
826 factory.console.info("Stop on failure triggered. Empty the queue.")
827
Jon Salz1acc8742012-07-17 17:45:55 +0800828 if new_state.iterations_left and new_state.status == TestState.PASSED:
829 # Play it again, Sam!
830 self._run_test(t)
831
Jon Salz0697cbf2012-07-04 15:14:04 +0800832 if (self.visible_test is None or
Jon Salz85a39882012-07-05 16:45:04 +0800833 self.visible_test not in self.invocations):
Jon Salz0697cbf2012-07-04 15:14:04 +0800834 self.set_visible_test(None)
835 # Make the first running test, if any, the visible test
836 for t in self.test_list.walk():
837 if t in self.invocations:
838 self.set_visible_test(t)
839 break
840
Jon Salz85a39882012-07-05 16:45:04 +0800841 def kill_active_tests(self, abort, root=None):
Jon Salz0697cbf2012-07-04 15:14:04 +0800842 '''
843 Kills and waits for all active tests.
844
Jon Salz85a39882012-07-05 16:45:04 +0800845 Args:
846 abort: True to change state of killed tests to FAILED, False for
Jon Salz0697cbf2012-07-04 15:14:04 +0800847 UNTESTED.
Jon Salz85a39882012-07-05 16:45:04 +0800848 root: If set, only kills tests with root as an ancestor.
Jon Salz0697cbf2012-07-04 15:14:04 +0800849 '''
850 self.reap_completed_tests()
851 for test, invoc in self.invocations.items():
Jon Salz85a39882012-07-05 16:45:04 +0800852 if root and not test.has_ancestor(root):
853 continue
854
Jon Salz0697cbf2012-07-04 15:14:04 +0800855 factory.console.info('Killing active test %s...' % test.path)
856 invoc.abort_and_join()
857 factory.console.info('Killed %s' % test.path)
Jon Salz1acc8742012-07-17 17:45:55 +0800858 test.update_state(**invoc.update_state_on_completion)
Jon Salz0697cbf2012-07-04 15:14:04 +0800859 del self.invocations[test]
Jon Salz1acc8742012-07-17 17:45:55 +0800860
Jon Salz0697cbf2012-07-04 15:14:04 +0800861 if not abort:
862 test.update_state(status=TestState.UNTESTED)
863 self.reap_completed_tests()
864
Jon Salz85a39882012-07-05 16:45:04 +0800865 def stop(self, root=None, fail=False):
866 self.kill_active_tests(fail, root)
867 # Remove any tests in the run queue under the root.
868 self.tests_to_run = deque([x for x in self.tests_to_run
869 if root and not x.has_ancestor(root)])
870 self.run_next_test()
Jon Salz0697cbf2012-07-04 15:14:04 +0800871
872 def abort_active_tests(self):
873 self.kill_active_tests(True)
874
875 def main(self):
876 try:
877 self.init()
878 self.event_log.Log('goofy_init',
879 success=True)
880 except:
881 if self.event_log:
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800882 try:
Jon Salz0697cbf2012-07-04 15:14:04 +0800883 self.event_log.Log('goofy_init',
884 success=False,
885 trace=traceback.format_exc())
886 except: # pylint: disable=W0702
887 pass
888 raise
889
890 self.run()
891
892 def update_system_info(self):
893 '''Updates system info.'''
894 system_info = system.SystemInfo()
895 self.state_instance.set_shared_data('system_info', system_info.__dict__)
896 self.event_client.post_event(Event(Event.Type.SYSTEM_INFO,
897 system_info=system_info.__dict__))
898 logging.info('System info: %r', system_info.__dict__)
899
Jon Salzeb42f0d2012-07-27 19:14:04 +0800900 def update_factory(self, auto_run_on_restart=False, post_update_hook=None):
901 '''Commences updating factory software.
902
903 Args:
904 auto_run_on_restart: Auto-run when the machine comes back up.
905 post_update_hook: Code to call after update but immediately before
906 restart.
907
908 Returns:
909 Never if the update was successful (we just reboot).
910 False if the update was unnecessary (no update available).
911 '''
Jon Salz0697cbf2012-07-04 15:14:04 +0800912 self.kill_active_tests(False)
Jon Salza6711d72012-07-18 14:33:03 +0800913 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +0800914
Jon Salz5c344f62012-07-13 14:31:16 +0800915 def pre_update_hook():
916 if auto_run_on_restart:
917 self.state_instance.set_shared_data('tests_after_shutdown',
918 FORCE_AUTO_RUN)
919 self.state_instance.close()
920
Jon Salzeb42f0d2012-07-27 19:14:04 +0800921 if updater.TryUpdate(pre_update_hook=pre_update_hook):
922 if post_update_hook:
923 post_update_hook()
924 self.env.shutdown('reboot')
Jon Salz0697cbf2012-07-04 15:14:04 +0800925
Jon Salzcef132a2012-08-30 04:58:08 +0800926 def handle_sigint(self, dummy_signum, dummy_frame):
Jon Salz77c151e2012-08-28 07:20:37 +0800927 logging.error('Received SIGINT')
928 self.run_queue.put(None)
929 raise KeyboardInterrupt()
930
Jon Salz0697cbf2012-07-04 15:14:04 +0800931 def init(self, args=None, env=None):
932 '''Initializes Goofy.
933
934 Args:
935 args: A list of command-line arguments. Uses sys.argv if
936 args is None.
937 env: An Environment instance to use (or None to choose
938 FakeChrootEnvironment or DUTEnvironment as appropriate).
939 '''
Jon Salz77c151e2012-08-28 07:20:37 +0800940 signal.signal(signal.SIGINT, self.handle_sigint)
941
Jon Salz0697cbf2012-07-04 15:14:04 +0800942 parser = OptionParser()
943 parser.add_option('-v', '--verbose', dest='verbose',
Jon Salz8fa8e832012-07-13 19:04:09 +0800944 action='store_true',
945 help='Enable debug logging')
Jon Salz0697cbf2012-07-04 15:14:04 +0800946 parser.add_option('--print_test_list', dest='print_test_list',
Jon Salz8fa8e832012-07-13 19:04:09 +0800947 metavar='FILE',
948 help='Read and print test list FILE, and exit')
Jon Salz0697cbf2012-07-04 15:14:04 +0800949 parser.add_option('--restart', dest='restart',
Jon Salz8fa8e832012-07-13 19:04:09 +0800950 action='store_true',
951 help='Clear all test state')
Jon Salz0697cbf2012-07-04 15:14:04 +0800952 parser.add_option('--ui', dest='ui', type='choice',
Jon Salz8fa8e832012-07-13 19:04:09 +0800953 choices=['none', 'gtk', 'chrome'],
954 default=('chrome' if utils.in_chroot() else 'gtk'),
955 help='UI to use')
Jon Salz0697cbf2012-07-04 15:14:04 +0800956 parser.add_option('--ui_scale_factor', dest='ui_scale_factor',
Jon Salz8fa8e832012-07-13 19:04:09 +0800957 type='int', default=1,
958 help=('Factor by which to scale UI '
959 '(Chrome UI only)'))
Jon Salz0697cbf2012-07-04 15:14:04 +0800960 parser.add_option('--test_list', dest='test_list',
Jon Salz8fa8e832012-07-13 19:04:09 +0800961 metavar='FILE',
962 help='Use FILE as test list')
Jon Salzc79a9982012-08-30 04:42:01 +0800963 parser.add_option('--dummy_shopfloor', action='store_true',
964 help='Use a dummy shopfloor server')
chungyiafe8f772012-08-15 19:36:29 +0800965 parser.add_option('--automation', dest='automation',
966 action='store_true',
967 help='Enable automation on running factory test')
Jon Salz0697cbf2012-07-04 15:14:04 +0800968 (self.options, self.args) = parser.parse_args(args)
969
Jon Salz46b89562012-07-05 11:49:22 +0800970 # Make sure factory directories exist.
971 factory.get_log_root()
972 factory.get_state_root()
973 factory.get_test_data_root()
974
Jon Salz0697cbf2012-07-04 15:14:04 +0800975 global _inited_logging # pylint: disable=W0603
976 if not _inited_logging:
977 factory.init_logging('goofy', verbose=self.options.verbose)
978 _inited_logging = True
Jon Salz8fa8e832012-07-13 19:04:09 +0800979
Jon Salz0f996602012-10-03 15:26:48 +0800980 if self.options.print_test_list:
981 print factory.read_test_list(
982 self.options.print_test_list).__repr__(recursive=True)
983 sys.exit(0)
984
Jon Salzee85d522012-07-17 14:34:46 +0800985 event_log.IncrementBootSequence()
Jon Salz0697cbf2012-07-04 15:14:04 +0800986 self.event_log = EventLog('goofy')
987
988 if (not suppress_chroot_warning and
989 factory.in_chroot() and
990 self.options.ui == 'gtk' and
991 os.environ.get('DISPLAY') in [None, '', ':0', ':0.0']):
992 # That's not going to work! Tell the user how to run
993 # this way.
994 logging.warn(GOOFY_IN_CHROOT_WARNING)
995 time.sleep(1)
996
997 if env:
998 self.env = env
999 elif factory.in_chroot():
1000 self.env = test_environment.FakeChrootEnvironment()
1001 logging.warn(
1002 'Using chroot environment: will not actually run autotests')
1003 else:
1004 self.env = test_environment.DUTEnvironment()
1005 self.env.goofy = self
1006
1007 if self.options.restart:
1008 state.clear_state()
1009
Jon Salz0697cbf2012-07-04 15:14:04 +08001010 if self.options.ui_scale_factor != 1 and utils.in_qemu():
1011 logging.warn(
1012 'In QEMU; ignoring ui_scale_factor argument')
1013 self.options.ui_scale_factor = 1
1014
1015 logging.info('Started')
1016
1017 self.start_state_server()
1018 self.state_instance.set_shared_data('hwid_cfg', get_hwid_cfg())
1019 self.state_instance.set_shared_data('ui_scale_factor',
1020 self.options.ui_scale_factor)
1021 self.last_shutdown_time = (
1022 self.state_instance.get_shared_data('shutdown_time', optional=True))
1023 self.state_instance.del_shared_data('shutdown_time', optional=True)
1024
1025 if not self.options.test_list:
1026 self.options.test_list = find_test_list()
1027 if not self.options.test_list:
1028 logging.error('No test list. Aborting.')
1029 sys.exit(1)
1030 logging.info('Using test list %s', self.options.test_list)
1031
1032 self.test_list = factory.read_test_list(
1033 self.options.test_list,
Jon Salzeb42f0d2012-07-27 19:14:04 +08001034 self.state_instance)
Jon Salz0697cbf2012-07-04 15:14:04 +08001035 if not self.state_instance.has_shared_data('ui_lang'):
1036 self.state_instance.set_shared_data('ui_lang',
1037 self.test_list.options.ui_lang)
1038 self.state_instance.set_shared_data(
1039 'test_list_options',
1040 self.test_list.options.__dict__)
1041 self.state_instance.test_list = self.test_list
1042
Jon Salz83ef34b2012-11-01 19:46:35 +08001043 if not utils.in_chroot() and self.test_list.options.disable_log_rotation:
1044 open('/var/lib/cleanup_logs_paused', 'w').close()
1045
Jon Salz23926422012-09-01 03:38:13 +08001046 if self.options.dummy_shopfloor:
1047 os.environ[shopfloor.SHOPFLOOR_SERVER_ENV_VAR_NAME] = (
1048 'http://localhost:%d/' % shopfloor.DEFAULT_SERVER_PORT)
1049 self.dummy_shopfloor = Spawn(
1050 [os.path.join(factory.FACTORY_PATH, 'bin', 'shopfloor_server'),
1051 '--dummy'])
1052 elif self.test_list.options.shopfloor_server_url:
1053 shopfloor.set_server_url(self.test_list.options.shopfloor_server_url)
1054
Jon Salz0f996602012-10-03 15:26:48 +08001055 if self.test_list.options.time_sanitizer and not utils.in_chroot():
Jon Salz8fa8e832012-07-13 19:04:09 +08001056 self.time_sanitizer = time_sanitizer.TimeSanitizer(
1057 base_time=time_sanitizer.GetBaseTimeFromFile(
1058 # lsb-factory is written by the factory install shim during
1059 # installation, so it should have a good time obtained from
Jon Salz54882d02012-08-31 01:57:54 +08001060 # the mini-Omaha server. If it's not available, we'll use
1061 # /etc/lsb-factory (which will be much older, but reasonably
1062 # sane) and rely on a shopfloor sync to set a more accurate
1063 # time.
1064 '/usr/local/etc/lsb-factory',
1065 '/etc/lsb-release'))
Jon Salz8fa8e832012-07-13 19:04:09 +08001066 self.time_sanitizer.RunOnce()
1067
Jon Salz0697cbf2012-07-04 15:14:04 +08001068 self.init_states()
1069 self.start_event_server()
1070 self.connection_manager = self.env.create_connection_manager(
Tai-Hsu Lin371351a2012-08-27 14:17:14 +08001071 self.test_list.options.wlans,
1072 self.test_list.options.scan_wifi_period_secs)
Jon Salz0697cbf2012-07-04 15:14:04 +08001073 # Note that we create a log watcher even if
1074 # sync_event_log_period_secs isn't set (no background
1075 # syncing), since we may use it to flush event logs as well.
1076 self.log_watcher = EventLogWatcher(
1077 self.test_list.options.sync_event_log_period_secs,
Jon Salz16d10542012-07-23 12:18:45 +08001078 handle_event_logs_callback=self.handle_event_logs)
Jon Salz0697cbf2012-07-04 15:14:04 +08001079 if self.test_list.options.sync_event_log_period_secs:
1080 self.log_watcher.StartWatchThread()
1081
1082 self.update_system_info()
1083
Vic Yang4953fc12012-07-26 16:19:53 +08001084 assert ((self.test_list.options.min_charge_pct is None) ==
1085 (self.test_list.options.max_charge_pct is None))
Jon Salzad7353b2012-10-15 16:22:46 +08001086 if self.test_list.options.min_charge_pct is not None:
Vic Yang4953fc12012-07-26 16:19:53 +08001087 self.charge_manager = ChargeManager(self.test_list.options.min_charge_pct,
1088 self.test_list.options.max_charge_pct)
Jon Salzad7353b2012-10-15 16:22:46 +08001089 system.SystemStatus.charge_manager = self.charge_manager
Vic Yang4953fc12012-07-26 16:19:53 +08001090
Jon Salz0697cbf2012-07-04 15:14:04 +08001091 os.environ['CROS_FACTORY'] = '1'
1092 os.environ['CROS_DISABLE_SITE_SYSINFO'] = '1'
1093
1094 # Set CROS_UI since some behaviors in ui.py depend on the
1095 # particular UI in use. TODO(jsalz): Remove this (and all
1096 # places it is used) when the GTK UI is removed.
1097 os.environ['CROS_UI'] = self.options.ui
1098
1099 if self.options.ui == 'chrome':
1100 self.env.launch_chrome()
1101 logging.info('Waiting for a web socket connection')
1102 self.web_socket_manager.wait()
1103
1104 # Wait for the test widget size to be set; this is done in
1105 # an asynchronous RPC so there is a small chance that the
1106 # web socket might be opened first.
1107 for _ in range(100): # 10 s
1108 try:
1109 if self.state_instance.get_shared_data('test_widget_size'):
1110 break
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001111 except KeyError:
Jon Salz0697cbf2012-07-04 15:14:04 +08001112 pass # Retry
1113 time.sleep(0.1) # 100 ms
1114 else:
1115 logging.warn('Never received test_widget_size from UI')
1116 elif self.options.ui == 'gtk':
1117 self.start_ui()
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001118
Ricky Liang650f6bf2012-09-28 13:22:54 +08001119 # Create download path for autotest beforehand or autotests run at
1120 # the same time might fail due to race condition.
1121 if not factory.in_chroot():
1122 utils.TryMakeDirs(os.path.join('/usr/local/autotest', 'tests',
1123 'download'))
1124
Jon Salz0697cbf2012-07-04 15:14:04 +08001125 def state_change_callback(test, test_state):
1126 self.event_client.post_event(
1127 Event(Event.Type.STATE_CHANGE,
1128 path=test.path, state=test_state))
1129 self.test_list.state_change_callback = state_change_callback
Jon Salz73e0fd02012-04-04 11:46:38 +08001130
Jon Salza6711d72012-07-18 14:33:03 +08001131 for handler in self.on_ui_startup:
1132 handler()
1133
1134 self.prespawner = Prespawner()
1135 self.prespawner.start()
1136
Jon Salz0697cbf2012-07-04 15:14:04 +08001137 try:
1138 tests_after_shutdown = self.state_instance.get_shared_data(
1139 'tests_after_shutdown')
1140 except KeyError:
1141 tests_after_shutdown = None
Jon Salz57717ca2012-04-04 16:47:25 +08001142
Jon Salz5c344f62012-07-13 14:31:16 +08001143 force_auto_run = (tests_after_shutdown == FORCE_AUTO_RUN)
1144 if not force_auto_run and tests_after_shutdown is not None:
Jon Salz0697cbf2012-07-04 15:14:04 +08001145 logging.info('Resuming tests after shutdown: %s',
1146 tests_after_shutdown)
Jon Salz0697cbf2012-07-04 15:14:04 +08001147 self.tests_to_run.extend(
1148 self.test_list.lookup_path(t) for t in tests_after_shutdown)
1149 self.run_queue.put(self.run_next_test)
1150 else:
Jon Salz5c344f62012-07-13 14:31:16 +08001151 if force_auto_run or self.test_list.options.auto_run_on_start:
Jon Salz0697cbf2012-07-04 15:14:04 +08001152 self.run_queue.put(
1153 lambda: self.run_tests(self.test_list, untested_only=True))
Jon Salz5c344f62012-07-13 14:31:16 +08001154 self.state_instance.set_shared_data('tests_after_shutdown', None)
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001155
Jon Salz0697cbf2012-07-04 15:14:04 +08001156 def run(self):
1157 '''Runs Goofy.'''
1158 # Process events forever.
1159 while self.run_once(True):
1160 pass
Jon Salz73e0fd02012-04-04 11:46:38 +08001161
Jon Salz0697cbf2012-07-04 15:14:04 +08001162 def run_once(self, block=False):
1163 '''Runs all items pending in the event loop.
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001164
Jon Salz0697cbf2012-07-04 15:14:04 +08001165 Args:
1166 block: If true, block until at least one event is processed.
Jon Salz7c15e8b2012-06-19 17:10:37 +08001167
Jon Salz0697cbf2012-07-04 15:14:04 +08001168 Returns:
1169 True to keep going or False to shut down.
1170 '''
1171 events = utils.DrainQueue(self.run_queue)
cychiang21886742012-07-05 15:16:32 +08001172 while not events:
Jon Salz0697cbf2012-07-04 15:14:04 +08001173 # Nothing on the run queue.
1174 self._run_queue_idle()
1175 if block:
1176 # Block for at least one event...
cychiang21886742012-07-05 15:16:32 +08001177 try:
1178 events.append(self.run_queue.get(timeout=RUN_QUEUE_TIMEOUT_SECS))
1179 except Queue.Empty:
1180 # Keep going (calling _run_queue_idle() again at the top of
1181 # the loop)
1182 continue
Jon Salz0697cbf2012-07-04 15:14:04 +08001183 # ...and grab anything else that showed up at the same
1184 # time.
1185 events.extend(utils.DrainQueue(self.run_queue))
cychiang21886742012-07-05 15:16:32 +08001186 else:
1187 break
Jon Salz51528e12012-07-02 18:54:45 +08001188
Jon Salz0697cbf2012-07-04 15:14:04 +08001189 for event in events:
1190 if not event:
1191 # Shutdown request.
1192 self.run_queue.task_done()
1193 return False
Jon Salz51528e12012-07-02 18:54:45 +08001194
Jon Salz0697cbf2012-07-04 15:14:04 +08001195 try:
1196 event()
Jon Salz85a39882012-07-05 16:45:04 +08001197 except: # pylint: disable=W0702
1198 logging.exception('Error in event loop')
Jon Salz0697cbf2012-07-04 15:14:04 +08001199 self.record_exception(traceback.format_exception_only(
1200 *sys.exc_info()[:2]))
1201 # But keep going
1202 finally:
1203 self.run_queue.task_done()
1204 return True
Jon Salz0405ab52012-03-16 15:26:52 +08001205
Jon Salz0e6532d2012-10-25 16:30:11 +08001206 def _should_sync_time(self, foreground=False):
1207 '''Returns True if we should attempt syncing time with shopfloor.
1208
1209 Args:
1210 foreground: If True, synchronizes even if background syncing
1211 is disabled (e.g., in explicit sync requests from the
1212 SyncShopfloor test).
1213 '''
1214 return ((foreground or
1215 self.test_list.options.sync_time_period_secs) and
Jon Salz54882d02012-08-31 01:57:54 +08001216 self.time_sanitizer and
1217 (not self.time_synced) and
1218 (not factory.in_chroot()))
1219
Jon Salz0e6532d2012-10-25 16:30:11 +08001220 def sync_time_with_shopfloor_server(self, foreground=False):
Jon Salz54882d02012-08-31 01:57:54 +08001221 '''Syncs time with shopfloor server, if not yet synced.
1222
Jon Salz0e6532d2012-10-25 16:30:11 +08001223 Args:
1224 foreground: If True, synchronizes even if background syncing
1225 is disabled (e.g., in explicit sync requests from the
1226 SyncShopfloor test).
1227
Jon Salz54882d02012-08-31 01:57:54 +08001228 Returns:
1229 False if no time sanitizer is available, or True if this sync (or a
1230 previous sync) succeeded.
1231
1232 Raises:
1233 Exception if unable to contact the shopfloor server.
1234 '''
Jon Salz0e6532d2012-10-25 16:30:11 +08001235 if self._should_sync_time(foreground):
Jon Salz54882d02012-08-31 01:57:54 +08001236 self.time_sanitizer.SyncWithShopfloor()
1237 self.time_synced = True
1238 return self.time_synced
1239
Jon Salzb92c5112012-09-21 15:40:11 +08001240 def log_disk_space_stats(self):
1241 if not self.test_list.options.log_disk_space_period_secs:
1242 return
1243
1244 now = time.time()
1245 if (self.last_log_disk_space_time and
1246 now - self.last_log_disk_space_time <
1247 self.test_list.options.log_disk_space_period_secs):
1248 return
1249 self.last_log_disk_space_time = now
1250
1251 try:
1252 logging.info(disk_space.FormatSpaceUsedAll())
1253 except: # pylint: disable=W0702
1254 logging.exception('Unable to get disk space used')
1255
Jon Salz8fa8e832012-07-13 19:04:09 +08001256 def sync_time_in_background(self):
Jon Salzb22d1172012-08-06 10:38:57 +08001257 '''Writes out current time and tries to sync with shopfloor server.'''
1258 if not self.time_sanitizer:
1259 return
1260
1261 # Write out the current time.
1262 self.time_sanitizer.SaveTime()
1263
Jon Salz54882d02012-08-31 01:57:54 +08001264 if not self._should_sync_time():
Jon Salz8fa8e832012-07-13 19:04:09 +08001265 return
1266
1267 now = time.time()
1268 if self.last_sync_time and (
1269 now - self.last_sync_time <
1270 self.test_list.options.sync_time_period_secs):
1271 # Not yet time for another check.
1272 return
1273 self.last_sync_time = now
1274
1275 def target():
1276 try:
Jon Salz54882d02012-08-31 01:57:54 +08001277 self.sync_time_with_shopfloor_server()
Jon Salz8fa8e832012-07-13 19:04:09 +08001278 except: # pylint: disable=W0702
1279 # Oh well. Log an error (but no trace)
1280 logging.info(
1281 'Unable to get time from shopfloor server: %s',
1282 utils.FormatExceptionOnly())
1283
1284 thread = threading.Thread(target=target)
1285 thread.daemon = True
1286 thread.start()
1287
Jon Salz0697cbf2012-07-04 15:14:04 +08001288 def _run_queue_idle(self):
Vic Yang4953fc12012-07-26 16:19:53 +08001289 '''Invoked when the run queue has no events.
1290
1291 This method must not raise exception.
1292 '''
Jon Salzb22d1172012-08-06 10:38:57 +08001293 now = time.time()
1294 if (self.last_idle and
1295 now < (self.last_idle + RUN_QUEUE_TIMEOUT_SECS - 1)):
1296 # Don't run more often than once every (RUN_QUEUE_TIMEOUT_SECS -
1297 # 1) seconds.
1298 return
1299
1300 self.last_idle = now
1301
Vic Yang311ddb82012-09-26 12:08:28 +08001302 self.check_exclusive()
cychiang21886742012-07-05 15:16:32 +08001303 self.check_for_updates()
Jon Salz8fa8e832012-07-13 19:04:09 +08001304 self.sync_time_in_background()
Jon Salzb92c5112012-09-21 15:40:11 +08001305 self.log_disk_space_stats()
Jon Salz57717ca2012-04-04 16:47:25 +08001306
Jon Salz16d10542012-07-23 12:18:45 +08001307 def handle_event_logs(self, log_name, chunk):
Jon Salz0697cbf2012-07-04 15:14:04 +08001308 '''Callback for event watcher.
Jon Salz258a40c2012-04-19 12:34:01 +08001309
Jon Salz0697cbf2012-07-04 15:14:04 +08001310 Attempts to upload the event logs to the shopfloor server.
1311 '''
1312 description = 'event logs (%s, %d bytes)' % (log_name, len(chunk))
1313 start_time = time.time()
Jon Salz0697cbf2012-07-04 15:14:04 +08001314 shopfloor_client = shopfloor.get_instance(
1315 detect=True,
1316 timeout=self.test_list.options.shopfloor_timeout_secs)
Jon Salzb10cf512012-08-09 17:29:21 +08001317 shopfloor_client.UploadEvent(log_name, Binary(chunk))
Jon Salz0697cbf2012-07-04 15:14:04 +08001318 logging.info(
1319 'Successfully synced %s in %.03f s',
1320 description, time.time() - start_time)
Jon Salz57717ca2012-04-04 16:47:25 +08001321
Jon Salz0697cbf2012-07-04 15:14:04 +08001322 def run_tests_with_status(self, statuses_to_run, starting_at=None,
1323 root=None):
1324 '''Runs all top-level tests with a particular status.
Jon Salz0405ab52012-03-16 15:26:52 +08001325
Jon Salz0697cbf2012-07-04 15:14:04 +08001326 All active tests, plus any tests to re-run, are reset.
Jon Salz57717ca2012-04-04 16:47:25 +08001327
Jon Salz0697cbf2012-07-04 15:14:04 +08001328 Args:
1329 starting_at: If provided, only auto-runs tests beginning with
1330 this test.
1331 '''
1332 root = root or self.test_list
Jon Salz57717ca2012-04-04 16:47:25 +08001333
Jon Salz0697cbf2012-07-04 15:14:04 +08001334 if starting_at:
1335 # Make sure they passed a test, not a string.
1336 assert isinstance(starting_at, factory.FactoryTest)
Jon Salz0405ab52012-03-16 15:26:52 +08001337
Jon Salz0697cbf2012-07-04 15:14:04 +08001338 tests_to_reset = []
1339 tests_to_run = []
Jon Salz0405ab52012-03-16 15:26:52 +08001340
Jon Salz0697cbf2012-07-04 15:14:04 +08001341 found_starting_at = False
Jon Salz0405ab52012-03-16 15:26:52 +08001342
Jon Salz0697cbf2012-07-04 15:14:04 +08001343 for test in root.get_top_level_tests():
1344 if starting_at:
1345 if test == starting_at:
1346 # We've found starting_at; do auto-run on all
1347 # subsequent tests.
1348 found_starting_at = True
1349 if not found_starting_at:
1350 # Don't start this guy yet
1351 continue
Jon Salz0405ab52012-03-16 15:26:52 +08001352
Jon Salz0697cbf2012-07-04 15:14:04 +08001353 status = test.get_state().status
1354 if status == TestState.ACTIVE or status in statuses_to_run:
1355 # Reset the test (later; we will need to abort
1356 # all active tests first).
1357 tests_to_reset.append(test)
1358 if status in statuses_to_run:
1359 tests_to_run.append(test)
Jon Salz0405ab52012-03-16 15:26:52 +08001360
Jon Salz0697cbf2012-07-04 15:14:04 +08001361 self.abort_active_tests()
Jon Salz258a40c2012-04-19 12:34:01 +08001362
Jon Salz0697cbf2012-07-04 15:14:04 +08001363 # Reset all statuses of the tests to run (in case any tests were active;
1364 # we want them to be run again).
1365 for test_to_reset in tests_to_reset:
1366 for test in test_to_reset.walk():
1367 test.update_state(status=TestState.UNTESTED)
Jon Salz57717ca2012-04-04 16:47:25 +08001368
Jon Salz0697cbf2012-07-04 15:14:04 +08001369 self.run_tests(tests_to_run, untested_only=True)
Jon Salz0405ab52012-03-16 15:26:52 +08001370
Jon Salz0697cbf2012-07-04 15:14:04 +08001371 def restart_tests(self, root=None):
1372 '''Restarts all tests.'''
1373 root = root or self.test_list
Jon Salz0405ab52012-03-16 15:26:52 +08001374
Jon Salz0697cbf2012-07-04 15:14:04 +08001375 self.abort_active_tests()
1376 for test in root.walk():
1377 test.update_state(status=TestState.UNTESTED)
1378 self.run_tests(root)
Hung-Te Lin96632362012-03-20 21:14:18 +08001379
Jon Salz0697cbf2012-07-04 15:14:04 +08001380 def auto_run(self, starting_at=None, root=None):
1381 '''"Auto-runs" tests that have not been run yet.
Hung-Te Lin96632362012-03-20 21:14:18 +08001382
Jon Salz0697cbf2012-07-04 15:14:04 +08001383 Args:
1384 starting_at: If provide, only auto-runs tests beginning with
1385 this test.
1386 '''
1387 root = root or self.test_list
1388 self.run_tests_with_status([TestState.UNTESTED, TestState.ACTIVE],
1389 starting_at=starting_at,
1390 root=root)
Jon Salz968e90b2012-03-18 16:12:43 +08001391
Jon Salz0697cbf2012-07-04 15:14:04 +08001392 def re_run_failed(self, root=None):
1393 '''Re-runs failed tests.'''
1394 root = root or self.test_list
1395 self.run_tests_with_status([TestState.FAILED], root=root)
Jon Salz57717ca2012-04-04 16:47:25 +08001396
Jon Salz0697cbf2012-07-04 15:14:04 +08001397 def show_review_information(self):
1398 '''Event handler for showing review information screen.
Jon Salz57717ca2012-04-04 16:47:25 +08001399
Jon Salz0697cbf2012-07-04 15:14:04 +08001400 The information screene is rendered by main UI program (ui.py), so in
1401 goofy we only need to kill all active tests, set them as untested, and
1402 clear remaining tests.
1403 '''
1404 self.kill_active_tests(False)
Jon Salza6711d72012-07-18 14:33:03 +08001405 self.cancel_pending_tests()
Jon Salz57717ca2012-04-04 16:47:25 +08001406
Jon Salz0697cbf2012-07-04 15:14:04 +08001407 def handle_switch_test(self, event):
1408 '''Switches to a particular test.
Jon Salz0405ab52012-03-16 15:26:52 +08001409
Jon Salz0697cbf2012-07-04 15:14:04 +08001410 @param event: The SWITCH_TEST event.
1411 '''
1412 test = self.test_list.lookup_path(event.path)
1413 if not test:
1414 logging.error('Unknown test %r', event.key)
1415 return
Jon Salz73e0fd02012-04-04 11:46:38 +08001416
Jon Salz0697cbf2012-07-04 15:14:04 +08001417 invoc = self.invocations.get(test)
1418 if invoc and test.backgroundable:
1419 # Already running: just bring to the front if it
1420 # has a UI.
1421 logging.info('Setting visible test to %s', test.path)
Jon Salz36fbbb52012-07-05 13:45:06 +08001422 self.set_visible_test(test)
Jon Salz0697cbf2012-07-04 15:14:04 +08001423 return
Jon Salz73e0fd02012-04-04 11:46:38 +08001424
Jon Salz0697cbf2012-07-04 15:14:04 +08001425 self.abort_active_tests()
1426 for t in test.walk():
1427 t.update_state(status=TestState.UNTESTED)
Jon Salz73e0fd02012-04-04 11:46:38 +08001428
Jon Salz0697cbf2012-07-04 15:14:04 +08001429 if self.test_list.options.auto_run_on_keypress:
1430 self.auto_run(starting_at=test)
1431 else:
1432 self.run_tests(test)
Jon Salz73e0fd02012-04-04 11:46:38 +08001433
Jon Salz0697cbf2012-07-04 15:14:04 +08001434 def wait(self):
1435 '''Waits for all pending invocations.
1436
1437 Useful for testing.
1438 '''
Jon Salz1acc8742012-07-17 17:45:55 +08001439 while self.invocations:
1440 for k, v in self.invocations.iteritems():
1441 logging.info('Waiting for %s to complete...', k)
1442 v.thread.join()
1443 self.reap_completed_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +08001444
1445 def check_exceptions(self):
1446 '''Raises an error if any exceptions have occurred in
1447 invocation threads.'''
1448 if self.exceptions:
1449 raise RuntimeError('Exception in invocation thread: %r' %
1450 self.exceptions)
1451
1452 def record_exception(self, msg):
1453 '''Records an exception in an invocation thread.
1454
1455 An exception with the given message will be rethrown when
1456 Goofy is destroyed.'''
1457 self.exceptions.append(msg)
Jon Salz73e0fd02012-04-04 11:46:38 +08001458
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001459
1460if __name__ == '__main__':
Jon Salz77c151e2012-08-28 07:20:37 +08001461 goofy = Goofy()
1462 try:
1463 goofy.main()
Jon Salz0f996602012-10-03 15:26:48 +08001464 except SystemExit:
1465 # Propagate SystemExit without logging.
1466 raise
Jon Salz31373eb2012-09-21 16:19:49 +08001467 except:
Jon Salz0f996602012-10-03 15:26:48 +08001468 # Log the error before trying to shut down (unless it's a graceful
1469 # exit).
Jon Salz31373eb2012-09-21 16:19:49 +08001470 logging.exception('Error in main loop')
1471 raise
Jon Salz77c151e2012-08-28 07:20:37 +08001472 finally:
1473 goofy.destroy()