blob: 06614f2cfcc1986caeb0227a904dfd700e583a08 [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
Tom Wai-Hong Tamd33723e2013-04-10 21:14:37 +080029from cros.factory.event_log_watcher import EventLogWatcher
jcliangcd688182012-08-20 21:01:26 +080030from cros.factory.goofy import test_environment
31from cros.factory.goofy import time_sanitizer
Jon Salz83591782012-06-26 11:09:58 +080032from cros.factory.goofy import updater
jcliangcd688182012-08-20 21:01:26 +080033from cros.factory.goofy.goofy_rpc import GoofyRPC
34from cros.factory.goofy.invocation import TestInvocation
35from cros.factory.goofy.prespawner import Prespawner
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +080036from cros.factory.goofy.system_log_manager import SystemLogManager
jcliangcd688182012-08-20 21:01:26 +080037from cros.factory.goofy.web_socket_manager import WebSocketManager
Cheng-Yi Chiangd8186952013-04-04 23:41:14 +080038from cros.factory.system.board import Board, BoardException
jcliangcd688182012-08-20 21:01:26 +080039from cros.factory.system.charge_manager import ChargeManager
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +080040from cros.factory.system.core_dump_manager import CoreDumpManager
Jon Salzb92c5112012-09-21 15:40:11 +080041from cros.factory.system import disk_space
jcliangcd688182012-08-20 21:01:26 +080042from cros.factory.test import factory
43from cros.factory.test import state
Jon Salz51528e12012-07-02 18:54:45 +080044from cros.factory.test import shopfloor
Jon Salz83591782012-06-26 11:09:58 +080045from cros.factory.test import utils
46from cros.factory.test.event import Event
47from cros.factory.test.event import EventClient
48from cros.factory.test.event import EventServer
jcliangcd688182012-08-20 21:01:26 +080049from cros.factory.test.factory import TestState
Dean Liao592e4d52013-01-10 20:06:39 +080050from cros.factory.tools.key_filter import KeyFilter
Jon Salz78c32392012-07-25 14:18:29 +080051from cros.factory.utils.process_utils import Spawn
Hung-Te Linf2f78f72012-02-08 19:27:11 +080052
53
Jon Salz2f757d42012-06-27 17:06:42 +080054CUSTOM_DIR = os.path.join(factory.FACTORY_PATH, 'custom')
Hung-Te Linf2f78f72012-02-08 19:27:11 +080055HWID_CFG_PATH = '/usr/local/share/chromeos-hwid/cfg'
Chun-ta Lin279e7e92013-02-19 17:40:39 +080056CACHES_DIR = os.path.join(factory.get_state_root(), "caches")
Hung-Te Linf2f78f72012-02-08 19:27:11 +080057
Jon Salz8796e362012-05-24 11:39:09 +080058# File that suppresses reboot if present (e.g., for development).
59NO_REBOOT_FILE = '/var/log/factory.noreboot'
60
Jon Salz5c344f62012-07-13 14:31:16 +080061# Value for tests_after_shutdown that forces auto-run (e.g., after
62# a factory update, when the available set of tests might change).
63FORCE_AUTO_RUN = 'force_auto_run'
64
cychiang21886742012-07-05 15:16:32 +080065RUN_QUEUE_TIMEOUT_SECS = 10
66
Jon Salz758e6cc2012-04-03 15:47:07 +080067GOOFY_IN_CHROOT_WARNING = '\n' + ('*' * 70) + '''
68You are running Goofy inside the chroot. Autotests are not supported.
69
70To use Goofy in the chroot, first install an Xvnc server:
71
Jon Salz0697cbf2012-07-04 15:14:04 +080072 sudo apt-get install tightvncserver
Jon Salz758e6cc2012-04-03 15:47:07 +080073
74...and then start a VNC X server outside the chroot:
75
Jon Salz0697cbf2012-07-04 15:14:04 +080076 vncserver :10 &
77 vncviewer :10
Jon Salz758e6cc2012-04-03 15:47:07 +080078
79...and run Goofy as follows:
80
Jon Salz0697cbf2012-07-04 15:14:04 +080081 env --unset=XAUTHORITY DISPLAY=localhost:10 python goofy.py
Jon Salz758e6cc2012-04-03 15:47:07 +080082''' + ('*' * 70)
Jon Salz73e0fd02012-04-04 11:46:38 +080083suppress_chroot_warning = False
Hung-Te Linf2f78f72012-02-08 19:27:11 +080084
85def get_hwid_cfg():
Jon Salz0697cbf2012-07-04 15:14:04 +080086 '''
87 Returns the HWID config tag, or an empty string if none can be found.
88 '''
89 if 'CROS_HWID' in os.environ:
90 return os.environ['CROS_HWID']
91 if os.path.exists(HWID_CFG_PATH):
92 with open(HWID_CFG_PATH, 'rt') as hwid_cfg_handle:
93 return hwid_cfg_handle.read().strip()
94 return ''
Hung-Te Linf2f78f72012-02-08 19:27:11 +080095
96
97def find_test_list():
Jon Salz0697cbf2012-07-04 15:14:04 +080098 '''
99 Returns the path to the active test list, based on the HWID config tag.
Jon Salzfb615892013-02-01 18:04:35 +0800100
101 The algorithm is:
102
103 - Try $FACTORY/test_lists/active (the symlink reflecting the option chosen
104 in the UI).
105 - For each of $FACTORY/custom, $FACTORY/test_lists (and
106 autotest/site_tests/suite_Factory for backward compatibility):
107 - Try test_list_${hwid_cfg} (if hwid_cfg is set)
108 - Try test_list
109 - Try test_list.generic
Jon Salz0697cbf2012-07-04 15:14:04 +0800110 '''
Jon Salzfb615892013-02-01 18:04:35 +0800111 # If the 'active' symlink is present, that trumps everything else.
112 if os.path.lexists(factory.ACTIVE_TEST_LIST_SYMLINK):
113 return os.path.realpath(factory.ACTIVE_TEST_LIST_SYMLINK)
114
Jon Salz0697cbf2012-07-04 15:14:04 +0800115 hwid_cfg = get_hwid_cfg()
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800116
Jon Salzfb615892013-02-01 18:04:35 +0800117 search_dirs = [CUSTOM_DIR, factory.TEST_LISTS_PATH]
Jon Salz4be56b02012-12-22 07:30:46 +0800118 if not utils.in_chroot():
119 # Also look in suite_Factory. For backward compatibility only;
120 # new boards should just put the test list in the "test_lists"
121 # directory.
122 search_dirs.insert(0, os.path.join(
123 os.path.dirname(factory.FACTORY_PATH),
124 'autotest', 'site_tests', 'suite_Factory'))
Jon Salz2f757d42012-06-27 17:06:42 +0800125
Jon Salzfb615892013-02-01 18:04:35 +0800126
127 search_files = []
Jon Salz0697cbf2012-07-04 15:14:04 +0800128 if hwid_cfg:
Jon Salzfb615892013-02-01 18:04:35 +0800129 search_files += [hwid_cfg]
130 search_files += ['test_list', 'test_list.generic']
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800131
Jon Salz0697cbf2012-07-04 15:14:04 +0800132 for d in search_dirs:
133 for f in search_files:
134 test_list = os.path.join(d, f)
135 if os.path.exists(test_list):
136 return test_list
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800137
Jon Salz0697cbf2012-07-04 15:14:04 +0800138 logging.warn('Cannot find test lists named any of %s in any of %s',
139 search_files, search_dirs)
140 return None
Jon Salz73e0fd02012-04-04 11:46:38 +0800141
Jon Salzfb615892013-02-01 18:04:35 +0800142
Jon Salz73e0fd02012-04-04 11:46:38 +0800143_inited_logging = False
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800144
145class Goofy(object):
Jon Salz0697cbf2012-07-04 15:14:04 +0800146 '''
147 The main factory flow.
148
149 Note that all methods in this class must be invoked from the main
150 (event) thread. Other threads, such as callbacks and TestInvocation
151 methods, should instead post events on the run queue.
152
153 TODO: Unit tests. (chrome-os-partner:7409)
154
155 Properties:
156 uuid: A unique UUID for this invocation of Goofy.
157 state_instance: An instance of FactoryState.
158 state_server: The FactoryState XML/RPC server.
159 state_server_thread: A thread running state_server.
160 event_server: The EventServer socket server.
161 event_server_thread: A thread running event_server.
162 event_client: A client to the event server.
163 connection_manager: The connection_manager object.
Jon Salz0697cbf2012-07-04 15:14:04 +0800164 ui_process: The factory ui process object.
165 run_queue: A queue of callbacks to invoke from the main thread.
166 invocations: A map from FactoryTest objects to the corresponding
167 TestInvocations objects representing active tests.
168 tests_to_run: A deque of tests that should be run when the current
169 test(s) complete.
170 options: Command-line options.
171 args: Command-line args.
172 test_list: The test list.
173 event_handlers: Map of Event.Type to the method used to handle that
174 event. If the method has an 'event' argument, the event is passed
175 to the handler.
176 exceptions: Exceptions encountered in invocation threads.
Jon Salz3c493bb2013-02-07 17:24:58 +0800177 last_log_disk_space_message: The last message we logged about disk space
178 (to avoid duplication).
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +0800179 last_kick_sync_time: The last time to kick system_log_manager to sync
180 because of core dump files (to avoid kicking too soon then abort the
181 sync.)
Jon Salz0697cbf2012-07-04 15:14:04 +0800182 '''
183 def __init__(self):
184 self.uuid = str(uuid.uuid4())
185 self.state_instance = None
186 self.state_server = None
187 self.state_server_thread = None
Jon Salz16d10542012-07-23 12:18:45 +0800188 self.goofy_rpc = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800189 self.event_server = None
190 self.event_server_thread = None
191 self.event_client = None
192 self.connection_manager = None
Vic Yang4953fc12012-07-26 16:19:53 +0800193 self.charge_manager = None
Jon Salz8fa8e832012-07-13 19:04:09 +0800194 self.time_sanitizer = None
195 self.time_synced = False
Jon Salz0697cbf2012-07-04 15:14:04 +0800196 self.log_watcher = None
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +0800197 self.system_log_manager = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800198 self.event_log = None
199 self.prespawner = None
200 self.ui_process = None
Jon Salzc79a9982012-08-30 04:42:01 +0800201 self.dummy_shopfloor = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800202 self.run_queue = Queue.Queue()
203 self.invocations = {}
204 self.tests_to_run = deque()
205 self.visible_test = None
206 self.chrome = None
207
208 self.options = None
209 self.args = None
210 self.test_list = None
211 self.on_ui_startup = []
212 self.env = None
Jon Salzb22d1172012-08-06 10:38:57 +0800213 self.last_idle = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800214 self.last_shutdown_time = None
cychiang21886742012-07-05 15:16:32 +0800215 self.last_update_check = None
Jon Salz8fa8e832012-07-13 19:04:09 +0800216 self.last_sync_time = None
Jon Salzb92c5112012-09-21 15:40:11 +0800217 self.last_log_disk_space_time = None
Jon Salz3c493bb2013-02-07 17:24:58 +0800218 self.last_log_disk_space_message = None
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +0800219 self.last_kick_sync_time = None
Vic Yang311ddb82012-09-26 12:08:28 +0800220 self.exclusive_items = set()
Jon Salz0f996602012-10-03 15:26:48 +0800221 self.event_log = None
Dean Liao592e4d52013-01-10 20:06:39 +0800222 self.key_filter = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800223
Jon Salz85a39882012-07-05 16:45:04 +0800224 def test_or_root(event, parent_or_group=True):
225 '''Returns the test affected by a particular event.
226
227 Args:
228 event: The event containing an optional 'path' attribute.
229 parent_on_group: If True, returns the top-level parent for a test (the
230 root node of the tests that need to be run together if the given test
231 path is to be run).
232 '''
Jon Salz0697cbf2012-07-04 15:14:04 +0800233 try:
234 path = event.path
235 except AttributeError:
236 path = None
237
238 if path:
Jon Salz85a39882012-07-05 16:45:04 +0800239 test = self.test_list.lookup_path(path)
240 if parent_or_group:
241 test = test.get_top_level_parent_or_group()
242 return test
Jon Salz0697cbf2012-07-04 15:14:04 +0800243 else:
244 return self.test_list
245
246 self.event_handlers = {
247 Event.Type.SWITCH_TEST: self.handle_switch_test,
248 Event.Type.SHOW_NEXT_ACTIVE_TEST:
249 lambda event: self.show_next_active_test(),
250 Event.Type.RESTART_TESTS:
251 lambda event: self.restart_tests(root=test_or_root(event)),
252 Event.Type.AUTO_RUN:
253 lambda event: self.auto_run(root=test_or_root(event)),
254 Event.Type.RE_RUN_FAILED:
255 lambda event: self.re_run_failed(root=test_or_root(event)),
256 Event.Type.RUN_TESTS_WITH_STATUS:
257 lambda event: self.run_tests_with_status(
258 event.status,
259 root=test_or_root(event)),
260 Event.Type.REVIEW:
261 lambda event: self.show_review_information(),
262 Event.Type.UPDATE_SYSTEM_INFO:
263 lambda event: self.update_system_info(),
Jon Salz0697cbf2012-07-04 15:14:04 +0800264 Event.Type.STOP:
Jon Salz85a39882012-07-05 16:45:04 +0800265 lambda event: self.stop(root=test_or_root(event, False),
266 fail=getattr(event, 'fail', False)),
Jon Salz36fbbb52012-07-05 13:45:06 +0800267 Event.Type.SET_VISIBLE_TEST:
268 lambda event: self.set_visible_test(
269 self.test_list.lookup_path(event.path)),
Jon Salz4712ac72013-02-07 17:12:05 +0800270 Event.Type.CLEAR_STATE:
271 lambda event: self.clear_state(self.test_list.lookup_path(event.path)),
Jon Salz0697cbf2012-07-04 15:14:04 +0800272 }
273
274 self.exceptions = []
275 self.web_socket_manager = None
276
277 def destroy(self):
278 if self.chrome:
279 self.chrome.kill()
280 self.chrome = None
Jon Salzc79a9982012-08-30 04:42:01 +0800281 if self.dummy_shopfloor:
282 self.dummy_shopfloor.kill()
283 self.dummy_shopfloor = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800284 if self.ui_process:
285 utils.kill_process_tree(self.ui_process, 'ui')
286 self.ui_process = None
287 if self.web_socket_manager:
288 logging.info('Stopping web sockets')
289 self.web_socket_manager.close()
290 self.web_socket_manager = None
291 if self.state_server_thread:
292 logging.info('Stopping state server')
293 self.state_server.shutdown()
294 self.state_server_thread.join()
295 self.state_server.server_close()
296 self.state_server_thread = None
297 if self.state_instance:
298 self.state_instance.close()
299 if self.event_server_thread:
300 logging.info('Stopping event server')
301 self.event_server.shutdown() # pylint: disable=E1101
302 self.event_server_thread.join()
303 self.event_server.server_close()
304 self.event_server_thread = None
305 if self.log_watcher:
306 if self.log_watcher.IsThreadStarted():
307 self.log_watcher.StopWatchThread()
308 self.log_watcher = None
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +0800309 if self.system_log_manager:
310 if self.system_log_manager.IsThreadRunning():
311 self.system_log_manager.StopSyncThread()
312 self.system_log_manager = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800313 if self.prespawner:
314 logging.info('Stopping prespawner')
315 self.prespawner.stop()
316 self.prespawner = None
317 if self.event_client:
318 logging.info('Closing event client')
319 self.event_client.close()
320 self.event_client = None
321 if self.event_log:
322 self.event_log.Close()
323 self.event_log = None
Dean Liao592e4d52013-01-10 20:06:39 +0800324 if self.key_filter:
325 self.key_filter.Stop()
326
Jon Salz0697cbf2012-07-04 15:14:04 +0800327 self.check_exceptions()
328 logging.info('Done destroying Goofy')
329
330 def start_state_server(self):
331 self.state_instance, self.state_server = (
332 state.create_server(bind_address='0.0.0.0'))
Jon Salz16d10542012-07-23 12:18:45 +0800333 self.goofy_rpc = GoofyRPC(self)
334 self.goofy_rpc.RegisterMethods(self.state_instance)
Jon Salz0697cbf2012-07-04 15:14:04 +0800335 logging.info('Starting state server')
336 self.state_server_thread = threading.Thread(
337 target=self.state_server.serve_forever,
338 name='StateServer')
339 self.state_server_thread.start()
340
341 def start_event_server(self):
342 self.event_server = EventServer()
343 logging.info('Starting factory event server')
344 self.event_server_thread = threading.Thread(
345 target=self.event_server.serve_forever,
346 name='EventServer') # pylint: disable=E1101
347 self.event_server_thread.start()
348
349 self.event_client = EventClient(
350 callback=self.handle_event, event_loop=self.run_queue)
351
352 self.web_socket_manager = WebSocketManager(self.uuid)
353 self.state_server.add_handler("/event",
354 self.web_socket_manager.handle_web_socket)
355
356 def start_ui(self):
357 ui_proc_args = [
358 os.path.join(factory.FACTORY_PACKAGE_PATH, 'test', 'ui.py'),
359 self.options.test_list]
360 if self.options.verbose:
361 ui_proc_args.append('-v')
362 logging.info('Starting ui %s', ui_proc_args)
Jon Salz78c32392012-07-25 14:18:29 +0800363 self.ui_process = Spawn(ui_proc_args)
Jon Salz0697cbf2012-07-04 15:14:04 +0800364 logging.info('Waiting for UI to come up...')
365 self.event_client.wait(
366 lambda event: event.type == Event.Type.UI_READY)
367 logging.info('UI has started')
368
369 def set_visible_test(self, test):
370 if self.visible_test == test:
371 return
Jon Salz2f2d42c2012-07-30 12:30:34 +0800372 if test and not test.has_ui:
373 return
Jon Salz0697cbf2012-07-04 15:14:04 +0800374
375 if test:
376 test.update_state(visible=True)
377 if self.visible_test:
378 self.visible_test.update_state(visible=False)
379 self.visible_test = test
380
Jon Salzd4306c82012-11-30 15:16:36 +0800381 def _log_startup_messages(self):
382 '''Logs the tail of var/log/messages and mosys and EC console logs.'''
383 # TODO(jsalz): This is mostly a copy-and-paste of code in init_states,
384 # for factory-3004.B only. Consolidate and merge back to ToT.
385 if utils.in_chroot():
386 return
387
388 try:
389 var_log_messages = (
390 utils.var_log_messages_before_reboot())
391 logging.info(
392 'Tail of /var/log/messages before last reboot:\n'
393 '%s', ('\n'.join(
394 ' ' + x for x in var_log_messages)))
395 except: # pylint: disable=W0702
396 logging.exception('Unable to grok /var/log/messages')
397
398 try:
399 mosys_log = utils.Spawn(
400 ['mosys', 'eventlog', 'list'],
401 read_stdout=True, log_stderr_on_error=True).stdout_data
402 logging.info('System eventlog from mosys:\n%s\n', mosys_log)
403 except: # pylint: disable=W0702
404 logging.exception('Unable to read mosys eventlog')
405
406 try:
Vic Yang8341dde2013-01-29 16:48:52 +0800407 board = system.GetBoard()
408 ec_console_log = board.GetECConsoleLog()
Jon Salzd4306c82012-11-30 15:16:36 +0800409 logging.info('EC console log after reboot:\n%s\n', ec_console_log)
410 except: # pylint: disable=W0702
411 logging.exception('Error retrieving EC console log')
412
Jon Salz0697cbf2012-07-04 15:14:04 +0800413 def handle_shutdown_complete(self, test, test_state):
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800414 '''
Jon Salz0697cbf2012-07-04 15:14:04 +0800415 Handles the case where a shutdown was detected during a shutdown step.
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800416
Jon Salz0697cbf2012-07-04 15:14:04 +0800417 @param test: The ShutdownStep.
418 @param test_state: The test state.
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800419 '''
Jon Salz0697cbf2012-07-04 15:14:04 +0800420 test_state = test.update_state(increment_shutdown_count=1)
421 logging.info('Detected shutdown (%d of %d)',
422 test_state.shutdown_count, test.iterations)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800423
Jon Salz0697cbf2012-07-04 15:14:04 +0800424 def log_and_update_state(status, error_msg, **kw):
425 self.event_log.Log('rebooted',
426 status=status, error_msg=error_msg, **kw)
Jon Salzd4306c82012-11-30 15:16:36 +0800427 logging.info('Rebooted: status=%s, %s', status,
428 (('error_msg=%s' % error_msg) if error_msg else None))
Jon Salz0697cbf2012-07-04 15:14:04 +0800429 test.update_state(status=status, error_msg=error_msg)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800430
Jon Salz0697cbf2012-07-04 15:14:04 +0800431 if not self.last_shutdown_time:
432 log_and_update_state(status=TestState.FAILED,
433 error_msg='Unable to read shutdown_time')
434 return
Jon Salz258a40c2012-04-19 12:34:01 +0800435
Jon Salz0697cbf2012-07-04 15:14:04 +0800436 now = time.time()
437 logging.info('%.03f s passed since reboot',
438 now - self.last_shutdown_time)
Jon Salz258a40c2012-04-19 12:34:01 +0800439
Jon Salz0697cbf2012-07-04 15:14:04 +0800440 if self.last_shutdown_time > now:
441 test.update_state(status=TestState.FAILED,
442 error_msg='Time moved backward during reboot')
443 elif (isinstance(test, factory.RebootStep) and
444 self.test_list.options.max_reboot_time_secs and
445 (now - self.last_shutdown_time >
446 self.test_list.options.max_reboot_time_secs)):
447 # A reboot took too long; fail. (We don't check this for
448 # HaltSteps, because the machine could be halted for a
449 # very long time, and even unplugged with battery backup,
450 # thus hosing the clock.)
451 log_and_update_state(
452 status=TestState.FAILED,
453 error_msg=('More than %d s elapsed during reboot '
454 '(%.03f s, from %s to %s)' % (
455 self.test_list.options.max_reboot_time_secs,
456 now - self.last_shutdown_time,
457 utils.TimeString(self.last_shutdown_time),
458 utils.TimeString(now))),
459 duration=(now-self.last_shutdown_time))
Jon Salzd4306c82012-11-30 15:16:36 +0800460 self._log_startup_messages()
Jon Salz0697cbf2012-07-04 15:14:04 +0800461 elif test_state.shutdown_count == test.iterations:
462 # Good!
463 log_and_update_state(status=TestState.PASSED,
464 duration=(now - self.last_shutdown_time),
465 error_msg='')
466 elif test_state.shutdown_count > test.iterations:
467 # Shut down too many times
468 log_and_update_state(status=TestState.FAILED,
469 error_msg='Too many shutdowns')
Jon Salzd4306c82012-11-30 15:16:36 +0800470 self._log_startup_messages()
Jon Salz0697cbf2012-07-04 15:14:04 +0800471 elif utils.are_shift_keys_depressed():
472 logging.info('Shift keys are depressed; cancelling restarts')
473 # Abort shutdown
474 log_and_update_state(
475 status=TestState.FAILED,
476 error_msg='Shutdown aborted with double shift keys')
Jon Salza6711d72012-07-18 14:33:03 +0800477 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +0800478 else:
479 def handler():
480 if self._prompt_cancel_shutdown(
481 test, test_state.shutdown_count + 1):
Jon Salza6711d72012-07-18 14:33:03 +0800482 factory.console.info('Shutdown aborted by operator')
Jon Salz0697cbf2012-07-04 15:14:04 +0800483 log_and_update_state(
484 status=TestState.FAILED,
485 error_msg='Shutdown aborted by operator')
Jon Salza6711d72012-07-18 14:33:03 +0800486 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +0800487 return
Jon Salz0405ab52012-03-16 15:26:52 +0800488
Jon Salz0697cbf2012-07-04 15:14:04 +0800489 # Time to shutdown again
490 log_and_update_state(
491 status=TestState.ACTIVE,
492 error_msg='',
493 iteration=test_state.shutdown_count)
Jon Salz73e0fd02012-04-04 11:46:38 +0800494
Jon Salz0697cbf2012-07-04 15:14:04 +0800495 self.event_log.Log('shutdown', operation='reboot')
496 self.state_instance.set_shared_data('shutdown_time',
497 time.time())
498 self.env.shutdown('reboot')
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800499
Jon Salz0697cbf2012-07-04 15:14:04 +0800500 self.on_ui_startup.append(handler)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800501
Jon Salz0697cbf2012-07-04 15:14:04 +0800502 def _prompt_cancel_shutdown(self, test, iteration):
503 if self.options.ui != 'chrome':
504 return False
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800505
Jon Salz0697cbf2012-07-04 15:14:04 +0800506 pending_shutdown_data = {
507 'delay_secs': test.delay_secs,
508 'time': time.time() + test.delay_secs,
509 'operation': test.operation,
510 'iteration': iteration,
511 'iterations': test.iterations,
512 }
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800513
Jon Salz0697cbf2012-07-04 15:14:04 +0800514 # Create a new (threaded) event client since we
515 # don't want to use the event loop for this.
516 with EventClient() as event_client:
517 event_client.post_event(Event(Event.Type.PENDING_SHUTDOWN,
518 **pending_shutdown_data))
519 aborted = event_client.wait(
520 lambda event: event.type == Event.Type.CANCEL_SHUTDOWN,
521 timeout=test.delay_secs) is not None
522 if aborted:
523 event_client.post_event(Event(Event.Type.PENDING_SHUTDOWN))
524 return aborted
Jon Salz258a40c2012-04-19 12:34:01 +0800525
Jon Salz0697cbf2012-07-04 15:14:04 +0800526 def init_states(self):
527 '''
528 Initializes all states on startup.
529 '''
530 for test in self.test_list.get_all_tests():
531 # Make sure the state server knows about all the tests,
532 # defaulting to an untested state.
533 test.update_state(update_parent=False, visible=False)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800534
Jon Salz0697cbf2012-07-04 15:14:04 +0800535 var_log_messages = None
Vic Yanga9c32212012-08-16 20:07:54 +0800536 mosys_log = None
Vic Yange4c275d2012-08-28 01:50:20 +0800537 ec_console_log = None
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800538
Jon Salz0697cbf2012-07-04 15:14:04 +0800539 # Any 'active' tests should be marked as failed now.
540 for test in self.test_list.walk():
Jon Salza6711d72012-07-18 14:33:03 +0800541 if not test.is_leaf():
542 # Don't bother with parents; they will be updated when their
543 # children are updated.
544 continue
545
Jon Salz0697cbf2012-07-04 15:14:04 +0800546 test_state = test.get_state()
547 if test_state.status != TestState.ACTIVE:
548 continue
549 if isinstance(test, factory.ShutdownStep):
550 # Shutdown while the test was active - that's good.
551 self.handle_shutdown_complete(test, test_state)
552 else:
553 # Unexpected shutdown. Grab /var/log/messages for context.
554 if var_log_messages is None:
555 try:
556 var_log_messages = (
557 utils.var_log_messages_before_reboot())
558 # Write it to the log, to make it easier to
559 # correlate with /var/log/messages.
560 logging.info(
561 'Unexpected shutdown. '
562 'Tail of /var/log/messages before last reboot:\n'
563 '%s', ('\n'.join(
564 ' ' + x for x in var_log_messages)))
565 except: # pylint: disable=W0702
566 logging.exception('Unable to grok /var/log/messages')
567 var_log_messages = []
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800568
Jon Salz008f4ea2012-08-28 05:39:45 +0800569 if mosys_log is None and not utils.in_chroot():
570 try:
571 mosys_log = utils.Spawn(
572 ['mosys', 'eventlog', 'list'],
573 read_stdout=True, log_stderr_on_error=True).stdout_data
574 # Write it to the log also.
575 logging.info('System eventlog from mosys:\n%s\n', mosys_log)
576 except: # pylint: disable=W0702
577 logging.exception('Unable to read mosys eventlog')
Vic Yanga9c32212012-08-16 20:07:54 +0800578
Vic Yange4c275d2012-08-28 01:50:20 +0800579 if ec_console_log is None:
580 try:
Vic Yang8341dde2013-01-29 16:48:52 +0800581 board = system.GetBoard()
582 ec_console_log = board.GetECConsoleLog()
Vic Yange4c275d2012-08-28 01:50:20 +0800583 logging.info('EC console log after reboot:\n%s\n', ec_console_log)
Jon Salzfe1f6652012-09-07 05:40:14 +0800584 except: # pylint: disable=W0702
Vic Yange4c275d2012-08-28 01:50:20 +0800585 logging.exception('Error retrieving EC console log')
586
Jon Salz0697cbf2012-07-04 15:14:04 +0800587 error_msg = 'Unexpected shutdown while test was running'
588 self.event_log.Log('end_test',
589 path=test.path,
590 status=TestState.FAILED,
591 invocation=test.get_state().invocation,
592 error_msg=error_msg,
Vic Yanga9c32212012-08-16 20:07:54 +0800593 var_log_messages='\n'.join(var_log_messages),
594 mosys_log=mosys_log)
Jon Salz0697cbf2012-07-04 15:14:04 +0800595 test.update_state(
596 status=TestState.FAILED,
597 error_msg=error_msg)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800598
Jon Salz50efe942012-07-26 11:54:10 +0800599 if not test.never_fails:
600 # For "never_fails" tests (such as "Start"), don't cancel
601 # pending tests, since reboot is expected.
602 factory.console.info('Unexpected shutdown while test %s '
603 'running; cancelling any pending tests',
604 test.path)
605 self.state_instance.set_shared_data('tests_after_shutdown', [])
Jon Salz69806bb2012-07-20 18:05:02 +0800606
Jon Salz008f4ea2012-08-28 05:39:45 +0800607 self.update_skipped_tests()
608
609 def update_skipped_tests(self):
610 '''
611 Updates skipped states based on run_if.
612 '''
613 for t in self.test_list.walk():
614 if t.is_leaf() and t.run_if_table_name:
615 skip = False
616 try:
617 aux = shopfloor.get_selected_aux_data(t.run_if_table_name)
618 value = aux.get(t.run_if_col)
619 if value is not None:
620 skip = (not value) ^ t.run_if_not
621 except ValueError:
622 # Not available; assume it shouldn't be skipped
623 pass
624
625 test_state = t.get_state()
626 if ((not skip) and
627 (test_state.status == TestState.PASSED) and
628 (test_state.error_msg == TestState.SKIPPED_MSG)):
629 # It was marked as skipped before, but now we need to run it.
630 # Mark as untested.
631 t.update_state(skip=skip, status=TestState.UNTESTED, error_msg='')
632 else:
633 t.update_state(skip=skip)
634
Jon Salz0697cbf2012-07-04 15:14:04 +0800635 def show_next_active_test(self):
636 '''
637 Rotates to the next visible active test.
638 '''
639 self.reap_completed_tests()
640 active_tests = [
641 t for t in self.test_list.walk()
642 if t.is_leaf() and t.get_state().status == TestState.ACTIVE]
643 if not active_tests:
644 return
Jon Salz4f6c7172012-06-11 20:45:36 +0800645
Jon Salz0697cbf2012-07-04 15:14:04 +0800646 try:
647 next_test = active_tests[
648 (active_tests.index(self.visible_test) + 1) % len(active_tests)]
649 except ValueError: # visible_test not present in active_tests
650 next_test = active_tests[0]
Jon Salz4f6c7172012-06-11 20:45:36 +0800651
Jon Salz0697cbf2012-07-04 15:14:04 +0800652 self.set_visible_test(next_test)
Jon Salz4f6c7172012-06-11 20:45:36 +0800653
Jon Salz0697cbf2012-07-04 15:14:04 +0800654 def handle_event(self, event):
655 '''
656 Handles an event from the event server.
657 '''
658 handler = self.event_handlers.get(event.type)
659 if handler:
660 handler(event)
661 else:
662 # We don't register handlers for all event types - just ignore
663 # this event.
664 logging.debug('Unbound event type %s', event.type)
Jon Salz4f6c7172012-06-11 20:45:36 +0800665
Vic Yangaabf9fd2013-04-09 18:56:13 +0800666 def check_critical_factory_note(self):
667 '''
668 Returns True if the last factory note is critical.
669 '''
670 notes = self.state_instance.get_shared_data('factory_note', True)
671 return notes and notes[-1]['level'] == 'CRITICAL'
672
Jon Salz0697cbf2012-07-04 15:14:04 +0800673 def run_next_test(self):
674 '''
675 Runs the next eligible test (or tests) in self.tests_to_run.
676 '''
677 self.reap_completed_tests()
Vic Yangaabf9fd2013-04-09 18:56:13 +0800678 if self.tests_to_run and self.check_critical_factory_note():
679 self.tests_to_run.clear()
680 return
Jon Salz0697cbf2012-07-04 15:14:04 +0800681 while self.tests_to_run:
682 logging.debug('Tests to run: %s',
683 [x.path for x in self.tests_to_run])
Jon Salz94eb56f2012-06-12 18:01:12 +0800684
Jon Salz0697cbf2012-07-04 15:14:04 +0800685 test = self.tests_to_run[0]
Jon Salz94eb56f2012-06-12 18:01:12 +0800686
Jon Salz0697cbf2012-07-04 15:14:04 +0800687 if test in self.invocations:
688 logging.info('Next test %s is already running', test.path)
689 self.tests_to_run.popleft()
690 return
Jon Salz94eb56f2012-06-12 18:01:12 +0800691
Jon Salza1412922012-07-23 16:04:17 +0800692 for requirement in test.require_run:
693 for i in requirement.test.walk():
694 if i.get_state().status == TestState.ACTIVE:
Jon Salz304a75d2012-07-06 11:14:15 +0800695 logging.info('Waiting for active test %s to complete '
Jon Salza1412922012-07-23 16:04:17 +0800696 'before running %s', i.path, test.path)
Jon Salz304a75d2012-07-06 11:14:15 +0800697 return
698
Jon Salz0697cbf2012-07-04 15:14:04 +0800699 if self.invocations and not (test.backgroundable and all(
700 [x.backgroundable for x in self.invocations])):
701 logging.debug('Waiting for non-backgroundable tests to '
702 'complete before running %s', test.path)
703 return
Jon Salz94eb56f2012-06-12 18:01:12 +0800704
Jon Salz3e6f5202012-10-15 15:08:29 +0800705 if test.get_state().skip:
706 factory.console.info('Skipping test %s', test.path)
707 test.update_state(status=TestState.PASSED,
708 error_msg=TestState.SKIPPED_MSG)
709 self.tests_to_run.popleft()
710 continue
711
Jon Salz0697cbf2012-07-04 15:14:04 +0800712 self.tests_to_run.popleft()
Jon Salz94eb56f2012-06-12 18:01:12 +0800713
Jon Salz304a75d2012-07-06 11:14:15 +0800714 untested = set()
Jon Salza1412922012-07-23 16:04:17 +0800715 for requirement in test.require_run:
716 for i in requirement.test.walk():
717 if i == test:
Jon Salz304a75d2012-07-06 11:14:15 +0800718 # We've hit this test itself; stop checking
719 break
Jon Salza1412922012-07-23 16:04:17 +0800720 if ((i.get_state().status == TestState.UNTESTED) or
721 (requirement.passed and i.get_state().status !=
722 TestState.PASSED)):
Jon Salz304a75d2012-07-06 11:14:15 +0800723 # Found an untested test; move on to the next
724 # element in require_run.
Jon Salza1412922012-07-23 16:04:17 +0800725 untested.add(i)
Jon Salz304a75d2012-07-06 11:14:15 +0800726 break
727
728 if untested:
729 untested_paths = ', '.join(sorted([x.path for x in untested]))
730 if self.state_instance.get_shared_data('engineering_mode',
731 optional=True):
732 # In engineering mode, we'll let it go.
733 factory.console.warn('In engineering mode; running '
734 '%s even though required tests '
735 '[%s] have not completed',
736 test.path, untested_paths)
737 else:
738 # Not in engineering mode; mark it failed.
739 error_msg = ('Required tests [%s] have not been run yet'
740 % untested_paths)
741 factory.console.error('Not running %s: %s',
742 test.path, error_msg)
743 test.update_state(status=TestState.FAILED,
744 error_msg=error_msg)
745 continue
746
Jon Salz0697cbf2012-07-04 15:14:04 +0800747 if isinstance(test, factory.ShutdownStep):
748 if os.path.exists(NO_REBOOT_FILE):
749 test.update_state(
750 status=TestState.FAILED, increment_count=1,
751 error_msg=('Skipped shutdown since %s is present' %
Jon Salz304a75d2012-07-06 11:14:15 +0800752 NO_REBOOT_FILE))
Jon Salz0697cbf2012-07-04 15:14:04 +0800753 continue
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800754
Jon Salz0697cbf2012-07-04 15:14:04 +0800755 test.update_state(status=TestState.ACTIVE, increment_count=1,
756 error_msg='', shutdown_count=0)
757 if self._prompt_cancel_shutdown(test, 1):
758 self.event_log.Log('reboot_cancelled')
759 test.update_state(
760 status=TestState.FAILED, increment_count=1,
761 error_msg='Shutdown aborted by operator',
762 shutdown_count=0)
chungyiafe8f772012-08-15 19:36:29 +0800763 continue
Jon Salz2f757d42012-06-27 17:06:42 +0800764
Jon Salz0697cbf2012-07-04 15:14:04 +0800765 # Save pending test list in the state server
Jon Salzdbf398f2012-06-14 17:30:01 +0800766 self.state_instance.set_shared_data(
Jon Salz0697cbf2012-07-04 15:14:04 +0800767 'tests_after_shutdown',
768 [t.path for t in self.tests_to_run])
769 # Save shutdown time
770 self.state_instance.set_shared_data('shutdown_time',
771 time.time())
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800772
Jon Salz0697cbf2012-07-04 15:14:04 +0800773 with self.env.lock:
774 self.event_log.Log('shutdown', operation=test.operation)
775 shutdown_result = self.env.shutdown(test.operation)
776 if shutdown_result:
777 # That's all, folks!
778 self.run_queue.put(None)
779 return
780 else:
781 # Just pass (e.g., in the chroot).
782 test.update_state(status=TestState.PASSED)
783 self.state_instance.set_shared_data(
784 'tests_after_shutdown', None)
785 # Send event with no fields to indicate that there is no
786 # longer a pending shutdown.
787 self.event_client.post_event(Event(
788 Event.Type.PENDING_SHUTDOWN))
789 continue
Jon Salz258a40c2012-04-19 12:34:01 +0800790
Cheng-Yi Chiangce05c002013-04-04 02:13:17 +0800791 self._run_test(test, test.iterations, test.retries)
Jon Salz1acc8742012-07-17 17:45:55 +0800792
Cheng-Yi Chiangce05c002013-04-04 02:13:17 +0800793 def _run_test(self, test, iterations_left=None, retries_left=None):
Jon Salz1acc8742012-07-17 17:45:55 +0800794 invoc = TestInvocation(self, test, on_completion=self.run_next_test)
795 new_state = test.update_state(
796 status=TestState.ACTIVE, increment_count=1, error_msg='',
Jon Salzbd42ce12012-09-18 08:03:59 +0800797 invocation=invoc.uuid, iterations_left=iterations_left,
Cheng-Yi Chiangce05c002013-04-04 02:13:17 +0800798 retries_left=retries_left,
Jon Salzbd42ce12012-09-18 08:03:59 +0800799 visible=(self.visible_test == test))
Jon Salz1acc8742012-07-17 17:45:55 +0800800 invoc.count = new_state.count
801
802 self.invocations[test] = invoc
803 if self.visible_test is None and test.has_ui:
804 self.set_visible_test(test)
Vic Yang311ddb82012-09-26 12:08:28 +0800805 self.check_exclusive()
Jon Salz1acc8742012-07-17 17:45:55 +0800806 invoc.start()
Jon Salz5f2a0672012-05-22 17:14:06 +0800807
Vic Yang311ddb82012-09-26 12:08:28 +0800808 def check_exclusive(self):
809 current_exclusive_items = set([
810 item
811 for item in factory.FactoryTest.EXCLUSIVE_OPTIONS
812 if any([test.is_exclusive(item) for test in self.invocations])])
813
814 new_exclusive_items = current_exclusive_items - self.exclusive_items
815 if factory.FactoryTest.EXCLUSIVE_OPTIONS.NETWORKING in new_exclusive_items:
816 logging.info('Disabling network')
817 self.connection_manager.DisableNetworking()
818 if factory.FactoryTest.EXCLUSIVE_OPTIONS.CHARGER in new_exclusive_items:
819 logging.info('Stop controlling charger')
820
821 new_non_exclusive_items = self.exclusive_items - current_exclusive_items
822 if (factory.FactoryTest.EXCLUSIVE_OPTIONS.NETWORKING in
823 new_non_exclusive_items):
824 logging.info('Re-enabling network')
825 self.connection_manager.EnableNetworking()
826 if factory.FactoryTest.EXCLUSIVE_OPTIONS.CHARGER in new_non_exclusive_items:
827 logging.info('Start controlling charger')
828
829 # Only adjust charge state if not excluded
Cheng-Yi Chiangd8186952013-04-04 23:41:14 +0800830 if (factory.FactoryTest.EXCLUSIVE_OPTIONS.CHARGER not in
Vic Yange83d9a12013-04-19 20:00:20 +0800831 current_exclusive_items and not utils.in_chroot()):
Cheng-Yi Chiangd8186952013-04-04 23:41:14 +0800832 if self.charge_manager:
833 self.charge_manager.AdjustChargeState()
834 else:
835 try:
836 system.GetBoard().SetChargeState(Board.ChargeState.CHARGE)
837 except BoardException:
838 logging.exception('Unable to set charge state on this board')
Vic Yang311ddb82012-09-26 12:08:28 +0800839
840 self.exclusive_items = current_exclusive_items
Jon Salz5da61e62012-05-31 13:06:22 +0800841
cychiang21886742012-07-05 15:16:32 +0800842 def check_for_updates(self):
843 '''
844 Schedules an asynchronous check for updates if necessary.
845 '''
846 if not self.test_list.options.update_period_secs:
847 # Not enabled.
848 return
849
850 now = time.time()
851 if self.last_update_check and (
852 now - self.last_update_check <
853 self.test_list.options.update_period_secs):
854 # Not yet time for another check.
855 return
856
857 self.last_update_check = now
858
859 def handle_check_for_update(reached_shopfloor, md5sum, needs_update):
860 if reached_shopfloor:
861 new_update_md5sum = md5sum if needs_update else None
862 if system.SystemInfo.update_md5sum != new_update_md5sum:
863 logging.info('Received new update MD5SUM: %s', new_update_md5sum)
864 system.SystemInfo.update_md5sum = new_update_md5sum
865 self.run_queue.put(self.update_system_info)
866
867 updater.CheckForUpdateAsync(
868 handle_check_for_update,
869 self.test_list.options.shopfloor_timeout_secs)
870
Jon Salza6711d72012-07-18 14:33:03 +0800871 def cancel_pending_tests(self):
872 '''Cancels any tests in the run queue.'''
873 self.run_tests([])
874
Jon Salz0697cbf2012-07-04 15:14:04 +0800875 def run_tests(self, subtrees, untested_only=False):
876 '''
877 Runs tests under subtree.
Jon Salz258a40c2012-04-19 12:34:01 +0800878
Jon Salz0697cbf2012-07-04 15:14:04 +0800879 The tests are run in order unless one fails (then stops).
880 Backgroundable tests are run simultaneously; when a foreground test is
881 encountered, we wait for all active tests to finish before continuing.
Jon Salzb1b39092012-05-03 02:05:09 +0800882
Jon Salz0697cbf2012-07-04 15:14:04 +0800883 @param subtrees: Node or nodes containing tests to run (may either be
884 a single test or a list). Duplicates will be ignored.
885 '''
886 if type(subtrees) != list:
887 subtrees = [subtrees]
Jon Salz258a40c2012-04-19 12:34:01 +0800888
Jon Salz0697cbf2012-07-04 15:14:04 +0800889 # Nodes we've seen so far, to avoid duplicates.
890 seen = set()
Jon Salz94eb56f2012-06-12 18:01:12 +0800891
Jon Salz0697cbf2012-07-04 15:14:04 +0800892 self.tests_to_run = deque()
893 for subtree in subtrees:
894 for test in subtree.walk():
895 if test in seen:
896 continue
897 seen.add(test)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800898
Jon Salz0697cbf2012-07-04 15:14:04 +0800899 if not test.is_leaf():
900 continue
901 if (untested_only and
902 test.get_state().status != TestState.UNTESTED):
903 continue
904 self.tests_to_run.append(test)
905 self.run_next_test()
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800906
Jon Salz0697cbf2012-07-04 15:14:04 +0800907 def reap_completed_tests(self):
908 '''
909 Removes completed tests from the set of active tests.
910
911 Also updates the visible test if it was reaped.
912 '''
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +0800913 test_completed = False
Jon Salz0697cbf2012-07-04 15:14:04 +0800914 for t, v in dict(self.invocations).iteritems():
915 if v.is_completed():
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +0800916 test_completed = True
Jon Salz1acc8742012-07-17 17:45:55 +0800917 new_state = t.update_state(**v.update_state_on_completion)
Jon Salz0697cbf2012-07-04 15:14:04 +0800918 del self.invocations[t]
919
Chun-Ta Lin54e17e42012-09-06 22:05:13 +0800920 # Stop on failure if flag is true.
921 if (self.test_list.options.stop_on_failure and
922 new_state.status == TestState.FAILED):
923 # Clean all the tests to cause goofy to stop.
924 self.tests_to_run = []
925 factory.console.info("Stop on failure triggered. Empty the queue.")
926
Jon Salz1acc8742012-07-17 17:45:55 +0800927 if new_state.iterations_left and new_state.status == TestState.PASSED:
928 # Play it again, Sam!
929 self._run_test(t)
Cheng-Yi Chiangce05c002013-04-04 02:13:17 +0800930 # new_state.retries_left is obtained after update.
931 # For retries_left == 0, test can still be run for the last time.
932 elif (new_state.retries_left >= 0 and
933 new_state.status == TestState.FAILED):
934 # Still have to retry, Sam!
935 self._run_test(t)
Jon Salz1acc8742012-07-17 17:45:55 +0800936
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +0800937 if test_completed:
Vic Yangf01c59f2013-04-19 17:37:56 +0800938 self.log_watcher.KickWatchThread()
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +0800939
Jon Salz0697cbf2012-07-04 15:14:04 +0800940 if (self.visible_test is None or
Jon Salz85a39882012-07-05 16:45:04 +0800941 self.visible_test not in self.invocations):
Jon Salz0697cbf2012-07-04 15:14:04 +0800942 self.set_visible_test(None)
943 # Make the first running test, if any, the visible test
944 for t in self.test_list.walk():
945 if t in self.invocations:
946 self.set_visible_test(t)
947 break
948
Jon Salz85a39882012-07-05 16:45:04 +0800949 def kill_active_tests(self, abort, root=None):
Jon Salz0697cbf2012-07-04 15:14:04 +0800950 '''
951 Kills and waits for all active tests.
952
Jon Salz85a39882012-07-05 16:45:04 +0800953 Args:
954 abort: True to change state of killed tests to FAILED, False for
Jon Salz0697cbf2012-07-04 15:14:04 +0800955 UNTESTED.
Jon Salz85a39882012-07-05 16:45:04 +0800956 root: If set, only kills tests with root as an ancestor.
Jon Salz0697cbf2012-07-04 15:14:04 +0800957 '''
958 self.reap_completed_tests()
959 for test, invoc in self.invocations.items():
Jon Salz85a39882012-07-05 16:45:04 +0800960 if root and not test.has_ancestor(root):
961 continue
962
Jon Salz0697cbf2012-07-04 15:14:04 +0800963 factory.console.info('Killing active test %s...' % test.path)
964 invoc.abort_and_join()
965 factory.console.info('Killed %s' % test.path)
Jon Salz1acc8742012-07-17 17:45:55 +0800966 test.update_state(**invoc.update_state_on_completion)
Jon Salz0697cbf2012-07-04 15:14:04 +0800967 del self.invocations[test]
Jon Salz1acc8742012-07-17 17:45:55 +0800968
Jon Salz0697cbf2012-07-04 15:14:04 +0800969 if not abort:
970 test.update_state(status=TestState.UNTESTED)
971 self.reap_completed_tests()
972
Jon Salz85a39882012-07-05 16:45:04 +0800973 def stop(self, root=None, fail=False):
974 self.kill_active_tests(fail, root)
975 # Remove any tests in the run queue under the root.
976 self.tests_to_run = deque([x for x in self.tests_to_run
977 if root and not x.has_ancestor(root)])
978 self.run_next_test()
Jon Salz0697cbf2012-07-04 15:14:04 +0800979
Jon Salz4712ac72013-02-07 17:12:05 +0800980 def clear_state(self, root=None):
981 self.stop(root)
982 for f in root.walk():
983 if f.is_leaf():
984 f.update_state(status=TestState.UNTESTED)
985
Jon Salz0697cbf2012-07-04 15:14:04 +0800986 def abort_active_tests(self):
987 self.kill_active_tests(True)
988
989 def main(self):
990 try:
991 self.init()
992 self.event_log.Log('goofy_init',
993 success=True)
994 except:
995 if self.event_log:
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800996 try:
Jon Salz0697cbf2012-07-04 15:14:04 +0800997 self.event_log.Log('goofy_init',
998 success=False,
999 trace=traceback.format_exc())
1000 except: # pylint: disable=W0702
1001 pass
1002 raise
1003
1004 self.run()
1005
1006 def update_system_info(self):
1007 '''Updates system info.'''
1008 system_info = system.SystemInfo()
1009 self.state_instance.set_shared_data('system_info', system_info.__dict__)
1010 self.event_client.post_event(Event(Event.Type.SYSTEM_INFO,
1011 system_info=system_info.__dict__))
1012 logging.info('System info: %r', system_info.__dict__)
1013
Jon Salzeb42f0d2012-07-27 19:14:04 +08001014 def update_factory(self, auto_run_on_restart=False, post_update_hook=None):
1015 '''Commences updating factory software.
1016
1017 Args:
1018 auto_run_on_restart: Auto-run when the machine comes back up.
1019 post_update_hook: Code to call after update but immediately before
1020 restart.
1021
1022 Returns:
1023 Never if the update was successful (we just reboot).
1024 False if the update was unnecessary (no update available).
1025 '''
Jon Salz0697cbf2012-07-04 15:14:04 +08001026 self.kill_active_tests(False)
Jon Salza6711d72012-07-18 14:33:03 +08001027 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +08001028
Jon Salz5c344f62012-07-13 14:31:16 +08001029 def pre_update_hook():
1030 if auto_run_on_restart:
1031 self.state_instance.set_shared_data('tests_after_shutdown',
1032 FORCE_AUTO_RUN)
1033 self.state_instance.close()
1034
Jon Salzeb42f0d2012-07-27 19:14:04 +08001035 if updater.TryUpdate(pre_update_hook=pre_update_hook):
1036 if post_update_hook:
1037 post_update_hook()
1038 self.env.shutdown('reboot')
Jon Salz0697cbf2012-07-04 15:14:04 +08001039
Jon Salzcef132a2012-08-30 04:58:08 +08001040 def handle_sigint(self, dummy_signum, dummy_frame):
Jon Salz77c151e2012-08-28 07:20:37 +08001041 logging.error('Received SIGINT')
1042 self.run_queue.put(None)
1043 raise KeyboardInterrupt()
1044
Jon Salz0697cbf2012-07-04 15:14:04 +08001045 def init(self, args=None, env=None):
1046 '''Initializes Goofy.
1047
1048 Args:
1049 args: A list of command-line arguments. Uses sys.argv if
1050 args is None.
1051 env: An Environment instance to use (or None to choose
1052 FakeChrootEnvironment or DUTEnvironment as appropriate).
1053 '''
Jon Salz77c151e2012-08-28 07:20:37 +08001054 signal.signal(signal.SIGINT, self.handle_sigint)
1055
Jon Salz0697cbf2012-07-04 15:14:04 +08001056 parser = OptionParser()
1057 parser.add_option('-v', '--verbose', dest='verbose',
Jon Salz8fa8e832012-07-13 19:04:09 +08001058 action='store_true',
1059 help='Enable debug logging')
Jon Salz0697cbf2012-07-04 15:14:04 +08001060 parser.add_option('--print_test_list', dest='print_test_list',
Jon Salz8fa8e832012-07-13 19:04:09 +08001061 metavar='FILE',
1062 help='Read and print test list FILE, and exit')
Jon Salz0697cbf2012-07-04 15:14:04 +08001063 parser.add_option('--restart', dest='restart',
Jon Salz8fa8e832012-07-13 19:04:09 +08001064 action='store_true',
1065 help='Clear all test state')
Jon Salz0697cbf2012-07-04 15:14:04 +08001066 parser.add_option('--ui', dest='ui', type='choice',
Jon Salz8fa8e832012-07-13 19:04:09 +08001067 choices=['none', 'gtk', 'chrome'],
Jon Salz2f881df2013-02-01 17:00:35 +08001068 default='chrome',
Jon Salz8fa8e832012-07-13 19:04:09 +08001069 help='UI to use')
Jon Salz0697cbf2012-07-04 15:14:04 +08001070 parser.add_option('--ui_scale_factor', dest='ui_scale_factor',
Jon Salz8fa8e832012-07-13 19:04:09 +08001071 type='int', default=1,
1072 help=('Factor by which to scale UI '
1073 '(Chrome UI only)'))
Jon Salz0697cbf2012-07-04 15:14:04 +08001074 parser.add_option('--test_list', dest='test_list',
Jon Salz8fa8e832012-07-13 19:04:09 +08001075 metavar='FILE',
1076 help='Use FILE as test list')
Jon Salzc79a9982012-08-30 04:42:01 +08001077 parser.add_option('--dummy_shopfloor', action='store_true',
1078 help='Use a dummy shopfloor server')
chungyiafe8f772012-08-15 19:36:29 +08001079 parser.add_option('--automation', dest='automation',
1080 action='store_true',
1081 help='Enable automation on running factory test')
Ricky Liang09216dc2013-02-22 17:26:45 +08001082 parser.add_option('--one_pixel_less', dest='one_pixel_less',
1083 action='store_true',
1084 help=('Start Chrome one pixel less than the full screen.'
1085 'Needed by Exynos platform to run GTK.'))
Jon Salz0697cbf2012-07-04 15:14:04 +08001086 (self.options, self.args) = parser.parse_args(args)
1087
Jon Salz46b89562012-07-05 11:49:22 +08001088 # Make sure factory directories exist.
1089 factory.get_log_root()
1090 factory.get_state_root()
1091 factory.get_test_data_root()
1092
Jon Salz0697cbf2012-07-04 15:14:04 +08001093 global _inited_logging # pylint: disable=W0603
1094 if not _inited_logging:
1095 factory.init_logging('goofy', verbose=self.options.verbose)
1096 _inited_logging = True
Jon Salz8fa8e832012-07-13 19:04:09 +08001097
Jon Salz0f996602012-10-03 15:26:48 +08001098 if self.options.print_test_list:
1099 print factory.read_test_list(
1100 self.options.print_test_list).__repr__(recursive=True)
1101 sys.exit(0)
1102
Jon Salzee85d522012-07-17 14:34:46 +08001103 event_log.IncrementBootSequence()
Jon Salz0697cbf2012-07-04 15:14:04 +08001104 self.event_log = EventLog('goofy')
1105
1106 if (not suppress_chroot_warning and
1107 factory.in_chroot() and
1108 self.options.ui == 'gtk' and
1109 os.environ.get('DISPLAY') in [None, '', ':0', ':0.0']):
1110 # That's not going to work! Tell the user how to run
1111 # this way.
1112 logging.warn(GOOFY_IN_CHROOT_WARNING)
1113 time.sleep(1)
1114
1115 if env:
1116 self.env = env
1117 elif factory.in_chroot():
1118 self.env = test_environment.FakeChrootEnvironment()
1119 logging.warn(
1120 'Using chroot environment: will not actually run autotests')
1121 else:
1122 self.env = test_environment.DUTEnvironment()
1123 self.env.goofy = self
1124
1125 if self.options.restart:
1126 state.clear_state()
1127
Jon Salz0697cbf2012-07-04 15:14:04 +08001128 if self.options.ui_scale_factor != 1 and utils.in_qemu():
1129 logging.warn(
1130 'In QEMU; ignoring ui_scale_factor argument')
1131 self.options.ui_scale_factor = 1
1132
1133 logging.info('Started')
1134
1135 self.start_state_server()
1136 self.state_instance.set_shared_data('hwid_cfg', get_hwid_cfg())
1137 self.state_instance.set_shared_data('ui_scale_factor',
Ricky Liang09216dc2013-02-22 17:26:45 +08001138 self.options.ui_scale_factor)
1139 self.state_instance.set_shared_data('one_pixel_less',
1140 self.options.one_pixel_less)
Jon Salz0697cbf2012-07-04 15:14:04 +08001141 self.last_shutdown_time = (
1142 self.state_instance.get_shared_data('shutdown_time', optional=True))
1143 self.state_instance.del_shared_data('shutdown_time', optional=True)
1144
Jon Salzb19ea072013-02-07 16:35:00 +08001145 self.state_instance.del_shared_data('startup_error', optional=True)
Jon Salz0697cbf2012-07-04 15:14:04 +08001146 if not self.options.test_list:
1147 self.options.test_list = find_test_list()
Jon Salzb19ea072013-02-07 16:35:00 +08001148 if self.options.test_list:
Jon Salz0697cbf2012-07-04 15:14:04 +08001149 logging.info('Using test list %s', self.options.test_list)
Jon Salzb19ea072013-02-07 16:35:00 +08001150 try:
1151 self.test_list = factory.read_test_list(
1152 self.options.test_list,
1153 self.state_instance)
1154 except: # pylint: disable=W0702
1155 logging.exception('Unable to read test list %r', self.options.test_list)
1156 self.state_instance.set_shared_data('startup_error',
1157 'Unable to read test list %s\n%s' % (
1158 self.options.test_list,
1159 traceback.format_exc()))
1160 else:
1161 logging.error('No test list found.')
1162 self.state_instance.set_shared_data('startup_error',
1163 'No test list found.')
Jon Salz0697cbf2012-07-04 15:14:04 +08001164
Jon Salzb19ea072013-02-07 16:35:00 +08001165 if not self.test_list:
1166 if self.options.ui == 'chrome':
1167 # Create an empty test list with default options so that the rest of
1168 # startup can proceed.
1169 self.test_list = factory.FactoryTestList(
1170 [], self.state_instance, factory.Options())
1171 else:
1172 # Bail with an error; no point in starting up.
1173 sys.exit('No valid test list; exiting.')
1174
Jon Salz822838b2013-03-25 17:32:33 +08001175 if self.test_list.options.clear_state_on_start:
1176 self.state_instance.clear_test_state()
1177
Jon Salz0697cbf2012-07-04 15:14:04 +08001178 if not self.state_instance.has_shared_data('ui_lang'):
1179 self.state_instance.set_shared_data('ui_lang',
1180 self.test_list.options.ui_lang)
1181 self.state_instance.set_shared_data(
1182 'test_list_options',
1183 self.test_list.options.__dict__)
1184 self.state_instance.test_list = self.test_list
1185
Jon Salz83ef34b2012-11-01 19:46:35 +08001186 if not utils.in_chroot() and self.test_list.options.disable_log_rotation:
1187 open('/var/lib/cleanup_logs_paused', 'w').close()
1188
Jon Salz23926422012-09-01 03:38:13 +08001189 if self.options.dummy_shopfloor:
1190 os.environ[shopfloor.SHOPFLOOR_SERVER_ENV_VAR_NAME] = (
1191 'http://localhost:%d/' % shopfloor.DEFAULT_SERVER_PORT)
1192 self.dummy_shopfloor = Spawn(
1193 [os.path.join(factory.FACTORY_PATH, 'bin', 'shopfloor_server'),
1194 '--dummy'])
1195 elif self.test_list.options.shopfloor_server_url:
1196 shopfloor.set_server_url(self.test_list.options.shopfloor_server_url)
Jon Salz2bf2f6b2013-03-28 18:49:26 +08001197 shopfloor.set_enabled(True)
Jon Salz23926422012-09-01 03:38:13 +08001198
Jon Salz0f996602012-10-03 15:26:48 +08001199 if self.test_list.options.time_sanitizer and not utils.in_chroot():
Jon Salz8fa8e832012-07-13 19:04:09 +08001200 self.time_sanitizer = time_sanitizer.TimeSanitizer(
1201 base_time=time_sanitizer.GetBaseTimeFromFile(
1202 # lsb-factory is written by the factory install shim during
1203 # installation, so it should have a good time obtained from
Jon Salz54882d02012-08-31 01:57:54 +08001204 # the mini-Omaha server. If it's not available, we'll use
1205 # /etc/lsb-factory (which will be much older, but reasonably
1206 # sane) and rely on a shopfloor sync to set a more accurate
1207 # time.
1208 '/usr/local/etc/lsb-factory',
1209 '/etc/lsb-release'))
Jon Salz8fa8e832012-07-13 19:04:09 +08001210 self.time_sanitizer.RunOnce()
1211
Jon Salz0697cbf2012-07-04 15:14:04 +08001212 self.init_states()
1213 self.start_event_server()
1214 self.connection_manager = self.env.create_connection_manager(
Tai-Hsu Lin371351a2012-08-27 14:17:14 +08001215 self.test_list.options.wlans,
1216 self.test_list.options.scan_wifi_period_secs)
Jon Salz0697cbf2012-07-04 15:14:04 +08001217 # Note that we create a log watcher even if
1218 # sync_event_log_period_secs isn't set (no background
1219 # syncing), since we may use it to flush event logs as well.
1220 self.log_watcher = EventLogWatcher(
1221 self.test_list.options.sync_event_log_period_secs,
Jon Salz16d10542012-07-23 12:18:45 +08001222 handle_event_logs_callback=self.handle_event_logs)
Jon Salz0697cbf2012-07-04 15:14:04 +08001223 if self.test_list.options.sync_event_log_period_secs:
1224 self.log_watcher.StartWatchThread()
1225
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +08001226 # Note that we create a system log manager even if
1227 # sync_log_period_secs isn't set (no background
1228 # syncing), since we may kick it to sync logs in its
1229 # thread.
1230 self.system_log_manager = SystemLogManager(
1231 self.test_list.options.sync_log_paths,
1232 self.test_list.options.sync_log_period_secs)
1233 self.system_log_manager.StartSyncThread()
1234
Jon Salz0697cbf2012-07-04 15:14:04 +08001235 self.update_system_info()
1236
Vic Yang4953fc12012-07-26 16:19:53 +08001237 assert ((self.test_list.options.min_charge_pct is None) ==
1238 (self.test_list.options.max_charge_pct is None))
Vic Yange83d9a12013-04-19 20:00:20 +08001239 if utils.in_chroot():
1240 logging.info('In chroot, ignoring charge manager and charge state')
1241 elif self.test_list.options.min_charge_pct is not None:
Vic Yang4953fc12012-07-26 16:19:53 +08001242 self.charge_manager = ChargeManager(self.test_list.options.min_charge_pct,
1243 self.test_list.options.max_charge_pct)
Jon Salzad7353b2012-10-15 16:22:46 +08001244 system.SystemStatus.charge_manager = self.charge_manager
Cheng-Yi Chiangd8186952013-04-04 23:41:14 +08001245 else:
1246 # Goofy should set charger state to charge if charge_manager is disabled.
1247 try:
1248 system.GetBoard().SetChargeState(Board.ChargeState.CHARGE)
1249 except BoardException:
1250 logging.exception('Unable to set charge state on this board')
Vic Yang4953fc12012-07-26 16:19:53 +08001251
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001252 self.core_dump_manager = CoreDumpManager(
1253 self.test_list.options.core_dump_watchlist)
1254
Jon Salz0697cbf2012-07-04 15:14:04 +08001255 os.environ['CROS_FACTORY'] = '1'
1256 os.environ['CROS_DISABLE_SITE_SYSINFO'] = '1'
1257
1258 # Set CROS_UI since some behaviors in ui.py depend on the
1259 # particular UI in use. TODO(jsalz): Remove this (and all
1260 # places it is used) when the GTK UI is removed.
1261 os.environ['CROS_UI'] = self.options.ui
1262
1263 if self.options.ui == 'chrome':
1264 self.env.launch_chrome()
1265 logging.info('Waiting for a web socket connection')
Cheng-Yi Chiangfd8ed392013-03-08 21:37:31 +08001266 self.web_socket_manager.wait()
Jon Salz0697cbf2012-07-04 15:14:04 +08001267
1268 # Wait for the test widget size to be set; this is done in
1269 # an asynchronous RPC so there is a small chance that the
1270 # web socket might be opened first.
1271 for _ in range(100): # 10 s
1272 try:
1273 if self.state_instance.get_shared_data('test_widget_size'):
1274 break
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001275 except KeyError:
Jon Salz0697cbf2012-07-04 15:14:04 +08001276 pass # Retry
1277 time.sleep(0.1) # 100 ms
1278 else:
1279 logging.warn('Never received test_widget_size from UI')
1280 elif self.options.ui == 'gtk':
1281 self.start_ui()
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001282
Ricky Liang650f6bf2012-09-28 13:22:54 +08001283 # Create download path for autotest beforehand or autotests run at
1284 # the same time might fail due to race condition.
1285 if not factory.in_chroot():
1286 utils.TryMakeDirs(os.path.join('/usr/local/autotest', 'tests',
1287 'download'))
1288
Jon Salz0697cbf2012-07-04 15:14:04 +08001289 def state_change_callback(test, test_state):
1290 self.event_client.post_event(
1291 Event(Event.Type.STATE_CHANGE,
1292 path=test.path, state=test_state))
1293 self.test_list.state_change_callback = state_change_callback
Jon Salz73e0fd02012-04-04 11:46:38 +08001294
Jon Salza6711d72012-07-18 14:33:03 +08001295 for handler in self.on_ui_startup:
1296 handler()
1297
1298 self.prespawner = Prespawner()
1299 self.prespawner.start()
1300
Jon Salz0697cbf2012-07-04 15:14:04 +08001301 try:
1302 tests_after_shutdown = self.state_instance.get_shared_data(
1303 'tests_after_shutdown')
1304 except KeyError:
1305 tests_after_shutdown = None
Jon Salz57717ca2012-04-04 16:47:25 +08001306
Jon Salz5c344f62012-07-13 14:31:16 +08001307 force_auto_run = (tests_after_shutdown == FORCE_AUTO_RUN)
1308 if not force_auto_run and tests_after_shutdown is not None:
Jon Salz0697cbf2012-07-04 15:14:04 +08001309 logging.info('Resuming tests after shutdown: %s',
1310 tests_after_shutdown)
Jon Salz0697cbf2012-07-04 15:14:04 +08001311 self.tests_to_run.extend(
1312 self.test_list.lookup_path(t) for t in tests_after_shutdown)
1313 self.run_queue.put(self.run_next_test)
1314 else:
Jon Salz5c344f62012-07-13 14:31:16 +08001315 if force_auto_run or self.test_list.options.auto_run_on_start:
Jon Salz0697cbf2012-07-04 15:14:04 +08001316 self.run_queue.put(
1317 lambda: self.run_tests(self.test_list, untested_only=True))
Jon Salz5c344f62012-07-13 14:31:16 +08001318 self.state_instance.set_shared_data('tests_after_shutdown', None)
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001319
Dean Liao592e4d52013-01-10 20:06:39 +08001320 self.may_disable_cros_shortcut_keys()
1321
1322 def may_disable_cros_shortcut_keys(self):
1323 test_options = self.test_list.options
1324 if test_options.disable_cros_shortcut_keys:
1325 logging.info('Filter ChromeOS shortcut keys.')
1326 self.key_filter = KeyFilter(
1327 unmap_caps_lock=test_options.disable_caps_lock,
1328 caps_lock_keycode=test_options.caps_lock_keycode)
1329 self.key_filter.Start()
1330
Jon Salz0697cbf2012-07-04 15:14:04 +08001331 def run(self):
1332 '''Runs Goofy.'''
1333 # Process events forever.
1334 while self.run_once(True):
1335 pass
Jon Salz73e0fd02012-04-04 11:46:38 +08001336
Jon Salz0697cbf2012-07-04 15:14:04 +08001337 def run_once(self, block=False):
1338 '''Runs all items pending in the event loop.
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001339
Jon Salz0697cbf2012-07-04 15:14:04 +08001340 Args:
1341 block: If true, block until at least one event is processed.
Jon Salz7c15e8b2012-06-19 17:10:37 +08001342
Jon Salz0697cbf2012-07-04 15:14:04 +08001343 Returns:
1344 True to keep going or False to shut down.
1345 '''
1346 events = utils.DrainQueue(self.run_queue)
cychiang21886742012-07-05 15:16:32 +08001347 while not events:
Jon Salz0697cbf2012-07-04 15:14:04 +08001348 # Nothing on the run queue.
1349 self._run_queue_idle()
1350 if block:
1351 # Block for at least one event...
cychiang21886742012-07-05 15:16:32 +08001352 try:
1353 events.append(self.run_queue.get(timeout=RUN_QUEUE_TIMEOUT_SECS))
1354 except Queue.Empty:
1355 # Keep going (calling _run_queue_idle() again at the top of
1356 # the loop)
1357 continue
Jon Salz0697cbf2012-07-04 15:14:04 +08001358 # ...and grab anything else that showed up at the same
1359 # time.
1360 events.extend(utils.DrainQueue(self.run_queue))
cychiang21886742012-07-05 15:16:32 +08001361 else:
1362 break
Jon Salz51528e12012-07-02 18:54:45 +08001363
Jon Salz0697cbf2012-07-04 15:14:04 +08001364 for event in events:
1365 if not event:
1366 # Shutdown request.
1367 self.run_queue.task_done()
1368 return False
Jon Salz51528e12012-07-02 18:54:45 +08001369
Jon Salz0697cbf2012-07-04 15:14:04 +08001370 try:
1371 event()
Jon Salz85a39882012-07-05 16:45:04 +08001372 except: # pylint: disable=W0702
1373 logging.exception('Error in event loop')
Jon Salz0697cbf2012-07-04 15:14:04 +08001374 self.record_exception(traceback.format_exception_only(
1375 *sys.exc_info()[:2]))
1376 # But keep going
1377 finally:
1378 self.run_queue.task_done()
1379 return True
Jon Salz0405ab52012-03-16 15:26:52 +08001380
Jon Salz0e6532d2012-10-25 16:30:11 +08001381 def _should_sync_time(self, foreground=False):
1382 '''Returns True if we should attempt syncing time with shopfloor.
1383
1384 Args:
1385 foreground: If True, synchronizes even if background syncing
1386 is disabled (e.g., in explicit sync requests from the
1387 SyncShopfloor test).
1388 '''
1389 return ((foreground or
1390 self.test_list.options.sync_time_period_secs) and
Jon Salz54882d02012-08-31 01:57:54 +08001391 self.time_sanitizer and
1392 (not self.time_synced) and
1393 (not factory.in_chroot()))
1394
Jon Salz0e6532d2012-10-25 16:30:11 +08001395 def sync_time_with_shopfloor_server(self, foreground=False):
Jon Salz54882d02012-08-31 01:57:54 +08001396 '''Syncs time with shopfloor server, if not yet synced.
1397
Jon Salz0e6532d2012-10-25 16:30:11 +08001398 Args:
1399 foreground: If True, synchronizes even if background syncing
1400 is disabled (e.g., in explicit sync requests from the
1401 SyncShopfloor test).
1402
Jon Salz54882d02012-08-31 01:57:54 +08001403 Returns:
1404 False if no time sanitizer is available, or True if this sync (or a
1405 previous sync) succeeded.
1406
1407 Raises:
1408 Exception if unable to contact the shopfloor server.
1409 '''
Jon Salz0e6532d2012-10-25 16:30:11 +08001410 if self._should_sync_time(foreground):
Jon Salz54882d02012-08-31 01:57:54 +08001411 self.time_sanitizer.SyncWithShopfloor()
1412 self.time_synced = True
1413 return self.time_synced
1414
Jon Salzb92c5112012-09-21 15:40:11 +08001415 def log_disk_space_stats(self):
1416 if not self.test_list.options.log_disk_space_period_secs:
1417 return
1418
1419 now = time.time()
1420 if (self.last_log_disk_space_time and
1421 now - self.last_log_disk_space_time <
1422 self.test_list.options.log_disk_space_period_secs):
1423 return
1424 self.last_log_disk_space_time = now
1425
1426 try:
Jon Salz3c493bb2013-02-07 17:24:58 +08001427 message = disk_space.FormatSpaceUsedAll()
1428 if message != self.last_log_disk_space_message:
1429 logging.info(message)
1430 self.last_log_disk_space_message = message
Jon Salzb92c5112012-09-21 15:40:11 +08001431 except: # pylint: disable=W0702
1432 logging.exception('Unable to get disk space used')
1433
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001434 def check_core_dump(self):
1435 '''Checks if there is any core dumped file.
1436
1437 Removes unwanted core dump files immediately.
1438 Syncs those files matching watch list to server with a delay between
1439 each sync. After the files have been synced to server, deletes the files.
1440 '''
1441 core_dump_files = self.core_dump_manager.ScanFiles()
1442 if core_dump_files:
1443 now = time.time()
1444 if (self.last_kick_sync_time and now - self.last_kick_sync_time <
1445 self.test_list.options.kick_sync_min_interval_secs):
1446 return
1447 self.last_kick_sync_time = now
1448
1449 # Sends event to server
1450 self.event_log.Log('core_dumped', files=core_dump_files)
1451 self.log_watcher.KickWatchThread()
1452
1453 # Syncs files to server
1454 self.system_log_manager.KickSyncThread(
1455 core_dump_files, self.core_dump_manager.ClearFiles)
1456
Jon Salz8fa8e832012-07-13 19:04:09 +08001457 def sync_time_in_background(self):
Jon Salzb22d1172012-08-06 10:38:57 +08001458 '''Writes out current time and tries to sync with shopfloor server.'''
1459 if not self.time_sanitizer:
1460 return
1461
1462 # Write out the current time.
1463 self.time_sanitizer.SaveTime()
1464
Jon Salz54882d02012-08-31 01:57:54 +08001465 if not self._should_sync_time():
Jon Salz8fa8e832012-07-13 19:04:09 +08001466 return
1467
1468 now = time.time()
1469 if self.last_sync_time and (
1470 now - self.last_sync_time <
1471 self.test_list.options.sync_time_period_secs):
1472 # Not yet time for another check.
1473 return
1474 self.last_sync_time = now
1475
1476 def target():
1477 try:
Jon Salz54882d02012-08-31 01:57:54 +08001478 self.sync_time_with_shopfloor_server()
Jon Salz8fa8e832012-07-13 19:04:09 +08001479 except: # pylint: disable=W0702
1480 # Oh well. Log an error (but no trace)
1481 logging.info(
1482 'Unable to get time from shopfloor server: %s',
1483 utils.FormatExceptionOnly())
1484
1485 thread = threading.Thread(target=target)
1486 thread.daemon = True
1487 thread.start()
1488
Jon Salz0697cbf2012-07-04 15:14:04 +08001489 def _run_queue_idle(self):
Vic Yang4953fc12012-07-26 16:19:53 +08001490 '''Invoked when the run queue has no events.
1491
1492 This method must not raise exception.
1493 '''
Jon Salzb22d1172012-08-06 10:38:57 +08001494 now = time.time()
1495 if (self.last_idle and
1496 now < (self.last_idle + RUN_QUEUE_TIMEOUT_SECS - 1)):
1497 # Don't run more often than once every (RUN_QUEUE_TIMEOUT_SECS -
1498 # 1) seconds.
1499 return
1500
1501 self.last_idle = now
1502
Vic Yang311ddb82012-09-26 12:08:28 +08001503 self.check_exclusive()
cychiang21886742012-07-05 15:16:32 +08001504 self.check_for_updates()
Jon Salz8fa8e832012-07-13 19:04:09 +08001505 self.sync_time_in_background()
Jon Salzb92c5112012-09-21 15:40:11 +08001506 self.log_disk_space_stats()
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001507 self.check_core_dump()
Jon Salz57717ca2012-04-04 16:47:25 +08001508
Jon Salz16d10542012-07-23 12:18:45 +08001509 def handle_event_logs(self, log_name, chunk):
Jon Salz0697cbf2012-07-04 15:14:04 +08001510 '''Callback for event watcher.
Jon Salz258a40c2012-04-19 12:34:01 +08001511
Jon Salz0697cbf2012-07-04 15:14:04 +08001512 Attempts to upload the event logs to the shopfloor server.
1513 '''
1514 description = 'event logs (%s, %d bytes)' % (log_name, len(chunk))
1515 start_time = time.time()
Jon Salz0697cbf2012-07-04 15:14:04 +08001516 shopfloor_client = shopfloor.get_instance(
1517 detect=True,
1518 timeout=self.test_list.options.shopfloor_timeout_secs)
Jon Salzb10cf512012-08-09 17:29:21 +08001519 shopfloor_client.UploadEvent(log_name, Binary(chunk))
Jon Salz0697cbf2012-07-04 15:14:04 +08001520 logging.info(
1521 'Successfully synced %s in %.03f s',
1522 description, time.time() - start_time)
Jon Salz57717ca2012-04-04 16:47:25 +08001523
Jon Salz0697cbf2012-07-04 15:14:04 +08001524 def run_tests_with_status(self, statuses_to_run, starting_at=None,
1525 root=None):
1526 '''Runs all top-level tests with a particular status.
Jon Salz0405ab52012-03-16 15:26:52 +08001527
Jon Salz0697cbf2012-07-04 15:14:04 +08001528 All active tests, plus any tests to re-run, are reset.
Jon Salz57717ca2012-04-04 16:47:25 +08001529
Jon Salz0697cbf2012-07-04 15:14:04 +08001530 Args:
1531 starting_at: If provided, only auto-runs tests beginning with
1532 this test.
1533 '''
1534 root = root or self.test_list
Jon Salz57717ca2012-04-04 16:47:25 +08001535
Jon Salz0697cbf2012-07-04 15:14:04 +08001536 if starting_at:
1537 # Make sure they passed a test, not a string.
1538 assert isinstance(starting_at, factory.FactoryTest)
Jon Salz0405ab52012-03-16 15:26:52 +08001539
Jon Salz0697cbf2012-07-04 15:14:04 +08001540 tests_to_reset = []
1541 tests_to_run = []
Jon Salz0405ab52012-03-16 15:26:52 +08001542
Jon Salz0697cbf2012-07-04 15:14:04 +08001543 found_starting_at = False
Jon Salz0405ab52012-03-16 15:26:52 +08001544
Jon Salz0697cbf2012-07-04 15:14:04 +08001545 for test in root.get_top_level_tests():
1546 if starting_at:
1547 if test == starting_at:
1548 # We've found starting_at; do auto-run on all
1549 # subsequent tests.
1550 found_starting_at = True
1551 if not found_starting_at:
1552 # Don't start this guy yet
1553 continue
Jon Salz0405ab52012-03-16 15:26:52 +08001554
Jon Salz0697cbf2012-07-04 15:14:04 +08001555 status = test.get_state().status
1556 if status == TestState.ACTIVE or status in statuses_to_run:
1557 # Reset the test (later; we will need to abort
1558 # all active tests first).
1559 tests_to_reset.append(test)
1560 if status in statuses_to_run:
1561 tests_to_run.append(test)
Jon Salz0405ab52012-03-16 15:26:52 +08001562
Jon Salz0697cbf2012-07-04 15:14:04 +08001563 self.abort_active_tests()
Jon Salz258a40c2012-04-19 12:34:01 +08001564
Jon Salz0697cbf2012-07-04 15:14:04 +08001565 # Reset all statuses of the tests to run (in case any tests were active;
1566 # we want them to be run again).
1567 for test_to_reset in tests_to_reset:
1568 for test in test_to_reset.walk():
1569 test.update_state(status=TestState.UNTESTED)
Jon Salz57717ca2012-04-04 16:47:25 +08001570
Jon Salz0697cbf2012-07-04 15:14:04 +08001571 self.run_tests(tests_to_run, untested_only=True)
Jon Salz0405ab52012-03-16 15:26:52 +08001572
Jon Salz0697cbf2012-07-04 15:14:04 +08001573 def restart_tests(self, root=None):
1574 '''Restarts all tests.'''
1575 root = root or self.test_list
Jon Salz0405ab52012-03-16 15:26:52 +08001576
Jon Salz0697cbf2012-07-04 15:14:04 +08001577 self.abort_active_tests()
1578 for test in root.walk():
1579 test.update_state(status=TestState.UNTESTED)
1580 self.run_tests(root)
Hung-Te Lin96632362012-03-20 21:14:18 +08001581
Jon Salz0697cbf2012-07-04 15:14:04 +08001582 def auto_run(self, starting_at=None, root=None):
1583 '''"Auto-runs" tests that have not been run yet.
Hung-Te Lin96632362012-03-20 21:14:18 +08001584
Jon Salz0697cbf2012-07-04 15:14:04 +08001585 Args:
1586 starting_at: If provide, only auto-runs tests beginning with
1587 this test.
1588 '''
1589 root = root or self.test_list
1590 self.run_tests_with_status([TestState.UNTESTED, TestState.ACTIVE],
1591 starting_at=starting_at,
1592 root=root)
Jon Salz968e90b2012-03-18 16:12:43 +08001593
Jon Salz0697cbf2012-07-04 15:14:04 +08001594 def re_run_failed(self, root=None):
1595 '''Re-runs failed tests.'''
1596 root = root or self.test_list
1597 self.run_tests_with_status([TestState.FAILED], root=root)
Jon Salz57717ca2012-04-04 16:47:25 +08001598
Jon Salz0697cbf2012-07-04 15:14:04 +08001599 def show_review_information(self):
1600 '''Event handler for showing review information screen.
Jon Salz57717ca2012-04-04 16:47:25 +08001601
Jon Salz0697cbf2012-07-04 15:14:04 +08001602 The information screene is rendered by main UI program (ui.py), so in
1603 goofy we only need to kill all active tests, set them as untested, and
1604 clear remaining tests.
1605 '''
1606 self.kill_active_tests(False)
Jon Salza6711d72012-07-18 14:33:03 +08001607 self.cancel_pending_tests()
Jon Salz57717ca2012-04-04 16:47:25 +08001608
Jon Salz0697cbf2012-07-04 15:14:04 +08001609 def handle_switch_test(self, event):
1610 '''Switches to a particular test.
Jon Salz0405ab52012-03-16 15:26:52 +08001611
Jon Salz0697cbf2012-07-04 15:14:04 +08001612 @param event: The SWITCH_TEST event.
1613 '''
1614 test = self.test_list.lookup_path(event.path)
1615 if not test:
1616 logging.error('Unknown test %r', event.key)
1617 return
Jon Salz73e0fd02012-04-04 11:46:38 +08001618
Jon Salz0697cbf2012-07-04 15:14:04 +08001619 invoc = self.invocations.get(test)
1620 if invoc and test.backgroundable:
1621 # Already running: just bring to the front if it
1622 # has a UI.
1623 logging.info('Setting visible test to %s', test.path)
Jon Salz36fbbb52012-07-05 13:45:06 +08001624 self.set_visible_test(test)
Jon Salz0697cbf2012-07-04 15:14:04 +08001625 return
Jon Salz73e0fd02012-04-04 11:46:38 +08001626
Jon Salz0697cbf2012-07-04 15:14:04 +08001627 self.abort_active_tests()
1628 for t in test.walk():
1629 t.update_state(status=TestState.UNTESTED)
Jon Salz73e0fd02012-04-04 11:46:38 +08001630
Jon Salz0697cbf2012-07-04 15:14:04 +08001631 if self.test_list.options.auto_run_on_keypress:
1632 self.auto_run(starting_at=test)
1633 else:
1634 self.run_tests(test)
Jon Salz73e0fd02012-04-04 11:46:38 +08001635
Jon Salz0697cbf2012-07-04 15:14:04 +08001636 def wait(self):
1637 '''Waits for all pending invocations.
1638
1639 Useful for testing.
1640 '''
Jon Salz1acc8742012-07-17 17:45:55 +08001641 while self.invocations:
1642 for k, v in self.invocations.iteritems():
1643 logging.info('Waiting for %s to complete...', k)
1644 v.thread.join()
1645 self.reap_completed_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +08001646
1647 def check_exceptions(self):
1648 '''Raises an error if any exceptions have occurred in
1649 invocation threads.'''
1650 if self.exceptions:
1651 raise RuntimeError('Exception in invocation thread: %r' %
1652 self.exceptions)
1653
1654 def record_exception(self, msg):
1655 '''Records an exception in an invocation thread.
1656
1657 An exception with the given message will be rethrown when
1658 Goofy is destroyed.'''
1659 self.exceptions.append(msg)
Jon Salz73e0fd02012-04-04 11:46:38 +08001660
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001661
1662if __name__ == '__main__':
Jon Salz77c151e2012-08-28 07:20:37 +08001663 goofy = Goofy()
1664 try:
1665 goofy.main()
Jon Salz0f996602012-10-03 15:26:48 +08001666 except SystemExit:
1667 # Propagate SystemExit without logging.
1668 raise
Jon Salz31373eb2012-09-21 16:19:49 +08001669 except:
Jon Salz0f996602012-10-03 15:26:48 +08001670 # Log the error before trying to shut down (unless it's a graceful
1671 # exit).
Jon Salz31373eb2012-09-21 16:19:49 +08001672 logging.exception('Error in main loop')
1673 raise
Jon Salz77c151e2012-08-28 07:20:37 +08001674 finally:
1675 goofy.destroy()