blob: 5a4884bd3ce425a66358842b35cdd216f98ec4f2 [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
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +080028from cros.factory.event_log import EventLog, FloatDigit
Tom Wai-Hong Tamd33723e2013-04-10 21:14:37 +080029from cros.factory.event_log_watcher import EventLogWatcher
jcliangcd688182012-08-20 21:01:26 +080030from cros.factory.goofy import test_environment
31from cros.factory.goofy import time_sanitizer
Jon Salz83591782012-06-26 11:09:58 +080032from cros.factory.goofy import updater
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
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +080036from cros.factory.goofy.system_log_manager import SystemLogManager
jcliangcd688182012-08-20 21:01:26 +080037from cros.factory.goofy.web_socket_manager import WebSocketManager
Cheng-Yi Chiangd8186952013-04-04 23:41:14 +080038from cros.factory.system.board import Board, BoardException
jcliangcd688182012-08-20 21:01:26 +080039from cros.factory.system.charge_manager import ChargeManager
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +080040from cros.factory.system.core_dump_manager import CoreDumpManager
Jon Salzce6a7f82013-06-10 18:22:54 +080041from cros.factory.system.cpufreq_manager import CpufreqManager
Jon Salzb92c5112012-09-21 15:40:11 +080042from cros.factory.system import disk_space
jcliangcd688182012-08-20 21:01:26 +080043from cros.factory.test import factory
44from cros.factory.test import state
Jon Salz51528e12012-07-02 18:54:45 +080045from cros.factory.test import shopfloor
Jon Salz83591782012-06-26 11:09:58 +080046from cros.factory.test import utils
47from cros.factory.test.event import Event
48from cros.factory.test.event import EventClient
49from cros.factory.test.event import EventServer
jcliangcd688182012-08-20 21:01:26 +080050from cros.factory.test.factory import TestState
Dean Liao592e4d52013-01-10 20:06:39 +080051from cros.factory.tools.key_filter import KeyFilter
Jon Salz78c32392012-07-25 14:18:29 +080052from cros.factory.utils.process_utils import Spawn
Hung-Te Linf2f78f72012-02-08 19:27:11 +080053
54
Jon Salz2f757d42012-06-27 17:06:42 +080055CUSTOM_DIR = os.path.join(factory.FACTORY_PATH, 'custom')
Hung-Te Linf2f78f72012-02-08 19:27:11 +080056HWID_CFG_PATH = '/usr/local/share/chromeos-hwid/cfg'
Chun-ta Lin279e7e92013-02-19 17:40:39 +080057CACHES_DIR = os.path.join(factory.get_state_root(), "caches")
Hung-Te Linf2f78f72012-02-08 19:27:11 +080058
Jon Salz8796e362012-05-24 11:39:09 +080059# File that suppresses reboot if present (e.g., for development).
60NO_REBOOT_FILE = '/var/log/factory.noreboot'
61
Jon Salz5c344f62012-07-13 14:31:16 +080062# Value for tests_after_shutdown that forces auto-run (e.g., after
63# a factory update, when the available set of tests might change).
64FORCE_AUTO_RUN = 'force_auto_run'
65
cychiang21886742012-07-05 15:16:32 +080066RUN_QUEUE_TIMEOUT_SECS = 10
67
Justin Chuang83813982013-05-13 01:26:32 +080068# Sync disks when battery level is higher than this value.
69# Otherwise, power loss during disk sync operation may incur even worse outcome.
70MIN_BATTERY_LEVEL_FOR_DISK_SYNC = 1.0
71
Jon Salz758e6cc2012-04-03 15:47:07 +080072GOOFY_IN_CHROOT_WARNING = '\n' + ('*' * 70) + '''
73You are running Goofy inside the chroot. Autotests are not supported.
74
75To use Goofy in the chroot, first install an Xvnc server:
76
Jon Salz0697cbf2012-07-04 15:14:04 +080077 sudo apt-get install tightvncserver
Jon Salz758e6cc2012-04-03 15:47:07 +080078
79...and then start a VNC X server outside the chroot:
80
Jon Salz0697cbf2012-07-04 15:14:04 +080081 vncserver :10 &
82 vncviewer :10
Jon Salz758e6cc2012-04-03 15:47:07 +080083
84...and run Goofy as follows:
85
Jon Salz0697cbf2012-07-04 15:14:04 +080086 env --unset=XAUTHORITY DISPLAY=localhost:10 python goofy.py
Jon Salz758e6cc2012-04-03 15:47:07 +080087''' + ('*' * 70)
Jon Salz73e0fd02012-04-04 11:46:38 +080088suppress_chroot_warning = False
Hung-Te Linf2f78f72012-02-08 19:27:11 +080089
90def get_hwid_cfg():
Jon Salz0697cbf2012-07-04 15:14:04 +080091 '''
92 Returns the HWID config tag, or an empty string if none can be found.
93 '''
94 if 'CROS_HWID' in os.environ:
95 return os.environ['CROS_HWID']
96 if os.path.exists(HWID_CFG_PATH):
97 with open(HWID_CFG_PATH, 'rt') as hwid_cfg_handle:
98 return hwid_cfg_handle.read().strip()
99 return ''
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800100
101
102def find_test_list():
Jon Salz0697cbf2012-07-04 15:14:04 +0800103 '''
104 Returns the path to the active test list, based on the HWID config tag.
Jon Salzfb615892013-02-01 18:04:35 +0800105
106 The algorithm is:
107
108 - Try $FACTORY/test_lists/active (the symlink reflecting the option chosen
109 in the UI).
110 - For each of $FACTORY/custom, $FACTORY/test_lists (and
111 autotest/site_tests/suite_Factory for backward compatibility):
112 - Try test_list_${hwid_cfg} (if hwid_cfg is set)
113 - Try test_list
114 - Try test_list.generic
Jon Salz0697cbf2012-07-04 15:14:04 +0800115 '''
Jon Salzfb615892013-02-01 18:04:35 +0800116 # If the 'active' symlink is present, that trumps everything else.
117 if os.path.lexists(factory.ACTIVE_TEST_LIST_SYMLINK):
118 return os.path.realpath(factory.ACTIVE_TEST_LIST_SYMLINK)
119
Jon Salz0697cbf2012-07-04 15:14:04 +0800120 hwid_cfg = get_hwid_cfg()
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800121
Jon Salzfb615892013-02-01 18:04:35 +0800122 search_dirs = [CUSTOM_DIR, factory.TEST_LISTS_PATH]
Jon Salz4be56b02012-12-22 07:30:46 +0800123 if not utils.in_chroot():
124 # Also look in suite_Factory. For backward compatibility only;
125 # new boards should just put the test list in the "test_lists"
126 # directory.
127 search_dirs.insert(0, os.path.join(
128 os.path.dirname(factory.FACTORY_PATH),
129 'autotest', 'site_tests', 'suite_Factory'))
Jon Salz2f757d42012-06-27 17:06:42 +0800130
Jon Salzfb615892013-02-01 18:04:35 +0800131
132 search_files = []
Jon Salz0697cbf2012-07-04 15:14:04 +0800133 if hwid_cfg:
Jon Salzfb615892013-02-01 18:04:35 +0800134 search_files += [hwid_cfg]
135 search_files += ['test_list', 'test_list.generic']
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800136
Jon Salz0697cbf2012-07-04 15:14:04 +0800137 for d in search_dirs:
138 for f in search_files:
139 test_list = os.path.join(d, f)
140 if os.path.exists(test_list):
141 return test_list
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800142
Jon Salz0697cbf2012-07-04 15:14:04 +0800143 logging.warn('Cannot find test lists named any of %s in any of %s',
144 search_files, search_dirs)
145 return None
Jon Salz73e0fd02012-04-04 11:46:38 +0800146
Jon Salzfb615892013-02-01 18:04:35 +0800147
Jon Salz73e0fd02012-04-04 11:46:38 +0800148_inited_logging = False
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800149
150class Goofy(object):
Jon Salz0697cbf2012-07-04 15:14:04 +0800151 '''
152 The main factory flow.
153
154 Note that all methods in this class must be invoked from the main
155 (event) thread. Other threads, such as callbacks and TestInvocation
156 methods, should instead post events on the run queue.
157
158 TODO: Unit tests. (chrome-os-partner:7409)
159
160 Properties:
161 uuid: A unique UUID for this invocation of Goofy.
162 state_instance: An instance of FactoryState.
163 state_server: The FactoryState XML/RPC server.
164 state_server_thread: A thread running state_server.
165 event_server: The EventServer socket server.
166 event_server_thread: A thread running event_server.
167 event_client: A client to the event server.
168 connection_manager: The connection_manager object.
Cheng-Yi Chiang835f2682013-05-06 22:15:48 +0800169 system_log_manager: The SystemLogManager object.
170 core_dump_manager: The CoreDumpManager object.
Jon Salz0697cbf2012-07-04 15:14:04 +0800171 ui_process: The factory ui process object.
172 run_queue: A queue of callbacks to invoke from the main thread.
173 invocations: A map from FactoryTest objects to the corresponding
174 TestInvocations objects representing active tests.
175 tests_to_run: A deque of tests that should be run when the current
176 test(s) complete.
177 options: Command-line options.
178 args: Command-line args.
179 test_list: The test list.
180 event_handlers: Map of Event.Type to the method used to handle that
181 event. If the method has an 'event' argument, the event is passed
182 to the handler.
183 exceptions: Exceptions encountered in invocation threads.
Jon Salz3c493bb2013-02-07 17:24:58 +0800184 last_log_disk_space_message: The last message we logged about disk space
185 (to avoid duplication).
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +0800186 last_kick_sync_time: The last time to kick system_log_manager to sync
187 because of core dump files (to avoid kicking too soon then abort the
188 sync.)
Jon Salz416f9cc2013-05-10 18:32:50 +0800189 hooks: A Hooks object containing hooks for various Goofy actions.
Jon Salz0697cbf2012-07-04 15:14:04 +0800190 '''
191 def __init__(self):
192 self.uuid = str(uuid.uuid4())
193 self.state_instance = None
194 self.state_server = None
195 self.state_server_thread = None
Jon Salz16d10542012-07-23 12:18:45 +0800196 self.goofy_rpc = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800197 self.event_server = None
198 self.event_server_thread = None
199 self.event_client = None
200 self.connection_manager = None
Vic Yang4953fc12012-07-26 16:19:53 +0800201 self.charge_manager = None
Jon Salz8fa8e832012-07-13 19:04:09 +0800202 self.time_sanitizer = None
203 self.time_synced = False
Jon Salz0697cbf2012-07-04 15:14:04 +0800204 self.log_watcher = None
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +0800205 self.system_log_manager = None
Cheng-Yi Chiang835f2682013-05-06 22:15:48 +0800206 self.core_dump_manager = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800207 self.event_log = None
208 self.prespawner = None
209 self.ui_process = None
Jon Salzc79a9982012-08-30 04:42:01 +0800210 self.dummy_shopfloor = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800211 self.run_queue = Queue.Queue()
212 self.invocations = {}
213 self.tests_to_run = deque()
214 self.visible_test = None
215 self.chrome = None
Jon Salz416f9cc2013-05-10 18:32:50 +0800216 self.hooks = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800217
218 self.options = None
219 self.args = None
220 self.test_list = None
221 self.on_ui_startup = []
222 self.env = None
Jon Salzb22d1172012-08-06 10:38:57 +0800223 self.last_idle = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800224 self.last_shutdown_time = None
cychiang21886742012-07-05 15:16:32 +0800225 self.last_update_check = None
Jon Salz8fa8e832012-07-13 19:04:09 +0800226 self.last_sync_time = None
Jon Salzb92c5112012-09-21 15:40:11 +0800227 self.last_log_disk_space_time = None
Jon Salz3c493bb2013-02-07 17:24:58 +0800228 self.last_log_disk_space_message = None
Justin Chuang83813982013-05-13 01:26:32 +0800229 self.last_check_battery_time = None
230 self.last_check_battery_message = None
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +0800231 self.last_kick_sync_time = None
Vic Yang311ddb82012-09-26 12:08:28 +0800232 self.exclusive_items = set()
Jon Salz0f996602012-10-03 15:26:48 +0800233 self.event_log = None
Dean Liao592e4d52013-01-10 20:06:39 +0800234 self.key_filter = None
Jon Salzce6a7f82013-06-10 18:22:54 +0800235 self.cpufreq_manager = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800236
Jon Salz85a39882012-07-05 16:45:04 +0800237 def test_or_root(event, parent_or_group=True):
238 '''Returns the test affected by a particular event.
239
240 Args:
241 event: The event containing an optional 'path' attribute.
242 parent_on_group: If True, returns the top-level parent for a test (the
243 root node of the tests that need to be run together if the given test
244 path is to be run).
245 '''
Jon Salz0697cbf2012-07-04 15:14:04 +0800246 try:
247 path = event.path
248 except AttributeError:
249 path = None
250
251 if path:
Jon Salz85a39882012-07-05 16:45:04 +0800252 test = self.test_list.lookup_path(path)
253 if parent_or_group:
254 test = test.get_top_level_parent_or_group()
255 return test
Jon Salz0697cbf2012-07-04 15:14:04 +0800256 else:
257 return self.test_list
258
259 self.event_handlers = {
260 Event.Type.SWITCH_TEST: self.handle_switch_test,
261 Event.Type.SHOW_NEXT_ACTIVE_TEST:
262 lambda event: self.show_next_active_test(),
263 Event.Type.RESTART_TESTS:
264 lambda event: self.restart_tests(root=test_or_root(event)),
265 Event.Type.AUTO_RUN:
266 lambda event: self.auto_run(root=test_or_root(event)),
267 Event.Type.RE_RUN_FAILED:
268 lambda event: self.re_run_failed(root=test_or_root(event)),
269 Event.Type.RUN_TESTS_WITH_STATUS:
270 lambda event: self.run_tests_with_status(
271 event.status,
272 root=test_or_root(event)),
273 Event.Type.REVIEW:
274 lambda event: self.show_review_information(),
275 Event.Type.UPDATE_SYSTEM_INFO:
276 lambda event: self.update_system_info(),
Jon Salz0697cbf2012-07-04 15:14:04 +0800277 Event.Type.STOP:
Jon Salz85a39882012-07-05 16:45:04 +0800278 lambda event: self.stop(root=test_or_root(event, False),
279 fail=getattr(event, 'fail', False)),
Jon Salz36fbbb52012-07-05 13:45:06 +0800280 Event.Type.SET_VISIBLE_TEST:
281 lambda event: self.set_visible_test(
282 self.test_list.lookup_path(event.path)),
Jon Salz4712ac72013-02-07 17:12:05 +0800283 Event.Type.CLEAR_STATE:
284 lambda event: self.clear_state(self.test_list.lookup_path(event.path)),
Jon Salz0697cbf2012-07-04 15:14:04 +0800285 }
286
287 self.exceptions = []
288 self.web_socket_manager = None
289
290 def destroy(self):
291 if self.chrome:
292 self.chrome.kill()
293 self.chrome = None
Jon Salzc79a9982012-08-30 04:42:01 +0800294 if self.dummy_shopfloor:
295 self.dummy_shopfloor.kill()
296 self.dummy_shopfloor = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800297 if self.ui_process:
298 utils.kill_process_tree(self.ui_process, 'ui')
299 self.ui_process = None
300 if self.web_socket_manager:
301 logging.info('Stopping web sockets')
302 self.web_socket_manager.close()
303 self.web_socket_manager = None
304 if self.state_server_thread:
305 logging.info('Stopping state server')
306 self.state_server.shutdown()
307 self.state_server_thread.join()
308 self.state_server.server_close()
309 self.state_server_thread = None
310 if self.state_instance:
311 self.state_instance.close()
312 if self.event_server_thread:
313 logging.info('Stopping event server')
314 self.event_server.shutdown() # pylint: disable=E1101
315 self.event_server_thread.join()
316 self.event_server.server_close()
317 self.event_server_thread = None
318 if self.log_watcher:
319 if self.log_watcher.IsThreadStarted():
320 self.log_watcher.StopWatchThread()
321 self.log_watcher = None
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +0800322 if self.system_log_manager:
323 if self.system_log_manager.IsThreadRunning():
324 self.system_log_manager.StopSyncThread()
325 self.system_log_manager = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800326 if self.prespawner:
327 logging.info('Stopping prespawner')
328 self.prespawner.stop()
329 self.prespawner = None
330 if self.event_client:
331 logging.info('Closing event client')
332 self.event_client.close()
333 self.event_client = None
334 if self.event_log:
335 self.event_log.Close()
336 self.event_log = None
Dean Liao592e4d52013-01-10 20:06:39 +0800337 if self.key_filter:
338 self.key_filter.Stop()
Jon Salzce6a7f82013-06-10 18:22:54 +0800339 if self.cpufreq_manager:
340 self.cpufreq_manager.Stop()
Dean Liao592e4d52013-01-10 20:06:39 +0800341
Jon Salz0697cbf2012-07-04 15:14:04 +0800342 self.check_exceptions()
343 logging.info('Done destroying Goofy')
344
345 def start_state_server(self):
346 self.state_instance, self.state_server = (
347 state.create_server(bind_address='0.0.0.0'))
Jon Salz16d10542012-07-23 12:18:45 +0800348 self.goofy_rpc = GoofyRPC(self)
349 self.goofy_rpc.RegisterMethods(self.state_instance)
Jon Salz0697cbf2012-07-04 15:14:04 +0800350 logging.info('Starting state server')
351 self.state_server_thread = threading.Thread(
352 target=self.state_server.serve_forever,
353 name='StateServer')
354 self.state_server_thread.start()
355
356 def start_event_server(self):
357 self.event_server = EventServer()
358 logging.info('Starting factory event server')
359 self.event_server_thread = threading.Thread(
360 target=self.event_server.serve_forever,
361 name='EventServer') # pylint: disable=E1101
362 self.event_server_thread.start()
363
364 self.event_client = EventClient(
365 callback=self.handle_event, event_loop=self.run_queue)
366
367 self.web_socket_manager = WebSocketManager(self.uuid)
368 self.state_server.add_handler("/event",
369 self.web_socket_manager.handle_web_socket)
370
371 def start_ui(self):
372 ui_proc_args = [
373 os.path.join(factory.FACTORY_PACKAGE_PATH, 'test', 'ui.py'),
374 self.options.test_list]
375 if self.options.verbose:
376 ui_proc_args.append('-v')
377 logging.info('Starting ui %s', ui_proc_args)
Jon Salz78c32392012-07-25 14:18:29 +0800378 self.ui_process = Spawn(ui_proc_args)
Jon Salz0697cbf2012-07-04 15:14:04 +0800379 logging.info('Waiting for UI to come up...')
380 self.event_client.wait(
381 lambda event: event.type == Event.Type.UI_READY)
382 logging.info('UI has started')
383
384 def set_visible_test(self, test):
385 if self.visible_test == test:
386 return
Jon Salz2f2d42c2012-07-30 12:30:34 +0800387 if test and not test.has_ui:
388 return
Jon Salz0697cbf2012-07-04 15:14:04 +0800389
390 if test:
391 test.update_state(visible=True)
392 if self.visible_test:
393 self.visible_test.update_state(visible=False)
394 self.visible_test = test
395
Jon Salzd4306c82012-11-30 15:16:36 +0800396 def _log_startup_messages(self):
397 '''Logs the tail of var/log/messages and mosys and EC console logs.'''
398 # TODO(jsalz): This is mostly a copy-and-paste of code in init_states,
399 # for factory-3004.B only. Consolidate and merge back to ToT.
400 if utils.in_chroot():
401 return
402
403 try:
404 var_log_messages = (
405 utils.var_log_messages_before_reboot())
406 logging.info(
407 'Tail of /var/log/messages before last reboot:\n'
408 '%s', ('\n'.join(
409 ' ' + x for x in var_log_messages)))
410 except: # pylint: disable=W0702
411 logging.exception('Unable to grok /var/log/messages')
412
413 try:
414 mosys_log = utils.Spawn(
415 ['mosys', 'eventlog', 'list'],
416 read_stdout=True, log_stderr_on_error=True).stdout_data
417 logging.info('System eventlog from mosys:\n%s\n', mosys_log)
418 except: # pylint: disable=W0702
419 logging.exception('Unable to read mosys eventlog')
420
421 try:
Vic Yang8341dde2013-01-29 16:48:52 +0800422 board = system.GetBoard()
423 ec_console_log = board.GetECConsoleLog()
Jon Salzd4306c82012-11-30 15:16:36 +0800424 logging.info('EC console log after reboot:\n%s\n', ec_console_log)
425 except: # pylint: disable=W0702
426 logging.exception('Error retrieving EC console log')
427
Jon Salz0697cbf2012-07-04 15:14:04 +0800428 def handle_shutdown_complete(self, test, test_state):
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800429 '''
Jon Salz0697cbf2012-07-04 15:14:04 +0800430 Handles the case where a shutdown was detected during a shutdown step.
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800431
Jon Salz0697cbf2012-07-04 15:14:04 +0800432 @param test: The ShutdownStep.
433 @param test_state: The test state.
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800434 '''
Jon Salz0697cbf2012-07-04 15:14:04 +0800435 test_state = test.update_state(increment_shutdown_count=1)
436 logging.info('Detected shutdown (%d of %d)',
437 test_state.shutdown_count, test.iterations)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800438
Jon Salz0697cbf2012-07-04 15:14:04 +0800439 def log_and_update_state(status, error_msg, **kw):
440 self.event_log.Log('rebooted',
441 status=status, error_msg=error_msg, **kw)
Jon Salzd4306c82012-11-30 15:16:36 +0800442 logging.info('Rebooted: status=%s, %s', status,
443 (('error_msg=%s' % error_msg) if error_msg else None))
Jon Salz0697cbf2012-07-04 15:14:04 +0800444 test.update_state(status=status, error_msg=error_msg)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800445
Jon Salz0697cbf2012-07-04 15:14:04 +0800446 if not self.last_shutdown_time:
447 log_and_update_state(status=TestState.FAILED,
448 error_msg='Unable to read shutdown_time')
449 return
Jon Salz258a40c2012-04-19 12:34:01 +0800450
Jon Salz0697cbf2012-07-04 15:14:04 +0800451 now = time.time()
452 logging.info('%.03f s passed since reboot',
453 now - self.last_shutdown_time)
Jon Salz258a40c2012-04-19 12:34:01 +0800454
Jon Salz0697cbf2012-07-04 15:14:04 +0800455 if self.last_shutdown_time > now:
456 test.update_state(status=TestState.FAILED,
457 error_msg='Time moved backward during reboot')
458 elif (isinstance(test, factory.RebootStep) and
459 self.test_list.options.max_reboot_time_secs and
460 (now - self.last_shutdown_time >
461 self.test_list.options.max_reboot_time_secs)):
462 # A reboot took too long; fail. (We don't check this for
463 # HaltSteps, because the machine could be halted for a
464 # very long time, and even unplugged with battery backup,
465 # thus hosing the clock.)
466 log_and_update_state(
467 status=TestState.FAILED,
468 error_msg=('More than %d s elapsed during reboot '
469 '(%.03f s, from %s to %s)' % (
470 self.test_list.options.max_reboot_time_secs,
471 now - self.last_shutdown_time,
472 utils.TimeString(self.last_shutdown_time),
473 utils.TimeString(now))),
474 duration=(now-self.last_shutdown_time))
Jon Salzd4306c82012-11-30 15:16:36 +0800475 self._log_startup_messages()
Jon Salz0697cbf2012-07-04 15:14:04 +0800476 elif test_state.shutdown_count == test.iterations:
477 # Good!
478 log_and_update_state(status=TestState.PASSED,
479 duration=(now - self.last_shutdown_time),
480 error_msg='')
481 elif test_state.shutdown_count > test.iterations:
482 # Shut down too many times
483 log_and_update_state(status=TestState.FAILED,
484 error_msg='Too many shutdowns')
Jon Salzd4306c82012-11-30 15:16:36 +0800485 self._log_startup_messages()
Jon Salz0697cbf2012-07-04 15:14:04 +0800486 elif utils.are_shift_keys_depressed():
487 logging.info('Shift keys are depressed; cancelling restarts')
488 # Abort shutdown
489 log_and_update_state(
490 status=TestState.FAILED,
491 error_msg='Shutdown aborted with double shift keys')
Jon Salza6711d72012-07-18 14:33:03 +0800492 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +0800493 else:
494 def handler():
495 if self._prompt_cancel_shutdown(
496 test, test_state.shutdown_count + 1):
Jon Salza6711d72012-07-18 14:33:03 +0800497 factory.console.info('Shutdown aborted by operator')
Jon Salz0697cbf2012-07-04 15:14:04 +0800498 log_and_update_state(
499 status=TestState.FAILED,
500 error_msg='Shutdown aborted by operator')
Jon Salza6711d72012-07-18 14:33:03 +0800501 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +0800502 return
Jon Salz0405ab52012-03-16 15:26:52 +0800503
Jon Salz0697cbf2012-07-04 15:14:04 +0800504 # Time to shutdown again
505 log_and_update_state(
506 status=TestState.ACTIVE,
507 error_msg='',
508 iteration=test_state.shutdown_count)
Jon Salz73e0fd02012-04-04 11:46:38 +0800509
Jon Salz0697cbf2012-07-04 15:14:04 +0800510 self.event_log.Log('shutdown', operation='reboot')
511 self.state_instance.set_shared_data('shutdown_time',
512 time.time())
513 self.env.shutdown('reboot')
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800514
Jon Salz0697cbf2012-07-04 15:14:04 +0800515 self.on_ui_startup.append(handler)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800516
Jon Salz0697cbf2012-07-04 15:14:04 +0800517 def _prompt_cancel_shutdown(self, test, iteration):
518 if self.options.ui != 'chrome':
519 return False
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800520
Jon Salz0697cbf2012-07-04 15:14:04 +0800521 pending_shutdown_data = {
522 'delay_secs': test.delay_secs,
523 'time': time.time() + test.delay_secs,
524 'operation': test.operation,
525 'iteration': iteration,
526 'iterations': test.iterations,
527 }
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800528
Jon Salz0697cbf2012-07-04 15:14:04 +0800529 # Create a new (threaded) event client since we
530 # don't want to use the event loop for this.
531 with EventClient() as event_client:
532 event_client.post_event(Event(Event.Type.PENDING_SHUTDOWN,
533 **pending_shutdown_data))
534 aborted = event_client.wait(
535 lambda event: event.type == Event.Type.CANCEL_SHUTDOWN,
536 timeout=test.delay_secs) is not None
537 if aborted:
538 event_client.post_event(Event(Event.Type.PENDING_SHUTDOWN))
539 return aborted
Jon Salz258a40c2012-04-19 12:34:01 +0800540
Jon Salz0697cbf2012-07-04 15:14:04 +0800541 def init_states(self):
542 '''
543 Initializes all states on startup.
544 '''
545 for test in self.test_list.get_all_tests():
546 # Make sure the state server knows about all the tests,
547 # defaulting to an untested state.
548 test.update_state(update_parent=False, visible=False)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800549
Jon Salz0697cbf2012-07-04 15:14:04 +0800550 var_log_messages = None
Vic Yanga9c32212012-08-16 20:07:54 +0800551 mosys_log = None
Vic Yange4c275d2012-08-28 01:50:20 +0800552 ec_console_log = None
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800553
Jon Salz0697cbf2012-07-04 15:14:04 +0800554 # Any 'active' tests should be marked as failed now.
555 for test in self.test_list.walk():
Jon Salza6711d72012-07-18 14:33:03 +0800556 if not test.is_leaf():
557 # Don't bother with parents; they will be updated when their
558 # children are updated.
559 continue
560
Jon Salz0697cbf2012-07-04 15:14:04 +0800561 test_state = test.get_state()
562 if test_state.status != TestState.ACTIVE:
563 continue
564 if isinstance(test, factory.ShutdownStep):
565 # Shutdown while the test was active - that's good.
566 self.handle_shutdown_complete(test, test_state)
567 else:
568 # Unexpected shutdown. Grab /var/log/messages for context.
569 if var_log_messages is None:
570 try:
571 var_log_messages = (
572 utils.var_log_messages_before_reboot())
573 # Write it to the log, to make it easier to
574 # correlate with /var/log/messages.
575 logging.info(
576 'Unexpected shutdown. '
577 'Tail of /var/log/messages before last reboot:\n'
578 '%s', ('\n'.join(
579 ' ' + x for x in var_log_messages)))
580 except: # pylint: disable=W0702
581 logging.exception('Unable to grok /var/log/messages')
582 var_log_messages = []
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800583
Jon Salz008f4ea2012-08-28 05:39:45 +0800584 if mosys_log is None and not utils.in_chroot():
585 try:
586 mosys_log = utils.Spawn(
587 ['mosys', 'eventlog', 'list'],
588 read_stdout=True, log_stderr_on_error=True).stdout_data
589 # Write it to the log also.
590 logging.info('System eventlog from mosys:\n%s\n', mosys_log)
591 except: # pylint: disable=W0702
592 logging.exception('Unable to read mosys eventlog')
Vic Yanga9c32212012-08-16 20:07:54 +0800593
Vic Yange4c275d2012-08-28 01:50:20 +0800594 if ec_console_log is None:
595 try:
Vic Yang8341dde2013-01-29 16:48:52 +0800596 board = system.GetBoard()
597 ec_console_log = board.GetECConsoleLog()
Vic Yange4c275d2012-08-28 01:50:20 +0800598 logging.info('EC console log after reboot:\n%s\n', ec_console_log)
Jon Salzfe1f6652012-09-07 05:40:14 +0800599 except: # pylint: disable=W0702
Vic Yange4c275d2012-08-28 01:50:20 +0800600 logging.exception('Error retrieving EC console log')
601
Jon Salz0697cbf2012-07-04 15:14:04 +0800602 error_msg = 'Unexpected shutdown while test was running'
603 self.event_log.Log('end_test',
604 path=test.path,
605 status=TestState.FAILED,
606 invocation=test.get_state().invocation,
607 error_msg=error_msg,
Vic Yanga9c32212012-08-16 20:07:54 +0800608 var_log_messages='\n'.join(var_log_messages),
609 mosys_log=mosys_log)
Jon Salz0697cbf2012-07-04 15:14:04 +0800610 test.update_state(
611 status=TestState.FAILED,
612 error_msg=error_msg)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800613
Jon Salz50efe942012-07-26 11:54:10 +0800614 if not test.never_fails:
615 # For "never_fails" tests (such as "Start"), don't cancel
616 # pending tests, since reboot is expected.
617 factory.console.info('Unexpected shutdown while test %s '
618 'running; cancelling any pending tests',
619 test.path)
620 self.state_instance.set_shared_data('tests_after_shutdown', [])
Jon Salz69806bb2012-07-20 18:05:02 +0800621
Jon Salz008f4ea2012-08-28 05:39:45 +0800622 self.update_skipped_tests()
623
624 def update_skipped_tests(self):
625 '''
626 Updates skipped states based on run_if.
627 '''
628 for t in self.test_list.walk():
629 if t.is_leaf() and t.run_if_table_name:
630 skip = False
631 try:
632 aux = shopfloor.get_selected_aux_data(t.run_if_table_name)
633 value = aux.get(t.run_if_col)
634 if value is not None:
635 skip = (not value) ^ t.run_if_not
636 except ValueError:
637 # Not available; assume it shouldn't be skipped
638 pass
639
640 test_state = t.get_state()
641 if ((not skip) and
642 (test_state.status == TestState.PASSED) and
643 (test_state.error_msg == TestState.SKIPPED_MSG)):
644 # It was marked as skipped before, but now we need to run it.
645 # Mark as untested.
646 t.update_state(skip=skip, status=TestState.UNTESTED, error_msg='')
647 else:
648 t.update_state(skip=skip)
649
Jon Salz0697cbf2012-07-04 15:14:04 +0800650 def show_next_active_test(self):
651 '''
652 Rotates to the next visible active test.
653 '''
654 self.reap_completed_tests()
655 active_tests = [
656 t for t in self.test_list.walk()
657 if t.is_leaf() and t.get_state().status == TestState.ACTIVE]
658 if not active_tests:
659 return
Jon Salz4f6c7172012-06-11 20:45:36 +0800660
Jon Salz0697cbf2012-07-04 15:14:04 +0800661 try:
662 next_test = active_tests[
663 (active_tests.index(self.visible_test) + 1) % len(active_tests)]
664 except ValueError: # visible_test not present in active_tests
665 next_test = active_tests[0]
Jon Salz4f6c7172012-06-11 20:45:36 +0800666
Jon Salz0697cbf2012-07-04 15:14:04 +0800667 self.set_visible_test(next_test)
Jon Salz4f6c7172012-06-11 20:45:36 +0800668
Jon Salz0697cbf2012-07-04 15:14:04 +0800669 def handle_event(self, event):
670 '''
671 Handles an event from the event server.
672 '''
673 handler = self.event_handlers.get(event.type)
674 if handler:
675 handler(event)
676 else:
677 # We don't register handlers for all event types - just ignore
678 # this event.
679 logging.debug('Unbound event type %s', event.type)
Jon Salz4f6c7172012-06-11 20:45:36 +0800680
Vic Yangaabf9fd2013-04-09 18:56:13 +0800681 def check_critical_factory_note(self):
682 '''
683 Returns True if the last factory note is critical.
684 '''
685 notes = self.state_instance.get_shared_data('factory_note', True)
686 return notes and notes[-1]['level'] == 'CRITICAL'
687
Jon Salz0697cbf2012-07-04 15:14:04 +0800688 def run_next_test(self):
689 '''
690 Runs the next eligible test (or tests) in self.tests_to_run.
691 '''
692 self.reap_completed_tests()
Vic Yangaabf9fd2013-04-09 18:56:13 +0800693 if self.tests_to_run and self.check_critical_factory_note():
694 self.tests_to_run.clear()
695 return
Jon Salz0697cbf2012-07-04 15:14:04 +0800696 while self.tests_to_run:
697 logging.debug('Tests to run: %s',
698 [x.path for x in self.tests_to_run])
Jon Salz94eb56f2012-06-12 18:01:12 +0800699
Jon Salz0697cbf2012-07-04 15:14:04 +0800700 test = self.tests_to_run[0]
Jon Salz94eb56f2012-06-12 18:01:12 +0800701
Jon Salz0697cbf2012-07-04 15:14:04 +0800702 if test in self.invocations:
703 logging.info('Next test %s is already running', test.path)
704 self.tests_to_run.popleft()
705 return
Jon Salz94eb56f2012-06-12 18:01:12 +0800706
Jon Salza1412922012-07-23 16:04:17 +0800707 for requirement in test.require_run:
708 for i in requirement.test.walk():
709 if i.get_state().status == TestState.ACTIVE:
Jon Salz304a75d2012-07-06 11:14:15 +0800710 logging.info('Waiting for active test %s to complete '
Jon Salza1412922012-07-23 16:04:17 +0800711 'before running %s', i.path, test.path)
Jon Salz304a75d2012-07-06 11:14:15 +0800712 return
713
Jon Salz0697cbf2012-07-04 15:14:04 +0800714 if self.invocations and not (test.backgroundable and all(
715 [x.backgroundable for x in self.invocations])):
716 logging.debug('Waiting for non-backgroundable tests to '
717 'complete before running %s', test.path)
718 return
Jon Salz94eb56f2012-06-12 18:01:12 +0800719
Jon Salz3e6f5202012-10-15 15:08:29 +0800720 if test.get_state().skip:
721 factory.console.info('Skipping test %s', test.path)
722 test.update_state(status=TestState.PASSED,
723 error_msg=TestState.SKIPPED_MSG)
724 self.tests_to_run.popleft()
725 continue
726
Jon Salz0697cbf2012-07-04 15:14:04 +0800727 self.tests_to_run.popleft()
Jon Salz94eb56f2012-06-12 18:01:12 +0800728
Jon Salz304a75d2012-07-06 11:14:15 +0800729 untested = set()
Jon Salza1412922012-07-23 16:04:17 +0800730 for requirement in test.require_run:
731 for i in requirement.test.walk():
732 if i == test:
Jon Salz304a75d2012-07-06 11:14:15 +0800733 # We've hit this test itself; stop checking
734 break
Jon Salza1412922012-07-23 16:04:17 +0800735 if ((i.get_state().status == TestState.UNTESTED) or
736 (requirement.passed and i.get_state().status !=
737 TestState.PASSED)):
Jon Salz304a75d2012-07-06 11:14:15 +0800738 # Found an untested test; move on to the next
739 # element in require_run.
Jon Salza1412922012-07-23 16:04:17 +0800740 untested.add(i)
Jon Salz304a75d2012-07-06 11:14:15 +0800741 break
742
743 if untested:
744 untested_paths = ', '.join(sorted([x.path for x in untested]))
745 if self.state_instance.get_shared_data('engineering_mode',
746 optional=True):
747 # In engineering mode, we'll let it go.
748 factory.console.warn('In engineering mode; running '
749 '%s even though required tests '
750 '[%s] have not completed',
751 test.path, untested_paths)
752 else:
753 # Not in engineering mode; mark it failed.
754 error_msg = ('Required tests [%s] have not been run yet'
755 % untested_paths)
756 factory.console.error('Not running %s: %s',
757 test.path, error_msg)
758 test.update_state(status=TestState.FAILED,
759 error_msg=error_msg)
760 continue
761
Jon Salz0697cbf2012-07-04 15:14:04 +0800762 if isinstance(test, factory.ShutdownStep):
763 if os.path.exists(NO_REBOOT_FILE):
764 test.update_state(
765 status=TestState.FAILED, increment_count=1,
766 error_msg=('Skipped shutdown since %s is present' %
Jon Salz304a75d2012-07-06 11:14:15 +0800767 NO_REBOOT_FILE))
Jon Salz0697cbf2012-07-04 15:14:04 +0800768 continue
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800769
Jon Salz0697cbf2012-07-04 15:14:04 +0800770 test.update_state(status=TestState.ACTIVE, increment_count=1,
771 error_msg='', shutdown_count=0)
772 if self._prompt_cancel_shutdown(test, 1):
773 self.event_log.Log('reboot_cancelled')
774 test.update_state(
775 status=TestState.FAILED, increment_count=1,
776 error_msg='Shutdown aborted by operator',
777 shutdown_count=0)
chungyiafe8f772012-08-15 19:36:29 +0800778 continue
Jon Salz2f757d42012-06-27 17:06:42 +0800779
Jon Salz0697cbf2012-07-04 15:14:04 +0800780 # Save pending test list in the state server
Jon Salzdbf398f2012-06-14 17:30:01 +0800781 self.state_instance.set_shared_data(
Jon Salz0697cbf2012-07-04 15:14:04 +0800782 'tests_after_shutdown',
783 [t.path for t in self.tests_to_run])
784 # Save shutdown time
785 self.state_instance.set_shared_data('shutdown_time',
786 time.time())
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800787
Jon Salz0697cbf2012-07-04 15:14:04 +0800788 with self.env.lock:
789 self.event_log.Log('shutdown', operation=test.operation)
790 shutdown_result = self.env.shutdown(test.operation)
791 if shutdown_result:
792 # That's all, folks!
793 self.run_queue.put(None)
794 return
795 else:
796 # Just pass (e.g., in the chroot).
797 test.update_state(status=TestState.PASSED)
798 self.state_instance.set_shared_data(
799 'tests_after_shutdown', None)
800 # Send event with no fields to indicate that there is no
801 # longer a pending shutdown.
802 self.event_client.post_event(Event(
803 Event.Type.PENDING_SHUTDOWN))
804 continue
Jon Salz258a40c2012-04-19 12:34:01 +0800805
Cheng-Yi Chiangce05c002013-04-04 02:13:17 +0800806 self._run_test(test, test.iterations, test.retries)
Jon Salz1acc8742012-07-17 17:45:55 +0800807
Cheng-Yi Chiangce05c002013-04-04 02:13:17 +0800808 def _run_test(self, test, iterations_left=None, retries_left=None):
Jon Salz1acc8742012-07-17 17:45:55 +0800809 invoc = TestInvocation(self, test, on_completion=self.run_next_test)
810 new_state = test.update_state(
811 status=TestState.ACTIVE, increment_count=1, error_msg='',
Jon Salzbd42ce12012-09-18 08:03:59 +0800812 invocation=invoc.uuid, iterations_left=iterations_left,
Cheng-Yi Chiangce05c002013-04-04 02:13:17 +0800813 retries_left=retries_left,
Jon Salzbd42ce12012-09-18 08:03:59 +0800814 visible=(self.visible_test == test))
Jon Salz1acc8742012-07-17 17:45:55 +0800815 invoc.count = new_state.count
816
817 self.invocations[test] = invoc
818 if self.visible_test is None and test.has_ui:
819 self.set_visible_test(test)
Vic Yang311ddb82012-09-26 12:08:28 +0800820 self.check_exclusive()
Jon Salz1acc8742012-07-17 17:45:55 +0800821 invoc.start()
Jon Salz5f2a0672012-05-22 17:14:06 +0800822
Vic Yang311ddb82012-09-26 12:08:28 +0800823 def check_exclusive(self):
Jon Salzce6a7f82013-06-10 18:22:54 +0800824 # alias since this is really long
825 EXCL_OPT = factory.FactoryTest.EXCLUSIVE_OPTIONS
826
Vic Yang311ddb82012-09-26 12:08:28 +0800827 current_exclusive_items = set([
Jon Salzce6a7f82013-06-10 18:22:54 +0800828 item for item in EXCL_OPT
Vic Yang311ddb82012-09-26 12:08:28 +0800829 if any([test.is_exclusive(item) for test in self.invocations])])
830
831 new_exclusive_items = current_exclusive_items - self.exclusive_items
Jon Salzce6a7f82013-06-10 18:22:54 +0800832 if EXCL_OPT.NETWORKING in new_exclusive_items:
Vic Yang311ddb82012-09-26 12:08:28 +0800833 logging.info('Disabling network')
834 self.connection_manager.DisableNetworking()
Jon Salzce6a7f82013-06-10 18:22:54 +0800835 if EXCL_OPT.CHARGER in new_exclusive_items:
Vic Yang311ddb82012-09-26 12:08:28 +0800836 logging.info('Stop controlling charger')
837
838 new_non_exclusive_items = self.exclusive_items - current_exclusive_items
Jon Salzce6a7f82013-06-10 18:22:54 +0800839 if EXCL_OPT.NETWORKING in new_non_exclusive_items:
Vic Yang311ddb82012-09-26 12:08:28 +0800840 logging.info('Re-enabling network')
841 self.connection_manager.EnableNetworking()
Jon Salzce6a7f82013-06-10 18:22:54 +0800842 if EXCL_OPT.CHARGER in new_non_exclusive_items:
Vic Yang311ddb82012-09-26 12:08:28 +0800843 logging.info('Start controlling charger')
844
Jon Salzce6a7f82013-06-10 18:22:54 +0800845 if self.cpufreq_manager:
846 enabled = EXCL_OPT.CPUFREQ not in current_exclusive_items
847 try:
848 self.cpufreq_manager.SetEnabled(enabled)
849 except: # pylint: disable=W0702
850 logging.exception('Unable to %s cpufreq services',
851 'enable' if enabled else 'disable')
852
Vic Yang311ddb82012-09-26 12:08:28 +0800853 # Only adjust charge state if not excluded
Jon Salzce6a7f82013-06-10 18:22:54 +0800854 if (EXCL_OPT.CHARGER not in current_exclusive_items and
855 not utils.in_chroot()):
Cheng-Yi Chiangd8186952013-04-04 23:41:14 +0800856 if self.charge_manager:
857 self.charge_manager.AdjustChargeState()
858 else:
859 try:
860 system.GetBoard().SetChargeState(Board.ChargeState.CHARGE)
861 except BoardException:
862 logging.exception('Unable to set charge state on this board')
Vic Yang311ddb82012-09-26 12:08:28 +0800863
864 self.exclusive_items = current_exclusive_items
Jon Salz5da61e62012-05-31 13:06:22 +0800865
cychiang21886742012-07-05 15:16:32 +0800866 def check_for_updates(self):
867 '''
868 Schedules an asynchronous check for updates if necessary.
869 '''
870 if not self.test_list.options.update_period_secs:
871 # Not enabled.
872 return
873
874 now = time.time()
875 if self.last_update_check and (
876 now - self.last_update_check <
877 self.test_list.options.update_period_secs):
878 # Not yet time for another check.
879 return
880
881 self.last_update_check = now
882
883 def handle_check_for_update(reached_shopfloor, md5sum, needs_update):
884 if reached_shopfloor:
885 new_update_md5sum = md5sum if needs_update else None
886 if system.SystemInfo.update_md5sum != new_update_md5sum:
887 logging.info('Received new update MD5SUM: %s', new_update_md5sum)
888 system.SystemInfo.update_md5sum = new_update_md5sum
889 self.run_queue.put(self.update_system_info)
890
891 updater.CheckForUpdateAsync(
892 handle_check_for_update,
893 self.test_list.options.shopfloor_timeout_secs)
894
Jon Salza6711d72012-07-18 14:33:03 +0800895 def cancel_pending_tests(self):
896 '''Cancels any tests in the run queue.'''
897 self.run_tests([])
898
Jon Salz0697cbf2012-07-04 15:14:04 +0800899 def run_tests(self, subtrees, untested_only=False):
900 '''
901 Runs tests under subtree.
Jon Salz258a40c2012-04-19 12:34:01 +0800902
Jon Salz0697cbf2012-07-04 15:14:04 +0800903 The tests are run in order unless one fails (then stops).
904 Backgroundable tests are run simultaneously; when a foreground test is
905 encountered, we wait for all active tests to finish before continuing.
Jon Salzb1b39092012-05-03 02:05:09 +0800906
Jon Salz0697cbf2012-07-04 15:14:04 +0800907 @param subtrees: Node or nodes containing tests to run (may either be
908 a single test or a list). Duplicates will be ignored.
909 '''
910 if type(subtrees) != list:
911 subtrees = [subtrees]
Jon Salz258a40c2012-04-19 12:34:01 +0800912
Jon Salz0697cbf2012-07-04 15:14:04 +0800913 # Nodes we've seen so far, to avoid duplicates.
914 seen = set()
Jon Salz94eb56f2012-06-12 18:01:12 +0800915
Jon Salz0697cbf2012-07-04 15:14:04 +0800916 self.tests_to_run = deque()
917 for subtree in subtrees:
918 for test in subtree.walk():
919 if test in seen:
920 continue
921 seen.add(test)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800922
Jon Salz0697cbf2012-07-04 15:14:04 +0800923 if not test.is_leaf():
924 continue
925 if (untested_only and
926 test.get_state().status != TestState.UNTESTED):
927 continue
928 self.tests_to_run.append(test)
929 self.run_next_test()
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800930
Jon Salz0697cbf2012-07-04 15:14:04 +0800931 def reap_completed_tests(self):
932 '''
933 Removes completed tests from the set of active tests.
934
935 Also updates the visible test if it was reaped.
936 '''
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +0800937 test_completed = False
Jon Salz0697cbf2012-07-04 15:14:04 +0800938 for t, v in dict(self.invocations).iteritems():
939 if v.is_completed():
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +0800940 test_completed = True
Jon Salz1acc8742012-07-17 17:45:55 +0800941 new_state = t.update_state(**v.update_state_on_completion)
Jon Salz0697cbf2012-07-04 15:14:04 +0800942 del self.invocations[t]
943
Chun-Ta Lin54e17e42012-09-06 22:05:13 +0800944 # Stop on failure if flag is true.
945 if (self.test_list.options.stop_on_failure and
946 new_state.status == TestState.FAILED):
947 # Clean all the tests to cause goofy to stop.
948 self.tests_to_run = []
949 factory.console.info("Stop on failure triggered. Empty the queue.")
950
Jon Salz1acc8742012-07-17 17:45:55 +0800951 if new_state.iterations_left and new_state.status == TestState.PASSED:
952 # Play it again, Sam!
953 self._run_test(t)
Cheng-Yi Chiangce05c002013-04-04 02:13:17 +0800954 # new_state.retries_left is obtained after update.
955 # For retries_left == 0, test can still be run for the last time.
956 elif (new_state.retries_left >= 0 and
957 new_state.status == TestState.FAILED):
958 # Still have to retry, Sam!
959 self._run_test(t)
Jon Salz1acc8742012-07-17 17:45:55 +0800960
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +0800961 if test_completed:
Vic Yangf01c59f2013-04-19 17:37:56 +0800962 self.log_watcher.KickWatchThread()
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +0800963
Jon Salz0697cbf2012-07-04 15:14:04 +0800964 if (self.visible_test is None or
Jon Salz85a39882012-07-05 16:45:04 +0800965 self.visible_test not in self.invocations):
Jon Salz0697cbf2012-07-04 15:14:04 +0800966 self.set_visible_test(None)
967 # Make the first running test, if any, the visible test
968 for t in self.test_list.walk():
969 if t in self.invocations:
970 self.set_visible_test(t)
971 break
972
Jon Salz85a39882012-07-05 16:45:04 +0800973 def kill_active_tests(self, abort, root=None):
Jon Salz0697cbf2012-07-04 15:14:04 +0800974 '''
975 Kills and waits for all active tests.
976
Jon Salz85a39882012-07-05 16:45:04 +0800977 Args:
978 abort: True to change state of killed tests to FAILED, False for
Jon Salz0697cbf2012-07-04 15:14:04 +0800979 UNTESTED.
Jon Salz85a39882012-07-05 16:45:04 +0800980 root: If set, only kills tests with root as an ancestor.
Jon Salz0697cbf2012-07-04 15:14:04 +0800981 '''
982 self.reap_completed_tests()
983 for test, invoc in self.invocations.items():
Jon Salz85a39882012-07-05 16:45:04 +0800984 if root and not test.has_ancestor(root):
985 continue
986
Jon Salz0697cbf2012-07-04 15:14:04 +0800987 factory.console.info('Killing active test %s...' % test.path)
988 invoc.abort_and_join()
989 factory.console.info('Killed %s' % test.path)
Jon Salz1acc8742012-07-17 17:45:55 +0800990 test.update_state(**invoc.update_state_on_completion)
Jon Salz0697cbf2012-07-04 15:14:04 +0800991 del self.invocations[test]
Jon Salz1acc8742012-07-17 17:45:55 +0800992
Jon Salz0697cbf2012-07-04 15:14:04 +0800993 if not abort:
994 test.update_state(status=TestState.UNTESTED)
995 self.reap_completed_tests()
996
Jon Salz85a39882012-07-05 16:45:04 +0800997 def stop(self, root=None, fail=False):
998 self.kill_active_tests(fail, root)
999 # Remove any tests in the run queue under the root.
1000 self.tests_to_run = deque([x for x in self.tests_to_run
1001 if root and not x.has_ancestor(root)])
1002 self.run_next_test()
Jon Salz0697cbf2012-07-04 15:14:04 +08001003
Jon Salz4712ac72013-02-07 17:12:05 +08001004 def clear_state(self, root=None):
1005 self.stop(root)
1006 for f in root.walk():
1007 if f.is_leaf():
1008 f.update_state(status=TestState.UNTESTED)
1009
Jon Salz0697cbf2012-07-04 15:14:04 +08001010 def abort_active_tests(self):
1011 self.kill_active_tests(True)
1012
1013 def main(self):
1014 try:
1015 self.init()
1016 self.event_log.Log('goofy_init',
1017 success=True)
1018 except:
1019 if self.event_log:
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001020 try:
Jon Salz0697cbf2012-07-04 15:14:04 +08001021 self.event_log.Log('goofy_init',
1022 success=False,
1023 trace=traceback.format_exc())
1024 except: # pylint: disable=W0702
1025 pass
1026 raise
1027
1028 self.run()
1029
1030 def update_system_info(self):
1031 '''Updates system info.'''
1032 system_info = system.SystemInfo()
1033 self.state_instance.set_shared_data('system_info', system_info.__dict__)
1034 self.event_client.post_event(Event(Event.Type.SYSTEM_INFO,
1035 system_info=system_info.__dict__))
1036 logging.info('System info: %r', system_info.__dict__)
1037
Jon Salzeb42f0d2012-07-27 19:14:04 +08001038 def update_factory(self, auto_run_on_restart=False, post_update_hook=None):
1039 '''Commences updating factory software.
1040
1041 Args:
1042 auto_run_on_restart: Auto-run when the machine comes back up.
1043 post_update_hook: Code to call after update but immediately before
1044 restart.
1045
1046 Returns:
1047 Never if the update was successful (we just reboot).
1048 False if the update was unnecessary (no update available).
1049 '''
Jon Salz0697cbf2012-07-04 15:14:04 +08001050 self.kill_active_tests(False)
Jon Salza6711d72012-07-18 14:33:03 +08001051 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +08001052
Jon Salz5c344f62012-07-13 14:31:16 +08001053 def pre_update_hook():
1054 if auto_run_on_restart:
1055 self.state_instance.set_shared_data('tests_after_shutdown',
1056 FORCE_AUTO_RUN)
1057 self.state_instance.close()
1058
Jon Salzeb42f0d2012-07-27 19:14:04 +08001059 if updater.TryUpdate(pre_update_hook=pre_update_hook):
1060 if post_update_hook:
1061 post_update_hook()
1062 self.env.shutdown('reboot')
Jon Salz0697cbf2012-07-04 15:14:04 +08001063
Jon Salzcef132a2012-08-30 04:58:08 +08001064 def handle_sigint(self, dummy_signum, dummy_frame):
Jon Salz77c151e2012-08-28 07:20:37 +08001065 logging.error('Received SIGINT')
1066 self.run_queue.put(None)
1067 raise KeyboardInterrupt()
1068
Jon Salz0697cbf2012-07-04 15:14:04 +08001069 def init(self, args=None, env=None):
1070 '''Initializes Goofy.
1071
1072 Args:
1073 args: A list of command-line arguments. Uses sys.argv if
1074 args is None.
1075 env: An Environment instance to use (or None to choose
1076 FakeChrootEnvironment or DUTEnvironment as appropriate).
1077 '''
Jon Salz77c151e2012-08-28 07:20:37 +08001078 signal.signal(signal.SIGINT, self.handle_sigint)
1079
Jon Salz0697cbf2012-07-04 15:14:04 +08001080 parser = OptionParser()
1081 parser.add_option('-v', '--verbose', dest='verbose',
Jon Salz8fa8e832012-07-13 19:04:09 +08001082 action='store_true',
1083 help='Enable debug logging')
Jon Salz0697cbf2012-07-04 15:14:04 +08001084 parser.add_option('--print_test_list', dest='print_test_list',
Jon Salz8fa8e832012-07-13 19:04:09 +08001085 metavar='FILE',
1086 help='Read and print test list FILE, and exit')
Jon Salz0697cbf2012-07-04 15:14:04 +08001087 parser.add_option('--restart', dest='restart',
Jon Salz8fa8e832012-07-13 19:04:09 +08001088 action='store_true',
1089 help='Clear all test state')
Jon Salz0697cbf2012-07-04 15:14:04 +08001090 parser.add_option('--ui', dest='ui', type='choice',
Jon Salz8fa8e832012-07-13 19:04:09 +08001091 choices=['none', 'gtk', 'chrome'],
Jon Salz2f881df2013-02-01 17:00:35 +08001092 default='chrome',
Jon Salz8fa8e832012-07-13 19:04:09 +08001093 help='UI to use')
Jon Salz0697cbf2012-07-04 15:14:04 +08001094 parser.add_option('--ui_scale_factor', dest='ui_scale_factor',
Jon Salz8fa8e832012-07-13 19:04:09 +08001095 type='int', default=1,
1096 help=('Factor by which to scale UI '
1097 '(Chrome UI only)'))
Jon Salz0697cbf2012-07-04 15:14:04 +08001098 parser.add_option('--test_list', dest='test_list',
Jon Salz8fa8e832012-07-13 19:04:09 +08001099 metavar='FILE',
1100 help='Use FILE as test list')
Jon Salzc79a9982012-08-30 04:42:01 +08001101 parser.add_option('--dummy_shopfloor', action='store_true',
1102 help='Use a dummy shopfloor server')
chungyiafe8f772012-08-15 19:36:29 +08001103 parser.add_option('--automation', dest='automation',
1104 action='store_true',
1105 help='Enable automation on running factory test')
Ricky Liang09216dc2013-02-22 17:26:45 +08001106 parser.add_option('--one_pixel_less', dest='one_pixel_less',
1107 action='store_true',
1108 help=('Start Chrome one pixel less than the full screen.'
1109 'Needed by Exynos platform to run GTK.'))
Jon Salz0697cbf2012-07-04 15:14:04 +08001110 (self.options, self.args) = parser.parse_args(args)
1111
Jon Salz46b89562012-07-05 11:49:22 +08001112 # Make sure factory directories exist.
1113 factory.get_log_root()
1114 factory.get_state_root()
1115 factory.get_test_data_root()
1116
Jon Salz0697cbf2012-07-04 15:14:04 +08001117 global _inited_logging # pylint: disable=W0603
1118 if not _inited_logging:
1119 factory.init_logging('goofy', verbose=self.options.verbose)
1120 _inited_logging = True
Jon Salz8fa8e832012-07-13 19:04:09 +08001121
Jon Salz0f996602012-10-03 15:26:48 +08001122 if self.options.print_test_list:
1123 print factory.read_test_list(
1124 self.options.print_test_list).__repr__(recursive=True)
1125 sys.exit(0)
1126
Jon Salzee85d522012-07-17 14:34:46 +08001127 event_log.IncrementBootSequence()
Jon Salzd15bbcf2013-05-21 17:33:57 +08001128 # Don't defer logging the initial event, so we can make sure
1129 # that device_id, reimage_id, etc. are all set up.
1130 self.event_log = EventLog('goofy', defer=False)
Jon Salz0697cbf2012-07-04 15:14:04 +08001131
1132 if (not suppress_chroot_warning and
1133 factory.in_chroot() and
1134 self.options.ui == 'gtk' and
1135 os.environ.get('DISPLAY') in [None, '', ':0', ':0.0']):
1136 # That's not going to work! Tell the user how to run
1137 # this way.
1138 logging.warn(GOOFY_IN_CHROOT_WARNING)
1139 time.sleep(1)
1140
1141 if env:
1142 self.env = env
1143 elif factory.in_chroot():
1144 self.env = test_environment.FakeChrootEnvironment()
1145 logging.warn(
1146 'Using chroot environment: will not actually run autotests')
1147 else:
1148 self.env = test_environment.DUTEnvironment()
1149 self.env.goofy = self
1150
1151 if self.options.restart:
1152 state.clear_state()
1153
Jon Salz0697cbf2012-07-04 15:14:04 +08001154 if self.options.ui_scale_factor != 1 and utils.in_qemu():
1155 logging.warn(
1156 'In QEMU; ignoring ui_scale_factor argument')
1157 self.options.ui_scale_factor = 1
1158
1159 logging.info('Started')
1160
1161 self.start_state_server()
1162 self.state_instance.set_shared_data('hwid_cfg', get_hwid_cfg())
1163 self.state_instance.set_shared_data('ui_scale_factor',
Ricky Liang09216dc2013-02-22 17:26:45 +08001164 self.options.ui_scale_factor)
1165 self.state_instance.set_shared_data('one_pixel_less',
1166 self.options.one_pixel_less)
Jon Salz0697cbf2012-07-04 15:14:04 +08001167 self.last_shutdown_time = (
1168 self.state_instance.get_shared_data('shutdown_time', optional=True))
1169 self.state_instance.del_shared_data('shutdown_time', optional=True)
1170
Jon Salzb19ea072013-02-07 16:35:00 +08001171 self.state_instance.del_shared_data('startup_error', optional=True)
Jon Salz0697cbf2012-07-04 15:14:04 +08001172 if not self.options.test_list:
1173 self.options.test_list = find_test_list()
Jon Salzb19ea072013-02-07 16:35:00 +08001174 if self.options.test_list:
Jon Salz0697cbf2012-07-04 15:14:04 +08001175 logging.info('Using test list %s', self.options.test_list)
Jon Salzb19ea072013-02-07 16:35:00 +08001176 try:
1177 self.test_list = factory.read_test_list(
1178 self.options.test_list,
1179 self.state_instance)
1180 except: # pylint: disable=W0702
1181 logging.exception('Unable to read test list %r', self.options.test_list)
1182 self.state_instance.set_shared_data('startup_error',
1183 'Unable to read test list %s\n%s' % (
1184 self.options.test_list,
1185 traceback.format_exc()))
1186 else:
1187 logging.error('No test list found.')
1188 self.state_instance.set_shared_data('startup_error',
1189 'No test list found.')
Jon Salz0697cbf2012-07-04 15:14:04 +08001190
Jon Salzb19ea072013-02-07 16:35:00 +08001191 if not self.test_list:
1192 if self.options.ui == 'chrome':
1193 # Create an empty test list with default options so that the rest of
1194 # startup can proceed.
1195 self.test_list = factory.FactoryTestList(
1196 [], self.state_instance, factory.Options())
1197 else:
1198 # Bail with an error; no point in starting up.
1199 sys.exit('No valid test list; exiting.')
1200
Jon Salz822838b2013-03-25 17:32:33 +08001201 if self.test_list.options.clear_state_on_start:
1202 self.state_instance.clear_test_state()
1203
Vic Yang3e1cf5d2013-06-05 18:50:24 +08001204 if system.SystemInfo().firmware_version is None and not utils.in_chroot():
Vic Yang9bd4f772013-06-04 17:34:00 +08001205 self.state_instance.set_shared_data('startup_error',
1206 'Netboot firmware detected\n'
1207 'Connect Ethernet and reboot to re-image.\n'
1208 u'侦测到网路开机固件\n'
1209 u'请连接乙太网并重启')
1210
Jon Salz0697cbf2012-07-04 15:14:04 +08001211 if not self.state_instance.has_shared_data('ui_lang'):
1212 self.state_instance.set_shared_data('ui_lang',
1213 self.test_list.options.ui_lang)
1214 self.state_instance.set_shared_data(
1215 'test_list_options',
1216 self.test_list.options.__dict__)
1217 self.state_instance.test_list = self.test_list
1218
Jon Salz83ef34b2012-11-01 19:46:35 +08001219 if not utils.in_chroot() and self.test_list.options.disable_log_rotation:
1220 open('/var/lib/cleanup_logs_paused', 'w').close()
1221
Jon Salz23926422012-09-01 03:38:13 +08001222 if self.options.dummy_shopfloor:
1223 os.environ[shopfloor.SHOPFLOOR_SERVER_ENV_VAR_NAME] = (
1224 'http://localhost:%d/' % shopfloor.DEFAULT_SERVER_PORT)
1225 self.dummy_shopfloor = Spawn(
1226 [os.path.join(factory.FACTORY_PATH, 'bin', 'shopfloor_server'),
1227 '--dummy'])
1228 elif self.test_list.options.shopfloor_server_url:
1229 shopfloor.set_server_url(self.test_list.options.shopfloor_server_url)
Jon Salz2bf2f6b2013-03-28 18:49:26 +08001230 shopfloor.set_enabled(True)
Jon Salz23926422012-09-01 03:38:13 +08001231
Jon Salz0f996602012-10-03 15:26:48 +08001232 if self.test_list.options.time_sanitizer and not utils.in_chroot():
Jon Salz8fa8e832012-07-13 19:04:09 +08001233 self.time_sanitizer = time_sanitizer.TimeSanitizer(
1234 base_time=time_sanitizer.GetBaseTimeFromFile(
1235 # lsb-factory is written by the factory install shim during
1236 # installation, so it should have a good time obtained from
Jon Salz54882d02012-08-31 01:57:54 +08001237 # the mini-Omaha server. If it's not available, we'll use
1238 # /etc/lsb-factory (which will be much older, but reasonably
1239 # sane) and rely on a shopfloor sync to set a more accurate
1240 # time.
1241 '/usr/local/etc/lsb-factory',
1242 '/etc/lsb-release'))
Jon Salz8fa8e832012-07-13 19:04:09 +08001243 self.time_sanitizer.RunOnce()
1244
Jon Salz0697cbf2012-07-04 15:14:04 +08001245 self.init_states()
1246 self.start_event_server()
1247 self.connection_manager = self.env.create_connection_manager(
Tai-Hsu Lin371351a2012-08-27 14:17:14 +08001248 self.test_list.options.wlans,
1249 self.test_list.options.scan_wifi_period_secs)
Jon Salz0697cbf2012-07-04 15:14:04 +08001250 # Note that we create a log watcher even if
1251 # sync_event_log_period_secs isn't set (no background
1252 # syncing), since we may use it to flush event logs as well.
1253 self.log_watcher = EventLogWatcher(
1254 self.test_list.options.sync_event_log_period_secs,
Jon Salzd15bbcf2013-05-21 17:33:57 +08001255 event_log_db_file=None,
Jon Salz16d10542012-07-23 12:18:45 +08001256 handle_event_logs_callback=self.handle_event_logs)
Jon Salz0697cbf2012-07-04 15:14:04 +08001257 if self.test_list.options.sync_event_log_period_secs:
1258 self.log_watcher.StartWatchThread()
1259
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +08001260 # Note that we create a system log manager even if
1261 # sync_log_period_secs isn't set (no background
1262 # syncing), since we may kick it to sync logs in its
1263 # thread.
1264 self.system_log_manager = SystemLogManager(
Cheng-Yi Chiang835f2682013-05-06 22:15:48 +08001265 sync_log_paths=self.test_list.options.sync_log_paths,
1266 sync_period_sec=self.test_list.options.sync_log_period_secs,
1267 clear_log_paths=self.test_list.options.clear_log_paths)
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +08001268 self.system_log_manager.StartSyncThread()
1269
Jon Salz0697cbf2012-07-04 15:14:04 +08001270 self.update_system_info()
1271
Vic Yang4953fc12012-07-26 16:19:53 +08001272 assert ((self.test_list.options.min_charge_pct is None) ==
1273 (self.test_list.options.max_charge_pct is None))
Vic Yange83d9a12013-04-19 20:00:20 +08001274 if utils.in_chroot():
1275 logging.info('In chroot, ignoring charge manager and charge state')
1276 elif self.test_list.options.min_charge_pct is not None:
Vic Yang4953fc12012-07-26 16:19:53 +08001277 self.charge_manager = ChargeManager(self.test_list.options.min_charge_pct,
1278 self.test_list.options.max_charge_pct)
Jon Salzad7353b2012-10-15 16:22:46 +08001279 system.SystemStatus.charge_manager = self.charge_manager
Cheng-Yi Chiangd8186952013-04-04 23:41:14 +08001280 else:
1281 # Goofy should set charger state to charge if charge_manager is disabled.
1282 try:
1283 system.GetBoard().SetChargeState(Board.ChargeState.CHARGE)
1284 except BoardException:
1285 logging.exception('Unable to set charge state on this board')
Vic Yang4953fc12012-07-26 16:19:53 +08001286
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001287 self.core_dump_manager = CoreDumpManager(
1288 self.test_list.options.core_dump_watchlist)
1289
Jon Salz0697cbf2012-07-04 15:14:04 +08001290 os.environ['CROS_FACTORY'] = '1'
1291 os.environ['CROS_DISABLE_SITE_SYSINFO'] = '1'
1292
1293 # Set CROS_UI since some behaviors in ui.py depend on the
1294 # particular UI in use. TODO(jsalz): Remove this (and all
1295 # places it is used) when the GTK UI is removed.
1296 os.environ['CROS_UI'] = self.options.ui
1297
Jon Salz416f9cc2013-05-10 18:32:50 +08001298 # Initialize hooks.
1299 module, cls = self.test_list.options.hooks_class.rsplit('.', 1)
1300 self.hooks = getattr(__import__(module, fromlist=[cls]), cls)()
1301 assert isinstance(self.hooks, factory.Hooks), (
1302 "hooks should be of type Hooks but is %r" % type(self.hooks))
1303 self.hooks.test_list = self.test_list
1304
Jon Salzce6a7f82013-06-10 18:22:54 +08001305 if not utils.in_chroot():
1306 self.cpufreq_manager = CpufreqManager()
1307
Jon Salz416f9cc2013-05-10 18:32:50 +08001308 # Call startup hook.
1309 self.hooks.OnStartup()
1310
Jon Salz0697cbf2012-07-04 15:14:04 +08001311 if self.options.ui == 'chrome':
1312 self.env.launch_chrome()
1313 logging.info('Waiting for a web socket connection')
Cheng-Yi Chiangfd8ed392013-03-08 21:37:31 +08001314 self.web_socket_manager.wait()
Jon Salz0697cbf2012-07-04 15:14:04 +08001315
1316 # Wait for the test widget size to be set; this is done in
1317 # an asynchronous RPC so there is a small chance that the
1318 # web socket might be opened first.
1319 for _ in range(100): # 10 s
1320 try:
1321 if self.state_instance.get_shared_data('test_widget_size'):
1322 break
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001323 except KeyError:
Jon Salz0697cbf2012-07-04 15:14:04 +08001324 pass # Retry
1325 time.sleep(0.1) # 100 ms
1326 else:
1327 logging.warn('Never received test_widget_size from UI')
Jon Salz45297282013-05-18 14:31:47 +08001328
1329 # Send Chrome a Tab to get focus to the factory UI
1330 # (http://crosbug.com/p/19444). TODO(jsalz): remove this hack
1331 # and figure out the right way to get the focus to Chrome.
1332 if not utils.in_chroot():
1333 Spawn(
1334 [os.path.join(factory.FACTORY_PATH, 'bin', 'send_key'), 'Tab'],
1335 check_call=True, log=True)
Jon Salz0697cbf2012-07-04 15:14:04 +08001336 elif self.options.ui == 'gtk':
1337 self.start_ui()
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001338
Ricky Liang650f6bf2012-09-28 13:22:54 +08001339 # Create download path for autotest beforehand or autotests run at
1340 # the same time might fail due to race condition.
1341 if not factory.in_chroot():
1342 utils.TryMakeDirs(os.path.join('/usr/local/autotest', 'tests',
1343 'download'))
1344
Jon Salz0697cbf2012-07-04 15:14:04 +08001345 def state_change_callback(test, test_state):
1346 self.event_client.post_event(
1347 Event(Event.Type.STATE_CHANGE,
1348 path=test.path, state=test_state))
1349 self.test_list.state_change_callback = state_change_callback
Jon Salz73e0fd02012-04-04 11:46:38 +08001350
Jon Salza6711d72012-07-18 14:33:03 +08001351 for handler in self.on_ui_startup:
1352 handler()
1353
1354 self.prespawner = Prespawner()
1355 self.prespawner.start()
1356
Jon Salz0697cbf2012-07-04 15:14:04 +08001357 try:
1358 tests_after_shutdown = self.state_instance.get_shared_data(
1359 'tests_after_shutdown')
1360 except KeyError:
1361 tests_after_shutdown = None
Jon Salz57717ca2012-04-04 16:47:25 +08001362
Jon Salz5c344f62012-07-13 14:31:16 +08001363 force_auto_run = (tests_after_shutdown == FORCE_AUTO_RUN)
1364 if not force_auto_run and tests_after_shutdown is not None:
Jon Salz0697cbf2012-07-04 15:14:04 +08001365 logging.info('Resuming tests after shutdown: %s',
1366 tests_after_shutdown)
Jon Salz0697cbf2012-07-04 15:14:04 +08001367 self.tests_to_run.extend(
1368 self.test_list.lookup_path(t) for t in tests_after_shutdown)
1369 self.run_queue.put(self.run_next_test)
1370 else:
Jon Salz5c344f62012-07-13 14:31:16 +08001371 if force_auto_run or self.test_list.options.auto_run_on_start:
Jon Salz0697cbf2012-07-04 15:14:04 +08001372 self.run_queue.put(
1373 lambda: self.run_tests(self.test_list, untested_only=True))
Jon Salz5c344f62012-07-13 14:31:16 +08001374 self.state_instance.set_shared_data('tests_after_shutdown', None)
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001375
Dean Liao592e4d52013-01-10 20:06:39 +08001376 self.may_disable_cros_shortcut_keys()
1377
1378 def may_disable_cros_shortcut_keys(self):
1379 test_options = self.test_list.options
1380 if test_options.disable_cros_shortcut_keys:
1381 logging.info('Filter ChromeOS shortcut keys.')
1382 self.key_filter = KeyFilter(
1383 unmap_caps_lock=test_options.disable_caps_lock,
1384 caps_lock_keycode=test_options.caps_lock_keycode)
1385 self.key_filter.Start()
1386
Jon Salz0697cbf2012-07-04 15:14:04 +08001387 def run(self):
1388 '''Runs Goofy.'''
1389 # Process events forever.
1390 while self.run_once(True):
1391 pass
Jon Salz73e0fd02012-04-04 11:46:38 +08001392
Jon Salz0697cbf2012-07-04 15:14:04 +08001393 def run_once(self, block=False):
1394 '''Runs all items pending in the event loop.
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001395
Jon Salz0697cbf2012-07-04 15:14:04 +08001396 Args:
1397 block: If true, block until at least one event is processed.
Jon Salz7c15e8b2012-06-19 17:10:37 +08001398
Jon Salz0697cbf2012-07-04 15:14:04 +08001399 Returns:
1400 True to keep going or False to shut down.
1401 '''
1402 events = utils.DrainQueue(self.run_queue)
cychiang21886742012-07-05 15:16:32 +08001403 while not events:
Jon Salz0697cbf2012-07-04 15:14:04 +08001404 # Nothing on the run queue.
1405 self._run_queue_idle()
1406 if block:
1407 # Block for at least one event...
cychiang21886742012-07-05 15:16:32 +08001408 try:
1409 events.append(self.run_queue.get(timeout=RUN_QUEUE_TIMEOUT_SECS))
1410 except Queue.Empty:
1411 # Keep going (calling _run_queue_idle() again at the top of
1412 # the loop)
1413 continue
Jon Salz0697cbf2012-07-04 15:14:04 +08001414 # ...and grab anything else that showed up at the same
1415 # time.
1416 events.extend(utils.DrainQueue(self.run_queue))
cychiang21886742012-07-05 15:16:32 +08001417 else:
1418 break
Jon Salz51528e12012-07-02 18:54:45 +08001419
Jon Salz0697cbf2012-07-04 15:14:04 +08001420 for event in events:
1421 if not event:
1422 # Shutdown request.
1423 self.run_queue.task_done()
1424 return False
Jon Salz51528e12012-07-02 18:54:45 +08001425
Jon Salz0697cbf2012-07-04 15:14:04 +08001426 try:
1427 event()
Jon Salz85a39882012-07-05 16:45:04 +08001428 except: # pylint: disable=W0702
1429 logging.exception('Error in event loop')
Jon Salz0697cbf2012-07-04 15:14:04 +08001430 self.record_exception(traceback.format_exception_only(
1431 *sys.exc_info()[:2]))
1432 # But keep going
1433 finally:
1434 self.run_queue.task_done()
1435 return True
Jon Salz0405ab52012-03-16 15:26:52 +08001436
Jon Salz0e6532d2012-10-25 16:30:11 +08001437 def _should_sync_time(self, foreground=False):
1438 '''Returns True if we should attempt syncing time with shopfloor.
1439
1440 Args:
1441 foreground: If True, synchronizes even if background syncing
1442 is disabled (e.g., in explicit sync requests from the
1443 SyncShopfloor test).
1444 '''
1445 return ((foreground or
1446 self.test_list.options.sync_time_period_secs) and
Jon Salz54882d02012-08-31 01:57:54 +08001447 self.time_sanitizer and
1448 (not self.time_synced) and
1449 (not factory.in_chroot()))
1450
Jon Salz0e6532d2012-10-25 16:30:11 +08001451 def sync_time_with_shopfloor_server(self, foreground=False):
Jon Salz54882d02012-08-31 01:57:54 +08001452 '''Syncs time with shopfloor server, if not yet synced.
1453
Jon Salz0e6532d2012-10-25 16:30:11 +08001454 Args:
1455 foreground: If True, synchronizes even if background syncing
1456 is disabled (e.g., in explicit sync requests from the
1457 SyncShopfloor test).
1458
Jon Salz54882d02012-08-31 01:57:54 +08001459 Returns:
1460 False if no time sanitizer is available, or True if this sync (or a
1461 previous sync) succeeded.
1462
1463 Raises:
1464 Exception if unable to contact the shopfloor server.
1465 '''
Jon Salz0e6532d2012-10-25 16:30:11 +08001466 if self._should_sync_time(foreground):
Jon Salz54882d02012-08-31 01:57:54 +08001467 self.time_sanitizer.SyncWithShopfloor()
1468 self.time_synced = True
1469 return self.time_synced
1470
Jon Salzb92c5112012-09-21 15:40:11 +08001471 def log_disk_space_stats(self):
Jon Salz18e0e022013-06-11 17:13:39 +08001472 if (utils.in_chroot() or
1473 not self.test_list.options.log_disk_space_period_secs):
Jon Salzb92c5112012-09-21 15:40:11 +08001474 return
1475
1476 now = time.time()
1477 if (self.last_log_disk_space_time and
1478 now - self.last_log_disk_space_time <
1479 self.test_list.options.log_disk_space_period_secs):
1480 return
1481 self.last_log_disk_space_time = now
1482
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001483 # Upload event if stateful partition usage is above threshold.
1484 # Stateful partition is mounted on /usr/local, while
1485 # encrypted stateful partition is mounted on /var.
1486 # If there are too much logs in the factory process,
1487 # these two partitions might get full.
Jon Salzb92c5112012-09-21 15:40:11 +08001488 try:
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001489 vfs_infos = disk_space.GetAllVFSInfo()
1490 stateful_info, encrypted_info = None, None
1491 for vfs_info in vfs_infos.values():
1492 if '/usr/local' in vfs_info.mount_points:
1493 stateful_info = vfs_info
1494 if '/var' in vfs_info.mount_points:
1495 encrypted_info = vfs_info
1496
1497 stateful = disk_space.GetPartitionUsage(stateful_info)
1498 encrypted = disk_space.GetPartitionUsage(encrypted_info)
1499
1500 above_threshold = (
1501 self.test_list.options.stateful_usage_threshold and
1502 max(stateful.bytes_used_pct,
1503 stateful.inodes_used_pct,
1504 encrypted.bytes_used_pct,
1505 encrypted.inodes_used_pct) >
1506 self.test_list.options.stateful_usage_threshold)
1507
1508 if above_threshold:
1509 self.event_log.Log('stateful_partition_usage',
1510 partitions={
1511 'stateful': {
1512 'bytes_used_pct': FloatDigit(stateful.bytes_used_pct, 2),
1513 'inodes_used_pct': FloatDigit(stateful.inodes_used_pct, 2)},
1514 'encrypted_stateful': {
1515 'bytes_used_pct': FloatDigit(encrypted.bytes_used_pct, 2),
1516 'inodes_used_pct': FloatDigit(encrypted.inodes_used_pct, 2)}
1517 })
1518 self.log_watcher.ScanEventLogs()
1519
1520 message = disk_space.FormatSpaceUsedAll(vfs_infos)
Jon Salz3c493bb2013-02-07 17:24:58 +08001521 if message != self.last_log_disk_space_message:
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001522 if above_threshold:
1523 logging.warning(message)
1524 else:
1525 logging.info(message)
Jon Salz3c493bb2013-02-07 17:24:58 +08001526 self.last_log_disk_space_message = message
Jon Salzb92c5112012-09-21 15:40:11 +08001527 except: # pylint: disable=W0702
1528 logging.exception('Unable to get disk space used')
1529
Justin Chuang83813982013-05-13 01:26:32 +08001530 def check_battery(self):
1531 '''Checks the current battery status.
1532
1533 Logs current battery charging level and status to log. If the battery level
1534 is lower below warning_low_battery_pct, send warning event to shopfloor.
1535 If the battery level is lower below critical_low_battery_pct, flush disks.
1536 '''
1537 if not self.test_list.options.check_battery_period_secs:
1538 return
1539
1540 now = time.time()
1541 if (self.last_check_battery_time and
1542 now - self.last_check_battery_time <
1543 self.test_list.options.check_battery_period_secs):
1544 return
1545 self.last_check_battery_time = now
1546
1547 message = ''
1548 log_level = logging.INFO
1549 try:
1550 power = system.GetBoard().power
1551 if not power.CheckBatteryPresent():
1552 message = 'Battery is not present'
1553 else:
1554 ac_present = power.CheckACPresent()
1555 charge_pct = power.GetChargePct(get_float=True)
1556 message = ('Current battery level %.1f%%, AC charger is %s' %
1557 (charge_pct, 'connected' if ac_present else 'disconnected'))
1558
1559 if charge_pct > self.test_list.options.critical_low_battery_pct:
1560 critical_low_battery = False
1561 else:
1562 critical_low_battery = True
1563 # Only sync disks when battery level is still above minimum
1564 # value. This can be used for offline analysis when shopfloor cannot
1565 # be connected.
1566 if charge_pct > MIN_BATTERY_LEVEL_FOR_DISK_SYNC:
1567 logging.warning('disk syncing for critical low battery situation')
1568 os.system('sync; sync; sync')
1569 else:
1570 logging.warning('disk syncing is cancelled '
1571 'because battery level is lower than %.1f',
1572 MIN_BATTERY_LEVEL_FOR_DISK_SYNC)
1573
1574 # Notify shopfloor server
1575 if (critical_low_battery or
1576 (not ac_present and
1577 charge_pct <= self.test_list.options.warning_low_battery_pct)):
1578 log_level = logging.WARNING
1579
1580 self.event_log.Log('low_battery',
1581 battery_level=charge_pct,
1582 charger_connected=ac_present,
1583 critical=critical_low_battery)
1584 self.log_watcher.KickWatchThread()
1585 self.system_log_manager.KickSyncThread()
1586 except: # pylint: disable=W0702
1587 logging.exception('Unable to check battery or notify shopfloor')
1588 finally:
1589 if message != self.last_check_battery_message:
1590 logging.log(log_level, message)
1591 self.last_check_battery_message = message
1592
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001593 def check_core_dump(self):
1594 '''Checks if there is any core dumped file.
1595
1596 Removes unwanted core dump files immediately.
1597 Syncs those files matching watch list to server with a delay between
1598 each sync. After the files have been synced to server, deletes the files.
1599 '''
1600 core_dump_files = self.core_dump_manager.ScanFiles()
1601 if core_dump_files:
1602 now = time.time()
1603 if (self.last_kick_sync_time and now - self.last_kick_sync_time <
1604 self.test_list.options.kick_sync_min_interval_secs):
1605 return
1606 self.last_kick_sync_time = now
1607
1608 # Sends event to server
1609 self.event_log.Log('core_dumped', files=core_dump_files)
1610 self.log_watcher.KickWatchThread()
1611
1612 # Syncs files to server
1613 self.system_log_manager.KickSyncThread(
1614 core_dump_files, self.core_dump_manager.ClearFiles)
1615
Jon Salz8fa8e832012-07-13 19:04:09 +08001616 def sync_time_in_background(self):
Jon Salzb22d1172012-08-06 10:38:57 +08001617 '''Writes out current time and tries to sync with shopfloor server.'''
1618 if not self.time_sanitizer:
1619 return
1620
1621 # Write out the current time.
1622 self.time_sanitizer.SaveTime()
1623
Jon Salz54882d02012-08-31 01:57:54 +08001624 if not self._should_sync_time():
Jon Salz8fa8e832012-07-13 19:04:09 +08001625 return
1626
1627 now = time.time()
1628 if self.last_sync_time and (
1629 now - self.last_sync_time <
1630 self.test_list.options.sync_time_period_secs):
1631 # Not yet time for another check.
1632 return
1633 self.last_sync_time = now
1634
1635 def target():
1636 try:
Jon Salz54882d02012-08-31 01:57:54 +08001637 self.sync_time_with_shopfloor_server()
Jon Salz8fa8e832012-07-13 19:04:09 +08001638 except: # pylint: disable=W0702
1639 # Oh well. Log an error (but no trace)
1640 logging.info(
1641 'Unable to get time from shopfloor server: %s',
1642 utils.FormatExceptionOnly())
1643
1644 thread = threading.Thread(target=target)
1645 thread.daemon = True
1646 thread.start()
1647
Jon Salz0697cbf2012-07-04 15:14:04 +08001648 def _run_queue_idle(self):
Vic Yang4953fc12012-07-26 16:19:53 +08001649 '''Invoked when the run queue has no events.
1650
1651 This method must not raise exception.
1652 '''
Jon Salzb22d1172012-08-06 10:38:57 +08001653 now = time.time()
1654 if (self.last_idle and
1655 now < (self.last_idle + RUN_QUEUE_TIMEOUT_SECS - 1)):
1656 # Don't run more often than once every (RUN_QUEUE_TIMEOUT_SECS -
1657 # 1) seconds.
1658 return
1659
1660 self.last_idle = now
1661
Vic Yang311ddb82012-09-26 12:08:28 +08001662 self.check_exclusive()
cychiang21886742012-07-05 15:16:32 +08001663 self.check_for_updates()
Jon Salz8fa8e832012-07-13 19:04:09 +08001664 self.sync_time_in_background()
Jon Salzb92c5112012-09-21 15:40:11 +08001665 self.log_disk_space_stats()
Justin Chuang83813982013-05-13 01:26:32 +08001666 self.check_battery()
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001667 self.check_core_dump()
Jon Salz57717ca2012-04-04 16:47:25 +08001668
Jon Salzd15bbcf2013-05-21 17:33:57 +08001669 def handle_event_logs(self, chunks):
Jon Salz0697cbf2012-07-04 15:14:04 +08001670 '''Callback for event watcher.
Jon Salz258a40c2012-04-19 12:34:01 +08001671
Jon Salz0697cbf2012-07-04 15:14:04 +08001672 Attempts to upload the event logs to the shopfloor server.
Vic Yang93027612013-05-06 02:42:49 +08001673
1674 Args:
Jon Salzd15bbcf2013-05-21 17:33:57 +08001675 chunks: A list of Chunk objects.
Jon Salz0697cbf2012-07-04 15:14:04 +08001676 '''
Vic Yang93027612013-05-06 02:42:49 +08001677 first_exception = None
1678 exception_count = 0
1679
Jon Salzd15bbcf2013-05-21 17:33:57 +08001680 for chunk in chunks:
Vic Yang93027612013-05-06 02:42:49 +08001681 try:
Jon Salzcddb6402013-05-23 12:56:42 +08001682 description = 'event logs (%s)' % str(chunk)
Vic Yang93027612013-05-06 02:42:49 +08001683 start_time = time.time()
1684 shopfloor_client = shopfloor.get_instance(
1685 detect=True,
1686 timeout=self.test_list.options.shopfloor_timeout_secs)
Jon Salzd15bbcf2013-05-21 17:33:57 +08001687 shopfloor_client.UploadEvent(chunk.log_name + "." +
1688 event_log.GetReimageId(),
1689 Binary(chunk.chunk))
Vic Yang93027612013-05-06 02:42:49 +08001690 logging.info(
1691 'Successfully synced %s in %.03f s',
1692 description, time.time() - start_time)
1693 except: # pylint: disable=W0702
Jon Salzd15bbcf2013-05-21 17:33:57 +08001694 first_exception = (first_exception or (chunk.log_name + ': ' +
Vic Yang93027612013-05-06 02:42:49 +08001695 utils.FormatExceptionOnly()))
1696 exception_count += 1
1697
1698 if exception_count:
1699 if exception_count == 1:
1700 msg = 'Log upload failed: %s' % first_exception
1701 else:
1702 msg = '%d log upload failed; first is: %s' % (
1703 exception_count, first_exception)
1704 raise Exception(msg)
1705
Jon Salz57717ca2012-04-04 16:47:25 +08001706
Jon Salz0697cbf2012-07-04 15:14:04 +08001707 def run_tests_with_status(self, statuses_to_run, starting_at=None,
1708 root=None):
1709 '''Runs all top-level tests with a particular status.
Jon Salz0405ab52012-03-16 15:26:52 +08001710
Jon Salz0697cbf2012-07-04 15:14:04 +08001711 All active tests, plus any tests to re-run, are reset.
Jon Salz57717ca2012-04-04 16:47:25 +08001712
Jon Salz0697cbf2012-07-04 15:14:04 +08001713 Args:
1714 starting_at: If provided, only auto-runs tests beginning with
1715 this test.
1716 '''
1717 root = root or self.test_list
Jon Salz57717ca2012-04-04 16:47:25 +08001718
Jon Salz0697cbf2012-07-04 15:14:04 +08001719 if starting_at:
1720 # Make sure they passed a test, not a string.
1721 assert isinstance(starting_at, factory.FactoryTest)
Jon Salz0405ab52012-03-16 15:26:52 +08001722
Jon Salz0697cbf2012-07-04 15:14:04 +08001723 tests_to_reset = []
1724 tests_to_run = []
Jon Salz0405ab52012-03-16 15:26:52 +08001725
Jon Salz0697cbf2012-07-04 15:14:04 +08001726 found_starting_at = False
Jon Salz0405ab52012-03-16 15:26:52 +08001727
Jon Salz0697cbf2012-07-04 15:14:04 +08001728 for test in root.get_top_level_tests():
1729 if starting_at:
1730 if test == starting_at:
1731 # We've found starting_at; do auto-run on all
1732 # subsequent tests.
1733 found_starting_at = True
1734 if not found_starting_at:
1735 # Don't start this guy yet
1736 continue
Jon Salz0405ab52012-03-16 15:26:52 +08001737
Jon Salz0697cbf2012-07-04 15:14:04 +08001738 status = test.get_state().status
1739 if status == TestState.ACTIVE or status in statuses_to_run:
1740 # Reset the test (later; we will need to abort
1741 # all active tests first).
1742 tests_to_reset.append(test)
1743 if status in statuses_to_run:
1744 tests_to_run.append(test)
Jon Salz0405ab52012-03-16 15:26:52 +08001745
Jon Salz0697cbf2012-07-04 15:14:04 +08001746 self.abort_active_tests()
Jon Salz258a40c2012-04-19 12:34:01 +08001747
Jon Salz0697cbf2012-07-04 15:14:04 +08001748 # Reset all statuses of the tests to run (in case any tests were active;
1749 # we want them to be run again).
1750 for test_to_reset in tests_to_reset:
1751 for test in test_to_reset.walk():
1752 test.update_state(status=TestState.UNTESTED)
Jon Salz57717ca2012-04-04 16:47:25 +08001753
Jon Salz0697cbf2012-07-04 15:14:04 +08001754 self.run_tests(tests_to_run, untested_only=True)
Jon Salz0405ab52012-03-16 15:26:52 +08001755
Jon Salz0697cbf2012-07-04 15:14:04 +08001756 def restart_tests(self, root=None):
1757 '''Restarts all tests.'''
1758 root = root or self.test_list
Jon Salz0405ab52012-03-16 15:26:52 +08001759
Jon Salz0697cbf2012-07-04 15:14:04 +08001760 self.abort_active_tests()
1761 for test in root.walk():
1762 test.update_state(status=TestState.UNTESTED)
1763 self.run_tests(root)
Hung-Te Lin96632362012-03-20 21:14:18 +08001764
Jon Salz0697cbf2012-07-04 15:14:04 +08001765 def auto_run(self, starting_at=None, root=None):
1766 '''"Auto-runs" tests that have not been run yet.
Hung-Te Lin96632362012-03-20 21:14:18 +08001767
Jon Salz0697cbf2012-07-04 15:14:04 +08001768 Args:
1769 starting_at: If provide, only auto-runs tests beginning with
1770 this test.
1771 '''
1772 root = root or self.test_list
1773 self.run_tests_with_status([TestState.UNTESTED, TestState.ACTIVE],
1774 starting_at=starting_at,
1775 root=root)
Jon Salz968e90b2012-03-18 16:12:43 +08001776
Jon Salz0697cbf2012-07-04 15:14:04 +08001777 def re_run_failed(self, root=None):
1778 '''Re-runs failed tests.'''
1779 root = root or self.test_list
1780 self.run_tests_with_status([TestState.FAILED], root=root)
Jon Salz57717ca2012-04-04 16:47:25 +08001781
Jon Salz0697cbf2012-07-04 15:14:04 +08001782 def show_review_information(self):
1783 '''Event handler for showing review information screen.
Jon Salz57717ca2012-04-04 16:47:25 +08001784
Jon Salz0697cbf2012-07-04 15:14:04 +08001785 The information screene is rendered by main UI program (ui.py), so in
1786 goofy we only need to kill all active tests, set them as untested, and
1787 clear remaining tests.
1788 '''
1789 self.kill_active_tests(False)
Jon Salza6711d72012-07-18 14:33:03 +08001790 self.cancel_pending_tests()
Jon Salz57717ca2012-04-04 16:47:25 +08001791
Jon Salz0697cbf2012-07-04 15:14:04 +08001792 def handle_switch_test(self, event):
1793 '''Switches to a particular test.
Jon Salz0405ab52012-03-16 15:26:52 +08001794
Jon Salz0697cbf2012-07-04 15:14:04 +08001795 @param event: The SWITCH_TEST event.
1796 '''
1797 test = self.test_list.lookup_path(event.path)
1798 if not test:
1799 logging.error('Unknown test %r', event.key)
1800 return
Jon Salz73e0fd02012-04-04 11:46:38 +08001801
Jon Salz0697cbf2012-07-04 15:14:04 +08001802 invoc = self.invocations.get(test)
1803 if invoc and test.backgroundable:
1804 # Already running: just bring to the front if it
1805 # has a UI.
1806 logging.info('Setting visible test to %s', test.path)
Jon Salz36fbbb52012-07-05 13:45:06 +08001807 self.set_visible_test(test)
Jon Salz0697cbf2012-07-04 15:14:04 +08001808 return
Jon Salz73e0fd02012-04-04 11:46:38 +08001809
Jon Salz0697cbf2012-07-04 15:14:04 +08001810 self.abort_active_tests()
1811 for t in test.walk():
1812 t.update_state(status=TestState.UNTESTED)
Jon Salz73e0fd02012-04-04 11:46:38 +08001813
Jon Salz0697cbf2012-07-04 15:14:04 +08001814 if self.test_list.options.auto_run_on_keypress:
1815 self.auto_run(starting_at=test)
1816 else:
1817 self.run_tests(test)
Jon Salz73e0fd02012-04-04 11:46:38 +08001818
Jon Salz0697cbf2012-07-04 15:14:04 +08001819 def wait(self):
1820 '''Waits for all pending invocations.
1821
1822 Useful for testing.
1823 '''
Jon Salz1acc8742012-07-17 17:45:55 +08001824 while self.invocations:
1825 for k, v in self.invocations.iteritems():
1826 logging.info('Waiting for %s to complete...', k)
1827 v.thread.join()
1828 self.reap_completed_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +08001829
1830 def check_exceptions(self):
1831 '''Raises an error if any exceptions have occurred in
1832 invocation threads.'''
1833 if self.exceptions:
1834 raise RuntimeError('Exception in invocation thread: %r' %
1835 self.exceptions)
1836
1837 def record_exception(self, msg):
1838 '''Records an exception in an invocation thread.
1839
1840 An exception with the given message will be rethrown when
1841 Goofy is destroyed.'''
1842 self.exceptions.append(msg)
Jon Salz73e0fd02012-04-04 11:46:38 +08001843
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001844
1845if __name__ == '__main__':
Jon Salz77c151e2012-08-28 07:20:37 +08001846 goofy = Goofy()
1847 try:
1848 goofy.main()
Jon Salz0f996602012-10-03 15:26:48 +08001849 except SystemExit:
1850 # Propagate SystemExit without logging.
1851 raise
Jon Salz31373eb2012-09-21 16:19:49 +08001852 except:
Jon Salz0f996602012-10-03 15:26:48 +08001853 # Log the error before trying to shut down (unless it's a graceful
1854 # exit).
Jon Salz31373eb2012-09-21 16:19:49 +08001855 logging.exception('Error in main loop')
1856 raise
Jon Salz77c151e2012-08-28 07:20:37 +08001857 finally:
1858 goofy.destroy()