blob: 10f5782f33480cf0dafb9cbe620d67c471218c90 [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
Cheng-Yi Chiangce05c002013-04-04 02:13:17 +0800769 self._run_test(test, test.iterations, test.retries)
Jon Salz1acc8742012-07-17 17:45:55 +0800770
Cheng-Yi Chiangce05c002013-04-04 02:13:17 +0800771 def _run_test(self, test, iterations_left=None, retries_left=None):
Jon Salz1acc8742012-07-17 17:45:55 +0800772 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,
Cheng-Yi Chiangce05c002013-04-04 02:13:17 +0800776 retries_left=retries_left,
Jon Salzbd42ce12012-09-18 08:03:59 +0800777 visible=(self.visible_test == test))
Jon Salz1acc8742012-07-17 17:45:55 +0800778 invoc.count = new_state.count
779
780 self.invocations[test] = invoc
781 if self.visible_test is None and test.has_ui:
782 self.set_visible_test(test)
Vic Yang311ddb82012-09-26 12:08:28 +0800783 self.check_exclusive()
Jon Salz1acc8742012-07-17 17:45:55 +0800784 invoc.start()
Jon Salz5f2a0672012-05-22 17:14:06 +0800785
Vic Yang311ddb82012-09-26 12:08:28 +0800786 def check_exclusive(self):
787 current_exclusive_items = set([
788 item
789 for item in factory.FactoryTest.EXCLUSIVE_OPTIONS
790 if any([test.is_exclusive(item) for test in self.invocations])])
791
792 new_exclusive_items = current_exclusive_items - self.exclusive_items
793 if factory.FactoryTest.EXCLUSIVE_OPTIONS.NETWORKING in new_exclusive_items:
794 logging.info('Disabling network')
795 self.connection_manager.DisableNetworking()
796 if factory.FactoryTest.EXCLUSIVE_OPTIONS.CHARGER in new_exclusive_items:
797 logging.info('Stop controlling charger')
798
799 new_non_exclusive_items = self.exclusive_items - current_exclusive_items
800 if (factory.FactoryTest.EXCLUSIVE_OPTIONS.NETWORKING in
801 new_non_exclusive_items):
802 logging.info('Re-enabling network')
803 self.connection_manager.EnableNetworking()
804 if factory.FactoryTest.EXCLUSIVE_OPTIONS.CHARGER in new_non_exclusive_items:
805 logging.info('Start controlling charger')
806
807 # Only adjust charge state if not excluded
808 if (self.charge_manager and
809 not factory.FactoryTest.EXCLUSIVE_OPTIONS.CHARGER in
810 current_exclusive_items):
811 self.charge_manager.AdjustChargeState()
812
813 self.exclusive_items = current_exclusive_items
Jon Salz5da61e62012-05-31 13:06:22 +0800814
cychiang21886742012-07-05 15:16:32 +0800815 def check_for_updates(self):
816 '''
817 Schedules an asynchronous check for updates if necessary.
818 '''
819 if not self.test_list.options.update_period_secs:
820 # Not enabled.
821 return
822
823 now = time.time()
824 if self.last_update_check and (
825 now - self.last_update_check <
826 self.test_list.options.update_period_secs):
827 # Not yet time for another check.
828 return
829
830 self.last_update_check = now
831
832 def handle_check_for_update(reached_shopfloor, md5sum, needs_update):
833 if reached_shopfloor:
834 new_update_md5sum = md5sum if needs_update else None
835 if system.SystemInfo.update_md5sum != new_update_md5sum:
836 logging.info('Received new update MD5SUM: %s', new_update_md5sum)
837 system.SystemInfo.update_md5sum = new_update_md5sum
838 self.run_queue.put(self.update_system_info)
839
840 updater.CheckForUpdateAsync(
841 handle_check_for_update,
842 self.test_list.options.shopfloor_timeout_secs)
843
Jon Salza6711d72012-07-18 14:33:03 +0800844 def cancel_pending_tests(self):
845 '''Cancels any tests in the run queue.'''
846 self.run_tests([])
847
Jon Salz0697cbf2012-07-04 15:14:04 +0800848 def run_tests(self, subtrees, untested_only=False):
849 '''
850 Runs tests under subtree.
Jon Salz258a40c2012-04-19 12:34:01 +0800851
Jon Salz0697cbf2012-07-04 15:14:04 +0800852 The tests are run in order unless one fails (then stops).
853 Backgroundable tests are run simultaneously; when a foreground test is
854 encountered, we wait for all active tests to finish before continuing.
Jon Salzb1b39092012-05-03 02:05:09 +0800855
Jon Salz0697cbf2012-07-04 15:14:04 +0800856 @param subtrees: Node or nodes containing tests to run (may either be
857 a single test or a list). Duplicates will be ignored.
858 '''
859 if type(subtrees) != list:
860 subtrees = [subtrees]
Jon Salz258a40c2012-04-19 12:34:01 +0800861
Jon Salz0697cbf2012-07-04 15:14:04 +0800862 # Nodes we've seen so far, to avoid duplicates.
863 seen = set()
Jon Salz94eb56f2012-06-12 18:01:12 +0800864
Jon Salz0697cbf2012-07-04 15:14:04 +0800865 self.tests_to_run = deque()
866 for subtree in subtrees:
867 for test in subtree.walk():
868 if test in seen:
869 continue
870 seen.add(test)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800871
Jon Salz0697cbf2012-07-04 15:14:04 +0800872 if not test.is_leaf():
873 continue
874 if (untested_only and
875 test.get_state().status != TestState.UNTESTED):
876 continue
877 self.tests_to_run.append(test)
878 self.run_next_test()
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800879
Jon Salz0697cbf2012-07-04 15:14:04 +0800880 def reap_completed_tests(self):
881 '''
882 Removes completed tests from the set of active tests.
883
884 Also updates the visible test if it was reaped.
885 '''
886 for t, v in dict(self.invocations).iteritems():
887 if v.is_completed():
Jon Salz1acc8742012-07-17 17:45:55 +0800888 new_state = t.update_state(**v.update_state_on_completion)
Jon Salz0697cbf2012-07-04 15:14:04 +0800889 del self.invocations[t]
890
Chun-Ta Lin54e17e42012-09-06 22:05:13 +0800891 # Stop on failure if flag is true.
892 if (self.test_list.options.stop_on_failure and
893 new_state.status == TestState.FAILED):
894 # Clean all the tests to cause goofy to stop.
895 self.tests_to_run = []
896 factory.console.info("Stop on failure triggered. Empty the queue.")
897
Jon Salz1acc8742012-07-17 17:45:55 +0800898 if new_state.iterations_left and new_state.status == TestState.PASSED:
899 # Play it again, Sam!
900 self._run_test(t)
Cheng-Yi Chiangce05c002013-04-04 02:13:17 +0800901 # new_state.retries_left is obtained after update.
902 # For retries_left == 0, test can still be run for the last time.
903 elif (new_state.retries_left >= 0 and
904 new_state.status == TestState.FAILED):
905 # Still have to retry, Sam!
906 self._run_test(t)
Jon Salz1acc8742012-07-17 17:45:55 +0800907
Jon Salz0697cbf2012-07-04 15:14:04 +0800908 if (self.visible_test is None or
Jon Salz85a39882012-07-05 16:45:04 +0800909 self.visible_test not in self.invocations):
Jon Salz0697cbf2012-07-04 15:14:04 +0800910 self.set_visible_test(None)
911 # Make the first running test, if any, the visible test
912 for t in self.test_list.walk():
913 if t in self.invocations:
914 self.set_visible_test(t)
915 break
916
Jon Salz85a39882012-07-05 16:45:04 +0800917 def kill_active_tests(self, abort, root=None):
Jon Salz0697cbf2012-07-04 15:14:04 +0800918 '''
919 Kills and waits for all active tests.
920
Jon Salz85a39882012-07-05 16:45:04 +0800921 Args:
922 abort: True to change state of killed tests to FAILED, False for
Jon Salz0697cbf2012-07-04 15:14:04 +0800923 UNTESTED.
Jon Salz85a39882012-07-05 16:45:04 +0800924 root: If set, only kills tests with root as an ancestor.
Jon Salz0697cbf2012-07-04 15:14:04 +0800925 '''
926 self.reap_completed_tests()
927 for test, invoc in self.invocations.items():
Jon Salz85a39882012-07-05 16:45:04 +0800928 if root and not test.has_ancestor(root):
929 continue
930
Jon Salz0697cbf2012-07-04 15:14:04 +0800931 factory.console.info('Killing active test %s...' % test.path)
932 invoc.abort_and_join()
933 factory.console.info('Killed %s' % test.path)
Jon Salz1acc8742012-07-17 17:45:55 +0800934 test.update_state(**invoc.update_state_on_completion)
Jon Salz0697cbf2012-07-04 15:14:04 +0800935 del self.invocations[test]
Jon Salz1acc8742012-07-17 17:45:55 +0800936
Jon Salz0697cbf2012-07-04 15:14:04 +0800937 if not abort:
938 test.update_state(status=TestState.UNTESTED)
939 self.reap_completed_tests()
940
Jon Salz85a39882012-07-05 16:45:04 +0800941 def stop(self, root=None, fail=False):
942 self.kill_active_tests(fail, root)
943 # Remove any tests in the run queue under the root.
944 self.tests_to_run = deque([x for x in self.tests_to_run
945 if root and not x.has_ancestor(root)])
946 self.run_next_test()
Jon Salz0697cbf2012-07-04 15:14:04 +0800947
Jon Salz4712ac72013-02-07 17:12:05 +0800948 def clear_state(self, root=None):
949 self.stop(root)
950 for f in root.walk():
951 if f.is_leaf():
952 f.update_state(status=TestState.UNTESTED)
953
Jon Salz0697cbf2012-07-04 15:14:04 +0800954 def abort_active_tests(self):
955 self.kill_active_tests(True)
956
957 def main(self):
958 try:
959 self.init()
960 self.event_log.Log('goofy_init',
961 success=True)
962 except:
963 if self.event_log:
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800964 try:
Jon Salz0697cbf2012-07-04 15:14:04 +0800965 self.event_log.Log('goofy_init',
966 success=False,
967 trace=traceback.format_exc())
968 except: # pylint: disable=W0702
969 pass
970 raise
971
972 self.run()
973
974 def update_system_info(self):
975 '''Updates system info.'''
976 system_info = system.SystemInfo()
977 self.state_instance.set_shared_data('system_info', system_info.__dict__)
978 self.event_client.post_event(Event(Event.Type.SYSTEM_INFO,
979 system_info=system_info.__dict__))
980 logging.info('System info: %r', system_info.__dict__)
981
Jon Salzeb42f0d2012-07-27 19:14:04 +0800982 def update_factory(self, auto_run_on_restart=False, post_update_hook=None):
983 '''Commences updating factory software.
984
985 Args:
986 auto_run_on_restart: Auto-run when the machine comes back up.
987 post_update_hook: Code to call after update but immediately before
988 restart.
989
990 Returns:
991 Never if the update was successful (we just reboot).
992 False if the update was unnecessary (no update available).
993 '''
Jon Salz0697cbf2012-07-04 15:14:04 +0800994 self.kill_active_tests(False)
Jon Salza6711d72012-07-18 14:33:03 +0800995 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +0800996
Jon Salz5c344f62012-07-13 14:31:16 +0800997 def pre_update_hook():
998 if auto_run_on_restart:
999 self.state_instance.set_shared_data('tests_after_shutdown',
1000 FORCE_AUTO_RUN)
1001 self.state_instance.close()
1002
Jon Salzeb42f0d2012-07-27 19:14:04 +08001003 if updater.TryUpdate(pre_update_hook=pre_update_hook):
1004 if post_update_hook:
1005 post_update_hook()
1006 self.env.shutdown('reboot')
Jon Salz0697cbf2012-07-04 15:14:04 +08001007
Jon Salzcef132a2012-08-30 04:58:08 +08001008 def handle_sigint(self, dummy_signum, dummy_frame):
Jon Salz77c151e2012-08-28 07:20:37 +08001009 logging.error('Received SIGINT')
1010 self.run_queue.put(None)
1011 raise KeyboardInterrupt()
1012
Jon Salz0697cbf2012-07-04 15:14:04 +08001013 def init(self, args=None, env=None):
1014 '''Initializes Goofy.
1015
1016 Args:
1017 args: A list of command-line arguments. Uses sys.argv if
1018 args is None.
1019 env: An Environment instance to use (or None to choose
1020 FakeChrootEnvironment or DUTEnvironment as appropriate).
1021 '''
Jon Salz77c151e2012-08-28 07:20:37 +08001022 signal.signal(signal.SIGINT, self.handle_sigint)
1023
Jon Salz0697cbf2012-07-04 15:14:04 +08001024 parser = OptionParser()
1025 parser.add_option('-v', '--verbose', dest='verbose',
Jon Salz8fa8e832012-07-13 19:04:09 +08001026 action='store_true',
1027 help='Enable debug logging')
Jon Salz0697cbf2012-07-04 15:14:04 +08001028 parser.add_option('--print_test_list', dest='print_test_list',
Jon Salz8fa8e832012-07-13 19:04:09 +08001029 metavar='FILE',
1030 help='Read and print test list FILE, and exit')
Jon Salz0697cbf2012-07-04 15:14:04 +08001031 parser.add_option('--restart', dest='restart',
Jon Salz8fa8e832012-07-13 19:04:09 +08001032 action='store_true',
1033 help='Clear all test state')
Jon Salz0697cbf2012-07-04 15:14:04 +08001034 parser.add_option('--ui', dest='ui', type='choice',
Jon Salz8fa8e832012-07-13 19:04:09 +08001035 choices=['none', 'gtk', 'chrome'],
Jon Salz2f881df2013-02-01 17:00:35 +08001036 default='chrome',
Jon Salz8fa8e832012-07-13 19:04:09 +08001037 help='UI to use')
Jon Salz0697cbf2012-07-04 15:14:04 +08001038 parser.add_option('--ui_scale_factor', dest='ui_scale_factor',
Jon Salz8fa8e832012-07-13 19:04:09 +08001039 type='int', default=1,
1040 help=('Factor by which to scale UI '
1041 '(Chrome UI only)'))
Jon Salz0697cbf2012-07-04 15:14:04 +08001042 parser.add_option('--test_list', dest='test_list',
Jon Salz8fa8e832012-07-13 19:04:09 +08001043 metavar='FILE',
1044 help='Use FILE as test list')
Jon Salzc79a9982012-08-30 04:42:01 +08001045 parser.add_option('--dummy_shopfloor', action='store_true',
1046 help='Use a dummy shopfloor server')
chungyiafe8f772012-08-15 19:36:29 +08001047 parser.add_option('--automation', dest='automation',
1048 action='store_true',
1049 help='Enable automation on running factory test')
Ricky Liang09216dc2013-02-22 17:26:45 +08001050 parser.add_option('--one_pixel_less', dest='one_pixel_less',
1051 action='store_true',
1052 help=('Start Chrome one pixel less than the full screen.'
1053 'Needed by Exynos platform to run GTK.'))
Jon Salz0697cbf2012-07-04 15:14:04 +08001054 (self.options, self.args) = parser.parse_args(args)
1055
Jon Salz46b89562012-07-05 11:49:22 +08001056 # Make sure factory directories exist.
1057 factory.get_log_root()
1058 factory.get_state_root()
1059 factory.get_test_data_root()
1060
Jon Salz0697cbf2012-07-04 15:14:04 +08001061 global _inited_logging # pylint: disable=W0603
1062 if not _inited_logging:
1063 factory.init_logging('goofy', verbose=self.options.verbose)
1064 _inited_logging = True
Jon Salz8fa8e832012-07-13 19:04:09 +08001065
Jon Salz0f996602012-10-03 15:26:48 +08001066 if self.options.print_test_list:
1067 print factory.read_test_list(
1068 self.options.print_test_list).__repr__(recursive=True)
1069 sys.exit(0)
1070
Jon Salzee85d522012-07-17 14:34:46 +08001071 event_log.IncrementBootSequence()
Jon Salz0697cbf2012-07-04 15:14:04 +08001072 self.event_log = EventLog('goofy')
1073
1074 if (not suppress_chroot_warning and
1075 factory.in_chroot() and
1076 self.options.ui == 'gtk' and
1077 os.environ.get('DISPLAY') in [None, '', ':0', ':0.0']):
1078 # That's not going to work! Tell the user how to run
1079 # this way.
1080 logging.warn(GOOFY_IN_CHROOT_WARNING)
1081 time.sleep(1)
1082
1083 if env:
1084 self.env = env
1085 elif factory.in_chroot():
1086 self.env = test_environment.FakeChrootEnvironment()
1087 logging.warn(
1088 'Using chroot environment: will not actually run autotests')
1089 else:
1090 self.env = test_environment.DUTEnvironment()
1091 self.env.goofy = self
1092
1093 if self.options.restart:
1094 state.clear_state()
1095
Jon Salz0697cbf2012-07-04 15:14:04 +08001096 if self.options.ui_scale_factor != 1 and utils.in_qemu():
1097 logging.warn(
1098 'In QEMU; ignoring ui_scale_factor argument')
1099 self.options.ui_scale_factor = 1
1100
1101 logging.info('Started')
1102
1103 self.start_state_server()
1104 self.state_instance.set_shared_data('hwid_cfg', get_hwid_cfg())
1105 self.state_instance.set_shared_data('ui_scale_factor',
Ricky Liang09216dc2013-02-22 17:26:45 +08001106 self.options.ui_scale_factor)
1107 self.state_instance.set_shared_data('one_pixel_less',
1108 self.options.one_pixel_less)
Jon Salz0697cbf2012-07-04 15:14:04 +08001109 self.last_shutdown_time = (
1110 self.state_instance.get_shared_data('shutdown_time', optional=True))
1111 self.state_instance.del_shared_data('shutdown_time', optional=True)
1112
Jon Salzb19ea072013-02-07 16:35:00 +08001113 self.state_instance.del_shared_data('startup_error', optional=True)
Jon Salz0697cbf2012-07-04 15:14:04 +08001114 if not self.options.test_list:
1115 self.options.test_list = find_test_list()
Jon Salzb19ea072013-02-07 16:35:00 +08001116 if self.options.test_list:
Jon Salz0697cbf2012-07-04 15:14:04 +08001117 logging.info('Using test list %s', self.options.test_list)
Jon Salzb19ea072013-02-07 16:35:00 +08001118 try:
1119 self.test_list = factory.read_test_list(
1120 self.options.test_list,
1121 self.state_instance)
1122 except: # pylint: disable=W0702
1123 logging.exception('Unable to read test list %r', self.options.test_list)
1124 self.state_instance.set_shared_data('startup_error',
1125 'Unable to read test list %s\n%s' % (
1126 self.options.test_list,
1127 traceback.format_exc()))
1128 else:
1129 logging.error('No test list found.')
1130 self.state_instance.set_shared_data('startup_error',
1131 'No test list found.')
Jon Salz0697cbf2012-07-04 15:14:04 +08001132
Jon Salzb19ea072013-02-07 16:35:00 +08001133 if not self.test_list:
1134 if self.options.ui == 'chrome':
1135 # Create an empty test list with default options so that the rest of
1136 # startup can proceed.
1137 self.test_list = factory.FactoryTestList(
1138 [], self.state_instance, factory.Options())
1139 else:
1140 # Bail with an error; no point in starting up.
1141 sys.exit('No valid test list; exiting.')
1142
Jon Salz822838b2013-03-25 17:32:33 +08001143 if self.test_list.options.clear_state_on_start:
1144 self.state_instance.clear_test_state()
1145
Jon Salz0697cbf2012-07-04 15:14:04 +08001146 if not self.state_instance.has_shared_data('ui_lang'):
1147 self.state_instance.set_shared_data('ui_lang',
1148 self.test_list.options.ui_lang)
1149 self.state_instance.set_shared_data(
1150 'test_list_options',
1151 self.test_list.options.__dict__)
1152 self.state_instance.test_list = self.test_list
1153
Jon Salz83ef34b2012-11-01 19:46:35 +08001154 if not utils.in_chroot() and self.test_list.options.disable_log_rotation:
1155 open('/var/lib/cleanup_logs_paused', 'w').close()
1156
Jon Salz23926422012-09-01 03:38:13 +08001157 if self.options.dummy_shopfloor:
1158 os.environ[shopfloor.SHOPFLOOR_SERVER_ENV_VAR_NAME] = (
1159 'http://localhost:%d/' % shopfloor.DEFAULT_SERVER_PORT)
1160 self.dummy_shopfloor = Spawn(
1161 [os.path.join(factory.FACTORY_PATH, 'bin', 'shopfloor_server'),
1162 '--dummy'])
1163 elif self.test_list.options.shopfloor_server_url:
1164 shopfloor.set_server_url(self.test_list.options.shopfloor_server_url)
Jon Salz2bf2f6b2013-03-28 18:49:26 +08001165 shopfloor.set_enabled(True)
Jon Salz23926422012-09-01 03:38:13 +08001166
Jon Salz0f996602012-10-03 15:26:48 +08001167 if self.test_list.options.time_sanitizer and not utils.in_chroot():
Jon Salz8fa8e832012-07-13 19:04:09 +08001168 self.time_sanitizer = time_sanitizer.TimeSanitizer(
1169 base_time=time_sanitizer.GetBaseTimeFromFile(
1170 # lsb-factory is written by the factory install shim during
1171 # installation, so it should have a good time obtained from
Jon Salz54882d02012-08-31 01:57:54 +08001172 # the mini-Omaha server. If it's not available, we'll use
1173 # /etc/lsb-factory (which will be much older, but reasonably
1174 # sane) and rely on a shopfloor sync to set a more accurate
1175 # time.
1176 '/usr/local/etc/lsb-factory',
1177 '/etc/lsb-release'))
Jon Salz8fa8e832012-07-13 19:04:09 +08001178 self.time_sanitizer.RunOnce()
1179
Jon Salz0697cbf2012-07-04 15:14:04 +08001180 self.init_states()
1181 self.start_event_server()
1182 self.connection_manager = self.env.create_connection_manager(
Tai-Hsu Lin371351a2012-08-27 14:17:14 +08001183 self.test_list.options.wlans,
1184 self.test_list.options.scan_wifi_period_secs)
Jon Salz0697cbf2012-07-04 15:14:04 +08001185 # Note that we create a log watcher even if
1186 # sync_event_log_period_secs isn't set (no background
1187 # syncing), since we may use it to flush event logs as well.
1188 self.log_watcher = EventLogWatcher(
1189 self.test_list.options.sync_event_log_period_secs,
Jon Salz16d10542012-07-23 12:18:45 +08001190 handle_event_logs_callback=self.handle_event_logs)
Jon Salz0697cbf2012-07-04 15:14:04 +08001191 if self.test_list.options.sync_event_log_period_secs:
1192 self.log_watcher.StartWatchThread()
1193
1194 self.update_system_info()
1195
Vic Yang4953fc12012-07-26 16:19:53 +08001196 assert ((self.test_list.options.min_charge_pct is None) ==
1197 (self.test_list.options.max_charge_pct is None))
Jon Salzad7353b2012-10-15 16:22:46 +08001198 if self.test_list.options.min_charge_pct is not None:
Vic Yang4953fc12012-07-26 16:19:53 +08001199 self.charge_manager = ChargeManager(self.test_list.options.min_charge_pct,
1200 self.test_list.options.max_charge_pct)
Jon Salzad7353b2012-10-15 16:22:46 +08001201 system.SystemStatus.charge_manager = self.charge_manager
Vic Yang4953fc12012-07-26 16:19:53 +08001202
Jon Salz0697cbf2012-07-04 15:14:04 +08001203 os.environ['CROS_FACTORY'] = '1'
1204 os.environ['CROS_DISABLE_SITE_SYSINFO'] = '1'
1205
1206 # Set CROS_UI since some behaviors in ui.py depend on the
1207 # particular UI in use. TODO(jsalz): Remove this (and all
1208 # places it is used) when the GTK UI is removed.
1209 os.environ['CROS_UI'] = self.options.ui
1210
1211 if self.options.ui == 'chrome':
1212 self.env.launch_chrome()
1213 logging.info('Waiting for a web socket connection')
Cheng-Yi Chiangfd8ed392013-03-08 21:37:31 +08001214 self.web_socket_manager.wait()
Jon Salz0697cbf2012-07-04 15:14:04 +08001215
1216 # Wait for the test widget size to be set; this is done in
1217 # an asynchronous RPC so there is a small chance that the
1218 # web socket might be opened first.
1219 for _ in range(100): # 10 s
1220 try:
1221 if self.state_instance.get_shared_data('test_widget_size'):
1222 break
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001223 except KeyError:
Jon Salz0697cbf2012-07-04 15:14:04 +08001224 pass # Retry
1225 time.sleep(0.1) # 100 ms
1226 else:
1227 logging.warn('Never received test_widget_size from UI')
1228 elif self.options.ui == 'gtk':
1229 self.start_ui()
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001230
Ricky Liang650f6bf2012-09-28 13:22:54 +08001231 # Create download path for autotest beforehand or autotests run at
1232 # the same time might fail due to race condition.
1233 if not factory.in_chroot():
1234 utils.TryMakeDirs(os.path.join('/usr/local/autotest', 'tests',
1235 'download'))
1236
Jon Salz0697cbf2012-07-04 15:14:04 +08001237 def state_change_callback(test, test_state):
1238 self.event_client.post_event(
1239 Event(Event.Type.STATE_CHANGE,
1240 path=test.path, state=test_state))
1241 self.test_list.state_change_callback = state_change_callback
Jon Salz73e0fd02012-04-04 11:46:38 +08001242
Jon Salza6711d72012-07-18 14:33:03 +08001243 for handler in self.on_ui_startup:
1244 handler()
1245
1246 self.prespawner = Prespawner()
1247 self.prespawner.start()
1248
Jon Salz0697cbf2012-07-04 15:14:04 +08001249 try:
1250 tests_after_shutdown = self.state_instance.get_shared_data(
1251 'tests_after_shutdown')
1252 except KeyError:
1253 tests_after_shutdown = None
Jon Salz57717ca2012-04-04 16:47:25 +08001254
Jon Salz5c344f62012-07-13 14:31:16 +08001255 force_auto_run = (tests_after_shutdown == FORCE_AUTO_RUN)
1256 if not force_auto_run and tests_after_shutdown is not None:
Jon Salz0697cbf2012-07-04 15:14:04 +08001257 logging.info('Resuming tests after shutdown: %s',
1258 tests_after_shutdown)
Jon Salz0697cbf2012-07-04 15:14:04 +08001259 self.tests_to_run.extend(
1260 self.test_list.lookup_path(t) for t in tests_after_shutdown)
1261 self.run_queue.put(self.run_next_test)
1262 else:
Jon Salz5c344f62012-07-13 14:31:16 +08001263 if force_auto_run or self.test_list.options.auto_run_on_start:
Jon Salz0697cbf2012-07-04 15:14:04 +08001264 self.run_queue.put(
1265 lambda: self.run_tests(self.test_list, untested_only=True))
Jon Salz5c344f62012-07-13 14:31:16 +08001266 self.state_instance.set_shared_data('tests_after_shutdown', None)
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001267
Dean Liao592e4d52013-01-10 20:06:39 +08001268 self.may_disable_cros_shortcut_keys()
1269
1270 def may_disable_cros_shortcut_keys(self):
1271 test_options = self.test_list.options
1272 if test_options.disable_cros_shortcut_keys:
1273 logging.info('Filter ChromeOS shortcut keys.')
1274 self.key_filter = KeyFilter(
1275 unmap_caps_lock=test_options.disable_caps_lock,
1276 caps_lock_keycode=test_options.caps_lock_keycode)
1277 self.key_filter.Start()
1278
Jon Salz0697cbf2012-07-04 15:14:04 +08001279 def run(self):
1280 '''Runs Goofy.'''
1281 # Process events forever.
1282 while self.run_once(True):
1283 pass
Jon Salz73e0fd02012-04-04 11:46:38 +08001284
Jon Salz0697cbf2012-07-04 15:14:04 +08001285 def run_once(self, block=False):
1286 '''Runs all items pending in the event loop.
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001287
Jon Salz0697cbf2012-07-04 15:14:04 +08001288 Args:
1289 block: If true, block until at least one event is processed.
Jon Salz7c15e8b2012-06-19 17:10:37 +08001290
Jon Salz0697cbf2012-07-04 15:14:04 +08001291 Returns:
1292 True to keep going or False to shut down.
1293 '''
1294 events = utils.DrainQueue(self.run_queue)
cychiang21886742012-07-05 15:16:32 +08001295 while not events:
Jon Salz0697cbf2012-07-04 15:14:04 +08001296 # Nothing on the run queue.
1297 self._run_queue_idle()
1298 if block:
1299 # Block for at least one event...
cychiang21886742012-07-05 15:16:32 +08001300 try:
1301 events.append(self.run_queue.get(timeout=RUN_QUEUE_TIMEOUT_SECS))
1302 except Queue.Empty:
1303 # Keep going (calling _run_queue_idle() again at the top of
1304 # the loop)
1305 continue
Jon Salz0697cbf2012-07-04 15:14:04 +08001306 # ...and grab anything else that showed up at the same
1307 # time.
1308 events.extend(utils.DrainQueue(self.run_queue))
cychiang21886742012-07-05 15:16:32 +08001309 else:
1310 break
Jon Salz51528e12012-07-02 18:54:45 +08001311
Jon Salz0697cbf2012-07-04 15:14:04 +08001312 for event in events:
1313 if not event:
1314 # Shutdown request.
1315 self.run_queue.task_done()
1316 return False
Jon Salz51528e12012-07-02 18:54:45 +08001317
Jon Salz0697cbf2012-07-04 15:14:04 +08001318 try:
1319 event()
Jon Salz85a39882012-07-05 16:45:04 +08001320 except: # pylint: disable=W0702
1321 logging.exception('Error in event loop')
Jon Salz0697cbf2012-07-04 15:14:04 +08001322 self.record_exception(traceback.format_exception_only(
1323 *sys.exc_info()[:2]))
1324 # But keep going
1325 finally:
1326 self.run_queue.task_done()
1327 return True
Jon Salz0405ab52012-03-16 15:26:52 +08001328
Jon Salz0e6532d2012-10-25 16:30:11 +08001329 def _should_sync_time(self, foreground=False):
1330 '''Returns True if we should attempt syncing time with shopfloor.
1331
1332 Args:
1333 foreground: If True, synchronizes even if background syncing
1334 is disabled (e.g., in explicit sync requests from the
1335 SyncShopfloor test).
1336 '''
1337 return ((foreground or
1338 self.test_list.options.sync_time_period_secs) and
Jon Salz54882d02012-08-31 01:57:54 +08001339 self.time_sanitizer and
1340 (not self.time_synced) and
1341 (not factory.in_chroot()))
1342
Jon Salz0e6532d2012-10-25 16:30:11 +08001343 def sync_time_with_shopfloor_server(self, foreground=False):
Jon Salz54882d02012-08-31 01:57:54 +08001344 '''Syncs time with shopfloor server, if not yet synced.
1345
Jon Salz0e6532d2012-10-25 16:30:11 +08001346 Args:
1347 foreground: If True, synchronizes even if background syncing
1348 is disabled (e.g., in explicit sync requests from the
1349 SyncShopfloor test).
1350
Jon Salz54882d02012-08-31 01:57:54 +08001351 Returns:
1352 False if no time sanitizer is available, or True if this sync (or a
1353 previous sync) succeeded.
1354
1355 Raises:
1356 Exception if unable to contact the shopfloor server.
1357 '''
Jon Salz0e6532d2012-10-25 16:30:11 +08001358 if self._should_sync_time(foreground):
Jon Salz54882d02012-08-31 01:57:54 +08001359 self.time_sanitizer.SyncWithShopfloor()
1360 self.time_synced = True
1361 return self.time_synced
1362
Jon Salzb92c5112012-09-21 15:40:11 +08001363 def log_disk_space_stats(self):
1364 if not self.test_list.options.log_disk_space_period_secs:
1365 return
1366
1367 now = time.time()
1368 if (self.last_log_disk_space_time and
1369 now - self.last_log_disk_space_time <
1370 self.test_list.options.log_disk_space_period_secs):
1371 return
1372 self.last_log_disk_space_time = now
1373
1374 try:
Jon Salz3c493bb2013-02-07 17:24:58 +08001375 message = disk_space.FormatSpaceUsedAll()
1376 if message != self.last_log_disk_space_message:
1377 logging.info(message)
1378 self.last_log_disk_space_message = message
Jon Salzb92c5112012-09-21 15:40:11 +08001379 except: # pylint: disable=W0702
1380 logging.exception('Unable to get disk space used')
1381
Jon Salz8fa8e832012-07-13 19:04:09 +08001382 def sync_time_in_background(self):
Jon Salzb22d1172012-08-06 10:38:57 +08001383 '''Writes out current time and tries to sync with shopfloor server.'''
1384 if not self.time_sanitizer:
1385 return
1386
1387 # Write out the current time.
1388 self.time_sanitizer.SaveTime()
1389
Jon Salz54882d02012-08-31 01:57:54 +08001390 if not self._should_sync_time():
Jon Salz8fa8e832012-07-13 19:04:09 +08001391 return
1392
1393 now = time.time()
1394 if self.last_sync_time and (
1395 now - self.last_sync_time <
1396 self.test_list.options.sync_time_period_secs):
1397 # Not yet time for another check.
1398 return
1399 self.last_sync_time = now
1400
1401 def target():
1402 try:
Jon Salz54882d02012-08-31 01:57:54 +08001403 self.sync_time_with_shopfloor_server()
Jon Salz8fa8e832012-07-13 19:04:09 +08001404 except: # pylint: disable=W0702
1405 # Oh well. Log an error (but no trace)
1406 logging.info(
1407 'Unable to get time from shopfloor server: %s',
1408 utils.FormatExceptionOnly())
1409
1410 thread = threading.Thread(target=target)
1411 thread.daemon = True
1412 thread.start()
1413
Jon Salz0697cbf2012-07-04 15:14:04 +08001414 def _run_queue_idle(self):
Vic Yang4953fc12012-07-26 16:19:53 +08001415 '''Invoked when the run queue has no events.
1416
1417 This method must not raise exception.
1418 '''
Jon Salzb22d1172012-08-06 10:38:57 +08001419 now = time.time()
1420 if (self.last_idle and
1421 now < (self.last_idle + RUN_QUEUE_TIMEOUT_SECS - 1)):
1422 # Don't run more often than once every (RUN_QUEUE_TIMEOUT_SECS -
1423 # 1) seconds.
1424 return
1425
1426 self.last_idle = now
1427
Vic Yang311ddb82012-09-26 12:08:28 +08001428 self.check_exclusive()
cychiang21886742012-07-05 15:16:32 +08001429 self.check_for_updates()
Jon Salz8fa8e832012-07-13 19:04:09 +08001430 self.sync_time_in_background()
Jon Salzb92c5112012-09-21 15:40:11 +08001431 self.log_disk_space_stats()
Jon Salz57717ca2012-04-04 16:47:25 +08001432
Jon Salz16d10542012-07-23 12:18:45 +08001433 def handle_event_logs(self, log_name, chunk):
Jon Salz0697cbf2012-07-04 15:14:04 +08001434 '''Callback for event watcher.
Jon Salz258a40c2012-04-19 12:34:01 +08001435
Jon Salz0697cbf2012-07-04 15:14:04 +08001436 Attempts to upload the event logs to the shopfloor server.
1437 '''
1438 description = 'event logs (%s, %d bytes)' % (log_name, len(chunk))
1439 start_time = time.time()
Jon Salz0697cbf2012-07-04 15:14:04 +08001440 shopfloor_client = shopfloor.get_instance(
1441 detect=True,
1442 timeout=self.test_list.options.shopfloor_timeout_secs)
Jon Salzb10cf512012-08-09 17:29:21 +08001443 shopfloor_client.UploadEvent(log_name, Binary(chunk))
Jon Salz0697cbf2012-07-04 15:14:04 +08001444 logging.info(
1445 'Successfully synced %s in %.03f s',
1446 description, time.time() - start_time)
Jon Salz57717ca2012-04-04 16:47:25 +08001447
Jon Salz0697cbf2012-07-04 15:14:04 +08001448 def run_tests_with_status(self, statuses_to_run, starting_at=None,
1449 root=None):
1450 '''Runs all top-level tests with a particular status.
Jon Salz0405ab52012-03-16 15:26:52 +08001451
Jon Salz0697cbf2012-07-04 15:14:04 +08001452 All active tests, plus any tests to re-run, are reset.
Jon Salz57717ca2012-04-04 16:47:25 +08001453
Jon Salz0697cbf2012-07-04 15:14:04 +08001454 Args:
1455 starting_at: If provided, only auto-runs tests beginning with
1456 this test.
1457 '''
1458 root = root or self.test_list
Jon Salz57717ca2012-04-04 16:47:25 +08001459
Jon Salz0697cbf2012-07-04 15:14:04 +08001460 if starting_at:
1461 # Make sure they passed a test, not a string.
1462 assert isinstance(starting_at, factory.FactoryTest)
Jon Salz0405ab52012-03-16 15:26:52 +08001463
Jon Salz0697cbf2012-07-04 15:14:04 +08001464 tests_to_reset = []
1465 tests_to_run = []
Jon Salz0405ab52012-03-16 15:26:52 +08001466
Jon Salz0697cbf2012-07-04 15:14:04 +08001467 found_starting_at = False
Jon Salz0405ab52012-03-16 15:26:52 +08001468
Jon Salz0697cbf2012-07-04 15:14:04 +08001469 for test in root.get_top_level_tests():
1470 if starting_at:
1471 if test == starting_at:
1472 # We've found starting_at; do auto-run on all
1473 # subsequent tests.
1474 found_starting_at = True
1475 if not found_starting_at:
1476 # Don't start this guy yet
1477 continue
Jon Salz0405ab52012-03-16 15:26:52 +08001478
Jon Salz0697cbf2012-07-04 15:14:04 +08001479 status = test.get_state().status
1480 if status == TestState.ACTIVE or status in statuses_to_run:
1481 # Reset the test (later; we will need to abort
1482 # all active tests first).
1483 tests_to_reset.append(test)
1484 if status in statuses_to_run:
1485 tests_to_run.append(test)
Jon Salz0405ab52012-03-16 15:26:52 +08001486
Jon Salz0697cbf2012-07-04 15:14:04 +08001487 self.abort_active_tests()
Jon Salz258a40c2012-04-19 12:34:01 +08001488
Jon Salz0697cbf2012-07-04 15:14:04 +08001489 # Reset all statuses of the tests to run (in case any tests were active;
1490 # we want them to be run again).
1491 for test_to_reset in tests_to_reset:
1492 for test in test_to_reset.walk():
1493 test.update_state(status=TestState.UNTESTED)
Jon Salz57717ca2012-04-04 16:47:25 +08001494
Jon Salz0697cbf2012-07-04 15:14:04 +08001495 self.run_tests(tests_to_run, untested_only=True)
Jon Salz0405ab52012-03-16 15:26:52 +08001496
Jon Salz0697cbf2012-07-04 15:14:04 +08001497 def restart_tests(self, root=None):
1498 '''Restarts all tests.'''
1499 root = root or self.test_list
Jon Salz0405ab52012-03-16 15:26:52 +08001500
Jon Salz0697cbf2012-07-04 15:14:04 +08001501 self.abort_active_tests()
1502 for test in root.walk():
1503 test.update_state(status=TestState.UNTESTED)
1504 self.run_tests(root)
Hung-Te Lin96632362012-03-20 21:14:18 +08001505
Jon Salz0697cbf2012-07-04 15:14:04 +08001506 def auto_run(self, starting_at=None, root=None):
1507 '''"Auto-runs" tests that have not been run yet.
Hung-Te Lin96632362012-03-20 21:14:18 +08001508
Jon Salz0697cbf2012-07-04 15:14:04 +08001509 Args:
1510 starting_at: If provide, only auto-runs tests beginning with
1511 this test.
1512 '''
1513 root = root or self.test_list
1514 self.run_tests_with_status([TestState.UNTESTED, TestState.ACTIVE],
1515 starting_at=starting_at,
1516 root=root)
Jon Salz968e90b2012-03-18 16:12:43 +08001517
Jon Salz0697cbf2012-07-04 15:14:04 +08001518 def re_run_failed(self, root=None):
1519 '''Re-runs failed tests.'''
1520 root = root or self.test_list
1521 self.run_tests_with_status([TestState.FAILED], root=root)
Jon Salz57717ca2012-04-04 16:47:25 +08001522
Jon Salz0697cbf2012-07-04 15:14:04 +08001523 def show_review_information(self):
1524 '''Event handler for showing review information screen.
Jon Salz57717ca2012-04-04 16:47:25 +08001525
Jon Salz0697cbf2012-07-04 15:14:04 +08001526 The information screene is rendered by main UI program (ui.py), so in
1527 goofy we only need to kill all active tests, set them as untested, and
1528 clear remaining tests.
1529 '''
1530 self.kill_active_tests(False)
Jon Salza6711d72012-07-18 14:33:03 +08001531 self.cancel_pending_tests()
Jon Salz57717ca2012-04-04 16:47:25 +08001532
Jon Salz0697cbf2012-07-04 15:14:04 +08001533 def handle_switch_test(self, event):
1534 '''Switches to a particular test.
Jon Salz0405ab52012-03-16 15:26:52 +08001535
Jon Salz0697cbf2012-07-04 15:14:04 +08001536 @param event: The SWITCH_TEST event.
1537 '''
1538 test = self.test_list.lookup_path(event.path)
1539 if not test:
1540 logging.error('Unknown test %r', event.key)
1541 return
Jon Salz73e0fd02012-04-04 11:46:38 +08001542
Jon Salz0697cbf2012-07-04 15:14:04 +08001543 invoc = self.invocations.get(test)
1544 if invoc and test.backgroundable:
1545 # Already running: just bring to the front if it
1546 # has a UI.
1547 logging.info('Setting visible test to %s', test.path)
Jon Salz36fbbb52012-07-05 13:45:06 +08001548 self.set_visible_test(test)
Jon Salz0697cbf2012-07-04 15:14:04 +08001549 return
Jon Salz73e0fd02012-04-04 11:46:38 +08001550
Jon Salz0697cbf2012-07-04 15:14:04 +08001551 self.abort_active_tests()
1552 for t in test.walk():
1553 t.update_state(status=TestState.UNTESTED)
Jon Salz73e0fd02012-04-04 11:46:38 +08001554
Jon Salz0697cbf2012-07-04 15:14:04 +08001555 if self.test_list.options.auto_run_on_keypress:
1556 self.auto_run(starting_at=test)
1557 else:
1558 self.run_tests(test)
Jon Salz73e0fd02012-04-04 11:46:38 +08001559
Jon Salz0697cbf2012-07-04 15:14:04 +08001560 def wait(self):
1561 '''Waits for all pending invocations.
1562
1563 Useful for testing.
1564 '''
Jon Salz1acc8742012-07-17 17:45:55 +08001565 while self.invocations:
1566 for k, v in self.invocations.iteritems():
1567 logging.info('Waiting for %s to complete...', k)
1568 v.thread.join()
1569 self.reap_completed_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +08001570
1571 def check_exceptions(self):
1572 '''Raises an error if any exceptions have occurred in
1573 invocation threads.'''
1574 if self.exceptions:
1575 raise RuntimeError('Exception in invocation thread: %r' %
1576 self.exceptions)
1577
1578 def record_exception(self, msg):
1579 '''Records an exception in an invocation thread.
1580
1581 An exception with the given message will be rethrown when
1582 Goofy is destroyed.'''
1583 self.exceptions.append(msg)
Jon Salz73e0fd02012-04-04 11:46:38 +08001584
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001585
1586if __name__ == '__main__':
Jon Salz77c151e2012-08-28 07:20:37 +08001587 goofy = Goofy()
1588 try:
1589 goofy.main()
Jon Salz0f996602012-10-03 15:26:48 +08001590 except SystemExit:
1591 # Propagate SystemExit without logging.
1592 raise
Jon Salz31373eb2012-09-21 16:19:49 +08001593 except:
Jon Salz0f996602012-10-03 15:26:48 +08001594 # Log the error before trying to shut down (unless it's a graceful
1595 # exit).
Jon Salz31373eb2012-09-21 16:19:49 +08001596 logging.exception('Error in main loop')
1597 raise
Jon Salz77c151e2012-08-28 07:20:37 +08001598 finally:
1599 goofy.destroy()