blob: de2d58045ed93bb6fa50315d1d0e8217f672e270 [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
Dean Liao592e4d52013-01-10 20:06:39 +080047from cros.factory.tools.key_filter import KeyFilter
Jon Salz78c32392012-07-25 14:18:29 +080048from cros.factory.utils.process_utils import Spawn
Hung-Te Linf2f78f72012-02-08 19:27:11 +080049
50
Jon Salz2f757d42012-06-27 17:06:42 +080051DEFAULT_TEST_LISTS_DIR = os.path.join(factory.FACTORY_PATH, 'test_lists')
52CUSTOM_DIR = os.path.join(factory.FACTORY_PATH, 'custom')
Hung-Te Linf2f78f72012-02-08 19:27:11 +080053HWID_CFG_PATH = '/usr/local/share/chromeos-hwid/cfg'
54
Jon Salz8796e362012-05-24 11:39:09 +080055# File that suppresses reboot if present (e.g., for development).
56NO_REBOOT_FILE = '/var/log/factory.noreboot'
57
Jon Salz5c344f62012-07-13 14:31:16 +080058# Value for tests_after_shutdown that forces auto-run (e.g., after
59# a factory update, when the available set of tests might change).
60FORCE_AUTO_RUN = 'force_auto_run'
61
cychiang21886742012-07-05 15:16:32 +080062RUN_QUEUE_TIMEOUT_SECS = 10
63
Jon Salz758e6cc2012-04-03 15:47:07 +080064GOOFY_IN_CHROOT_WARNING = '\n' + ('*' * 70) + '''
65You are running Goofy inside the chroot. Autotests are not supported.
66
67To use Goofy in the chroot, first install an Xvnc server:
68
Jon Salz0697cbf2012-07-04 15:14:04 +080069 sudo apt-get install tightvncserver
Jon Salz758e6cc2012-04-03 15:47:07 +080070
71...and then start a VNC X server outside the chroot:
72
Jon Salz0697cbf2012-07-04 15:14:04 +080073 vncserver :10 &
74 vncviewer :10
Jon Salz758e6cc2012-04-03 15:47:07 +080075
76...and run Goofy as follows:
77
Jon Salz0697cbf2012-07-04 15:14:04 +080078 env --unset=XAUTHORITY DISPLAY=localhost:10 python goofy.py
Jon Salz758e6cc2012-04-03 15:47:07 +080079''' + ('*' * 70)
Jon Salz73e0fd02012-04-04 11:46:38 +080080suppress_chroot_warning = False
Hung-Te Linf2f78f72012-02-08 19:27:11 +080081
82def get_hwid_cfg():
Jon Salz0697cbf2012-07-04 15:14:04 +080083 '''
84 Returns the HWID config tag, or an empty string if none can be found.
85 '''
86 if 'CROS_HWID' in os.environ:
87 return os.environ['CROS_HWID']
88 if os.path.exists(HWID_CFG_PATH):
89 with open(HWID_CFG_PATH, 'rt') as hwid_cfg_handle:
90 return hwid_cfg_handle.read().strip()
91 return ''
Hung-Te Linf2f78f72012-02-08 19:27:11 +080092
93
94def find_test_list():
Jon Salz0697cbf2012-07-04 15:14:04 +080095 '''
96 Returns the path to the active test list, based on the HWID config tag.
97 '''
98 hwid_cfg = get_hwid_cfg()
Hung-Te Linf2f78f72012-02-08 19:27:11 +080099
Jon Salz4be56b02012-12-22 07:30:46 +0800100 search_dirs = [DEFAULT_TEST_LISTS_DIR]
101 if not utils.in_chroot():
102 # Also look in suite_Factory. For backward compatibility only;
103 # new boards should just put the test list in the "test_lists"
104 # directory.
105 search_dirs.insert(0, os.path.join(
106 os.path.dirname(factory.FACTORY_PATH),
107 'autotest', 'site_tests', 'suite_Factory'))
Jon Salz2f757d42012-06-27 17:06:42 +0800108
Jon Salz0697cbf2012-07-04 15:14:04 +0800109 # Try in order: test_list_${hwid_cfg}, test_list, test_list.all
110 search_files = ['test_list', 'test_list.all']
111 if hwid_cfg:
112 search_files.insert(0, hwid_cfg)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800113
Jon Salz0697cbf2012-07-04 15:14:04 +0800114 for d in search_dirs:
115 for f in search_files:
116 test_list = os.path.join(d, f)
117 if os.path.exists(test_list):
118 return test_list
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800119
Jon Salz0697cbf2012-07-04 15:14:04 +0800120 logging.warn('Cannot find test lists named any of %s in any of %s',
121 search_files, search_dirs)
122 return None
Jon Salz73e0fd02012-04-04 11:46:38 +0800123
Jon Salz73e0fd02012-04-04 11:46:38 +0800124_inited_logging = False
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800125
126class Goofy(object):
Jon Salz0697cbf2012-07-04 15:14:04 +0800127 '''
128 The main factory flow.
129
130 Note that all methods in this class must be invoked from the main
131 (event) thread. Other threads, such as callbacks and TestInvocation
132 methods, should instead post events on the run queue.
133
134 TODO: Unit tests. (chrome-os-partner:7409)
135
136 Properties:
137 uuid: A unique UUID for this invocation of Goofy.
138 state_instance: An instance of FactoryState.
139 state_server: The FactoryState XML/RPC server.
140 state_server_thread: A thread running state_server.
141 event_server: The EventServer socket server.
142 event_server_thread: A thread running event_server.
143 event_client: A client to the event server.
144 connection_manager: The connection_manager object.
Jon Salz0697cbf2012-07-04 15:14:04 +0800145 ui_process: The factory ui process object.
146 run_queue: A queue of callbacks to invoke from the main thread.
147 invocations: A map from FactoryTest objects to the corresponding
148 TestInvocations objects representing active tests.
149 tests_to_run: A deque of tests that should be run when the current
150 test(s) complete.
151 options: Command-line options.
152 args: Command-line args.
153 test_list: The test list.
154 event_handlers: Map of Event.Type to the method used to handle that
155 event. If the method has an 'event' argument, the event is passed
156 to the handler.
157 exceptions: Exceptions encountered in invocation threads.
158 '''
159 def __init__(self):
160 self.uuid = str(uuid.uuid4())
161 self.state_instance = None
162 self.state_server = None
163 self.state_server_thread = None
Jon Salz16d10542012-07-23 12:18:45 +0800164 self.goofy_rpc = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800165 self.event_server = None
166 self.event_server_thread = None
167 self.event_client = None
168 self.connection_manager = None
Vic Yang4953fc12012-07-26 16:19:53 +0800169 self.charge_manager = None
Jon Salz8fa8e832012-07-13 19:04:09 +0800170 self.time_sanitizer = None
171 self.time_synced = False
Jon Salz0697cbf2012-07-04 15:14:04 +0800172 self.log_watcher = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800173 self.event_log = None
174 self.prespawner = None
175 self.ui_process = None
Jon Salzc79a9982012-08-30 04:42:01 +0800176 self.dummy_shopfloor = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800177 self.run_queue = Queue.Queue()
178 self.invocations = {}
179 self.tests_to_run = deque()
180 self.visible_test = None
181 self.chrome = None
182
183 self.options = None
184 self.args = None
185 self.test_list = None
186 self.on_ui_startup = []
187 self.env = None
Jon Salzb22d1172012-08-06 10:38:57 +0800188 self.last_idle = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800189 self.last_shutdown_time = None
cychiang21886742012-07-05 15:16:32 +0800190 self.last_update_check = None
Jon Salz8fa8e832012-07-13 19:04:09 +0800191 self.last_sync_time = None
Jon Salzb92c5112012-09-21 15:40:11 +0800192 self.last_log_disk_space_time = None
Vic Yang311ddb82012-09-26 12:08:28 +0800193 self.exclusive_items = set()
Jon Salz0f996602012-10-03 15:26:48 +0800194 self.event_log = None
Dean Liao592e4d52013-01-10 20:06:39 +0800195 self.key_filter = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800196
Jon Salz85a39882012-07-05 16:45:04 +0800197 def test_or_root(event, parent_or_group=True):
198 '''Returns the test affected by a particular event.
199
200 Args:
201 event: The event containing an optional 'path' attribute.
202 parent_on_group: If True, returns the top-level parent for a test (the
203 root node of the tests that need to be run together if the given test
204 path is to be run).
205 '''
Jon Salz0697cbf2012-07-04 15:14:04 +0800206 try:
207 path = event.path
208 except AttributeError:
209 path = None
210
211 if path:
Jon Salz85a39882012-07-05 16:45:04 +0800212 test = self.test_list.lookup_path(path)
213 if parent_or_group:
214 test = test.get_top_level_parent_or_group()
215 return test
Jon Salz0697cbf2012-07-04 15:14:04 +0800216 else:
217 return self.test_list
218
219 self.event_handlers = {
220 Event.Type.SWITCH_TEST: self.handle_switch_test,
221 Event.Type.SHOW_NEXT_ACTIVE_TEST:
222 lambda event: self.show_next_active_test(),
223 Event.Type.RESTART_TESTS:
224 lambda event: self.restart_tests(root=test_or_root(event)),
225 Event.Type.AUTO_RUN:
226 lambda event: self.auto_run(root=test_or_root(event)),
227 Event.Type.RE_RUN_FAILED:
228 lambda event: self.re_run_failed(root=test_or_root(event)),
229 Event.Type.RUN_TESTS_WITH_STATUS:
230 lambda event: self.run_tests_with_status(
231 event.status,
232 root=test_or_root(event)),
233 Event.Type.REVIEW:
234 lambda event: self.show_review_information(),
235 Event.Type.UPDATE_SYSTEM_INFO:
236 lambda event: self.update_system_info(),
Jon Salz0697cbf2012-07-04 15:14:04 +0800237 Event.Type.STOP:
Jon Salz85a39882012-07-05 16:45:04 +0800238 lambda event: self.stop(root=test_or_root(event, False),
239 fail=getattr(event, 'fail', False)),
Jon Salz36fbbb52012-07-05 13:45:06 +0800240 Event.Type.SET_VISIBLE_TEST:
241 lambda event: self.set_visible_test(
242 self.test_list.lookup_path(event.path)),
Jon Salz0697cbf2012-07-04 15:14:04 +0800243 }
244
245 self.exceptions = []
246 self.web_socket_manager = None
247
248 def destroy(self):
249 if self.chrome:
250 self.chrome.kill()
251 self.chrome = None
Jon Salzc79a9982012-08-30 04:42:01 +0800252 if self.dummy_shopfloor:
253 self.dummy_shopfloor.kill()
254 self.dummy_shopfloor = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800255 if self.ui_process:
256 utils.kill_process_tree(self.ui_process, 'ui')
257 self.ui_process = None
258 if self.web_socket_manager:
259 logging.info('Stopping web sockets')
260 self.web_socket_manager.close()
261 self.web_socket_manager = None
262 if self.state_server_thread:
263 logging.info('Stopping state server')
264 self.state_server.shutdown()
265 self.state_server_thread.join()
266 self.state_server.server_close()
267 self.state_server_thread = None
268 if self.state_instance:
269 self.state_instance.close()
270 if self.event_server_thread:
271 logging.info('Stopping event server')
272 self.event_server.shutdown() # pylint: disable=E1101
273 self.event_server_thread.join()
274 self.event_server.server_close()
275 self.event_server_thread = None
276 if self.log_watcher:
277 if self.log_watcher.IsThreadStarted():
278 self.log_watcher.StopWatchThread()
279 self.log_watcher = None
280 if self.prespawner:
281 logging.info('Stopping prespawner')
282 self.prespawner.stop()
283 self.prespawner = None
284 if self.event_client:
285 logging.info('Closing event client')
286 self.event_client.close()
287 self.event_client = None
288 if self.event_log:
289 self.event_log.Close()
290 self.event_log = None
Dean Liao592e4d52013-01-10 20:06:39 +0800291 if self.key_filter:
292 self.key_filter.Stop()
293
Jon Salz0697cbf2012-07-04 15:14:04 +0800294 self.check_exceptions()
295 logging.info('Done destroying Goofy')
296
297 def start_state_server(self):
298 self.state_instance, self.state_server = (
299 state.create_server(bind_address='0.0.0.0'))
Jon Salz16d10542012-07-23 12:18:45 +0800300 self.goofy_rpc = GoofyRPC(self)
301 self.goofy_rpc.RegisterMethods(self.state_instance)
Jon Salz0697cbf2012-07-04 15:14:04 +0800302 logging.info('Starting state server')
303 self.state_server_thread = threading.Thread(
304 target=self.state_server.serve_forever,
305 name='StateServer')
306 self.state_server_thread.start()
307
308 def start_event_server(self):
309 self.event_server = EventServer()
310 logging.info('Starting factory event server')
311 self.event_server_thread = threading.Thread(
312 target=self.event_server.serve_forever,
313 name='EventServer') # pylint: disable=E1101
314 self.event_server_thread.start()
315
316 self.event_client = EventClient(
317 callback=self.handle_event, event_loop=self.run_queue)
318
319 self.web_socket_manager = WebSocketManager(self.uuid)
320 self.state_server.add_handler("/event",
321 self.web_socket_manager.handle_web_socket)
322
323 def start_ui(self):
324 ui_proc_args = [
325 os.path.join(factory.FACTORY_PACKAGE_PATH, 'test', 'ui.py'),
326 self.options.test_list]
327 if self.options.verbose:
328 ui_proc_args.append('-v')
329 logging.info('Starting ui %s', ui_proc_args)
Jon Salz78c32392012-07-25 14:18:29 +0800330 self.ui_process = Spawn(ui_proc_args)
Jon Salz0697cbf2012-07-04 15:14:04 +0800331 logging.info('Waiting for UI to come up...')
332 self.event_client.wait(
333 lambda event: event.type == Event.Type.UI_READY)
334 logging.info('UI has started')
335
336 def set_visible_test(self, test):
337 if self.visible_test == test:
338 return
Jon Salz2f2d42c2012-07-30 12:30:34 +0800339 if test and not test.has_ui:
340 return
Jon Salz0697cbf2012-07-04 15:14:04 +0800341
342 if test:
343 test.update_state(visible=True)
344 if self.visible_test:
345 self.visible_test.update_state(visible=False)
346 self.visible_test = test
347
Jon Salzd4306c82012-11-30 15:16:36 +0800348 def _log_startup_messages(self):
349 '''Logs the tail of var/log/messages and mosys and EC console logs.'''
350 # TODO(jsalz): This is mostly a copy-and-paste of code in init_states,
351 # for factory-3004.B only. Consolidate and merge back to ToT.
352 if utils.in_chroot():
353 return
354
355 try:
356 var_log_messages = (
357 utils.var_log_messages_before_reboot())
358 logging.info(
359 'Tail of /var/log/messages before last reboot:\n'
360 '%s', ('\n'.join(
361 ' ' + x for x in var_log_messages)))
362 except: # pylint: disable=W0702
363 logging.exception('Unable to grok /var/log/messages')
364
365 try:
366 mosys_log = utils.Spawn(
367 ['mosys', 'eventlog', 'list'],
368 read_stdout=True, log_stderr_on_error=True).stdout_data
369 logging.info('System eventlog from mosys:\n%s\n', mosys_log)
370 except: # pylint: disable=W0702
371 logging.exception('Unable to read mosys eventlog')
372
373 try:
Vic Yang8341dde2013-01-29 16:48:52 +0800374 board = system.GetBoard()
375 ec_console_log = board.GetECConsoleLog()
Jon Salzd4306c82012-11-30 15:16:36 +0800376 logging.info('EC console log after reboot:\n%s\n', ec_console_log)
377 except: # pylint: disable=W0702
378 logging.exception('Error retrieving EC console log')
379
Jon Salz0697cbf2012-07-04 15:14:04 +0800380 def handle_shutdown_complete(self, test, test_state):
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800381 '''
Jon Salz0697cbf2012-07-04 15:14:04 +0800382 Handles the case where a shutdown was detected during a shutdown step.
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800383
Jon Salz0697cbf2012-07-04 15:14:04 +0800384 @param test: The ShutdownStep.
385 @param test_state: The test state.
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800386 '''
Jon Salz0697cbf2012-07-04 15:14:04 +0800387 test_state = test.update_state(increment_shutdown_count=1)
388 logging.info('Detected shutdown (%d of %d)',
389 test_state.shutdown_count, test.iterations)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800390
Jon Salz0697cbf2012-07-04 15:14:04 +0800391 def log_and_update_state(status, error_msg, **kw):
392 self.event_log.Log('rebooted',
393 status=status, error_msg=error_msg, **kw)
Jon Salzd4306c82012-11-30 15:16:36 +0800394 logging.info('Rebooted: status=%s, %s', status,
395 (('error_msg=%s' % error_msg) if error_msg else None))
Jon Salz0697cbf2012-07-04 15:14:04 +0800396 test.update_state(status=status, error_msg=error_msg)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800397
Jon Salz0697cbf2012-07-04 15:14:04 +0800398 if not self.last_shutdown_time:
399 log_and_update_state(status=TestState.FAILED,
400 error_msg='Unable to read shutdown_time')
401 return
Jon Salz258a40c2012-04-19 12:34:01 +0800402
Jon Salz0697cbf2012-07-04 15:14:04 +0800403 now = time.time()
404 logging.info('%.03f s passed since reboot',
405 now - self.last_shutdown_time)
Jon Salz258a40c2012-04-19 12:34:01 +0800406
Jon Salz0697cbf2012-07-04 15:14:04 +0800407 if self.last_shutdown_time > now:
408 test.update_state(status=TestState.FAILED,
409 error_msg='Time moved backward during reboot')
410 elif (isinstance(test, factory.RebootStep) and
411 self.test_list.options.max_reboot_time_secs and
412 (now - self.last_shutdown_time >
413 self.test_list.options.max_reboot_time_secs)):
414 # A reboot took too long; fail. (We don't check this for
415 # HaltSteps, because the machine could be halted for a
416 # very long time, and even unplugged with battery backup,
417 # thus hosing the clock.)
418 log_and_update_state(
419 status=TestState.FAILED,
420 error_msg=('More than %d s elapsed during reboot '
421 '(%.03f s, from %s to %s)' % (
422 self.test_list.options.max_reboot_time_secs,
423 now - self.last_shutdown_time,
424 utils.TimeString(self.last_shutdown_time),
425 utils.TimeString(now))),
426 duration=(now-self.last_shutdown_time))
Jon Salzd4306c82012-11-30 15:16:36 +0800427 self._log_startup_messages()
Jon Salz0697cbf2012-07-04 15:14:04 +0800428 elif test_state.shutdown_count == test.iterations:
429 # Good!
430 log_and_update_state(status=TestState.PASSED,
431 duration=(now - self.last_shutdown_time),
432 error_msg='')
433 elif test_state.shutdown_count > test.iterations:
434 # Shut down too many times
435 log_and_update_state(status=TestState.FAILED,
436 error_msg='Too many shutdowns')
Jon Salzd4306c82012-11-30 15:16:36 +0800437 self._log_startup_messages()
Jon Salz0697cbf2012-07-04 15:14:04 +0800438 elif utils.are_shift_keys_depressed():
439 logging.info('Shift keys are depressed; cancelling restarts')
440 # Abort shutdown
441 log_and_update_state(
442 status=TestState.FAILED,
443 error_msg='Shutdown aborted with double shift keys')
Jon Salza6711d72012-07-18 14:33:03 +0800444 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +0800445 else:
446 def handler():
447 if self._prompt_cancel_shutdown(
448 test, test_state.shutdown_count + 1):
Jon Salza6711d72012-07-18 14:33:03 +0800449 factory.console.info('Shutdown aborted by operator')
Jon Salz0697cbf2012-07-04 15:14:04 +0800450 log_and_update_state(
451 status=TestState.FAILED,
452 error_msg='Shutdown aborted by operator')
Jon Salza6711d72012-07-18 14:33:03 +0800453 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +0800454 return
Jon Salz0405ab52012-03-16 15:26:52 +0800455
Jon Salz0697cbf2012-07-04 15:14:04 +0800456 # Time to shutdown again
457 log_and_update_state(
458 status=TestState.ACTIVE,
459 error_msg='',
460 iteration=test_state.shutdown_count)
Jon Salz73e0fd02012-04-04 11:46:38 +0800461
Jon Salz0697cbf2012-07-04 15:14:04 +0800462 self.event_log.Log('shutdown', operation='reboot')
463 self.state_instance.set_shared_data('shutdown_time',
464 time.time())
465 self.env.shutdown('reboot')
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800466
Jon Salz0697cbf2012-07-04 15:14:04 +0800467 self.on_ui_startup.append(handler)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800468
Jon Salz0697cbf2012-07-04 15:14:04 +0800469 def _prompt_cancel_shutdown(self, test, iteration):
470 if self.options.ui != 'chrome':
471 return False
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800472
Jon Salz0697cbf2012-07-04 15:14:04 +0800473 pending_shutdown_data = {
474 'delay_secs': test.delay_secs,
475 'time': time.time() + test.delay_secs,
476 'operation': test.operation,
477 'iteration': iteration,
478 'iterations': test.iterations,
479 }
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800480
Jon Salz0697cbf2012-07-04 15:14:04 +0800481 # Create a new (threaded) event client since we
482 # don't want to use the event loop for this.
483 with EventClient() as event_client:
484 event_client.post_event(Event(Event.Type.PENDING_SHUTDOWN,
485 **pending_shutdown_data))
486 aborted = event_client.wait(
487 lambda event: event.type == Event.Type.CANCEL_SHUTDOWN,
488 timeout=test.delay_secs) is not None
489 if aborted:
490 event_client.post_event(Event(Event.Type.PENDING_SHUTDOWN))
491 return aborted
Jon Salz258a40c2012-04-19 12:34:01 +0800492
Jon Salz0697cbf2012-07-04 15:14:04 +0800493 def init_states(self):
494 '''
495 Initializes all states on startup.
496 '''
497 for test in self.test_list.get_all_tests():
498 # Make sure the state server knows about all the tests,
499 # defaulting to an untested state.
500 test.update_state(update_parent=False, visible=False)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800501
Jon Salz0697cbf2012-07-04 15:14:04 +0800502 var_log_messages = None
Vic Yanga9c32212012-08-16 20:07:54 +0800503 mosys_log = None
Vic Yange4c275d2012-08-28 01:50:20 +0800504 ec_console_log = None
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800505
Jon Salz0697cbf2012-07-04 15:14:04 +0800506 # Any 'active' tests should be marked as failed now.
507 for test in self.test_list.walk():
Jon Salza6711d72012-07-18 14:33:03 +0800508 if not test.is_leaf():
509 # Don't bother with parents; they will be updated when their
510 # children are updated.
511 continue
512
Jon Salz0697cbf2012-07-04 15:14:04 +0800513 test_state = test.get_state()
514 if test_state.status != TestState.ACTIVE:
515 continue
516 if isinstance(test, factory.ShutdownStep):
517 # Shutdown while the test was active - that's good.
518 self.handle_shutdown_complete(test, test_state)
519 else:
520 # Unexpected shutdown. Grab /var/log/messages for context.
521 if var_log_messages is None:
522 try:
523 var_log_messages = (
524 utils.var_log_messages_before_reboot())
525 # Write it to the log, to make it easier to
526 # correlate with /var/log/messages.
527 logging.info(
528 'Unexpected shutdown. '
529 'Tail of /var/log/messages before last reboot:\n'
530 '%s', ('\n'.join(
531 ' ' + x for x in var_log_messages)))
532 except: # pylint: disable=W0702
533 logging.exception('Unable to grok /var/log/messages')
534 var_log_messages = []
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800535
Jon Salz008f4ea2012-08-28 05:39:45 +0800536 if mosys_log is None and not utils.in_chroot():
537 try:
538 mosys_log = utils.Spawn(
539 ['mosys', 'eventlog', 'list'],
540 read_stdout=True, log_stderr_on_error=True).stdout_data
541 # Write it to the log also.
542 logging.info('System eventlog from mosys:\n%s\n', mosys_log)
543 except: # pylint: disable=W0702
544 logging.exception('Unable to read mosys eventlog')
Vic Yanga9c32212012-08-16 20:07:54 +0800545
Vic Yange4c275d2012-08-28 01:50:20 +0800546 if ec_console_log is None:
547 try:
Vic Yang8341dde2013-01-29 16:48:52 +0800548 board = system.GetBoard()
549 ec_console_log = board.GetECConsoleLog()
Vic Yange4c275d2012-08-28 01:50:20 +0800550 logging.info('EC console log after reboot:\n%s\n', ec_console_log)
Jon Salzfe1f6652012-09-07 05:40:14 +0800551 except: # pylint: disable=W0702
Vic Yange4c275d2012-08-28 01:50:20 +0800552 logging.exception('Error retrieving EC console log')
553
Jon Salz0697cbf2012-07-04 15:14:04 +0800554 error_msg = 'Unexpected shutdown while test was running'
555 self.event_log.Log('end_test',
556 path=test.path,
557 status=TestState.FAILED,
558 invocation=test.get_state().invocation,
559 error_msg=error_msg,
Vic Yanga9c32212012-08-16 20:07:54 +0800560 var_log_messages='\n'.join(var_log_messages),
561 mosys_log=mosys_log)
Jon Salz0697cbf2012-07-04 15:14:04 +0800562 test.update_state(
563 status=TestState.FAILED,
564 error_msg=error_msg)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800565
Jon Salz50efe942012-07-26 11:54:10 +0800566 if not test.never_fails:
567 # For "never_fails" tests (such as "Start"), don't cancel
568 # pending tests, since reboot is expected.
569 factory.console.info('Unexpected shutdown while test %s '
570 'running; cancelling any pending tests',
571 test.path)
572 self.state_instance.set_shared_data('tests_after_shutdown', [])
Jon Salz69806bb2012-07-20 18:05:02 +0800573
Jon Salz008f4ea2012-08-28 05:39:45 +0800574 self.update_skipped_tests()
575
576 def update_skipped_tests(self):
577 '''
578 Updates skipped states based on run_if.
579 '''
580 for t in self.test_list.walk():
581 if t.is_leaf() and t.run_if_table_name:
582 skip = False
583 try:
584 aux = shopfloor.get_selected_aux_data(t.run_if_table_name)
585 value = aux.get(t.run_if_col)
586 if value is not None:
587 skip = (not value) ^ t.run_if_not
588 except ValueError:
589 # Not available; assume it shouldn't be skipped
590 pass
591
592 test_state = t.get_state()
593 if ((not skip) and
594 (test_state.status == TestState.PASSED) and
595 (test_state.error_msg == TestState.SKIPPED_MSG)):
596 # It was marked as skipped before, but now we need to run it.
597 # Mark as untested.
598 t.update_state(skip=skip, status=TestState.UNTESTED, error_msg='')
599 else:
600 t.update_state(skip=skip)
601
Jon Salz0697cbf2012-07-04 15:14:04 +0800602 def show_next_active_test(self):
603 '''
604 Rotates to the next visible active test.
605 '''
606 self.reap_completed_tests()
607 active_tests = [
608 t for t in self.test_list.walk()
609 if t.is_leaf() and t.get_state().status == TestState.ACTIVE]
610 if not active_tests:
611 return
Jon Salz4f6c7172012-06-11 20:45:36 +0800612
Jon Salz0697cbf2012-07-04 15:14:04 +0800613 try:
614 next_test = active_tests[
615 (active_tests.index(self.visible_test) + 1) % len(active_tests)]
616 except ValueError: # visible_test not present in active_tests
617 next_test = active_tests[0]
Jon Salz4f6c7172012-06-11 20:45:36 +0800618
Jon Salz0697cbf2012-07-04 15:14:04 +0800619 self.set_visible_test(next_test)
Jon Salz4f6c7172012-06-11 20:45:36 +0800620
Jon Salz0697cbf2012-07-04 15:14:04 +0800621 def handle_event(self, event):
622 '''
623 Handles an event from the event server.
624 '''
625 handler = self.event_handlers.get(event.type)
626 if handler:
627 handler(event)
628 else:
629 # We don't register handlers for all event types - just ignore
630 # this event.
631 logging.debug('Unbound event type %s', event.type)
Jon Salz4f6c7172012-06-11 20:45:36 +0800632
Jon Salz0697cbf2012-07-04 15:14:04 +0800633 def run_next_test(self):
634 '''
635 Runs the next eligible test (or tests) in self.tests_to_run.
636 '''
637 self.reap_completed_tests()
638 while self.tests_to_run:
639 logging.debug('Tests to run: %s',
640 [x.path for x in self.tests_to_run])
Jon Salz94eb56f2012-06-12 18:01:12 +0800641
Jon Salz0697cbf2012-07-04 15:14:04 +0800642 test = self.tests_to_run[0]
Jon Salz94eb56f2012-06-12 18:01:12 +0800643
Jon Salz0697cbf2012-07-04 15:14:04 +0800644 if test in self.invocations:
645 logging.info('Next test %s is already running', test.path)
646 self.tests_to_run.popleft()
647 return
Jon Salz94eb56f2012-06-12 18:01:12 +0800648
Jon Salza1412922012-07-23 16:04:17 +0800649 for requirement in test.require_run:
650 for i in requirement.test.walk():
651 if i.get_state().status == TestState.ACTIVE:
Jon Salz304a75d2012-07-06 11:14:15 +0800652 logging.info('Waiting for active test %s to complete '
Jon Salza1412922012-07-23 16:04:17 +0800653 'before running %s', i.path, test.path)
Jon Salz304a75d2012-07-06 11:14:15 +0800654 return
655
Jon Salz0697cbf2012-07-04 15:14:04 +0800656 if self.invocations and not (test.backgroundable and all(
657 [x.backgroundable for x in self.invocations])):
658 logging.debug('Waiting for non-backgroundable tests to '
659 'complete before running %s', test.path)
660 return
Jon Salz94eb56f2012-06-12 18:01:12 +0800661
Jon Salz3e6f5202012-10-15 15:08:29 +0800662 if test.get_state().skip:
663 factory.console.info('Skipping test %s', test.path)
664 test.update_state(status=TestState.PASSED,
665 error_msg=TestState.SKIPPED_MSG)
666 self.tests_to_run.popleft()
667 continue
668
Jon Salz0697cbf2012-07-04 15:14:04 +0800669 self.tests_to_run.popleft()
Jon Salz94eb56f2012-06-12 18:01:12 +0800670
Jon Salz304a75d2012-07-06 11:14:15 +0800671 untested = set()
Jon Salza1412922012-07-23 16:04:17 +0800672 for requirement in test.require_run:
673 for i in requirement.test.walk():
674 if i == test:
Jon Salz304a75d2012-07-06 11:14:15 +0800675 # We've hit this test itself; stop checking
676 break
Jon Salza1412922012-07-23 16:04:17 +0800677 if ((i.get_state().status == TestState.UNTESTED) or
678 (requirement.passed and i.get_state().status !=
679 TestState.PASSED)):
Jon Salz304a75d2012-07-06 11:14:15 +0800680 # Found an untested test; move on to the next
681 # element in require_run.
Jon Salza1412922012-07-23 16:04:17 +0800682 untested.add(i)
Jon Salz304a75d2012-07-06 11:14:15 +0800683 break
684
685 if untested:
686 untested_paths = ', '.join(sorted([x.path for x in untested]))
687 if self.state_instance.get_shared_data('engineering_mode',
688 optional=True):
689 # In engineering mode, we'll let it go.
690 factory.console.warn('In engineering mode; running '
691 '%s even though required tests '
692 '[%s] have not completed',
693 test.path, untested_paths)
694 else:
695 # Not in engineering mode; mark it failed.
696 error_msg = ('Required tests [%s] have not been run yet'
697 % untested_paths)
698 factory.console.error('Not running %s: %s',
699 test.path, error_msg)
700 test.update_state(status=TestState.FAILED,
701 error_msg=error_msg)
702 continue
703
Jon Salz0697cbf2012-07-04 15:14:04 +0800704 if isinstance(test, factory.ShutdownStep):
705 if os.path.exists(NO_REBOOT_FILE):
706 test.update_state(
707 status=TestState.FAILED, increment_count=1,
708 error_msg=('Skipped shutdown since %s is present' %
Jon Salz304a75d2012-07-06 11:14:15 +0800709 NO_REBOOT_FILE))
Jon Salz0697cbf2012-07-04 15:14:04 +0800710 continue
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800711
Jon Salz0697cbf2012-07-04 15:14:04 +0800712 test.update_state(status=TestState.ACTIVE, increment_count=1,
713 error_msg='', shutdown_count=0)
714 if self._prompt_cancel_shutdown(test, 1):
715 self.event_log.Log('reboot_cancelled')
716 test.update_state(
717 status=TestState.FAILED, increment_count=1,
718 error_msg='Shutdown aborted by operator',
719 shutdown_count=0)
chungyiafe8f772012-08-15 19:36:29 +0800720 continue
Jon Salz2f757d42012-06-27 17:06:42 +0800721
Jon Salz0697cbf2012-07-04 15:14:04 +0800722 # Save pending test list in the state server
Jon Salzdbf398f2012-06-14 17:30:01 +0800723 self.state_instance.set_shared_data(
Jon Salz0697cbf2012-07-04 15:14:04 +0800724 'tests_after_shutdown',
725 [t.path for t in self.tests_to_run])
726 # Save shutdown time
727 self.state_instance.set_shared_data('shutdown_time',
728 time.time())
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800729
Jon Salz0697cbf2012-07-04 15:14:04 +0800730 with self.env.lock:
731 self.event_log.Log('shutdown', operation=test.operation)
732 shutdown_result = self.env.shutdown(test.operation)
733 if shutdown_result:
734 # That's all, folks!
735 self.run_queue.put(None)
736 return
737 else:
738 # Just pass (e.g., in the chroot).
739 test.update_state(status=TestState.PASSED)
740 self.state_instance.set_shared_data(
741 'tests_after_shutdown', None)
742 # Send event with no fields to indicate that there is no
743 # longer a pending shutdown.
744 self.event_client.post_event(Event(
745 Event.Type.PENDING_SHUTDOWN))
746 continue
Jon Salz258a40c2012-04-19 12:34:01 +0800747
Jon Salz1acc8742012-07-17 17:45:55 +0800748 self._run_test(test, test.iterations)
749
750 def _run_test(self, test, iterations_left=None):
751 invoc = TestInvocation(self, test, on_completion=self.run_next_test)
752 new_state = test.update_state(
753 status=TestState.ACTIVE, increment_count=1, error_msg='',
Jon Salzbd42ce12012-09-18 08:03:59 +0800754 invocation=invoc.uuid, iterations_left=iterations_left,
755 visible=(self.visible_test == test))
Jon Salz1acc8742012-07-17 17:45:55 +0800756 invoc.count = new_state.count
757
758 self.invocations[test] = invoc
759 if self.visible_test is None and test.has_ui:
760 self.set_visible_test(test)
Vic Yang311ddb82012-09-26 12:08:28 +0800761 self.check_exclusive()
Jon Salz1acc8742012-07-17 17:45:55 +0800762 invoc.start()
Jon Salz5f2a0672012-05-22 17:14:06 +0800763
Vic Yang311ddb82012-09-26 12:08:28 +0800764 def check_exclusive(self):
765 current_exclusive_items = set([
766 item
767 for item in factory.FactoryTest.EXCLUSIVE_OPTIONS
768 if any([test.is_exclusive(item) for test in self.invocations])])
769
770 new_exclusive_items = current_exclusive_items - self.exclusive_items
771 if factory.FactoryTest.EXCLUSIVE_OPTIONS.NETWORKING in new_exclusive_items:
772 logging.info('Disabling network')
773 self.connection_manager.DisableNetworking()
774 if factory.FactoryTest.EXCLUSIVE_OPTIONS.CHARGER in new_exclusive_items:
775 logging.info('Stop controlling charger')
776
777 new_non_exclusive_items = self.exclusive_items - current_exclusive_items
778 if (factory.FactoryTest.EXCLUSIVE_OPTIONS.NETWORKING in
779 new_non_exclusive_items):
780 logging.info('Re-enabling network')
781 self.connection_manager.EnableNetworking()
782 if factory.FactoryTest.EXCLUSIVE_OPTIONS.CHARGER in new_non_exclusive_items:
783 logging.info('Start controlling charger')
784
785 # Only adjust charge state if not excluded
786 if (self.charge_manager and
787 not factory.FactoryTest.EXCLUSIVE_OPTIONS.CHARGER in
788 current_exclusive_items):
789 self.charge_manager.AdjustChargeState()
790
791 self.exclusive_items = current_exclusive_items
Jon Salz5da61e62012-05-31 13:06:22 +0800792
cychiang21886742012-07-05 15:16:32 +0800793 def check_for_updates(self):
794 '''
795 Schedules an asynchronous check for updates if necessary.
796 '''
797 if not self.test_list.options.update_period_secs:
798 # Not enabled.
799 return
800
801 now = time.time()
802 if self.last_update_check and (
803 now - self.last_update_check <
804 self.test_list.options.update_period_secs):
805 # Not yet time for another check.
806 return
807
808 self.last_update_check = now
809
810 def handle_check_for_update(reached_shopfloor, md5sum, needs_update):
811 if reached_shopfloor:
812 new_update_md5sum = md5sum if needs_update else None
813 if system.SystemInfo.update_md5sum != new_update_md5sum:
814 logging.info('Received new update MD5SUM: %s', new_update_md5sum)
815 system.SystemInfo.update_md5sum = new_update_md5sum
816 self.run_queue.put(self.update_system_info)
817
818 updater.CheckForUpdateAsync(
819 handle_check_for_update,
820 self.test_list.options.shopfloor_timeout_secs)
821
Jon Salza6711d72012-07-18 14:33:03 +0800822 def cancel_pending_tests(self):
823 '''Cancels any tests in the run queue.'''
824 self.run_tests([])
825
Jon Salz0697cbf2012-07-04 15:14:04 +0800826 def run_tests(self, subtrees, untested_only=False):
827 '''
828 Runs tests under subtree.
Jon Salz258a40c2012-04-19 12:34:01 +0800829
Jon Salz0697cbf2012-07-04 15:14:04 +0800830 The tests are run in order unless one fails (then stops).
831 Backgroundable tests are run simultaneously; when a foreground test is
832 encountered, we wait for all active tests to finish before continuing.
Jon Salzb1b39092012-05-03 02:05:09 +0800833
Jon Salz0697cbf2012-07-04 15:14:04 +0800834 @param subtrees: Node or nodes containing tests to run (may either be
835 a single test or a list). Duplicates will be ignored.
836 '''
837 if type(subtrees) != list:
838 subtrees = [subtrees]
Jon Salz258a40c2012-04-19 12:34:01 +0800839
Jon Salz0697cbf2012-07-04 15:14:04 +0800840 # Nodes we've seen so far, to avoid duplicates.
841 seen = set()
Jon Salz94eb56f2012-06-12 18:01:12 +0800842
Jon Salz0697cbf2012-07-04 15:14:04 +0800843 self.tests_to_run = deque()
844 for subtree in subtrees:
845 for test in subtree.walk():
846 if test in seen:
847 continue
848 seen.add(test)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800849
Jon Salz0697cbf2012-07-04 15:14:04 +0800850 if not test.is_leaf():
851 continue
852 if (untested_only and
853 test.get_state().status != TestState.UNTESTED):
854 continue
855 self.tests_to_run.append(test)
856 self.run_next_test()
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800857
Jon Salz0697cbf2012-07-04 15:14:04 +0800858 def reap_completed_tests(self):
859 '''
860 Removes completed tests from the set of active tests.
861
862 Also updates the visible test if it was reaped.
863 '''
864 for t, v in dict(self.invocations).iteritems():
865 if v.is_completed():
Jon Salz1acc8742012-07-17 17:45:55 +0800866 new_state = t.update_state(**v.update_state_on_completion)
Jon Salz0697cbf2012-07-04 15:14:04 +0800867 del self.invocations[t]
868
Chun-Ta Lin54e17e42012-09-06 22:05:13 +0800869 # Stop on failure if flag is true.
870 if (self.test_list.options.stop_on_failure and
871 new_state.status == TestState.FAILED):
872 # Clean all the tests to cause goofy to stop.
873 self.tests_to_run = []
874 factory.console.info("Stop on failure triggered. Empty the queue.")
875
Jon Salz1acc8742012-07-17 17:45:55 +0800876 if new_state.iterations_left and new_state.status == TestState.PASSED:
877 # Play it again, Sam!
878 self._run_test(t)
879
Jon Salz0697cbf2012-07-04 15:14:04 +0800880 if (self.visible_test is None or
Jon Salz85a39882012-07-05 16:45:04 +0800881 self.visible_test not in self.invocations):
Jon Salz0697cbf2012-07-04 15:14:04 +0800882 self.set_visible_test(None)
883 # Make the first running test, if any, the visible test
884 for t in self.test_list.walk():
885 if t in self.invocations:
886 self.set_visible_test(t)
887 break
888
Jon Salz85a39882012-07-05 16:45:04 +0800889 def kill_active_tests(self, abort, root=None):
Jon Salz0697cbf2012-07-04 15:14:04 +0800890 '''
891 Kills and waits for all active tests.
892
Jon Salz85a39882012-07-05 16:45:04 +0800893 Args:
894 abort: True to change state of killed tests to FAILED, False for
Jon Salz0697cbf2012-07-04 15:14:04 +0800895 UNTESTED.
Jon Salz85a39882012-07-05 16:45:04 +0800896 root: If set, only kills tests with root as an ancestor.
Jon Salz0697cbf2012-07-04 15:14:04 +0800897 '''
898 self.reap_completed_tests()
899 for test, invoc in self.invocations.items():
Jon Salz85a39882012-07-05 16:45:04 +0800900 if root and not test.has_ancestor(root):
901 continue
902
Jon Salz0697cbf2012-07-04 15:14:04 +0800903 factory.console.info('Killing active test %s...' % test.path)
904 invoc.abort_and_join()
905 factory.console.info('Killed %s' % test.path)
Jon Salz1acc8742012-07-17 17:45:55 +0800906 test.update_state(**invoc.update_state_on_completion)
Jon Salz0697cbf2012-07-04 15:14:04 +0800907 del self.invocations[test]
Jon Salz1acc8742012-07-17 17:45:55 +0800908
Jon Salz0697cbf2012-07-04 15:14:04 +0800909 if not abort:
910 test.update_state(status=TestState.UNTESTED)
911 self.reap_completed_tests()
912
Jon Salz85a39882012-07-05 16:45:04 +0800913 def stop(self, root=None, fail=False):
914 self.kill_active_tests(fail, root)
915 # Remove any tests in the run queue under the root.
916 self.tests_to_run = deque([x for x in self.tests_to_run
917 if root and not x.has_ancestor(root)])
918 self.run_next_test()
Jon Salz0697cbf2012-07-04 15:14:04 +0800919
920 def abort_active_tests(self):
921 self.kill_active_tests(True)
922
923 def main(self):
924 try:
925 self.init()
926 self.event_log.Log('goofy_init',
927 success=True)
928 except:
929 if self.event_log:
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800930 try:
Jon Salz0697cbf2012-07-04 15:14:04 +0800931 self.event_log.Log('goofy_init',
932 success=False,
933 trace=traceback.format_exc())
934 except: # pylint: disable=W0702
935 pass
936 raise
937
938 self.run()
939
940 def update_system_info(self):
941 '''Updates system info.'''
942 system_info = system.SystemInfo()
943 self.state_instance.set_shared_data('system_info', system_info.__dict__)
944 self.event_client.post_event(Event(Event.Type.SYSTEM_INFO,
945 system_info=system_info.__dict__))
946 logging.info('System info: %r', system_info.__dict__)
947
Jon Salzeb42f0d2012-07-27 19:14:04 +0800948 def update_factory(self, auto_run_on_restart=False, post_update_hook=None):
949 '''Commences updating factory software.
950
951 Args:
952 auto_run_on_restart: Auto-run when the machine comes back up.
953 post_update_hook: Code to call after update but immediately before
954 restart.
955
956 Returns:
957 Never if the update was successful (we just reboot).
958 False if the update was unnecessary (no update available).
959 '''
Jon Salz0697cbf2012-07-04 15:14:04 +0800960 self.kill_active_tests(False)
Jon Salza6711d72012-07-18 14:33:03 +0800961 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +0800962
Jon Salz5c344f62012-07-13 14:31:16 +0800963 def pre_update_hook():
964 if auto_run_on_restart:
965 self.state_instance.set_shared_data('tests_after_shutdown',
966 FORCE_AUTO_RUN)
967 self.state_instance.close()
968
Jon Salzeb42f0d2012-07-27 19:14:04 +0800969 if updater.TryUpdate(pre_update_hook=pre_update_hook):
970 if post_update_hook:
971 post_update_hook()
972 self.env.shutdown('reboot')
Jon Salz0697cbf2012-07-04 15:14:04 +0800973
Jon Salzcef132a2012-08-30 04:58:08 +0800974 def handle_sigint(self, dummy_signum, dummy_frame):
Jon Salz77c151e2012-08-28 07:20:37 +0800975 logging.error('Received SIGINT')
976 self.run_queue.put(None)
977 raise KeyboardInterrupt()
978
Jon Salz0697cbf2012-07-04 15:14:04 +0800979 def init(self, args=None, env=None):
980 '''Initializes Goofy.
981
982 Args:
983 args: A list of command-line arguments. Uses sys.argv if
984 args is None.
985 env: An Environment instance to use (or None to choose
986 FakeChrootEnvironment or DUTEnvironment as appropriate).
987 '''
Jon Salz77c151e2012-08-28 07:20:37 +0800988 signal.signal(signal.SIGINT, self.handle_sigint)
989
Jon Salz0697cbf2012-07-04 15:14:04 +0800990 parser = OptionParser()
991 parser.add_option('-v', '--verbose', dest='verbose',
Jon Salz8fa8e832012-07-13 19:04:09 +0800992 action='store_true',
993 help='Enable debug logging')
Jon Salz0697cbf2012-07-04 15:14:04 +0800994 parser.add_option('--print_test_list', dest='print_test_list',
Jon Salz8fa8e832012-07-13 19:04:09 +0800995 metavar='FILE',
996 help='Read and print test list FILE, and exit')
Jon Salz0697cbf2012-07-04 15:14:04 +0800997 parser.add_option('--restart', dest='restart',
Jon Salz8fa8e832012-07-13 19:04:09 +0800998 action='store_true',
999 help='Clear all test state')
Jon Salz0697cbf2012-07-04 15:14:04 +08001000 parser.add_option('--ui', dest='ui', type='choice',
Jon Salz8fa8e832012-07-13 19:04:09 +08001001 choices=['none', 'gtk', 'chrome'],
1002 default=('chrome' if utils.in_chroot() else 'gtk'),
1003 help='UI to use')
Jon Salz0697cbf2012-07-04 15:14:04 +08001004 parser.add_option('--ui_scale_factor', dest='ui_scale_factor',
Jon Salz8fa8e832012-07-13 19:04:09 +08001005 type='int', default=1,
1006 help=('Factor by which to scale UI '
1007 '(Chrome UI only)'))
Jon Salz0697cbf2012-07-04 15:14:04 +08001008 parser.add_option('--test_list', dest='test_list',
Jon Salz8fa8e832012-07-13 19:04:09 +08001009 metavar='FILE',
1010 help='Use FILE as test list')
Jon Salzc79a9982012-08-30 04:42:01 +08001011 parser.add_option('--dummy_shopfloor', action='store_true',
1012 help='Use a dummy shopfloor server')
chungyiafe8f772012-08-15 19:36:29 +08001013 parser.add_option('--automation', dest='automation',
1014 action='store_true',
1015 help='Enable automation on running factory test')
Jon Salz0697cbf2012-07-04 15:14:04 +08001016 (self.options, self.args) = parser.parse_args(args)
1017
Jon Salz46b89562012-07-05 11:49:22 +08001018 # Make sure factory directories exist.
1019 factory.get_log_root()
1020 factory.get_state_root()
1021 factory.get_test_data_root()
1022
Jon Salz0697cbf2012-07-04 15:14:04 +08001023 global _inited_logging # pylint: disable=W0603
1024 if not _inited_logging:
1025 factory.init_logging('goofy', verbose=self.options.verbose)
1026 _inited_logging = True
Jon Salz8fa8e832012-07-13 19:04:09 +08001027
Jon Salz0f996602012-10-03 15:26:48 +08001028 if self.options.print_test_list:
1029 print factory.read_test_list(
1030 self.options.print_test_list).__repr__(recursive=True)
1031 sys.exit(0)
1032
Jon Salzee85d522012-07-17 14:34:46 +08001033 event_log.IncrementBootSequence()
Jon Salz0697cbf2012-07-04 15:14:04 +08001034 self.event_log = EventLog('goofy')
1035
1036 if (not suppress_chroot_warning and
1037 factory.in_chroot() and
1038 self.options.ui == 'gtk' and
1039 os.environ.get('DISPLAY') in [None, '', ':0', ':0.0']):
1040 # That's not going to work! Tell the user how to run
1041 # this way.
1042 logging.warn(GOOFY_IN_CHROOT_WARNING)
1043 time.sleep(1)
1044
1045 if env:
1046 self.env = env
1047 elif factory.in_chroot():
1048 self.env = test_environment.FakeChrootEnvironment()
1049 logging.warn(
1050 'Using chroot environment: will not actually run autotests')
1051 else:
1052 self.env = test_environment.DUTEnvironment()
1053 self.env.goofy = self
1054
1055 if self.options.restart:
1056 state.clear_state()
1057
Jon Salz0697cbf2012-07-04 15:14:04 +08001058 if self.options.ui_scale_factor != 1 and utils.in_qemu():
1059 logging.warn(
1060 'In QEMU; ignoring ui_scale_factor argument')
1061 self.options.ui_scale_factor = 1
1062
1063 logging.info('Started')
1064
1065 self.start_state_server()
1066 self.state_instance.set_shared_data('hwid_cfg', get_hwid_cfg())
1067 self.state_instance.set_shared_data('ui_scale_factor',
1068 self.options.ui_scale_factor)
1069 self.last_shutdown_time = (
1070 self.state_instance.get_shared_data('shutdown_time', optional=True))
1071 self.state_instance.del_shared_data('shutdown_time', optional=True)
1072
Jon Salzb19ea072013-02-07 16:35:00 +08001073 self.state_instance.del_shared_data('startup_error', optional=True)
Jon Salz0697cbf2012-07-04 15:14:04 +08001074 if not self.options.test_list:
1075 self.options.test_list = find_test_list()
Jon Salzb19ea072013-02-07 16:35:00 +08001076 if self.options.test_list:
Jon Salz0697cbf2012-07-04 15:14:04 +08001077 logging.info('Using test list %s', self.options.test_list)
Jon Salzb19ea072013-02-07 16:35:00 +08001078 try:
1079 self.test_list = factory.read_test_list(
1080 self.options.test_list,
1081 self.state_instance)
1082 except: # pylint: disable=W0702
1083 logging.exception('Unable to read test list %r', self.options.test_list)
1084 self.state_instance.set_shared_data('startup_error',
1085 'Unable to read test list %s\n%s' % (
1086 self.options.test_list,
1087 traceback.format_exc()))
1088 else:
1089 logging.error('No test list found.')
1090 self.state_instance.set_shared_data('startup_error',
1091 'No test list found.')
Jon Salz0697cbf2012-07-04 15:14:04 +08001092
Jon Salzb19ea072013-02-07 16:35:00 +08001093 if not self.test_list:
1094 if self.options.ui == 'chrome':
1095 # Create an empty test list with default options so that the rest of
1096 # startup can proceed.
1097 self.test_list = factory.FactoryTestList(
1098 [], self.state_instance, factory.Options())
1099 else:
1100 # Bail with an error; no point in starting up.
1101 sys.exit('No valid test list; exiting.')
1102
Jon Salz0697cbf2012-07-04 15:14:04 +08001103 if not self.state_instance.has_shared_data('ui_lang'):
1104 self.state_instance.set_shared_data('ui_lang',
1105 self.test_list.options.ui_lang)
1106 self.state_instance.set_shared_data(
1107 'test_list_options',
1108 self.test_list.options.__dict__)
1109 self.state_instance.test_list = self.test_list
1110
Jon Salz83ef34b2012-11-01 19:46:35 +08001111 if not utils.in_chroot() and self.test_list.options.disable_log_rotation:
1112 open('/var/lib/cleanup_logs_paused', 'w').close()
1113
Jon Salz23926422012-09-01 03:38:13 +08001114 if self.options.dummy_shopfloor:
1115 os.environ[shopfloor.SHOPFLOOR_SERVER_ENV_VAR_NAME] = (
1116 'http://localhost:%d/' % shopfloor.DEFAULT_SERVER_PORT)
1117 self.dummy_shopfloor = Spawn(
1118 [os.path.join(factory.FACTORY_PATH, 'bin', 'shopfloor_server'),
1119 '--dummy'])
1120 elif self.test_list.options.shopfloor_server_url:
1121 shopfloor.set_server_url(self.test_list.options.shopfloor_server_url)
1122
Jon Salz0f996602012-10-03 15:26:48 +08001123 if self.test_list.options.time_sanitizer and not utils.in_chroot():
Jon Salz8fa8e832012-07-13 19:04:09 +08001124 self.time_sanitizer = time_sanitizer.TimeSanitizer(
1125 base_time=time_sanitizer.GetBaseTimeFromFile(
1126 # lsb-factory is written by the factory install shim during
1127 # installation, so it should have a good time obtained from
Jon Salz54882d02012-08-31 01:57:54 +08001128 # the mini-Omaha server. If it's not available, we'll use
1129 # /etc/lsb-factory (which will be much older, but reasonably
1130 # sane) and rely on a shopfloor sync to set a more accurate
1131 # time.
1132 '/usr/local/etc/lsb-factory',
1133 '/etc/lsb-release'))
Jon Salz8fa8e832012-07-13 19:04:09 +08001134 self.time_sanitizer.RunOnce()
1135
Jon Salz0697cbf2012-07-04 15:14:04 +08001136 self.init_states()
1137 self.start_event_server()
1138 self.connection_manager = self.env.create_connection_manager(
Tai-Hsu Lin371351a2012-08-27 14:17:14 +08001139 self.test_list.options.wlans,
1140 self.test_list.options.scan_wifi_period_secs)
Jon Salz0697cbf2012-07-04 15:14:04 +08001141 # Note that we create a log watcher even if
1142 # sync_event_log_period_secs isn't set (no background
1143 # syncing), since we may use it to flush event logs as well.
1144 self.log_watcher = EventLogWatcher(
1145 self.test_list.options.sync_event_log_period_secs,
Jon Salz16d10542012-07-23 12:18:45 +08001146 handle_event_logs_callback=self.handle_event_logs)
Jon Salz0697cbf2012-07-04 15:14:04 +08001147 if self.test_list.options.sync_event_log_period_secs:
1148 self.log_watcher.StartWatchThread()
1149
1150 self.update_system_info()
1151
Vic Yang4953fc12012-07-26 16:19:53 +08001152 assert ((self.test_list.options.min_charge_pct is None) ==
1153 (self.test_list.options.max_charge_pct is None))
Jon Salzad7353b2012-10-15 16:22:46 +08001154 if self.test_list.options.min_charge_pct is not None:
Vic Yang4953fc12012-07-26 16:19:53 +08001155 self.charge_manager = ChargeManager(self.test_list.options.min_charge_pct,
1156 self.test_list.options.max_charge_pct)
Jon Salzad7353b2012-10-15 16:22:46 +08001157 system.SystemStatus.charge_manager = self.charge_manager
Vic Yang4953fc12012-07-26 16:19:53 +08001158
Jon Salz0697cbf2012-07-04 15:14:04 +08001159 os.environ['CROS_FACTORY'] = '1'
1160 os.environ['CROS_DISABLE_SITE_SYSINFO'] = '1'
1161
1162 # Set CROS_UI since some behaviors in ui.py depend on the
1163 # particular UI in use. TODO(jsalz): Remove this (and all
1164 # places it is used) when the GTK UI is removed.
1165 os.environ['CROS_UI'] = self.options.ui
1166
1167 if self.options.ui == 'chrome':
1168 self.env.launch_chrome()
1169 logging.info('Waiting for a web socket connection')
1170 self.web_socket_manager.wait()
1171
1172 # Wait for the test widget size to be set; this is done in
1173 # an asynchronous RPC so there is a small chance that the
1174 # web socket might be opened first.
1175 for _ in range(100): # 10 s
1176 try:
1177 if self.state_instance.get_shared_data('test_widget_size'):
1178 break
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001179 except KeyError:
Jon Salz0697cbf2012-07-04 15:14:04 +08001180 pass # Retry
1181 time.sleep(0.1) # 100 ms
1182 else:
1183 logging.warn('Never received test_widget_size from UI')
1184 elif self.options.ui == 'gtk':
1185 self.start_ui()
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001186
Ricky Liang650f6bf2012-09-28 13:22:54 +08001187 # Create download path for autotest beforehand or autotests run at
1188 # the same time might fail due to race condition.
1189 if not factory.in_chroot():
1190 utils.TryMakeDirs(os.path.join('/usr/local/autotest', 'tests',
1191 'download'))
1192
Jon Salz0697cbf2012-07-04 15:14:04 +08001193 def state_change_callback(test, test_state):
1194 self.event_client.post_event(
1195 Event(Event.Type.STATE_CHANGE,
1196 path=test.path, state=test_state))
1197 self.test_list.state_change_callback = state_change_callback
Jon Salz73e0fd02012-04-04 11:46:38 +08001198
Jon Salza6711d72012-07-18 14:33:03 +08001199 for handler in self.on_ui_startup:
1200 handler()
1201
1202 self.prespawner = Prespawner()
1203 self.prespawner.start()
1204
Jon Salz0697cbf2012-07-04 15:14:04 +08001205 try:
1206 tests_after_shutdown = self.state_instance.get_shared_data(
1207 'tests_after_shutdown')
1208 except KeyError:
1209 tests_after_shutdown = None
Jon Salz57717ca2012-04-04 16:47:25 +08001210
Jon Salz5c344f62012-07-13 14:31:16 +08001211 force_auto_run = (tests_after_shutdown == FORCE_AUTO_RUN)
1212 if not force_auto_run and tests_after_shutdown is not None:
Jon Salz0697cbf2012-07-04 15:14:04 +08001213 logging.info('Resuming tests after shutdown: %s',
1214 tests_after_shutdown)
Jon Salz0697cbf2012-07-04 15:14:04 +08001215 self.tests_to_run.extend(
1216 self.test_list.lookup_path(t) for t in tests_after_shutdown)
1217 self.run_queue.put(self.run_next_test)
1218 else:
Jon Salz5c344f62012-07-13 14:31:16 +08001219 if force_auto_run or self.test_list.options.auto_run_on_start:
Jon Salz0697cbf2012-07-04 15:14:04 +08001220 self.run_queue.put(
1221 lambda: self.run_tests(self.test_list, untested_only=True))
Jon Salz5c344f62012-07-13 14:31:16 +08001222 self.state_instance.set_shared_data('tests_after_shutdown', None)
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001223
Dean Liao592e4d52013-01-10 20:06:39 +08001224 self.may_disable_cros_shortcut_keys()
1225
1226 def may_disable_cros_shortcut_keys(self):
1227 test_options = self.test_list.options
1228 if test_options.disable_cros_shortcut_keys:
1229 logging.info('Filter ChromeOS shortcut keys.')
1230 self.key_filter = KeyFilter(
1231 unmap_caps_lock=test_options.disable_caps_lock,
1232 caps_lock_keycode=test_options.caps_lock_keycode)
1233 self.key_filter.Start()
1234
Jon Salz0697cbf2012-07-04 15:14:04 +08001235 def run(self):
1236 '''Runs Goofy.'''
1237 # Process events forever.
1238 while self.run_once(True):
1239 pass
Jon Salz73e0fd02012-04-04 11:46:38 +08001240
Jon Salz0697cbf2012-07-04 15:14:04 +08001241 def run_once(self, block=False):
1242 '''Runs all items pending in the event loop.
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001243
Jon Salz0697cbf2012-07-04 15:14:04 +08001244 Args:
1245 block: If true, block until at least one event is processed.
Jon Salz7c15e8b2012-06-19 17:10:37 +08001246
Jon Salz0697cbf2012-07-04 15:14:04 +08001247 Returns:
1248 True to keep going or False to shut down.
1249 '''
1250 events = utils.DrainQueue(self.run_queue)
cychiang21886742012-07-05 15:16:32 +08001251 while not events:
Jon Salz0697cbf2012-07-04 15:14:04 +08001252 # Nothing on the run queue.
1253 self._run_queue_idle()
1254 if block:
1255 # Block for at least one event...
cychiang21886742012-07-05 15:16:32 +08001256 try:
1257 events.append(self.run_queue.get(timeout=RUN_QUEUE_TIMEOUT_SECS))
1258 except Queue.Empty:
1259 # Keep going (calling _run_queue_idle() again at the top of
1260 # the loop)
1261 continue
Jon Salz0697cbf2012-07-04 15:14:04 +08001262 # ...and grab anything else that showed up at the same
1263 # time.
1264 events.extend(utils.DrainQueue(self.run_queue))
cychiang21886742012-07-05 15:16:32 +08001265 else:
1266 break
Jon Salz51528e12012-07-02 18:54:45 +08001267
Jon Salz0697cbf2012-07-04 15:14:04 +08001268 for event in events:
1269 if not event:
1270 # Shutdown request.
1271 self.run_queue.task_done()
1272 return False
Jon Salz51528e12012-07-02 18:54:45 +08001273
Jon Salz0697cbf2012-07-04 15:14:04 +08001274 try:
1275 event()
Jon Salz85a39882012-07-05 16:45:04 +08001276 except: # pylint: disable=W0702
1277 logging.exception('Error in event loop')
Jon Salz0697cbf2012-07-04 15:14:04 +08001278 self.record_exception(traceback.format_exception_only(
1279 *sys.exc_info()[:2]))
1280 # But keep going
1281 finally:
1282 self.run_queue.task_done()
1283 return True
Jon Salz0405ab52012-03-16 15:26:52 +08001284
Jon Salz0e6532d2012-10-25 16:30:11 +08001285 def _should_sync_time(self, foreground=False):
1286 '''Returns True if we should attempt syncing time with shopfloor.
1287
1288 Args:
1289 foreground: If True, synchronizes even if background syncing
1290 is disabled (e.g., in explicit sync requests from the
1291 SyncShopfloor test).
1292 '''
1293 return ((foreground or
1294 self.test_list.options.sync_time_period_secs) and
Jon Salz54882d02012-08-31 01:57:54 +08001295 self.time_sanitizer and
1296 (not self.time_synced) and
1297 (not factory.in_chroot()))
1298
Jon Salz0e6532d2012-10-25 16:30:11 +08001299 def sync_time_with_shopfloor_server(self, foreground=False):
Jon Salz54882d02012-08-31 01:57:54 +08001300 '''Syncs time with shopfloor server, if not yet synced.
1301
Jon Salz0e6532d2012-10-25 16:30:11 +08001302 Args:
1303 foreground: If True, synchronizes even if background syncing
1304 is disabled (e.g., in explicit sync requests from the
1305 SyncShopfloor test).
1306
Jon Salz54882d02012-08-31 01:57:54 +08001307 Returns:
1308 False if no time sanitizer is available, or True if this sync (or a
1309 previous sync) succeeded.
1310
1311 Raises:
1312 Exception if unable to contact the shopfloor server.
1313 '''
Jon Salz0e6532d2012-10-25 16:30:11 +08001314 if self._should_sync_time(foreground):
Jon Salz54882d02012-08-31 01:57:54 +08001315 self.time_sanitizer.SyncWithShopfloor()
1316 self.time_synced = True
1317 return self.time_synced
1318
Jon Salzb92c5112012-09-21 15:40:11 +08001319 def log_disk_space_stats(self):
1320 if not self.test_list.options.log_disk_space_period_secs:
1321 return
1322
1323 now = time.time()
1324 if (self.last_log_disk_space_time and
1325 now - self.last_log_disk_space_time <
1326 self.test_list.options.log_disk_space_period_secs):
1327 return
1328 self.last_log_disk_space_time = now
1329
1330 try:
1331 logging.info(disk_space.FormatSpaceUsedAll())
1332 except: # pylint: disable=W0702
1333 logging.exception('Unable to get disk space used')
1334
Jon Salz8fa8e832012-07-13 19:04:09 +08001335 def sync_time_in_background(self):
Jon Salzb22d1172012-08-06 10:38:57 +08001336 '''Writes out current time and tries to sync with shopfloor server.'''
1337 if not self.time_sanitizer:
1338 return
1339
1340 # Write out the current time.
1341 self.time_sanitizer.SaveTime()
1342
Jon Salz54882d02012-08-31 01:57:54 +08001343 if not self._should_sync_time():
Jon Salz8fa8e832012-07-13 19:04:09 +08001344 return
1345
1346 now = time.time()
1347 if self.last_sync_time and (
1348 now - self.last_sync_time <
1349 self.test_list.options.sync_time_period_secs):
1350 # Not yet time for another check.
1351 return
1352 self.last_sync_time = now
1353
1354 def target():
1355 try:
Jon Salz54882d02012-08-31 01:57:54 +08001356 self.sync_time_with_shopfloor_server()
Jon Salz8fa8e832012-07-13 19:04:09 +08001357 except: # pylint: disable=W0702
1358 # Oh well. Log an error (but no trace)
1359 logging.info(
1360 'Unable to get time from shopfloor server: %s',
1361 utils.FormatExceptionOnly())
1362
1363 thread = threading.Thread(target=target)
1364 thread.daemon = True
1365 thread.start()
1366
Jon Salz0697cbf2012-07-04 15:14:04 +08001367 def _run_queue_idle(self):
Vic Yang4953fc12012-07-26 16:19:53 +08001368 '''Invoked when the run queue has no events.
1369
1370 This method must not raise exception.
1371 '''
Jon Salzb22d1172012-08-06 10:38:57 +08001372 now = time.time()
1373 if (self.last_idle and
1374 now < (self.last_idle + RUN_QUEUE_TIMEOUT_SECS - 1)):
1375 # Don't run more often than once every (RUN_QUEUE_TIMEOUT_SECS -
1376 # 1) seconds.
1377 return
1378
1379 self.last_idle = now
1380
Vic Yang311ddb82012-09-26 12:08:28 +08001381 self.check_exclusive()
cychiang21886742012-07-05 15:16:32 +08001382 self.check_for_updates()
Jon Salz8fa8e832012-07-13 19:04:09 +08001383 self.sync_time_in_background()
Jon Salzb92c5112012-09-21 15:40:11 +08001384 self.log_disk_space_stats()
Jon Salz57717ca2012-04-04 16:47:25 +08001385
Jon Salz16d10542012-07-23 12:18:45 +08001386 def handle_event_logs(self, log_name, chunk):
Jon Salz0697cbf2012-07-04 15:14:04 +08001387 '''Callback for event watcher.
Jon Salz258a40c2012-04-19 12:34:01 +08001388
Jon Salz0697cbf2012-07-04 15:14:04 +08001389 Attempts to upload the event logs to the shopfloor server.
1390 '''
1391 description = 'event logs (%s, %d bytes)' % (log_name, len(chunk))
1392 start_time = time.time()
Jon Salz0697cbf2012-07-04 15:14:04 +08001393 shopfloor_client = shopfloor.get_instance(
1394 detect=True,
1395 timeout=self.test_list.options.shopfloor_timeout_secs)
Jon Salzb10cf512012-08-09 17:29:21 +08001396 shopfloor_client.UploadEvent(log_name, Binary(chunk))
Jon Salz0697cbf2012-07-04 15:14:04 +08001397 logging.info(
1398 'Successfully synced %s in %.03f s',
1399 description, time.time() - start_time)
Jon Salz57717ca2012-04-04 16:47:25 +08001400
Jon Salz0697cbf2012-07-04 15:14:04 +08001401 def run_tests_with_status(self, statuses_to_run, starting_at=None,
1402 root=None):
1403 '''Runs all top-level tests with a particular status.
Jon Salz0405ab52012-03-16 15:26:52 +08001404
Jon Salz0697cbf2012-07-04 15:14:04 +08001405 All active tests, plus any tests to re-run, are reset.
Jon Salz57717ca2012-04-04 16:47:25 +08001406
Jon Salz0697cbf2012-07-04 15:14:04 +08001407 Args:
1408 starting_at: If provided, only auto-runs tests beginning with
1409 this test.
1410 '''
1411 root = root or self.test_list
Jon Salz57717ca2012-04-04 16:47:25 +08001412
Jon Salz0697cbf2012-07-04 15:14:04 +08001413 if starting_at:
1414 # Make sure they passed a test, not a string.
1415 assert isinstance(starting_at, factory.FactoryTest)
Jon Salz0405ab52012-03-16 15:26:52 +08001416
Jon Salz0697cbf2012-07-04 15:14:04 +08001417 tests_to_reset = []
1418 tests_to_run = []
Jon Salz0405ab52012-03-16 15:26:52 +08001419
Jon Salz0697cbf2012-07-04 15:14:04 +08001420 found_starting_at = False
Jon Salz0405ab52012-03-16 15:26:52 +08001421
Jon Salz0697cbf2012-07-04 15:14:04 +08001422 for test in root.get_top_level_tests():
1423 if starting_at:
1424 if test == starting_at:
1425 # We've found starting_at; do auto-run on all
1426 # subsequent tests.
1427 found_starting_at = True
1428 if not found_starting_at:
1429 # Don't start this guy yet
1430 continue
Jon Salz0405ab52012-03-16 15:26:52 +08001431
Jon Salz0697cbf2012-07-04 15:14:04 +08001432 status = test.get_state().status
1433 if status == TestState.ACTIVE or status in statuses_to_run:
1434 # Reset the test (later; we will need to abort
1435 # all active tests first).
1436 tests_to_reset.append(test)
1437 if status in statuses_to_run:
1438 tests_to_run.append(test)
Jon Salz0405ab52012-03-16 15:26:52 +08001439
Jon Salz0697cbf2012-07-04 15:14:04 +08001440 self.abort_active_tests()
Jon Salz258a40c2012-04-19 12:34:01 +08001441
Jon Salz0697cbf2012-07-04 15:14:04 +08001442 # Reset all statuses of the tests to run (in case any tests were active;
1443 # we want them to be run again).
1444 for test_to_reset in tests_to_reset:
1445 for test in test_to_reset.walk():
1446 test.update_state(status=TestState.UNTESTED)
Jon Salz57717ca2012-04-04 16:47:25 +08001447
Jon Salz0697cbf2012-07-04 15:14:04 +08001448 self.run_tests(tests_to_run, untested_only=True)
Jon Salz0405ab52012-03-16 15:26:52 +08001449
Jon Salz0697cbf2012-07-04 15:14:04 +08001450 def restart_tests(self, root=None):
1451 '''Restarts all tests.'''
1452 root = root or self.test_list
Jon Salz0405ab52012-03-16 15:26:52 +08001453
Jon Salz0697cbf2012-07-04 15:14:04 +08001454 self.abort_active_tests()
1455 for test in root.walk():
1456 test.update_state(status=TestState.UNTESTED)
1457 self.run_tests(root)
Hung-Te Lin96632362012-03-20 21:14:18 +08001458
Jon Salz0697cbf2012-07-04 15:14:04 +08001459 def auto_run(self, starting_at=None, root=None):
1460 '''"Auto-runs" tests that have not been run yet.
Hung-Te Lin96632362012-03-20 21:14:18 +08001461
Jon Salz0697cbf2012-07-04 15:14:04 +08001462 Args:
1463 starting_at: If provide, only auto-runs tests beginning with
1464 this test.
1465 '''
1466 root = root or self.test_list
1467 self.run_tests_with_status([TestState.UNTESTED, TestState.ACTIVE],
1468 starting_at=starting_at,
1469 root=root)
Jon Salz968e90b2012-03-18 16:12:43 +08001470
Jon Salz0697cbf2012-07-04 15:14:04 +08001471 def re_run_failed(self, root=None):
1472 '''Re-runs failed tests.'''
1473 root = root or self.test_list
1474 self.run_tests_with_status([TestState.FAILED], root=root)
Jon Salz57717ca2012-04-04 16:47:25 +08001475
Jon Salz0697cbf2012-07-04 15:14:04 +08001476 def show_review_information(self):
1477 '''Event handler for showing review information screen.
Jon Salz57717ca2012-04-04 16:47:25 +08001478
Jon Salz0697cbf2012-07-04 15:14:04 +08001479 The information screene is rendered by main UI program (ui.py), so in
1480 goofy we only need to kill all active tests, set them as untested, and
1481 clear remaining tests.
1482 '''
1483 self.kill_active_tests(False)
Jon Salza6711d72012-07-18 14:33:03 +08001484 self.cancel_pending_tests()
Jon Salz57717ca2012-04-04 16:47:25 +08001485
Jon Salz0697cbf2012-07-04 15:14:04 +08001486 def handle_switch_test(self, event):
1487 '''Switches to a particular test.
Jon Salz0405ab52012-03-16 15:26:52 +08001488
Jon Salz0697cbf2012-07-04 15:14:04 +08001489 @param event: The SWITCH_TEST event.
1490 '''
1491 test = self.test_list.lookup_path(event.path)
1492 if not test:
1493 logging.error('Unknown test %r', event.key)
1494 return
Jon Salz73e0fd02012-04-04 11:46:38 +08001495
Jon Salz0697cbf2012-07-04 15:14:04 +08001496 invoc = self.invocations.get(test)
1497 if invoc and test.backgroundable:
1498 # Already running: just bring to the front if it
1499 # has a UI.
1500 logging.info('Setting visible test to %s', test.path)
Jon Salz36fbbb52012-07-05 13:45:06 +08001501 self.set_visible_test(test)
Jon Salz0697cbf2012-07-04 15:14:04 +08001502 return
Jon Salz73e0fd02012-04-04 11:46:38 +08001503
Jon Salz0697cbf2012-07-04 15:14:04 +08001504 self.abort_active_tests()
1505 for t in test.walk():
1506 t.update_state(status=TestState.UNTESTED)
Jon Salz73e0fd02012-04-04 11:46:38 +08001507
Jon Salz0697cbf2012-07-04 15:14:04 +08001508 if self.test_list.options.auto_run_on_keypress:
1509 self.auto_run(starting_at=test)
1510 else:
1511 self.run_tests(test)
Jon Salz73e0fd02012-04-04 11:46:38 +08001512
Jon Salz0697cbf2012-07-04 15:14:04 +08001513 def wait(self):
1514 '''Waits for all pending invocations.
1515
1516 Useful for testing.
1517 '''
Jon Salz1acc8742012-07-17 17:45:55 +08001518 while self.invocations:
1519 for k, v in self.invocations.iteritems():
1520 logging.info('Waiting for %s to complete...', k)
1521 v.thread.join()
1522 self.reap_completed_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +08001523
1524 def check_exceptions(self):
1525 '''Raises an error if any exceptions have occurred in
1526 invocation threads.'''
1527 if self.exceptions:
1528 raise RuntimeError('Exception in invocation thread: %r' %
1529 self.exceptions)
1530
1531 def record_exception(self, msg):
1532 '''Records an exception in an invocation thread.
1533
1534 An exception with the given message will be rethrown when
1535 Goofy is destroyed.'''
1536 self.exceptions.append(msg)
Jon Salz73e0fd02012-04-04 11:46:38 +08001537
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001538
1539if __name__ == '__main__':
Jon Salz77c151e2012-08-28 07:20:37 +08001540 goofy = Goofy()
1541 try:
1542 goofy.main()
Jon Salz0f996602012-10-03 15:26:48 +08001543 except SystemExit:
1544 # Propagate SystemExit without logging.
1545 raise
Jon Salz31373eb2012-09-21 16:19:49 +08001546 except:
Jon Salz0f996602012-10-03 15:26:48 +08001547 # Log the error before trying to shut down (unless it's a graceful
1548 # exit).
Jon Salz31373eb2012-09-21 16:19:49 +08001549 logging.exception('Error in main loop')
1550 raise
Jon Salz77c151e2012-08-28 07:20:37 +08001551 finally:
1552 goofy.destroy()