blob: 2fa11df3353c1d2b3c9d094a5b04afb19b0b29b7 [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 Salzeff94182013-06-19 15:06:28 +080017import syslog
Jon Salz0405ab52012-03-16 15:26:52 +080018import threading
19import time
20import traceback
Jon Salz258a40c2012-04-19 12:34:01 +080021import uuid
Jon Salzb10cf512012-08-09 17:29:21 +080022from xmlrpclib import Binary
Hung-Te Linf2f78f72012-02-08 19:27:11 +080023from collections import deque
24from optparse import OptionParser
Hung-Te Linf2f78f72012-02-08 19:27:11 +080025
Jon Salz0697cbf2012-07-04 15:14:04 +080026import factory_common # pylint: disable=W0611
jcliangcd688182012-08-20 21:01:26 +080027from cros.factory import event_log
28from cros.factory import system
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +080029from cros.factory.event_log import EventLog, FloatDigit
Tom Wai-Hong Tamd33723e2013-04-10 21:14:37 +080030from cros.factory.event_log_watcher import EventLogWatcher
jcliangcd688182012-08-20 21:01:26 +080031from cros.factory.goofy import test_environment
32from cros.factory.goofy import time_sanitizer
Jon Salz83591782012-06-26 11:09:58 +080033from cros.factory.goofy import updater
jcliangcd688182012-08-20 21:01:26 +080034from cros.factory.goofy.goofy_rpc import GoofyRPC
35from cros.factory.goofy.invocation import TestInvocation
36from cros.factory.goofy.prespawner import Prespawner
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +080037from cros.factory.goofy.system_log_manager import SystemLogManager
jcliangcd688182012-08-20 21:01:26 +080038from cros.factory.goofy.web_socket_manager import WebSocketManager
Cheng-Yi Chiangd8186952013-04-04 23:41:14 +080039from cros.factory.system.board import Board, BoardException
jcliangcd688182012-08-20 21:01:26 +080040from cros.factory.system.charge_manager import ChargeManager
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +080041from cros.factory.system.core_dump_manager import CoreDumpManager
Jon Salzce6a7f82013-06-10 18:22:54 +080042from cros.factory.system.cpufreq_manager import CpufreqManager
Jon Salzb92c5112012-09-21 15:40:11 +080043from cros.factory.system import disk_space
jcliangcd688182012-08-20 21:01:26 +080044from cros.factory.test import factory
45from cros.factory.test import state
Jon Salz51528e12012-07-02 18:54:45 +080046from cros.factory.test import shopfloor
Jon Salz83591782012-06-26 11:09:58 +080047from cros.factory.test import utils
48from cros.factory.test.event import Event
49from cros.factory.test.event import EventClient
50from cros.factory.test.event import EventServer
jcliangcd688182012-08-20 21:01:26 +080051from cros.factory.test.factory import TestState
Dean Liao592e4d52013-01-10 20:06:39 +080052from cros.factory.tools.key_filter import KeyFilter
Jon Salz78c32392012-07-25 14:18:29 +080053from cros.factory.utils.process_utils import Spawn
Hung-Te Linf2f78f72012-02-08 19:27:11 +080054
55
Jon Salz2f757d42012-06-27 17:06:42 +080056CUSTOM_DIR = os.path.join(factory.FACTORY_PATH, 'custom')
Hung-Te Linf2f78f72012-02-08 19:27:11 +080057HWID_CFG_PATH = '/usr/local/share/chromeos-hwid/cfg'
Chun-ta Lin279e7e92013-02-19 17:40:39 +080058CACHES_DIR = os.path.join(factory.get_state_root(), "caches")
Hung-Te Linf2f78f72012-02-08 19:27:11 +080059
Jon Salz8796e362012-05-24 11:39:09 +080060# File that suppresses reboot if present (e.g., for development).
61NO_REBOOT_FILE = '/var/log/factory.noreboot'
62
Jon Salz5c344f62012-07-13 14:31:16 +080063# Value for tests_after_shutdown that forces auto-run (e.g., after
64# a factory update, when the available set of tests might change).
65FORCE_AUTO_RUN = 'force_auto_run'
66
cychiang21886742012-07-05 15:16:32 +080067RUN_QUEUE_TIMEOUT_SECS = 10
68
Justin Chuang83813982013-05-13 01:26:32 +080069# Sync disks when battery level is higher than this value.
70# Otherwise, power loss during disk sync operation may incur even worse outcome.
71MIN_BATTERY_LEVEL_FOR_DISK_SYNC = 1.0
72
Jon Salz758e6cc2012-04-03 15:47:07 +080073GOOFY_IN_CHROOT_WARNING = '\n' + ('*' * 70) + '''
74You are running Goofy inside the chroot. Autotests are not supported.
75
76To use Goofy in the chroot, first install an Xvnc server:
77
Jon Salz0697cbf2012-07-04 15:14:04 +080078 sudo apt-get install tightvncserver
Jon Salz758e6cc2012-04-03 15:47:07 +080079
80...and then start a VNC X server outside the chroot:
81
Jon Salz0697cbf2012-07-04 15:14:04 +080082 vncserver :10 &
83 vncviewer :10
Jon Salz758e6cc2012-04-03 15:47:07 +080084
85...and run Goofy as follows:
86
Jon Salz0697cbf2012-07-04 15:14:04 +080087 env --unset=XAUTHORITY DISPLAY=localhost:10 python goofy.py
Jon Salz758e6cc2012-04-03 15:47:07 +080088''' + ('*' * 70)
Jon Salz73e0fd02012-04-04 11:46:38 +080089suppress_chroot_warning = False
Hung-Te Linf2f78f72012-02-08 19:27:11 +080090
91def get_hwid_cfg():
Jon Salz0697cbf2012-07-04 15:14:04 +080092 '''
93 Returns the HWID config tag, or an empty string if none can be found.
94 '''
95 if 'CROS_HWID' in os.environ:
96 return os.environ['CROS_HWID']
97 if os.path.exists(HWID_CFG_PATH):
98 with open(HWID_CFG_PATH, 'rt') as hwid_cfg_handle:
99 return hwid_cfg_handle.read().strip()
100 return ''
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800101
102
103def find_test_list():
Jon Salz0697cbf2012-07-04 15:14:04 +0800104 '''
105 Returns the path to the active test list, based on the HWID config tag.
Jon Salzfb615892013-02-01 18:04:35 +0800106
107 The algorithm is:
108
109 - Try $FACTORY/test_lists/active (the symlink reflecting the option chosen
110 in the UI).
111 - For each of $FACTORY/custom, $FACTORY/test_lists (and
112 autotest/site_tests/suite_Factory for backward compatibility):
113 - Try test_list_${hwid_cfg} (if hwid_cfg is set)
114 - Try test_list
115 - Try test_list.generic
Jon Salz0697cbf2012-07-04 15:14:04 +0800116 '''
Jon Salzfb615892013-02-01 18:04:35 +0800117 # If the 'active' symlink is present, that trumps everything else.
118 if os.path.lexists(factory.ACTIVE_TEST_LIST_SYMLINK):
119 return os.path.realpath(factory.ACTIVE_TEST_LIST_SYMLINK)
120
Jon Salz0697cbf2012-07-04 15:14:04 +0800121 hwid_cfg = get_hwid_cfg()
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800122
Jon Salzfb615892013-02-01 18:04:35 +0800123 search_dirs = [CUSTOM_DIR, factory.TEST_LISTS_PATH]
Jon Salz4be56b02012-12-22 07:30:46 +0800124 if not utils.in_chroot():
125 # Also look in suite_Factory. For backward compatibility only;
126 # new boards should just put the test list in the "test_lists"
127 # directory.
128 search_dirs.insert(0, os.path.join(
129 os.path.dirname(factory.FACTORY_PATH),
130 'autotest', 'site_tests', 'suite_Factory'))
Jon Salz2f757d42012-06-27 17:06:42 +0800131
Jon Salzfb615892013-02-01 18:04:35 +0800132
133 search_files = []
Jon Salz0697cbf2012-07-04 15:14:04 +0800134 if hwid_cfg:
Jon Salzfb615892013-02-01 18:04:35 +0800135 search_files += [hwid_cfg]
136 search_files += ['test_list', 'test_list.generic']
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800137
Jon Salz0697cbf2012-07-04 15:14:04 +0800138 for d in search_dirs:
139 for f in search_files:
140 test_list = os.path.join(d, f)
141 if os.path.exists(test_list):
142 return test_list
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800143
Jon Salz0697cbf2012-07-04 15:14:04 +0800144 logging.warn('Cannot find test lists named any of %s in any of %s',
145 search_files, search_dirs)
146 return None
Jon Salz73e0fd02012-04-04 11:46:38 +0800147
Jon Salzfb615892013-02-01 18:04:35 +0800148
Jon Salz73e0fd02012-04-04 11:46:38 +0800149_inited_logging = False
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800150
151class Goofy(object):
Jon Salz0697cbf2012-07-04 15:14:04 +0800152 '''
153 The main factory flow.
154
155 Note that all methods in this class must be invoked from the main
156 (event) thread. Other threads, such as callbacks and TestInvocation
157 methods, should instead post events on the run queue.
158
159 TODO: Unit tests. (chrome-os-partner:7409)
160
161 Properties:
162 uuid: A unique UUID for this invocation of Goofy.
163 state_instance: An instance of FactoryState.
164 state_server: The FactoryState XML/RPC server.
165 state_server_thread: A thread running state_server.
166 event_server: The EventServer socket server.
167 event_server_thread: A thread running event_server.
168 event_client: A client to the event server.
169 connection_manager: The connection_manager object.
Cheng-Yi Chiang835f2682013-05-06 22:15:48 +0800170 system_log_manager: The SystemLogManager object.
171 core_dump_manager: The CoreDumpManager object.
Jon Salz0697cbf2012-07-04 15:14:04 +0800172 ui_process: The factory ui process object.
173 run_queue: A queue of callbacks to invoke from the main thread.
174 invocations: A map from FactoryTest objects to the corresponding
175 TestInvocations objects representing active tests.
176 tests_to_run: A deque of tests that should be run when the current
177 test(s) complete.
178 options: Command-line options.
179 args: Command-line args.
180 test_list: The test list.
181 event_handlers: Map of Event.Type to the method used to handle that
182 event. If the method has an 'event' argument, the event is passed
183 to the handler.
184 exceptions: Exceptions encountered in invocation threads.
Jon Salz3c493bb2013-02-07 17:24:58 +0800185 last_log_disk_space_message: The last message we logged about disk space
186 (to avoid duplication).
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +0800187 last_kick_sync_time: The last time to kick system_log_manager to sync
188 because of core dump files (to avoid kicking too soon then abort the
189 sync.)
Jon Salz416f9cc2013-05-10 18:32:50 +0800190 hooks: A Hooks object containing hooks for various Goofy actions.
Jon Salz0697cbf2012-07-04 15:14:04 +0800191 '''
192 def __init__(self):
193 self.uuid = str(uuid.uuid4())
194 self.state_instance = None
195 self.state_server = None
196 self.state_server_thread = None
Jon Salz16d10542012-07-23 12:18:45 +0800197 self.goofy_rpc = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800198 self.event_server = None
199 self.event_server_thread = None
200 self.event_client = None
201 self.connection_manager = None
Vic Yang4953fc12012-07-26 16:19:53 +0800202 self.charge_manager = None
Jon Salz8fa8e832012-07-13 19:04:09 +0800203 self.time_sanitizer = None
204 self.time_synced = False
Jon Salz0697cbf2012-07-04 15:14:04 +0800205 self.log_watcher = None
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +0800206 self.system_log_manager = None
Cheng-Yi Chiang835f2682013-05-06 22:15:48 +0800207 self.core_dump_manager = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800208 self.event_log = None
209 self.prespawner = None
210 self.ui_process = None
Jon Salzc79a9982012-08-30 04:42:01 +0800211 self.dummy_shopfloor = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800212 self.run_queue = Queue.Queue()
213 self.invocations = {}
214 self.tests_to_run = deque()
215 self.visible_test = None
216 self.chrome = None
Jon Salz416f9cc2013-05-10 18:32:50 +0800217 self.hooks = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800218
219 self.options = None
220 self.args = None
221 self.test_list = None
222 self.on_ui_startup = []
223 self.env = None
Jon Salzb22d1172012-08-06 10:38:57 +0800224 self.last_idle = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800225 self.last_shutdown_time = None
cychiang21886742012-07-05 15:16:32 +0800226 self.last_update_check = None
Jon Salz8fa8e832012-07-13 19:04:09 +0800227 self.last_sync_time = None
Jon Salzb92c5112012-09-21 15:40:11 +0800228 self.last_log_disk_space_time = None
Jon Salz3c493bb2013-02-07 17:24:58 +0800229 self.last_log_disk_space_message = None
Justin Chuang83813982013-05-13 01:26:32 +0800230 self.last_check_battery_time = None
231 self.last_check_battery_message = None
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +0800232 self.last_kick_sync_time = None
Vic Yang311ddb82012-09-26 12:08:28 +0800233 self.exclusive_items = set()
Jon Salz0f996602012-10-03 15:26:48 +0800234 self.event_log = None
Dean Liao592e4d52013-01-10 20:06:39 +0800235 self.key_filter = None
Jon Salzce6a7f82013-06-10 18:22:54 +0800236 self.cpufreq_manager = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800237
Jon Salz85a39882012-07-05 16:45:04 +0800238 def test_or_root(event, parent_or_group=True):
239 '''Returns the test affected by a particular event.
240
241 Args:
242 event: The event containing an optional 'path' attribute.
243 parent_on_group: If True, returns the top-level parent for a test (the
244 root node of the tests that need to be run together if the given test
245 path is to be run).
246 '''
Jon Salz0697cbf2012-07-04 15:14:04 +0800247 try:
248 path = event.path
249 except AttributeError:
250 path = None
251
252 if path:
Jon Salz85a39882012-07-05 16:45:04 +0800253 test = self.test_list.lookup_path(path)
254 if parent_or_group:
255 test = test.get_top_level_parent_or_group()
256 return test
Jon Salz0697cbf2012-07-04 15:14:04 +0800257 else:
258 return self.test_list
259
260 self.event_handlers = {
261 Event.Type.SWITCH_TEST: self.handle_switch_test,
262 Event.Type.SHOW_NEXT_ACTIVE_TEST:
263 lambda event: self.show_next_active_test(),
264 Event.Type.RESTART_TESTS:
265 lambda event: self.restart_tests(root=test_or_root(event)),
266 Event.Type.AUTO_RUN:
267 lambda event: self.auto_run(root=test_or_root(event)),
268 Event.Type.RE_RUN_FAILED:
269 lambda event: self.re_run_failed(root=test_or_root(event)),
270 Event.Type.RUN_TESTS_WITH_STATUS:
271 lambda event: self.run_tests_with_status(
272 event.status,
273 root=test_or_root(event)),
274 Event.Type.REVIEW:
275 lambda event: self.show_review_information(),
276 Event.Type.UPDATE_SYSTEM_INFO:
277 lambda event: self.update_system_info(),
Jon Salz0697cbf2012-07-04 15:14:04 +0800278 Event.Type.STOP:
Jon Salz85a39882012-07-05 16:45:04 +0800279 lambda event: self.stop(root=test_or_root(event, False),
Jon Salz6dc031d2013-06-19 13:06:23 +0800280 fail=getattr(event, 'fail', False),
281 reason=getattr(event, 'reason', None)),
Jon Salz36fbbb52012-07-05 13:45:06 +0800282 Event.Type.SET_VISIBLE_TEST:
283 lambda event: self.set_visible_test(
284 self.test_list.lookup_path(event.path)),
Jon Salz4712ac72013-02-07 17:12:05 +0800285 Event.Type.CLEAR_STATE:
286 lambda event: self.clear_state(self.test_list.lookup_path(event.path)),
Jon Salz0697cbf2012-07-04 15:14:04 +0800287 }
288
289 self.exceptions = []
290 self.web_socket_manager = None
291
292 def destroy(self):
293 if self.chrome:
294 self.chrome.kill()
295 self.chrome = None
Jon Salzc79a9982012-08-30 04:42:01 +0800296 if self.dummy_shopfloor:
297 self.dummy_shopfloor.kill()
298 self.dummy_shopfloor = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800299 if self.ui_process:
300 utils.kill_process_tree(self.ui_process, 'ui')
301 self.ui_process = None
302 if self.web_socket_manager:
303 logging.info('Stopping web sockets')
304 self.web_socket_manager.close()
305 self.web_socket_manager = None
306 if self.state_server_thread:
307 logging.info('Stopping state server')
308 self.state_server.shutdown()
309 self.state_server_thread.join()
310 self.state_server.server_close()
311 self.state_server_thread = None
312 if self.state_instance:
313 self.state_instance.close()
314 if self.event_server_thread:
315 logging.info('Stopping event server')
316 self.event_server.shutdown() # pylint: disable=E1101
317 self.event_server_thread.join()
318 self.event_server.server_close()
319 self.event_server_thread = None
320 if self.log_watcher:
321 if self.log_watcher.IsThreadStarted():
322 self.log_watcher.StopWatchThread()
323 self.log_watcher = None
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +0800324 if self.system_log_manager:
325 if self.system_log_manager.IsThreadRunning():
326 self.system_log_manager.StopSyncThread()
327 self.system_log_manager = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800328 if self.prespawner:
329 logging.info('Stopping prespawner')
330 self.prespawner.stop()
331 self.prespawner = None
332 if self.event_client:
333 logging.info('Closing event client')
334 self.event_client.close()
335 self.event_client = None
Jon Salzddf0d052013-06-18 12:52:44 +0800336 if self.cpufreq_manager:
337 self.cpufreq_manager.Stop()
Jon Salz0697cbf2012-07-04 15:14:04 +0800338 if self.event_log:
339 self.event_log.Close()
340 self.event_log = None
Dean Liao592e4d52013-01-10 20:06:39 +0800341 if self.key_filter:
342 self.key_filter.Stop()
343
Jon Salz0697cbf2012-07-04 15:14:04 +0800344 self.check_exceptions()
345 logging.info('Done destroying Goofy')
346
347 def start_state_server(self):
348 self.state_instance, self.state_server = (
349 state.create_server(bind_address='0.0.0.0'))
Jon Salz16d10542012-07-23 12:18:45 +0800350 self.goofy_rpc = GoofyRPC(self)
351 self.goofy_rpc.RegisterMethods(self.state_instance)
Jon Salz0697cbf2012-07-04 15:14:04 +0800352 logging.info('Starting state server')
353 self.state_server_thread = threading.Thread(
354 target=self.state_server.serve_forever,
355 name='StateServer')
356 self.state_server_thread.start()
357
358 def start_event_server(self):
359 self.event_server = EventServer()
360 logging.info('Starting factory event server')
361 self.event_server_thread = threading.Thread(
362 target=self.event_server.serve_forever,
363 name='EventServer') # pylint: disable=E1101
364 self.event_server_thread.start()
365
366 self.event_client = EventClient(
367 callback=self.handle_event, event_loop=self.run_queue)
368
369 self.web_socket_manager = WebSocketManager(self.uuid)
370 self.state_server.add_handler("/event",
371 self.web_socket_manager.handle_web_socket)
372
373 def start_ui(self):
374 ui_proc_args = [
375 os.path.join(factory.FACTORY_PACKAGE_PATH, 'test', 'ui.py'),
376 self.options.test_list]
377 if self.options.verbose:
378 ui_proc_args.append('-v')
379 logging.info('Starting ui %s', ui_proc_args)
Jon Salz78c32392012-07-25 14:18:29 +0800380 self.ui_process = Spawn(ui_proc_args)
Jon Salz0697cbf2012-07-04 15:14:04 +0800381 logging.info('Waiting for UI to come up...')
382 self.event_client.wait(
383 lambda event: event.type == Event.Type.UI_READY)
384 logging.info('UI has started')
385
386 def set_visible_test(self, test):
387 if self.visible_test == test:
388 return
Jon Salz2f2d42c2012-07-30 12:30:34 +0800389 if test and not test.has_ui:
390 return
Jon Salz0697cbf2012-07-04 15:14:04 +0800391
392 if test:
393 test.update_state(visible=True)
394 if self.visible_test:
395 self.visible_test.update_state(visible=False)
396 self.visible_test = test
397
Jon Salzd4306c82012-11-30 15:16:36 +0800398 def _log_startup_messages(self):
399 '''Logs the tail of var/log/messages and mosys and EC console logs.'''
400 # TODO(jsalz): This is mostly a copy-and-paste of code in init_states,
401 # for factory-3004.B only. Consolidate and merge back to ToT.
402 if utils.in_chroot():
403 return
404
405 try:
406 var_log_messages = (
407 utils.var_log_messages_before_reboot())
408 logging.info(
409 'Tail of /var/log/messages before last reboot:\n'
410 '%s', ('\n'.join(
411 ' ' + x for x in var_log_messages)))
412 except: # pylint: disable=W0702
413 logging.exception('Unable to grok /var/log/messages')
414
415 try:
416 mosys_log = utils.Spawn(
417 ['mosys', 'eventlog', 'list'],
418 read_stdout=True, log_stderr_on_error=True).stdout_data
419 logging.info('System eventlog from mosys:\n%s\n', mosys_log)
420 except: # pylint: disable=W0702
421 logging.exception('Unable to read mosys eventlog')
422
423 try:
Vic Yang8341dde2013-01-29 16:48:52 +0800424 board = system.GetBoard()
425 ec_console_log = board.GetECConsoleLog()
Jon Salzd4306c82012-11-30 15:16:36 +0800426 logging.info('EC console log after reboot:\n%s\n', ec_console_log)
427 except: # pylint: disable=W0702
428 logging.exception('Error retrieving EC console log')
429
Jon Salz0697cbf2012-07-04 15:14:04 +0800430 def handle_shutdown_complete(self, test, test_state):
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800431 '''
Jon Salz0697cbf2012-07-04 15:14:04 +0800432 Handles the case where a shutdown was detected during a shutdown step.
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800433
Jon Salz0697cbf2012-07-04 15:14:04 +0800434 @param test: The ShutdownStep.
435 @param test_state: The test state.
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800436 '''
Jon Salz0697cbf2012-07-04 15:14:04 +0800437 test_state = test.update_state(increment_shutdown_count=1)
438 logging.info('Detected shutdown (%d of %d)',
439 test_state.shutdown_count, test.iterations)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800440
Jon Salz0697cbf2012-07-04 15:14:04 +0800441 def log_and_update_state(status, error_msg, **kw):
442 self.event_log.Log('rebooted',
443 status=status, error_msg=error_msg, **kw)
Jon Salzd4306c82012-11-30 15:16:36 +0800444 logging.info('Rebooted: status=%s, %s', status,
445 (('error_msg=%s' % error_msg) if error_msg else None))
Jon Salz0697cbf2012-07-04 15:14:04 +0800446 test.update_state(status=status, error_msg=error_msg)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800447
Jon Salz0697cbf2012-07-04 15:14:04 +0800448 if not self.last_shutdown_time:
449 log_and_update_state(status=TestState.FAILED,
450 error_msg='Unable to read shutdown_time')
451 return
Jon Salz258a40c2012-04-19 12:34:01 +0800452
Jon Salz0697cbf2012-07-04 15:14:04 +0800453 now = time.time()
454 logging.info('%.03f s passed since reboot',
455 now - self.last_shutdown_time)
Jon Salz258a40c2012-04-19 12:34:01 +0800456
Jon Salz0697cbf2012-07-04 15:14:04 +0800457 if self.last_shutdown_time > now:
458 test.update_state(status=TestState.FAILED,
459 error_msg='Time moved backward during reboot')
460 elif (isinstance(test, factory.RebootStep) and
461 self.test_list.options.max_reboot_time_secs and
462 (now - self.last_shutdown_time >
463 self.test_list.options.max_reboot_time_secs)):
464 # A reboot took too long; fail. (We don't check this for
465 # HaltSteps, because the machine could be halted for a
466 # very long time, and even unplugged with battery backup,
467 # thus hosing the clock.)
468 log_and_update_state(
469 status=TestState.FAILED,
470 error_msg=('More than %d s elapsed during reboot '
471 '(%.03f s, from %s to %s)' % (
472 self.test_list.options.max_reboot_time_secs,
473 now - self.last_shutdown_time,
474 utils.TimeString(self.last_shutdown_time),
475 utils.TimeString(now))),
476 duration=(now-self.last_shutdown_time))
Jon Salzd4306c82012-11-30 15:16:36 +0800477 self._log_startup_messages()
Jon Salz0697cbf2012-07-04 15:14:04 +0800478 elif test_state.shutdown_count == test.iterations:
479 # Good!
480 log_and_update_state(status=TestState.PASSED,
481 duration=(now - self.last_shutdown_time),
482 error_msg='')
483 elif test_state.shutdown_count > test.iterations:
484 # Shut down too many times
485 log_and_update_state(status=TestState.FAILED,
486 error_msg='Too many shutdowns')
Jon Salzd4306c82012-11-30 15:16:36 +0800487 self._log_startup_messages()
Jon Salz0697cbf2012-07-04 15:14:04 +0800488 elif utils.are_shift_keys_depressed():
489 logging.info('Shift keys are depressed; cancelling restarts')
490 # Abort shutdown
491 log_and_update_state(
492 status=TestState.FAILED,
493 error_msg='Shutdown aborted with double shift keys')
Jon Salza6711d72012-07-18 14:33:03 +0800494 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +0800495 else:
496 def handler():
497 if self._prompt_cancel_shutdown(
498 test, test_state.shutdown_count + 1):
Jon Salza6711d72012-07-18 14:33:03 +0800499 factory.console.info('Shutdown aborted by operator')
Jon Salz0697cbf2012-07-04 15:14:04 +0800500 log_and_update_state(
501 status=TestState.FAILED,
502 error_msg='Shutdown aborted by operator')
Jon Salza6711d72012-07-18 14:33:03 +0800503 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +0800504 return
Jon Salz0405ab52012-03-16 15:26:52 +0800505
Jon Salz0697cbf2012-07-04 15:14:04 +0800506 # Time to shutdown again
507 log_and_update_state(
508 status=TestState.ACTIVE,
509 error_msg='',
510 iteration=test_state.shutdown_count)
Jon Salz73e0fd02012-04-04 11:46:38 +0800511
Jon Salz0697cbf2012-07-04 15:14:04 +0800512 self.event_log.Log('shutdown', operation='reboot')
513 self.state_instance.set_shared_data('shutdown_time',
514 time.time())
515 self.env.shutdown('reboot')
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800516
Jon Salz0697cbf2012-07-04 15:14:04 +0800517 self.on_ui_startup.append(handler)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800518
Jon Salz0697cbf2012-07-04 15:14:04 +0800519 def _prompt_cancel_shutdown(self, test, iteration):
520 if self.options.ui != 'chrome':
521 return False
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800522
Jon Salz0697cbf2012-07-04 15:14:04 +0800523 pending_shutdown_data = {
524 'delay_secs': test.delay_secs,
525 'time': time.time() + test.delay_secs,
526 'operation': test.operation,
527 'iteration': iteration,
528 'iterations': test.iterations,
529 }
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800530
Jon Salz0697cbf2012-07-04 15:14:04 +0800531 # Create a new (threaded) event client since we
532 # don't want to use the event loop for this.
533 with EventClient() as event_client:
534 event_client.post_event(Event(Event.Type.PENDING_SHUTDOWN,
535 **pending_shutdown_data))
536 aborted = event_client.wait(
537 lambda event: event.type == Event.Type.CANCEL_SHUTDOWN,
538 timeout=test.delay_secs) is not None
539 if aborted:
540 event_client.post_event(Event(Event.Type.PENDING_SHUTDOWN))
541 return aborted
Jon Salz258a40c2012-04-19 12:34:01 +0800542
Jon Salz0697cbf2012-07-04 15:14:04 +0800543 def init_states(self):
544 '''
545 Initializes all states on startup.
546 '''
547 for test in self.test_list.get_all_tests():
548 # Make sure the state server knows about all the tests,
549 # defaulting to an untested state.
550 test.update_state(update_parent=False, visible=False)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800551
Jon Salz0697cbf2012-07-04 15:14:04 +0800552 var_log_messages = None
Vic Yanga9c32212012-08-16 20:07:54 +0800553 mosys_log = None
Vic Yange4c275d2012-08-28 01:50:20 +0800554 ec_console_log = None
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800555
Jon Salz0697cbf2012-07-04 15:14:04 +0800556 # Any 'active' tests should be marked as failed now.
557 for test in self.test_list.walk():
Jon Salza6711d72012-07-18 14:33:03 +0800558 if not test.is_leaf():
559 # Don't bother with parents; they will be updated when their
560 # children are updated.
561 continue
562
Jon Salz0697cbf2012-07-04 15:14:04 +0800563 test_state = test.get_state()
564 if test_state.status != TestState.ACTIVE:
565 continue
566 if isinstance(test, factory.ShutdownStep):
567 # Shutdown while the test was active - that's good.
568 self.handle_shutdown_complete(test, test_state)
569 else:
570 # Unexpected shutdown. Grab /var/log/messages for context.
571 if var_log_messages is None:
572 try:
573 var_log_messages = (
574 utils.var_log_messages_before_reboot())
575 # Write it to the log, to make it easier to
576 # correlate with /var/log/messages.
577 logging.info(
578 'Unexpected shutdown. '
579 'Tail of /var/log/messages before last reboot:\n'
580 '%s', ('\n'.join(
581 ' ' + x for x in var_log_messages)))
582 except: # pylint: disable=W0702
583 logging.exception('Unable to grok /var/log/messages')
584 var_log_messages = []
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800585
Jon Salz008f4ea2012-08-28 05:39:45 +0800586 if mosys_log is None and not utils.in_chroot():
587 try:
588 mosys_log = utils.Spawn(
589 ['mosys', 'eventlog', 'list'],
590 read_stdout=True, log_stderr_on_error=True).stdout_data
591 # Write it to the log also.
592 logging.info('System eventlog from mosys:\n%s\n', mosys_log)
593 except: # pylint: disable=W0702
594 logging.exception('Unable to read mosys eventlog')
Vic Yanga9c32212012-08-16 20:07:54 +0800595
Vic Yange4c275d2012-08-28 01:50:20 +0800596 if ec_console_log is None:
597 try:
Vic Yang8341dde2013-01-29 16:48:52 +0800598 board = system.GetBoard()
599 ec_console_log = board.GetECConsoleLog()
Vic Yange4c275d2012-08-28 01:50:20 +0800600 logging.info('EC console log after reboot:\n%s\n', ec_console_log)
Jon Salzfe1f6652012-09-07 05:40:14 +0800601 except: # pylint: disable=W0702
Vic Yange4c275d2012-08-28 01:50:20 +0800602 logging.exception('Error retrieving EC console log')
603
Jon Salz0697cbf2012-07-04 15:14:04 +0800604 error_msg = 'Unexpected shutdown while test was running'
605 self.event_log.Log('end_test',
606 path=test.path,
607 status=TestState.FAILED,
608 invocation=test.get_state().invocation,
609 error_msg=error_msg,
Vic Yanga9c32212012-08-16 20:07:54 +0800610 var_log_messages='\n'.join(var_log_messages),
611 mosys_log=mosys_log)
Jon Salz0697cbf2012-07-04 15:14:04 +0800612 test.update_state(
613 status=TestState.FAILED,
614 error_msg=error_msg)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800615
Jon Salz50efe942012-07-26 11:54:10 +0800616 if not test.never_fails:
617 # For "never_fails" tests (such as "Start"), don't cancel
618 # pending tests, since reboot is expected.
619 factory.console.info('Unexpected shutdown while test %s '
620 'running; cancelling any pending tests',
621 test.path)
622 self.state_instance.set_shared_data('tests_after_shutdown', [])
Jon Salz69806bb2012-07-20 18:05:02 +0800623
Jon Salz008f4ea2012-08-28 05:39:45 +0800624 self.update_skipped_tests()
625
626 def update_skipped_tests(self):
627 '''
628 Updates skipped states based on run_if.
629 '''
630 for t in self.test_list.walk():
631 if t.is_leaf() and t.run_if_table_name:
632 skip = False
633 try:
634 aux = shopfloor.get_selected_aux_data(t.run_if_table_name)
635 value = aux.get(t.run_if_col)
636 if value is not None:
637 skip = (not value) ^ t.run_if_not
638 except ValueError:
639 # Not available; assume it shouldn't be skipped
640 pass
641
642 test_state = t.get_state()
643 if ((not skip) and
644 (test_state.status == TestState.PASSED) and
645 (test_state.error_msg == TestState.SKIPPED_MSG)):
646 # It was marked as skipped before, but now we need to run it.
647 # Mark as untested.
648 t.update_state(skip=skip, status=TestState.UNTESTED, error_msg='')
649 else:
650 t.update_state(skip=skip)
651
Jon Salz0697cbf2012-07-04 15:14:04 +0800652 def show_next_active_test(self):
653 '''
654 Rotates to the next visible active test.
655 '''
656 self.reap_completed_tests()
657 active_tests = [
658 t for t in self.test_list.walk()
659 if t.is_leaf() and t.get_state().status == TestState.ACTIVE]
660 if not active_tests:
661 return
Jon Salz4f6c7172012-06-11 20:45:36 +0800662
Jon Salz0697cbf2012-07-04 15:14:04 +0800663 try:
664 next_test = active_tests[
665 (active_tests.index(self.visible_test) + 1) % len(active_tests)]
666 except ValueError: # visible_test not present in active_tests
667 next_test = active_tests[0]
Jon Salz4f6c7172012-06-11 20:45:36 +0800668
Jon Salz0697cbf2012-07-04 15:14:04 +0800669 self.set_visible_test(next_test)
Jon Salz4f6c7172012-06-11 20:45:36 +0800670
Jon Salz0697cbf2012-07-04 15:14:04 +0800671 def handle_event(self, event):
672 '''
673 Handles an event from the event server.
674 '''
675 handler = self.event_handlers.get(event.type)
676 if handler:
677 handler(event)
678 else:
679 # We don't register handlers for all event types - just ignore
680 # this event.
681 logging.debug('Unbound event type %s', event.type)
Jon Salz4f6c7172012-06-11 20:45:36 +0800682
Vic Yangaabf9fd2013-04-09 18:56:13 +0800683 def check_critical_factory_note(self):
684 '''
685 Returns True if the last factory note is critical.
686 '''
687 notes = self.state_instance.get_shared_data('factory_note', True)
688 return notes and notes[-1]['level'] == 'CRITICAL'
689
Jon Salz0697cbf2012-07-04 15:14:04 +0800690 def run_next_test(self):
691 '''
692 Runs the next eligible test (or tests) in self.tests_to_run.
693 '''
694 self.reap_completed_tests()
Vic Yangaabf9fd2013-04-09 18:56:13 +0800695 if self.tests_to_run and self.check_critical_factory_note():
696 self.tests_to_run.clear()
697 return
Jon Salz0697cbf2012-07-04 15:14:04 +0800698 while self.tests_to_run:
699 logging.debug('Tests to run: %s',
700 [x.path for x in self.tests_to_run])
Jon Salz94eb56f2012-06-12 18:01:12 +0800701
Jon Salz0697cbf2012-07-04 15:14:04 +0800702 test = self.tests_to_run[0]
Jon Salz94eb56f2012-06-12 18:01:12 +0800703
Jon Salz0697cbf2012-07-04 15:14:04 +0800704 if test in self.invocations:
705 logging.info('Next test %s is already running', test.path)
706 self.tests_to_run.popleft()
707 return
Jon Salz94eb56f2012-06-12 18:01:12 +0800708
Jon Salza1412922012-07-23 16:04:17 +0800709 for requirement in test.require_run:
710 for i in requirement.test.walk():
711 if i.get_state().status == TestState.ACTIVE:
Jon Salz304a75d2012-07-06 11:14:15 +0800712 logging.info('Waiting for active test %s to complete '
Jon Salza1412922012-07-23 16:04:17 +0800713 'before running %s', i.path, test.path)
Jon Salz304a75d2012-07-06 11:14:15 +0800714 return
715
Jon Salz0697cbf2012-07-04 15:14:04 +0800716 if self.invocations and not (test.backgroundable and all(
717 [x.backgroundable for x in self.invocations])):
718 logging.debug('Waiting for non-backgroundable tests to '
719 'complete before running %s', test.path)
720 return
Jon Salz94eb56f2012-06-12 18:01:12 +0800721
Jon Salz3e6f5202012-10-15 15:08:29 +0800722 if test.get_state().skip:
723 factory.console.info('Skipping test %s', test.path)
724 test.update_state(status=TestState.PASSED,
725 error_msg=TestState.SKIPPED_MSG)
726 self.tests_to_run.popleft()
727 continue
728
Jon Salz0697cbf2012-07-04 15:14:04 +0800729 self.tests_to_run.popleft()
Jon Salz94eb56f2012-06-12 18:01:12 +0800730
Jon Salz304a75d2012-07-06 11:14:15 +0800731 untested = set()
Jon Salza1412922012-07-23 16:04:17 +0800732 for requirement in test.require_run:
733 for i in requirement.test.walk():
734 if i == test:
Jon Salz304a75d2012-07-06 11:14:15 +0800735 # We've hit this test itself; stop checking
736 break
Jon Salza1412922012-07-23 16:04:17 +0800737 if ((i.get_state().status == TestState.UNTESTED) or
738 (requirement.passed and i.get_state().status !=
739 TestState.PASSED)):
Jon Salz304a75d2012-07-06 11:14:15 +0800740 # Found an untested test; move on to the next
741 # element in require_run.
Jon Salza1412922012-07-23 16:04:17 +0800742 untested.add(i)
Jon Salz304a75d2012-07-06 11:14:15 +0800743 break
744
745 if untested:
746 untested_paths = ', '.join(sorted([x.path for x in untested]))
747 if self.state_instance.get_shared_data('engineering_mode',
748 optional=True):
749 # In engineering mode, we'll let it go.
750 factory.console.warn('In engineering mode; running '
751 '%s even though required tests '
752 '[%s] have not completed',
753 test.path, untested_paths)
754 else:
755 # Not in engineering mode; mark it failed.
756 error_msg = ('Required tests [%s] have not been run yet'
757 % untested_paths)
758 factory.console.error('Not running %s: %s',
759 test.path, error_msg)
760 test.update_state(status=TestState.FAILED,
761 error_msg=error_msg)
762 continue
763
Jon Salz0697cbf2012-07-04 15:14:04 +0800764 if isinstance(test, factory.ShutdownStep):
765 if os.path.exists(NO_REBOOT_FILE):
766 test.update_state(
767 status=TestState.FAILED, increment_count=1,
768 error_msg=('Skipped shutdown since %s is present' %
Jon Salz304a75d2012-07-06 11:14:15 +0800769 NO_REBOOT_FILE))
Jon Salz0697cbf2012-07-04 15:14:04 +0800770 continue
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800771
Jon Salz0697cbf2012-07-04 15:14:04 +0800772 test.update_state(status=TestState.ACTIVE, increment_count=1,
773 error_msg='', shutdown_count=0)
774 if self._prompt_cancel_shutdown(test, 1):
775 self.event_log.Log('reboot_cancelled')
776 test.update_state(
777 status=TestState.FAILED, increment_count=1,
778 error_msg='Shutdown aborted by operator',
779 shutdown_count=0)
chungyiafe8f772012-08-15 19:36:29 +0800780 continue
Jon Salz2f757d42012-06-27 17:06:42 +0800781
Jon Salz0697cbf2012-07-04 15:14:04 +0800782 # Save pending test list in the state server
Jon Salzdbf398f2012-06-14 17:30:01 +0800783 self.state_instance.set_shared_data(
Jon Salz0697cbf2012-07-04 15:14:04 +0800784 'tests_after_shutdown',
785 [t.path for t in self.tests_to_run])
786 # Save shutdown time
787 self.state_instance.set_shared_data('shutdown_time',
788 time.time())
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800789
Jon Salz0697cbf2012-07-04 15:14:04 +0800790 with self.env.lock:
791 self.event_log.Log('shutdown', operation=test.operation)
792 shutdown_result = self.env.shutdown(test.operation)
793 if shutdown_result:
794 # That's all, folks!
795 self.run_queue.put(None)
796 return
797 else:
798 # Just pass (e.g., in the chroot).
799 test.update_state(status=TestState.PASSED)
800 self.state_instance.set_shared_data(
801 'tests_after_shutdown', None)
802 # Send event with no fields to indicate that there is no
803 # longer a pending shutdown.
804 self.event_client.post_event(Event(
805 Event.Type.PENDING_SHUTDOWN))
806 continue
Jon Salz258a40c2012-04-19 12:34:01 +0800807
Cheng-Yi Chiangce05c002013-04-04 02:13:17 +0800808 self._run_test(test, test.iterations, test.retries)
Jon Salz1acc8742012-07-17 17:45:55 +0800809
Cheng-Yi Chiangce05c002013-04-04 02:13:17 +0800810 def _run_test(self, test, iterations_left=None, retries_left=None):
Jon Salz1acc8742012-07-17 17:45:55 +0800811 invoc = TestInvocation(self, test, on_completion=self.run_next_test)
812 new_state = test.update_state(
813 status=TestState.ACTIVE, increment_count=1, error_msg='',
Jon Salzbd42ce12012-09-18 08:03:59 +0800814 invocation=invoc.uuid, iterations_left=iterations_left,
Cheng-Yi Chiangce05c002013-04-04 02:13:17 +0800815 retries_left=retries_left,
Jon Salzbd42ce12012-09-18 08:03:59 +0800816 visible=(self.visible_test == test))
Jon Salz1acc8742012-07-17 17:45:55 +0800817 invoc.count = new_state.count
818
819 self.invocations[test] = invoc
820 if self.visible_test is None and test.has_ui:
821 self.set_visible_test(test)
Vic Yang311ddb82012-09-26 12:08:28 +0800822 self.check_exclusive()
Jon Salz1acc8742012-07-17 17:45:55 +0800823 invoc.start()
Jon Salz5f2a0672012-05-22 17:14:06 +0800824
Vic Yang311ddb82012-09-26 12:08:28 +0800825 def check_exclusive(self):
Jon Salzce6a7f82013-06-10 18:22:54 +0800826 # alias since this is really long
827 EXCL_OPT = factory.FactoryTest.EXCLUSIVE_OPTIONS
828
Vic Yang311ddb82012-09-26 12:08:28 +0800829 current_exclusive_items = set([
Jon Salzce6a7f82013-06-10 18:22:54 +0800830 item for item in EXCL_OPT
Vic Yang311ddb82012-09-26 12:08:28 +0800831 if any([test.is_exclusive(item) for test in self.invocations])])
832
833 new_exclusive_items = current_exclusive_items - self.exclusive_items
Jon Salzce6a7f82013-06-10 18:22:54 +0800834 if EXCL_OPT.NETWORKING in new_exclusive_items:
Vic Yang311ddb82012-09-26 12:08:28 +0800835 logging.info('Disabling network')
836 self.connection_manager.DisableNetworking()
Jon Salzce6a7f82013-06-10 18:22:54 +0800837 if EXCL_OPT.CHARGER in new_exclusive_items:
Vic Yang311ddb82012-09-26 12:08:28 +0800838 logging.info('Stop controlling charger')
839
840 new_non_exclusive_items = self.exclusive_items - current_exclusive_items
Jon Salzce6a7f82013-06-10 18:22:54 +0800841 if EXCL_OPT.NETWORKING in new_non_exclusive_items:
Vic Yang311ddb82012-09-26 12:08:28 +0800842 logging.info('Re-enabling network')
843 self.connection_manager.EnableNetworking()
Jon Salzce6a7f82013-06-10 18:22:54 +0800844 if EXCL_OPT.CHARGER in new_non_exclusive_items:
Vic Yang311ddb82012-09-26 12:08:28 +0800845 logging.info('Start controlling charger')
846
Jon Salzce6a7f82013-06-10 18:22:54 +0800847 if self.cpufreq_manager:
848 enabled = EXCL_OPT.CPUFREQ not in current_exclusive_items
849 try:
850 self.cpufreq_manager.SetEnabled(enabled)
851 except: # pylint: disable=W0702
852 logging.exception('Unable to %s cpufreq services',
853 'enable' if enabled else 'disable')
854
Vic Yang311ddb82012-09-26 12:08:28 +0800855 # Only adjust charge state if not excluded
Jon Salzce6a7f82013-06-10 18:22:54 +0800856 if (EXCL_OPT.CHARGER not in current_exclusive_items and
857 not utils.in_chroot()):
Cheng-Yi Chiangd8186952013-04-04 23:41:14 +0800858 if self.charge_manager:
859 self.charge_manager.AdjustChargeState()
860 else:
861 try:
862 system.GetBoard().SetChargeState(Board.ChargeState.CHARGE)
863 except BoardException:
864 logging.exception('Unable to set charge state on this board')
Vic Yang311ddb82012-09-26 12:08:28 +0800865
866 self.exclusive_items = current_exclusive_items
Jon Salz5da61e62012-05-31 13:06:22 +0800867
cychiang21886742012-07-05 15:16:32 +0800868 def check_for_updates(self):
869 '''
870 Schedules an asynchronous check for updates if necessary.
871 '''
872 if not self.test_list.options.update_period_secs:
873 # Not enabled.
874 return
875
876 now = time.time()
877 if self.last_update_check and (
878 now - self.last_update_check <
879 self.test_list.options.update_period_secs):
880 # Not yet time for another check.
881 return
882
883 self.last_update_check = now
884
885 def handle_check_for_update(reached_shopfloor, md5sum, needs_update):
886 if reached_shopfloor:
887 new_update_md5sum = md5sum if needs_update else None
888 if system.SystemInfo.update_md5sum != new_update_md5sum:
889 logging.info('Received new update MD5SUM: %s', new_update_md5sum)
890 system.SystemInfo.update_md5sum = new_update_md5sum
891 self.run_queue.put(self.update_system_info)
892
893 updater.CheckForUpdateAsync(
894 handle_check_for_update,
895 self.test_list.options.shopfloor_timeout_secs)
896
Jon Salza6711d72012-07-18 14:33:03 +0800897 def cancel_pending_tests(self):
898 '''Cancels any tests in the run queue.'''
899 self.run_tests([])
900
Jon Salz0697cbf2012-07-04 15:14:04 +0800901 def run_tests(self, subtrees, untested_only=False):
902 '''
903 Runs tests under subtree.
Jon Salz258a40c2012-04-19 12:34:01 +0800904
Jon Salz0697cbf2012-07-04 15:14:04 +0800905 The tests are run in order unless one fails (then stops).
906 Backgroundable tests are run simultaneously; when a foreground test is
907 encountered, we wait for all active tests to finish before continuing.
Jon Salzb1b39092012-05-03 02:05:09 +0800908
Jon Salz0697cbf2012-07-04 15:14:04 +0800909 @param subtrees: Node or nodes containing tests to run (may either be
910 a single test or a list). Duplicates will be ignored.
911 '''
912 if type(subtrees) != list:
913 subtrees = [subtrees]
Jon Salz258a40c2012-04-19 12:34:01 +0800914
Jon Salz0697cbf2012-07-04 15:14:04 +0800915 # Nodes we've seen so far, to avoid duplicates.
916 seen = set()
Jon Salz94eb56f2012-06-12 18:01:12 +0800917
Jon Salz0697cbf2012-07-04 15:14:04 +0800918 self.tests_to_run = deque()
919 for subtree in subtrees:
920 for test in subtree.walk():
921 if test in seen:
922 continue
923 seen.add(test)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800924
Jon Salz0697cbf2012-07-04 15:14:04 +0800925 if not test.is_leaf():
926 continue
927 if (untested_only and
928 test.get_state().status != TestState.UNTESTED):
929 continue
930 self.tests_to_run.append(test)
931 self.run_next_test()
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800932
Jon Salz0697cbf2012-07-04 15:14:04 +0800933 def reap_completed_tests(self):
934 '''
935 Removes completed tests from the set of active tests.
936
937 Also updates the visible test if it was reaped.
938 '''
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +0800939 test_completed = False
Jon Salz0697cbf2012-07-04 15:14:04 +0800940 for t, v in dict(self.invocations).iteritems():
941 if v.is_completed():
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +0800942 test_completed = True
Jon Salz1acc8742012-07-17 17:45:55 +0800943 new_state = t.update_state(**v.update_state_on_completion)
Jon Salz0697cbf2012-07-04 15:14:04 +0800944 del self.invocations[t]
945
Chun-Ta Lin54e17e42012-09-06 22:05:13 +0800946 # Stop on failure if flag is true.
947 if (self.test_list.options.stop_on_failure and
948 new_state.status == TestState.FAILED):
949 # Clean all the tests to cause goofy to stop.
950 self.tests_to_run = []
951 factory.console.info("Stop on failure triggered. Empty the queue.")
952
Jon Salz1acc8742012-07-17 17:45:55 +0800953 if new_state.iterations_left and new_state.status == TestState.PASSED:
954 # Play it again, Sam!
955 self._run_test(t)
Cheng-Yi Chiangce05c002013-04-04 02:13:17 +0800956 # new_state.retries_left is obtained after update.
957 # For retries_left == 0, test can still be run for the last time.
958 elif (new_state.retries_left >= 0 and
959 new_state.status == TestState.FAILED):
960 # Still have to retry, Sam!
961 self._run_test(t)
Jon Salz1acc8742012-07-17 17:45:55 +0800962
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +0800963 if test_completed:
Vic Yangf01c59f2013-04-19 17:37:56 +0800964 self.log_watcher.KickWatchThread()
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +0800965
Jon Salz0697cbf2012-07-04 15:14:04 +0800966 if (self.visible_test is None or
Jon Salz85a39882012-07-05 16:45:04 +0800967 self.visible_test not in self.invocations):
Jon Salz0697cbf2012-07-04 15:14:04 +0800968 self.set_visible_test(None)
969 # Make the first running test, if any, the visible test
970 for t in self.test_list.walk():
971 if t in self.invocations:
972 self.set_visible_test(t)
973 break
974
Jon Salz6dc031d2013-06-19 13:06:23 +0800975 def kill_active_tests(self, abort, root=None, reason=None):
Jon Salz0697cbf2012-07-04 15:14:04 +0800976 '''
977 Kills and waits for all active tests.
978
Jon Salz85a39882012-07-05 16:45:04 +0800979 Args:
980 abort: True to change state of killed tests to FAILED, False for
Jon Salz0697cbf2012-07-04 15:14:04 +0800981 UNTESTED.
Jon Salz85a39882012-07-05 16:45:04 +0800982 root: If set, only kills tests with root as an ancestor.
Jon Salz0697cbf2012-07-04 15:14:04 +0800983 '''
984 self.reap_completed_tests()
985 for test, invoc in self.invocations.items():
Jon Salz85a39882012-07-05 16:45:04 +0800986 if root and not test.has_ancestor(root):
987 continue
988
Jon Salz0697cbf2012-07-04 15:14:04 +0800989 factory.console.info('Killing active test %s...' % test.path)
Jon Salz6dc031d2013-06-19 13:06:23 +0800990 invoc.abort_and_join(reason)
Jon Salz0697cbf2012-07-04 15:14:04 +0800991 factory.console.info('Killed %s' % test.path)
Jon Salz1acc8742012-07-17 17:45:55 +0800992 test.update_state(**invoc.update_state_on_completion)
Jon Salz0697cbf2012-07-04 15:14:04 +0800993 del self.invocations[test]
Jon Salz1acc8742012-07-17 17:45:55 +0800994
Jon Salz0697cbf2012-07-04 15:14:04 +0800995 if not abort:
996 test.update_state(status=TestState.UNTESTED)
997 self.reap_completed_tests()
998
Jon Salz6dc031d2013-06-19 13:06:23 +0800999 def stop(self, root=None, fail=False, reason=None):
1000 self.kill_active_tests(fail, root, reason)
Jon Salz85a39882012-07-05 16:45:04 +08001001 # Remove any tests in the run queue under the root.
1002 self.tests_to_run = deque([x for x in self.tests_to_run
1003 if root and not x.has_ancestor(root)])
1004 self.run_next_test()
Jon Salz0697cbf2012-07-04 15:14:04 +08001005
Jon Salz4712ac72013-02-07 17:12:05 +08001006 def clear_state(self, root=None):
Jon Salz6dc031d2013-06-19 13:06:23 +08001007 self.stop(root, reason='Clearing test state')
Jon Salz4712ac72013-02-07 17:12:05 +08001008 for f in root.walk():
1009 if f.is_leaf():
1010 f.update_state(status=TestState.UNTESTED)
1011
Jon Salz6dc031d2013-06-19 13:06:23 +08001012 def abort_active_tests(self, reason=None):
1013 self.kill_active_tests(True, reason=reason)
Jon Salz0697cbf2012-07-04 15:14:04 +08001014
1015 def main(self):
Jon Salzeff94182013-06-19 15:06:28 +08001016 syslog.openlog('goofy')
1017
Jon Salz0697cbf2012-07-04 15:14:04 +08001018 try:
1019 self.init()
1020 self.event_log.Log('goofy_init',
1021 success=True)
1022 except:
1023 if self.event_log:
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001024 try:
Jon Salz0697cbf2012-07-04 15:14:04 +08001025 self.event_log.Log('goofy_init',
1026 success=False,
1027 trace=traceback.format_exc())
1028 except: # pylint: disable=W0702
1029 pass
1030 raise
1031
Jon Salzeff94182013-06-19 15:06:28 +08001032 syslog.syslog('Goofy (factory test harness) starting')
Jon Salz0697cbf2012-07-04 15:14:04 +08001033 self.run()
1034
1035 def update_system_info(self):
1036 '''Updates system info.'''
1037 system_info = system.SystemInfo()
1038 self.state_instance.set_shared_data('system_info', system_info.__dict__)
1039 self.event_client.post_event(Event(Event.Type.SYSTEM_INFO,
1040 system_info=system_info.__dict__))
1041 logging.info('System info: %r', system_info.__dict__)
1042
Jon Salzeb42f0d2012-07-27 19:14:04 +08001043 def update_factory(self, auto_run_on_restart=False, post_update_hook=None):
1044 '''Commences updating factory software.
1045
1046 Args:
1047 auto_run_on_restart: Auto-run when the machine comes back up.
1048 post_update_hook: Code to call after update but immediately before
1049 restart.
1050
1051 Returns:
1052 Never if the update was successful (we just reboot).
1053 False if the update was unnecessary (no update available).
1054 '''
Jon Salz6dc031d2013-06-19 13:06:23 +08001055 self.kill_active_tests(False, reason='Factory software update')
Jon Salza6711d72012-07-18 14:33:03 +08001056 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +08001057
Jon Salz5c344f62012-07-13 14:31:16 +08001058 def pre_update_hook():
1059 if auto_run_on_restart:
1060 self.state_instance.set_shared_data('tests_after_shutdown',
1061 FORCE_AUTO_RUN)
1062 self.state_instance.close()
1063
Jon Salzeb42f0d2012-07-27 19:14:04 +08001064 if updater.TryUpdate(pre_update_hook=pre_update_hook):
1065 if post_update_hook:
1066 post_update_hook()
1067 self.env.shutdown('reboot')
Jon Salz0697cbf2012-07-04 15:14:04 +08001068
Jon Salzcef132a2012-08-30 04:58:08 +08001069 def handle_sigint(self, dummy_signum, dummy_frame):
Jon Salz77c151e2012-08-28 07:20:37 +08001070 logging.error('Received SIGINT')
1071 self.run_queue.put(None)
1072 raise KeyboardInterrupt()
1073
Jon Salz0697cbf2012-07-04 15:14:04 +08001074 def init(self, args=None, env=None):
1075 '''Initializes Goofy.
1076
1077 Args:
1078 args: A list of command-line arguments. Uses sys.argv if
1079 args is None.
1080 env: An Environment instance to use (or None to choose
1081 FakeChrootEnvironment or DUTEnvironment as appropriate).
1082 '''
Jon Salz77c151e2012-08-28 07:20:37 +08001083 signal.signal(signal.SIGINT, self.handle_sigint)
1084
Jon Salz0697cbf2012-07-04 15:14:04 +08001085 parser = OptionParser()
1086 parser.add_option('-v', '--verbose', dest='verbose',
Jon Salz8fa8e832012-07-13 19:04:09 +08001087 action='store_true',
1088 help='Enable debug logging')
Jon Salz0697cbf2012-07-04 15:14:04 +08001089 parser.add_option('--print_test_list', dest='print_test_list',
Jon Salz8fa8e832012-07-13 19:04:09 +08001090 metavar='FILE',
1091 help='Read and print test list FILE, and exit')
Jon Salz0697cbf2012-07-04 15:14:04 +08001092 parser.add_option('--restart', dest='restart',
Jon Salz8fa8e832012-07-13 19:04:09 +08001093 action='store_true',
1094 help='Clear all test state')
Jon Salz0697cbf2012-07-04 15:14:04 +08001095 parser.add_option('--ui', dest='ui', type='choice',
Jon Salz8fa8e832012-07-13 19:04:09 +08001096 choices=['none', 'gtk', 'chrome'],
Jon Salz2f881df2013-02-01 17:00:35 +08001097 default='chrome',
Jon Salz8fa8e832012-07-13 19:04:09 +08001098 help='UI to use')
Jon Salz0697cbf2012-07-04 15:14:04 +08001099 parser.add_option('--ui_scale_factor', dest='ui_scale_factor',
Jon Salz8fa8e832012-07-13 19:04:09 +08001100 type='int', default=1,
1101 help=('Factor by which to scale UI '
1102 '(Chrome UI only)'))
Jon Salz0697cbf2012-07-04 15:14:04 +08001103 parser.add_option('--test_list', dest='test_list',
Jon Salz8fa8e832012-07-13 19:04:09 +08001104 metavar='FILE',
1105 help='Use FILE as test list')
Jon Salzc79a9982012-08-30 04:42:01 +08001106 parser.add_option('--dummy_shopfloor', action='store_true',
1107 help='Use a dummy shopfloor server')
chungyiafe8f772012-08-15 19:36:29 +08001108 parser.add_option('--automation', dest='automation',
1109 action='store_true',
1110 help='Enable automation on running factory test')
Ricky Liang09216dc2013-02-22 17:26:45 +08001111 parser.add_option('--one_pixel_less', dest='one_pixel_less',
1112 action='store_true',
1113 help=('Start Chrome one pixel less than the full screen.'
1114 'Needed by Exynos platform to run GTK.'))
Jon Salz0697cbf2012-07-04 15:14:04 +08001115 (self.options, self.args) = parser.parse_args(args)
1116
Jon Salz46b89562012-07-05 11:49:22 +08001117 # Make sure factory directories exist.
1118 factory.get_log_root()
1119 factory.get_state_root()
1120 factory.get_test_data_root()
1121
Jon Salz0697cbf2012-07-04 15:14:04 +08001122 global _inited_logging # pylint: disable=W0603
1123 if not _inited_logging:
1124 factory.init_logging('goofy', verbose=self.options.verbose)
1125 _inited_logging = True
Jon Salz8fa8e832012-07-13 19:04:09 +08001126
Jon Salz0f996602012-10-03 15:26:48 +08001127 if self.options.print_test_list:
1128 print factory.read_test_list(
1129 self.options.print_test_list).__repr__(recursive=True)
1130 sys.exit(0)
1131
Jon Salzee85d522012-07-17 14:34:46 +08001132 event_log.IncrementBootSequence()
Jon Salzd15bbcf2013-05-21 17:33:57 +08001133 # Don't defer logging the initial event, so we can make sure
1134 # that device_id, reimage_id, etc. are all set up.
1135 self.event_log = EventLog('goofy', defer=False)
Jon Salz0697cbf2012-07-04 15:14:04 +08001136
1137 if (not suppress_chroot_warning and
1138 factory.in_chroot() and
1139 self.options.ui == 'gtk' and
1140 os.environ.get('DISPLAY') in [None, '', ':0', ':0.0']):
1141 # That's not going to work! Tell the user how to run
1142 # this way.
1143 logging.warn(GOOFY_IN_CHROOT_WARNING)
1144 time.sleep(1)
1145
1146 if env:
1147 self.env = env
1148 elif factory.in_chroot():
1149 self.env = test_environment.FakeChrootEnvironment()
1150 logging.warn(
1151 'Using chroot environment: will not actually run autotests')
1152 else:
1153 self.env = test_environment.DUTEnvironment()
1154 self.env.goofy = self
1155
1156 if self.options.restart:
1157 state.clear_state()
1158
Jon Salz0697cbf2012-07-04 15:14:04 +08001159 if self.options.ui_scale_factor != 1 and utils.in_qemu():
1160 logging.warn(
1161 'In QEMU; ignoring ui_scale_factor argument')
1162 self.options.ui_scale_factor = 1
1163
1164 logging.info('Started')
1165
1166 self.start_state_server()
1167 self.state_instance.set_shared_data('hwid_cfg', get_hwid_cfg())
1168 self.state_instance.set_shared_data('ui_scale_factor',
Ricky Liang09216dc2013-02-22 17:26:45 +08001169 self.options.ui_scale_factor)
1170 self.state_instance.set_shared_data('one_pixel_less',
1171 self.options.one_pixel_less)
Jon Salz0697cbf2012-07-04 15:14:04 +08001172 self.last_shutdown_time = (
1173 self.state_instance.get_shared_data('shutdown_time', optional=True))
1174 self.state_instance.del_shared_data('shutdown_time', optional=True)
1175
Jon Salzb19ea072013-02-07 16:35:00 +08001176 self.state_instance.del_shared_data('startup_error', optional=True)
Jon Salz0697cbf2012-07-04 15:14:04 +08001177 if not self.options.test_list:
1178 self.options.test_list = find_test_list()
Jon Salzb19ea072013-02-07 16:35:00 +08001179 if self.options.test_list:
Jon Salz0697cbf2012-07-04 15:14:04 +08001180 logging.info('Using test list %s', self.options.test_list)
Jon Salzb19ea072013-02-07 16:35:00 +08001181 try:
1182 self.test_list = factory.read_test_list(
1183 self.options.test_list,
1184 self.state_instance)
1185 except: # pylint: disable=W0702
1186 logging.exception('Unable to read test list %r', self.options.test_list)
1187 self.state_instance.set_shared_data('startup_error',
1188 'Unable to read test list %s\n%s' % (
1189 self.options.test_list,
1190 traceback.format_exc()))
1191 else:
1192 logging.error('No test list found.')
1193 self.state_instance.set_shared_data('startup_error',
1194 'No test list found.')
Jon Salz0697cbf2012-07-04 15:14:04 +08001195
Jon Salzb19ea072013-02-07 16:35:00 +08001196 if not self.test_list:
1197 if self.options.ui == 'chrome':
1198 # Create an empty test list with default options so that the rest of
1199 # startup can proceed.
1200 self.test_list = factory.FactoryTestList(
1201 [], self.state_instance, factory.Options())
1202 else:
1203 # Bail with an error; no point in starting up.
1204 sys.exit('No valid test list; exiting.')
1205
Jon Salz822838b2013-03-25 17:32:33 +08001206 if self.test_list.options.clear_state_on_start:
1207 self.state_instance.clear_test_state()
1208
Vic Yang3e1cf5d2013-06-05 18:50:24 +08001209 if system.SystemInfo().firmware_version is None and not utils.in_chroot():
Vic Yang9bd4f772013-06-04 17:34:00 +08001210 self.state_instance.set_shared_data('startup_error',
1211 'Netboot firmware detected\n'
1212 'Connect Ethernet and reboot to re-image.\n'
1213 u'侦测到网路开机固件\n'
1214 u'请连接乙太网并重启')
1215
Jon Salz0697cbf2012-07-04 15:14:04 +08001216 if not self.state_instance.has_shared_data('ui_lang'):
1217 self.state_instance.set_shared_data('ui_lang',
1218 self.test_list.options.ui_lang)
1219 self.state_instance.set_shared_data(
1220 'test_list_options',
1221 self.test_list.options.__dict__)
1222 self.state_instance.test_list = self.test_list
1223
Jon Salz83ef34b2012-11-01 19:46:35 +08001224 if not utils.in_chroot() and self.test_list.options.disable_log_rotation:
1225 open('/var/lib/cleanup_logs_paused', 'w').close()
1226
Jon Salz23926422012-09-01 03:38:13 +08001227 if self.options.dummy_shopfloor:
1228 os.environ[shopfloor.SHOPFLOOR_SERVER_ENV_VAR_NAME] = (
1229 'http://localhost:%d/' % shopfloor.DEFAULT_SERVER_PORT)
1230 self.dummy_shopfloor = Spawn(
1231 [os.path.join(factory.FACTORY_PATH, 'bin', 'shopfloor_server'),
1232 '--dummy'])
1233 elif self.test_list.options.shopfloor_server_url:
1234 shopfloor.set_server_url(self.test_list.options.shopfloor_server_url)
Jon Salz2bf2f6b2013-03-28 18:49:26 +08001235 shopfloor.set_enabled(True)
Jon Salz23926422012-09-01 03:38:13 +08001236
Jon Salz0f996602012-10-03 15:26:48 +08001237 if self.test_list.options.time_sanitizer and not utils.in_chroot():
Jon Salz8fa8e832012-07-13 19:04:09 +08001238 self.time_sanitizer = time_sanitizer.TimeSanitizer(
1239 base_time=time_sanitizer.GetBaseTimeFromFile(
1240 # lsb-factory is written by the factory install shim during
1241 # installation, so it should have a good time obtained from
Jon Salz54882d02012-08-31 01:57:54 +08001242 # the mini-Omaha server. If it's not available, we'll use
1243 # /etc/lsb-factory (which will be much older, but reasonably
1244 # sane) and rely on a shopfloor sync to set a more accurate
1245 # time.
1246 '/usr/local/etc/lsb-factory',
1247 '/etc/lsb-release'))
Jon Salz8fa8e832012-07-13 19:04:09 +08001248 self.time_sanitizer.RunOnce()
1249
Jon Salz0697cbf2012-07-04 15:14:04 +08001250 self.init_states()
1251 self.start_event_server()
1252 self.connection_manager = self.env.create_connection_manager(
Tai-Hsu Lin371351a2012-08-27 14:17:14 +08001253 self.test_list.options.wlans,
1254 self.test_list.options.scan_wifi_period_secs)
Jon Salz0697cbf2012-07-04 15:14:04 +08001255 # Note that we create a log watcher even if
1256 # sync_event_log_period_secs isn't set (no background
1257 # syncing), since we may use it to flush event logs as well.
1258 self.log_watcher = EventLogWatcher(
1259 self.test_list.options.sync_event_log_period_secs,
Jon Salzd15bbcf2013-05-21 17:33:57 +08001260 event_log_db_file=None,
Jon Salz16d10542012-07-23 12:18:45 +08001261 handle_event_logs_callback=self.handle_event_logs)
Jon Salz0697cbf2012-07-04 15:14:04 +08001262 if self.test_list.options.sync_event_log_period_secs:
1263 self.log_watcher.StartWatchThread()
1264
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +08001265 # Note that we create a system log manager even if
1266 # sync_log_period_secs isn't set (no background
1267 # syncing), since we may kick it to sync logs in its
1268 # thread.
1269 self.system_log_manager = SystemLogManager(
Cheng-Yi Chiang835f2682013-05-06 22:15:48 +08001270 sync_log_paths=self.test_list.options.sync_log_paths,
1271 sync_period_sec=self.test_list.options.sync_log_period_secs,
1272 clear_log_paths=self.test_list.options.clear_log_paths)
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +08001273 self.system_log_manager.StartSyncThread()
1274
Jon Salz0697cbf2012-07-04 15:14:04 +08001275 self.update_system_info()
1276
Vic Yang4953fc12012-07-26 16:19:53 +08001277 assert ((self.test_list.options.min_charge_pct is None) ==
1278 (self.test_list.options.max_charge_pct is None))
Vic Yange83d9a12013-04-19 20:00:20 +08001279 if utils.in_chroot():
1280 logging.info('In chroot, ignoring charge manager and charge state')
1281 elif self.test_list.options.min_charge_pct is not None:
Vic Yang4953fc12012-07-26 16:19:53 +08001282 self.charge_manager = ChargeManager(self.test_list.options.min_charge_pct,
1283 self.test_list.options.max_charge_pct)
Jon Salzad7353b2012-10-15 16:22:46 +08001284 system.SystemStatus.charge_manager = self.charge_manager
Cheng-Yi Chiangd8186952013-04-04 23:41:14 +08001285 else:
1286 # Goofy should set charger state to charge if charge_manager is disabled.
1287 try:
1288 system.GetBoard().SetChargeState(Board.ChargeState.CHARGE)
1289 except BoardException:
1290 logging.exception('Unable to set charge state on this board')
Vic Yang4953fc12012-07-26 16:19:53 +08001291
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001292 self.core_dump_manager = CoreDumpManager(
1293 self.test_list.options.core_dump_watchlist)
1294
Jon Salz0697cbf2012-07-04 15:14:04 +08001295 os.environ['CROS_FACTORY'] = '1'
1296 os.environ['CROS_DISABLE_SITE_SYSINFO'] = '1'
1297
1298 # Set CROS_UI since some behaviors in ui.py depend on the
1299 # particular UI in use. TODO(jsalz): Remove this (and all
1300 # places it is used) when the GTK UI is removed.
1301 os.environ['CROS_UI'] = self.options.ui
1302
Jon Salz416f9cc2013-05-10 18:32:50 +08001303 # Initialize hooks.
1304 module, cls = self.test_list.options.hooks_class.rsplit('.', 1)
1305 self.hooks = getattr(__import__(module, fromlist=[cls]), cls)()
1306 assert isinstance(self.hooks, factory.Hooks), (
1307 "hooks should be of type Hooks but is %r" % type(self.hooks))
1308 self.hooks.test_list = self.test_list
1309
Jon Salzce6a7f82013-06-10 18:22:54 +08001310 if not utils.in_chroot():
Jon Salzddf0d052013-06-18 12:52:44 +08001311 self.cpufreq_manager = CpufreqManager(event_log=self.event_log)
Jon Salzce6a7f82013-06-10 18:22:54 +08001312
Jon Salz416f9cc2013-05-10 18:32:50 +08001313 # Call startup hook.
1314 self.hooks.OnStartup()
1315
Jon Salz0697cbf2012-07-04 15:14:04 +08001316 if self.options.ui == 'chrome':
1317 self.env.launch_chrome()
1318 logging.info('Waiting for a web socket connection')
Cheng-Yi Chiangfd8ed392013-03-08 21:37:31 +08001319 self.web_socket_manager.wait()
Jon Salz0697cbf2012-07-04 15:14:04 +08001320
1321 # Wait for the test widget size to be set; this is done in
1322 # an asynchronous RPC so there is a small chance that the
1323 # web socket might be opened first.
1324 for _ in range(100): # 10 s
1325 try:
1326 if self.state_instance.get_shared_data('test_widget_size'):
1327 break
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001328 except KeyError:
Jon Salz0697cbf2012-07-04 15:14:04 +08001329 pass # Retry
1330 time.sleep(0.1) # 100 ms
1331 else:
1332 logging.warn('Never received test_widget_size from UI')
Jon Salz45297282013-05-18 14:31:47 +08001333
1334 # Send Chrome a Tab to get focus to the factory UI
1335 # (http://crosbug.com/p/19444). TODO(jsalz): remove this hack
1336 # and figure out the right way to get the focus to Chrome.
1337 if not utils.in_chroot():
1338 Spawn(
1339 [os.path.join(factory.FACTORY_PATH, 'bin', 'send_key'), 'Tab'],
1340 check_call=True, log=True)
Jon Salz0697cbf2012-07-04 15:14:04 +08001341 elif self.options.ui == 'gtk':
1342 self.start_ui()
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001343
Ricky Liang650f6bf2012-09-28 13:22:54 +08001344 # Create download path for autotest beforehand or autotests run at
1345 # the same time might fail due to race condition.
1346 if not factory.in_chroot():
1347 utils.TryMakeDirs(os.path.join('/usr/local/autotest', 'tests',
1348 'download'))
1349
Jon Salz0697cbf2012-07-04 15:14:04 +08001350 def state_change_callback(test, test_state):
1351 self.event_client.post_event(
1352 Event(Event.Type.STATE_CHANGE,
1353 path=test.path, state=test_state))
1354 self.test_list.state_change_callback = state_change_callback
Jon Salz73e0fd02012-04-04 11:46:38 +08001355
Jon Salza6711d72012-07-18 14:33:03 +08001356 for handler in self.on_ui_startup:
1357 handler()
1358
1359 self.prespawner = Prespawner()
1360 self.prespawner.start()
1361
Jon Salz0697cbf2012-07-04 15:14:04 +08001362 try:
1363 tests_after_shutdown = self.state_instance.get_shared_data(
1364 'tests_after_shutdown')
1365 except KeyError:
1366 tests_after_shutdown = None
Jon Salz57717ca2012-04-04 16:47:25 +08001367
Jon Salz5c344f62012-07-13 14:31:16 +08001368 force_auto_run = (tests_after_shutdown == FORCE_AUTO_RUN)
1369 if not force_auto_run and tests_after_shutdown is not None:
Jon Salz0697cbf2012-07-04 15:14:04 +08001370 logging.info('Resuming tests after shutdown: %s',
1371 tests_after_shutdown)
Jon Salz0697cbf2012-07-04 15:14:04 +08001372 self.tests_to_run.extend(
1373 self.test_list.lookup_path(t) for t in tests_after_shutdown)
1374 self.run_queue.put(self.run_next_test)
1375 else:
Jon Salz5c344f62012-07-13 14:31:16 +08001376 if force_auto_run or self.test_list.options.auto_run_on_start:
Jon Salz0697cbf2012-07-04 15:14:04 +08001377 self.run_queue.put(
1378 lambda: self.run_tests(self.test_list, untested_only=True))
Jon Salz5c344f62012-07-13 14:31:16 +08001379 self.state_instance.set_shared_data('tests_after_shutdown', None)
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001380
Dean Liao592e4d52013-01-10 20:06:39 +08001381 self.may_disable_cros_shortcut_keys()
1382
1383 def may_disable_cros_shortcut_keys(self):
1384 test_options = self.test_list.options
1385 if test_options.disable_cros_shortcut_keys:
1386 logging.info('Filter ChromeOS shortcut keys.')
1387 self.key_filter = KeyFilter(
1388 unmap_caps_lock=test_options.disable_caps_lock,
1389 caps_lock_keycode=test_options.caps_lock_keycode)
1390 self.key_filter.Start()
1391
Jon Salz0697cbf2012-07-04 15:14:04 +08001392 def run(self):
1393 '''Runs Goofy.'''
1394 # Process events forever.
1395 while self.run_once(True):
1396 pass
Jon Salz73e0fd02012-04-04 11:46:38 +08001397
Jon Salz0697cbf2012-07-04 15:14:04 +08001398 def run_once(self, block=False):
1399 '''Runs all items pending in the event loop.
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001400
Jon Salz0697cbf2012-07-04 15:14:04 +08001401 Args:
1402 block: If true, block until at least one event is processed.
Jon Salz7c15e8b2012-06-19 17:10:37 +08001403
Jon Salz0697cbf2012-07-04 15:14:04 +08001404 Returns:
1405 True to keep going or False to shut down.
1406 '''
1407 events = utils.DrainQueue(self.run_queue)
cychiang21886742012-07-05 15:16:32 +08001408 while not events:
Jon Salz0697cbf2012-07-04 15:14:04 +08001409 # Nothing on the run queue.
1410 self._run_queue_idle()
1411 if block:
1412 # Block for at least one event...
cychiang21886742012-07-05 15:16:32 +08001413 try:
1414 events.append(self.run_queue.get(timeout=RUN_QUEUE_TIMEOUT_SECS))
1415 except Queue.Empty:
1416 # Keep going (calling _run_queue_idle() again at the top of
1417 # the loop)
1418 continue
Jon Salz0697cbf2012-07-04 15:14:04 +08001419 # ...and grab anything else that showed up at the same
1420 # time.
1421 events.extend(utils.DrainQueue(self.run_queue))
cychiang21886742012-07-05 15:16:32 +08001422 else:
1423 break
Jon Salz51528e12012-07-02 18:54:45 +08001424
Jon Salz0697cbf2012-07-04 15:14:04 +08001425 for event in events:
1426 if not event:
1427 # Shutdown request.
1428 self.run_queue.task_done()
1429 return False
Jon Salz51528e12012-07-02 18:54:45 +08001430
Jon Salz0697cbf2012-07-04 15:14:04 +08001431 try:
1432 event()
Jon Salz85a39882012-07-05 16:45:04 +08001433 except: # pylint: disable=W0702
1434 logging.exception('Error in event loop')
Jon Salz0697cbf2012-07-04 15:14:04 +08001435 self.record_exception(traceback.format_exception_only(
1436 *sys.exc_info()[:2]))
1437 # But keep going
1438 finally:
1439 self.run_queue.task_done()
1440 return True
Jon Salz0405ab52012-03-16 15:26:52 +08001441
Jon Salz0e6532d2012-10-25 16:30:11 +08001442 def _should_sync_time(self, foreground=False):
1443 '''Returns True if we should attempt syncing time with shopfloor.
1444
1445 Args:
1446 foreground: If True, synchronizes even if background syncing
1447 is disabled (e.g., in explicit sync requests from the
1448 SyncShopfloor test).
1449 '''
1450 return ((foreground or
1451 self.test_list.options.sync_time_period_secs) and
Jon Salz54882d02012-08-31 01:57:54 +08001452 self.time_sanitizer and
1453 (not self.time_synced) and
1454 (not factory.in_chroot()))
1455
Jon Salz0e6532d2012-10-25 16:30:11 +08001456 def sync_time_with_shopfloor_server(self, foreground=False):
Jon Salz54882d02012-08-31 01:57:54 +08001457 '''Syncs time with shopfloor server, if not yet synced.
1458
Jon Salz0e6532d2012-10-25 16:30:11 +08001459 Args:
1460 foreground: If True, synchronizes even if background syncing
1461 is disabled (e.g., in explicit sync requests from the
1462 SyncShopfloor test).
1463
Jon Salz54882d02012-08-31 01:57:54 +08001464 Returns:
1465 False if no time sanitizer is available, or True if this sync (or a
1466 previous sync) succeeded.
1467
1468 Raises:
1469 Exception if unable to contact the shopfloor server.
1470 '''
Jon Salz0e6532d2012-10-25 16:30:11 +08001471 if self._should_sync_time(foreground):
Jon Salz54882d02012-08-31 01:57:54 +08001472 self.time_sanitizer.SyncWithShopfloor()
1473 self.time_synced = True
1474 return self.time_synced
1475
Jon Salzb92c5112012-09-21 15:40:11 +08001476 def log_disk_space_stats(self):
Jon Salz18e0e022013-06-11 17:13:39 +08001477 if (utils.in_chroot() or
1478 not self.test_list.options.log_disk_space_period_secs):
Jon Salzb92c5112012-09-21 15:40:11 +08001479 return
1480
1481 now = time.time()
1482 if (self.last_log_disk_space_time and
1483 now - self.last_log_disk_space_time <
1484 self.test_list.options.log_disk_space_period_secs):
1485 return
1486 self.last_log_disk_space_time = now
1487
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001488 # Upload event if stateful partition usage is above threshold.
1489 # Stateful partition is mounted on /usr/local, while
1490 # encrypted stateful partition is mounted on /var.
1491 # If there are too much logs in the factory process,
1492 # these two partitions might get full.
Jon Salzb92c5112012-09-21 15:40:11 +08001493 try:
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001494 vfs_infos = disk_space.GetAllVFSInfo()
1495 stateful_info, encrypted_info = None, None
1496 for vfs_info in vfs_infos.values():
1497 if '/usr/local' in vfs_info.mount_points:
1498 stateful_info = vfs_info
1499 if '/var' in vfs_info.mount_points:
1500 encrypted_info = vfs_info
1501
1502 stateful = disk_space.GetPartitionUsage(stateful_info)
1503 encrypted = disk_space.GetPartitionUsage(encrypted_info)
1504
1505 above_threshold = (
1506 self.test_list.options.stateful_usage_threshold and
1507 max(stateful.bytes_used_pct,
1508 stateful.inodes_used_pct,
1509 encrypted.bytes_used_pct,
1510 encrypted.inodes_used_pct) >
1511 self.test_list.options.stateful_usage_threshold)
1512
1513 if above_threshold:
1514 self.event_log.Log('stateful_partition_usage',
1515 partitions={
1516 'stateful': {
1517 'bytes_used_pct': FloatDigit(stateful.bytes_used_pct, 2),
1518 'inodes_used_pct': FloatDigit(stateful.inodes_used_pct, 2)},
1519 'encrypted_stateful': {
1520 'bytes_used_pct': FloatDigit(encrypted.bytes_used_pct, 2),
1521 'inodes_used_pct': FloatDigit(encrypted.inodes_used_pct, 2)}
1522 })
1523 self.log_watcher.ScanEventLogs()
1524
1525 message = disk_space.FormatSpaceUsedAll(vfs_infos)
Jon Salz3c493bb2013-02-07 17:24:58 +08001526 if message != self.last_log_disk_space_message:
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001527 if above_threshold:
1528 logging.warning(message)
1529 else:
1530 logging.info(message)
Jon Salz3c493bb2013-02-07 17:24:58 +08001531 self.last_log_disk_space_message = message
Jon Salzb92c5112012-09-21 15:40:11 +08001532 except: # pylint: disable=W0702
1533 logging.exception('Unable to get disk space used')
1534
Justin Chuang83813982013-05-13 01:26:32 +08001535 def check_battery(self):
1536 '''Checks the current battery status.
1537
1538 Logs current battery charging level and status to log. If the battery level
1539 is lower below warning_low_battery_pct, send warning event to shopfloor.
1540 If the battery level is lower below critical_low_battery_pct, flush disks.
1541 '''
1542 if not self.test_list.options.check_battery_period_secs:
1543 return
1544
1545 now = time.time()
1546 if (self.last_check_battery_time and
1547 now - self.last_check_battery_time <
1548 self.test_list.options.check_battery_period_secs):
1549 return
1550 self.last_check_battery_time = now
1551
1552 message = ''
1553 log_level = logging.INFO
1554 try:
1555 power = system.GetBoard().power
1556 if not power.CheckBatteryPresent():
1557 message = 'Battery is not present'
1558 else:
1559 ac_present = power.CheckACPresent()
1560 charge_pct = power.GetChargePct(get_float=True)
1561 message = ('Current battery level %.1f%%, AC charger is %s' %
1562 (charge_pct, 'connected' if ac_present else 'disconnected'))
1563
1564 if charge_pct > self.test_list.options.critical_low_battery_pct:
1565 critical_low_battery = False
1566 else:
1567 critical_low_battery = True
1568 # Only sync disks when battery level is still above minimum
1569 # value. This can be used for offline analysis when shopfloor cannot
1570 # be connected.
1571 if charge_pct > MIN_BATTERY_LEVEL_FOR_DISK_SYNC:
1572 logging.warning('disk syncing for critical low battery situation')
1573 os.system('sync; sync; sync')
1574 else:
1575 logging.warning('disk syncing is cancelled '
1576 'because battery level is lower than %.1f',
1577 MIN_BATTERY_LEVEL_FOR_DISK_SYNC)
1578
1579 # Notify shopfloor server
1580 if (critical_low_battery or
1581 (not ac_present and
1582 charge_pct <= self.test_list.options.warning_low_battery_pct)):
1583 log_level = logging.WARNING
1584
1585 self.event_log.Log('low_battery',
1586 battery_level=charge_pct,
1587 charger_connected=ac_present,
1588 critical=critical_low_battery)
1589 self.log_watcher.KickWatchThread()
1590 self.system_log_manager.KickSyncThread()
1591 except: # pylint: disable=W0702
1592 logging.exception('Unable to check battery or notify shopfloor')
1593 finally:
1594 if message != self.last_check_battery_message:
1595 logging.log(log_level, message)
1596 self.last_check_battery_message = message
1597
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001598 def check_core_dump(self):
1599 '''Checks if there is any core dumped file.
1600
1601 Removes unwanted core dump files immediately.
1602 Syncs those files matching watch list to server with a delay between
1603 each sync. After the files have been synced to server, deletes the files.
1604 '''
1605 core_dump_files = self.core_dump_manager.ScanFiles()
1606 if core_dump_files:
1607 now = time.time()
1608 if (self.last_kick_sync_time and now - self.last_kick_sync_time <
1609 self.test_list.options.kick_sync_min_interval_secs):
1610 return
1611 self.last_kick_sync_time = now
1612
1613 # Sends event to server
1614 self.event_log.Log('core_dumped', files=core_dump_files)
1615 self.log_watcher.KickWatchThread()
1616
1617 # Syncs files to server
1618 self.system_log_manager.KickSyncThread(
1619 core_dump_files, self.core_dump_manager.ClearFiles)
1620
Jon Salz8fa8e832012-07-13 19:04:09 +08001621 def sync_time_in_background(self):
Jon Salzb22d1172012-08-06 10:38:57 +08001622 '''Writes out current time and tries to sync with shopfloor server.'''
1623 if not self.time_sanitizer:
1624 return
1625
1626 # Write out the current time.
1627 self.time_sanitizer.SaveTime()
1628
Jon Salz54882d02012-08-31 01:57:54 +08001629 if not self._should_sync_time():
Jon Salz8fa8e832012-07-13 19:04:09 +08001630 return
1631
1632 now = time.time()
1633 if self.last_sync_time and (
1634 now - self.last_sync_time <
1635 self.test_list.options.sync_time_period_secs):
1636 # Not yet time for another check.
1637 return
1638 self.last_sync_time = now
1639
1640 def target():
1641 try:
Jon Salz54882d02012-08-31 01:57:54 +08001642 self.sync_time_with_shopfloor_server()
Jon Salz8fa8e832012-07-13 19:04:09 +08001643 except: # pylint: disable=W0702
1644 # Oh well. Log an error (but no trace)
1645 logging.info(
1646 'Unable to get time from shopfloor server: %s',
1647 utils.FormatExceptionOnly())
1648
1649 thread = threading.Thread(target=target)
1650 thread.daemon = True
1651 thread.start()
1652
Jon Salz0697cbf2012-07-04 15:14:04 +08001653 def _run_queue_idle(self):
Vic Yang4953fc12012-07-26 16:19:53 +08001654 '''Invoked when the run queue has no events.
1655
1656 This method must not raise exception.
1657 '''
Jon Salzb22d1172012-08-06 10:38:57 +08001658 now = time.time()
1659 if (self.last_idle and
1660 now < (self.last_idle + RUN_QUEUE_TIMEOUT_SECS - 1)):
1661 # Don't run more often than once every (RUN_QUEUE_TIMEOUT_SECS -
1662 # 1) seconds.
1663 return
1664
1665 self.last_idle = now
1666
Vic Yang311ddb82012-09-26 12:08:28 +08001667 self.check_exclusive()
cychiang21886742012-07-05 15:16:32 +08001668 self.check_for_updates()
Jon Salz8fa8e832012-07-13 19:04:09 +08001669 self.sync_time_in_background()
Jon Salzb92c5112012-09-21 15:40:11 +08001670 self.log_disk_space_stats()
Justin Chuang83813982013-05-13 01:26:32 +08001671 self.check_battery()
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001672 self.check_core_dump()
Jon Salz57717ca2012-04-04 16:47:25 +08001673
Jon Salzd15bbcf2013-05-21 17:33:57 +08001674 def handle_event_logs(self, chunks):
Jon Salz0697cbf2012-07-04 15:14:04 +08001675 '''Callback for event watcher.
Jon Salz258a40c2012-04-19 12:34:01 +08001676
Jon Salz0697cbf2012-07-04 15:14:04 +08001677 Attempts to upload the event logs to the shopfloor server.
Vic Yang93027612013-05-06 02:42:49 +08001678
1679 Args:
Jon Salzd15bbcf2013-05-21 17:33:57 +08001680 chunks: A list of Chunk objects.
Jon Salz0697cbf2012-07-04 15:14:04 +08001681 '''
Vic Yang93027612013-05-06 02:42:49 +08001682 first_exception = None
1683 exception_count = 0
1684
Jon Salzd15bbcf2013-05-21 17:33:57 +08001685 for chunk in chunks:
Vic Yang93027612013-05-06 02:42:49 +08001686 try:
Jon Salzcddb6402013-05-23 12:56:42 +08001687 description = 'event logs (%s)' % str(chunk)
Vic Yang93027612013-05-06 02:42:49 +08001688 start_time = time.time()
1689 shopfloor_client = shopfloor.get_instance(
1690 detect=True,
1691 timeout=self.test_list.options.shopfloor_timeout_secs)
Jon Salzd15bbcf2013-05-21 17:33:57 +08001692 shopfloor_client.UploadEvent(chunk.log_name + "." +
1693 event_log.GetReimageId(),
1694 Binary(chunk.chunk))
Vic Yang93027612013-05-06 02:42:49 +08001695 logging.info(
1696 'Successfully synced %s in %.03f s',
1697 description, time.time() - start_time)
1698 except: # pylint: disable=W0702
Jon Salzd15bbcf2013-05-21 17:33:57 +08001699 first_exception = (first_exception or (chunk.log_name + ': ' +
Vic Yang93027612013-05-06 02:42:49 +08001700 utils.FormatExceptionOnly()))
1701 exception_count += 1
1702
1703 if exception_count:
1704 if exception_count == 1:
1705 msg = 'Log upload failed: %s' % first_exception
1706 else:
1707 msg = '%d log upload failed; first is: %s' % (
1708 exception_count, first_exception)
1709 raise Exception(msg)
1710
Jon Salz57717ca2012-04-04 16:47:25 +08001711
Jon Salz0697cbf2012-07-04 15:14:04 +08001712 def run_tests_with_status(self, statuses_to_run, starting_at=None,
1713 root=None):
1714 '''Runs all top-level tests with a particular status.
Jon Salz0405ab52012-03-16 15:26:52 +08001715
Jon Salz0697cbf2012-07-04 15:14:04 +08001716 All active tests, plus any tests to re-run, are reset.
Jon Salz57717ca2012-04-04 16:47:25 +08001717
Jon Salz0697cbf2012-07-04 15:14:04 +08001718 Args:
1719 starting_at: If provided, only auto-runs tests beginning with
1720 this test.
1721 '''
1722 root = root or self.test_list
Jon Salz57717ca2012-04-04 16:47:25 +08001723
Jon Salz0697cbf2012-07-04 15:14:04 +08001724 if starting_at:
1725 # Make sure they passed a test, not a string.
1726 assert isinstance(starting_at, factory.FactoryTest)
Jon Salz0405ab52012-03-16 15:26:52 +08001727
Jon Salz0697cbf2012-07-04 15:14:04 +08001728 tests_to_reset = []
1729 tests_to_run = []
Jon Salz0405ab52012-03-16 15:26:52 +08001730
Jon Salz0697cbf2012-07-04 15:14:04 +08001731 found_starting_at = False
Jon Salz0405ab52012-03-16 15:26:52 +08001732
Jon Salz0697cbf2012-07-04 15:14:04 +08001733 for test in root.get_top_level_tests():
1734 if starting_at:
1735 if test == starting_at:
1736 # We've found starting_at; do auto-run on all
1737 # subsequent tests.
1738 found_starting_at = True
1739 if not found_starting_at:
1740 # Don't start this guy yet
1741 continue
Jon Salz0405ab52012-03-16 15:26:52 +08001742
Jon Salz0697cbf2012-07-04 15:14:04 +08001743 status = test.get_state().status
1744 if status == TestState.ACTIVE or status in statuses_to_run:
1745 # Reset the test (later; we will need to abort
1746 # all active tests first).
1747 tests_to_reset.append(test)
1748 if status in statuses_to_run:
1749 tests_to_run.append(test)
Jon Salz0405ab52012-03-16 15:26:52 +08001750
Jon Salz6dc031d2013-06-19 13:06:23 +08001751 self.abort_active_tests('Operator requested run/re-run of certain tests')
Jon Salz258a40c2012-04-19 12:34:01 +08001752
Jon Salz0697cbf2012-07-04 15:14:04 +08001753 # Reset all statuses of the tests to run (in case any tests were active;
1754 # we want them to be run again).
1755 for test_to_reset in tests_to_reset:
1756 for test in test_to_reset.walk():
1757 test.update_state(status=TestState.UNTESTED)
Jon Salz57717ca2012-04-04 16:47:25 +08001758
Jon Salz0697cbf2012-07-04 15:14:04 +08001759 self.run_tests(tests_to_run, untested_only=True)
Jon Salz0405ab52012-03-16 15:26:52 +08001760
Jon Salz0697cbf2012-07-04 15:14:04 +08001761 def restart_tests(self, root=None):
1762 '''Restarts all tests.'''
1763 root = root or self.test_list
Jon Salz0405ab52012-03-16 15:26:52 +08001764
Jon Salz6dc031d2013-06-19 13:06:23 +08001765 self.abort_active_tests('Operator requested restart of certain tests')
Jon Salz0697cbf2012-07-04 15:14:04 +08001766 for test in root.walk():
1767 test.update_state(status=TestState.UNTESTED)
1768 self.run_tests(root)
Hung-Te Lin96632362012-03-20 21:14:18 +08001769
Jon Salz0697cbf2012-07-04 15:14:04 +08001770 def auto_run(self, starting_at=None, root=None):
1771 '''"Auto-runs" tests that have not been run yet.
Hung-Te Lin96632362012-03-20 21:14:18 +08001772
Jon Salz0697cbf2012-07-04 15:14:04 +08001773 Args:
1774 starting_at: If provide, only auto-runs tests beginning with
1775 this test.
1776 '''
1777 root = root or self.test_list
1778 self.run_tests_with_status([TestState.UNTESTED, TestState.ACTIVE],
1779 starting_at=starting_at,
1780 root=root)
Jon Salz968e90b2012-03-18 16:12:43 +08001781
Jon Salz0697cbf2012-07-04 15:14:04 +08001782 def re_run_failed(self, root=None):
1783 '''Re-runs failed tests.'''
1784 root = root or self.test_list
1785 self.run_tests_with_status([TestState.FAILED], root=root)
Jon Salz57717ca2012-04-04 16:47:25 +08001786
Jon Salz0697cbf2012-07-04 15:14:04 +08001787 def show_review_information(self):
1788 '''Event handler for showing review information screen.
Jon Salz57717ca2012-04-04 16:47:25 +08001789
Jon Salz0697cbf2012-07-04 15:14:04 +08001790 The information screene is rendered by main UI program (ui.py), so in
1791 goofy we only need to kill all active tests, set them as untested, and
1792 clear remaining tests.
1793 '''
1794 self.kill_active_tests(False)
Jon Salza6711d72012-07-18 14:33:03 +08001795 self.cancel_pending_tests()
Jon Salz57717ca2012-04-04 16:47:25 +08001796
Jon Salz0697cbf2012-07-04 15:14:04 +08001797 def handle_switch_test(self, event):
1798 '''Switches to a particular test.
Jon Salz0405ab52012-03-16 15:26:52 +08001799
Jon Salz0697cbf2012-07-04 15:14:04 +08001800 @param event: The SWITCH_TEST event.
1801 '''
1802 test = self.test_list.lookup_path(event.path)
1803 if not test:
1804 logging.error('Unknown test %r', event.key)
1805 return
Jon Salz73e0fd02012-04-04 11:46:38 +08001806
Jon Salz0697cbf2012-07-04 15:14:04 +08001807 invoc = self.invocations.get(test)
1808 if invoc and test.backgroundable:
1809 # Already running: just bring to the front if it
1810 # has a UI.
1811 logging.info('Setting visible test to %s', test.path)
Jon Salz36fbbb52012-07-05 13:45:06 +08001812 self.set_visible_test(test)
Jon Salz0697cbf2012-07-04 15:14:04 +08001813 return
Jon Salz73e0fd02012-04-04 11:46:38 +08001814
Jon Salz6dc031d2013-06-19 13:06:23 +08001815 self.abort_active_tests('Operator requested abort (switch_test)')
Jon Salz0697cbf2012-07-04 15:14:04 +08001816 for t in test.walk():
1817 t.update_state(status=TestState.UNTESTED)
Jon Salz73e0fd02012-04-04 11:46:38 +08001818
Jon Salz0697cbf2012-07-04 15:14:04 +08001819 if self.test_list.options.auto_run_on_keypress:
1820 self.auto_run(starting_at=test)
1821 else:
1822 self.run_tests(test)
Jon Salz73e0fd02012-04-04 11:46:38 +08001823
Jon Salz0697cbf2012-07-04 15:14:04 +08001824 def wait(self):
1825 '''Waits for all pending invocations.
1826
1827 Useful for testing.
1828 '''
Jon Salz1acc8742012-07-17 17:45:55 +08001829 while self.invocations:
1830 for k, v in self.invocations.iteritems():
1831 logging.info('Waiting for %s to complete...', k)
1832 v.thread.join()
1833 self.reap_completed_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +08001834
1835 def check_exceptions(self):
1836 '''Raises an error if any exceptions have occurred in
1837 invocation threads.'''
1838 if self.exceptions:
1839 raise RuntimeError('Exception in invocation thread: %r' %
1840 self.exceptions)
1841
1842 def record_exception(self, msg):
1843 '''Records an exception in an invocation thread.
1844
1845 An exception with the given message will be rethrown when
1846 Goofy is destroyed.'''
1847 self.exceptions.append(msg)
Jon Salz73e0fd02012-04-04 11:46:38 +08001848
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001849
1850if __name__ == '__main__':
Jon Salz77c151e2012-08-28 07:20:37 +08001851 goofy = Goofy()
1852 try:
1853 goofy.main()
Jon Salz0f996602012-10-03 15:26:48 +08001854 except SystemExit:
1855 # Propagate SystemExit without logging.
1856 raise
Jon Salz31373eb2012-09-21 16:19:49 +08001857 except:
Jon Salz0f996602012-10-03 15:26:48 +08001858 # Log the error before trying to shut down (unless it's a graceful
1859 # exit).
Jon Salz31373eb2012-09-21 16:19:49 +08001860 logging.exception('Error in main loop')
1861 raise
Jon Salz77c151e2012-08-28 07:20:37 +08001862 finally:
1863 goofy.destroy()