blob: 76b44bb2591cf52299078710422da649ced1706d [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
Vic Yangaabf9fd2013-04-09 18:56:13 +0800654 def check_critical_factory_note(self):
655 '''
656 Returns True if the last factory note is critical.
657 '''
658 notes = self.state_instance.get_shared_data('factory_note', True)
659 return notes and notes[-1]['level'] == 'CRITICAL'
660
Jon Salz0697cbf2012-07-04 15:14:04 +0800661 def run_next_test(self):
662 '''
663 Runs the next eligible test (or tests) in self.tests_to_run.
664 '''
665 self.reap_completed_tests()
Vic Yangaabf9fd2013-04-09 18:56:13 +0800666 if self.tests_to_run and self.check_critical_factory_note():
667 self.tests_to_run.clear()
668 return
Jon Salz0697cbf2012-07-04 15:14:04 +0800669 while self.tests_to_run:
670 logging.debug('Tests to run: %s',
671 [x.path for x in self.tests_to_run])
Jon Salz94eb56f2012-06-12 18:01:12 +0800672
Jon Salz0697cbf2012-07-04 15:14:04 +0800673 test = self.tests_to_run[0]
Jon Salz94eb56f2012-06-12 18:01:12 +0800674
Jon Salz0697cbf2012-07-04 15:14:04 +0800675 if test in self.invocations:
676 logging.info('Next test %s is already running', test.path)
677 self.tests_to_run.popleft()
678 return
Jon Salz94eb56f2012-06-12 18:01:12 +0800679
Jon Salza1412922012-07-23 16:04:17 +0800680 for requirement in test.require_run:
681 for i in requirement.test.walk():
682 if i.get_state().status == TestState.ACTIVE:
Jon Salz304a75d2012-07-06 11:14:15 +0800683 logging.info('Waiting for active test %s to complete '
Jon Salza1412922012-07-23 16:04:17 +0800684 'before running %s', i.path, test.path)
Jon Salz304a75d2012-07-06 11:14:15 +0800685 return
686
Jon Salz0697cbf2012-07-04 15:14:04 +0800687 if self.invocations and not (test.backgroundable and all(
688 [x.backgroundable for x in self.invocations])):
689 logging.debug('Waiting for non-backgroundable tests to '
690 'complete before running %s', test.path)
691 return
Jon Salz94eb56f2012-06-12 18:01:12 +0800692
Jon Salz3e6f5202012-10-15 15:08:29 +0800693 if test.get_state().skip:
694 factory.console.info('Skipping test %s', test.path)
695 test.update_state(status=TestState.PASSED,
696 error_msg=TestState.SKIPPED_MSG)
697 self.tests_to_run.popleft()
698 continue
699
Jon Salz0697cbf2012-07-04 15:14:04 +0800700 self.tests_to_run.popleft()
Jon Salz94eb56f2012-06-12 18:01:12 +0800701
Jon Salz304a75d2012-07-06 11:14:15 +0800702 untested = set()
Jon Salza1412922012-07-23 16:04:17 +0800703 for requirement in test.require_run:
704 for i in requirement.test.walk():
705 if i == test:
Jon Salz304a75d2012-07-06 11:14:15 +0800706 # We've hit this test itself; stop checking
707 break
Jon Salza1412922012-07-23 16:04:17 +0800708 if ((i.get_state().status == TestState.UNTESTED) or
709 (requirement.passed and i.get_state().status !=
710 TestState.PASSED)):
Jon Salz304a75d2012-07-06 11:14:15 +0800711 # Found an untested test; move on to the next
712 # element in require_run.
Jon Salza1412922012-07-23 16:04:17 +0800713 untested.add(i)
Jon Salz304a75d2012-07-06 11:14:15 +0800714 break
715
716 if untested:
717 untested_paths = ', '.join(sorted([x.path for x in untested]))
718 if self.state_instance.get_shared_data('engineering_mode',
719 optional=True):
720 # In engineering mode, we'll let it go.
721 factory.console.warn('In engineering mode; running '
722 '%s even though required tests '
723 '[%s] have not completed',
724 test.path, untested_paths)
725 else:
726 # Not in engineering mode; mark it failed.
727 error_msg = ('Required tests [%s] have not been run yet'
728 % untested_paths)
729 factory.console.error('Not running %s: %s',
730 test.path, error_msg)
731 test.update_state(status=TestState.FAILED,
732 error_msg=error_msg)
733 continue
734
Jon Salz0697cbf2012-07-04 15:14:04 +0800735 if isinstance(test, factory.ShutdownStep):
736 if os.path.exists(NO_REBOOT_FILE):
737 test.update_state(
738 status=TestState.FAILED, increment_count=1,
739 error_msg=('Skipped shutdown since %s is present' %
Jon Salz304a75d2012-07-06 11:14:15 +0800740 NO_REBOOT_FILE))
Jon Salz0697cbf2012-07-04 15:14:04 +0800741 continue
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800742
Jon Salz0697cbf2012-07-04 15:14:04 +0800743 test.update_state(status=TestState.ACTIVE, increment_count=1,
744 error_msg='', shutdown_count=0)
745 if self._prompt_cancel_shutdown(test, 1):
746 self.event_log.Log('reboot_cancelled')
747 test.update_state(
748 status=TestState.FAILED, increment_count=1,
749 error_msg='Shutdown aborted by operator',
750 shutdown_count=0)
chungyiafe8f772012-08-15 19:36:29 +0800751 continue
Jon Salz2f757d42012-06-27 17:06:42 +0800752
Jon Salz0697cbf2012-07-04 15:14:04 +0800753 # Save pending test list in the state server
Jon Salzdbf398f2012-06-14 17:30:01 +0800754 self.state_instance.set_shared_data(
Jon Salz0697cbf2012-07-04 15:14:04 +0800755 'tests_after_shutdown',
756 [t.path for t in self.tests_to_run])
757 # Save shutdown time
758 self.state_instance.set_shared_data('shutdown_time',
759 time.time())
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800760
Jon Salz0697cbf2012-07-04 15:14:04 +0800761 with self.env.lock:
762 self.event_log.Log('shutdown', operation=test.operation)
763 shutdown_result = self.env.shutdown(test.operation)
764 if shutdown_result:
765 # That's all, folks!
766 self.run_queue.put(None)
767 return
768 else:
769 # Just pass (e.g., in the chroot).
770 test.update_state(status=TestState.PASSED)
771 self.state_instance.set_shared_data(
772 'tests_after_shutdown', None)
773 # Send event with no fields to indicate that there is no
774 # longer a pending shutdown.
775 self.event_client.post_event(Event(
776 Event.Type.PENDING_SHUTDOWN))
777 continue
Jon Salz258a40c2012-04-19 12:34:01 +0800778
Cheng-Yi Chiangce05c002013-04-04 02:13:17 +0800779 self._run_test(test, test.iterations, test.retries)
Jon Salz1acc8742012-07-17 17:45:55 +0800780
Cheng-Yi Chiangce05c002013-04-04 02:13:17 +0800781 def _run_test(self, test, iterations_left=None, retries_left=None):
Jon Salz1acc8742012-07-17 17:45:55 +0800782 invoc = TestInvocation(self, test, on_completion=self.run_next_test)
783 new_state = test.update_state(
784 status=TestState.ACTIVE, increment_count=1, error_msg='',
Jon Salzbd42ce12012-09-18 08:03:59 +0800785 invocation=invoc.uuid, iterations_left=iterations_left,
Cheng-Yi Chiangce05c002013-04-04 02:13:17 +0800786 retries_left=retries_left,
Jon Salzbd42ce12012-09-18 08:03:59 +0800787 visible=(self.visible_test == test))
Jon Salz1acc8742012-07-17 17:45:55 +0800788 invoc.count = new_state.count
789
790 self.invocations[test] = invoc
791 if self.visible_test is None and test.has_ui:
792 self.set_visible_test(test)
Vic Yang311ddb82012-09-26 12:08:28 +0800793 self.check_exclusive()
Jon Salz1acc8742012-07-17 17:45:55 +0800794 invoc.start()
Jon Salz5f2a0672012-05-22 17:14:06 +0800795
Vic Yang311ddb82012-09-26 12:08:28 +0800796 def check_exclusive(self):
797 current_exclusive_items = set([
798 item
799 for item in factory.FactoryTest.EXCLUSIVE_OPTIONS
800 if any([test.is_exclusive(item) for test in self.invocations])])
801
802 new_exclusive_items = current_exclusive_items - self.exclusive_items
803 if factory.FactoryTest.EXCLUSIVE_OPTIONS.NETWORKING in new_exclusive_items:
804 logging.info('Disabling network')
805 self.connection_manager.DisableNetworking()
806 if factory.FactoryTest.EXCLUSIVE_OPTIONS.CHARGER in new_exclusive_items:
807 logging.info('Stop controlling charger')
808
809 new_non_exclusive_items = self.exclusive_items - current_exclusive_items
810 if (factory.FactoryTest.EXCLUSIVE_OPTIONS.NETWORKING in
811 new_non_exclusive_items):
812 logging.info('Re-enabling network')
813 self.connection_manager.EnableNetworking()
814 if factory.FactoryTest.EXCLUSIVE_OPTIONS.CHARGER in new_non_exclusive_items:
815 logging.info('Start controlling charger')
816
817 # Only adjust charge state if not excluded
818 if (self.charge_manager and
819 not factory.FactoryTest.EXCLUSIVE_OPTIONS.CHARGER in
820 current_exclusive_items):
821 self.charge_manager.AdjustChargeState()
822
823 self.exclusive_items = current_exclusive_items
Jon Salz5da61e62012-05-31 13:06:22 +0800824
cychiang21886742012-07-05 15:16:32 +0800825 def check_for_updates(self):
826 '''
827 Schedules an asynchronous check for updates if necessary.
828 '''
829 if not self.test_list.options.update_period_secs:
830 # Not enabled.
831 return
832
833 now = time.time()
834 if self.last_update_check and (
835 now - self.last_update_check <
836 self.test_list.options.update_period_secs):
837 # Not yet time for another check.
838 return
839
840 self.last_update_check = now
841
842 def handle_check_for_update(reached_shopfloor, md5sum, needs_update):
843 if reached_shopfloor:
844 new_update_md5sum = md5sum if needs_update else None
845 if system.SystemInfo.update_md5sum != new_update_md5sum:
846 logging.info('Received new update MD5SUM: %s', new_update_md5sum)
847 system.SystemInfo.update_md5sum = new_update_md5sum
848 self.run_queue.put(self.update_system_info)
849
850 updater.CheckForUpdateAsync(
851 handle_check_for_update,
852 self.test_list.options.shopfloor_timeout_secs)
853
Jon Salza6711d72012-07-18 14:33:03 +0800854 def cancel_pending_tests(self):
855 '''Cancels any tests in the run queue.'''
856 self.run_tests([])
857
Jon Salz0697cbf2012-07-04 15:14:04 +0800858 def run_tests(self, subtrees, untested_only=False):
859 '''
860 Runs tests under subtree.
Jon Salz258a40c2012-04-19 12:34:01 +0800861
Jon Salz0697cbf2012-07-04 15:14:04 +0800862 The tests are run in order unless one fails (then stops).
863 Backgroundable tests are run simultaneously; when a foreground test is
864 encountered, we wait for all active tests to finish before continuing.
Jon Salzb1b39092012-05-03 02:05:09 +0800865
Jon Salz0697cbf2012-07-04 15:14:04 +0800866 @param subtrees: Node or nodes containing tests to run (may either be
867 a single test or a list). Duplicates will be ignored.
868 '''
869 if type(subtrees) != list:
870 subtrees = [subtrees]
Jon Salz258a40c2012-04-19 12:34:01 +0800871
Jon Salz0697cbf2012-07-04 15:14:04 +0800872 # Nodes we've seen so far, to avoid duplicates.
873 seen = set()
Jon Salz94eb56f2012-06-12 18:01:12 +0800874
Jon Salz0697cbf2012-07-04 15:14:04 +0800875 self.tests_to_run = deque()
876 for subtree in subtrees:
877 for test in subtree.walk():
878 if test in seen:
879 continue
880 seen.add(test)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800881
Jon Salz0697cbf2012-07-04 15:14:04 +0800882 if not test.is_leaf():
883 continue
884 if (untested_only and
885 test.get_state().status != TestState.UNTESTED):
886 continue
887 self.tests_to_run.append(test)
888 self.run_next_test()
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800889
Jon Salz0697cbf2012-07-04 15:14:04 +0800890 def reap_completed_tests(self):
891 '''
892 Removes completed tests from the set of active tests.
893
894 Also updates the visible test if it was reaped.
895 '''
896 for t, v in dict(self.invocations).iteritems():
897 if v.is_completed():
Jon Salz1acc8742012-07-17 17:45:55 +0800898 new_state = t.update_state(**v.update_state_on_completion)
Jon Salz0697cbf2012-07-04 15:14:04 +0800899 del self.invocations[t]
900
Chun-Ta Lin54e17e42012-09-06 22:05:13 +0800901 # Stop on failure if flag is true.
902 if (self.test_list.options.stop_on_failure and
903 new_state.status == TestState.FAILED):
904 # Clean all the tests to cause goofy to stop.
905 self.tests_to_run = []
906 factory.console.info("Stop on failure triggered. Empty the queue.")
907
Jon Salz1acc8742012-07-17 17:45:55 +0800908 if new_state.iterations_left and new_state.status == TestState.PASSED:
909 # Play it again, Sam!
910 self._run_test(t)
Cheng-Yi Chiangce05c002013-04-04 02:13:17 +0800911 # new_state.retries_left is obtained after update.
912 # For retries_left == 0, test can still be run for the last time.
913 elif (new_state.retries_left >= 0 and
914 new_state.status == TestState.FAILED):
915 # Still have to retry, Sam!
916 self._run_test(t)
Jon Salz1acc8742012-07-17 17:45:55 +0800917
Jon Salz0697cbf2012-07-04 15:14:04 +0800918 if (self.visible_test is None or
Jon Salz85a39882012-07-05 16:45:04 +0800919 self.visible_test not in self.invocations):
Jon Salz0697cbf2012-07-04 15:14:04 +0800920 self.set_visible_test(None)
921 # Make the first running test, if any, the visible test
922 for t in self.test_list.walk():
923 if t in self.invocations:
924 self.set_visible_test(t)
925 break
926
Jon Salz85a39882012-07-05 16:45:04 +0800927 def kill_active_tests(self, abort, root=None):
Jon Salz0697cbf2012-07-04 15:14:04 +0800928 '''
929 Kills and waits for all active tests.
930
Jon Salz85a39882012-07-05 16:45:04 +0800931 Args:
932 abort: True to change state of killed tests to FAILED, False for
Jon Salz0697cbf2012-07-04 15:14:04 +0800933 UNTESTED.
Jon Salz85a39882012-07-05 16:45:04 +0800934 root: If set, only kills tests with root as an ancestor.
Jon Salz0697cbf2012-07-04 15:14:04 +0800935 '''
936 self.reap_completed_tests()
937 for test, invoc in self.invocations.items():
Jon Salz85a39882012-07-05 16:45:04 +0800938 if root and not test.has_ancestor(root):
939 continue
940
Jon Salz0697cbf2012-07-04 15:14:04 +0800941 factory.console.info('Killing active test %s...' % test.path)
942 invoc.abort_and_join()
943 factory.console.info('Killed %s' % test.path)
Jon Salz1acc8742012-07-17 17:45:55 +0800944 test.update_state(**invoc.update_state_on_completion)
Jon Salz0697cbf2012-07-04 15:14:04 +0800945 del self.invocations[test]
Jon Salz1acc8742012-07-17 17:45:55 +0800946
Jon Salz0697cbf2012-07-04 15:14:04 +0800947 if not abort:
948 test.update_state(status=TestState.UNTESTED)
949 self.reap_completed_tests()
950
Jon Salz85a39882012-07-05 16:45:04 +0800951 def stop(self, root=None, fail=False):
952 self.kill_active_tests(fail, root)
953 # Remove any tests in the run queue under the root.
954 self.tests_to_run = deque([x for x in self.tests_to_run
955 if root and not x.has_ancestor(root)])
956 self.run_next_test()
Jon Salz0697cbf2012-07-04 15:14:04 +0800957
Jon Salz4712ac72013-02-07 17:12:05 +0800958 def clear_state(self, root=None):
959 self.stop(root)
960 for f in root.walk():
961 if f.is_leaf():
962 f.update_state(status=TestState.UNTESTED)
963
Jon Salz0697cbf2012-07-04 15:14:04 +0800964 def abort_active_tests(self):
965 self.kill_active_tests(True)
966
967 def main(self):
968 try:
969 self.init()
970 self.event_log.Log('goofy_init',
971 success=True)
972 except:
973 if self.event_log:
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800974 try:
Jon Salz0697cbf2012-07-04 15:14:04 +0800975 self.event_log.Log('goofy_init',
976 success=False,
977 trace=traceback.format_exc())
978 except: # pylint: disable=W0702
979 pass
980 raise
981
982 self.run()
983
984 def update_system_info(self):
985 '''Updates system info.'''
986 system_info = system.SystemInfo()
987 self.state_instance.set_shared_data('system_info', system_info.__dict__)
988 self.event_client.post_event(Event(Event.Type.SYSTEM_INFO,
989 system_info=system_info.__dict__))
990 logging.info('System info: %r', system_info.__dict__)
991
Jon Salzeb42f0d2012-07-27 19:14:04 +0800992 def update_factory(self, auto_run_on_restart=False, post_update_hook=None):
993 '''Commences updating factory software.
994
995 Args:
996 auto_run_on_restart: Auto-run when the machine comes back up.
997 post_update_hook: Code to call after update but immediately before
998 restart.
999
1000 Returns:
1001 Never if the update was successful (we just reboot).
1002 False if the update was unnecessary (no update available).
1003 '''
Jon Salz0697cbf2012-07-04 15:14:04 +08001004 self.kill_active_tests(False)
Jon Salza6711d72012-07-18 14:33:03 +08001005 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +08001006
Jon Salz5c344f62012-07-13 14:31:16 +08001007 def pre_update_hook():
1008 if auto_run_on_restart:
1009 self.state_instance.set_shared_data('tests_after_shutdown',
1010 FORCE_AUTO_RUN)
1011 self.state_instance.close()
1012
Jon Salzeb42f0d2012-07-27 19:14:04 +08001013 if updater.TryUpdate(pre_update_hook=pre_update_hook):
1014 if post_update_hook:
1015 post_update_hook()
1016 self.env.shutdown('reboot')
Jon Salz0697cbf2012-07-04 15:14:04 +08001017
Jon Salzcef132a2012-08-30 04:58:08 +08001018 def handle_sigint(self, dummy_signum, dummy_frame):
Jon Salz77c151e2012-08-28 07:20:37 +08001019 logging.error('Received SIGINT')
1020 self.run_queue.put(None)
1021 raise KeyboardInterrupt()
1022
Jon Salz0697cbf2012-07-04 15:14:04 +08001023 def init(self, args=None, env=None):
1024 '''Initializes Goofy.
1025
1026 Args:
1027 args: A list of command-line arguments. Uses sys.argv if
1028 args is None.
1029 env: An Environment instance to use (or None to choose
1030 FakeChrootEnvironment or DUTEnvironment as appropriate).
1031 '''
Jon Salz77c151e2012-08-28 07:20:37 +08001032 signal.signal(signal.SIGINT, self.handle_sigint)
1033
Jon Salz0697cbf2012-07-04 15:14:04 +08001034 parser = OptionParser()
1035 parser.add_option('-v', '--verbose', dest='verbose',
Jon Salz8fa8e832012-07-13 19:04:09 +08001036 action='store_true',
1037 help='Enable debug logging')
Jon Salz0697cbf2012-07-04 15:14:04 +08001038 parser.add_option('--print_test_list', dest='print_test_list',
Jon Salz8fa8e832012-07-13 19:04:09 +08001039 metavar='FILE',
1040 help='Read and print test list FILE, and exit')
Jon Salz0697cbf2012-07-04 15:14:04 +08001041 parser.add_option('--restart', dest='restart',
Jon Salz8fa8e832012-07-13 19:04:09 +08001042 action='store_true',
1043 help='Clear all test state')
Jon Salz0697cbf2012-07-04 15:14:04 +08001044 parser.add_option('--ui', dest='ui', type='choice',
Jon Salz8fa8e832012-07-13 19:04:09 +08001045 choices=['none', 'gtk', 'chrome'],
Jon Salz2f881df2013-02-01 17:00:35 +08001046 default='chrome',
Jon Salz8fa8e832012-07-13 19:04:09 +08001047 help='UI to use')
Jon Salz0697cbf2012-07-04 15:14:04 +08001048 parser.add_option('--ui_scale_factor', dest='ui_scale_factor',
Jon Salz8fa8e832012-07-13 19:04:09 +08001049 type='int', default=1,
1050 help=('Factor by which to scale UI '
1051 '(Chrome UI only)'))
Jon Salz0697cbf2012-07-04 15:14:04 +08001052 parser.add_option('--test_list', dest='test_list',
Jon Salz8fa8e832012-07-13 19:04:09 +08001053 metavar='FILE',
1054 help='Use FILE as test list')
Jon Salzc79a9982012-08-30 04:42:01 +08001055 parser.add_option('--dummy_shopfloor', action='store_true',
1056 help='Use a dummy shopfloor server')
chungyiafe8f772012-08-15 19:36:29 +08001057 parser.add_option('--automation', dest='automation',
1058 action='store_true',
1059 help='Enable automation on running factory test')
Ricky Liang09216dc2013-02-22 17:26:45 +08001060 parser.add_option('--one_pixel_less', dest='one_pixel_less',
1061 action='store_true',
1062 help=('Start Chrome one pixel less than the full screen.'
1063 'Needed by Exynos platform to run GTK.'))
Jon Salz0697cbf2012-07-04 15:14:04 +08001064 (self.options, self.args) = parser.parse_args(args)
1065
Jon Salz46b89562012-07-05 11:49:22 +08001066 # Make sure factory directories exist.
1067 factory.get_log_root()
1068 factory.get_state_root()
1069 factory.get_test_data_root()
1070
Jon Salz0697cbf2012-07-04 15:14:04 +08001071 global _inited_logging # pylint: disable=W0603
1072 if not _inited_logging:
1073 factory.init_logging('goofy', verbose=self.options.verbose)
1074 _inited_logging = True
Jon Salz8fa8e832012-07-13 19:04:09 +08001075
Jon Salz0f996602012-10-03 15:26:48 +08001076 if self.options.print_test_list:
1077 print factory.read_test_list(
1078 self.options.print_test_list).__repr__(recursive=True)
1079 sys.exit(0)
1080
Jon Salzee85d522012-07-17 14:34:46 +08001081 event_log.IncrementBootSequence()
Jon Salz0697cbf2012-07-04 15:14:04 +08001082 self.event_log = EventLog('goofy')
1083
1084 if (not suppress_chroot_warning and
1085 factory.in_chroot() and
1086 self.options.ui == 'gtk' and
1087 os.environ.get('DISPLAY') in [None, '', ':0', ':0.0']):
1088 # That's not going to work! Tell the user how to run
1089 # this way.
1090 logging.warn(GOOFY_IN_CHROOT_WARNING)
1091 time.sleep(1)
1092
1093 if env:
1094 self.env = env
1095 elif factory.in_chroot():
1096 self.env = test_environment.FakeChrootEnvironment()
1097 logging.warn(
1098 'Using chroot environment: will not actually run autotests')
1099 else:
1100 self.env = test_environment.DUTEnvironment()
1101 self.env.goofy = self
1102
1103 if self.options.restart:
1104 state.clear_state()
1105
Jon Salz0697cbf2012-07-04 15:14:04 +08001106 if self.options.ui_scale_factor != 1 and utils.in_qemu():
1107 logging.warn(
1108 'In QEMU; ignoring ui_scale_factor argument')
1109 self.options.ui_scale_factor = 1
1110
1111 logging.info('Started')
1112
1113 self.start_state_server()
1114 self.state_instance.set_shared_data('hwid_cfg', get_hwid_cfg())
1115 self.state_instance.set_shared_data('ui_scale_factor',
Ricky Liang09216dc2013-02-22 17:26:45 +08001116 self.options.ui_scale_factor)
1117 self.state_instance.set_shared_data('one_pixel_less',
1118 self.options.one_pixel_less)
Jon Salz0697cbf2012-07-04 15:14:04 +08001119 self.last_shutdown_time = (
1120 self.state_instance.get_shared_data('shutdown_time', optional=True))
1121 self.state_instance.del_shared_data('shutdown_time', optional=True)
1122
Jon Salzb19ea072013-02-07 16:35:00 +08001123 self.state_instance.del_shared_data('startup_error', optional=True)
Jon Salz0697cbf2012-07-04 15:14:04 +08001124 if not self.options.test_list:
1125 self.options.test_list = find_test_list()
Jon Salzb19ea072013-02-07 16:35:00 +08001126 if self.options.test_list:
Jon Salz0697cbf2012-07-04 15:14:04 +08001127 logging.info('Using test list %s', self.options.test_list)
Jon Salzb19ea072013-02-07 16:35:00 +08001128 try:
1129 self.test_list = factory.read_test_list(
1130 self.options.test_list,
1131 self.state_instance)
1132 except: # pylint: disable=W0702
1133 logging.exception('Unable to read test list %r', self.options.test_list)
1134 self.state_instance.set_shared_data('startup_error',
1135 'Unable to read test list %s\n%s' % (
1136 self.options.test_list,
1137 traceback.format_exc()))
1138 else:
1139 logging.error('No test list found.')
1140 self.state_instance.set_shared_data('startup_error',
1141 'No test list found.')
Jon Salz0697cbf2012-07-04 15:14:04 +08001142
Jon Salzb19ea072013-02-07 16:35:00 +08001143 if not self.test_list:
1144 if self.options.ui == 'chrome':
1145 # Create an empty test list with default options so that the rest of
1146 # startup can proceed.
1147 self.test_list = factory.FactoryTestList(
1148 [], self.state_instance, factory.Options())
1149 else:
1150 # Bail with an error; no point in starting up.
1151 sys.exit('No valid test list; exiting.')
1152
Jon Salz822838b2013-03-25 17:32:33 +08001153 if self.test_list.options.clear_state_on_start:
1154 self.state_instance.clear_test_state()
1155
Jon Salz0697cbf2012-07-04 15:14:04 +08001156 if not self.state_instance.has_shared_data('ui_lang'):
1157 self.state_instance.set_shared_data('ui_lang',
1158 self.test_list.options.ui_lang)
1159 self.state_instance.set_shared_data(
1160 'test_list_options',
1161 self.test_list.options.__dict__)
1162 self.state_instance.test_list = self.test_list
1163
Jon Salz83ef34b2012-11-01 19:46:35 +08001164 if not utils.in_chroot() and self.test_list.options.disable_log_rotation:
1165 open('/var/lib/cleanup_logs_paused', 'w').close()
1166
Jon Salz23926422012-09-01 03:38:13 +08001167 if self.options.dummy_shopfloor:
1168 os.environ[shopfloor.SHOPFLOOR_SERVER_ENV_VAR_NAME] = (
1169 'http://localhost:%d/' % shopfloor.DEFAULT_SERVER_PORT)
1170 self.dummy_shopfloor = Spawn(
1171 [os.path.join(factory.FACTORY_PATH, 'bin', 'shopfloor_server'),
1172 '--dummy'])
1173 elif self.test_list.options.shopfloor_server_url:
1174 shopfloor.set_server_url(self.test_list.options.shopfloor_server_url)
Jon Salz2bf2f6b2013-03-28 18:49:26 +08001175 shopfloor.set_enabled(True)
Jon Salz23926422012-09-01 03:38:13 +08001176
Jon Salz0f996602012-10-03 15:26:48 +08001177 if self.test_list.options.time_sanitizer and not utils.in_chroot():
Jon Salz8fa8e832012-07-13 19:04:09 +08001178 self.time_sanitizer = time_sanitizer.TimeSanitizer(
1179 base_time=time_sanitizer.GetBaseTimeFromFile(
1180 # lsb-factory is written by the factory install shim during
1181 # installation, so it should have a good time obtained from
Jon Salz54882d02012-08-31 01:57:54 +08001182 # the mini-Omaha server. If it's not available, we'll use
1183 # /etc/lsb-factory (which will be much older, but reasonably
1184 # sane) and rely on a shopfloor sync to set a more accurate
1185 # time.
1186 '/usr/local/etc/lsb-factory',
1187 '/etc/lsb-release'))
Jon Salz8fa8e832012-07-13 19:04:09 +08001188 self.time_sanitizer.RunOnce()
1189
Jon Salz0697cbf2012-07-04 15:14:04 +08001190 self.init_states()
1191 self.start_event_server()
1192 self.connection_manager = self.env.create_connection_manager(
Tai-Hsu Lin371351a2012-08-27 14:17:14 +08001193 self.test_list.options.wlans,
1194 self.test_list.options.scan_wifi_period_secs)
Jon Salz0697cbf2012-07-04 15:14:04 +08001195 # Note that we create a log watcher even if
1196 # sync_event_log_period_secs isn't set (no background
1197 # syncing), since we may use it to flush event logs as well.
1198 self.log_watcher = EventLogWatcher(
1199 self.test_list.options.sync_event_log_period_secs,
Jon Salz16d10542012-07-23 12:18:45 +08001200 handle_event_logs_callback=self.handle_event_logs)
Jon Salz0697cbf2012-07-04 15:14:04 +08001201 if self.test_list.options.sync_event_log_period_secs:
1202 self.log_watcher.StartWatchThread()
1203
1204 self.update_system_info()
1205
Vic Yang4953fc12012-07-26 16:19:53 +08001206 assert ((self.test_list.options.min_charge_pct is None) ==
1207 (self.test_list.options.max_charge_pct is None))
Jon Salzad7353b2012-10-15 16:22:46 +08001208 if self.test_list.options.min_charge_pct is not None:
Vic Yang4953fc12012-07-26 16:19:53 +08001209 self.charge_manager = ChargeManager(self.test_list.options.min_charge_pct,
1210 self.test_list.options.max_charge_pct)
Jon Salzad7353b2012-10-15 16:22:46 +08001211 system.SystemStatus.charge_manager = self.charge_manager
Vic Yang4953fc12012-07-26 16:19:53 +08001212
Jon Salz0697cbf2012-07-04 15:14:04 +08001213 os.environ['CROS_FACTORY'] = '1'
1214 os.environ['CROS_DISABLE_SITE_SYSINFO'] = '1'
1215
1216 # Set CROS_UI since some behaviors in ui.py depend on the
1217 # particular UI in use. TODO(jsalz): Remove this (and all
1218 # places it is used) when the GTK UI is removed.
1219 os.environ['CROS_UI'] = self.options.ui
1220
1221 if self.options.ui == 'chrome':
1222 self.env.launch_chrome()
1223 logging.info('Waiting for a web socket connection')
Cheng-Yi Chiangfd8ed392013-03-08 21:37:31 +08001224 self.web_socket_manager.wait()
Jon Salz0697cbf2012-07-04 15:14:04 +08001225
1226 # Wait for the test widget size to be set; this is done in
1227 # an asynchronous RPC so there is a small chance that the
1228 # web socket might be opened first.
1229 for _ in range(100): # 10 s
1230 try:
1231 if self.state_instance.get_shared_data('test_widget_size'):
1232 break
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001233 except KeyError:
Jon Salz0697cbf2012-07-04 15:14:04 +08001234 pass # Retry
1235 time.sleep(0.1) # 100 ms
1236 else:
1237 logging.warn('Never received test_widget_size from UI')
1238 elif self.options.ui == 'gtk':
1239 self.start_ui()
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001240
Ricky Liang650f6bf2012-09-28 13:22:54 +08001241 # Create download path for autotest beforehand or autotests run at
1242 # the same time might fail due to race condition.
1243 if not factory.in_chroot():
1244 utils.TryMakeDirs(os.path.join('/usr/local/autotest', 'tests',
1245 'download'))
1246
Jon Salz0697cbf2012-07-04 15:14:04 +08001247 def state_change_callback(test, test_state):
1248 self.event_client.post_event(
1249 Event(Event.Type.STATE_CHANGE,
1250 path=test.path, state=test_state))
1251 self.test_list.state_change_callback = state_change_callback
Jon Salz73e0fd02012-04-04 11:46:38 +08001252
Jon Salza6711d72012-07-18 14:33:03 +08001253 for handler in self.on_ui_startup:
1254 handler()
1255
1256 self.prespawner = Prespawner()
1257 self.prespawner.start()
1258
Jon Salz0697cbf2012-07-04 15:14:04 +08001259 try:
1260 tests_after_shutdown = self.state_instance.get_shared_data(
1261 'tests_after_shutdown')
1262 except KeyError:
1263 tests_after_shutdown = None
Jon Salz57717ca2012-04-04 16:47:25 +08001264
Jon Salz5c344f62012-07-13 14:31:16 +08001265 force_auto_run = (tests_after_shutdown == FORCE_AUTO_RUN)
1266 if not force_auto_run and tests_after_shutdown is not None:
Jon Salz0697cbf2012-07-04 15:14:04 +08001267 logging.info('Resuming tests after shutdown: %s',
1268 tests_after_shutdown)
Jon Salz0697cbf2012-07-04 15:14:04 +08001269 self.tests_to_run.extend(
1270 self.test_list.lookup_path(t) for t in tests_after_shutdown)
1271 self.run_queue.put(self.run_next_test)
1272 else:
Jon Salz5c344f62012-07-13 14:31:16 +08001273 if force_auto_run or self.test_list.options.auto_run_on_start:
Jon Salz0697cbf2012-07-04 15:14:04 +08001274 self.run_queue.put(
1275 lambda: self.run_tests(self.test_list, untested_only=True))
Jon Salz5c344f62012-07-13 14:31:16 +08001276 self.state_instance.set_shared_data('tests_after_shutdown', None)
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001277
Dean Liao592e4d52013-01-10 20:06:39 +08001278 self.may_disable_cros_shortcut_keys()
1279
1280 def may_disable_cros_shortcut_keys(self):
1281 test_options = self.test_list.options
1282 if test_options.disable_cros_shortcut_keys:
1283 logging.info('Filter ChromeOS shortcut keys.')
1284 self.key_filter = KeyFilter(
1285 unmap_caps_lock=test_options.disable_caps_lock,
1286 caps_lock_keycode=test_options.caps_lock_keycode)
1287 self.key_filter.Start()
1288
Jon Salz0697cbf2012-07-04 15:14:04 +08001289 def run(self):
1290 '''Runs Goofy.'''
1291 # Process events forever.
1292 while self.run_once(True):
1293 pass
Jon Salz73e0fd02012-04-04 11:46:38 +08001294
Jon Salz0697cbf2012-07-04 15:14:04 +08001295 def run_once(self, block=False):
1296 '''Runs all items pending in the event loop.
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001297
Jon Salz0697cbf2012-07-04 15:14:04 +08001298 Args:
1299 block: If true, block until at least one event is processed.
Jon Salz7c15e8b2012-06-19 17:10:37 +08001300
Jon Salz0697cbf2012-07-04 15:14:04 +08001301 Returns:
1302 True to keep going or False to shut down.
1303 '''
1304 events = utils.DrainQueue(self.run_queue)
cychiang21886742012-07-05 15:16:32 +08001305 while not events:
Jon Salz0697cbf2012-07-04 15:14:04 +08001306 # Nothing on the run queue.
1307 self._run_queue_idle()
1308 if block:
1309 # Block for at least one event...
cychiang21886742012-07-05 15:16:32 +08001310 try:
1311 events.append(self.run_queue.get(timeout=RUN_QUEUE_TIMEOUT_SECS))
1312 except Queue.Empty:
1313 # Keep going (calling _run_queue_idle() again at the top of
1314 # the loop)
1315 continue
Jon Salz0697cbf2012-07-04 15:14:04 +08001316 # ...and grab anything else that showed up at the same
1317 # time.
1318 events.extend(utils.DrainQueue(self.run_queue))
cychiang21886742012-07-05 15:16:32 +08001319 else:
1320 break
Jon Salz51528e12012-07-02 18:54:45 +08001321
Jon Salz0697cbf2012-07-04 15:14:04 +08001322 for event in events:
1323 if not event:
1324 # Shutdown request.
1325 self.run_queue.task_done()
1326 return False
Jon Salz51528e12012-07-02 18:54:45 +08001327
Jon Salz0697cbf2012-07-04 15:14:04 +08001328 try:
1329 event()
Jon Salz85a39882012-07-05 16:45:04 +08001330 except: # pylint: disable=W0702
1331 logging.exception('Error in event loop')
Jon Salz0697cbf2012-07-04 15:14:04 +08001332 self.record_exception(traceback.format_exception_only(
1333 *sys.exc_info()[:2]))
1334 # But keep going
1335 finally:
1336 self.run_queue.task_done()
1337 return True
Jon Salz0405ab52012-03-16 15:26:52 +08001338
Jon Salz0e6532d2012-10-25 16:30:11 +08001339 def _should_sync_time(self, foreground=False):
1340 '''Returns True if we should attempt syncing time with shopfloor.
1341
1342 Args:
1343 foreground: If True, synchronizes even if background syncing
1344 is disabled (e.g., in explicit sync requests from the
1345 SyncShopfloor test).
1346 '''
1347 return ((foreground or
1348 self.test_list.options.sync_time_period_secs) and
Jon Salz54882d02012-08-31 01:57:54 +08001349 self.time_sanitizer and
1350 (not self.time_synced) and
1351 (not factory.in_chroot()))
1352
Jon Salz0e6532d2012-10-25 16:30:11 +08001353 def sync_time_with_shopfloor_server(self, foreground=False):
Jon Salz54882d02012-08-31 01:57:54 +08001354 '''Syncs time with shopfloor server, if not yet synced.
1355
Jon Salz0e6532d2012-10-25 16:30:11 +08001356 Args:
1357 foreground: If True, synchronizes even if background syncing
1358 is disabled (e.g., in explicit sync requests from the
1359 SyncShopfloor test).
1360
Jon Salz54882d02012-08-31 01:57:54 +08001361 Returns:
1362 False if no time sanitizer is available, or True if this sync (or a
1363 previous sync) succeeded.
1364
1365 Raises:
1366 Exception if unable to contact the shopfloor server.
1367 '''
Jon Salz0e6532d2012-10-25 16:30:11 +08001368 if self._should_sync_time(foreground):
Jon Salz54882d02012-08-31 01:57:54 +08001369 self.time_sanitizer.SyncWithShopfloor()
1370 self.time_synced = True
1371 return self.time_synced
1372
Jon Salzb92c5112012-09-21 15:40:11 +08001373 def log_disk_space_stats(self):
1374 if not self.test_list.options.log_disk_space_period_secs:
1375 return
1376
1377 now = time.time()
1378 if (self.last_log_disk_space_time and
1379 now - self.last_log_disk_space_time <
1380 self.test_list.options.log_disk_space_period_secs):
1381 return
1382 self.last_log_disk_space_time = now
1383
1384 try:
Jon Salz3c493bb2013-02-07 17:24:58 +08001385 message = disk_space.FormatSpaceUsedAll()
1386 if message != self.last_log_disk_space_message:
1387 logging.info(message)
1388 self.last_log_disk_space_message = message
Jon Salzb92c5112012-09-21 15:40:11 +08001389 except: # pylint: disable=W0702
1390 logging.exception('Unable to get disk space used')
1391
Jon Salz8fa8e832012-07-13 19:04:09 +08001392 def sync_time_in_background(self):
Jon Salzb22d1172012-08-06 10:38:57 +08001393 '''Writes out current time and tries to sync with shopfloor server.'''
1394 if not self.time_sanitizer:
1395 return
1396
1397 # Write out the current time.
1398 self.time_sanitizer.SaveTime()
1399
Jon Salz54882d02012-08-31 01:57:54 +08001400 if not self._should_sync_time():
Jon Salz8fa8e832012-07-13 19:04:09 +08001401 return
1402
1403 now = time.time()
1404 if self.last_sync_time and (
1405 now - self.last_sync_time <
1406 self.test_list.options.sync_time_period_secs):
1407 # Not yet time for another check.
1408 return
1409 self.last_sync_time = now
1410
1411 def target():
1412 try:
Jon Salz54882d02012-08-31 01:57:54 +08001413 self.sync_time_with_shopfloor_server()
Jon Salz8fa8e832012-07-13 19:04:09 +08001414 except: # pylint: disable=W0702
1415 # Oh well. Log an error (but no trace)
1416 logging.info(
1417 'Unable to get time from shopfloor server: %s',
1418 utils.FormatExceptionOnly())
1419
1420 thread = threading.Thread(target=target)
1421 thread.daemon = True
1422 thread.start()
1423
Jon Salz0697cbf2012-07-04 15:14:04 +08001424 def _run_queue_idle(self):
Vic Yang4953fc12012-07-26 16:19:53 +08001425 '''Invoked when the run queue has no events.
1426
1427 This method must not raise exception.
1428 '''
Jon Salzb22d1172012-08-06 10:38:57 +08001429 now = time.time()
1430 if (self.last_idle and
1431 now < (self.last_idle + RUN_QUEUE_TIMEOUT_SECS - 1)):
1432 # Don't run more often than once every (RUN_QUEUE_TIMEOUT_SECS -
1433 # 1) seconds.
1434 return
1435
1436 self.last_idle = now
1437
Vic Yang311ddb82012-09-26 12:08:28 +08001438 self.check_exclusive()
cychiang21886742012-07-05 15:16:32 +08001439 self.check_for_updates()
Jon Salz8fa8e832012-07-13 19:04:09 +08001440 self.sync_time_in_background()
Jon Salzb92c5112012-09-21 15:40:11 +08001441 self.log_disk_space_stats()
Jon Salz57717ca2012-04-04 16:47:25 +08001442
Jon Salz16d10542012-07-23 12:18:45 +08001443 def handle_event_logs(self, log_name, chunk):
Jon Salz0697cbf2012-07-04 15:14:04 +08001444 '''Callback for event watcher.
Jon Salz258a40c2012-04-19 12:34:01 +08001445
Jon Salz0697cbf2012-07-04 15:14:04 +08001446 Attempts to upload the event logs to the shopfloor server.
1447 '''
1448 description = 'event logs (%s, %d bytes)' % (log_name, len(chunk))
1449 start_time = time.time()
Jon Salz0697cbf2012-07-04 15:14:04 +08001450 shopfloor_client = shopfloor.get_instance(
1451 detect=True,
1452 timeout=self.test_list.options.shopfloor_timeout_secs)
Jon Salzb10cf512012-08-09 17:29:21 +08001453 shopfloor_client.UploadEvent(log_name, Binary(chunk))
Jon Salz0697cbf2012-07-04 15:14:04 +08001454 logging.info(
1455 'Successfully synced %s in %.03f s',
1456 description, time.time() - start_time)
Jon Salz57717ca2012-04-04 16:47:25 +08001457
Jon Salz0697cbf2012-07-04 15:14:04 +08001458 def run_tests_with_status(self, statuses_to_run, starting_at=None,
1459 root=None):
1460 '''Runs all top-level tests with a particular status.
Jon Salz0405ab52012-03-16 15:26:52 +08001461
Jon Salz0697cbf2012-07-04 15:14:04 +08001462 All active tests, plus any tests to re-run, are reset.
Jon Salz57717ca2012-04-04 16:47:25 +08001463
Jon Salz0697cbf2012-07-04 15:14:04 +08001464 Args:
1465 starting_at: If provided, only auto-runs tests beginning with
1466 this test.
1467 '''
1468 root = root or self.test_list
Jon Salz57717ca2012-04-04 16:47:25 +08001469
Jon Salz0697cbf2012-07-04 15:14:04 +08001470 if starting_at:
1471 # Make sure they passed a test, not a string.
1472 assert isinstance(starting_at, factory.FactoryTest)
Jon Salz0405ab52012-03-16 15:26:52 +08001473
Jon Salz0697cbf2012-07-04 15:14:04 +08001474 tests_to_reset = []
1475 tests_to_run = []
Jon Salz0405ab52012-03-16 15:26:52 +08001476
Jon Salz0697cbf2012-07-04 15:14:04 +08001477 found_starting_at = False
Jon Salz0405ab52012-03-16 15:26:52 +08001478
Jon Salz0697cbf2012-07-04 15:14:04 +08001479 for test in root.get_top_level_tests():
1480 if starting_at:
1481 if test == starting_at:
1482 # We've found starting_at; do auto-run on all
1483 # subsequent tests.
1484 found_starting_at = True
1485 if not found_starting_at:
1486 # Don't start this guy yet
1487 continue
Jon Salz0405ab52012-03-16 15:26:52 +08001488
Jon Salz0697cbf2012-07-04 15:14:04 +08001489 status = test.get_state().status
1490 if status == TestState.ACTIVE or status in statuses_to_run:
1491 # Reset the test (later; we will need to abort
1492 # all active tests first).
1493 tests_to_reset.append(test)
1494 if status in statuses_to_run:
1495 tests_to_run.append(test)
Jon Salz0405ab52012-03-16 15:26:52 +08001496
Jon Salz0697cbf2012-07-04 15:14:04 +08001497 self.abort_active_tests()
Jon Salz258a40c2012-04-19 12:34:01 +08001498
Jon Salz0697cbf2012-07-04 15:14:04 +08001499 # Reset all statuses of the tests to run (in case any tests were active;
1500 # we want them to be run again).
1501 for test_to_reset in tests_to_reset:
1502 for test in test_to_reset.walk():
1503 test.update_state(status=TestState.UNTESTED)
Jon Salz57717ca2012-04-04 16:47:25 +08001504
Jon Salz0697cbf2012-07-04 15:14:04 +08001505 self.run_tests(tests_to_run, untested_only=True)
Jon Salz0405ab52012-03-16 15:26:52 +08001506
Jon Salz0697cbf2012-07-04 15:14:04 +08001507 def restart_tests(self, root=None):
1508 '''Restarts all tests.'''
1509 root = root or self.test_list
Jon Salz0405ab52012-03-16 15:26:52 +08001510
Jon Salz0697cbf2012-07-04 15:14:04 +08001511 self.abort_active_tests()
1512 for test in root.walk():
1513 test.update_state(status=TestState.UNTESTED)
1514 self.run_tests(root)
Hung-Te Lin96632362012-03-20 21:14:18 +08001515
Jon Salz0697cbf2012-07-04 15:14:04 +08001516 def auto_run(self, starting_at=None, root=None):
1517 '''"Auto-runs" tests that have not been run yet.
Hung-Te Lin96632362012-03-20 21:14:18 +08001518
Jon Salz0697cbf2012-07-04 15:14:04 +08001519 Args:
1520 starting_at: If provide, only auto-runs tests beginning with
1521 this test.
1522 '''
1523 root = root or self.test_list
1524 self.run_tests_with_status([TestState.UNTESTED, TestState.ACTIVE],
1525 starting_at=starting_at,
1526 root=root)
Jon Salz968e90b2012-03-18 16:12:43 +08001527
Jon Salz0697cbf2012-07-04 15:14:04 +08001528 def re_run_failed(self, root=None):
1529 '''Re-runs failed tests.'''
1530 root = root or self.test_list
1531 self.run_tests_with_status([TestState.FAILED], root=root)
Jon Salz57717ca2012-04-04 16:47:25 +08001532
Jon Salz0697cbf2012-07-04 15:14:04 +08001533 def show_review_information(self):
1534 '''Event handler for showing review information screen.
Jon Salz57717ca2012-04-04 16:47:25 +08001535
Jon Salz0697cbf2012-07-04 15:14:04 +08001536 The information screene is rendered by main UI program (ui.py), so in
1537 goofy we only need to kill all active tests, set them as untested, and
1538 clear remaining tests.
1539 '''
1540 self.kill_active_tests(False)
Jon Salza6711d72012-07-18 14:33:03 +08001541 self.cancel_pending_tests()
Jon Salz57717ca2012-04-04 16:47:25 +08001542
Jon Salz0697cbf2012-07-04 15:14:04 +08001543 def handle_switch_test(self, event):
1544 '''Switches to a particular test.
Jon Salz0405ab52012-03-16 15:26:52 +08001545
Jon Salz0697cbf2012-07-04 15:14:04 +08001546 @param event: The SWITCH_TEST event.
1547 '''
1548 test = self.test_list.lookup_path(event.path)
1549 if not test:
1550 logging.error('Unknown test %r', event.key)
1551 return
Jon Salz73e0fd02012-04-04 11:46:38 +08001552
Jon Salz0697cbf2012-07-04 15:14:04 +08001553 invoc = self.invocations.get(test)
1554 if invoc and test.backgroundable:
1555 # Already running: just bring to the front if it
1556 # has a UI.
1557 logging.info('Setting visible test to %s', test.path)
Jon Salz36fbbb52012-07-05 13:45:06 +08001558 self.set_visible_test(test)
Jon Salz0697cbf2012-07-04 15:14:04 +08001559 return
Jon Salz73e0fd02012-04-04 11:46:38 +08001560
Jon Salz0697cbf2012-07-04 15:14:04 +08001561 self.abort_active_tests()
1562 for t in test.walk():
1563 t.update_state(status=TestState.UNTESTED)
Jon Salz73e0fd02012-04-04 11:46:38 +08001564
Jon Salz0697cbf2012-07-04 15:14:04 +08001565 if self.test_list.options.auto_run_on_keypress:
1566 self.auto_run(starting_at=test)
1567 else:
1568 self.run_tests(test)
Jon Salz73e0fd02012-04-04 11:46:38 +08001569
Jon Salz0697cbf2012-07-04 15:14:04 +08001570 def wait(self):
1571 '''Waits for all pending invocations.
1572
1573 Useful for testing.
1574 '''
Jon Salz1acc8742012-07-17 17:45:55 +08001575 while self.invocations:
1576 for k, v in self.invocations.iteritems():
1577 logging.info('Waiting for %s to complete...', k)
1578 v.thread.join()
1579 self.reap_completed_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +08001580
1581 def check_exceptions(self):
1582 '''Raises an error if any exceptions have occurred in
1583 invocation threads.'''
1584 if self.exceptions:
1585 raise RuntimeError('Exception in invocation thread: %r' %
1586 self.exceptions)
1587
1588 def record_exception(self, msg):
1589 '''Records an exception in an invocation thread.
1590
1591 An exception with the given message will be rethrown when
1592 Goofy is destroyed.'''
1593 self.exceptions.append(msg)
Jon Salz73e0fd02012-04-04 11:46:38 +08001594
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001595
1596if __name__ == '__main__':
Jon Salz77c151e2012-08-28 07:20:37 +08001597 goofy = Goofy()
1598 try:
1599 goofy.main()
Jon Salz0f996602012-10-03 15:26:48 +08001600 except SystemExit:
1601 # Propagate SystemExit without logging.
1602 raise
Jon Salz31373eb2012-09-21 16:19:49 +08001603 except:
Jon Salz0f996602012-10-03 15:26:48 +08001604 # Log the error before trying to shut down (unless it's a graceful
1605 # exit).
Jon Salz31373eb2012-09-21 16:19:49 +08001606 logging.exception('Error in main loop')
1607 raise
Jon Salz77c151e2012-08-28 07:20:37 +08001608 finally:
1609 goofy.destroy()