blob: ba55fbbe800a0c9629286b4eba447e5f0b9e908d [file] [log] [blame]
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001#!/usr/bin/python -u
Hung-Te Linf2f78f72012-02-08 19:27:11 +08002# -*- coding: utf-8 -*-
3#
Jon Salz37eccbd2012-05-25 16:06:52 +08004# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
Hung-Te Linf2f78f72012-02-08 19:27:11 +08005# Use of this source code is governed by a BSD-style license that can be
6# found in the LICENSE file.
7
8'''
9The main factory flow that runs the factory test and finalizes a device.
10'''
11
Jon Salz0405ab52012-03-16 15:26:52 +080012import logging
13import os
Jon Salz73e0fd02012-04-04 11:46:38 +080014import Queue
Jon Salz77c151e2012-08-28 07:20:37 +080015import signal
Jon Salz0405ab52012-03-16 15:26:52 +080016import sys
Jon Salz0405ab52012-03-16 15:26:52 +080017import threading
18import time
19import traceback
Jon Salz258a40c2012-04-19 12:34:01 +080020import uuid
Jon Salzb10cf512012-08-09 17:29:21 +080021from xmlrpclib import Binary
Hung-Te Linf2f78f72012-02-08 19:27:11 +080022from collections import deque
23from optparse import OptionParser
Hung-Te Linf2f78f72012-02-08 19:27:11 +080024
Jon Salz0697cbf2012-07-04 15:14:04 +080025import factory_common # pylint: disable=W0611
jcliangcd688182012-08-20 21:01:26 +080026from cros.factory import event_log
27from cros.factory import system
28from cros.factory.event_log import EventLog
29from cros.factory.goofy import test_environment
30from cros.factory.goofy import time_sanitizer
Jon Salz83591782012-06-26 11:09:58 +080031from cros.factory.goofy import updater
Jon Salz51528e12012-07-02 18:54:45 +080032from cros.factory.goofy.event_log_watcher import EventLogWatcher
jcliangcd688182012-08-20 21:01:26 +080033from cros.factory.goofy.goofy_rpc import GoofyRPC
34from cros.factory.goofy.invocation import TestInvocation
35from cros.factory.goofy.prespawner import Prespawner
36from cros.factory.goofy.web_socket_manager import WebSocketManager
37from cros.factory.system.charge_manager import ChargeManager
Jon Salzb92c5112012-09-21 15:40:11 +080038from cros.factory.system import disk_space
jcliangcd688182012-08-20 21:01:26 +080039from cros.factory.test import factory
40from cros.factory.test import state
Jon Salz51528e12012-07-02 18:54:45 +080041from cros.factory.test import shopfloor
Jon Salz83591782012-06-26 11:09:58 +080042from cros.factory.test import utils
43from cros.factory.test.event import Event
44from cros.factory.test.event import EventClient
45from cros.factory.test.event import EventServer
jcliangcd688182012-08-20 21:01:26 +080046from cros.factory.test.factory import TestState
Jon Salz78c32392012-07-25 14:18:29 +080047from cros.factory.utils.process_utils import Spawn
Hung-Te Linf2f78f72012-02-08 19:27:11 +080048
49
Jon Salz2f757d42012-06-27 17:06:42 +080050DEFAULT_TEST_LISTS_DIR = os.path.join(factory.FACTORY_PATH, 'test_lists')
51CUSTOM_DIR = os.path.join(factory.FACTORY_PATH, 'custom')
Hung-Te Linf2f78f72012-02-08 19:27:11 +080052HWID_CFG_PATH = '/usr/local/share/chromeos-hwid/cfg'
53
Jon Salz8796e362012-05-24 11:39:09 +080054# File that suppresses reboot if present (e.g., for development).
55NO_REBOOT_FILE = '/var/log/factory.noreboot'
56
Jon Salz5c344f62012-07-13 14:31:16 +080057# Value for tests_after_shutdown that forces auto-run (e.g., after
58# a factory update, when the available set of tests might change).
59FORCE_AUTO_RUN = 'force_auto_run'
60
cychiang21886742012-07-05 15:16:32 +080061RUN_QUEUE_TIMEOUT_SECS = 10
62
Jon Salz758e6cc2012-04-03 15:47:07 +080063GOOFY_IN_CHROOT_WARNING = '\n' + ('*' * 70) + '''
64You are running Goofy inside the chroot. Autotests are not supported.
65
66To use Goofy in the chroot, first install an Xvnc server:
67
Jon Salz0697cbf2012-07-04 15:14:04 +080068 sudo apt-get install tightvncserver
Jon Salz758e6cc2012-04-03 15:47:07 +080069
70...and then start a VNC X server outside the chroot:
71
Jon Salz0697cbf2012-07-04 15:14:04 +080072 vncserver :10 &
73 vncviewer :10
Jon Salz758e6cc2012-04-03 15:47:07 +080074
75...and run Goofy as follows:
76
Jon Salz0697cbf2012-07-04 15:14:04 +080077 env --unset=XAUTHORITY DISPLAY=localhost:10 python goofy.py
Jon Salz758e6cc2012-04-03 15:47:07 +080078''' + ('*' * 70)
Jon Salz73e0fd02012-04-04 11:46:38 +080079suppress_chroot_warning = False
Hung-Te Linf2f78f72012-02-08 19:27:11 +080080
81def get_hwid_cfg():
Jon Salz0697cbf2012-07-04 15:14:04 +080082 '''
83 Returns the HWID config tag, or an empty string if none can be found.
84 '''
85 if 'CROS_HWID' in os.environ:
86 return os.environ['CROS_HWID']
87 if os.path.exists(HWID_CFG_PATH):
88 with open(HWID_CFG_PATH, 'rt') as hwid_cfg_handle:
89 return hwid_cfg_handle.read().strip()
90 return ''
Hung-Te Linf2f78f72012-02-08 19:27:11 +080091
92
93def find_test_list():
Jon Salz0697cbf2012-07-04 15:14:04 +080094 '''
95 Returns the path to the active test list, based on the HWID config tag.
96 '''
97 hwid_cfg = get_hwid_cfg()
Hung-Te Linf2f78f72012-02-08 19:27:11 +080098
Jon Salz4be56b02012-12-22 07:30:46 +080099 search_dirs = [DEFAULT_TEST_LISTS_DIR]
100 if not utils.in_chroot():
101 # Also look in suite_Factory. For backward compatibility only;
102 # new boards should just put the test list in the "test_lists"
103 # directory.
104 search_dirs.insert(0, os.path.join(
105 os.path.dirname(factory.FACTORY_PATH),
106 'autotest', 'site_tests', 'suite_Factory'))
Jon Salz2f757d42012-06-27 17:06:42 +0800107
Jon Salz0697cbf2012-07-04 15:14:04 +0800108 # Try in order: test_list_${hwid_cfg}, test_list, test_list.all
109 search_files = ['test_list', 'test_list.all']
110 if hwid_cfg:
111 search_files.insert(0, hwid_cfg)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800112
Jon Salz0697cbf2012-07-04 15:14:04 +0800113 for d in search_dirs:
114 for f in search_files:
115 test_list = os.path.join(d, f)
116 if os.path.exists(test_list):
117 return test_list
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800118
Jon Salz0697cbf2012-07-04 15:14:04 +0800119 logging.warn('Cannot find test lists named any of %s in any of %s',
120 search_files, search_dirs)
121 return None
Jon Salz73e0fd02012-04-04 11:46:38 +0800122
Jon Salz73e0fd02012-04-04 11:46:38 +0800123_inited_logging = False
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800124
125class Goofy(object):
Jon Salz0697cbf2012-07-04 15:14:04 +0800126 '''
127 The main factory flow.
128
129 Note that all methods in this class must be invoked from the main
130 (event) thread. Other threads, such as callbacks and TestInvocation
131 methods, should instead post events on the run queue.
132
133 TODO: Unit tests. (chrome-os-partner:7409)
134
135 Properties:
136 uuid: A unique UUID for this invocation of Goofy.
137 state_instance: An instance of FactoryState.
138 state_server: The FactoryState XML/RPC server.
139 state_server_thread: A thread running state_server.
140 event_server: The EventServer socket server.
141 event_server_thread: A thread running event_server.
142 event_client: A client to the event server.
143 connection_manager: The connection_manager object.
Jon Salz0697cbf2012-07-04 15:14:04 +0800144 ui_process: The factory ui process object.
145 run_queue: A queue of callbacks to invoke from the main thread.
146 invocations: A map from FactoryTest objects to the corresponding
147 TestInvocations objects representing active tests.
148 tests_to_run: A deque of tests that should be run when the current
149 test(s) complete.
150 options: Command-line options.
151 args: Command-line args.
152 test_list: The test list.
153 event_handlers: Map of Event.Type to the method used to handle that
154 event. If the method has an 'event' argument, the event is passed
155 to the handler.
156 exceptions: Exceptions encountered in invocation threads.
157 '''
158 def __init__(self):
159 self.uuid = str(uuid.uuid4())
160 self.state_instance = None
161 self.state_server = None
162 self.state_server_thread = None
Jon Salz16d10542012-07-23 12:18:45 +0800163 self.goofy_rpc = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800164 self.event_server = None
165 self.event_server_thread = None
166 self.event_client = None
167 self.connection_manager = None
Vic Yang4953fc12012-07-26 16:19:53 +0800168 self.charge_manager = None
Jon Salz8fa8e832012-07-13 19:04:09 +0800169 self.time_sanitizer = None
170 self.time_synced = False
Jon Salz0697cbf2012-07-04 15:14:04 +0800171 self.log_watcher = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800172 self.event_log = None
173 self.prespawner = None
174 self.ui_process = None
Jon Salzc79a9982012-08-30 04:42:01 +0800175 self.dummy_shopfloor = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800176 self.run_queue = Queue.Queue()
177 self.invocations = {}
178 self.tests_to_run = deque()
179 self.visible_test = None
180 self.chrome = None
181
182 self.options = None
183 self.args = None
184 self.test_list = None
185 self.on_ui_startup = []
186 self.env = None
Jon Salzb22d1172012-08-06 10:38:57 +0800187 self.last_idle = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800188 self.last_shutdown_time = None
cychiang21886742012-07-05 15:16:32 +0800189 self.last_update_check = None
Jon Salz8fa8e832012-07-13 19:04:09 +0800190 self.last_sync_time = None
Jon Salzb92c5112012-09-21 15:40:11 +0800191 self.last_log_disk_space_time = None
Vic Yang311ddb82012-09-26 12:08:28 +0800192 self.exclusive_items = set()
Jon Salz0f996602012-10-03 15:26:48 +0800193 self.event_log = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800194
Jon Salz85a39882012-07-05 16:45:04 +0800195 def test_or_root(event, parent_or_group=True):
196 '''Returns the test affected by a particular event.
197
198 Args:
199 event: The event containing an optional 'path' attribute.
200 parent_on_group: If True, returns the top-level parent for a test (the
201 root node of the tests that need to be run together if the given test
202 path is to be run).
203 '''
Jon Salz0697cbf2012-07-04 15:14:04 +0800204 try:
205 path = event.path
206 except AttributeError:
207 path = None
208
209 if path:
Jon Salz85a39882012-07-05 16:45:04 +0800210 test = self.test_list.lookup_path(path)
211 if parent_or_group:
212 test = test.get_top_level_parent_or_group()
213 return test
Jon Salz0697cbf2012-07-04 15:14:04 +0800214 else:
215 return self.test_list
216
217 self.event_handlers = {
218 Event.Type.SWITCH_TEST: self.handle_switch_test,
219 Event.Type.SHOW_NEXT_ACTIVE_TEST:
220 lambda event: self.show_next_active_test(),
221 Event.Type.RESTART_TESTS:
222 lambda event: self.restart_tests(root=test_or_root(event)),
223 Event.Type.AUTO_RUN:
224 lambda event: self.auto_run(root=test_or_root(event)),
225 Event.Type.RE_RUN_FAILED:
226 lambda event: self.re_run_failed(root=test_or_root(event)),
227 Event.Type.RUN_TESTS_WITH_STATUS:
228 lambda event: self.run_tests_with_status(
229 event.status,
230 root=test_or_root(event)),
231 Event.Type.REVIEW:
232 lambda event: self.show_review_information(),
233 Event.Type.UPDATE_SYSTEM_INFO:
234 lambda event: self.update_system_info(),
Jon Salz0697cbf2012-07-04 15:14:04 +0800235 Event.Type.STOP:
Jon Salz85a39882012-07-05 16:45:04 +0800236 lambda event: self.stop(root=test_or_root(event, False),
237 fail=getattr(event, 'fail', False)),
Jon Salz36fbbb52012-07-05 13:45:06 +0800238 Event.Type.SET_VISIBLE_TEST:
239 lambda event: self.set_visible_test(
240 self.test_list.lookup_path(event.path)),
Jon Salz0697cbf2012-07-04 15:14:04 +0800241 }
242
243 self.exceptions = []
244 self.web_socket_manager = None
245
246 def destroy(self):
247 if self.chrome:
248 self.chrome.kill()
249 self.chrome = None
Jon Salzc79a9982012-08-30 04:42:01 +0800250 if self.dummy_shopfloor:
251 self.dummy_shopfloor.kill()
252 self.dummy_shopfloor = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800253 if self.ui_process:
254 utils.kill_process_tree(self.ui_process, 'ui')
255 self.ui_process = None
256 if self.web_socket_manager:
257 logging.info('Stopping web sockets')
258 self.web_socket_manager.close()
259 self.web_socket_manager = None
260 if self.state_server_thread:
261 logging.info('Stopping state server')
262 self.state_server.shutdown()
263 self.state_server_thread.join()
264 self.state_server.server_close()
265 self.state_server_thread = None
266 if self.state_instance:
267 self.state_instance.close()
268 if self.event_server_thread:
269 logging.info('Stopping event server')
270 self.event_server.shutdown() # pylint: disable=E1101
271 self.event_server_thread.join()
272 self.event_server.server_close()
273 self.event_server_thread = None
274 if self.log_watcher:
275 if self.log_watcher.IsThreadStarted():
276 self.log_watcher.StopWatchThread()
277 self.log_watcher = None
278 if self.prespawner:
279 logging.info('Stopping prespawner')
280 self.prespawner.stop()
281 self.prespawner = None
282 if self.event_client:
283 logging.info('Closing event client')
284 self.event_client.close()
285 self.event_client = None
286 if self.event_log:
287 self.event_log.Close()
288 self.event_log = None
289 self.check_exceptions()
290 logging.info('Done destroying Goofy')
291
292 def start_state_server(self):
293 self.state_instance, self.state_server = (
294 state.create_server(bind_address='0.0.0.0'))
Jon Salz16d10542012-07-23 12:18:45 +0800295 self.goofy_rpc = GoofyRPC(self)
296 self.goofy_rpc.RegisterMethods(self.state_instance)
Jon Salz0697cbf2012-07-04 15:14:04 +0800297 logging.info('Starting state server')
298 self.state_server_thread = threading.Thread(
299 target=self.state_server.serve_forever,
300 name='StateServer')
301 self.state_server_thread.start()
302
303 def start_event_server(self):
304 self.event_server = EventServer()
305 logging.info('Starting factory event server')
306 self.event_server_thread = threading.Thread(
307 target=self.event_server.serve_forever,
308 name='EventServer') # pylint: disable=E1101
309 self.event_server_thread.start()
310
311 self.event_client = EventClient(
312 callback=self.handle_event, event_loop=self.run_queue)
313
314 self.web_socket_manager = WebSocketManager(self.uuid)
315 self.state_server.add_handler("/event",
316 self.web_socket_manager.handle_web_socket)
317
318 def start_ui(self):
319 ui_proc_args = [
320 os.path.join(factory.FACTORY_PACKAGE_PATH, 'test', 'ui.py'),
321 self.options.test_list]
322 if self.options.verbose:
323 ui_proc_args.append('-v')
324 logging.info('Starting ui %s', ui_proc_args)
Jon Salz78c32392012-07-25 14:18:29 +0800325 self.ui_process = Spawn(ui_proc_args)
Jon Salz0697cbf2012-07-04 15:14:04 +0800326 logging.info('Waiting for UI to come up...')
327 self.event_client.wait(
328 lambda event: event.type == Event.Type.UI_READY)
329 logging.info('UI has started')
330
331 def set_visible_test(self, test):
332 if self.visible_test == test:
333 return
Jon Salz2f2d42c2012-07-30 12:30:34 +0800334 if test and not test.has_ui:
335 return
Jon Salz0697cbf2012-07-04 15:14:04 +0800336
337 if test:
338 test.update_state(visible=True)
339 if self.visible_test:
340 self.visible_test.update_state(visible=False)
341 self.visible_test = test
342
Jon Salzd4306c82012-11-30 15:16:36 +0800343 def _log_startup_messages(self):
344 '''Logs the tail of var/log/messages and mosys and EC console logs.'''
345 # TODO(jsalz): This is mostly a copy-and-paste of code in init_states,
346 # for factory-3004.B only. Consolidate and merge back to ToT.
347 if utils.in_chroot():
348 return
349
350 try:
351 var_log_messages = (
352 utils.var_log_messages_before_reboot())
353 logging.info(
354 'Tail of /var/log/messages before last reboot:\n'
355 '%s', ('\n'.join(
356 ' ' + x for x in var_log_messages)))
357 except: # pylint: disable=W0702
358 logging.exception('Unable to grok /var/log/messages')
359
360 try:
361 mosys_log = utils.Spawn(
362 ['mosys', 'eventlog', 'list'],
363 read_stdout=True, log_stderr_on_error=True).stdout_data
364 logging.info('System eventlog from mosys:\n%s\n', mosys_log)
365 except: # pylint: disable=W0702
366 logging.exception('Unable to read mosys eventlog')
367
368 try:
369 ec = system.GetEC()
370 ec_console_log = ec.GetConsoleLog()
371 logging.info('EC console log after reboot:\n%s\n', ec_console_log)
372 except: # pylint: disable=W0702
373 logging.exception('Error retrieving EC console log')
374
Jon Salz0697cbf2012-07-04 15:14:04 +0800375 def handle_shutdown_complete(self, test, test_state):
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800376 '''
Jon Salz0697cbf2012-07-04 15:14:04 +0800377 Handles the case where a shutdown was detected during a shutdown step.
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800378
Jon Salz0697cbf2012-07-04 15:14:04 +0800379 @param test: The ShutdownStep.
380 @param test_state: The test state.
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800381 '''
Jon Salz0697cbf2012-07-04 15:14:04 +0800382 test_state = test.update_state(increment_shutdown_count=1)
383 logging.info('Detected shutdown (%d of %d)',
384 test_state.shutdown_count, test.iterations)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800385
Jon Salz0697cbf2012-07-04 15:14:04 +0800386 def log_and_update_state(status, error_msg, **kw):
387 self.event_log.Log('rebooted',
388 status=status, error_msg=error_msg, **kw)
Jon Salzd4306c82012-11-30 15:16:36 +0800389 logging.info('Rebooted: status=%s, %s', status,
390 (('error_msg=%s' % error_msg) if error_msg else None))
Jon Salz0697cbf2012-07-04 15:14:04 +0800391 test.update_state(status=status, error_msg=error_msg)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800392
Jon Salz0697cbf2012-07-04 15:14:04 +0800393 if not self.last_shutdown_time:
394 log_and_update_state(status=TestState.FAILED,
395 error_msg='Unable to read shutdown_time')
396 return
Jon Salz258a40c2012-04-19 12:34:01 +0800397
Jon Salz0697cbf2012-07-04 15:14:04 +0800398 now = time.time()
399 logging.info('%.03f s passed since reboot',
400 now - self.last_shutdown_time)
Jon Salz258a40c2012-04-19 12:34:01 +0800401
Jon Salz0697cbf2012-07-04 15:14:04 +0800402 if self.last_shutdown_time > now:
403 test.update_state(status=TestState.FAILED,
404 error_msg='Time moved backward during reboot')
405 elif (isinstance(test, factory.RebootStep) and
406 self.test_list.options.max_reboot_time_secs and
407 (now - self.last_shutdown_time >
408 self.test_list.options.max_reboot_time_secs)):
409 # A reboot took too long; fail. (We don't check this for
410 # HaltSteps, because the machine could be halted for a
411 # very long time, and even unplugged with battery backup,
412 # thus hosing the clock.)
413 log_and_update_state(
414 status=TestState.FAILED,
415 error_msg=('More than %d s elapsed during reboot '
416 '(%.03f s, from %s to %s)' % (
417 self.test_list.options.max_reboot_time_secs,
418 now - self.last_shutdown_time,
419 utils.TimeString(self.last_shutdown_time),
420 utils.TimeString(now))),
421 duration=(now-self.last_shutdown_time))
Jon Salzd4306c82012-11-30 15:16:36 +0800422 self._log_startup_messages()
Jon Salz0697cbf2012-07-04 15:14:04 +0800423 elif test_state.shutdown_count == test.iterations:
424 # Good!
425 log_and_update_state(status=TestState.PASSED,
426 duration=(now - self.last_shutdown_time),
427 error_msg='')
428 elif test_state.shutdown_count > test.iterations:
429 # Shut down too many times
430 log_and_update_state(status=TestState.FAILED,
431 error_msg='Too many shutdowns')
Jon Salzd4306c82012-11-30 15:16:36 +0800432 self._log_startup_messages()
Jon Salz0697cbf2012-07-04 15:14:04 +0800433 elif utils.are_shift_keys_depressed():
434 logging.info('Shift keys are depressed; cancelling restarts')
435 # Abort shutdown
436 log_and_update_state(
437 status=TestState.FAILED,
438 error_msg='Shutdown aborted with double shift keys')
Jon Salza6711d72012-07-18 14:33:03 +0800439 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +0800440 else:
441 def handler():
442 if self._prompt_cancel_shutdown(
443 test, test_state.shutdown_count + 1):
Jon Salza6711d72012-07-18 14:33:03 +0800444 factory.console.info('Shutdown aborted by operator')
Jon Salz0697cbf2012-07-04 15:14:04 +0800445 log_and_update_state(
446 status=TestState.FAILED,
447 error_msg='Shutdown aborted by operator')
Jon Salza6711d72012-07-18 14:33:03 +0800448 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +0800449 return
Jon Salz0405ab52012-03-16 15:26:52 +0800450
Jon Salz0697cbf2012-07-04 15:14:04 +0800451 # Time to shutdown again
452 log_and_update_state(
453 status=TestState.ACTIVE,
454 error_msg='',
455 iteration=test_state.shutdown_count)
Jon Salz73e0fd02012-04-04 11:46:38 +0800456
Jon Salz0697cbf2012-07-04 15:14:04 +0800457 self.event_log.Log('shutdown', operation='reboot')
458 self.state_instance.set_shared_data('shutdown_time',
459 time.time())
460 self.env.shutdown('reboot')
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800461
Jon Salz0697cbf2012-07-04 15:14:04 +0800462 self.on_ui_startup.append(handler)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800463
Jon Salz0697cbf2012-07-04 15:14:04 +0800464 def _prompt_cancel_shutdown(self, test, iteration):
465 if self.options.ui != 'chrome':
466 return False
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800467
Jon Salz0697cbf2012-07-04 15:14:04 +0800468 pending_shutdown_data = {
469 'delay_secs': test.delay_secs,
470 'time': time.time() + test.delay_secs,
471 'operation': test.operation,
472 'iteration': iteration,
473 'iterations': test.iterations,
474 }
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800475
Jon Salz0697cbf2012-07-04 15:14:04 +0800476 # Create a new (threaded) event client since we
477 # don't want to use the event loop for this.
478 with EventClient() as event_client:
479 event_client.post_event(Event(Event.Type.PENDING_SHUTDOWN,
480 **pending_shutdown_data))
481 aborted = event_client.wait(
482 lambda event: event.type == Event.Type.CANCEL_SHUTDOWN,
483 timeout=test.delay_secs) is not None
484 if aborted:
485 event_client.post_event(Event(Event.Type.PENDING_SHUTDOWN))
486 return aborted
Jon Salz258a40c2012-04-19 12:34:01 +0800487
Jon Salz0697cbf2012-07-04 15:14:04 +0800488 def init_states(self):
489 '''
490 Initializes all states on startup.
491 '''
492 for test in self.test_list.get_all_tests():
493 # Make sure the state server knows about all the tests,
494 # defaulting to an untested state.
495 test.update_state(update_parent=False, visible=False)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800496
Jon Salz0697cbf2012-07-04 15:14:04 +0800497 var_log_messages = None
Vic Yanga9c32212012-08-16 20:07:54 +0800498 mosys_log = None
Vic Yange4c275d2012-08-28 01:50:20 +0800499 ec_console_log = None
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800500
Jon Salz0697cbf2012-07-04 15:14:04 +0800501 # Any 'active' tests should be marked as failed now.
502 for test in self.test_list.walk():
Jon Salza6711d72012-07-18 14:33:03 +0800503 if not test.is_leaf():
504 # Don't bother with parents; they will be updated when their
505 # children are updated.
506 continue
507
Jon Salz0697cbf2012-07-04 15:14:04 +0800508 test_state = test.get_state()
509 if test_state.status != TestState.ACTIVE:
510 continue
511 if isinstance(test, factory.ShutdownStep):
512 # Shutdown while the test was active - that's good.
513 self.handle_shutdown_complete(test, test_state)
514 else:
515 # Unexpected shutdown. Grab /var/log/messages for context.
516 if var_log_messages is None:
517 try:
518 var_log_messages = (
519 utils.var_log_messages_before_reboot())
520 # Write it to the log, to make it easier to
521 # correlate with /var/log/messages.
522 logging.info(
523 'Unexpected shutdown. '
524 'Tail of /var/log/messages before last reboot:\n'
525 '%s', ('\n'.join(
526 ' ' + x for x in var_log_messages)))
527 except: # pylint: disable=W0702
528 logging.exception('Unable to grok /var/log/messages')
529 var_log_messages = []
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800530
Jon Salz008f4ea2012-08-28 05:39:45 +0800531 if mosys_log is None and not utils.in_chroot():
532 try:
533 mosys_log = utils.Spawn(
534 ['mosys', 'eventlog', 'list'],
535 read_stdout=True, log_stderr_on_error=True).stdout_data
536 # Write it to the log also.
537 logging.info('System eventlog from mosys:\n%s\n', mosys_log)
538 except: # pylint: disable=W0702
539 logging.exception('Unable to read mosys eventlog')
Vic Yanga9c32212012-08-16 20:07:54 +0800540
Vic Yange4c275d2012-08-28 01:50:20 +0800541 if ec_console_log is None:
542 try:
543 ec = system.GetEC()
544 ec_console_log = ec.GetConsoleLog()
545 logging.info('EC console log after reboot:\n%s\n', ec_console_log)
Jon Salzfe1f6652012-09-07 05:40:14 +0800546 except: # pylint: disable=W0702
Vic Yange4c275d2012-08-28 01:50:20 +0800547 logging.exception('Error retrieving EC console log')
548
Jon Salz0697cbf2012-07-04 15:14:04 +0800549 error_msg = 'Unexpected shutdown while test was running'
550 self.event_log.Log('end_test',
551 path=test.path,
552 status=TestState.FAILED,
553 invocation=test.get_state().invocation,
554 error_msg=error_msg,
Vic Yanga9c32212012-08-16 20:07:54 +0800555 var_log_messages='\n'.join(var_log_messages),
556 mosys_log=mosys_log)
Jon Salz0697cbf2012-07-04 15:14:04 +0800557 test.update_state(
558 status=TestState.FAILED,
559 error_msg=error_msg)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800560
Jon Salz50efe942012-07-26 11:54:10 +0800561 if not test.never_fails:
562 # For "never_fails" tests (such as "Start"), don't cancel
563 # pending tests, since reboot is expected.
564 factory.console.info('Unexpected shutdown while test %s '
565 'running; cancelling any pending tests',
566 test.path)
567 self.state_instance.set_shared_data('tests_after_shutdown', [])
Jon Salz69806bb2012-07-20 18:05:02 +0800568
Jon Salz008f4ea2012-08-28 05:39:45 +0800569 self.update_skipped_tests()
570
571 def update_skipped_tests(self):
572 '''
573 Updates skipped states based on run_if.
574 '''
575 for t in self.test_list.walk():
576 if t.is_leaf() and t.run_if_table_name:
577 skip = False
578 try:
579 aux = shopfloor.get_selected_aux_data(t.run_if_table_name)
580 value = aux.get(t.run_if_col)
581 if value is not None:
582 skip = (not value) ^ t.run_if_not
583 except ValueError:
584 # Not available; assume it shouldn't be skipped
585 pass
586
587 test_state = t.get_state()
588 if ((not skip) and
589 (test_state.status == TestState.PASSED) and
590 (test_state.error_msg == TestState.SKIPPED_MSG)):
591 # It was marked as skipped before, but now we need to run it.
592 # Mark as untested.
593 t.update_state(skip=skip, status=TestState.UNTESTED, error_msg='')
594 else:
595 t.update_state(skip=skip)
596
Jon Salz0697cbf2012-07-04 15:14:04 +0800597 def show_next_active_test(self):
598 '''
599 Rotates to the next visible active test.
600 '''
601 self.reap_completed_tests()
602 active_tests = [
603 t for t in self.test_list.walk()
604 if t.is_leaf() and t.get_state().status == TestState.ACTIVE]
605 if not active_tests:
606 return
Jon Salz4f6c7172012-06-11 20:45:36 +0800607
Jon Salz0697cbf2012-07-04 15:14:04 +0800608 try:
609 next_test = active_tests[
610 (active_tests.index(self.visible_test) + 1) % len(active_tests)]
611 except ValueError: # visible_test not present in active_tests
612 next_test = active_tests[0]
Jon Salz4f6c7172012-06-11 20:45:36 +0800613
Jon Salz0697cbf2012-07-04 15:14:04 +0800614 self.set_visible_test(next_test)
Jon Salz4f6c7172012-06-11 20:45:36 +0800615
Jon Salz0697cbf2012-07-04 15:14:04 +0800616 def handle_event(self, event):
617 '''
618 Handles an event from the event server.
619 '''
620 handler = self.event_handlers.get(event.type)
621 if handler:
622 handler(event)
623 else:
624 # We don't register handlers for all event types - just ignore
625 # this event.
626 logging.debug('Unbound event type %s', event.type)
Jon Salz4f6c7172012-06-11 20:45:36 +0800627
Jon Salz0697cbf2012-07-04 15:14:04 +0800628 def run_next_test(self):
629 '''
630 Runs the next eligible test (or tests) in self.tests_to_run.
631 '''
632 self.reap_completed_tests()
633 while self.tests_to_run:
634 logging.debug('Tests to run: %s',
635 [x.path for x in self.tests_to_run])
Jon Salz94eb56f2012-06-12 18:01:12 +0800636
Jon Salz0697cbf2012-07-04 15:14:04 +0800637 test = self.tests_to_run[0]
Jon Salz94eb56f2012-06-12 18:01:12 +0800638
Jon Salz0697cbf2012-07-04 15:14:04 +0800639 if test in self.invocations:
640 logging.info('Next test %s is already running', test.path)
641 self.tests_to_run.popleft()
642 return
Jon Salz94eb56f2012-06-12 18:01:12 +0800643
Jon Salza1412922012-07-23 16:04:17 +0800644 for requirement in test.require_run:
645 for i in requirement.test.walk():
646 if i.get_state().status == TestState.ACTIVE:
Jon Salz304a75d2012-07-06 11:14:15 +0800647 logging.info('Waiting for active test %s to complete '
Jon Salza1412922012-07-23 16:04:17 +0800648 'before running %s', i.path, test.path)
Jon Salz304a75d2012-07-06 11:14:15 +0800649 return
650
Jon Salz0697cbf2012-07-04 15:14:04 +0800651 if self.invocations and not (test.backgroundable and all(
652 [x.backgroundable for x in self.invocations])):
653 logging.debug('Waiting for non-backgroundable tests to '
654 'complete before running %s', test.path)
655 return
Jon Salz94eb56f2012-06-12 18:01:12 +0800656
Jon Salz3e6f5202012-10-15 15:08:29 +0800657 if test.get_state().skip:
658 factory.console.info('Skipping test %s', test.path)
659 test.update_state(status=TestState.PASSED,
660 error_msg=TestState.SKIPPED_MSG)
661 self.tests_to_run.popleft()
662 continue
663
Jon Salz0697cbf2012-07-04 15:14:04 +0800664 self.tests_to_run.popleft()
Jon Salz94eb56f2012-06-12 18:01:12 +0800665
Jon Salz304a75d2012-07-06 11:14:15 +0800666 untested = set()
Jon Salza1412922012-07-23 16:04:17 +0800667 for requirement in test.require_run:
668 for i in requirement.test.walk():
669 if i == test:
Jon Salz304a75d2012-07-06 11:14:15 +0800670 # We've hit this test itself; stop checking
671 break
Jon Salza1412922012-07-23 16:04:17 +0800672 if ((i.get_state().status == TestState.UNTESTED) or
673 (requirement.passed and i.get_state().status !=
674 TestState.PASSED)):
Jon Salz304a75d2012-07-06 11:14:15 +0800675 # Found an untested test; move on to the next
676 # element in require_run.
Jon Salza1412922012-07-23 16:04:17 +0800677 untested.add(i)
Jon Salz304a75d2012-07-06 11:14:15 +0800678 break
679
680 if untested:
681 untested_paths = ', '.join(sorted([x.path for x in untested]))
682 if self.state_instance.get_shared_data('engineering_mode',
683 optional=True):
684 # In engineering mode, we'll let it go.
685 factory.console.warn('In engineering mode; running '
686 '%s even though required tests '
687 '[%s] have not completed',
688 test.path, untested_paths)
689 else:
690 # Not in engineering mode; mark it failed.
691 error_msg = ('Required tests [%s] have not been run yet'
692 % untested_paths)
693 factory.console.error('Not running %s: %s',
694 test.path, error_msg)
695 test.update_state(status=TestState.FAILED,
696 error_msg=error_msg)
697 continue
698
Jon Salz0697cbf2012-07-04 15:14:04 +0800699 if isinstance(test, factory.ShutdownStep):
700 if os.path.exists(NO_REBOOT_FILE):
701 test.update_state(
702 status=TestState.FAILED, increment_count=1,
703 error_msg=('Skipped shutdown since %s is present' %
Jon Salz304a75d2012-07-06 11:14:15 +0800704 NO_REBOOT_FILE))
Jon Salz0697cbf2012-07-04 15:14:04 +0800705 continue
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800706
Jon Salz0697cbf2012-07-04 15:14:04 +0800707 test.update_state(status=TestState.ACTIVE, increment_count=1,
708 error_msg='', shutdown_count=0)
709 if self._prompt_cancel_shutdown(test, 1):
710 self.event_log.Log('reboot_cancelled')
711 test.update_state(
712 status=TestState.FAILED, increment_count=1,
713 error_msg='Shutdown aborted by operator',
714 shutdown_count=0)
chungyiafe8f772012-08-15 19:36:29 +0800715 continue
Jon Salz2f757d42012-06-27 17:06:42 +0800716
Jon Salz0697cbf2012-07-04 15:14:04 +0800717 # Save pending test list in the state server
Jon Salzdbf398f2012-06-14 17:30:01 +0800718 self.state_instance.set_shared_data(
Jon Salz0697cbf2012-07-04 15:14:04 +0800719 'tests_after_shutdown',
720 [t.path for t in self.tests_to_run])
721 # Save shutdown time
722 self.state_instance.set_shared_data('shutdown_time',
723 time.time())
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800724
Jon Salz0697cbf2012-07-04 15:14:04 +0800725 with self.env.lock:
726 self.event_log.Log('shutdown', operation=test.operation)
727 shutdown_result = self.env.shutdown(test.operation)
728 if shutdown_result:
729 # That's all, folks!
730 self.run_queue.put(None)
731 return
732 else:
733 # Just pass (e.g., in the chroot).
734 test.update_state(status=TestState.PASSED)
735 self.state_instance.set_shared_data(
736 'tests_after_shutdown', None)
737 # Send event with no fields to indicate that there is no
738 # longer a pending shutdown.
739 self.event_client.post_event(Event(
740 Event.Type.PENDING_SHUTDOWN))
741 continue
Jon Salz258a40c2012-04-19 12:34:01 +0800742
Jon Salz1acc8742012-07-17 17:45:55 +0800743 self._run_test(test, test.iterations)
744
745 def _run_test(self, test, iterations_left=None):
746 invoc = TestInvocation(self, test, on_completion=self.run_next_test)
747 new_state = test.update_state(
748 status=TestState.ACTIVE, increment_count=1, error_msg='',
Jon Salzbd42ce12012-09-18 08:03:59 +0800749 invocation=invoc.uuid, iterations_left=iterations_left,
750 visible=(self.visible_test == test))
Jon Salz1acc8742012-07-17 17:45:55 +0800751 invoc.count = new_state.count
752
753 self.invocations[test] = invoc
754 if self.visible_test is None and test.has_ui:
755 self.set_visible_test(test)
Vic Yang311ddb82012-09-26 12:08:28 +0800756 self.check_exclusive()
Jon Salz1acc8742012-07-17 17:45:55 +0800757 invoc.start()
Jon Salz5f2a0672012-05-22 17:14:06 +0800758
Vic Yang311ddb82012-09-26 12:08:28 +0800759 def check_exclusive(self):
760 current_exclusive_items = set([
761 item
762 for item in factory.FactoryTest.EXCLUSIVE_OPTIONS
763 if any([test.is_exclusive(item) for test in self.invocations])])
764
765 new_exclusive_items = current_exclusive_items - self.exclusive_items
766 if factory.FactoryTest.EXCLUSIVE_OPTIONS.NETWORKING in new_exclusive_items:
767 logging.info('Disabling network')
768 self.connection_manager.DisableNetworking()
769 if factory.FactoryTest.EXCLUSIVE_OPTIONS.CHARGER in new_exclusive_items:
770 logging.info('Stop controlling charger')
771
772 new_non_exclusive_items = self.exclusive_items - current_exclusive_items
773 if (factory.FactoryTest.EXCLUSIVE_OPTIONS.NETWORKING in
774 new_non_exclusive_items):
775 logging.info('Re-enabling network')
776 self.connection_manager.EnableNetworking()
777 if factory.FactoryTest.EXCLUSIVE_OPTIONS.CHARGER in new_non_exclusive_items:
778 logging.info('Start controlling charger')
779
780 # Only adjust charge state if not excluded
781 if (self.charge_manager and
782 not factory.FactoryTest.EXCLUSIVE_OPTIONS.CHARGER in
783 current_exclusive_items):
784 self.charge_manager.AdjustChargeState()
785
786 self.exclusive_items = current_exclusive_items
Jon Salz5da61e62012-05-31 13:06:22 +0800787
cychiang21886742012-07-05 15:16:32 +0800788 def check_for_updates(self):
789 '''
790 Schedules an asynchronous check for updates if necessary.
791 '''
792 if not self.test_list.options.update_period_secs:
793 # Not enabled.
794 return
795
796 now = time.time()
797 if self.last_update_check and (
798 now - self.last_update_check <
799 self.test_list.options.update_period_secs):
800 # Not yet time for another check.
801 return
802
803 self.last_update_check = now
804
805 def handle_check_for_update(reached_shopfloor, md5sum, needs_update):
806 if reached_shopfloor:
807 new_update_md5sum = md5sum if needs_update else None
808 if system.SystemInfo.update_md5sum != new_update_md5sum:
809 logging.info('Received new update MD5SUM: %s', new_update_md5sum)
810 system.SystemInfo.update_md5sum = new_update_md5sum
811 self.run_queue.put(self.update_system_info)
812
813 updater.CheckForUpdateAsync(
814 handle_check_for_update,
815 self.test_list.options.shopfloor_timeout_secs)
816
Jon Salza6711d72012-07-18 14:33:03 +0800817 def cancel_pending_tests(self):
818 '''Cancels any tests in the run queue.'''
819 self.run_tests([])
820
Jon Salz0697cbf2012-07-04 15:14:04 +0800821 def run_tests(self, subtrees, untested_only=False):
822 '''
823 Runs tests under subtree.
Jon Salz258a40c2012-04-19 12:34:01 +0800824
Jon Salz0697cbf2012-07-04 15:14:04 +0800825 The tests are run in order unless one fails (then stops).
826 Backgroundable tests are run simultaneously; when a foreground test is
827 encountered, we wait for all active tests to finish before continuing.
Jon Salzb1b39092012-05-03 02:05:09 +0800828
Jon Salz0697cbf2012-07-04 15:14:04 +0800829 @param subtrees: Node or nodes containing tests to run (may either be
830 a single test or a list). Duplicates will be ignored.
831 '''
832 if type(subtrees) != list:
833 subtrees = [subtrees]
Jon Salz258a40c2012-04-19 12:34:01 +0800834
Jon Salz0697cbf2012-07-04 15:14:04 +0800835 # Nodes we've seen so far, to avoid duplicates.
836 seen = set()
Jon Salz94eb56f2012-06-12 18:01:12 +0800837
Jon Salz0697cbf2012-07-04 15:14:04 +0800838 self.tests_to_run = deque()
839 for subtree in subtrees:
840 for test in subtree.walk():
841 if test in seen:
842 continue
843 seen.add(test)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800844
Jon Salz0697cbf2012-07-04 15:14:04 +0800845 if not test.is_leaf():
846 continue
847 if (untested_only and
848 test.get_state().status != TestState.UNTESTED):
849 continue
850 self.tests_to_run.append(test)
851 self.run_next_test()
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800852
Jon Salz0697cbf2012-07-04 15:14:04 +0800853 def reap_completed_tests(self):
854 '''
855 Removes completed tests from the set of active tests.
856
857 Also updates the visible test if it was reaped.
858 '''
859 for t, v in dict(self.invocations).iteritems():
860 if v.is_completed():
Jon Salz1acc8742012-07-17 17:45:55 +0800861 new_state = t.update_state(**v.update_state_on_completion)
Jon Salz0697cbf2012-07-04 15:14:04 +0800862 del self.invocations[t]
863
Chun-Ta Lin54e17e42012-09-06 22:05:13 +0800864 # Stop on failure if flag is true.
865 if (self.test_list.options.stop_on_failure and
866 new_state.status == TestState.FAILED):
867 # Clean all the tests to cause goofy to stop.
868 self.tests_to_run = []
869 factory.console.info("Stop on failure triggered. Empty the queue.")
870
Jon Salz1acc8742012-07-17 17:45:55 +0800871 if new_state.iterations_left and new_state.status == TestState.PASSED:
872 # Play it again, Sam!
873 self._run_test(t)
874
Jon Salz0697cbf2012-07-04 15:14:04 +0800875 if (self.visible_test is None or
Jon Salz85a39882012-07-05 16:45:04 +0800876 self.visible_test not in self.invocations):
Jon Salz0697cbf2012-07-04 15:14:04 +0800877 self.set_visible_test(None)
878 # Make the first running test, if any, the visible test
879 for t in self.test_list.walk():
880 if t in self.invocations:
881 self.set_visible_test(t)
882 break
883
Jon Salz85a39882012-07-05 16:45:04 +0800884 def kill_active_tests(self, abort, root=None):
Jon Salz0697cbf2012-07-04 15:14:04 +0800885 '''
886 Kills and waits for all active tests.
887
Jon Salz85a39882012-07-05 16:45:04 +0800888 Args:
889 abort: True to change state of killed tests to FAILED, False for
Jon Salz0697cbf2012-07-04 15:14:04 +0800890 UNTESTED.
Jon Salz85a39882012-07-05 16:45:04 +0800891 root: If set, only kills tests with root as an ancestor.
Jon Salz0697cbf2012-07-04 15:14:04 +0800892 '''
893 self.reap_completed_tests()
894 for test, invoc in self.invocations.items():
Jon Salz85a39882012-07-05 16:45:04 +0800895 if root and not test.has_ancestor(root):
896 continue
897
Jon Salz0697cbf2012-07-04 15:14:04 +0800898 factory.console.info('Killing active test %s...' % test.path)
899 invoc.abort_and_join()
900 factory.console.info('Killed %s' % test.path)
Jon Salz1acc8742012-07-17 17:45:55 +0800901 test.update_state(**invoc.update_state_on_completion)
Jon Salz0697cbf2012-07-04 15:14:04 +0800902 del self.invocations[test]
Jon Salz1acc8742012-07-17 17:45:55 +0800903
Jon Salz0697cbf2012-07-04 15:14:04 +0800904 if not abort:
905 test.update_state(status=TestState.UNTESTED)
906 self.reap_completed_tests()
907
Jon Salz85a39882012-07-05 16:45:04 +0800908 def stop(self, root=None, fail=False):
909 self.kill_active_tests(fail, root)
910 # Remove any tests in the run queue under the root.
911 self.tests_to_run = deque([x for x in self.tests_to_run
912 if root and not x.has_ancestor(root)])
913 self.run_next_test()
Jon Salz0697cbf2012-07-04 15:14:04 +0800914
915 def abort_active_tests(self):
916 self.kill_active_tests(True)
917
918 def main(self):
919 try:
920 self.init()
921 self.event_log.Log('goofy_init',
922 success=True)
923 except:
924 if self.event_log:
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800925 try:
Jon Salz0697cbf2012-07-04 15:14:04 +0800926 self.event_log.Log('goofy_init',
927 success=False,
928 trace=traceback.format_exc())
929 except: # pylint: disable=W0702
930 pass
931 raise
932
933 self.run()
934
935 def update_system_info(self):
936 '''Updates system info.'''
937 system_info = system.SystemInfo()
938 self.state_instance.set_shared_data('system_info', system_info.__dict__)
939 self.event_client.post_event(Event(Event.Type.SYSTEM_INFO,
940 system_info=system_info.__dict__))
941 logging.info('System info: %r', system_info.__dict__)
942
Jon Salzeb42f0d2012-07-27 19:14:04 +0800943 def update_factory(self, auto_run_on_restart=False, post_update_hook=None):
944 '''Commences updating factory software.
945
946 Args:
947 auto_run_on_restart: Auto-run when the machine comes back up.
948 post_update_hook: Code to call after update but immediately before
949 restart.
950
951 Returns:
952 Never if the update was successful (we just reboot).
953 False if the update was unnecessary (no update available).
954 '''
Jon Salz0697cbf2012-07-04 15:14:04 +0800955 self.kill_active_tests(False)
Jon Salza6711d72012-07-18 14:33:03 +0800956 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +0800957
Jon Salz5c344f62012-07-13 14:31:16 +0800958 def pre_update_hook():
959 if auto_run_on_restart:
960 self.state_instance.set_shared_data('tests_after_shutdown',
961 FORCE_AUTO_RUN)
962 self.state_instance.close()
963
Jon Salzeb42f0d2012-07-27 19:14:04 +0800964 if updater.TryUpdate(pre_update_hook=pre_update_hook):
965 if post_update_hook:
966 post_update_hook()
967 self.env.shutdown('reboot')
Jon Salz0697cbf2012-07-04 15:14:04 +0800968
Jon Salzcef132a2012-08-30 04:58:08 +0800969 def handle_sigint(self, dummy_signum, dummy_frame):
Jon Salz77c151e2012-08-28 07:20:37 +0800970 logging.error('Received SIGINT')
971 self.run_queue.put(None)
972 raise KeyboardInterrupt()
973
Jon Salz0697cbf2012-07-04 15:14:04 +0800974 def init(self, args=None, env=None):
975 '''Initializes Goofy.
976
977 Args:
978 args: A list of command-line arguments. Uses sys.argv if
979 args is None.
980 env: An Environment instance to use (or None to choose
981 FakeChrootEnvironment or DUTEnvironment as appropriate).
982 '''
Jon Salz77c151e2012-08-28 07:20:37 +0800983 signal.signal(signal.SIGINT, self.handle_sigint)
984
Jon Salz0697cbf2012-07-04 15:14:04 +0800985 parser = OptionParser()
986 parser.add_option('-v', '--verbose', dest='verbose',
Jon Salz8fa8e832012-07-13 19:04:09 +0800987 action='store_true',
988 help='Enable debug logging')
Jon Salz0697cbf2012-07-04 15:14:04 +0800989 parser.add_option('--print_test_list', dest='print_test_list',
Jon Salz8fa8e832012-07-13 19:04:09 +0800990 metavar='FILE',
991 help='Read and print test list FILE, and exit')
Jon Salz0697cbf2012-07-04 15:14:04 +0800992 parser.add_option('--restart', dest='restart',
Jon Salz8fa8e832012-07-13 19:04:09 +0800993 action='store_true',
994 help='Clear all test state')
Jon Salz0697cbf2012-07-04 15:14:04 +0800995 parser.add_option('--ui', dest='ui', type='choice',
Jon Salz8fa8e832012-07-13 19:04:09 +0800996 choices=['none', 'gtk', 'chrome'],
997 default=('chrome' if utils.in_chroot() else 'gtk'),
998 help='UI to use')
Jon Salz0697cbf2012-07-04 15:14:04 +0800999 parser.add_option('--ui_scale_factor', dest='ui_scale_factor',
Jon Salz8fa8e832012-07-13 19:04:09 +08001000 type='int', default=1,
1001 help=('Factor by which to scale UI '
1002 '(Chrome UI only)'))
Jon Salz0697cbf2012-07-04 15:14:04 +08001003 parser.add_option('--test_list', dest='test_list',
Jon Salz8fa8e832012-07-13 19:04:09 +08001004 metavar='FILE',
1005 help='Use FILE as test list')
Jon Salzc79a9982012-08-30 04:42:01 +08001006 parser.add_option('--dummy_shopfloor', action='store_true',
1007 help='Use a dummy shopfloor server')
chungyiafe8f772012-08-15 19:36:29 +08001008 parser.add_option('--automation', dest='automation',
1009 action='store_true',
1010 help='Enable automation on running factory test')
Jon Salz0697cbf2012-07-04 15:14:04 +08001011 (self.options, self.args) = parser.parse_args(args)
1012
Jon Salz46b89562012-07-05 11:49:22 +08001013 # Make sure factory directories exist.
1014 factory.get_log_root()
1015 factory.get_state_root()
1016 factory.get_test_data_root()
1017
Jon Salz0697cbf2012-07-04 15:14:04 +08001018 global _inited_logging # pylint: disable=W0603
1019 if not _inited_logging:
1020 factory.init_logging('goofy', verbose=self.options.verbose)
1021 _inited_logging = True
Jon Salz8fa8e832012-07-13 19:04:09 +08001022
Jon Salz0f996602012-10-03 15:26:48 +08001023 if self.options.print_test_list:
1024 print factory.read_test_list(
1025 self.options.print_test_list).__repr__(recursive=True)
1026 sys.exit(0)
1027
Jon Salzee85d522012-07-17 14:34:46 +08001028 event_log.IncrementBootSequence()
Jon Salz0697cbf2012-07-04 15:14:04 +08001029 self.event_log = EventLog('goofy')
1030
1031 if (not suppress_chroot_warning and
1032 factory.in_chroot() and
1033 self.options.ui == 'gtk' and
1034 os.environ.get('DISPLAY') in [None, '', ':0', ':0.0']):
1035 # That's not going to work! Tell the user how to run
1036 # this way.
1037 logging.warn(GOOFY_IN_CHROOT_WARNING)
1038 time.sleep(1)
1039
1040 if env:
1041 self.env = env
1042 elif factory.in_chroot():
1043 self.env = test_environment.FakeChrootEnvironment()
1044 logging.warn(
1045 'Using chroot environment: will not actually run autotests')
1046 else:
1047 self.env = test_environment.DUTEnvironment()
1048 self.env.goofy = self
1049
1050 if self.options.restart:
1051 state.clear_state()
1052
Jon Salz0697cbf2012-07-04 15:14:04 +08001053 if self.options.ui_scale_factor != 1 and utils.in_qemu():
1054 logging.warn(
1055 'In QEMU; ignoring ui_scale_factor argument')
1056 self.options.ui_scale_factor = 1
1057
1058 logging.info('Started')
1059
1060 self.start_state_server()
1061 self.state_instance.set_shared_data('hwid_cfg', get_hwid_cfg())
1062 self.state_instance.set_shared_data('ui_scale_factor',
1063 self.options.ui_scale_factor)
1064 self.last_shutdown_time = (
1065 self.state_instance.get_shared_data('shutdown_time', optional=True))
1066 self.state_instance.del_shared_data('shutdown_time', optional=True)
1067
1068 if not self.options.test_list:
1069 self.options.test_list = find_test_list()
1070 if not self.options.test_list:
1071 logging.error('No test list. Aborting.')
1072 sys.exit(1)
1073 logging.info('Using test list %s', self.options.test_list)
1074
1075 self.test_list = factory.read_test_list(
1076 self.options.test_list,
Jon Salzeb42f0d2012-07-27 19:14:04 +08001077 self.state_instance)
Jon Salz0697cbf2012-07-04 15:14:04 +08001078 if not self.state_instance.has_shared_data('ui_lang'):
1079 self.state_instance.set_shared_data('ui_lang',
1080 self.test_list.options.ui_lang)
1081 self.state_instance.set_shared_data(
1082 'test_list_options',
1083 self.test_list.options.__dict__)
1084 self.state_instance.test_list = self.test_list
1085
Jon Salz83ef34b2012-11-01 19:46:35 +08001086 if not utils.in_chroot() and self.test_list.options.disable_log_rotation:
1087 open('/var/lib/cleanup_logs_paused', 'w').close()
1088
Jon Salz23926422012-09-01 03:38:13 +08001089 if self.options.dummy_shopfloor:
1090 os.environ[shopfloor.SHOPFLOOR_SERVER_ENV_VAR_NAME] = (
1091 'http://localhost:%d/' % shopfloor.DEFAULT_SERVER_PORT)
1092 self.dummy_shopfloor = Spawn(
1093 [os.path.join(factory.FACTORY_PATH, 'bin', 'shopfloor_server'),
1094 '--dummy'])
1095 elif self.test_list.options.shopfloor_server_url:
1096 shopfloor.set_server_url(self.test_list.options.shopfloor_server_url)
1097
Jon Salz0f996602012-10-03 15:26:48 +08001098 if self.test_list.options.time_sanitizer and not utils.in_chroot():
Jon Salz8fa8e832012-07-13 19:04:09 +08001099 self.time_sanitizer = time_sanitizer.TimeSanitizer(
1100 base_time=time_sanitizer.GetBaseTimeFromFile(
1101 # lsb-factory is written by the factory install shim during
1102 # installation, so it should have a good time obtained from
Jon Salz54882d02012-08-31 01:57:54 +08001103 # the mini-Omaha server. If it's not available, we'll use
1104 # /etc/lsb-factory (which will be much older, but reasonably
1105 # sane) and rely on a shopfloor sync to set a more accurate
1106 # time.
1107 '/usr/local/etc/lsb-factory',
1108 '/etc/lsb-release'))
Jon Salz8fa8e832012-07-13 19:04:09 +08001109 self.time_sanitizer.RunOnce()
1110
Jon Salz0697cbf2012-07-04 15:14:04 +08001111 self.init_states()
1112 self.start_event_server()
1113 self.connection_manager = self.env.create_connection_manager(
Tai-Hsu Lin371351a2012-08-27 14:17:14 +08001114 self.test_list.options.wlans,
1115 self.test_list.options.scan_wifi_period_secs)
Jon Salz0697cbf2012-07-04 15:14:04 +08001116 # Note that we create a log watcher even if
1117 # sync_event_log_period_secs isn't set (no background
1118 # syncing), since we may use it to flush event logs as well.
1119 self.log_watcher = EventLogWatcher(
1120 self.test_list.options.sync_event_log_period_secs,
Jon Salz16d10542012-07-23 12:18:45 +08001121 handle_event_logs_callback=self.handle_event_logs)
Jon Salz0697cbf2012-07-04 15:14:04 +08001122 if self.test_list.options.sync_event_log_period_secs:
1123 self.log_watcher.StartWatchThread()
1124
1125 self.update_system_info()
1126
Vic Yang4953fc12012-07-26 16:19:53 +08001127 assert ((self.test_list.options.min_charge_pct is None) ==
1128 (self.test_list.options.max_charge_pct is None))
Jon Salzad7353b2012-10-15 16:22:46 +08001129 if self.test_list.options.min_charge_pct is not None:
Vic Yang4953fc12012-07-26 16:19:53 +08001130 self.charge_manager = ChargeManager(self.test_list.options.min_charge_pct,
1131 self.test_list.options.max_charge_pct)
Jon Salzad7353b2012-10-15 16:22:46 +08001132 system.SystemStatus.charge_manager = self.charge_manager
Vic Yang4953fc12012-07-26 16:19:53 +08001133
Jon Salz0697cbf2012-07-04 15:14:04 +08001134 os.environ['CROS_FACTORY'] = '1'
1135 os.environ['CROS_DISABLE_SITE_SYSINFO'] = '1'
1136
1137 # Set CROS_UI since some behaviors in ui.py depend on the
1138 # particular UI in use. TODO(jsalz): Remove this (and all
1139 # places it is used) when the GTK UI is removed.
1140 os.environ['CROS_UI'] = self.options.ui
1141
1142 if self.options.ui == 'chrome':
1143 self.env.launch_chrome()
1144 logging.info('Waiting for a web socket connection')
1145 self.web_socket_manager.wait()
1146
1147 # Wait for the test widget size to be set; this is done in
1148 # an asynchronous RPC so there is a small chance that the
1149 # web socket might be opened first.
1150 for _ in range(100): # 10 s
1151 try:
1152 if self.state_instance.get_shared_data('test_widget_size'):
1153 break
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001154 except KeyError:
Jon Salz0697cbf2012-07-04 15:14:04 +08001155 pass # Retry
1156 time.sleep(0.1) # 100 ms
1157 else:
1158 logging.warn('Never received test_widget_size from UI')
1159 elif self.options.ui == 'gtk':
1160 self.start_ui()
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001161
Ricky Liang650f6bf2012-09-28 13:22:54 +08001162 # Create download path for autotest beforehand or autotests run at
1163 # the same time might fail due to race condition.
1164 if not factory.in_chroot():
1165 utils.TryMakeDirs(os.path.join('/usr/local/autotest', 'tests',
1166 'download'))
1167
Jon Salz0697cbf2012-07-04 15:14:04 +08001168 def state_change_callback(test, test_state):
1169 self.event_client.post_event(
1170 Event(Event.Type.STATE_CHANGE,
1171 path=test.path, state=test_state))
1172 self.test_list.state_change_callback = state_change_callback
Jon Salz73e0fd02012-04-04 11:46:38 +08001173
Jon Salza6711d72012-07-18 14:33:03 +08001174 for handler in self.on_ui_startup:
1175 handler()
1176
1177 self.prespawner = Prespawner()
1178 self.prespawner.start()
1179
Jon Salz0697cbf2012-07-04 15:14:04 +08001180 try:
1181 tests_after_shutdown = self.state_instance.get_shared_data(
1182 'tests_after_shutdown')
1183 except KeyError:
1184 tests_after_shutdown = None
Jon Salz57717ca2012-04-04 16:47:25 +08001185
Jon Salz5c344f62012-07-13 14:31:16 +08001186 force_auto_run = (tests_after_shutdown == FORCE_AUTO_RUN)
1187 if not force_auto_run and tests_after_shutdown is not None:
Jon Salz0697cbf2012-07-04 15:14:04 +08001188 logging.info('Resuming tests after shutdown: %s',
1189 tests_after_shutdown)
Jon Salz0697cbf2012-07-04 15:14:04 +08001190 self.tests_to_run.extend(
1191 self.test_list.lookup_path(t) for t in tests_after_shutdown)
1192 self.run_queue.put(self.run_next_test)
1193 else:
Jon Salz5c344f62012-07-13 14:31:16 +08001194 if force_auto_run or self.test_list.options.auto_run_on_start:
Jon Salz0697cbf2012-07-04 15:14:04 +08001195 self.run_queue.put(
1196 lambda: self.run_tests(self.test_list, untested_only=True))
Jon Salz5c344f62012-07-13 14:31:16 +08001197 self.state_instance.set_shared_data('tests_after_shutdown', None)
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001198
Jon Salz0697cbf2012-07-04 15:14:04 +08001199 def run(self):
1200 '''Runs Goofy.'''
1201 # Process events forever.
1202 while self.run_once(True):
1203 pass
Jon Salz73e0fd02012-04-04 11:46:38 +08001204
Jon Salz0697cbf2012-07-04 15:14:04 +08001205 def run_once(self, block=False):
1206 '''Runs all items pending in the event loop.
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001207
Jon Salz0697cbf2012-07-04 15:14:04 +08001208 Args:
1209 block: If true, block until at least one event is processed.
Jon Salz7c15e8b2012-06-19 17:10:37 +08001210
Jon Salz0697cbf2012-07-04 15:14:04 +08001211 Returns:
1212 True to keep going or False to shut down.
1213 '''
1214 events = utils.DrainQueue(self.run_queue)
cychiang21886742012-07-05 15:16:32 +08001215 while not events:
Jon Salz0697cbf2012-07-04 15:14:04 +08001216 # Nothing on the run queue.
1217 self._run_queue_idle()
1218 if block:
1219 # Block for at least one event...
cychiang21886742012-07-05 15:16:32 +08001220 try:
1221 events.append(self.run_queue.get(timeout=RUN_QUEUE_TIMEOUT_SECS))
1222 except Queue.Empty:
1223 # Keep going (calling _run_queue_idle() again at the top of
1224 # the loop)
1225 continue
Jon Salz0697cbf2012-07-04 15:14:04 +08001226 # ...and grab anything else that showed up at the same
1227 # time.
1228 events.extend(utils.DrainQueue(self.run_queue))
cychiang21886742012-07-05 15:16:32 +08001229 else:
1230 break
Jon Salz51528e12012-07-02 18:54:45 +08001231
Jon Salz0697cbf2012-07-04 15:14:04 +08001232 for event in events:
1233 if not event:
1234 # Shutdown request.
1235 self.run_queue.task_done()
1236 return False
Jon Salz51528e12012-07-02 18:54:45 +08001237
Jon Salz0697cbf2012-07-04 15:14:04 +08001238 try:
1239 event()
Jon Salz85a39882012-07-05 16:45:04 +08001240 except: # pylint: disable=W0702
1241 logging.exception('Error in event loop')
Jon Salz0697cbf2012-07-04 15:14:04 +08001242 self.record_exception(traceback.format_exception_only(
1243 *sys.exc_info()[:2]))
1244 # But keep going
1245 finally:
1246 self.run_queue.task_done()
1247 return True
Jon Salz0405ab52012-03-16 15:26:52 +08001248
Jon Salz0e6532d2012-10-25 16:30:11 +08001249 def _should_sync_time(self, foreground=False):
1250 '''Returns True if we should attempt syncing time with shopfloor.
1251
1252 Args:
1253 foreground: If True, synchronizes even if background syncing
1254 is disabled (e.g., in explicit sync requests from the
1255 SyncShopfloor test).
1256 '''
1257 return ((foreground or
1258 self.test_list.options.sync_time_period_secs) and
Jon Salz54882d02012-08-31 01:57:54 +08001259 self.time_sanitizer and
1260 (not self.time_synced) and
1261 (not factory.in_chroot()))
1262
Jon Salz0e6532d2012-10-25 16:30:11 +08001263 def sync_time_with_shopfloor_server(self, foreground=False):
Jon Salz54882d02012-08-31 01:57:54 +08001264 '''Syncs time with shopfloor server, if not yet synced.
1265
Jon Salz0e6532d2012-10-25 16:30:11 +08001266 Args:
1267 foreground: If True, synchronizes even if background syncing
1268 is disabled (e.g., in explicit sync requests from the
1269 SyncShopfloor test).
1270
Jon Salz54882d02012-08-31 01:57:54 +08001271 Returns:
1272 False if no time sanitizer is available, or True if this sync (or a
1273 previous sync) succeeded.
1274
1275 Raises:
1276 Exception if unable to contact the shopfloor server.
1277 '''
Jon Salz0e6532d2012-10-25 16:30:11 +08001278 if self._should_sync_time(foreground):
Jon Salz54882d02012-08-31 01:57:54 +08001279 self.time_sanitizer.SyncWithShopfloor()
1280 self.time_synced = True
1281 return self.time_synced
1282
Jon Salzb92c5112012-09-21 15:40:11 +08001283 def log_disk_space_stats(self):
1284 if not self.test_list.options.log_disk_space_period_secs:
1285 return
1286
1287 now = time.time()
1288 if (self.last_log_disk_space_time and
1289 now - self.last_log_disk_space_time <
1290 self.test_list.options.log_disk_space_period_secs):
1291 return
1292 self.last_log_disk_space_time = now
1293
1294 try:
1295 logging.info(disk_space.FormatSpaceUsedAll())
1296 except: # pylint: disable=W0702
1297 logging.exception('Unable to get disk space used')
1298
Jon Salz8fa8e832012-07-13 19:04:09 +08001299 def sync_time_in_background(self):
Jon Salzb22d1172012-08-06 10:38:57 +08001300 '''Writes out current time and tries to sync with shopfloor server.'''
1301 if not self.time_sanitizer:
1302 return
1303
1304 # Write out the current time.
1305 self.time_sanitizer.SaveTime()
1306
Jon Salz54882d02012-08-31 01:57:54 +08001307 if not self._should_sync_time():
Jon Salz8fa8e832012-07-13 19:04:09 +08001308 return
1309
1310 now = time.time()
1311 if self.last_sync_time and (
1312 now - self.last_sync_time <
1313 self.test_list.options.sync_time_period_secs):
1314 # Not yet time for another check.
1315 return
1316 self.last_sync_time = now
1317
1318 def target():
1319 try:
Jon Salz54882d02012-08-31 01:57:54 +08001320 self.sync_time_with_shopfloor_server()
Jon Salz8fa8e832012-07-13 19:04:09 +08001321 except: # pylint: disable=W0702
1322 # Oh well. Log an error (but no trace)
1323 logging.info(
1324 'Unable to get time from shopfloor server: %s',
1325 utils.FormatExceptionOnly())
1326
1327 thread = threading.Thread(target=target)
1328 thread.daemon = True
1329 thread.start()
1330
Jon Salz0697cbf2012-07-04 15:14:04 +08001331 def _run_queue_idle(self):
Vic Yang4953fc12012-07-26 16:19:53 +08001332 '''Invoked when the run queue has no events.
1333
1334 This method must not raise exception.
1335 '''
Jon Salzb22d1172012-08-06 10:38:57 +08001336 now = time.time()
1337 if (self.last_idle and
1338 now < (self.last_idle + RUN_QUEUE_TIMEOUT_SECS - 1)):
1339 # Don't run more often than once every (RUN_QUEUE_TIMEOUT_SECS -
1340 # 1) seconds.
1341 return
1342
1343 self.last_idle = now
1344
Vic Yang311ddb82012-09-26 12:08:28 +08001345 self.check_exclusive()
cychiang21886742012-07-05 15:16:32 +08001346 self.check_for_updates()
Jon Salz8fa8e832012-07-13 19:04:09 +08001347 self.sync_time_in_background()
Jon Salzb92c5112012-09-21 15:40:11 +08001348 self.log_disk_space_stats()
Jon Salz57717ca2012-04-04 16:47:25 +08001349
Jon Salz16d10542012-07-23 12:18:45 +08001350 def handle_event_logs(self, log_name, chunk):
Jon Salz0697cbf2012-07-04 15:14:04 +08001351 '''Callback for event watcher.
Jon Salz258a40c2012-04-19 12:34:01 +08001352
Jon Salz0697cbf2012-07-04 15:14:04 +08001353 Attempts to upload the event logs to the shopfloor server.
1354 '''
1355 description = 'event logs (%s, %d bytes)' % (log_name, len(chunk))
1356 start_time = time.time()
Jon Salz0697cbf2012-07-04 15:14:04 +08001357 shopfloor_client = shopfloor.get_instance(
1358 detect=True,
1359 timeout=self.test_list.options.shopfloor_timeout_secs)
Jon Salzb10cf512012-08-09 17:29:21 +08001360 shopfloor_client.UploadEvent(log_name, Binary(chunk))
Jon Salz0697cbf2012-07-04 15:14:04 +08001361 logging.info(
1362 'Successfully synced %s in %.03f s',
1363 description, time.time() - start_time)
Jon Salz57717ca2012-04-04 16:47:25 +08001364
Jon Salz0697cbf2012-07-04 15:14:04 +08001365 def run_tests_with_status(self, statuses_to_run, starting_at=None,
1366 root=None):
1367 '''Runs all top-level tests with a particular status.
Jon Salz0405ab52012-03-16 15:26:52 +08001368
Jon Salz0697cbf2012-07-04 15:14:04 +08001369 All active tests, plus any tests to re-run, are reset.
Jon Salz57717ca2012-04-04 16:47:25 +08001370
Jon Salz0697cbf2012-07-04 15:14:04 +08001371 Args:
1372 starting_at: If provided, only auto-runs tests beginning with
1373 this test.
1374 '''
1375 root = root or self.test_list
Jon Salz57717ca2012-04-04 16:47:25 +08001376
Jon Salz0697cbf2012-07-04 15:14:04 +08001377 if starting_at:
1378 # Make sure they passed a test, not a string.
1379 assert isinstance(starting_at, factory.FactoryTest)
Jon Salz0405ab52012-03-16 15:26:52 +08001380
Jon Salz0697cbf2012-07-04 15:14:04 +08001381 tests_to_reset = []
1382 tests_to_run = []
Jon Salz0405ab52012-03-16 15:26:52 +08001383
Jon Salz0697cbf2012-07-04 15:14:04 +08001384 found_starting_at = False
Jon Salz0405ab52012-03-16 15:26:52 +08001385
Jon Salz0697cbf2012-07-04 15:14:04 +08001386 for test in root.get_top_level_tests():
1387 if starting_at:
1388 if test == starting_at:
1389 # We've found starting_at; do auto-run on all
1390 # subsequent tests.
1391 found_starting_at = True
1392 if not found_starting_at:
1393 # Don't start this guy yet
1394 continue
Jon Salz0405ab52012-03-16 15:26:52 +08001395
Jon Salz0697cbf2012-07-04 15:14:04 +08001396 status = test.get_state().status
1397 if status == TestState.ACTIVE or status in statuses_to_run:
1398 # Reset the test (later; we will need to abort
1399 # all active tests first).
1400 tests_to_reset.append(test)
1401 if status in statuses_to_run:
1402 tests_to_run.append(test)
Jon Salz0405ab52012-03-16 15:26:52 +08001403
Jon Salz0697cbf2012-07-04 15:14:04 +08001404 self.abort_active_tests()
Jon Salz258a40c2012-04-19 12:34:01 +08001405
Jon Salz0697cbf2012-07-04 15:14:04 +08001406 # Reset all statuses of the tests to run (in case any tests were active;
1407 # we want them to be run again).
1408 for test_to_reset in tests_to_reset:
1409 for test in test_to_reset.walk():
1410 test.update_state(status=TestState.UNTESTED)
Jon Salz57717ca2012-04-04 16:47:25 +08001411
Jon Salz0697cbf2012-07-04 15:14:04 +08001412 self.run_tests(tests_to_run, untested_only=True)
Jon Salz0405ab52012-03-16 15:26:52 +08001413
Jon Salz0697cbf2012-07-04 15:14:04 +08001414 def restart_tests(self, root=None):
1415 '''Restarts all tests.'''
1416 root = root or self.test_list
Jon Salz0405ab52012-03-16 15:26:52 +08001417
Jon Salz0697cbf2012-07-04 15:14:04 +08001418 self.abort_active_tests()
1419 for test in root.walk():
1420 test.update_state(status=TestState.UNTESTED)
1421 self.run_tests(root)
Hung-Te Lin96632362012-03-20 21:14:18 +08001422
Jon Salz0697cbf2012-07-04 15:14:04 +08001423 def auto_run(self, starting_at=None, root=None):
1424 '''"Auto-runs" tests that have not been run yet.
Hung-Te Lin96632362012-03-20 21:14:18 +08001425
Jon Salz0697cbf2012-07-04 15:14:04 +08001426 Args:
1427 starting_at: If provide, only auto-runs tests beginning with
1428 this test.
1429 '''
1430 root = root or self.test_list
1431 self.run_tests_with_status([TestState.UNTESTED, TestState.ACTIVE],
1432 starting_at=starting_at,
1433 root=root)
Jon Salz968e90b2012-03-18 16:12:43 +08001434
Jon Salz0697cbf2012-07-04 15:14:04 +08001435 def re_run_failed(self, root=None):
1436 '''Re-runs failed tests.'''
1437 root = root or self.test_list
1438 self.run_tests_with_status([TestState.FAILED], root=root)
Jon Salz57717ca2012-04-04 16:47:25 +08001439
Jon Salz0697cbf2012-07-04 15:14:04 +08001440 def show_review_information(self):
1441 '''Event handler for showing review information screen.
Jon Salz57717ca2012-04-04 16:47:25 +08001442
Jon Salz0697cbf2012-07-04 15:14:04 +08001443 The information screene is rendered by main UI program (ui.py), so in
1444 goofy we only need to kill all active tests, set them as untested, and
1445 clear remaining tests.
1446 '''
1447 self.kill_active_tests(False)
Jon Salza6711d72012-07-18 14:33:03 +08001448 self.cancel_pending_tests()
Jon Salz57717ca2012-04-04 16:47:25 +08001449
Jon Salz0697cbf2012-07-04 15:14:04 +08001450 def handle_switch_test(self, event):
1451 '''Switches to a particular test.
Jon Salz0405ab52012-03-16 15:26:52 +08001452
Jon Salz0697cbf2012-07-04 15:14:04 +08001453 @param event: The SWITCH_TEST event.
1454 '''
1455 test = self.test_list.lookup_path(event.path)
1456 if not test:
1457 logging.error('Unknown test %r', event.key)
1458 return
Jon Salz73e0fd02012-04-04 11:46:38 +08001459
Jon Salz0697cbf2012-07-04 15:14:04 +08001460 invoc = self.invocations.get(test)
1461 if invoc and test.backgroundable:
1462 # Already running: just bring to the front if it
1463 # has a UI.
1464 logging.info('Setting visible test to %s', test.path)
Jon Salz36fbbb52012-07-05 13:45:06 +08001465 self.set_visible_test(test)
Jon Salz0697cbf2012-07-04 15:14:04 +08001466 return
Jon Salz73e0fd02012-04-04 11:46:38 +08001467
Jon Salz0697cbf2012-07-04 15:14:04 +08001468 self.abort_active_tests()
1469 for t in test.walk():
1470 t.update_state(status=TestState.UNTESTED)
Jon Salz73e0fd02012-04-04 11:46:38 +08001471
Jon Salz0697cbf2012-07-04 15:14:04 +08001472 if self.test_list.options.auto_run_on_keypress:
1473 self.auto_run(starting_at=test)
1474 else:
1475 self.run_tests(test)
Jon Salz73e0fd02012-04-04 11:46:38 +08001476
Jon Salz0697cbf2012-07-04 15:14:04 +08001477 def wait(self):
1478 '''Waits for all pending invocations.
1479
1480 Useful for testing.
1481 '''
Jon Salz1acc8742012-07-17 17:45:55 +08001482 while self.invocations:
1483 for k, v in self.invocations.iteritems():
1484 logging.info('Waiting for %s to complete...', k)
1485 v.thread.join()
1486 self.reap_completed_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +08001487
1488 def check_exceptions(self):
1489 '''Raises an error if any exceptions have occurred in
1490 invocation threads.'''
1491 if self.exceptions:
1492 raise RuntimeError('Exception in invocation thread: %r' %
1493 self.exceptions)
1494
1495 def record_exception(self, msg):
1496 '''Records an exception in an invocation thread.
1497
1498 An exception with the given message will be rethrown when
1499 Goofy is destroyed.'''
1500 self.exceptions.append(msg)
Jon Salz73e0fd02012-04-04 11:46:38 +08001501
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001502
1503if __name__ == '__main__':
Jon Salz77c151e2012-08-28 07:20:37 +08001504 goofy = Goofy()
1505 try:
1506 goofy.main()
Jon Salz0f996602012-10-03 15:26:48 +08001507 except SystemExit:
1508 # Propagate SystemExit without logging.
1509 raise
Jon Salz31373eb2012-09-21 16:19:49 +08001510 except:
Jon Salz0f996602012-10-03 15:26:48 +08001511 # Log the error before trying to shut down (unless it's a graceful
1512 # exit).
Jon Salz31373eb2012-09-21 16:19:49 +08001513 logging.exception('Error in main loop')
1514 raise
Jon Salz77c151e2012-08-28 07:20:37 +08001515 finally:
1516 goofy.destroy()