blob: e5a64897c36b58d5e3b39dfef805242349932314 [file] [log] [blame]
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001#!/usr/bin/python -u
Hung-Te Linf2f78f72012-02-08 19:27:11 +08002# -*- coding: utf-8 -*-
3#
Jon Salz37eccbd2012-05-25 16:06:52 +08004# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
Hung-Te Linf2f78f72012-02-08 19:27:11 +08005# Use of this source code is governed by a BSD-style license that can be
6# found in the LICENSE file.
7
8'''
9The main factory flow that runs the factory test and finalizes a device.
10'''
11
Jon Salz0405ab52012-03-16 15:26:52 +080012import logging
13import os
Jon Salz73e0fd02012-04-04 11:46:38 +080014import Queue
Jon Salz77c151e2012-08-28 07:20:37 +080015import signal
Jon Salz0405ab52012-03-16 15:26:52 +080016import sys
Jon Salz0405ab52012-03-16 15:26:52 +080017import threading
18import time
19import traceback
Jon Salz258a40c2012-04-19 12:34:01 +080020import uuid
Jon Salzb10cf512012-08-09 17:29:21 +080021from xmlrpclib import Binary
Hung-Te Linf2f78f72012-02-08 19:27:11 +080022from collections import deque
23from optparse import OptionParser
Hung-Te Linf2f78f72012-02-08 19:27:11 +080024
Jon Salz0697cbf2012-07-04 15:14:04 +080025import factory_common # pylint: disable=W0611
jcliangcd688182012-08-20 21:01:26 +080026from cros.factory import event_log
27from cros.factory import system
28from cros.factory.event_log import EventLog
29from cros.factory.goofy import test_environment
30from cros.factory.goofy import time_sanitizer
Jon Salz83591782012-06-26 11:09:58 +080031from cros.factory.goofy import updater
Jon Salz51528e12012-07-02 18:54:45 +080032from cros.factory.goofy.event_log_watcher import EventLogWatcher
jcliangcd688182012-08-20 21:01:26 +080033from cros.factory.goofy.goofy_rpc import GoofyRPC
34from cros.factory.goofy.invocation import TestInvocation
35from cros.factory.goofy.prespawner import Prespawner
36from cros.factory.goofy.web_socket_manager import WebSocketManager
37from cros.factory.system.charge_manager import ChargeManager
Jon Salzb92c5112012-09-21 15:40:11 +080038from cros.factory.system import disk_space
jcliangcd688182012-08-20 21:01:26 +080039from cros.factory.test import factory
40from cros.factory.test import state
Jon Salz51528e12012-07-02 18:54:45 +080041from cros.factory.test import shopfloor
Jon Salz83591782012-06-26 11:09:58 +080042from cros.factory.test import utils
43from cros.factory.test.event import Event
44from cros.factory.test.event import EventClient
45from cros.factory.test.event import EventServer
jcliangcd688182012-08-20 21:01:26 +080046from cros.factory.test.factory import TestState
Dean Liao592e4d52013-01-10 20:06:39 +080047from cros.factory.tools.key_filter import KeyFilter
Jon Salz78c32392012-07-25 14:18:29 +080048from cros.factory.utils.process_utils import Spawn
Hung-Te Linf2f78f72012-02-08 19:27:11 +080049
50
Jon Salz2f757d42012-06-27 17:06:42 +080051CUSTOM_DIR = os.path.join(factory.FACTORY_PATH, 'custom')
Hung-Te Linf2f78f72012-02-08 19:27:11 +080052HWID_CFG_PATH = '/usr/local/share/chromeos-hwid/cfg'
Chun-ta Lin279e7e92013-02-19 17:40:39 +080053CACHES_DIR = os.path.join(factory.get_state_root(), "caches")
Hung-Te Linf2f78f72012-02-08 19:27:11 +080054
Jon Salz8796e362012-05-24 11:39:09 +080055# File that suppresses reboot if present (e.g., for development).
56NO_REBOOT_FILE = '/var/log/factory.noreboot'
57
Jon Salz5c344f62012-07-13 14:31:16 +080058# Value for tests_after_shutdown that forces auto-run (e.g., after
59# a factory update, when the available set of tests might change).
60FORCE_AUTO_RUN = 'force_auto_run'
61
cychiang21886742012-07-05 15:16:32 +080062RUN_QUEUE_TIMEOUT_SECS = 10
63
Jon Salz758e6cc2012-04-03 15:47:07 +080064GOOFY_IN_CHROOT_WARNING = '\n' + ('*' * 70) + '''
65You are running Goofy inside the chroot. Autotests are not supported.
66
67To use Goofy in the chroot, first install an Xvnc server:
68
Jon Salz0697cbf2012-07-04 15:14:04 +080069 sudo apt-get install tightvncserver
Jon Salz758e6cc2012-04-03 15:47:07 +080070
71...and then start a VNC X server outside the chroot:
72
Jon Salz0697cbf2012-07-04 15:14:04 +080073 vncserver :10 &
74 vncviewer :10
Jon Salz758e6cc2012-04-03 15:47:07 +080075
76...and run Goofy as follows:
77
Jon Salz0697cbf2012-07-04 15:14:04 +080078 env --unset=XAUTHORITY DISPLAY=localhost:10 python goofy.py
Jon Salz758e6cc2012-04-03 15:47:07 +080079''' + ('*' * 70)
Jon Salz73e0fd02012-04-04 11:46:38 +080080suppress_chroot_warning = False
Hung-Te Linf2f78f72012-02-08 19:27:11 +080081
82def get_hwid_cfg():
Jon Salz0697cbf2012-07-04 15:14:04 +080083 '''
84 Returns the HWID config tag, or an empty string if none can be found.
85 '''
86 if 'CROS_HWID' in os.environ:
87 return os.environ['CROS_HWID']
88 if os.path.exists(HWID_CFG_PATH):
89 with open(HWID_CFG_PATH, 'rt') as hwid_cfg_handle:
90 return hwid_cfg_handle.read().strip()
91 return ''
Hung-Te Linf2f78f72012-02-08 19:27:11 +080092
93
94def find_test_list():
Jon Salz0697cbf2012-07-04 15:14:04 +080095 '''
96 Returns the path to the active test list, based on the HWID config tag.
Jon Salzfb615892013-02-01 18:04:35 +080097
98 The algorithm is:
99
100 - Try $FACTORY/test_lists/active (the symlink reflecting the option chosen
101 in the UI).
102 - For each of $FACTORY/custom, $FACTORY/test_lists (and
103 autotest/site_tests/suite_Factory for backward compatibility):
104 - Try test_list_${hwid_cfg} (if hwid_cfg is set)
105 - Try test_list
106 - Try test_list.generic
Jon Salz0697cbf2012-07-04 15:14:04 +0800107 '''
Jon Salzfb615892013-02-01 18:04:35 +0800108 # If the 'active' symlink is present, that trumps everything else.
109 if os.path.lexists(factory.ACTIVE_TEST_LIST_SYMLINK):
110 return os.path.realpath(factory.ACTIVE_TEST_LIST_SYMLINK)
111
Jon Salz0697cbf2012-07-04 15:14:04 +0800112 hwid_cfg = get_hwid_cfg()
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800113
Jon Salzfb615892013-02-01 18:04:35 +0800114 search_dirs = [CUSTOM_DIR, factory.TEST_LISTS_PATH]
Jon Salz4be56b02012-12-22 07:30:46 +0800115 if not utils.in_chroot():
116 # Also look in suite_Factory. For backward compatibility only;
117 # new boards should just put the test list in the "test_lists"
118 # directory.
119 search_dirs.insert(0, os.path.join(
120 os.path.dirname(factory.FACTORY_PATH),
121 'autotest', 'site_tests', 'suite_Factory'))
Jon Salz2f757d42012-06-27 17:06:42 +0800122
Jon Salzfb615892013-02-01 18:04:35 +0800123
124 search_files = []
Jon Salz0697cbf2012-07-04 15:14:04 +0800125 if hwid_cfg:
Jon Salzfb615892013-02-01 18:04:35 +0800126 search_files += [hwid_cfg]
127 search_files += ['test_list', 'test_list.generic']
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800128
Jon Salz0697cbf2012-07-04 15:14:04 +0800129 for d in search_dirs:
130 for f in search_files:
131 test_list = os.path.join(d, f)
132 if os.path.exists(test_list):
133 return test_list
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800134
Jon Salz0697cbf2012-07-04 15:14:04 +0800135 logging.warn('Cannot find test lists named any of %s in any of %s',
136 search_files, search_dirs)
137 return None
Jon Salz73e0fd02012-04-04 11:46:38 +0800138
Jon Salzfb615892013-02-01 18:04:35 +0800139
Jon Salz73e0fd02012-04-04 11:46:38 +0800140_inited_logging = False
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800141
142class Goofy(object):
Jon Salz0697cbf2012-07-04 15:14:04 +0800143 '''
144 The main factory flow.
145
146 Note that all methods in this class must be invoked from the main
147 (event) thread. Other threads, such as callbacks and TestInvocation
148 methods, should instead post events on the run queue.
149
150 TODO: Unit tests. (chrome-os-partner:7409)
151
152 Properties:
153 uuid: A unique UUID for this invocation of Goofy.
154 state_instance: An instance of FactoryState.
155 state_server: The FactoryState XML/RPC server.
156 state_server_thread: A thread running state_server.
157 event_server: The EventServer socket server.
158 event_server_thread: A thread running event_server.
159 event_client: A client to the event server.
160 connection_manager: The connection_manager object.
Jon Salz0697cbf2012-07-04 15:14:04 +0800161 ui_process: The factory ui process object.
162 run_queue: A queue of callbacks to invoke from the main thread.
163 invocations: A map from FactoryTest objects to the corresponding
164 TestInvocations objects representing active tests.
165 tests_to_run: A deque of tests that should be run when the current
166 test(s) complete.
167 options: Command-line options.
168 args: Command-line args.
169 test_list: The test list.
170 event_handlers: Map of Event.Type to the method used to handle that
171 event. If the method has an 'event' argument, the event is passed
172 to the handler.
173 exceptions: Exceptions encountered in invocation threads.
Jon Salz3c493bb2013-02-07 17:24:58 +0800174 last_log_disk_space_message: The last message we logged about disk space
175 (to avoid duplication).
Jon Salz0697cbf2012-07-04 15:14:04 +0800176 '''
177 def __init__(self):
178 self.uuid = str(uuid.uuid4())
179 self.state_instance = None
180 self.state_server = None
181 self.state_server_thread = None
Jon Salz16d10542012-07-23 12:18:45 +0800182 self.goofy_rpc = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800183 self.event_server = None
184 self.event_server_thread = None
185 self.event_client = None
186 self.connection_manager = None
Vic Yang4953fc12012-07-26 16:19:53 +0800187 self.charge_manager = None
Jon Salz8fa8e832012-07-13 19:04:09 +0800188 self.time_sanitizer = None
189 self.time_synced = False
Jon Salz0697cbf2012-07-04 15:14:04 +0800190 self.log_watcher = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800191 self.event_log = None
192 self.prespawner = None
193 self.ui_process = None
Jon Salzc79a9982012-08-30 04:42:01 +0800194 self.dummy_shopfloor = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800195 self.run_queue = Queue.Queue()
196 self.invocations = {}
197 self.tests_to_run = deque()
198 self.visible_test = None
199 self.chrome = None
200
201 self.options = None
202 self.args = None
203 self.test_list = None
204 self.on_ui_startup = []
205 self.env = None
Jon Salzb22d1172012-08-06 10:38:57 +0800206 self.last_idle = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800207 self.last_shutdown_time = None
cychiang21886742012-07-05 15:16:32 +0800208 self.last_update_check = None
Jon Salz8fa8e832012-07-13 19:04:09 +0800209 self.last_sync_time = None
Jon Salzb92c5112012-09-21 15:40:11 +0800210 self.last_log_disk_space_time = None
Jon Salz3c493bb2013-02-07 17:24:58 +0800211 self.last_log_disk_space_message = None
Vic Yang311ddb82012-09-26 12:08:28 +0800212 self.exclusive_items = set()
Jon Salz0f996602012-10-03 15:26:48 +0800213 self.event_log = None
Dean Liao592e4d52013-01-10 20:06:39 +0800214 self.key_filter = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800215
Jon Salz85a39882012-07-05 16:45:04 +0800216 def test_or_root(event, parent_or_group=True):
217 '''Returns the test affected by a particular event.
218
219 Args:
220 event: The event containing an optional 'path' attribute.
221 parent_on_group: If True, returns the top-level parent for a test (the
222 root node of the tests that need to be run together if the given test
223 path is to be run).
224 '''
Jon Salz0697cbf2012-07-04 15:14:04 +0800225 try:
226 path = event.path
227 except AttributeError:
228 path = None
229
230 if path:
Jon Salz85a39882012-07-05 16:45:04 +0800231 test = self.test_list.lookup_path(path)
232 if parent_or_group:
233 test = test.get_top_level_parent_or_group()
234 return test
Jon Salz0697cbf2012-07-04 15:14:04 +0800235 else:
236 return self.test_list
237
238 self.event_handlers = {
239 Event.Type.SWITCH_TEST: self.handle_switch_test,
240 Event.Type.SHOW_NEXT_ACTIVE_TEST:
241 lambda event: self.show_next_active_test(),
242 Event.Type.RESTART_TESTS:
243 lambda event: self.restart_tests(root=test_or_root(event)),
244 Event.Type.AUTO_RUN:
245 lambda event: self.auto_run(root=test_or_root(event)),
246 Event.Type.RE_RUN_FAILED:
247 lambda event: self.re_run_failed(root=test_or_root(event)),
248 Event.Type.RUN_TESTS_WITH_STATUS:
249 lambda event: self.run_tests_with_status(
250 event.status,
251 root=test_or_root(event)),
252 Event.Type.REVIEW:
253 lambda event: self.show_review_information(),
254 Event.Type.UPDATE_SYSTEM_INFO:
255 lambda event: self.update_system_info(),
Jon Salz0697cbf2012-07-04 15:14:04 +0800256 Event.Type.STOP:
Jon Salz85a39882012-07-05 16:45:04 +0800257 lambda event: self.stop(root=test_or_root(event, False),
258 fail=getattr(event, 'fail', False)),
Jon Salz36fbbb52012-07-05 13:45:06 +0800259 Event.Type.SET_VISIBLE_TEST:
260 lambda event: self.set_visible_test(
261 self.test_list.lookup_path(event.path)),
Jon Salz4712ac72013-02-07 17:12:05 +0800262 Event.Type.CLEAR_STATE:
263 lambda event: self.clear_state(self.test_list.lookup_path(event.path)),
Jon Salz0697cbf2012-07-04 15:14:04 +0800264 }
265
266 self.exceptions = []
267 self.web_socket_manager = None
268
269 def destroy(self):
270 if self.chrome:
271 self.chrome.kill()
272 self.chrome = None
Jon Salzc79a9982012-08-30 04:42:01 +0800273 if self.dummy_shopfloor:
274 self.dummy_shopfloor.kill()
275 self.dummy_shopfloor = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800276 if self.ui_process:
277 utils.kill_process_tree(self.ui_process, 'ui')
278 self.ui_process = None
279 if self.web_socket_manager:
280 logging.info('Stopping web sockets')
281 self.web_socket_manager.close()
282 self.web_socket_manager = None
283 if self.state_server_thread:
284 logging.info('Stopping state server')
285 self.state_server.shutdown()
286 self.state_server_thread.join()
287 self.state_server.server_close()
288 self.state_server_thread = None
289 if self.state_instance:
290 self.state_instance.close()
291 if self.event_server_thread:
292 logging.info('Stopping event server')
293 self.event_server.shutdown() # pylint: disable=E1101
294 self.event_server_thread.join()
295 self.event_server.server_close()
296 self.event_server_thread = None
297 if self.log_watcher:
298 if self.log_watcher.IsThreadStarted():
299 self.log_watcher.StopWatchThread()
300 self.log_watcher = None
301 if self.prespawner:
302 logging.info('Stopping prespawner')
303 self.prespawner.stop()
304 self.prespawner = None
305 if self.event_client:
306 logging.info('Closing event client')
307 self.event_client.close()
308 self.event_client = None
309 if self.event_log:
310 self.event_log.Close()
311 self.event_log = None
Dean Liao592e4d52013-01-10 20:06:39 +0800312 if self.key_filter:
313 self.key_filter.Stop()
314
Jon Salz0697cbf2012-07-04 15:14:04 +0800315 self.check_exceptions()
316 logging.info('Done destroying Goofy')
317
318 def start_state_server(self):
319 self.state_instance, self.state_server = (
320 state.create_server(bind_address='0.0.0.0'))
Jon Salz16d10542012-07-23 12:18:45 +0800321 self.goofy_rpc = GoofyRPC(self)
322 self.goofy_rpc.RegisterMethods(self.state_instance)
Jon Salz0697cbf2012-07-04 15:14:04 +0800323 logging.info('Starting state server')
324 self.state_server_thread = threading.Thread(
325 target=self.state_server.serve_forever,
326 name='StateServer')
327 self.state_server_thread.start()
328
329 def start_event_server(self):
330 self.event_server = EventServer()
331 logging.info('Starting factory event server')
332 self.event_server_thread = threading.Thread(
333 target=self.event_server.serve_forever,
334 name='EventServer') # pylint: disable=E1101
335 self.event_server_thread.start()
336
337 self.event_client = EventClient(
338 callback=self.handle_event, event_loop=self.run_queue)
339
340 self.web_socket_manager = WebSocketManager(self.uuid)
341 self.state_server.add_handler("/event",
342 self.web_socket_manager.handle_web_socket)
343
344 def start_ui(self):
345 ui_proc_args = [
346 os.path.join(factory.FACTORY_PACKAGE_PATH, 'test', 'ui.py'),
347 self.options.test_list]
348 if self.options.verbose:
349 ui_proc_args.append('-v')
350 logging.info('Starting ui %s', ui_proc_args)
Jon Salz78c32392012-07-25 14:18:29 +0800351 self.ui_process = Spawn(ui_proc_args)
Jon Salz0697cbf2012-07-04 15:14:04 +0800352 logging.info('Waiting for UI to come up...')
353 self.event_client.wait(
354 lambda event: event.type == Event.Type.UI_READY)
355 logging.info('UI has started')
356
357 def set_visible_test(self, test):
358 if self.visible_test == test:
359 return
Jon Salz2f2d42c2012-07-30 12:30:34 +0800360 if test and not test.has_ui:
361 return
Jon Salz0697cbf2012-07-04 15:14:04 +0800362
363 if test:
364 test.update_state(visible=True)
365 if self.visible_test:
366 self.visible_test.update_state(visible=False)
367 self.visible_test = test
368
Jon Salzd4306c82012-11-30 15:16:36 +0800369 def _log_startup_messages(self):
370 '''Logs the tail of var/log/messages and mosys and EC console logs.'''
371 # TODO(jsalz): This is mostly a copy-and-paste of code in init_states,
372 # for factory-3004.B only. Consolidate and merge back to ToT.
373 if utils.in_chroot():
374 return
375
376 try:
377 var_log_messages = (
378 utils.var_log_messages_before_reboot())
379 logging.info(
380 'Tail of /var/log/messages before last reboot:\n'
381 '%s', ('\n'.join(
382 ' ' + x for x in var_log_messages)))
383 except: # pylint: disable=W0702
384 logging.exception('Unable to grok /var/log/messages')
385
386 try:
387 mosys_log = utils.Spawn(
388 ['mosys', 'eventlog', 'list'],
389 read_stdout=True, log_stderr_on_error=True).stdout_data
390 logging.info('System eventlog from mosys:\n%s\n', mosys_log)
391 except: # pylint: disable=W0702
392 logging.exception('Unable to read mosys eventlog')
393
394 try:
Vic Yang8341dde2013-01-29 16:48:52 +0800395 board = system.GetBoard()
396 ec_console_log = board.GetECConsoleLog()
Jon Salzd4306c82012-11-30 15:16:36 +0800397 logging.info('EC console log after reboot:\n%s\n', ec_console_log)
398 except: # pylint: disable=W0702
399 logging.exception('Error retrieving EC console log')
400
Jon Salz0697cbf2012-07-04 15:14:04 +0800401 def handle_shutdown_complete(self, test, test_state):
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800402 '''
Jon Salz0697cbf2012-07-04 15:14:04 +0800403 Handles the case where a shutdown was detected during a shutdown step.
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800404
Jon Salz0697cbf2012-07-04 15:14:04 +0800405 @param test: The ShutdownStep.
406 @param test_state: The test state.
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800407 '''
Jon Salz0697cbf2012-07-04 15:14:04 +0800408 test_state = test.update_state(increment_shutdown_count=1)
409 logging.info('Detected shutdown (%d of %d)',
410 test_state.shutdown_count, test.iterations)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800411
Jon Salz0697cbf2012-07-04 15:14:04 +0800412 def log_and_update_state(status, error_msg, **kw):
413 self.event_log.Log('rebooted',
414 status=status, error_msg=error_msg, **kw)
Jon Salzd4306c82012-11-30 15:16:36 +0800415 logging.info('Rebooted: status=%s, %s', status,
416 (('error_msg=%s' % error_msg) if error_msg else None))
Jon Salz0697cbf2012-07-04 15:14:04 +0800417 test.update_state(status=status, error_msg=error_msg)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800418
Jon Salz0697cbf2012-07-04 15:14:04 +0800419 if not self.last_shutdown_time:
420 log_and_update_state(status=TestState.FAILED,
421 error_msg='Unable to read shutdown_time')
422 return
Jon Salz258a40c2012-04-19 12:34:01 +0800423
Jon Salz0697cbf2012-07-04 15:14:04 +0800424 now = time.time()
425 logging.info('%.03f s passed since reboot',
426 now - self.last_shutdown_time)
Jon Salz258a40c2012-04-19 12:34:01 +0800427
Jon Salz0697cbf2012-07-04 15:14:04 +0800428 if self.last_shutdown_time > now:
429 test.update_state(status=TestState.FAILED,
430 error_msg='Time moved backward during reboot')
431 elif (isinstance(test, factory.RebootStep) and
432 self.test_list.options.max_reboot_time_secs and
433 (now - self.last_shutdown_time >
434 self.test_list.options.max_reboot_time_secs)):
435 # A reboot took too long; fail. (We don't check this for
436 # HaltSteps, because the machine could be halted for a
437 # very long time, and even unplugged with battery backup,
438 # thus hosing the clock.)
439 log_and_update_state(
440 status=TestState.FAILED,
441 error_msg=('More than %d s elapsed during reboot '
442 '(%.03f s, from %s to %s)' % (
443 self.test_list.options.max_reboot_time_secs,
444 now - self.last_shutdown_time,
445 utils.TimeString(self.last_shutdown_time),
446 utils.TimeString(now))),
447 duration=(now-self.last_shutdown_time))
Jon Salzd4306c82012-11-30 15:16:36 +0800448 self._log_startup_messages()
Jon Salz0697cbf2012-07-04 15:14:04 +0800449 elif test_state.shutdown_count == test.iterations:
450 # Good!
451 log_and_update_state(status=TestState.PASSED,
452 duration=(now - self.last_shutdown_time),
453 error_msg='')
454 elif test_state.shutdown_count > test.iterations:
455 # Shut down too many times
456 log_and_update_state(status=TestState.FAILED,
457 error_msg='Too many shutdowns')
Jon Salzd4306c82012-11-30 15:16:36 +0800458 self._log_startup_messages()
Jon Salz0697cbf2012-07-04 15:14:04 +0800459 elif utils.are_shift_keys_depressed():
460 logging.info('Shift keys are depressed; cancelling restarts')
461 # Abort shutdown
462 log_and_update_state(
463 status=TestState.FAILED,
464 error_msg='Shutdown aborted with double shift keys')
Jon Salza6711d72012-07-18 14:33:03 +0800465 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +0800466 else:
467 def handler():
468 if self._prompt_cancel_shutdown(
469 test, test_state.shutdown_count + 1):
Jon Salza6711d72012-07-18 14:33:03 +0800470 factory.console.info('Shutdown aborted by operator')
Jon Salz0697cbf2012-07-04 15:14:04 +0800471 log_and_update_state(
472 status=TestState.FAILED,
473 error_msg='Shutdown aborted by operator')
Jon Salza6711d72012-07-18 14:33:03 +0800474 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +0800475 return
Jon Salz0405ab52012-03-16 15:26:52 +0800476
Jon Salz0697cbf2012-07-04 15:14:04 +0800477 # Time to shutdown again
478 log_and_update_state(
479 status=TestState.ACTIVE,
480 error_msg='',
481 iteration=test_state.shutdown_count)
Jon Salz73e0fd02012-04-04 11:46:38 +0800482
Jon Salz0697cbf2012-07-04 15:14:04 +0800483 self.event_log.Log('shutdown', operation='reboot')
484 self.state_instance.set_shared_data('shutdown_time',
485 time.time())
486 self.env.shutdown('reboot')
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800487
Jon Salz0697cbf2012-07-04 15:14:04 +0800488 self.on_ui_startup.append(handler)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800489
Jon Salz0697cbf2012-07-04 15:14:04 +0800490 def _prompt_cancel_shutdown(self, test, iteration):
491 if self.options.ui != 'chrome':
492 return False
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800493
Jon Salz0697cbf2012-07-04 15:14:04 +0800494 pending_shutdown_data = {
495 'delay_secs': test.delay_secs,
496 'time': time.time() + test.delay_secs,
497 'operation': test.operation,
498 'iteration': iteration,
499 'iterations': test.iterations,
500 }
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800501
Jon Salz0697cbf2012-07-04 15:14:04 +0800502 # Create a new (threaded) event client since we
503 # don't want to use the event loop for this.
504 with EventClient() as event_client:
505 event_client.post_event(Event(Event.Type.PENDING_SHUTDOWN,
506 **pending_shutdown_data))
507 aborted = event_client.wait(
508 lambda event: event.type == Event.Type.CANCEL_SHUTDOWN,
509 timeout=test.delay_secs) is not None
510 if aborted:
511 event_client.post_event(Event(Event.Type.PENDING_SHUTDOWN))
512 return aborted
Jon Salz258a40c2012-04-19 12:34:01 +0800513
Jon Salz0697cbf2012-07-04 15:14:04 +0800514 def init_states(self):
515 '''
516 Initializes all states on startup.
517 '''
518 for test in self.test_list.get_all_tests():
519 # Make sure the state server knows about all the tests,
520 # defaulting to an untested state.
521 test.update_state(update_parent=False, visible=False)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800522
Jon Salz0697cbf2012-07-04 15:14:04 +0800523 var_log_messages = None
Vic Yanga9c32212012-08-16 20:07:54 +0800524 mosys_log = None
Vic Yange4c275d2012-08-28 01:50:20 +0800525 ec_console_log = None
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800526
Jon Salz0697cbf2012-07-04 15:14:04 +0800527 # Any 'active' tests should be marked as failed now.
528 for test in self.test_list.walk():
Jon Salza6711d72012-07-18 14:33:03 +0800529 if not test.is_leaf():
530 # Don't bother with parents; they will be updated when their
531 # children are updated.
532 continue
533
Jon Salz0697cbf2012-07-04 15:14:04 +0800534 test_state = test.get_state()
535 if test_state.status != TestState.ACTIVE:
536 continue
537 if isinstance(test, factory.ShutdownStep):
538 # Shutdown while the test was active - that's good.
539 self.handle_shutdown_complete(test, test_state)
540 else:
541 # Unexpected shutdown. Grab /var/log/messages for context.
542 if var_log_messages is None:
543 try:
544 var_log_messages = (
545 utils.var_log_messages_before_reboot())
546 # Write it to the log, to make it easier to
547 # correlate with /var/log/messages.
548 logging.info(
549 'Unexpected shutdown. '
550 'Tail of /var/log/messages before last reboot:\n'
551 '%s', ('\n'.join(
552 ' ' + x for x in var_log_messages)))
553 except: # pylint: disable=W0702
554 logging.exception('Unable to grok /var/log/messages')
555 var_log_messages = []
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800556
Jon Salz008f4ea2012-08-28 05:39:45 +0800557 if mosys_log is None and not utils.in_chroot():
558 try:
559 mosys_log = utils.Spawn(
560 ['mosys', 'eventlog', 'list'],
561 read_stdout=True, log_stderr_on_error=True).stdout_data
562 # Write it to the log also.
563 logging.info('System eventlog from mosys:\n%s\n', mosys_log)
564 except: # pylint: disable=W0702
565 logging.exception('Unable to read mosys eventlog')
Vic Yanga9c32212012-08-16 20:07:54 +0800566
Vic Yange4c275d2012-08-28 01:50:20 +0800567 if ec_console_log is None:
568 try:
Vic Yang8341dde2013-01-29 16:48:52 +0800569 board = system.GetBoard()
570 ec_console_log = board.GetECConsoleLog()
Vic Yange4c275d2012-08-28 01:50:20 +0800571 logging.info('EC console log after reboot:\n%s\n', ec_console_log)
Jon Salzfe1f6652012-09-07 05:40:14 +0800572 except: # pylint: disable=W0702
Vic Yange4c275d2012-08-28 01:50:20 +0800573 logging.exception('Error retrieving EC console log')
574
Jon Salz0697cbf2012-07-04 15:14:04 +0800575 error_msg = 'Unexpected shutdown while test was running'
576 self.event_log.Log('end_test',
577 path=test.path,
578 status=TestState.FAILED,
579 invocation=test.get_state().invocation,
580 error_msg=error_msg,
Vic Yanga9c32212012-08-16 20:07:54 +0800581 var_log_messages='\n'.join(var_log_messages),
582 mosys_log=mosys_log)
Jon Salz0697cbf2012-07-04 15:14:04 +0800583 test.update_state(
584 status=TestState.FAILED,
585 error_msg=error_msg)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800586
Jon Salz50efe942012-07-26 11:54:10 +0800587 if not test.never_fails:
588 # For "never_fails" tests (such as "Start"), don't cancel
589 # pending tests, since reboot is expected.
590 factory.console.info('Unexpected shutdown while test %s '
591 'running; cancelling any pending tests',
592 test.path)
593 self.state_instance.set_shared_data('tests_after_shutdown', [])
Jon Salz69806bb2012-07-20 18:05:02 +0800594
Jon Salz008f4ea2012-08-28 05:39:45 +0800595 self.update_skipped_tests()
596
597 def update_skipped_tests(self):
598 '''
599 Updates skipped states based on run_if.
600 '''
601 for t in self.test_list.walk():
602 if t.is_leaf() and t.run_if_table_name:
603 skip = False
604 try:
605 aux = shopfloor.get_selected_aux_data(t.run_if_table_name)
606 value = aux.get(t.run_if_col)
607 if value is not None:
608 skip = (not value) ^ t.run_if_not
609 except ValueError:
610 # Not available; assume it shouldn't be skipped
611 pass
612
613 test_state = t.get_state()
614 if ((not skip) and
615 (test_state.status == TestState.PASSED) and
616 (test_state.error_msg == TestState.SKIPPED_MSG)):
617 # It was marked as skipped before, but now we need to run it.
618 # Mark as untested.
619 t.update_state(skip=skip, status=TestState.UNTESTED, error_msg='')
620 else:
621 t.update_state(skip=skip)
622
Jon Salz0697cbf2012-07-04 15:14:04 +0800623 def show_next_active_test(self):
624 '''
625 Rotates to the next visible active test.
626 '''
627 self.reap_completed_tests()
628 active_tests = [
629 t for t in self.test_list.walk()
630 if t.is_leaf() and t.get_state().status == TestState.ACTIVE]
631 if not active_tests:
632 return
Jon Salz4f6c7172012-06-11 20:45:36 +0800633
Jon Salz0697cbf2012-07-04 15:14:04 +0800634 try:
635 next_test = active_tests[
636 (active_tests.index(self.visible_test) + 1) % len(active_tests)]
637 except ValueError: # visible_test not present in active_tests
638 next_test = active_tests[0]
Jon Salz4f6c7172012-06-11 20:45:36 +0800639
Jon Salz0697cbf2012-07-04 15:14:04 +0800640 self.set_visible_test(next_test)
Jon Salz4f6c7172012-06-11 20:45:36 +0800641
Jon Salz0697cbf2012-07-04 15:14:04 +0800642 def handle_event(self, event):
643 '''
644 Handles an event from the event server.
645 '''
646 handler = self.event_handlers.get(event.type)
647 if handler:
648 handler(event)
649 else:
650 # We don't register handlers for all event types - just ignore
651 # this event.
652 logging.debug('Unbound event type %s', event.type)
Jon Salz4f6c7172012-06-11 20:45:36 +0800653
Jon Salz0697cbf2012-07-04 15:14:04 +0800654 def run_next_test(self):
655 '''
656 Runs the next eligible test (or tests) in self.tests_to_run.
657 '''
658 self.reap_completed_tests()
659 while self.tests_to_run:
660 logging.debug('Tests to run: %s',
661 [x.path for x in self.tests_to_run])
Jon Salz94eb56f2012-06-12 18:01:12 +0800662
Jon Salz0697cbf2012-07-04 15:14:04 +0800663 test = self.tests_to_run[0]
Jon Salz94eb56f2012-06-12 18:01:12 +0800664
Jon Salz0697cbf2012-07-04 15:14:04 +0800665 if test in self.invocations:
666 logging.info('Next test %s is already running', test.path)
667 self.tests_to_run.popleft()
668 return
Jon Salz94eb56f2012-06-12 18:01:12 +0800669
Jon Salza1412922012-07-23 16:04:17 +0800670 for requirement in test.require_run:
671 for i in requirement.test.walk():
672 if i.get_state().status == TestState.ACTIVE:
Jon Salz304a75d2012-07-06 11:14:15 +0800673 logging.info('Waiting for active test %s to complete '
Jon Salza1412922012-07-23 16:04:17 +0800674 'before running %s', i.path, test.path)
Jon Salz304a75d2012-07-06 11:14:15 +0800675 return
676
Jon Salz0697cbf2012-07-04 15:14:04 +0800677 if self.invocations and not (test.backgroundable and all(
678 [x.backgroundable for x in self.invocations])):
679 logging.debug('Waiting for non-backgroundable tests to '
680 'complete before running %s', test.path)
681 return
Jon Salz94eb56f2012-06-12 18:01:12 +0800682
Jon Salz3e6f5202012-10-15 15:08:29 +0800683 if test.get_state().skip:
684 factory.console.info('Skipping test %s', test.path)
685 test.update_state(status=TestState.PASSED,
686 error_msg=TestState.SKIPPED_MSG)
687 self.tests_to_run.popleft()
688 continue
689
Jon Salz0697cbf2012-07-04 15:14:04 +0800690 self.tests_to_run.popleft()
Jon Salz94eb56f2012-06-12 18:01:12 +0800691
Jon Salz304a75d2012-07-06 11:14:15 +0800692 untested = set()
Jon Salza1412922012-07-23 16:04:17 +0800693 for requirement in test.require_run:
694 for i in requirement.test.walk():
695 if i == test:
Jon Salz304a75d2012-07-06 11:14:15 +0800696 # We've hit this test itself; stop checking
697 break
Jon Salza1412922012-07-23 16:04:17 +0800698 if ((i.get_state().status == TestState.UNTESTED) or
699 (requirement.passed and i.get_state().status !=
700 TestState.PASSED)):
Jon Salz304a75d2012-07-06 11:14:15 +0800701 # Found an untested test; move on to the next
702 # element in require_run.
Jon Salza1412922012-07-23 16:04:17 +0800703 untested.add(i)
Jon Salz304a75d2012-07-06 11:14:15 +0800704 break
705
706 if untested:
707 untested_paths = ', '.join(sorted([x.path for x in untested]))
708 if self.state_instance.get_shared_data('engineering_mode',
709 optional=True):
710 # In engineering mode, we'll let it go.
711 factory.console.warn('In engineering mode; running '
712 '%s even though required tests '
713 '[%s] have not completed',
714 test.path, untested_paths)
715 else:
716 # Not in engineering mode; mark it failed.
717 error_msg = ('Required tests [%s] have not been run yet'
718 % untested_paths)
719 factory.console.error('Not running %s: %s',
720 test.path, error_msg)
721 test.update_state(status=TestState.FAILED,
722 error_msg=error_msg)
723 continue
724
Jon Salz0697cbf2012-07-04 15:14:04 +0800725 if isinstance(test, factory.ShutdownStep):
726 if os.path.exists(NO_REBOOT_FILE):
727 test.update_state(
728 status=TestState.FAILED, increment_count=1,
729 error_msg=('Skipped shutdown since %s is present' %
Jon Salz304a75d2012-07-06 11:14:15 +0800730 NO_REBOOT_FILE))
Jon Salz0697cbf2012-07-04 15:14:04 +0800731 continue
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800732
Jon Salz0697cbf2012-07-04 15:14:04 +0800733 test.update_state(status=TestState.ACTIVE, increment_count=1,
734 error_msg='', shutdown_count=0)
735 if self._prompt_cancel_shutdown(test, 1):
736 self.event_log.Log('reboot_cancelled')
737 test.update_state(
738 status=TestState.FAILED, increment_count=1,
739 error_msg='Shutdown aborted by operator',
740 shutdown_count=0)
chungyiafe8f772012-08-15 19:36:29 +0800741 continue
Jon Salz2f757d42012-06-27 17:06:42 +0800742
Jon Salz0697cbf2012-07-04 15:14:04 +0800743 # Save pending test list in the state server
Jon Salzdbf398f2012-06-14 17:30:01 +0800744 self.state_instance.set_shared_data(
Jon Salz0697cbf2012-07-04 15:14:04 +0800745 'tests_after_shutdown',
746 [t.path for t in self.tests_to_run])
747 # Save shutdown time
748 self.state_instance.set_shared_data('shutdown_time',
749 time.time())
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800750
Jon Salz0697cbf2012-07-04 15:14:04 +0800751 with self.env.lock:
752 self.event_log.Log('shutdown', operation=test.operation)
753 shutdown_result = self.env.shutdown(test.operation)
754 if shutdown_result:
755 # That's all, folks!
756 self.run_queue.put(None)
757 return
758 else:
759 # Just pass (e.g., in the chroot).
760 test.update_state(status=TestState.PASSED)
761 self.state_instance.set_shared_data(
762 'tests_after_shutdown', None)
763 # Send event with no fields to indicate that there is no
764 # longer a pending shutdown.
765 self.event_client.post_event(Event(
766 Event.Type.PENDING_SHUTDOWN))
767 continue
Jon Salz258a40c2012-04-19 12:34:01 +0800768
Jon Salz1acc8742012-07-17 17:45:55 +0800769 self._run_test(test, test.iterations)
770
771 def _run_test(self, test, iterations_left=None):
772 invoc = TestInvocation(self, test, on_completion=self.run_next_test)
773 new_state = test.update_state(
774 status=TestState.ACTIVE, increment_count=1, error_msg='',
Jon Salzbd42ce12012-09-18 08:03:59 +0800775 invocation=invoc.uuid, iterations_left=iterations_left,
776 visible=(self.visible_test == test))
Jon Salz1acc8742012-07-17 17:45:55 +0800777 invoc.count = new_state.count
778
779 self.invocations[test] = invoc
780 if self.visible_test is None and test.has_ui:
781 self.set_visible_test(test)
Vic Yang311ddb82012-09-26 12:08:28 +0800782 self.check_exclusive()
Jon Salz1acc8742012-07-17 17:45:55 +0800783 invoc.start()
Jon Salz5f2a0672012-05-22 17:14:06 +0800784
Vic Yang311ddb82012-09-26 12:08:28 +0800785 def check_exclusive(self):
786 current_exclusive_items = set([
787 item
788 for item in factory.FactoryTest.EXCLUSIVE_OPTIONS
789 if any([test.is_exclusive(item) for test in self.invocations])])
790
791 new_exclusive_items = current_exclusive_items - self.exclusive_items
792 if factory.FactoryTest.EXCLUSIVE_OPTIONS.NETWORKING in new_exclusive_items:
793 logging.info('Disabling network')
794 self.connection_manager.DisableNetworking()
795 if factory.FactoryTest.EXCLUSIVE_OPTIONS.CHARGER in new_exclusive_items:
796 logging.info('Stop controlling charger')
797
798 new_non_exclusive_items = self.exclusive_items - current_exclusive_items
799 if (factory.FactoryTest.EXCLUSIVE_OPTIONS.NETWORKING in
800 new_non_exclusive_items):
801 logging.info('Re-enabling network')
802 self.connection_manager.EnableNetworking()
803 if factory.FactoryTest.EXCLUSIVE_OPTIONS.CHARGER in new_non_exclusive_items:
804 logging.info('Start controlling charger')
805
806 # Only adjust charge state if not excluded
807 if (self.charge_manager and
808 not factory.FactoryTest.EXCLUSIVE_OPTIONS.CHARGER in
809 current_exclusive_items):
810 self.charge_manager.AdjustChargeState()
811
812 self.exclusive_items = current_exclusive_items
Jon Salz5da61e62012-05-31 13:06:22 +0800813
cychiang21886742012-07-05 15:16:32 +0800814 def check_for_updates(self):
815 '''
816 Schedules an asynchronous check for updates if necessary.
817 '''
818 if not self.test_list.options.update_period_secs:
819 # Not enabled.
820 return
821
822 now = time.time()
823 if self.last_update_check and (
824 now - self.last_update_check <
825 self.test_list.options.update_period_secs):
826 # Not yet time for another check.
827 return
828
829 self.last_update_check = now
830
831 def handle_check_for_update(reached_shopfloor, md5sum, needs_update):
832 if reached_shopfloor:
833 new_update_md5sum = md5sum if needs_update else None
834 if system.SystemInfo.update_md5sum != new_update_md5sum:
835 logging.info('Received new update MD5SUM: %s', new_update_md5sum)
836 system.SystemInfo.update_md5sum = new_update_md5sum
837 self.run_queue.put(self.update_system_info)
838
839 updater.CheckForUpdateAsync(
840 handle_check_for_update,
841 self.test_list.options.shopfloor_timeout_secs)
842
Jon Salza6711d72012-07-18 14:33:03 +0800843 def cancel_pending_tests(self):
844 '''Cancels any tests in the run queue.'''
845 self.run_tests([])
846
Jon Salz0697cbf2012-07-04 15:14:04 +0800847 def run_tests(self, subtrees, untested_only=False):
848 '''
849 Runs tests under subtree.
Jon Salz258a40c2012-04-19 12:34:01 +0800850
Jon Salz0697cbf2012-07-04 15:14:04 +0800851 The tests are run in order unless one fails (then stops).
852 Backgroundable tests are run simultaneously; when a foreground test is
853 encountered, we wait for all active tests to finish before continuing.
Jon Salzb1b39092012-05-03 02:05:09 +0800854
Jon Salz0697cbf2012-07-04 15:14:04 +0800855 @param subtrees: Node or nodes containing tests to run (may either be
856 a single test or a list). Duplicates will be ignored.
857 '''
858 if type(subtrees) != list:
859 subtrees = [subtrees]
Jon Salz258a40c2012-04-19 12:34:01 +0800860
Jon Salz0697cbf2012-07-04 15:14:04 +0800861 # Nodes we've seen so far, to avoid duplicates.
862 seen = set()
Jon Salz94eb56f2012-06-12 18:01:12 +0800863
Jon Salz0697cbf2012-07-04 15:14:04 +0800864 self.tests_to_run = deque()
865 for subtree in subtrees:
866 for test in subtree.walk():
867 if test in seen:
868 continue
869 seen.add(test)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800870
Jon Salz0697cbf2012-07-04 15:14:04 +0800871 if not test.is_leaf():
872 continue
873 if (untested_only and
874 test.get_state().status != TestState.UNTESTED):
875 continue
876 self.tests_to_run.append(test)
877 self.run_next_test()
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800878
Jon Salz0697cbf2012-07-04 15:14:04 +0800879 def reap_completed_tests(self):
880 '''
881 Removes completed tests from the set of active tests.
882
883 Also updates the visible test if it was reaped.
884 '''
885 for t, v in dict(self.invocations).iteritems():
886 if v.is_completed():
Jon Salz1acc8742012-07-17 17:45:55 +0800887 new_state = t.update_state(**v.update_state_on_completion)
Jon Salz0697cbf2012-07-04 15:14:04 +0800888 del self.invocations[t]
889
Chun-Ta Lin54e17e42012-09-06 22:05:13 +0800890 # Stop on failure if flag is true.
891 if (self.test_list.options.stop_on_failure and
892 new_state.status == TestState.FAILED):
893 # Clean all the tests to cause goofy to stop.
894 self.tests_to_run = []
895 factory.console.info("Stop on failure triggered. Empty the queue.")
896
Jon Salz1acc8742012-07-17 17:45:55 +0800897 if new_state.iterations_left and new_state.status == TestState.PASSED:
898 # Play it again, Sam!
899 self._run_test(t)
900
Jon Salz0697cbf2012-07-04 15:14:04 +0800901 if (self.visible_test is None or
Jon Salz85a39882012-07-05 16:45:04 +0800902 self.visible_test not in self.invocations):
Jon Salz0697cbf2012-07-04 15:14:04 +0800903 self.set_visible_test(None)
904 # Make the first running test, if any, the visible test
905 for t in self.test_list.walk():
906 if t in self.invocations:
907 self.set_visible_test(t)
908 break
909
Jon Salz85a39882012-07-05 16:45:04 +0800910 def kill_active_tests(self, abort, root=None):
Jon Salz0697cbf2012-07-04 15:14:04 +0800911 '''
912 Kills and waits for all active tests.
913
Jon Salz85a39882012-07-05 16:45:04 +0800914 Args:
915 abort: True to change state of killed tests to FAILED, False for
Jon Salz0697cbf2012-07-04 15:14:04 +0800916 UNTESTED.
Jon Salz85a39882012-07-05 16:45:04 +0800917 root: If set, only kills tests with root as an ancestor.
Jon Salz0697cbf2012-07-04 15:14:04 +0800918 '''
919 self.reap_completed_tests()
920 for test, invoc in self.invocations.items():
Jon Salz85a39882012-07-05 16:45:04 +0800921 if root and not test.has_ancestor(root):
922 continue
923
Jon Salz0697cbf2012-07-04 15:14:04 +0800924 factory.console.info('Killing active test %s...' % test.path)
925 invoc.abort_and_join()
926 factory.console.info('Killed %s' % test.path)
Jon Salz1acc8742012-07-17 17:45:55 +0800927 test.update_state(**invoc.update_state_on_completion)
Jon Salz0697cbf2012-07-04 15:14:04 +0800928 del self.invocations[test]
Jon Salz1acc8742012-07-17 17:45:55 +0800929
Jon Salz0697cbf2012-07-04 15:14:04 +0800930 if not abort:
931 test.update_state(status=TestState.UNTESTED)
932 self.reap_completed_tests()
933
Jon Salz85a39882012-07-05 16:45:04 +0800934 def stop(self, root=None, fail=False):
935 self.kill_active_tests(fail, root)
936 # Remove any tests in the run queue under the root.
937 self.tests_to_run = deque([x for x in self.tests_to_run
938 if root and not x.has_ancestor(root)])
939 self.run_next_test()
Jon Salz0697cbf2012-07-04 15:14:04 +0800940
Jon Salz4712ac72013-02-07 17:12:05 +0800941 def clear_state(self, root=None):
942 self.stop(root)
943 for f in root.walk():
944 if f.is_leaf():
945 f.update_state(status=TestState.UNTESTED)
946
Jon Salz0697cbf2012-07-04 15:14:04 +0800947 def abort_active_tests(self):
948 self.kill_active_tests(True)
949
950 def main(self):
951 try:
952 self.init()
953 self.event_log.Log('goofy_init',
954 success=True)
955 except:
956 if self.event_log:
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800957 try:
Jon Salz0697cbf2012-07-04 15:14:04 +0800958 self.event_log.Log('goofy_init',
959 success=False,
960 trace=traceback.format_exc())
961 except: # pylint: disable=W0702
962 pass
963 raise
964
965 self.run()
966
967 def update_system_info(self):
968 '''Updates system info.'''
969 system_info = system.SystemInfo()
970 self.state_instance.set_shared_data('system_info', system_info.__dict__)
971 self.event_client.post_event(Event(Event.Type.SYSTEM_INFO,
972 system_info=system_info.__dict__))
973 logging.info('System info: %r', system_info.__dict__)
974
Jon Salzeb42f0d2012-07-27 19:14:04 +0800975 def update_factory(self, auto_run_on_restart=False, post_update_hook=None):
976 '''Commences updating factory software.
977
978 Args:
979 auto_run_on_restart: Auto-run when the machine comes back up.
980 post_update_hook: Code to call after update but immediately before
981 restart.
982
983 Returns:
984 Never if the update was successful (we just reboot).
985 False if the update was unnecessary (no update available).
986 '''
Jon Salz0697cbf2012-07-04 15:14:04 +0800987 self.kill_active_tests(False)
Jon Salza6711d72012-07-18 14:33:03 +0800988 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +0800989
Jon Salz5c344f62012-07-13 14:31:16 +0800990 def pre_update_hook():
991 if auto_run_on_restart:
992 self.state_instance.set_shared_data('tests_after_shutdown',
993 FORCE_AUTO_RUN)
994 self.state_instance.close()
995
Jon Salzeb42f0d2012-07-27 19:14:04 +0800996 if updater.TryUpdate(pre_update_hook=pre_update_hook):
997 if post_update_hook:
998 post_update_hook()
999 self.env.shutdown('reboot')
Jon Salz0697cbf2012-07-04 15:14:04 +08001000
Jon Salzcef132a2012-08-30 04:58:08 +08001001 def handle_sigint(self, dummy_signum, dummy_frame):
Jon Salz77c151e2012-08-28 07:20:37 +08001002 logging.error('Received SIGINT')
1003 self.run_queue.put(None)
1004 raise KeyboardInterrupt()
1005
Jon Salz0697cbf2012-07-04 15:14:04 +08001006 def init(self, args=None, env=None):
1007 '''Initializes Goofy.
1008
1009 Args:
1010 args: A list of command-line arguments. Uses sys.argv if
1011 args is None.
1012 env: An Environment instance to use (or None to choose
1013 FakeChrootEnvironment or DUTEnvironment as appropriate).
1014 '''
Jon Salz77c151e2012-08-28 07:20:37 +08001015 signal.signal(signal.SIGINT, self.handle_sigint)
1016
Jon Salz0697cbf2012-07-04 15:14:04 +08001017 parser = OptionParser()
1018 parser.add_option('-v', '--verbose', dest='verbose',
Jon Salz8fa8e832012-07-13 19:04:09 +08001019 action='store_true',
1020 help='Enable debug logging')
Jon Salz0697cbf2012-07-04 15:14:04 +08001021 parser.add_option('--print_test_list', dest='print_test_list',
Jon Salz8fa8e832012-07-13 19:04:09 +08001022 metavar='FILE',
1023 help='Read and print test list FILE, and exit')
Jon Salz0697cbf2012-07-04 15:14:04 +08001024 parser.add_option('--restart', dest='restart',
Jon Salz8fa8e832012-07-13 19:04:09 +08001025 action='store_true',
1026 help='Clear all test state')
Jon Salz0697cbf2012-07-04 15:14:04 +08001027 parser.add_option('--ui', dest='ui', type='choice',
Jon Salz8fa8e832012-07-13 19:04:09 +08001028 choices=['none', 'gtk', 'chrome'],
Jon Salz2f881df2013-02-01 17:00:35 +08001029 default='chrome',
Jon Salz8fa8e832012-07-13 19:04:09 +08001030 help='UI to use')
Jon Salz0697cbf2012-07-04 15:14:04 +08001031 parser.add_option('--ui_scale_factor', dest='ui_scale_factor',
Jon Salz8fa8e832012-07-13 19:04:09 +08001032 type='int', default=1,
1033 help=('Factor by which to scale UI '
1034 '(Chrome UI only)'))
Jon Salz0697cbf2012-07-04 15:14:04 +08001035 parser.add_option('--test_list', dest='test_list',
Jon Salz8fa8e832012-07-13 19:04:09 +08001036 metavar='FILE',
1037 help='Use FILE as test list')
Jon Salzc79a9982012-08-30 04:42:01 +08001038 parser.add_option('--dummy_shopfloor', action='store_true',
1039 help='Use a dummy shopfloor server')
chungyiafe8f772012-08-15 19:36:29 +08001040 parser.add_option('--automation', dest='automation',
1041 action='store_true',
1042 help='Enable automation on running factory test')
Ricky Liang09216dc2013-02-22 17:26:45 +08001043 parser.add_option('--one_pixel_less', dest='one_pixel_less',
1044 action='store_true',
1045 help=('Start Chrome one pixel less than the full screen.'
1046 'Needed by Exynos platform to run GTK.'))
Jon Salz0697cbf2012-07-04 15:14:04 +08001047 (self.options, self.args) = parser.parse_args(args)
1048
Jon Salz46b89562012-07-05 11:49:22 +08001049 # Make sure factory directories exist.
1050 factory.get_log_root()
1051 factory.get_state_root()
1052 factory.get_test_data_root()
1053
Jon Salz0697cbf2012-07-04 15:14:04 +08001054 global _inited_logging # pylint: disable=W0603
1055 if not _inited_logging:
1056 factory.init_logging('goofy', verbose=self.options.verbose)
1057 _inited_logging = True
Jon Salz8fa8e832012-07-13 19:04:09 +08001058
Jon Salz0f996602012-10-03 15:26:48 +08001059 if self.options.print_test_list:
1060 print factory.read_test_list(
1061 self.options.print_test_list).__repr__(recursive=True)
1062 sys.exit(0)
1063
Jon Salzee85d522012-07-17 14:34:46 +08001064 event_log.IncrementBootSequence()
Jon Salz0697cbf2012-07-04 15:14:04 +08001065 self.event_log = EventLog('goofy')
1066
1067 if (not suppress_chroot_warning and
1068 factory.in_chroot() and
1069 self.options.ui == 'gtk' and
1070 os.environ.get('DISPLAY') in [None, '', ':0', ':0.0']):
1071 # That's not going to work! Tell the user how to run
1072 # this way.
1073 logging.warn(GOOFY_IN_CHROOT_WARNING)
1074 time.sleep(1)
1075
1076 if env:
1077 self.env = env
1078 elif factory.in_chroot():
1079 self.env = test_environment.FakeChrootEnvironment()
1080 logging.warn(
1081 'Using chroot environment: will not actually run autotests')
1082 else:
1083 self.env = test_environment.DUTEnvironment()
1084 self.env.goofy = self
1085
1086 if self.options.restart:
1087 state.clear_state()
1088
Jon Salz0697cbf2012-07-04 15:14:04 +08001089 if self.options.ui_scale_factor != 1 and utils.in_qemu():
1090 logging.warn(
1091 'In QEMU; ignoring ui_scale_factor argument')
1092 self.options.ui_scale_factor = 1
1093
1094 logging.info('Started')
1095
1096 self.start_state_server()
1097 self.state_instance.set_shared_data('hwid_cfg', get_hwid_cfg())
1098 self.state_instance.set_shared_data('ui_scale_factor',
Ricky Liang09216dc2013-02-22 17:26:45 +08001099 self.options.ui_scale_factor)
1100 self.state_instance.set_shared_data('one_pixel_less',
1101 self.options.one_pixel_less)
Jon Salz0697cbf2012-07-04 15:14:04 +08001102 self.last_shutdown_time = (
1103 self.state_instance.get_shared_data('shutdown_time', optional=True))
1104 self.state_instance.del_shared_data('shutdown_time', optional=True)
1105
Jon Salzb19ea072013-02-07 16:35:00 +08001106 self.state_instance.del_shared_data('startup_error', optional=True)
Jon Salz0697cbf2012-07-04 15:14:04 +08001107 if not self.options.test_list:
1108 self.options.test_list = find_test_list()
Jon Salzb19ea072013-02-07 16:35:00 +08001109 if self.options.test_list:
Jon Salz0697cbf2012-07-04 15:14:04 +08001110 logging.info('Using test list %s', self.options.test_list)
Jon Salzb19ea072013-02-07 16:35:00 +08001111 try:
1112 self.test_list = factory.read_test_list(
1113 self.options.test_list,
1114 self.state_instance)
1115 except: # pylint: disable=W0702
1116 logging.exception('Unable to read test list %r', self.options.test_list)
1117 self.state_instance.set_shared_data('startup_error',
1118 'Unable to read test list %s\n%s' % (
1119 self.options.test_list,
1120 traceback.format_exc()))
1121 else:
1122 logging.error('No test list found.')
1123 self.state_instance.set_shared_data('startup_error',
1124 'No test list found.')
Jon Salz0697cbf2012-07-04 15:14:04 +08001125
Jon Salzb19ea072013-02-07 16:35:00 +08001126 if not self.test_list:
1127 if self.options.ui == 'chrome':
1128 # Create an empty test list with default options so that the rest of
1129 # startup can proceed.
1130 self.test_list = factory.FactoryTestList(
1131 [], self.state_instance, factory.Options())
1132 else:
1133 # Bail with an error; no point in starting up.
1134 sys.exit('No valid test list; exiting.')
1135
Jon Salz0697cbf2012-07-04 15:14:04 +08001136 if not self.state_instance.has_shared_data('ui_lang'):
1137 self.state_instance.set_shared_data('ui_lang',
1138 self.test_list.options.ui_lang)
1139 self.state_instance.set_shared_data(
1140 'test_list_options',
1141 self.test_list.options.__dict__)
1142 self.state_instance.test_list = self.test_list
1143
Jon Salz83ef34b2012-11-01 19:46:35 +08001144 if not utils.in_chroot() and self.test_list.options.disable_log_rotation:
1145 open('/var/lib/cleanup_logs_paused', 'w').close()
1146
Jon Salz23926422012-09-01 03:38:13 +08001147 if self.options.dummy_shopfloor:
1148 os.environ[shopfloor.SHOPFLOOR_SERVER_ENV_VAR_NAME] = (
1149 'http://localhost:%d/' % shopfloor.DEFAULT_SERVER_PORT)
1150 self.dummy_shopfloor = Spawn(
1151 [os.path.join(factory.FACTORY_PATH, 'bin', 'shopfloor_server'),
1152 '--dummy'])
1153 elif self.test_list.options.shopfloor_server_url:
1154 shopfloor.set_server_url(self.test_list.options.shopfloor_server_url)
1155
Jon Salz0f996602012-10-03 15:26:48 +08001156 if self.test_list.options.time_sanitizer and not utils.in_chroot():
Jon Salz8fa8e832012-07-13 19:04:09 +08001157 self.time_sanitizer = time_sanitizer.TimeSanitizer(
1158 base_time=time_sanitizer.GetBaseTimeFromFile(
1159 # lsb-factory is written by the factory install shim during
1160 # installation, so it should have a good time obtained from
Jon Salz54882d02012-08-31 01:57:54 +08001161 # the mini-Omaha server. If it's not available, we'll use
1162 # /etc/lsb-factory (which will be much older, but reasonably
1163 # sane) and rely on a shopfloor sync to set a more accurate
1164 # time.
1165 '/usr/local/etc/lsb-factory',
1166 '/etc/lsb-release'))
Jon Salz8fa8e832012-07-13 19:04:09 +08001167 self.time_sanitizer.RunOnce()
1168
Jon Salz0697cbf2012-07-04 15:14:04 +08001169 self.init_states()
1170 self.start_event_server()
1171 self.connection_manager = self.env.create_connection_manager(
Tai-Hsu Lin371351a2012-08-27 14:17:14 +08001172 self.test_list.options.wlans,
1173 self.test_list.options.scan_wifi_period_secs)
Jon Salz0697cbf2012-07-04 15:14:04 +08001174 # Note that we create a log watcher even if
1175 # sync_event_log_period_secs isn't set (no background
1176 # syncing), since we may use it to flush event logs as well.
1177 self.log_watcher = EventLogWatcher(
1178 self.test_list.options.sync_event_log_period_secs,
Jon Salz16d10542012-07-23 12:18:45 +08001179 handle_event_logs_callback=self.handle_event_logs)
Jon Salz0697cbf2012-07-04 15:14:04 +08001180 if self.test_list.options.sync_event_log_period_secs:
1181 self.log_watcher.StartWatchThread()
1182
1183 self.update_system_info()
1184
Vic Yang4953fc12012-07-26 16:19:53 +08001185 assert ((self.test_list.options.min_charge_pct is None) ==
1186 (self.test_list.options.max_charge_pct is None))
Jon Salzad7353b2012-10-15 16:22:46 +08001187 if self.test_list.options.min_charge_pct is not None:
Vic Yang4953fc12012-07-26 16:19:53 +08001188 self.charge_manager = ChargeManager(self.test_list.options.min_charge_pct,
1189 self.test_list.options.max_charge_pct)
Jon Salzad7353b2012-10-15 16:22:46 +08001190 system.SystemStatus.charge_manager = self.charge_manager
Vic Yang4953fc12012-07-26 16:19:53 +08001191
Jon Salz0697cbf2012-07-04 15:14:04 +08001192 os.environ['CROS_FACTORY'] = '1'
1193 os.environ['CROS_DISABLE_SITE_SYSINFO'] = '1'
1194
1195 # Set CROS_UI since some behaviors in ui.py depend on the
1196 # particular UI in use. TODO(jsalz): Remove this (and all
1197 # places it is used) when the GTK UI is removed.
1198 os.environ['CROS_UI'] = self.options.ui
1199
1200 if self.options.ui == 'chrome':
1201 self.env.launch_chrome()
1202 logging.info('Waiting for a web socket connection')
Cheng-Yi Chiangfd8ed392013-03-08 21:37:31 +08001203 self.web_socket_manager.wait()
Jon Salz0697cbf2012-07-04 15:14:04 +08001204
1205 # Wait for the test widget size to be set; this is done in
1206 # an asynchronous RPC so there is a small chance that the
1207 # web socket might be opened first.
1208 for _ in range(100): # 10 s
1209 try:
1210 if self.state_instance.get_shared_data('test_widget_size'):
1211 break
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001212 except KeyError:
Jon Salz0697cbf2012-07-04 15:14:04 +08001213 pass # Retry
1214 time.sleep(0.1) # 100 ms
1215 else:
1216 logging.warn('Never received test_widget_size from UI')
1217 elif self.options.ui == 'gtk':
1218 self.start_ui()
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001219
Ricky Liang650f6bf2012-09-28 13:22:54 +08001220 # Create download path for autotest beforehand or autotests run at
1221 # the same time might fail due to race condition.
1222 if not factory.in_chroot():
1223 utils.TryMakeDirs(os.path.join('/usr/local/autotest', 'tests',
1224 'download'))
1225
Jon Salz0697cbf2012-07-04 15:14:04 +08001226 def state_change_callback(test, test_state):
1227 self.event_client.post_event(
1228 Event(Event.Type.STATE_CHANGE,
1229 path=test.path, state=test_state))
1230 self.test_list.state_change_callback = state_change_callback
Jon Salz73e0fd02012-04-04 11:46:38 +08001231
Jon Salza6711d72012-07-18 14:33:03 +08001232 for handler in self.on_ui_startup:
1233 handler()
1234
1235 self.prespawner = Prespawner()
1236 self.prespawner.start()
1237
Jon Salz0697cbf2012-07-04 15:14:04 +08001238 try:
1239 tests_after_shutdown = self.state_instance.get_shared_data(
1240 'tests_after_shutdown')
1241 except KeyError:
1242 tests_after_shutdown = None
Jon Salz57717ca2012-04-04 16:47:25 +08001243
Jon Salz5c344f62012-07-13 14:31:16 +08001244 force_auto_run = (tests_after_shutdown == FORCE_AUTO_RUN)
1245 if not force_auto_run and tests_after_shutdown is not None:
Jon Salz0697cbf2012-07-04 15:14:04 +08001246 logging.info('Resuming tests after shutdown: %s',
1247 tests_after_shutdown)
Jon Salz0697cbf2012-07-04 15:14:04 +08001248 self.tests_to_run.extend(
1249 self.test_list.lookup_path(t) for t in tests_after_shutdown)
1250 self.run_queue.put(self.run_next_test)
1251 else:
Jon Salz5c344f62012-07-13 14:31:16 +08001252 if force_auto_run or self.test_list.options.auto_run_on_start:
Jon Salz0697cbf2012-07-04 15:14:04 +08001253 self.run_queue.put(
1254 lambda: self.run_tests(self.test_list, untested_only=True))
Jon Salz5c344f62012-07-13 14:31:16 +08001255 self.state_instance.set_shared_data('tests_after_shutdown', None)
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001256
Dean Liao592e4d52013-01-10 20:06:39 +08001257 self.may_disable_cros_shortcut_keys()
1258
1259 def may_disable_cros_shortcut_keys(self):
1260 test_options = self.test_list.options
1261 if test_options.disable_cros_shortcut_keys:
1262 logging.info('Filter ChromeOS shortcut keys.')
1263 self.key_filter = KeyFilter(
1264 unmap_caps_lock=test_options.disable_caps_lock,
1265 caps_lock_keycode=test_options.caps_lock_keycode)
1266 self.key_filter.Start()
1267
Jon Salz0697cbf2012-07-04 15:14:04 +08001268 def run(self):
1269 '''Runs Goofy.'''
1270 # Process events forever.
1271 while self.run_once(True):
1272 pass
Jon Salz73e0fd02012-04-04 11:46:38 +08001273
Jon Salz0697cbf2012-07-04 15:14:04 +08001274 def run_once(self, block=False):
1275 '''Runs all items pending in the event loop.
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001276
Jon Salz0697cbf2012-07-04 15:14:04 +08001277 Args:
1278 block: If true, block until at least one event is processed.
Jon Salz7c15e8b2012-06-19 17:10:37 +08001279
Jon Salz0697cbf2012-07-04 15:14:04 +08001280 Returns:
1281 True to keep going or False to shut down.
1282 '''
1283 events = utils.DrainQueue(self.run_queue)
cychiang21886742012-07-05 15:16:32 +08001284 while not events:
Jon Salz0697cbf2012-07-04 15:14:04 +08001285 # Nothing on the run queue.
1286 self._run_queue_idle()
1287 if block:
1288 # Block for at least one event...
cychiang21886742012-07-05 15:16:32 +08001289 try:
1290 events.append(self.run_queue.get(timeout=RUN_QUEUE_TIMEOUT_SECS))
1291 except Queue.Empty:
1292 # Keep going (calling _run_queue_idle() again at the top of
1293 # the loop)
1294 continue
Jon Salz0697cbf2012-07-04 15:14:04 +08001295 # ...and grab anything else that showed up at the same
1296 # time.
1297 events.extend(utils.DrainQueue(self.run_queue))
cychiang21886742012-07-05 15:16:32 +08001298 else:
1299 break
Jon Salz51528e12012-07-02 18:54:45 +08001300
Jon Salz0697cbf2012-07-04 15:14:04 +08001301 for event in events:
1302 if not event:
1303 # Shutdown request.
1304 self.run_queue.task_done()
1305 return False
Jon Salz51528e12012-07-02 18:54:45 +08001306
Jon Salz0697cbf2012-07-04 15:14:04 +08001307 try:
1308 event()
Jon Salz85a39882012-07-05 16:45:04 +08001309 except: # pylint: disable=W0702
1310 logging.exception('Error in event loop')
Jon Salz0697cbf2012-07-04 15:14:04 +08001311 self.record_exception(traceback.format_exception_only(
1312 *sys.exc_info()[:2]))
1313 # But keep going
1314 finally:
1315 self.run_queue.task_done()
1316 return True
Jon Salz0405ab52012-03-16 15:26:52 +08001317
Jon Salz0e6532d2012-10-25 16:30:11 +08001318 def _should_sync_time(self, foreground=False):
1319 '''Returns True if we should attempt syncing time with shopfloor.
1320
1321 Args:
1322 foreground: If True, synchronizes even if background syncing
1323 is disabled (e.g., in explicit sync requests from the
1324 SyncShopfloor test).
1325 '''
1326 return ((foreground or
1327 self.test_list.options.sync_time_period_secs) and
Jon Salz54882d02012-08-31 01:57:54 +08001328 self.time_sanitizer and
1329 (not self.time_synced) and
1330 (not factory.in_chroot()))
1331
Jon Salz0e6532d2012-10-25 16:30:11 +08001332 def sync_time_with_shopfloor_server(self, foreground=False):
Jon Salz54882d02012-08-31 01:57:54 +08001333 '''Syncs time with shopfloor server, if not yet synced.
1334
Jon Salz0e6532d2012-10-25 16:30:11 +08001335 Args:
1336 foreground: If True, synchronizes even if background syncing
1337 is disabled (e.g., in explicit sync requests from the
1338 SyncShopfloor test).
1339
Jon Salz54882d02012-08-31 01:57:54 +08001340 Returns:
1341 False if no time sanitizer is available, or True if this sync (or a
1342 previous sync) succeeded.
1343
1344 Raises:
1345 Exception if unable to contact the shopfloor server.
1346 '''
Jon Salz0e6532d2012-10-25 16:30:11 +08001347 if self._should_sync_time(foreground):
Jon Salz54882d02012-08-31 01:57:54 +08001348 self.time_sanitizer.SyncWithShopfloor()
1349 self.time_synced = True
1350 return self.time_synced
1351
Jon Salzb92c5112012-09-21 15:40:11 +08001352 def log_disk_space_stats(self):
1353 if not self.test_list.options.log_disk_space_period_secs:
1354 return
1355
1356 now = time.time()
1357 if (self.last_log_disk_space_time and
1358 now - self.last_log_disk_space_time <
1359 self.test_list.options.log_disk_space_period_secs):
1360 return
1361 self.last_log_disk_space_time = now
1362
1363 try:
Jon Salz3c493bb2013-02-07 17:24:58 +08001364 message = disk_space.FormatSpaceUsedAll()
1365 if message != self.last_log_disk_space_message:
1366 logging.info(message)
1367 self.last_log_disk_space_message = message
Jon Salzb92c5112012-09-21 15:40:11 +08001368 except: # pylint: disable=W0702
1369 logging.exception('Unable to get disk space used')
1370
Jon Salz8fa8e832012-07-13 19:04:09 +08001371 def sync_time_in_background(self):
Jon Salzb22d1172012-08-06 10:38:57 +08001372 '''Writes out current time and tries to sync with shopfloor server.'''
1373 if not self.time_sanitizer:
1374 return
1375
1376 # Write out the current time.
1377 self.time_sanitizer.SaveTime()
1378
Jon Salz54882d02012-08-31 01:57:54 +08001379 if not self._should_sync_time():
Jon Salz8fa8e832012-07-13 19:04:09 +08001380 return
1381
1382 now = time.time()
1383 if self.last_sync_time and (
1384 now - self.last_sync_time <
1385 self.test_list.options.sync_time_period_secs):
1386 # Not yet time for another check.
1387 return
1388 self.last_sync_time = now
1389
1390 def target():
1391 try:
Jon Salz54882d02012-08-31 01:57:54 +08001392 self.sync_time_with_shopfloor_server()
Jon Salz8fa8e832012-07-13 19:04:09 +08001393 except: # pylint: disable=W0702
1394 # Oh well. Log an error (but no trace)
1395 logging.info(
1396 'Unable to get time from shopfloor server: %s',
1397 utils.FormatExceptionOnly())
1398
1399 thread = threading.Thread(target=target)
1400 thread.daemon = True
1401 thread.start()
1402
Jon Salz0697cbf2012-07-04 15:14:04 +08001403 def _run_queue_idle(self):
Vic Yang4953fc12012-07-26 16:19:53 +08001404 '''Invoked when the run queue has no events.
1405
1406 This method must not raise exception.
1407 '''
Jon Salzb22d1172012-08-06 10:38:57 +08001408 now = time.time()
1409 if (self.last_idle and
1410 now < (self.last_idle + RUN_QUEUE_TIMEOUT_SECS - 1)):
1411 # Don't run more often than once every (RUN_QUEUE_TIMEOUT_SECS -
1412 # 1) seconds.
1413 return
1414
1415 self.last_idle = now
1416
Vic Yang311ddb82012-09-26 12:08:28 +08001417 self.check_exclusive()
cychiang21886742012-07-05 15:16:32 +08001418 self.check_for_updates()
Jon Salz8fa8e832012-07-13 19:04:09 +08001419 self.sync_time_in_background()
Jon Salzb92c5112012-09-21 15:40:11 +08001420 self.log_disk_space_stats()
Jon Salz57717ca2012-04-04 16:47:25 +08001421
Jon Salz16d10542012-07-23 12:18:45 +08001422 def handle_event_logs(self, log_name, chunk):
Jon Salz0697cbf2012-07-04 15:14:04 +08001423 '''Callback for event watcher.
Jon Salz258a40c2012-04-19 12:34:01 +08001424
Jon Salz0697cbf2012-07-04 15:14:04 +08001425 Attempts to upload the event logs to the shopfloor server.
1426 '''
1427 description = 'event logs (%s, %d bytes)' % (log_name, len(chunk))
1428 start_time = time.time()
Jon Salz0697cbf2012-07-04 15:14:04 +08001429 shopfloor_client = shopfloor.get_instance(
1430 detect=True,
1431 timeout=self.test_list.options.shopfloor_timeout_secs)
Jon Salzb10cf512012-08-09 17:29:21 +08001432 shopfloor_client.UploadEvent(log_name, Binary(chunk))
Jon Salz0697cbf2012-07-04 15:14:04 +08001433 logging.info(
1434 'Successfully synced %s in %.03f s',
1435 description, time.time() - start_time)
Jon Salz57717ca2012-04-04 16:47:25 +08001436
Jon Salz0697cbf2012-07-04 15:14:04 +08001437 def run_tests_with_status(self, statuses_to_run, starting_at=None,
1438 root=None):
1439 '''Runs all top-level tests with a particular status.
Jon Salz0405ab52012-03-16 15:26:52 +08001440
Jon Salz0697cbf2012-07-04 15:14:04 +08001441 All active tests, plus any tests to re-run, are reset.
Jon Salz57717ca2012-04-04 16:47:25 +08001442
Jon Salz0697cbf2012-07-04 15:14:04 +08001443 Args:
1444 starting_at: If provided, only auto-runs tests beginning with
1445 this test.
1446 '''
1447 root = root or self.test_list
Jon Salz57717ca2012-04-04 16:47:25 +08001448
Jon Salz0697cbf2012-07-04 15:14:04 +08001449 if starting_at:
1450 # Make sure they passed a test, not a string.
1451 assert isinstance(starting_at, factory.FactoryTest)
Jon Salz0405ab52012-03-16 15:26:52 +08001452
Jon Salz0697cbf2012-07-04 15:14:04 +08001453 tests_to_reset = []
1454 tests_to_run = []
Jon Salz0405ab52012-03-16 15:26:52 +08001455
Jon Salz0697cbf2012-07-04 15:14:04 +08001456 found_starting_at = False
Jon Salz0405ab52012-03-16 15:26:52 +08001457
Jon Salz0697cbf2012-07-04 15:14:04 +08001458 for test in root.get_top_level_tests():
1459 if starting_at:
1460 if test == starting_at:
1461 # We've found starting_at; do auto-run on all
1462 # subsequent tests.
1463 found_starting_at = True
1464 if not found_starting_at:
1465 # Don't start this guy yet
1466 continue
Jon Salz0405ab52012-03-16 15:26:52 +08001467
Jon Salz0697cbf2012-07-04 15:14:04 +08001468 status = test.get_state().status
1469 if status == TestState.ACTIVE or status in statuses_to_run:
1470 # Reset the test (later; we will need to abort
1471 # all active tests first).
1472 tests_to_reset.append(test)
1473 if status in statuses_to_run:
1474 tests_to_run.append(test)
Jon Salz0405ab52012-03-16 15:26:52 +08001475
Jon Salz0697cbf2012-07-04 15:14:04 +08001476 self.abort_active_tests()
Jon Salz258a40c2012-04-19 12:34:01 +08001477
Jon Salz0697cbf2012-07-04 15:14:04 +08001478 # Reset all statuses of the tests to run (in case any tests were active;
1479 # we want them to be run again).
1480 for test_to_reset in tests_to_reset:
1481 for test in test_to_reset.walk():
1482 test.update_state(status=TestState.UNTESTED)
Jon Salz57717ca2012-04-04 16:47:25 +08001483
Jon Salz0697cbf2012-07-04 15:14:04 +08001484 self.run_tests(tests_to_run, untested_only=True)
Jon Salz0405ab52012-03-16 15:26:52 +08001485
Jon Salz0697cbf2012-07-04 15:14:04 +08001486 def restart_tests(self, root=None):
1487 '''Restarts all tests.'''
1488 root = root or self.test_list
Jon Salz0405ab52012-03-16 15:26:52 +08001489
Jon Salz0697cbf2012-07-04 15:14:04 +08001490 self.abort_active_tests()
1491 for test in root.walk():
1492 test.update_state(status=TestState.UNTESTED)
1493 self.run_tests(root)
Hung-Te Lin96632362012-03-20 21:14:18 +08001494
Jon Salz0697cbf2012-07-04 15:14:04 +08001495 def auto_run(self, starting_at=None, root=None):
1496 '''"Auto-runs" tests that have not been run yet.
Hung-Te Lin96632362012-03-20 21:14:18 +08001497
Jon Salz0697cbf2012-07-04 15:14:04 +08001498 Args:
1499 starting_at: If provide, only auto-runs tests beginning with
1500 this test.
1501 '''
1502 root = root or self.test_list
1503 self.run_tests_with_status([TestState.UNTESTED, TestState.ACTIVE],
1504 starting_at=starting_at,
1505 root=root)
Jon Salz968e90b2012-03-18 16:12:43 +08001506
Jon Salz0697cbf2012-07-04 15:14:04 +08001507 def re_run_failed(self, root=None):
1508 '''Re-runs failed tests.'''
1509 root = root or self.test_list
1510 self.run_tests_with_status([TestState.FAILED], root=root)
Jon Salz57717ca2012-04-04 16:47:25 +08001511
Jon Salz0697cbf2012-07-04 15:14:04 +08001512 def show_review_information(self):
1513 '''Event handler for showing review information screen.
Jon Salz57717ca2012-04-04 16:47:25 +08001514
Jon Salz0697cbf2012-07-04 15:14:04 +08001515 The information screene is rendered by main UI program (ui.py), so in
1516 goofy we only need to kill all active tests, set them as untested, and
1517 clear remaining tests.
1518 '''
1519 self.kill_active_tests(False)
Jon Salza6711d72012-07-18 14:33:03 +08001520 self.cancel_pending_tests()
Jon Salz57717ca2012-04-04 16:47:25 +08001521
Jon Salz0697cbf2012-07-04 15:14:04 +08001522 def handle_switch_test(self, event):
1523 '''Switches to a particular test.
Jon Salz0405ab52012-03-16 15:26:52 +08001524
Jon Salz0697cbf2012-07-04 15:14:04 +08001525 @param event: The SWITCH_TEST event.
1526 '''
1527 test = self.test_list.lookup_path(event.path)
1528 if not test:
1529 logging.error('Unknown test %r', event.key)
1530 return
Jon Salz73e0fd02012-04-04 11:46:38 +08001531
Jon Salz0697cbf2012-07-04 15:14:04 +08001532 invoc = self.invocations.get(test)
1533 if invoc and test.backgroundable:
1534 # Already running: just bring to the front if it
1535 # has a UI.
1536 logging.info('Setting visible test to %s', test.path)
Jon Salz36fbbb52012-07-05 13:45:06 +08001537 self.set_visible_test(test)
Jon Salz0697cbf2012-07-04 15:14:04 +08001538 return
Jon Salz73e0fd02012-04-04 11:46:38 +08001539
Jon Salz0697cbf2012-07-04 15:14:04 +08001540 self.abort_active_tests()
1541 for t in test.walk():
1542 t.update_state(status=TestState.UNTESTED)
Jon Salz73e0fd02012-04-04 11:46:38 +08001543
Jon Salz0697cbf2012-07-04 15:14:04 +08001544 if self.test_list.options.auto_run_on_keypress:
1545 self.auto_run(starting_at=test)
1546 else:
1547 self.run_tests(test)
Jon Salz73e0fd02012-04-04 11:46:38 +08001548
Jon Salz0697cbf2012-07-04 15:14:04 +08001549 def wait(self):
1550 '''Waits for all pending invocations.
1551
1552 Useful for testing.
1553 '''
Jon Salz1acc8742012-07-17 17:45:55 +08001554 while self.invocations:
1555 for k, v in self.invocations.iteritems():
1556 logging.info('Waiting for %s to complete...', k)
1557 v.thread.join()
1558 self.reap_completed_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +08001559
1560 def check_exceptions(self):
1561 '''Raises an error if any exceptions have occurred in
1562 invocation threads.'''
1563 if self.exceptions:
1564 raise RuntimeError('Exception in invocation thread: %r' %
1565 self.exceptions)
1566
1567 def record_exception(self, msg):
1568 '''Records an exception in an invocation thread.
1569
1570 An exception with the given message will be rethrown when
1571 Goofy is destroyed.'''
1572 self.exceptions.append(msg)
Jon Salz73e0fd02012-04-04 11:46:38 +08001573
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001574
1575if __name__ == '__main__':
Jon Salz77c151e2012-08-28 07:20:37 +08001576 goofy = Goofy()
1577 try:
1578 goofy.main()
Jon Salz0f996602012-10-03 15:26:48 +08001579 except SystemExit:
1580 # Propagate SystemExit without logging.
1581 raise
Jon Salz31373eb2012-09-21 16:19:49 +08001582 except:
Jon Salz0f996602012-10-03 15:26:48 +08001583 # Log the error before trying to shut down (unless it's a graceful
1584 # exit).
Jon Salz31373eb2012-09-21 16:19:49 +08001585 logging.exception('Error in main loop')
1586 raise
Jon Salz77c151e2012-08-28 07:20:37 +08001587 finally:
1588 goofy.destroy()