blob: 86b5820b1f766680a08ebeb4d9853a8fdc48d1ec [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),
Jon Salz6dc031d2013-06-19 13:06:23 +0800279 fail=getattr(event, 'fail', False),
280 reason=getattr(event, 'reason', None)),
Jon Salz36fbbb52012-07-05 13:45:06 +0800281 Event.Type.SET_VISIBLE_TEST:
282 lambda event: self.set_visible_test(
283 self.test_list.lookup_path(event.path)),
Jon Salz4712ac72013-02-07 17:12:05 +0800284 Event.Type.CLEAR_STATE:
285 lambda event: self.clear_state(self.test_list.lookup_path(event.path)),
Jon Salz0697cbf2012-07-04 15:14:04 +0800286 }
287
288 self.exceptions = []
289 self.web_socket_manager = None
290
291 def destroy(self):
292 if self.chrome:
293 self.chrome.kill()
294 self.chrome = None
Jon Salzc79a9982012-08-30 04:42:01 +0800295 if self.dummy_shopfloor:
296 self.dummy_shopfloor.kill()
297 self.dummy_shopfloor = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800298 if self.ui_process:
299 utils.kill_process_tree(self.ui_process, 'ui')
300 self.ui_process = None
301 if self.web_socket_manager:
302 logging.info('Stopping web sockets')
303 self.web_socket_manager.close()
304 self.web_socket_manager = None
305 if self.state_server_thread:
306 logging.info('Stopping state server')
307 self.state_server.shutdown()
308 self.state_server_thread.join()
309 self.state_server.server_close()
310 self.state_server_thread = None
311 if self.state_instance:
312 self.state_instance.close()
313 if self.event_server_thread:
314 logging.info('Stopping event server')
315 self.event_server.shutdown() # pylint: disable=E1101
316 self.event_server_thread.join()
317 self.event_server.server_close()
318 self.event_server_thread = None
319 if self.log_watcher:
320 if self.log_watcher.IsThreadStarted():
321 self.log_watcher.StopWatchThread()
322 self.log_watcher = None
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +0800323 if self.system_log_manager:
324 if self.system_log_manager.IsThreadRunning():
325 self.system_log_manager.StopSyncThread()
326 self.system_log_manager = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800327 if self.prespawner:
328 logging.info('Stopping prespawner')
329 self.prespawner.stop()
330 self.prespawner = None
331 if self.event_client:
332 logging.info('Closing event client')
333 self.event_client.close()
334 self.event_client = None
Jon Salzddf0d052013-06-18 12:52:44 +0800335 if self.cpufreq_manager:
336 self.cpufreq_manager.Stop()
Jon Salz0697cbf2012-07-04 15:14:04 +0800337 if self.event_log:
338 self.event_log.Close()
339 self.event_log = None
Dean Liao592e4d52013-01-10 20:06:39 +0800340 if self.key_filter:
341 self.key_filter.Stop()
342
Jon Salz0697cbf2012-07-04 15:14:04 +0800343 self.check_exceptions()
344 logging.info('Done destroying Goofy')
345
346 def start_state_server(self):
347 self.state_instance, self.state_server = (
348 state.create_server(bind_address='0.0.0.0'))
Jon Salz16d10542012-07-23 12:18:45 +0800349 self.goofy_rpc = GoofyRPC(self)
350 self.goofy_rpc.RegisterMethods(self.state_instance)
Jon Salz0697cbf2012-07-04 15:14:04 +0800351 logging.info('Starting state server')
352 self.state_server_thread = threading.Thread(
353 target=self.state_server.serve_forever,
354 name='StateServer')
355 self.state_server_thread.start()
356
357 def start_event_server(self):
358 self.event_server = EventServer()
359 logging.info('Starting factory event server')
360 self.event_server_thread = threading.Thread(
361 target=self.event_server.serve_forever,
362 name='EventServer') # pylint: disable=E1101
363 self.event_server_thread.start()
364
365 self.event_client = EventClient(
366 callback=self.handle_event, event_loop=self.run_queue)
367
368 self.web_socket_manager = WebSocketManager(self.uuid)
369 self.state_server.add_handler("/event",
370 self.web_socket_manager.handle_web_socket)
371
372 def start_ui(self):
373 ui_proc_args = [
374 os.path.join(factory.FACTORY_PACKAGE_PATH, 'test', 'ui.py'),
375 self.options.test_list]
376 if self.options.verbose:
377 ui_proc_args.append('-v')
378 logging.info('Starting ui %s', ui_proc_args)
Jon Salz78c32392012-07-25 14:18:29 +0800379 self.ui_process = Spawn(ui_proc_args)
Jon Salz0697cbf2012-07-04 15:14:04 +0800380 logging.info('Waiting for UI to come up...')
381 self.event_client.wait(
382 lambda event: event.type == Event.Type.UI_READY)
383 logging.info('UI has started')
384
385 def set_visible_test(self, test):
386 if self.visible_test == test:
387 return
Jon Salz2f2d42c2012-07-30 12:30:34 +0800388 if test and not test.has_ui:
389 return
Jon Salz0697cbf2012-07-04 15:14:04 +0800390
391 if test:
392 test.update_state(visible=True)
393 if self.visible_test:
394 self.visible_test.update_state(visible=False)
395 self.visible_test = test
396
Jon Salzd4306c82012-11-30 15:16:36 +0800397 def _log_startup_messages(self):
398 '''Logs the tail of var/log/messages and mosys and EC console logs.'''
399 # TODO(jsalz): This is mostly a copy-and-paste of code in init_states,
400 # for factory-3004.B only. Consolidate and merge back to ToT.
401 if utils.in_chroot():
402 return
403
404 try:
405 var_log_messages = (
406 utils.var_log_messages_before_reboot())
407 logging.info(
408 'Tail of /var/log/messages before last reboot:\n'
409 '%s', ('\n'.join(
410 ' ' + x for x in var_log_messages)))
411 except: # pylint: disable=W0702
412 logging.exception('Unable to grok /var/log/messages')
413
414 try:
415 mosys_log = utils.Spawn(
416 ['mosys', 'eventlog', 'list'],
417 read_stdout=True, log_stderr_on_error=True).stdout_data
418 logging.info('System eventlog from mosys:\n%s\n', mosys_log)
419 except: # pylint: disable=W0702
420 logging.exception('Unable to read mosys eventlog')
421
422 try:
Vic Yang8341dde2013-01-29 16:48:52 +0800423 board = system.GetBoard()
424 ec_console_log = board.GetECConsoleLog()
Jon Salzd4306c82012-11-30 15:16:36 +0800425 logging.info('EC console log after reboot:\n%s\n', ec_console_log)
426 except: # pylint: disable=W0702
427 logging.exception('Error retrieving EC console log')
428
Jon Salz0697cbf2012-07-04 15:14:04 +0800429 def handle_shutdown_complete(self, test, test_state):
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800430 '''
Jon Salz0697cbf2012-07-04 15:14:04 +0800431 Handles the case where a shutdown was detected during a shutdown step.
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800432
Jon Salz0697cbf2012-07-04 15:14:04 +0800433 @param test: The ShutdownStep.
434 @param test_state: The test state.
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800435 '''
Jon Salz0697cbf2012-07-04 15:14:04 +0800436 test_state = test.update_state(increment_shutdown_count=1)
437 logging.info('Detected shutdown (%d of %d)',
438 test_state.shutdown_count, test.iterations)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800439
Jon Salz0697cbf2012-07-04 15:14:04 +0800440 def log_and_update_state(status, error_msg, **kw):
441 self.event_log.Log('rebooted',
442 status=status, error_msg=error_msg, **kw)
Jon Salzd4306c82012-11-30 15:16:36 +0800443 logging.info('Rebooted: status=%s, %s', status,
444 (('error_msg=%s' % error_msg) if error_msg else None))
Jon Salz0697cbf2012-07-04 15:14:04 +0800445 test.update_state(status=status, error_msg=error_msg)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800446
Jon Salz0697cbf2012-07-04 15:14:04 +0800447 if not self.last_shutdown_time:
448 log_and_update_state(status=TestState.FAILED,
449 error_msg='Unable to read shutdown_time')
450 return
Jon Salz258a40c2012-04-19 12:34:01 +0800451
Jon Salz0697cbf2012-07-04 15:14:04 +0800452 now = time.time()
453 logging.info('%.03f s passed since reboot',
454 now - self.last_shutdown_time)
Jon Salz258a40c2012-04-19 12:34:01 +0800455
Jon Salz0697cbf2012-07-04 15:14:04 +0800456 if self.last_shutdown_time > now:
457 test.update_state(status=TestState.FAILED,
458 error_msg='Time moved backward during reboot')
459 elif (isinstance(test, factory.RebootStep) and
460 self.test_list.options.max_reboot_time_secs and
461 (now - self.last_shutdown_time >
462 self.test_list.options.max_reboot_time_secs)):
463 # A reboot took too long; fail. (We don't check this for
464 # HaltSteps, because the machine could be halted for a
465 # very long time, and even unplugged with battery backup,
466 # thus hosing the clock.)
467 log_and_update_state(
468 status=TestState.FAILED,
469 error_msg=('More than %d s elapsed during reboot '
470 '(%.03f s, from %s to %s)' % (
471 self.test_list.options.max_reboot_time_secs,
472 now - self.last_shutdown_time,
473 utils.TimeString(self.last_shutdown_time),
474 utils.TimeString(now))),
475 duration=(now-self.last_shutdown_time))
Jon Salzd4306c82012-11-30 15:16:36 +0800476 self._log_startup_messages()
Jon Salz0697cbf2012-07-04 15:14:04 +0800477 elif test_state.shutdown_count == test.iterations:
478 # Good!
479 log_and_update_state(status=TestState.PASSED,
480 duration=(now - self.last_shutdown_time),
481 error_msg='')
482 elif test_state.shutdown_count > test.iterations:
483 # Shut down too many times
484 log_and_update_state(status=TestState.FAILED,
485 error_msg='Too many shutdowns')
Jon Salzd4306c82012-11-30 15:16:36 +0800486 self._log_startup_messages()
Jon Salz0697cbf2012-07-04 15:14:04 +0800487 elif utils.are_shift_keys_depressed():
488 logging.info('Shift keys are depressed; cancelling restarts')
489 # Abort shutdown
490 log_and_update_state(
491 status=TestState.FAILED,
492 error_msg='Shutdown aborted with double shift keys')
Jon Salza6711d72012-07-18 14:33:03 +0800493 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +0800494 else:
495 def handler():
496 if self._prompt_cancel_shutdown(
497 test, test_state.shutdown_count + 1):
Jon Salza6711d72012-07-18 14:33:03 +0800498 factory.console.info('Shutdown aborted by operator')
Jon Salz0697cbf2012-07-04 15:14:04 +0800499 log_and_update_state(
500 status=TestState.FAILED,
501 error_msg='Shutdown aborted by operator')
Jon Salza6711d72012-07-18 14:33:03 +0800502 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +0800503 return
Jon Salz0405ab52012-03-16 15:26:52 +0800504
Jon Salz0697cbf2012-07-04 15:14:04 +0800505 # Time to shutdown again
506 log_and_update_state(
507 status=TestState.ACTIVE,
508 error_msg='',
509 iteration=test_state.shutdown_count)
Jon Salz73e0fd02012-04-04 11:46:38 +0800510
Jon Salz0697cbf2012-07-04 15:14:04 +0800511 self.event_log.Log('shutdown', operation='reboot')
512 self.state_instance.set_shared_data('shutdown_time',
513 time.time())
514 self.env.shutdown('reboot')
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800515
Jon Salz0697cbf2012-07-04 15:14:04 +0800516 self.on_ui_startup.append(handler)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800517
Jon Salz0697cbf2012-07-04 15:14:04 +0800518 def _prompt_cancel_shutdown(self, test, iteration):
519 if self.options.ui != 'chrome':
520 return False
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800521
Jon Salz0697cbf2012-07-04 15:14:04 +0800522 pending_shutdown_data = {
523 'delay_secs': test.delay_secs,
524 'time': time.time() + test.delay_secs,
525 'operation': test.operation,
526 'iteration': iteration,
527 'iterations': test.iterations,
528 }
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800529
Jon Salz0697cbf2012-07-04 15:14:04 +0800530 # Create a new (threaded) event client since we
531 # don't want to use the event loop for this.
532 with EventClient() as event_client:
533 event_client.post_event(Event(Event.Type.PENDING_SHUTDOWN,
534 **pending_shutdown_data))
535 aborted = event_client.wait(
536 lambda event: event.type == Event.Type.CANCEL_SHUTDOWN,
537 timeout=test.delay_secs) is not None
538 if aborted:
539 event_client.post_event(Event(Event.Type.PENDING_SHUTDOWN))
540 return aborted
Jon Salz258a40c2012-04-19 12:34:01 +0800541
Jon Salz0697cbf2012-07-04 15:14:04 +0800542 def init_states(self):
543 '''
544 Initializes all states on startup.
545 '''
546 for test in self.test_list.get_all_tests():
547 # Make sure the state server knows about all the tests,
548 # defaulting to an untested state.
549 test.update_state(update_parent=False, visible=False)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800550
Jon Salz0697cbf2012-07-04 15:14:04 +0800551 var_log_messages = None
Vic Yanga9c32212012-08-16 20:07:54 +0800552 mosys_log = None
Vic Yange4c275d2012-08-28 01:50:20 +0800553 ec_console_log = None
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800554
Jon Salz0697cbf2012-07-04 15:14:04 +0800555 # Any 'active' tests should be marked as failed now.
556 for test in self.test_list.walk():
Jon Salza6711d72012-07-18 14:33:03 +0800557 if not test.is_leaf():
558 # Don't bother with parents; they will be updated when their
559 # children are updated.
560 continue
561
Jon Salz0697cbf2012-07-04 15:14:04 +0800562 test_state = test.get_state()
563 if test_state.status != TestState.ACTIVE:
564 continue
565 if isinstance(test, factory.ShutdownStep):
566 # Shutdown while the test was active - that's good.
567 self.handle_shutdown_complete(test, test_state)
568 else:
569 # Unexpected shutdown. Grab /var/log/messages for context.
570 if var_log_messages is None:
571 try:
572 var_log_messages = (
573 utils.var_log_messages_before_reboot())
574 # Write it to the log, to make it easier to
575 # correlate with /var/log/messages.
576 logging.info(
577 'Unexpected shutdown. '
578 'Tail of /var/log/messages before last reboot:\n'
579 '%s', ('\n'.join(
580 ' ' + x for x in var_log_messages)))
581 except: # pylint: disable=W0702
582 logging.exception('Unable to grok /var/log/messages')
583 var_log_messages = []
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800584
Jon Salz008f4ea2012-08-28 05:39:45 +0800585 if mosys_log is None and not utils.in_chroot():
586 try:
587 mosys_log = utils.Spawn(
588 ['mosys', 'eventlog', 'list'],
589 read_stdout=True, log_stderr_on_error=True).stdout_data
590 # Write it to the log also.
591 logging.info('System eventlog from mosys:\n%s\n', mosys_log)
592 except: # pylint: disable=W0702
593 logging.exception('Unable to read mosys eventlog')
Vic Yanga9c32212012-08-16 20:07:54 +0800594
Vic Yange4c275d2012-08-28 01:50:20 +0800595 if ec_console_log is None:
596 try:
Vic Yang8341dde2013-01-29 16:48:52 +0800597 board = system.GetBoard()
598 ec_console_log = board.GetECConsoleLog()
Vic Yange4c275d2012-08-28 01:50:20 +0800599 logging.info('EC console log after reboot:\n%s\n', ec_console_log)
Jon Salzfe1f6652012-09-07 05:40:14 +0800600 except: # pylint: disable=W0702
Vic Yange4c275d2012-08-28 01:50:20 +0800601 logging.exception('Error retrieving EC console log')
602
Jon Salz0697cbf2012-07-04 15:14:04 +0800603 error_msg = 'Unexpected shutdown while test was running'
604 self.event_log.Log('end_test',
605 path=test.path,
606 status=TestState.FAILED,
607 invocation=test.get_state().invocation,
608 error_msg=error_msg,
Vic Yanga9c32212012-08-16 20:07:54 +0800609 var_log_messages='\n'.join(var_log_messages),
610 mosys_log=mosys_log)
Jon Salz0697cbf2012-07-04 15:14:04 +0800611 test.update_state(
612 status=TestState.FAILED,
613 error_msg=error_msg)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800614
Jon Salz50efe942012-07-26 11:54:10 +0800615 if not test.never_fails:
616 # For "never_fails" tests (such as "Start"), don't cancel
617 # pending tests, since reboot is expected.
618 factory.console.info('Unexpected shutdown while test %s '
619 'running; cancelling any pending tests',
620 test.path)
621 self.state_instance.set_shared_data('tests_after_shutdown', [])
Jon Salz69806bb2012-07-20 18:05:02 +0800622
Jon Salz008f4ea2012-08-28 05:39:45 +0800623 self.update_skipped_tests()
624
625 def update_skipped_tests(self):
626 '''
627 Updates skipped states based on run_if.
628 '''
629 for t in self.test_list.walk():
630 if t.is_leaf() and t.run_if_table_name:
631 skip = False
632 try:
633 aux = shopfloor.get_selected_aux_data(t.run_if_table_name)
634 value = aux.get(t.run_if_col)
635 if value is not None:
636 skip = (not value) ^ t.run_if_not
637 except ValueError:
638 # Not available; assume it shouldn't be skipped
639 pass
640
641 test_state = t.get_state()
642 if ((not skip) and
643 (test_state.status == TestState.PASSED) and
644 (test_state.error_msg == TestState.SKIPPED_MSG)):
645 # It was marked as skipped before, but now we need to run it.
646 # Mark as untested.
647 t.update_state(skip=skip, status=TestState.UNTESTED, error_msg='')
648 else:
649 t.update_state(skip=skip)
650
Jon Salz0697cbf2012-07-04 15:14:04 +0800651 def show_next_active_test(self):
652 '''
653 Rotates to the next visible active test.
654 '''
655 self.reap_completed_tests()
656 active_tests = [
657 t for t in self.test_list.walk()
658 if t.is_leaf() and t.get_state().status == TestState.ACTIVE]
659 if not active_tests:
660 return
Jon Salz4f6c7172012-06-11 20:45:36 +0800661
Jon Salz0697cbf2012-07-04 15:14:04 +0800662 try:
663 next_test = active_tests[
664 (active_tests.index(self.visible_test) + 1) % len(active_tests)]
665 except ValueError: # visible_test not present in active_tests
666 next_test = active_tests[0]
Jon Salz4f6c7172012-06-11 20:45:36 +0800667
Jon Salz0697cbf2012-07-04 15:14:04 +0800668 self.set_visible_test(next_test)
Jon Salz4f6c7172012-06-11 20:45:36 +0800669
Jon Salz0697cbf2012-07-04 15:14:04 +0800670 def handle_event(self, event):
671 '''
672 Handles an event from the event server.
673 '''
674 handler = self.event_handlers.get(event.type)
675 if handler:
676 handler(event)
677 else:
678 # We don't register handlers for all event types - just ignore
679 # this event.
680 logging.debug('Unbound event type %s', event.type)
Jon Salz4f6c7172012-06-11 20:45:36 +0800681
Vic Yangaabf9fd2013-04-09 18:56:13 +0800682 def check_critical_factory_note(self):
683 '''
684 Returns True if the last factory note is critical.
685 '''
686 notes = self.state_instance.get_shared_data('factory_note', True)
687 return notes and notes[-1]['level'] == 'CRITICAL'
688
Jon Salz0697cbf2012-07-04 15:14:04 +0800689 def run_next_test(self):
690 '''
691 Runs the next eligible test (or tests) in self.tests_to_run.
692 '''
693 self.reap_completed_tests()
Vic Yangaabf9fd2013-04-09 18:56:13 +0800694 if self.tests_to_run and self.check_critical_factory_note():
695 self.tests_to_run.clear()
696 return
Jon Salz0697cbf2012-07-04 15:14:04 +0800697 while self.tests_to_run:
698 logging.debug('Tests to run: %s',
699 [x.path for x in self.tests_to_run])
Jon Salz94eb56f2012-06-12 18:01:12 +0800700
Jon Salz0697cbf2012-07-04 15:14:04 +0800701 test = self.tests_to_run[0]
Jon Salz94eb56f2012-06-12 18:01:12 +0800702
Jon Salz0697cbf2012-07-04 15:14:04 +0800703 if test in self.invocations:
704 logging.info('Next test %s is already running', test.path)
705 self.tests_to_run.popleft()
706 return
Jon Salz94eb56f2012-06-12 18:01:12 +0800707
Jon Salza1412922012-07-23 16:04:17 +0800708 for requirement in test.require_run:
709 for i in requirement.test.walk():
710 if i.get_state().status == TestState.ACTIVE:
Jon Salz304a75d2012-07-06 11:14:15 +0800711 logging.info('Waiting for active test %s to complete '
Jon Salza1412922012-07-23 16:04:17 +0800712 'before running %s', i.path, test.path)
Jon Salz304a75d2012-07-06 11:14:15 +0800713 return
714
Jon Salz0697cbf2012-07-04 15:14:04 +0800715 if self.invocations and not (test.backgroundable and all(
716 [x.backgroundable for x in self.invocations])):
717 logging.debug('Waiting for non-backgroundable tests to '
718 'complete before running %s', test.path)
719 return
Jon Salz94eb56f2012-06-12 18:01:12 +0800720
Jon Salz3e6f5202012-10-15 15:08:29 +0800721 if test.get_state().skip:
722 factory.console.info('Skipping test %s', test.path)
723 test.update_state(status=TestState.PASSED,
724 error_msg=TestState.SKIPPED_MSG)
725 self.tests_to_run.popleft()
726 continue
727
Jon Salz0697cbf2012-07-04 15:14:04 +0800728 self.tests_to_run.popleft()
Jon Salz94eb56f2012-06-12 18:01:12 +0800729
Jon Salz304a75d2012-07-06 11:14:15 +0800730 untested = set()
Jon Salza1412922012-07-23 16:04:17 +0800731 for requirement in test.require_run:
732 for i in requirement.test.walk():
733 if i == test:
Jon Salz304a75d2012-07-06 11:14:15 +0800734 # We've hit this test itself; stop checking
735 break
Jon Salza1412922012-07-23 16:04:17 +0800736 if ((i.get_state().status == TestState.UNTESTED) or
737 (requirement.passed and i.get_state().status !=
738 TestState.PASSED)):
Jon Salz304a75d2012-07-06 11:14:15 +0800739 # Found an untested test; move on to the next
740 # element in require_run.
Jon Salza1412922012-07-23 16:04:17 +0800741 untested.add(i)
Jon Salz304a75d2012-07-06 11:14:15 +0800742 break
743
744 if untested:
745 untested_paths = ', '.join(sorted([x.path for x in untested]))
746 if self.state_instance.get_shared_data('engineering_mode',
747 optional=True):
748 # In engineering mode, we'll let it go.
749 factory.console.warn('In engineering mode; running '
750 '%s even though required tests '
751 '[%s] have not completed',
752 test.path, untested_paths)
753 else:
754 # Not in engineering mode; mark it failed.
755 error_msg = ('Required tests [%s] have not been run yet'
756 % untested_paths)
757 factory.console.error('Not running %s: %s',
758 test.path, error_msg)
759 test.update_state(status=TestState.FAILED,
760 error_msg=error_msg)
761 continue
762
Jon Salz0697cbf2012-07-04 15:14:04 +0800763 if isinstance(test, factory.ShutdownStep):
764 if os.path.exists(NO_REBOOT_FILE):
765 test.update_state(
766 status=TestState.FAILED, increment_count=1,
767 error_msg=('Skipped shutdown since %s is present' %
Jon Salz304a75d2012-07-06 11:14:15 +0800768 NO_REBOOT_FILE))
Jon Salz0697cbf2012-07-04 15:14:04 +0800769 continue
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800770
Jon Salz0697cbf2012-07-04 15:14:04 +0800771 test.update_state(status=TestState.ACTIVE, increment_count=1,
772 error_msg='', shutdown_count=0)
773 if self._prompt_cancel_shutdown(test, 1):
774 self.event_log.Log('reboot_cancelled')
775 test.update_state(
776 status=TestState.FAILED, increment_count=1,
777 error_msg='Shutdown aborted by operator',
778 shutdown_count=0)
chungyiafe8f772012-08-15 19:36:29 +0800779 continue
Jon Salz2f757d42012-06-27 17:06:42 +0800780
Jon Salz0697cbf2012-07-04 15:14:04 +0800781 # Save pending test list in the state server
Jon Salzdbf398f2012-06-14 17:30:01 +0800782 self.state_instance.set_shared_data(
Jon Salz0697cbf2012-07-04 15:14:04 +0800783 'tests_after_shutdown',
784 [t.path for t in self.tests_to_run])
785 # Save shutdown time
786 self.state_instance.set_shared_data('shutdown_time',
787 time.time())
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800788
Jon Salz0697cbf2012-07-04 15:14:04 +0800789 with self.env.lock:
790 self.event_log.Log('shutdown', operation=test.operation)
791 shutdown_result = self.env.shutdown(test.operation)
792 if shutdown_result:
793 # That's all, folks!
794 self.run_queue.put(None)
795 return
796 else:
797 # Just pass (e.g., in the chroot).
798 test.update_state(status=TestState.PASSED)
799 self.state_instance.set_shared_data(
800 'tests_after_shutdown', None)
801 # Send event with no fields to indicate that there is no
802 # longer a pending shutdown.
803 self.event_client.post_event(Event(
804 Event.Type.PENDING_SHUTDOWN))
805 continue
Jon Salz258a40c2012-04-19 12:34:01 +0800806
Cheng-Yi Chiangce05c002013-04-04 02:13:17 +0800807 self._run_test(test, test.iterations, test.retries)
Jon Salz1acc8742012-07-17 17:45:55 +0800808
Cheng-Yi Chiangce05c002013-04-04 02:13:17 +0800809 def _run_test(self, test, iterations_left=None, retries_left=None):
Jon Salz1acc8742012-07-17 17:45:55 +0800810 invoc = TestInvocation(self, test, on_completion=self.run_next_test)
811 new_state = test.update_state(
812 status=TestState.ACTIVE, increment_count=1, error_msg='',
Jon Salzbd42ce12012-09-18 08:03:59 +0800813 invocation=invoc.uuid, iterations_left=iterations_left,
Cheng-Yi Chiangce05c002013-04-04 02:13:17 +0800814 retries_left=retries_left,
Jon Salzbd42ce12012-09-18 08:03:59 +0800815 visible=(self.visible_test == test))
Jon Salz1acc8742012-07-17 17:45:55 +0800816 invoc.count = new_state.count
817
818 self.invocations[test] = invoc
819 if self.visible_test is None and test.has_ui:
820 self.set_visible_test(test)
Vic Yang311ddb82012-09-26 12:08:28 +0800821 self.check_exclusive()
Jon Salz1acc8742012-07-17 17:45:55 +0800822 invoc.start()
Jon Salz5f2a0672012-05-22 17:14:06 +0800823
Vic Yang311ddb82012-09-26 12:08:28 +0800824 def check_exclusive(self):
Jon Salzce6a7f82013-06-10 18:22:54 +0800825 # alias since this is really long
826 EXCL_OPT = factory.FactoryTest.EXCLUSIVE_OPTIONS
827
Vic Yang311ddb82012-09-26 12:08:28 +0800828 current_exclusive_items = set([
Jon Salzce6a7f82013-06-10 18:22:54 +0800829 item for item in EXCL_OPT
Vic Yang311ddb82012-09-26 12:08:28 +0800830 if any([test.is_exclusive(item) for test in self.invocations])])
831
832 new_exclusive_items = current_exclusive_items - self.exclusive_items
Jon Salzce6a7f82013-06-10 18:22:54 +0800833 if EXCL_OPT.NETWORKING in new_exclusive_items:
Vic Yang311ddb82012-09-26 12:08:28 +0800834 logging.info('Disabling network')
835 self.connection_manager.DisableNetworking()
Jon Salzce6a7f82013-06-10 18:22:54 +0800836 if EXCL_OPT.CHARGER in new_exclusive_items:
Vic Yang311ddb82012-09-26 12:08:28 +0800837 logging.info('Stop controlling charger')
838
839 new_non_exclusive_items = self.exclusive_items - current_exclusive_items
Jon Salzce6a7f82013-06-10 18:22:54 +0800840 if EXCL_OPT.NETWORKING in new_non_exclusive_items:
Vic Yang311ddb82012-09-26 12:08:28 +0800841 logging.info('Re-enabling network')
842 self.connection_manager.EnableNetworking()
Jon Salzce6a7f82013-06-10 18:22:54 +0800843 if EXCL_OPT.CHARGER in new_non_exclusive_items:
Vic Yang311ddb82012-09-26 12:08:28 +0800844 logging.info('Start controlling charger')
845
Jon Salzce6a7f82013-06-10 18:22:54 +0800846 if self.cpufreq_manager:
847 enabled = EXCL_OPT.CPUFREQ not in current_exclusive_items
848 try:
849 self.cpufreq_manager.SetEnabled(enabled)
850 except: # pylint: disable=W0702
851 logging.exception('Unable to %s cpufreq services',
852 'enable' if enabled else 'disable')
853
Vic Yang311ddb82012-09-26 12:08:28 +0800854 # Only adjust charge state if not excluded
Jon Salzce6a7f82013-06-10 18:22:54 +0800855 if (EXCL_OPT.CHARGER not in current_exclusive_items and
856 not utils.in_chroot()):
Cheng-Yi Chiangd8186952013-04-04 23:41:14 +0800857 if self.charge_manager:
858 self.charge_manager.AdjustChargeState()
859 else:
860 try:
861 system.GetBoard().SetChargeState(Board.ChargeState.CHARGE)
862 except BoardException:
863 logging.exception('Unable to set charge state on this board')
Vic Yang311ddb82012-09-26 12:08:28 +0800864
865 self.exclusive_items = current_exclusive_items
Jon Salz5da61e62012-05-31 13:06:22 +0800866
cychiang21886742012-07-05 15:16:32 +0800867 def check_for_updates(self):
868 '''
869 Schedules an asynchronous check for updates if necessary.
870 '''
871 if not self.test_list.options.update_period_secs:
872 # Not enabled.
873 return
874
875 now = time.time()
876 if self.last_update_check and (
877 now - self.last_update_check <
878 self.test_list.options.update_period_secs):
879 # Not yet time for another check.
880 return
881
882 self.last_update_check = now
883
884 def handle_check_for_update(reached_shopfloor, md5sum, needs_update):
885 if reached_shopfloor:
886 new_update_md5sum = md5sum if needs_update else None
887 if system.SystemInfo.update_md5sum != new_update_md5sum:
888 logging.info('Received new update MD5SUM: %s', new_update_md5sum)
889 system.SystemInfo.update_md5sum = new_update_md5sum
890 self.run_queue.put(self.update_system_info)
891
892 updater.CheckForUpdateAsync(
893 handle_check_for_update,
894 self.test_list.options.shopfloor_timeout_secs)
895
Jon Salza6711d72012-07-18 14:33:03 +0800896 def cancel_pending_tests(self):
897 '''Cancels any tests in the run queue.'''
898 self.run_tests([])
899
Jon Salz0697cbf2012-07-04 15:14:04 +0800900 def run_tests(self, subtrees, untested_only=False):
901 '''
902 Runs tests under subtree.
Jon Salz258a40c2012-04-19 12:34:01 +0800903
Jon Salz0697cbf2012-07-04 15:14:04 +0800904 The tests are run in order unless one fails (then stops).
905 Backgroundable tests are run simultaneously; when a foreground test is
906 encountered, we wait for all active tests to finish before continuing.
Jon Salzb1b39092012-05-03 02:05:09 +0800907
Jon Salz0697cbf2012-07-04 15:14:04 +0800908 @param subtrees: Node or nodes containing tests to run (may either be
909 a single test or a list). Duplicates will be ignored.
910 '''
911 if type(subtrees) != list:
912 subtrees = [subtrees]
Jon Salz258a40c2012-04-19 12:34:01 +0800913
Jon Salz0697cbf2012-07-04 15:14:04 +0800914 # Nodes we've seen so far, to avoid duplicates.
915 seen = set()
Jon Salz94eb56f2012-06-12 18:01:12 +0800916
Jon Salz0697cbf2012-07-04 15:14:04 +0800917 self.tests_to_run = deque()
918 for subtree in subtrees:
919 for test in subtree.walk():
920 if test in seen:
921 continue
922 seen.add(test)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800923
Jon Salz0697cbf2012-07-04 15:14:04 +0800924 if not test.is_leaf():
925 continue
926 if (untested_only and
927 test.get_state().status != TestState.UNTESTED):
928 continue
929 self.tests_to_run.append(test)
930 self.run_next_test()
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800931
Jon Salz0697cbf2012-07-04 15:14:04 +0800932 def reap_completed_tests(self):
933 '''
934 Removes completed tests from the set of active tests.
935
936 Also updates the visible test if it was reaped.
937 '''
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +0800938 test_completed = False
Jon Salz0697cbf2012-07-04 15:14:04 +0800939 for t, v in dict(self.invocations).iteritems():
940 if v.is_completed():
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +0800941 test_completed = True
Jon Salz1acc8742012-07-17 17:45:55 +0800942 new_state = t.update_state(**v.update_state_on_completion)
Jon Salz0697cbf2012-07-04 15:14:04 +0800943 del self.invocations[t]
944
Chun-Ta Lin54e17e42012-09-06 22:05:13 +0800945 # Stop on failure if flag is true.
946 if (self.test_list.options.stop_on_failure and
947 new_state.status == TestState.FAILED):
948 # Clean all the tests to cause goofy to stop.
949 self.tests_to_run = []
950 factory.console.info("Stop on failure triggered. Empty the queue.")
951
Jon Salz1acc8742012-07-17 17:45:55 +0800952 if new_state.iterations_left and new_state.status == TestState.PASSED:
953 # Play it again, Sam!
954 self._run_test(t)
Cheng-Yi Chiangce05c002013-04-04 02:13:17 +0800955 # new_state.retries_left is obtained after update.
956 # For retries_left == 0, test can still be run for the last time.
957 elif (new_state.retries_left >= 0 and
958 new_state.status == TestState.FAILED):
959 # Still have to retry, Sam!
960 self._run_test(t)
Jon Salz1acc8742012-07-17 17:45:55 +0800961
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +0800962 if test_completed:
Vic Yangf01c59f2013-04-19 17:37:56 +0800963 self.log_watcher.KickWatchThread()
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +0800964
Jon Salz0697cbf2012-07-04 15:14:04 +0800965 if (self.visible_test is None or
Jon Salz85a39882012-07-05 16:45:04 +0800966 self.visible_test not in self.invocations):
Jon Salz0697cbf2012-07-04 15:14:04 +0800967 self.set_visible_test(None)
968 # Make the first running test, if any, the visible test
969 for t in self.test_list.walk():
970 if t in self.invocations:
971 self.set_visible_test(t)
972 break
973
Jon Salz6dc031d2013-06-19 13:06:23 +0800974 def kill_active_tests(self, abort, root=None, reason=None):
Jon Salz0697cbf2012-07-04 15:14:04 +0800975 '''
976 Kills and waits for all active tests.
977
Jon Salz85a39882012-07-05 16:45:04 +0800978 Args:
979 abort: True to change state of killed tests to FAILED, False for
Jon Salz0697cbf2012-07-04 15:14:04 +0800980 UNTESTED.
Jon Salz85a39882012-07-05 16:45:04 +0800981 root: If set, only kills tests with root as an ancestor.
Jon Salz0697cbf2012-07-04 15:14:04 +0800982 '''
983 self.reap_completed_tests()
984 for test, invoc in self.invocations.items():
Jon Salz85a39882012-07-05 16:45:04 +0800985 if root and not test.has_ancestor(root):
986 continue
987
Jon Salz0697cbf2012-07-04 15:14:04 +0800988 factory.console.info('Killing active test %s...' % test.path)
Jon Salz6dc031d2013-06-19 13:06:23 +0800989 invoc.abort_and_join(reason)
Jon Salz0697cbf2012-07-04 15:14:04 +0800990 factory.console.info('Killed %s' % test.path)
Jon Salz1acc8742012-07-17 17:45:55 +0800991 test.update_state(**invoc.update_state_on_completion)
Jon Salz0697cbf2012-07-04 15:14:04 +0800992 del self.invocations[test]
Jon Salz1acc8742012-07-17 17:45:55 +0800993
Jon Salz0697cbf2012-07-04 15:14:04 +0800994 if not abort:
995 test.update_state(status=TestState.UNTESTED)
996 self.reap_completed_tests()
997
Jon Salz6dc031d2013-06-19 13:06:23 +0800998 def stop(self, root=None, fail=False, reason=None):
999 self.kill_active_tests(fail, root, reason)
Jon Salz85a39882012-07-05 16:45:04 +08001000 # Remove any tests in the run queue under the root.
1001 self.tests_to_run = deque([x for x in self.tests_to_run
1002 if root and not x.has_ancestor(root)])
1003 self.run_next_test()
Jon Salz0697cbf2012-07-04 15:14:04 +08001004
Jon Salz4712ac72013-02-07 17:12:05 +08001005 def clear_state(self, root=None):
Jon Salz6dc031d2013-06-19 13:06:23 +08001006 self.stop(root, reason='Clearing test state')
Jon Salz4712ac72013-02-07 17:12:05 +08001007 for f in root.walk():
1008 if f.is_leaf():
1009 f.update_state(status=TestState.UNTESTED)
1010
Jon Salz6dc031d2013-06-19 13:06:23 +08001011 def abort_active_tests(self, reason=None):
1012 self.kill_active_tests(True, reason=reason)
Jon Salz0697cbf2012-07-04 15:14:04 +08001013
1014 def main(self):
1015 try:
1016 self.init()
1017 self.event_log.Log('goofy_init',
1018 success=True)
1019 except:
1020 if self.event_log:
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001021 try:
Jon Salz0697cbf2012-07-04 15:14:04 +08001022 self.event_log.Log('goofy_init',
1023 success=False,
1024 trace=traceback.format_exc())
1025 except: # pylint: disable=W0702
1026 pass
1027 raise
1028
1029 self.run()
1030
1031 def update_system_info(self):
1032 '''Updates system info.'''
1033 system_info = system.SystemInfo()
1034 self.state_instance.set_shared_data('system_info', system_info.__dict__)
1035 self.event_client.post_event(Event(Event.Type.SYSTEM_INFO,
1036 system_info=system_info.__dict__))
1037 logging.info('System info: %r', system_info.__dict__)
1038
Jon Salzeb42f0d2012-07-27 19:14:04 +08001039 def update_factory(self, auto_run_on_restart=False, post_update_hook=None):
1040 '''Commences updating factory software.
1041
1042 Args:
1043 auto_run_on_restart: Auto-run when the machine comes back up.
1044 post_update_hook: Code to call after update but immediately before
1045 restart.
1046
1047 Returns:
1048 Never if the update was successful (we just reboot).
1049 False if the update was unnecessary (no update available).
1050 '''
Jon Salz6dc031d2013-06-19 13:06:23 +08001051 self.kill_active_tests(False, reason='Factory software update')
Jon Salza6711d72012-07-18 14:33:03 +08001052 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +08001053
Jon Salz5c344f62012-07-13 14:31:16 +08001054 def pre_update_hook():
1055 if auto_run_on_restart:
1056 self.state_instance.set_shared_data('tests_after_shutdown',
1057 FORCE_AUTO_RUN)
1058 self.state_instance.close()
1059
Jon Salzeb42f0d2012-07-27 19:14:04 +08001060 if updater.TryUpdate(pre_update_hook=pre_update_hook):
1061 if post_update_hook:
1062 post_update_hook()
1063 self.env.shutdown('reboot')
Jon Salz0697cbf2012-07-04 15:14:04 +08001064
Jon Salzcef132a2012-08-30 04:58:08 +08001065 def handle_sigint(self, dummy_signum, dummy_frame):
Jon Salz77c151e2012-08-28 07:20:37 +08001066 logging.error('Received SIGINT')
1067 self.run_queue.put(None)
1068 raise KeyboardInterrupt()
1069
Jon Salz0697cbf2012-07-04 15:14:04 +08001070 def init(self, args=None, env=None):
1071 '''Initializes Goofy.
1072
1073 Args:
1074 args: A list of command-line arguments. Uses sys.argv if
1075 args is None.
1076 env: An Environment instance to use (or None to choose
1077 FakeChrootEnvironment or DUTEnvironment as appropriate).
1078 '''
Jon Salz77c151e2012-08-28 07:20:37 +08001079 signal.signal(signal.SIGINT, self.handle_sigint)
1080
Jon Salz0697cbf2012-07-04 15:14:04 +08001081 parser = OptionParser()
1082 parser.add_option('-v', '--verbose', dest='verbose',
Jon Salz8fa8e832012-07-13 19:04:09 +08001083 action='store_true',
1084 help='Enable debug logging')
Jon Salz0697cbf2012-07-04 15:14:04 +08001085 parser.add_option('--print_test_list', dest='print_test_list',
Jon Salz8fa8e832012-07-13 19:04:09 +08001086 metavar='FILE',
1087 help='Read and print test list FILE, and exit')
Jon Salz0697cbf2012-07-04 15:14:04 +08001088 parser.add_option('--restart', dest='restart',
Jon Salz8fa8e832012-07-13 19:04:09 +08001089 action='store_true',
1090 help='Clear all test state')
Jon Salz0697cbf2012-07-04 15:14:04 +08001091 parser.add_option('--ui', dest='ui', type='choice',
Jon Salz8fa8e832012-07-13 19:04:09 +08001092 choices=['none', 'gtk', 'chrome'],
Jon Salz2f881df2013-02-01 17:00:35 +08001093 default='chrome',
Jon Salz8fa8e832012-07-13 19:04:09 +08001094 help='UI to use')
Jon Salz0697cbf2012-07-04 15:14:04 +08001095 parser.add_option('--ui_scale_factor', dest='ui_scale_factor',
Jon Salz8fa8e832012-07-13 19:04:09 +08001096 type='int', default=1,
1097 help=('Factor by which to scale UI '
1098 '(Chrome UI only)'))
Jon Salz0697cbf2012-07-04 15:14:04 +08001099 parser.add_option('--test_list', dest='test_list',
Jon Salz8fa8e832012-07-13 19:04:09 +08001100 metavar='FILE',
1101 help='Use FILE as test list')
Jon Salzc79a9982012-08-30 04:42:01 +08001102 parser.add_option('--dummy_shopfloor', action='store_true',
1103 help='Use a dummy shopfloor server')
chungyiafe8f772012-08-15 19:36:29 +08001104 parser.add_option('--automation', dest='automation',
1105 action='store_true',
1106 help='Enable automation on running factory test')
Ricky Liang09216dc2013-02-22 17:26:45 +08001107 parser.add_option('--one_pixel_less', dest='one_pixel_less',
1108 action='store_true',
1109 help=('Start Chrome one pixel less than the full screen.'
1110 'Needed by Exynos platform to run GTK.'))
Jon Salz0697cbf2012-07-04 15:14:04 +08001111 (self.options, self.args) = parser.parse_args(args)
1112
Jon Salz46b89562012-07-05 11:49:22 +08001113 # Make sure factory directories exist.
1114 factory.get_log_root()
1115 factory.get_state_root()
1116 factory.get_test_data_root()
1117
Jon Salz0697cbf2012-07-04 15:14:04 +08001118 global _inited_logging # pylint: disable=W0603
1119 if not _inited_logging:
1120 factory.init_logging('goofy', verbose=self.options.verbose)
1121 _inited_logging = True
Jon Salz8fa8e832012-07-13 19:04:09 +08001122
Jon Salz0f996602012-10-03 15:26:48 +08001123 if self.options.print_test_list:
1124 print factory.read_test_list(
1125 self.options.print_test_list).__repr__(recursive=True)
1126 sys.exit(0)
1127
Jon Salzee85d522012-07-17 14:34:46 +08001128 event_log.IncrementBootSequence()
Jon Salzd15bbcf2013-05-21 17:33:57 +08001129 # Don't defer logging the initial event, so we can make sure
1130 # that device_id, reimage_id, etc. are all set up.
1131 self.event_log = EventLog('goofy', defer=False)
Jon Salz0697cbf2012-07-04 15:14:04 +08001132
1133 if (not suppress_chroot_warning and
1134 factory.in_chroot() and
1135 self.options.ui == 'gtk' and
1136 os.environ.get('DISPLAY') in [None, '', ':0', ':0.0']):
1137 # That's not going to work! Tell the user how to run
1138 # this way.
1139 logging.warn(GOOFY_IN_CHROOT_WARNING)
1140 time.sleep(1)
1141
1142 if env:
1143 self.env = env
1144 elif factory.in_chroot():
1145 self.env = test_environment.FakeChrootEnvironment()
1146 logging.warn(
1147 'Using chroot environment: will not actually run autotests')
1148 else:
1149 self.env = test_environment.DUTEnvironment()
1150 self.env.goofy = self
1151
1152 if self.options.restart:
1153 state.clear_state()
1154
Jon Salz0697cbf2012-07-04 15:14:04 +08001155 if self.options.ui_scale_factor != 1 and utils.in_qemu():
1156 logging.warn(
1157 'In QEMU; ignoring ui_scale_factor argument')
1158 self.options.ui_scale_factor = 1
1159
1160 logging.info('Started')
1161
1162 self.start_state_server()
1163 self.state_instance.set_shared_data('hwid_cfg', get_hwid_cfg())
1164 self.state_instance.set_shared_data('ui_scale_factor',
Ricky Liang09216dc2013-02-22 17:26:45 +08001165 self.options.ui_scale_factor)
1166 self.state_instance.set_shared_data('one_pixel_less',
1167 self.options.one_pixel_less)
Jon Salz0697cbf2012-07-04 15:14:04 +08001168 self.last_shutdown_time = (
1169 self.state_instance.get_shared_data('shutdown_time', optional=True))
1170 self.state_instance.del_shared_data('shutdown_time', optional=True)
1171
Jon Salzb19ea072013-02-07 16:35:00 +08001172 self.state_instance.del_shared_data('startup_error', optional=True)
Jon Salz0697cbf2012-07-04 15:14:04 +08001173 if not self.options.test_list:
1174 self.options.test_list = find_test_list()
Jon Salzb19ea072013-02-07 16:35:00 +08001175 if self.options.test_list:
Jon Salz0697cbf2012-07-04 15:14:04 +08001176 logging.info('Using test list %s', self.options.test_list)
Jon Salzb19ea072013-02-07 16:35:00 +08001177 try:
1178 self.test_list = factory.read_test_list(
1179 self.options.test_list,
1180 self.state_instance)
1181 except: # pylint: disable=W0702
1182 logging.exception('Unable to read test list %r', self.options.test_list)
1183 self.state_instance.set_shared_data('startup_error',
1184 'Unable to read test list %s\n%s' % (
1185 self.options.test_list,
1186 traceback.format_exc()))
1187 else:
1188 logging.error('No test list found.')
1189 self.state_instance.set_shared_data('startup_error',
1190 'No test list found.')
Jon Salz0697cbf2012-07-04 15:14:04 +08001191
Jon Salzb19ea072013-02-07 16:35:00 +08001192 if not self.test_list:
1193 if self.options.ui == 'chrome':
1194 # Create an empty test list with default options so that the rest of
1195 # startup can proceed.
1196 self.test_list = factory.FactoryTestList(
1197 [], self.state_instance, factory.Options())
1198 else:
1199 # Bail with an error; no point in starting up.
1200 sys.exit('No valid test list; exiting.')
1201
Jon Salz822838b2013-03-25 17:32:33 +08001202 if self.test_list.options.clear_state_on_start:
1203 self.state_instance.clear_test_state()
1204
Vic Yang3e1cf5d2013-06-05 18:50:24 +08001205 if system.SystemInfo().firmware_version is None and not utils.in_chroot():
Vic Yang9bd4f772013-06-04 17:34:00 +08001206 self.state_instance.set_shared_data('startup_error',
1207 'Netboot firmware detected\n'
1208 'Connect Ethernet and reboot to re-image.\n'
1209 u'侦测到网路开机固件\n'
1210 u'请连接乙太网并重启')
1211
Jon Salz0697cbf2012-07-04 15:14:04 +08001212 if not self.state_instance.has_shared_data('ui_lang'):
1213 self.state_instance.set_shared_data('ui_lang',
1214 self.test_list.options.ui_lang)
1215 self.state_instance.set_shared_data(
1216 'test_list_options',
1217 self.test_list.options.__dict__)
1218 self.state_instance.test_list = self.test_list
1219
Jon Salz83ef34b2012-11-01 19:46:35 +08001220 if not utils.in_chroot() and self.test_list.options.disable_log_rotation:
1221 open('/var/lib/cleanup_logs_paused', 'w').close()
1222
Jon Salz23926422012-09-01 03:38:13 +08001223 if self.options.dummy_shopfloor:
1224 os.environ[shopfloor.SHOPFLOOR_SERVER_ENV_VAR_NAME] = (
1225 'http://localhost:%d/' % shopfloor.DEFAULT_SERVER_PORT)
1226 self.dummy_shopfloor = Spawn(
1227 [os.path.join(factory.FACTORY_PATH, 'bin', 'shopfloor_server'),
1228 '--dummy'])
1229 elif self.test_list.options.shopfloor_server_url:
1230 shopfloor.set_server_url(self.test_list.options.shopfloor_server_url)
Jon Salz2bf2f6b2013-03-28 18:49:26 +08001231 shopfloor.set_enabled(True)
Jon Salz23926422012-09-01 03:38:13 +08001232
Jon Salz0f996602012-10-03 15:26:48 +08001233 if self.test_list.options.time_sanitizer and not utils.in_chroot():
Jon Salz8fa8e832012-07-13 19:04:09 +08001234 self.time_sanitizer = time_sanitizer.TimeSanitizer(
1235 base_time=time_sanitizer.GetBaseTimeFromFile(
1236 # lsb-factory is written by the factory install shim during
1237 # installation, so it should have a good time obtained from
Jon Salz54882d02012-08-31 01:57:54 +08001238 # the mini-Omaha server. If it's not available, we'll use
1239 # /etc/lsb-factory (which will be much older, but reasonably
1240 # sane) and rely on a shopfloor sync to set a more accurate
1241 # time.
1242 '/usr/local/etc/lsb-factory',
1243 '/etc/lsb-release'))
Jon Salz8fa8e832012-07-13 19:04:09 +08001244 self.time_sanitizer.RunOnce()
1245
Jon Salz0697cbf2012-07-04 15:14:04 +08001246 self.init_states()
1247 self.start_event_server()
1248 self.connection_manager = self.env.create_connection_manager(
Tai-Hsu Lin371351a2012-08-27 14:17:14 +08001249 self.test_list.options.wlans,
1250 self.test_list.options.scan_wifi_period_secs)
Jon Salz0697cbf2012-07-04 15:14:04 +08001251 # Note that we create a log watcher even if
1252 # sync_event_log_period_secs isn't set (no background
1253 # syncing), since we may use it to flush event logs as well.
1254 self.log_watcher = EventLogWatcher(
1255 self.test_list.options.sync_event_log_period_secs,
Jon Salzd15bbcf2013-05-21 17:33:57 +08001256 event_log_db_file=None,
Jon Salz16d10542012-07-23 12:18:45 +08001257 handle_event_logs_callback=self.handle_event_logs)
Jon Salz0697cbf2012-07-04 15:14:04 +08001258 if self.test_list.options.sync_event_log_period_secs:
1259 self.log_watcher.StartWatchThread()
1260
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +08001261 # Note that we create a system log manager even if
1262 # sync_log_period_secs isn't set (no background
1263 # syncing), since we may kick it to sync logs in its
1264 # thread.
1265 self.system_log_manager = SystemLogManager(
Cheng-Yi Chiang835f2682013-05-06 22:15:48 +08001266 sync_log_paths=self.test_list.options.sync_log_paths,
1267 sync_period_sec=self.test_list.options.sync_log_period_secs,
1268 clear_log_paths=self.test_list.options.clear_log_paths)
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +08001269 self.system_log_manager.StartSyncThread()
1270
Jon Salz0697cbf2012-07-04 15:14:04 +08001271 self.update_system_info()
1272
Vic Yang4953fc12012-07-26 16:19:53 +08001273 assert ((self.test_list.options.min_charge_pct is None) ==
1274 (self.test_list.options.max_charge_pct is None))
Vic Yange83d9a12013-04-19 20:00:20 +08001275 if utils.in_chroot():
1276 logging.info('In chroot, ignoring charge manager and charge state')
1277 elif self.test_list.options.min_charge_pct is not None:
Vic Yang4953fc12012-07-26 16:19:53 +08001278 self.charge_manager = ChargeManager(self.test_list.options.min_charge_pct,
1279 self.test_list.options.max_charge_pct)
Jon Salzad7353b2012-10-15 16:22:46 +08001280 system.SystemStatus.charge_manager = self.charge_manager
Cheng-Yi Chiangd8186952013-04-04 23:41:14 +08001281 else:
1282 # Goofy should set charger state to charge if charge_manager is disabled.
1283 try:
1284 system.GetBoard().SetChargeState(Board.ChargeState.CHARGE)
1285 except BoardException:
1286 logging.exception('Unable to set charge state on this board')
Vic Yang4953fc12012-07-26 16:19:53 +08001287
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001288 self.core_dump_manager = CoreDumpManager(
1289 self.test_list.options.core_dump_watchlist)
1290
Jon Salz0697cbf2012-07-04 15:14:04 +08001291 os.environ['CROS_FACTORY'] = '1'
1292 os.environ['CROS_DISABLE_SITE_SYSINFO'] = '1'
1293
1294 # Set CROS_UI since some behaviors in ui.py depend on the
1295 # particular UI in use. TODO(jsalz): Remove this (and all
1296 # places it is used) when the GTK UI is removed.
1297 os.environ['CROS_UI'] = self.options.ui
1298
Jon Salz416f9cc2013-05-10 18:32:50 +08001299 # Initialize hooks.
1300 module, cls = self.test_list.options.hooks_class.rsplit('.', 1)
1301 self.hooks = getattr(__import__(module, fromlist=[cls]), cls)()
1302 assert isinstance(self.hooks, factory.Hooks), (
1303 "hooks should be of type Hooks but is %r" % type(self.hooks))
1304 self.hooks.test_list = self.test_list
1305
Jon Salzce6a7f82013-06-10 18:22:54 +08001306 if not utils.in_chroot():
Jon Salzddf0d052013-06-18 12:52:44 +08001307 self.cpufreq_manager = CpufreqManager(event_log=self.event_log)
Jon Salzce6a7f82013-06-10 18:22:54 +08001308
Jon Salz416f9cc2013-05-10 18:32:50 +08001309 # Call startup hook.
1310 self.hooks.OnStartup()
1311
Jon Salz0697cbf2012-07-04 15:14:04 +08001312 if self.options.ui == 'chrome':
1313 self.env.launch_chrome()
1314 logging.info('Waiting for a web socket connection')
Cheng-Yi Chiangfd8ed392013-03-08 21:37:31 +08001315 self.web_socket_manager.wait()
Jon Salz0697cbf2012-07-04 15:14:04 +08001316
1317 # Wait for the test widget size to be set; this is done in
1318 # an asynchronous RPC so there is a small chance that the
1319 # web socket might be opened first.
1320 for _ in range(100): # 10 s
1321 try:
1322 if self.state_instance.get_shared_data('test_widget_size'):
1323 break
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001324 except KeyError:
Jon Salz0697cbf2012-07-04 15:14:04 +08001325 pass # Retry
1326 time.sleep(0.1) # 100 ms
1327 else:
1328 logging.warn('Never received test_widget_size from UI')
Jon Salz45297282013-05-18 14:31:47 +08001329
1330 # Send Chrome a Tab to get focus to the factory UI
1331 # (http://crosbug.com/p/19444). TODO(jsalz): remove this hack
1332 # and figure out the right way to get the focus to Chrome.
1333 if not utils.in_chroot():
1334 Spawn(
1335 [os.path.join(factory.FACTORY_PATH, 'bin', 'send_key'), 'Tab'],
1336 check_call=True, log=True)
Jon Salz0697cbf2012-07-04 15:14:04 +08001337 elif self.options.ui == 'gtk':
1338 self.start_ui()
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001339
Ricky Liang650f6bf2012-09-28 13:22:54 +08001340 # Create download path for autotest beforehand or autotests run at
1341 # the same time might fail due to race condition.
1342 if not factory.in_chroot():
1343 utils.TryMakeDirs(os.path.join('/usr/local/autotest', 'tests',
1344 'download'))
1345
Jon Salz0697cbf2012-07-04 15:14:04 +08001346 def state_change_callback(test, test_state):
1347 self.event_client.post_event(
1348 Event(Event.Type.STATE_CHANGE,
1349 path=test.path, state=test_state))
1350 self.test_list.state_change_callback = state_change_callback
Jon Salz73e0fd02012-04-04 11:46:38 +08001351
Jon Salza6711d72012-07-18 14:33:03 +08001352 for handler in self.on_ui_startup:
1353 handler()
1354
1355 self.prespawner = Prespawner()
1356 self.prespawner.start()
1357
Jon Salz0697cbf2012-07-04 15:14:04 +08001358 try:
1359 tests_after_shutdown = self.state_instance.get_shared_data(
1360 'tests_after_shutdown')
1361 except KeyError:
1362 tests_after_shutdown = None
Jon Salz57717ca2012-04-04 16:47:25 +08001363
Jon Salz5c344f62012-07-13 14:31:16 +08001364 force_auto_run = (tests_after_shutdown == FORCE_AUTO_RUN)
1365 if not force_auto_run and tests_after_shutdown is not None:
Jon Salz0697cbf2012-07-04 15:14:04 +08001366 logging.info('Resuming tests after shutdown: %s',
1367 tests_after_shutdown)
Jon Salz0697cbf2012-07-04 15:14:04 +08001368 self.tests_to_run.extend(
1369 self.test_list.lookup_path(t) for t in tests_after_shutdown)
1370 self.run_queue.put(self.run_next_test)
1371 else:
Jon Salz5c344f62012-07-13 14:31:16 +08001372 if force_auto_run or self.test_list.options.auto_run_on_start:
Jon Salz0697cbf2012-07-04 15:14:04 +08001373 self.run_queue.put(
1374 lambda: self.run_tests(self.test_list, untested_only=True))
Jon Salz5c344f62012-07-13 14:31:16 +08001375 self.state_instance.set_shared_data('tests_after_shutdown', None)
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001376
Dean Liao592e4d52013-01-10 20:06:39 +08001377 self.may_disable_cros_shortcut_keys()
1378
1379 def may_disable_cros_shortcut_keys(self):
1380 test_options = self.test_list.options
1381 if test_options.disable_cros_shortcut_keys:
1382 logging.info('Filter ChromeOS shortcut keys.')
1383 self.key_filter = KeyFilter(
1384 unmap_caps_lock=test_options.disable_caps_lock,
1385 caps_lock_keycode=test_options.caps_lock_keycode)
1386 self.key_filter.Start()
1387
Jon Salz0697cbf2012-07-04 15:14:04 +08001388 def run(self):
1389 '''Runs Goofy.'''
1390 # Process events forever.
1391 while self.run_once(True):
1392 pass
Jon Salz73e0fd02012-04-04 11:46:38 +08001393
Jon Salz0697cbf2012-07-04 15:14:04 +08001394 def run_once(self, block=False):
1395 '''Runs all items pending in the event loop.
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001396
Jon Salz0697cbf2012-07-04 15:14:04 +08001397 Args:
1398 block: If true, block until at least one event is processed.
Jon Salz7c15e8b2012-06-19 17:10:37 +08001399
Jon Salz0697cbf2012-07-04 15:14:04 +08001400 Returns:
1401 True to keep going or False to shut down.
1402 '''
1403 events = utils.DrainQueue(self.run_queue)
cychiang21886742012-07-05 15:16:32 +08001404 while not events:
Jon Salz0697cbf2012-07-04 15:14:04 +08001405 # Nothing on the run queue.
1406 self._run_queue_idle()
1407 if block:
1408 # Block for at least one event...
cychiang21886742012-07-05 15:16:32 +08001409 try:
1410 events.append(self.run_queue.get(timeout=RUN_QUEUE_TIMEOUT_SECS))
1411 except Queue.Empty:
1412 # Keep going (calling _run_queue_idle() again at the top of
1413 # the loop)
1414 continue
Jon Salz0697cbf2012-07-04 15:14:04 +08001415 # ...and grab anything else that showed up at the same
1416 # time.
1417 events.extend(utils.DrainQueue(self.run_queue))
cychiang21886742012-07-05 15:16:32 +08001418 else:
1419 break
Jon Salz51528e12012-07-02 18:54:45 +08001420
Jon Salz0697cbf2012-07-04 15:14:04 +08001421 for event in events:
1422 if not event:
1423 # Shutdown request.
1424 self.run_queue.task_done()
1425 return False
Jon Salz51528e12012-07-02 18:54:45 +08001426
Jon Salz0697cbf2012-07-04 15:14:04 +08001427 try:
1428 event()
Jon Salz85a39882012-07-05 16:45:04 +08001429 except: # pylint: disable=W0702
1430 logging.exception('Error in event loop')
Jon Salz0697cbf2012-07-04 15:14:04 +08001431 self.record_exception(traceback.format_exception_only(
1432 *sys.exc_info()[:2]))
1433 # But keep going
1434 finally:
1435 self.run_queue.task_done()
1436 return True
Jon Salz0405ab52012-03-16 15:26:52 +08001437
Jon Salz0e6532d2012-10-25 16:30:11 +08001438 def _should_sync_time(self, foreground=False):
1439 '''Returns True if we should attempt syncing time with shopfloor.
1440
1441 Args:
1442 foreground: If True, synchronizes even if background syncing
1443 is disabled (e.g., in explicit sync requests from the
1444 SyncShopfloor test).
1445 '''
1446 return ((foreground or
1447 self.test_list.options.sync_time_period_secs) and
Jon Salz54882d02012-08-31 01:57:54 +08001448 self.time_sanitizer and
1449 (not self.time_synced) and
1450 (not factory.in_chroot()))
1451
Jon Salz0e6532d2012-10-25 16:30:11 +08001452 def sync_time_with_shopfloor_server(self, foreground=False):
Jon Salz54882d02012-08-31 01:57:54 +08001453 '''Syncs time with shopfloor server, if not yet synced.
1454
Jon Salz0e6532d2012-10-25 16:30:11 +08001455 Args:
1456 foreground: If True, synchronizes even if background syncing
1457 is disabled (e.g., in explicit sync requests from the
1458 SyncShopfloor test).
1459
Jon Salz54882d02012-08-31 01:57:54 +08001460 Returns:
1461 False if no time sanitizer is available, or True if this sync (or a
1462 previous sync) succeeded.
1463
1464 Raises:
1465 Exception if unable to contact the shopfloor server.
1466 '''
Jon Salz0e6532d2012-10-25 16:30:11 +08001467 if self._should_sync_time(foreground):
Jon Salz54882d02012-08-31 01:57:54 +08001468 self.time_sanitizer.SyncWithShopfloor()
1469 self.time_synced = True
1470 return self.time_synced
1471
Jon Salzb92c5112012-09-21 15:40:11 +08001472 def log_disk_space_stats(self):
Jon Salz18e0e022013-06-11 17:13:39 +08001473 if (utils.in_chroot() or
1474 not self.test_list.options.log_disk_space_period_secs):
Jon Salzb92c5112012-09-21 15:40:11 +08001475 return
1476
1477 now = time.time()
1478 if (self.last_log_disk_space_time and
1479 now - self.last_log_disk_space_time <
1480 self.test_list.options.log_disk_space_period_secs):
1481 return
1482 self.last_log_disk_space_time = now
1483
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001484 # Upload event if stateful partition usage is above threshold.
1485 # Stateful partition is mounted on /usr/local, while
1486 # encrypted stateful partition is mounted on /var.
1487 # If there are too much logs in the factory process,
1488 # these two partitions might get full.
Jon Salzb92c5112012-09-21 15:40:11 +08001489 try:
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001490 vfs_infos = disk_space.GetAllVFSInfo()
1491 stateful_info, encrypted_info = None, None
1492 for vfs_info in vfs_infos.values():
1493 if '/usr/local' in vfs_info.mount_points:
1494 stateful_info = vfs_info
1495 if '/var' in vfs_info.mount_points:
1496 encrypted_info = vfs_info
1497
1498 stateful = disk_space.GetPartitionUsage(stateful_info)
1499 encrypted = disk_space.GetPartitionUsage(encrypted_info)
1500
1501 above_threshold = (
1502 self.test_list.options.stateful_usage_threshold and
1503 max(stateful.bytes_used_pct,
1504 stateful.inodes_used_pct,
1505 encrypted.bytes_used_pct,
1506 encrypted.inodes_used_pct) >
1507 self.test_list.options.stateful_usage_threshold)
1508
1509 if above_threshold:
1510 self.event_log.Log('stateful_partition_usage',
1511 partitions={
1512 'stateful': {
1513 'bytes_used_pct': FloatDigit(stateful.bytes_used_pct, 2),
1514 'inodes_used_pct': FloatDigit(stateful.inodes_used_pct, 2)},
1515 'encrypted_stateful': {
1516 'bytes_used_pct': FloatDigit(encrypted.bytes_used_pct, 2),
1517 'inodes_used_pct': FloatDigit(encrypted.inodes_used_pct, 2)}
1518 })
1519 self.log_watcher.ScanEventLogs()
1520
1521 message = disk_space.FormatSpaceUsedAll(vfs_infos)
Jon Salz3c493bb2013-02-07 17:24:58 +08001522 if message != self.last_log_disk_space_message:
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001523 if above_threshold:
1524 logging.warning(message)
1525 else:
1526 logging.info(message)
Jon Salz3c493bb2013-02-07 17:24:58 +08001527 self.last_log_disk_space_message = message
Jon Salzb92c5112012-09-21 15:40:11 +08001528 except: # pylint: disable=W0702
1529 logging.exception('Unable to get disk space used')
1530
Justin Chuang83813982013-05-13 01:26:32 +08001531 def check_battery(self):
1532 '''Checks the current battery status.
1533
1534 Logs current battery charging level and status to log. If the battery level
1535 is lower below warning_low_battery_pct, send warning event to shopfloor.
1536 If the battery level is lower below critical_low_battery_pct, flush disks.
1537 '''
1538 if not self.test_list.options.check_battery_period_secs:
1539 return
1540
1541 now = time.time()
1542 if (self.last_check_battery_time and
1543 now - self.last_check_battery_time <
1544 self.test_list.options.check_battery_period_secs):
1545 return
1546 self.last_check_battery_time = now
1547
1548 message = ''
1549 log_level = logging.INFO
1550 try:
1551 power = system.GetBoard().power
1552 if not power.CheckBatteryPresent():
1553 message = 'Battery is not present'
1554 else:
1555 ac_present = power.CheckACPresent()
1556 charge_pct = power.GetChargePct(get_float=True)
1557 message = ('Current battery level %.1f%%, AC charger is %s' %
1558 (charge_pct, 'connected' if ac_present else 'disconnected'))
1559
1560 if charge_pct > self.test_list.options.critical_low_battery_pct:
1561 critical_low_battery = False
1562 else:
1563 critical_low_battery = True
1564 # Only sync disks when battery level is still above minimum
1565 # value. This can be used for offline analysis when shopfloor cannot
1566 # be connected.
1567 if charge_pct > MIN_BATTERY_LEVEL_FOR_DISK_SYNC:
1568 logging.warning('disk syncing for critical low battery situation')
1569 os.system('sync; sync; sync')
1570 else:
1571 logging.warning('disk syncing is cancelled '
1572 'because battery level is lower than %.1f',
1573 MIN_BATTERY_LEVEL_FOR_DISK_SYNC)
1574
1575 # Notify shopfloor server
1576 if (critical_low_battery or
1577 (not ac_present and
1578 charge_pct <= self.test_list.options.warning_low_battery_pct)):
1579 log_level = logging.WARNING
1580
1581 self.event_log.Log('low_battery',
1582 battery_level=charge_pct,
1583 charger_connected=ac_present,
1584 critical=critical_low_battery)
1585 self.log_watcher.KickWatchThread()
1586 self.system_log_manager.KickSyncThread()
1587 except: # pylint: disable=W0702
1588 logging.exception('Unable to check battery or notify shopfloor')
1589 finally:
1590 if message != self.last_check_battery_message:
1591 logging.log(log_level, message)
1592 self.last_check_battery_message = message
1593
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001594 def check_core_dump(self):
1595 '''Checks if there is any core dumped file.
1596
1597 Removes unwanted core dump files immediately.
1598 Syncs those files matching watch list to server with a delay between
1599 each sync. After the files have been synced to server, deletes the files.
1600 '''
1601 core_dump_files = self.core_dump_manager.ScanFiles()
1602 if core_dump_files:
1603 now = time.time()
1604 if (self.last_kick_sync_time and now - self.last_kick_sync_time <
1605 self.test_list.options.kick_sync_min_interval_secs):
1606 return
1607 self.last_kick_sync_time = now
1608
1609 # Sends event to server
1610 self.event_log.Log('core_dumped', files=core_dump_files)
1611 self.log_watcher.KickWatchThread()
1612
1613 # Syncs files to server
1614 self.system_log_manager.KickSyncThread(
1615 core_dump_files, self.core_dump_manager.ClearFiles)
1616
Jon Salz8fa8e832012-07-13 19:04:09 +08001617 def sync_time_in_background(self):
Jon Salzb22d1172012-08-06 10:38:57 +08001618 '''Writes out current time and tries to sync with shopfloor server.'''
1619 if not self.time_sanitizer:
1620 return
1621
1622 # Write out the current time.
1623 self.time_sanitizer.SaveTime()
1624
Jon Salz54882d02012-08-31 01:57:54 +08001625 if not self._should_sync_time():
Jon Salz8fa8e832012-07-13 19:04:09 +08001626 return
1627
1628 now = time.time()
1629 if self.last_sync_time and (
1630 now - self.last_sync_time <
1631 self.test_list.options.sync_time_period_secs):
1632 # Not yet time for another check.
1633 return
1634 self.last_sync_time = now
1635
1636 def target():
1637 try:
Jon Salz54882d02012-08-31 01:57:54 +08001638 self.sync_time_with_shopfloor_server()
Jon Salz8fa8e832012-07-13 19:04:09 +08001639 except: # pylint: disable=W0702
1640 # Oh well. Log an error (but no trace)
1641 logging.info(
1642 'Unable to get time from shopfloor server: %s',
1643 utils.FormatExceptionOnly())
1644
1645 thread = threading.Thread(target=target)
1646 thread.daemon = True
1647 thread.start()
1648
Jon Salz0697cbf2012-07-04 15:14:04 +08001649 def _run_queue_idle(self):
Vic Yang4953fc12012-07-26 16:19:53 +08001650 '''Invoked when the run queue has no events.
1651
1652 This method must not raise exception.
1653 '''
Jon Salzb22d1172012-08-06 10:38:57 +08001654 now = time.time()
1655 if (self.last_idle and
1656 now < (self.last_idle + RUN_QUEUE_TIMEOUT_SECS - 1)):
1657 # Don't run more often than once every (RUN_QUEUE_TIMEOUT_SECS -
1658 # 1) seconds.
1659 return
1660
1661 self.last_idle = now
1662
Vic Yang311ddb82012-09-26 12:08:28 +08001663 self.check_exclusive()
cychiang21886742012-07-05 15:16:32 +08001664 self.check_for_updates()
Jon Salz8fa8e832012-07-13 19:04:09 +08001665 self.sync_time_in_background()
Jon Salzb92c5112012-09-21 15:40:11 +08001666 self.log_disk_space_stats()
Justin Chuang83813982013-05-13 01:26:32 +08001667 self.check_battery()
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001668 self.check_core_dump()
Jon Salz57717ca2012-04-04 16:47:25 +08001669
Jon Salzd15bbcf2013-05-21 17:33:57 +08001670 def handle_event_logs(self, chunks):
Jon Salz0697cbf2012-07-04 15:14:04 +08001671 '''Callback for event watcher.
Jon Salz258a40c2012-04-19 12:34:01 +08001672
Jon Salz0697cbf2012-07-04 15:14:04 +08001673 Attempts to upload the event logs to the shopfloor server.
Vic Yang93027612013-05-06 02:42:49 +08001674
1675 Args:
Jon Salzd15bbcf2013-05-21 17:33:57 +08001676 chunks: A list of Chunk objects.
Jon Salz0697cbf2012-07-04 15:14:04 +08001677 '''
Vic Yang93027612013-05-06 02:42:49 +08001678 first_exception = None
1679 exception_count = 0
1680
Jon Salzd15bbcf2013-05-21 17:33:57 +08001681 for chunk in chunks:
Vic Yang93027612013-05-06 02:42:49 +08001682 try:
Jon Salzcddb6402013-05-23 12:56:42 +08001683 description = 'event logs (%s)' % str(chunk)
Vic Yang93027612013-05-06 02:42:49 +08001684 start_time = time.time()
1685 shopfloor_client = shopfloor.get_instance(
1686 detect=True,
1687 timeout=self.test_list.options.shopfloor_timeout_secs)
Jon Salzd15bbcf2013-05-21 17:33:57 +08001688 shopfloor_client.UploadEvent(chunk.log_name + "." +
1689 event_log.GetReimageId(),
1690 Binary(chunk.chunk))
Vic Yang93027612013-05-06 02:42:49 +08001691 logging.info(
1692 'Successfully synced %s in %.03f s',
1693 description, time.time() - start_time)
1694 except: # pylint: disable=W0702
Jon Salzd15bbcf2013-05-21 17:33:57 +08001695 first_exception = (first_exception or (chunk.log_name + ': ' +
Vic Yang93027612013-05-06 02:42:49 +08001696 utils.FormatExceptionOnly()))
1697 exception_count += 1
1698
1699 if exception_count:
1700 if exception_count == 1:
1701 msg = 'Log upload failed: %s' % first_exception
1702 else:
1703 msg = '%d log upload failed; first is: %s' % (
1704 exception_count, first_exception)
1705 raise Exception(msg)
1706
Jon Salz57717ca2012-04-04 16:47:25 +08001707
Jon Salz0697cbf2012-07-04 15:14:04 +08001708 def run_tests_with_status(self, statuses_to_run, starting_at=None,
1709 root=None):
1710 '''Runs all top-level tests with a particular status.
Jon Salz0405ab52012-03-16 15:26:52 +08001711
Jon Salz0697cbf2012-07-04 15:14:04 +08001712 All active tests, plus any tests to re-run, are reset.
Jon Salz57717ca2012-04-04 16:47:25 +08001713
Jon Salz0697cbf2012-07-04 15:14:04 +08001714 Args:
1715 starting_at: If provided, only auto-runs tests beginning with
1716 this test.
1717 '''
1718 root = root or self.test_list
Jon Salz57717ca2012-04-04 16:47:25 +08001719
Jon Salz0697cbf2012-07-04 15:14:04 +08001720 if starting_at:
1721 # Make sure they passed a test, not a string.
1722 assert isinstance(starting_at, factory.FactoryTest)
Jon Salz0405ab52012-03-16 15:26:52 +08001723
Jon Salz0697cbf2012-07-04 15:14:04 +08001724 tests_to_reset = []
1725 tests_to_run = []
Jon Salz0405ab52012-03-16 15:26:52 +08001726
Jon Salz0697cbf2012-07-04 15:14:04 +08001727 found_starting_at = False
Jon Salz0405ab52012-03-16 15:26:52 +08001728
Jon Salz0697cbf2012-07-04 15:14:04 +08001729 for test in root.get_top_level_tests():
1730 if starting_at:
1731 if test == starting_at:
1732 # We've found starting_at; do auto-run on all
1733 # subsequent tests.
1734 found_starting_at = True
1735 if not found_starting_at:
1736 # Don't start this guy yet
1737 continue
Jon Salz0405ab52012-03-16 15:26:52 +08001738
Jon Salz0697cbf2012-07-04 15:14:04 +08001739 status = test.get_state().status
1740 if status == TestState.ACTIVE or status in statuses_to_run:
1741 # Reset the test (later; we will need to abort
1742 # all active tests first).
1743 tests_to_reset.append(test)
1744 if status in statuses_to_run:
1745 tests_to_run.append(test)
Jon Salz0405ab52012-03-16 15:26:52 +08001746
Jon Salz6dc031d2013-06-19 13:06:23 +08001747 self.abort_active_tests('Operator requested run/re-run of certain tests')
Jon Salz258a40c2012-04-19 12:34:01 +08001748
Jon Salz0697cbf2012-07-04 15:14:04 +08001749 # Reset all statuses of the tests to run (in case any tests were active;
1750 # we want them to be run again).
1751 for test_to_reset in tests_to_reset:
1752 for test in test_to_reset.walk():
1753 test.update_state(status=TestState.UNTESTED)
Jon Salz57717ca2012-04-04 16:47:25 +08001754
Jon Salz0697cbf2012-07-04 15:14:04 +08001755 self.run_tests(tests_to_run, untested_only=True)
Jon Salz0405ab52012-03-16 15:26:52 +08001756
Jon Salz0697cbf2012-07-04 15:14:04 +08001757 def restart_tests(self, root=None):
1758 '''Restarts all tests.'''
1759 root = root or self.test_list
Jon Salz0405ab52012-03-16 15:26:52 +08001760
Jon Salz6dc031d2013-06-19 13:06:23 +08001761 self.abort_active_tests('Operator requested restart of certain tests')
Jon Salz0697cbf2012-07-04 15:14:04 +08001762 for test in root.walk():
1763 test.update_state(status=TestState.UNTESTED)
1764 self.run_tests(root)
Hung-Te Lin96632362012-03-20 21:14:18 +08001765
Jon Salz0697cbf2012-07-04 15:14:04 +08001766 def auto_run(self, starting_at=None, root=None):
1767 '''"Auto-runs" tests that have not been run yet.
Hung-Te Lin96632362012-03-20 21:14:18 +08001768
Jon Salz0697cbf2012-07-04 15:14:04 +08001769 Args:
1770 starting_at: If provide, only auto-runs tests beginning with
1771 this test.
1772 '''
1773 root = root or self.test_list
1774 self.run_tests_with_status([TestState.UNTESTED, TestState.ACTIVE],
1775 starting_at=starting_at,
1776 root=root)
Jon Salz968e90b2012-03-18 16:12:43 +08001777
Jon Salz0697cbf2012-07-04 15:14:04 +08001778 def re_run_failed(self, root=None):
1779 '''Re-runs failed tests.'''
1780 root = root or self.test_list
1781 self.run_tests_with_status([TestState.FAILED], root=root)
Jon Salz57717ca2012-04-04 16:47:25 +08001782
Jon Salz0697cbf2012-07-04 15:14:04 +08001783 def show_review_information(self):
1784 '''Event handler for showing review information screen.
Jon Salz57717ca2012-04-04 16:47:25 +08001785
Jon Salz0697cbf2012-07-04 15:14:04 +08001786 The information screene is rendered by main UI program (ui.py), so in
1787 goofy we only need to kill all active tests, set them as untested, and
1788 clear remaining tests.
1789 '''
1790 self.kill_active_tests(False)
Jon Salza6711d72012-07-18 14:33:03 +08001791 self.cancel_pending_tests()
Jon Salz57717ca2012-04-04 16:47:25 +08001792
Jon Salz0697cbf2012-07-04 15:14:04 +08001793 def handle_switch_test(self, event):
1794 '''Switches to a particular test.
Jon Salz0405ab52012-03-16 15:26:52 +08001795
Jon Salz0697cbf2012-07-04 15:14:04 +08001796 @param event: The SWITCH_TEST event.
1797 '''
1798 test = self.test_list.lookup_path(event.path)
1799 if not test:
1800 logging.error('Unknown test %r', event.key)
1801 return
Jon Salz73e0fd02012-04-04 11:46:38 +08001802
Jon Salz0697cbf2012-07-04 15:14:04 +08001803 invoc = self.invocations.get(test)
1804 if invoc and test.backgroundable:
1805 # Already running: just bring to the front if it
1806 # has a UI.
1807 logging.info('Setting visible test to %s', test.path)
Jon Salz36fbbb52012-07-05 13:45:06 +08001808 self.set_visible_test(test)
Jon Salz0697cbf2012-07-04 15:14:04 +08001809 return
Jon Salz73e0fd02012-04-04 11:46:38 +08001810
Jon Salz6dc031d2013-06-19 13:06:23 +08001811 self.abort_active_tests('Operator requested abort (switch_test)')
Jon Salz0697cbf2012-07-04 15:14:04 +08001812 for t in test.walk():
1813 t.update_state(status=TestState.UNTESTED)
Jon Salz73e0fd02012-04-04 11:46:38 +08001814
Jon Salz0697cbf2012-07-04 15:14:04 +08001815 if self.test_list.options.auto_run_on_keypress:
1816 self.auto_run(starting_at=test)
1817 else:
1818 self.run_tests(test)
Jon Salz73e0fd02012-04-04 11:46:38 +08001819
Jon Salz0697cbf2012-07-04 15:14:04 +08001820 def wait(self):
1821 '''Waits for all pending invocations.
1822
1823 Useful for testing.
1824 '''
Jon Salz1acc8742012-07-17 17:45:55 +08001825 while self.invocations:
1826 for k, v in self.invocations.iteritems():
1827 logging.info('Waiting for %s to complete...', k)
1828 v.thread.join()
1829 self.reap_completed_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +08001830
1831 def check_exceptions(self):
1832 '''Raises an error if any exceptions have occurred in
1833 invocation threads.'''
1834 if self.exceptions:
1835 raise RuntimeError('Exception in invocation thread: %r' %
1836 self.exceptions)
1837
1838 def record_exception(self, msg):
1839 '''Records an exception in an invocation thread.
1840
1841 An exception with the given message will be rethrown when
1842 Goofy is destroyed.'''
1843 self.exceptions.append(msg)
Jon Salz73e0fd02012-04-04 11:46:38 +08001844
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001845
1846if __name__ == '__main__':
Jon Salz77c151e2012-08-28 07:20:37 +08001847 goofy = Goofy()
1848 try:
1849 goofy.main()
Jon Salz0f996602012-10-03 15:26:48 +08001850 except SystemExit:
1851 # Propagate SystemExit without logging.
1852 raise
Jon Salz31373eb2012-09-21 16:19:49 +08001853 except:
Jon Salz0f996602012-10-03 15:26:48 +08001854 # Log the error before trying to shut down (unless it's a graceful
1855 # exit).
Jon Salz31373eb2012-09-21 16:19:49 +08001856 logging.exception('Error in main loop')
1857 raise
Jon Salz77c151e2012-08-28 07:20:37 +08001858 finally:
1859 goofy.destroy()