blob: cf6b51ecc1916e053702c6bb50b84293d8ebabe3 [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
Jon Salzb92c5112012-09-21 15:40:11 +080040from cros.factory.system import disk_space
jcliangcd688182012-08-20 21:01:26 +080041from cros.factory.test import factory
42from cros.factory.test import state
Jon Salz51528e12012-07-02 18:54:45 +080043from cros.factory.test import shopfloor
Jon Salz83591782012-06-26 11:09:58 +080044from cros.factory.test import utils
45from cros.factory.test.event import Event
46from cros.factory.test.event import EventClient
47from cros.factory.test.event import EventServer
jcliangcd688182012-08-20 21:01:26 +080048from cros.factory.test.factory import TestState
Dean Liao592e4d52013-01-10 20:06:39 +080049from cros.factory.tools.key_filter import KeyFilter
Jon Salz78c32392012-07-25 14:18:29 +080050from cros.factory.utils.process_utils import Spawn
Hung-Te Linf2f78f72012-02-08 19:27:11 +080051
52
Jon Salz2f757d42012-06-27 17:06:42 +080053CUSTOM_DIR = os.path.join(factory.FACTORY_PATH, 'custom')
Hung-Te Linf2f78f72012-02-08 19:27:11 +080054HWID_CFG_PATH = '/usr/local/share/chromeos-hwid/cfg'
Chun-ta Lin279e7e92013-02-19 17:40:39 +080055CACHES_DIR = os.path.join(factory.get_state_root(), "caches")
Hung-Te Linf2f78f72012-02-08 19:27:11 +080056
Jon Salz8796e362012-05-24 11:39:09 +080057# File that suppresses reboot if present (e.g., for development).
58NO_REBOOT_FILE = '/var/log/factory.noreboot'
59
Jon Salz5c344f62012-07-13 14:31:16 +080060# Value for tests_after_shutdown that forces auto-run (e.g., after
61# a factory update, when the available set of tests might change).
62FORCE_AUTO_RUN = 'force_auto_run'
63
cychiang21886742012-07-05 15:16:32 +080064RUN_QUEUE_TIMEOUT_SECS = 10
65
Jon Salz758e6cc2012-04-03 15:47:07 +080066GOOFY_IN_CHROOT_WARNING = '\n' + ('*' * 70) + '''
67You are running Goofy inside the chroot. Autotests are not supported.
68
69To use Goofy in the chroot, first install an Xvnc server:
70
Jon Salz0697cbf2012-07-04 15:14:04 +080071 sudo apt-get install tightvncserver
Jon Salz758e6cc2012-04-03 15:47:07 +080072
73...and then start a VNC X server outside the chroot:
74
Jon Salz0697cbf2012-07-04 15:14:04 +080075 vncserver :10 &
76 vncviewer :10
Jon Salz758e6cc2012-04-03 15:47:07 +080077
78...and run Goofy as follows:
79
Jon Salz0697cbf2012-07-04 15:14:04 +080080 env --unset=XAUTHORITY DISPLAY=localhost:10 python goofy.py
Jon Salz758e6cc2012-04-03 15:47:07 +080081''' + ('*' * 70)
Jon Salz73e0fd02012-04-04 11:46:38 +080082suppress_chroot_warning = False
Hung-Te Linf2f78f72012-02-08 19:27:11 +080083
84def get_hwid_cfg():
Jon Salz0697cbf2012-07-04 15:14:04 +080085 '''
86 Returns the HWID config tag, or an empty string if none can be found.
87 '''
88 if 'CROS_HWID' in os.environ:
89 return os.environ['CROS_HWID']
90 if os.path.exists(HWID_CFG_PATH):
91 with open(HWID_CFG_PATH, 'rt') as hwid_cfg_handle:
92 return hwid_cfg_handle.read().strip()
93 return ''
Hung-Te Linf2f78f72012-02-08 19:27:11 +080094
95
96def find_test_list():
Jon Salz0697cbf2012-07-04 15:14:04 +080097 '''
98 Returns the path to the active test list, based on the HWID config tag.
Jon Salzfb615892013-02-01 18:04:35 +080099
100 The algorithm is:
101
102 - Try $FACTORY/test_lists/active (the symlink reflecting the option chosen
103 in the UI).
104 - For each of $FACTORY/custom, $FACTORY/test_lists (and
105 autotest/site_tests/suite_Factory for backward compatibility):
106 - Try test_list_${hwid_cfg} (if hwid_cfg is set)
107 - Try test_list
108 - Try test_list.generic
Jon Salz0697cbf2012-07-04 15:14:04 +0800109 '''
Jon Salzfb615892013-02-01 18:04:35 +0800110 # If the 'active' symlink is present, that trumps everything else.
111 if os.path.lexists(factory.ACTIVE_TEST_LIST_SYMLINK):
112 return os.path.realpath(factory.ACTIVE_TEST_LIST_SYMLINK)
113
Jon Salz0697cbf2012-07-04 15:14:04 +0800114 hwid_cfg = get_hwid_cfg()
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800115
Jon Salzfb615892013-02-01 18:04:35 +0800116 search_dirs = [CUSTOM_DIR, factory.TEST_LISTS_PATH]
Jon Salz4be56b02012-12-22 07:30:46 +0800117 if not utils.in_chroot():
118 # Also look in suite_Factory. For backward compatibility only;
119 # new boards should just put the test list in the "test_lists"
120 # directory.
121 search_dirs.insert(0, os.path.join(
122 os.path.dirname(factory.FACTORY_PATH),
123 'autotest', 'site_tests', 'suite_Factory'))
Jon Salz2f757d42012-06-27 17:06:42 +0800124
Jon Salzfb615892013-02-01 18:04:35 +0800125
126 search_files = []
Jon Salz0697cbf2012-07-04 15:14:04 +0800127 if hwid_cfg:
Jon Salzfb615892013-02-01 18:04:35 +0800128 search_files += [hwid_cfg]
129 search_files += ['test_list', 'test_list.generic']
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800130
Jon Salz0697cbf2012-07-04 15:14:04 +0800131 for d in search_dirs:
132 for f in search_files:
133 test_list = os.path.join(d, f)
134 if os.path.exists(test_list):
135 return test_list
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800136
Jon Salz0697cbf2012-07-04 15:14:04 +0800137 logging.warn('Cannot find test lists named any of %s in any of %s',
138 search_files, search_dirs)
139 return None
Jon Salz73e0fd02012-04-04 11:46:38 +0800140
Jon Salzfb615892013-02-01 18:04:35 +0800141
Jon Salz73e0fd02012-04-04 11:46:38 +0800142_inited_logging = False
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800143
144class Goofy(object):
Jon Salz0697cbf2012-07-04 15:14:04 +0800145 '''
146 The main factory flow.
147
148 Note that all methods in this class must be invoked from the main
149 (event) thread. Other threads, such as callbacks and TestInvocation
150 methods, should instead post events on the run queue.
151
152 TODO: Unit tests. (chrome-os-partner:7409)
153
154 Properties:
155 uuid: A unique UUID for this invocation of Goofy.
156 state_instance: An instance of FactoryState.
157 state_server: The FactoryState XML/RPC server.
158 state_server_thread: A thread running state_server.
159 event_server: The EventServer socket server.
160 event_server_thread: A thread running event_server.
161 event_client: A client to the event server.
162 connection_manager: The connection_manager object.
Jon Salz0697cbf2012-07-04 15:14:04 +0800163 ui_process: The factory ui process object.
164 run_queue: A queue of callbacks to invoke from the main thread.
165 invocations: A map from FactoryTest objects to the corresponding
166 TestInvocations objects representing active tests.
167 tests_to_run: A deque of tests that should be run when the current
168 test(s) complete.
169 options: Command-line options.
170 args: Command-line args.
171 test_list: The test list.
172 event_handlers: Map of Event.Type to the method used to handle that
173 event. If the method has an 'event' argument, the event is passed
174 to the handler.
175 exceptions: Exceptions encountered in invocation threads.
Jon Salz3c493bb2013-02-07 17:24:58 +0800176 last_log_disk_space_message: The last message we logged about disk space
177 (to avoid duplication).
Jon Salz0697cbf2012-07-04 15:14:04 +0800178 '''
179 def __init__(self):
180 self.uuid = str(uuid.uuid4())
181 self.state_instance = None
182 self.state_server = None
183 self.state_server_thread = None
Jon Salz16d10542012-07-23 12:18:45 +0800184 self.goofy_rpc = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800185 self.event_server = None
186 self.event_server_thread = None
187 self.event_client = None
188 self.connection_manager = None
Vic Yang4953fc12012-07-26 16:19:53 +0800189 self.charge_manager = None
Jon Salz8fa8e832012-07-13 19:04:09 +0800190 self.time_sanitizer = None
191 self.time_synced = False
Jon Salz0697cbf2012-07-04 15:14:04 +0800192 self.log_watcher = None
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +0800193 self.system_log_manager = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800194 self.event_log = None
195 self.prespawner = None
196 self.ui_process = None
Jon Salzc79a9982012-08-30 04:42:01 +0800197 self.dummy_shopfloor = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800198 self.run_queue = Queue.Queue()
199 self.invocations = {}
200 self.tests_to_run = deque()
201 self.visible_test = None
202 self.chrome = None
203
204 self.options = None
205 self.args = None
206 self.test_list = None
207 self.on_ui_startup = []
208 self.env = None
Jon Salzb22d1172012-08-06 10:38:57 +0800209 self.last_idle = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800210 self.last_shutdown_time = None
cychiang21886742012-07-05 15:16:32 +0800211 self.last_update_check = None
Jon Salz8fa8e832012-07-13 19:04:09 +0800212 self.last_sync_time = None
Jon Salzb92c5112012-09-21 15:40:11 +0800213 self.last_log_disk_space_time = None
Jon Salz3c493bb2013-02-07 17:24:58 +0800214 self.last_log_disk_space_message = None
Vic Yang311ddb82012-09-26 12:08:28 +0800215 self.exclusive_items = set()
Jon Salz0f996602012-10-03 15:26:48 +0800216 self.event_log = None
Dean Liao592e4d52013-01-10 20:06:39 +0800217 self.key_filter = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800218
Jon Salz85a39882012-07-05 16:45:04 +0800219 def test_or_root(event, parent_or_group=True):
220 '''Returns the test affected by a particular event.
221
222 Args:
223 event: The event containing an optional 'path' attribute.
224 parent_on_group: If True, returns the top-level parent for a test (the
225 root node of the tests that need to be run together if the given test
226 path is to be run).
227 '''
Jon Salz0697cbf2012-07-04 15:14:04 +0800228 try:
229 path = event.path
230 except AttributeError:
231 path = None
232
233 if path:
Jon Salz85a39882012-07-05 16:45:04 +0800234 test = self.test_list.lookup_path(path)
235 if parent_or_group:
236 test = test.get_top_level_parent_or_group()
237 return test
Jon Salz0697cbf2012-07-04 15:14:04 +0800238 else:
239 return self.test_list
240
241 self.event_handlers = {
242 Event.Type.SWITCH_TEST: self.handle_switch_test,
243 Event.Type.SHOW_NEXT_ACTIVE_TEST:
244 lambda event: self.show_next_active_test(),
245 Event.Type.RESTART_TESTS:
246 lambda event: self.restart_tests(root=test_or_root(event)),
247 Event.Type.AUTO_RUN:
248 lambda event: self.auto_run(root=test_or_root(event)),
249 Event.Type.RE_RUN_FAILED:
250 lambda event: self.re_run_failed(root=test_or_root(event)),
251 Event.Type.RUN_TESTS_WITH_STATUS:
252 lambda event: self.run_tests_with_status(
253 event.status,
254 root=test_or_root(event)),
255 Event.Type.REVIEW:
256 lambda event: self.show_review_information(),
257 Event.Type.UPDATE_SYSTEM_INFO:
258 lambda event: self.update_system_info(),
Jon Salz0697cbf2012-07-04 15:14:04 +0800259 Event.Type.STOP:
Jon Salz85a39882012-07-05 16:45:04 +0800260 lambda event: self.stop(root=test_or_root(event, False),
261 fail=getattr(event, 'fail', False)),
Jon Salz36fbbb52012-07-05 13:45:06 +0800262 Event.Type.SET_VISIBLE_TEST:
263 lambda event: self.set_visible_test(
264 self.test_list.lookup_path(event.path)),
Jon Salz4712ac72013-02-07 17:12:05 +0800265 Event.Type.CLEAR_STATE:
266 lambda event: self.clear_state(self.test_list.lookup_path(event.path)),
Jon Salz0697cbf2012-07-04 15:14:04 +0800267 }
268
269 self.exceptions = []
270 self.web_socket_manager = None
271
272 def destroy(self):
273 if self.chrome:
274 self.chrome.kill()
275 self.chrome = None
Jon Salzc79a9982012-08-30 04:42:01 +0800276 if self.dummy_shopfloor:
277 self.dummy_shopfloor.kill()
278 self.dummy_shopfloor = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800279 if self.ui_process:
280 utils.kill_process_tree(self.ui_process, 'ui')
281 self.ui_process = None
282 if self.web_socket_manager:
283 logging.info('Stopping web sockets')
284 self.web_socket_manager.close()
285 self.web_socket_manager = None
286 if self.state_server_thread:
287 logging.info('Stopping state server')
288 self.state_server.shutdown()
289 self.state_server_thread.join()
290 self.state_server.server_close()
291 self.state_server_thread = None
292 if self.state_instance:
293 self.state_instance.close()
294 if self.event_server_thread:
295 logging.info('Stopping event server')
296 self.event_server.shutdown() # pylint: disable=E1101
297 self.event_server_thread.join()
298 self.event_server.server_close()
299 self.event_server_thread = None
300 if self.log_watcher:
301 if self.log_watcher.IsThreadStarted():
302 self.log_watcher.StopWatchThread()
303 self.log_watcher = None
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +0800304 if self.system_log_manager:
305 if self.system_log_manager.IsThreadRunning():
306 self.system_log_manager.StopSyncThread()
307 self.system_log_manager = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800308 if self.prespawner:
309 logging.info('Stopping prespawner')
310 self.prespawner.stop()
311 self.prespawner = None
312 if self.event_client:
313 logging.info('Closing event client')
314 self.event_client.close()
315 self.event_client = None
316 if self.event_log:
317 self.event_log.Close()
318 self.event_log = None
Dean Liao592e4d52013-01-10 20:06:39 +0800319 if self.key_filter:
320 self.key_filter.Stop()
321
Jon Salz0697cbf2012-07-04 15:14:04 +0800322 self.check_exceptions()
323 logging.info('Done destroying Goofy')
324
325 def start_state_server(self):
326 self.state_instance, self.state_server = (
327 state.create_server(bind_address='0.0.0.0'))
Jon Salz16d10542012-07-23 12:18:45 +0800328 self.goofy_rpc = GoofyRPC(self)
329 self.goofy_rpc.RegisterMethods(self.state_instance)
Jon Salz0697cbf2012-07-04 15:14:04 +0800330 logging.info('Starting state server')
331 self.state_server_thread = threading.Thread(
332 target=self.state_server.serve_forever,
333 name='StateServer')
334 self.state_server_thread.start()
335
336 def start_event_server(self):
337 self.event_server = EventServer()
338 logging.info('Starting factory event server')
339 self.event_server_thread = threading.Thread(
340 target=self.event_server.serve_forever,
341 name='EventServer') # pylint: disable=E1101
342 self.event_server_thread.start()
343
344 self.event_client = EventClient(
345 callback=self.handle_event, event_loop=self.run_queue)
346
347 self.web_socket_manager = WebSocketManager(self.uuid)
348 self.state_server.add_handler("/event",
349 self.web_socket_manager.handle_web_socket)
350
351 def start_ui(self):
352 ui_proc_args = [
353 os.path.join(factory.FACTORY_PACKAGE_PATH, 'test', 'ui.py'),
354 self.options.test_list]
355 if self.options.verbose:
356 ui_proc_args.append('-v')
357 logging.info('Starting ui %s', ui_proc_args)
Jon Salz78c32392012-07-25 14:18:29 +0800358 self.ui_process = Spawn(ui_proc_args)
Jon Salz0697cbf2012-07-04 15:14:04 +0800359 logging.info('Waiting for UI to come up...')
360 self.event_client.wait(
361 lambda event: event.type == Event.Type.UI_READY)
362 logging.info('UI has started')
363
364 def set_visible_test(self, test):
365 if self.visible_test == test:
366 return
Jon Salz2f2d42c2012-07-30 12:30:34 +0800367 if test and not test.has_ui:
368 return
Jon Salz0697cbf2012-07-04 15:14:04 +0800369
370 if test:
371 test.update_state(visible=True)
372 if self.visible_test:
373 self.visible_test.update_state(visible=False)
374 self.visible_test = test
375
Jon Salzd4306c82012-11-30 15:16:36 +0800376 def _log_startup_messages(self):
377 '''Logs the tail of var/log/messages and mosys and EC console logs.'''
378 # TODO(jsalz): This is mostly a copy-and-paste of code in init_states,
379 # for factory-3004.B only. Consolidate and merge back to ToT.
380 if utils.in_chroot():
381 return
382
383 try:
384 var_log_messages = (
385 utils.var_log_messages_before_reboot())
386 logging.info(
387 'Tail of /var/log/messages before last reboot:\n'
388 '%s', ('\n'.join(
389 ' ' + x for x in var_log_messages)))
390 except: # pylint: disable=W0702
391 logging.exception('Unable to grok /var/log/messages')
392
393 try:
394 mosys_log = utils.Spawn(
395 ['mosys', 'eventlog', 'list'],
396 read_stdout=True, log_stderr_on_error=True).stdout_data
397 logging.info('System eventlog from mosys:\n%s\n', mosys_log)
398 except: # pylint: disable=W0702
399 logging.exception('Unable to read mosys eventlog')
400
401 try:
Vic Yang8341dde2013-01-29 16:48:52 +0800402 board = system.GetBoard()
403 ec_console_log = board.GetECConsoleLog()
Jon Salzd4306c82012-11-30 15:16:36 +0800404 logging.info('EC console log after reboot:\n%s\n', ec_console_log)
405 except: # pylint: disable=W0702
406 logging.exception('Error retrieving EC console log')
407
Jon Salz0697cbf2012-07-04 15:14:04 +0800408 def handle_shutdown_complete(self, test, test_state):
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800409 '''
Jon Salz0697cbf2012-07-04 15:14:04 +0800410 Handles the case where a shutdown was detected during a shutdown step.
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800411
Jon Salz0697cbf2012-07-04 15:14:04 +0800412 @param test: The ShutdownStep.
413 @param test_state: The test state.
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800414 '''
Jon Salz0697cbf2012-07-04 15:14:04 +0800415 test_state = test.update_state(increment_shutdown_count=1)
416 logging.info('Detected shutdown (%d of %d)',
417 test_state.shutdown_count, test.iterations)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800418
Jon Salz0697cbf2012-07-04 15:14:04 +0800419 def log_and_update_state(status, error_msg, **kw):
420 self.event_log.Log('rebooted',
421 status=status, error_msg=error_msg, **kw)
Jon Salzd4306c82012-11-30 15:16:36 +0800422 logging.info('Rebooted: status=%s, %s', status,
423 (('error_msg=%s' % error_msg) if error_msg else None))
Jon Salz0697cbf2012-07-04 15:14:04 +0800424 test.update_state(status=status, error_msg=error_msg)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800425
Jon Salz0697cbf2012-07-04 15:14:04 +0800426 if not self.last_shutdown_time:
427 log_and_update_state(status=TestState.FAILED,
428 error_msg='Unable to read shutdown_time')
429 return
Jon Salz258a40c2012-04-19 12:34:01 +0800430
Jon Salz0697cbf2012-07-04 15:14:04 +0800431 now = time.time()
432 logging.info('%.03f s passed since reboot',
433 now - self.last_shutdown_time)
Jon Salz258a40c2012-04-19 12:34:01 +0800434
Jon Salz0697cbf2012-07-04 15:14:04 +0800435 if self.last_shutdown_time > now:
436 test.update_state(status=TestState.FAILED,
437 error_msg='Time moved backward during reboot')
438 elif (isinstance(test, factory.RebootStep) and
439 self.test_list.options.max_reboot_time_secs and
440 (now - self.last_shutdown_time >
441 self.test_list.options.max_reboot_time_secs)):
442 # A reboot took too long; fail. (We don't check this for
443 # HaltSteps, because the machine could be halted for a
444 # very long time, and even unplugged with battery backup,
445 # thus hosing the clock.)
446 log_and_update_state(
447 status=TestState.FAILED,
448 error_msg=('More than %d s elapsed during reboot '
449 '(%.03f s, from %s to %s)' % (
450 self.test_list.options.max_reboot_time_secs,
451 now - self.last_shutdown_time,
452 utils.TimeString(self.last_shutdown_time),
453 utils.TimeString(now))),
454 duration=(now-self.last_shutdown_time))
Jon Salzd4306c82012-11-30 15:16:36 +0800455 self._log_startup_messages()
Jon Salz0697cbf2012-07-04 15:14:04 +0800456 elif test_state.shutdown_count == test.iterations:
457 # Good!
458 log_and_update_state(status=TestState.PASSED,
459 duration=(now - self.last_shutdown_time),
460 error_msg='')
461 elif test_state.shutdown_count > test.iterations:
462 # Shut down too many times
463 log_and_update_state(status=TestState.FAILED,
464 error_msg='Too many shutdowns')
Jon Salzd4306c82012-11-30 15:16:36 +0800465 self._log_startup_messages()
Jon Salz0697cbf2012-07-04 15:14:04 +0800466 elif utils.are_shift_keys_depressed():
467 logging.info('Shift keys are depressed; cancelling restarts')
468 # Abort shutdown
469 log_and_update_state(
470 status=TestState.FAILED,
471 error_msg='Shutdown aborted with double shift keys')
Jon Salza6711d72012-07-18 14:33:03 +0800472 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +0800473 else:
474 def handler():
475 if self._prompt_cancel_shutdown(
476 test, test_state.shutdown_count + 1):
Jon Salza6711d72012-07-18 14:33:03 +0800477 factory.console.info('Shutdown aborted by operator')
Jon Salz0697cbf2012-07-04 15:14:04 +0800478 log_and_update_state(
479 status=TestState.FAILED,
480 error_msg='Shutdown aborted by operator')
Jon Salza6711d72012-07-18 14:33:03 +0800481 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +0800482 return
Jon Salz0405ab52012-03-16 15:26:52 +0800483
Jon Salz0697cbf2012-07-04 15:14:04 +0800484 # Time to shutdown again
485 log_and_update_state(
486 status=TestState.ACTIVE,
487 error_msg='',
488 iteration=test_state.shutdown_count)
Jon Salz73e0fd02012-04-04 11:46:38 +0800489
Jon Salz0697cbf2012-07-04 15:14:04 +0800490 self.event_log.Log('shutdown', operation='reboot')
491 self.state_instance.set_shared_data('shutdown_time',
492 time.time())
493 self.env.shutdown('reboot')
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800494
Jon Salz0697cbf2012-07-04 15:14:04 +0800495 self.on_ui_startup.append(handler)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800496
Jon Salz0697cbf2012-07-04 15:14:04 +0800497 def _prompt_cancel_shutdown(self, test, iteration):
498 if self.options.ui != 'chrome':
499 return False
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800500
Jon Salz0697cbf2012-07-04 15:14:04 +0800501 pending_shutdown_data = {
502 'delay_secs': test.delay_secs,
503 'time': time.time() + test.delay_secs,
504 'operation': test.operation,
505 'iteration': iteration,
506 'iterations': test.iterations,
507 }
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800508
Jon Salz0697cbf2012-07-04 15:14:04 +0800509 # Create a new (threaded) event client since we
510 # don't want to use the event loop for this.
511 with EventClient() as event_client:
512 event_client.post_event(Event(Event.Type.PENDING_SHUTDOWN,
513 **pending_shutdown_data))
514 aborted = event_client.wait(
515 lambda event: event.type == Event.Type.CANCEL_SHUTDOWN,
516 timeout=test.delay_secs) is not None
517 if aborted:
518 event_client.post_event(Event(Event.Type.PENDING_SHUTDOWN))
519 return aborted
Jon Salz258a40c2012-04-19 12:34:01 +0800520
Jon Salz0697cbf2012-07-04 15:14:04 +0800521 def init_states(self):
522 '''
523 Initializes all states on startup.
524 '''
525 for test in self.test_list.get_all_tests():
526 # Make sure the state server knows about all the tests,
527 # defaulting to an untested state.
528 test.update_state(update_parent=False, visible=False)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800529
Jon Salz0697cbf2012-07-04 15:14:04 +0800530 var_log_messages = None
Vic Yanga9c32212012-08-16 20:07:54 +0800531 mosys_log = None
Vic Yange4c275d2012-08-28 01:50:20 +0800532 ec_console_log = None
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800533
Jon Salz0697cbf2012-07-04 15:14:04 +0800534 # Any 'active' tests should be marked as failed now.
535 for test in self.test_list.walk():
Jon Salza6711d72012-07-18 14:33:03 +0800536 if not test.is_leaf():
537 # Don't bother with parents; they will be updated when their
538 # children are updated.
539 continue
540
Jon Salz0697cbf2012-07-04 15:14:04 +0800541 test_state = test.get_state()
542 if test_state.status != TestState.ACTIVE:
543 continue
544 if isinstance(test, factory.ShutdownStep):
545 # Shutdown while the test was active - that's good.
546 self.handle_shutdown_complete(test, test_state)
547 else:
548 # Unexpected shutdown. Grab /var/log/messages for context.
549 if var_log_messages is None:
550 try:
551 var_log_messages = (
552 utils.var_log_messages_before_reboot())
553 # Write it to the log, to make it easier to
554 # correlate with /var/log/messages.
555 logging.info(
556 'Unexpected shutdown. '
557 'Tail of /var/log/messages before last reboot:\n'
558 '%s', ('\n'.join(
559 ' ' + x for x in var_log_messages)))
560 except: # pylint: disable=W0702
561 logging.exception('Unable to grok /var/log/messages')
562 var_log_messages = []
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800563
Jon Salz008f4ea2012-08-28 05:39:45 +0800564 if mosys_log is None and not utils.in_chroot():
565 try:
566 mosys_log = utils.Spawn(
567 ['mosys', 'eventlog', 'list'],
568 read_stdout=True, log_stderr_on_error=True).stdout_data
569 # Write it to the log also.
570 logging.info('System eventlog from mosys:\n%s\n', mosys_log)
571 except: # pylint: disable=W0702
572 logging.exception('Unable to read mosys eventlog')
Vic Yanga9c32212012-08-16 20:07:54 +0800573
Vic Yange4c275d2012-08-28 01:50:20 +0800574 if ec_console_log is None:
575 try:
Vic Yang8341dde2013-01-29 16:48:52 +0800576 board = system.GetBoard()
577 ec_console_log = board.GetECConsoleLog()
Vic Yange4c275d2012-08-28 01:50:20 +0800578 logging.info('EC console log after reboot:\n%s\n', ec_console_log)
Jon Salzfe1f6652012-09-07 05:40:14 +0800579 except: # pylint: disable=W0702
Vic Yange4c275d2012-08-28 01:50:20 +0800580 logging.exception('Error retrieving EC console log')
581
Jon Salz0697cbf2012-07-04 15:14:04 +0800582 error_msg = 'Unexpected shutdown while test was running'
583 self.event_log.Log('end_test',
584 path=test.path,
585 status=TestState.FAILED,
586 invocation=test.get_state().invocation,
587 error_msg=error_msg,
Vic Yanga9c32212012-08-16 20:07:54 +0800588 var_log_messages='\n'.join(var_log_messages),
589 mosys_log=mosys_log)
Jon Salz0697cbf2012-07-04 15:14:04 +0800590 test.update_state(
591 status=TestState.FAILED,
592 error_msg=error_msg)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800593
Jon Salz50efe942012-07-26 11:54:10 +0800594 if not test.never_fails:
595 # For "never_fails" tests (such as "Start"), don't cancel
596 # pending tests, since reboot is expected.
597 factory.console.info('Unexpected shutdown while test %s '
598 'running; cancelling any pending tests',
599 test.path)
600 self.state_instance.set_shared_data('tests_after_shutdown', [])
Jon Salz69806bb2012-07-20 18:05:02 +0800601
Jon Salz008f4ea2012-08-28 05:39:45 +0800602 self.update_skipped_tests()
603
604 def update_skipped_tests(self):
605 '''
606 Updates skipped states based on run_if.
607 '''
608 for t in self.test_list.walk():
609 if t.is_leaf() and t.run_if_table_name:
610 skip = False
611 try:
612 aux = shopfloor.get_selected_aux_data(t.run_if_table_name)
613 value = aux.get(t.run_if_col)
614 if value is not None:
615 skip = (not value) ^ t.run_if_not
616 except ValueError:
617 # Not available; assume it shouldn't be skipped
618 pass
619
620 test_state = t.get_state()
621 if ((not skip) and
622 (test_state.status == TestState.PASSED) and
623 (test_state.error_msg == TestState.SKIPPED_MSG)):
624 # It was marked as skipped before, but now we need to run it.
625 # Mark as untested.
626 t.update_state(skip=skip, status=TestState.UNTESTED, error_msg='')
627 else:
628 t.update_state(skip=skip)
629
Jon Salz0697cbf2012-07-04 15:14:04 +0800630 def show_next_active_test(self):
631 '''
632 Rotates to the next visible active test.
633 '''
634 self.reap_completed_tests()
635 active_tests = [
636 t for t in self.test_list.walk()
637 if t.is_leaf() and t.get_state().status == TestState.ACTIVE]
638 if not active_tests:
639 return
Jon Salz4f6c7172012-06-11 20:45:36 +0800640
Jon Salz0697cbf2012-07-04 15:14:04 +0800641 try:
642 next_test = active_tests[
643 (active_tests.index(self.visible_test) + 1) % len(active_tests)]
644 except ValueError: # visible_test not present in active_tests
645 next_test = active_tests[0]
Jon Salz4f6c7172012-06-11 20:45:36 +0800646
Jon Salz0697cbf2012-07-04 15:14:04 +0800647 self.set_visible_test(next_test)
Jon Salz4f6c7172012-06-11 20:45:36 +0800648
Jon Salz0697cbf2012-07-04 15:14:04 +0800649 def handle_event(self, event):
650 '''
651 Handles an event from the event server.
652 '''
653 handler = self.event_handlers.get(event.type)
654 if handler:
655 handler(event)
656 else:
657 # We don't register handlers for all event types - just ignore
658 # this event.
659 logging.debug('Unbound event type %s', event.type)
Jon Salz4f6c7172012-06-11 20:45:36 +0800660
Vic Yangaabf9fd2013-04-09 18:56:13 +0800661 def check_critical_factory_note(self):
662 '''
663 Returns True if the last factory note is critical.
664 '''
665 notes = self.state_instance.get_shared_data('factory_note', True)
666 return notes and notes[-1]['level'] == 'CRITICAL'
667
Jon Salz0697cbf2012-07-04 15:14:04 +0800668 def run_next_test(self):
669 '''
670 Runs the next eligible test (or tests) in self.tests_to_run.
671 '''
672 self.reap_completed_tests()
Vic Yangaabf9fd2013-04-09 18:56:13 +0800673 if self.tests_to_run and self.check_critical_factory_note():
674 self.tests_to_run.clear()
675 return
Jon Salz0697cbf2012-07-04 15:14:04 +0800676 while self.tests_to_run:
677 logging.debug('Tests to run: %s',
678 [x.path for x in self.tests_to_run])
Jon Salz94eb56f2012-06-12 18:01:12 +0800679
Jon Salz0697cbf2012-07-04 15:14:04 +0800680 test = self.tests_to_run[0]
Jon Salz94eb56f2012-06-12 18:01:12 +0800681
Jon Salz0697cbf2012-07-04 15:14:04 +0800682 if test in self.invocations:
683 logging.info('Next test %s is already running', test.path)
684 self.tests_to_run.popleft()
685 return
Jon Salz94eb56f2012-06-12 18:01:12 +0800686
Jon Salza1412922012-07-23 16:04:17 +0800687 for requirement in test.require_run:
688 for i in requirement.test.walk():
689 if i.get_state().status == TestState.ACTIVE:
Jon Salz304a75d2012-07-06 11:14:15 +0800690 logging.info('Waiting for active test %s to complete '
Jon Salza1412922012-07-23 16:04:17 +0800691 'before running %s', i.path, test.path)
Jon Salz304a75d2012-07-06 11:14:15 +0800692 return
693
Jon Salz0697cbf2012-07-04 15:14:04 +0800694 if self.invocations and not (test.backgroundable and all(
695 [x.backgroundable for x in self.invocations])):
696 logging.debug('Waiting for non-backgroundable tests to '
697 'complete before running %s', test.path)
698 return
Jon Salz94eb56f2012-06-12 18:01:12 +0800699
Jon Salz3e6f5202012-10-15 15:08:29 +0800700 if test.get_state().skip:
701 factory.console.info('Skipping test %s', test.path)
702 test.update_state(status=TestState.PASSED,
703 error_msg=TestState.SKIPPED_MSG)
704 self.tests_to_run.popleft()
705 continue
706
Jon Salz0697cbf2012-07-04 15:14:04 +0800707 self.tests_to_run.popleft()
Jon Salz94eb56f2012-06-12 18:01:12 +0800708
Jon Salz304a75d2012-07-06 11:14:15 +0800709 untested = set()
Jon Salza1412922012-07-23 16:04:17 +0800710 for requirement in test.require_run:
711 for i in requirement.test.walk():
712 if i == test:
Jon Salz304a75d2012-07-06 11:14:15 +0800713 # We've hit this test itself; stop checking
714 break
Jon Salza1412922012-07-23 16:04:17 +0800715 if ((i.get_state().status == TestState.UNTESTED) or
716 (requirement.passed and i.get_state().status !=
717 TestState.PASSED)):
Jon Salz304a75d2012-07-06 11:14:15 +0800718 # Found an untested test; move on to the next
719 # element in require_run.
Jon Salza1412922012-07-23 16:04:17 +0800720 untested.add(i)
Jon Salz304a75d2012-07-06 11:14:15 +0800721 break
722
723 if untested:
724 untested_paths = ', '.join(sorted([x.path for x in untested]))
725 if self.state_instance.get_shared_data('engineering_mode',
726 optional=True):
727 # In engineering mode, we'll let it go.
728 factory.console.warn('In engineering mode; running '
729 '%s even though required tests '
730 '[%s] have not completed',
731 test.path, untested_paths)
732 else:
733 # Not in engineering mode; mark it failed.
734 error_msg = ('Required tests [%s] have not been run yet'
735 % untested_paths)
736 factory.console.error('Not running %s: %s',
737 test.path, error_msg)
738 test.update_state(status=TestState.FAILED,
739 error_msg=error_msg)
740 continue
741
Jon Salz0697cbf2012-07-04 15:14:04 +0800742 if isinstance(test, factory.ShutdownStep):
743 if os.path.exists(NO_REBOOT_FILE):
744 test.update_state(
745 status=TestState.FAILED, increment_count=1,
746 error_msg=('Skipped shutdown since %s is present' %
Jon Salz304a75d2012-07-06 11:14:15 +0800747 NO_REBOOT_FILE))
Jon Salz0697cbf2012-07-04 15:14:04 +0800748 continue
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800749
Jon Salz0697cbf2012-07-04 15:14:04 +0800750 test.update_state(status=TestState.ACTIVE, increment_count=1,
751 error_msg='', shutdown_count=0)
752 if self._prompt_cancel_shutdown(test, 1):
753 self.event_log.Log('reboot_cancelled')
754 test.update_state(
755 status=TestState.FAILED, increment_count=1,
756 error_msg='Shutdown aborted by operator',
757 shutdown_count=0)
chungyiafe8f772012-08-15 19:36:29 +0800758 continue
Jon Salz2f757d42012-06-27 17:06:42 +0800759
Jon Salz0697cbf2012-07-04 15:14:04 +0800760 # Save pending test list in the state server
Jon Salzdbf398f2012-06-14 17:30:01 +0800761 self.state_instance.set_shared_data(
Jon Salz0697cbf2012-07-04 15:14:04 +0800762 'tests_after_shutdown',
763 [t.path for t in self.tests_to_run])
764 # Save shutdown time
765 self.state_instance.set_shared_data('shutdown_time',
766 time.time())
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800767
Jon Salz0697cbf2012-07-04 15:14:04 +0800768 with self.env.lock:
769 self.event_log.Log('shutdown', operation=test.operation)
770 shutdown_result = self.env.shutdown(test.operation)
771 if shutdown_result:
772 # That's all, folks!
773 self.run_queue.put(None)
774 return
775 else:
776 # Just pass (e.g., in the chroot).
777 test.update_state(status=TestState.PASSED)
778 self.state_instance.set_shared_data(
779 'tests_after_shutdown', None)
780 # Send event with no fields to indicate that there is no
781 # longer a pending shutdown.
782 self.event_client.post_event(Event(
783 Event.Type.PENDING_SHUTDOWN))
784 continue
Jon Salz258a40c2012-04-19 12:34:01 +0800785
Cheng-Yi Chiangce05c002013-04-04 02:13:17 +0800786 self._run_test(test, test.iterations, test.retries)
Jon Salz1acc8742012-07-17 17:45:55 +0800787
Cheng-Yi Chiangce05c002013-04-04 02:13:17 +0800788 def _run_test(self, test, iterations_left=None, retries_left=None):
Jon Salz1acc8742012-07-17 17:45:55 +0800789 invoc = TestInvocation(self, test, on_completion=self.run_next_test)
790 new_state = test.update_state(
791 status=TestState.ACTIVE, increment_count=1, error_msg='',
Jon Salzbd42ce12012-09-18 08:03:59 +0800792 invocation=invoc.uuid, iterations_left=iterations_left,
Cheng-Yi Chiangce05c002013-04-04 02:13:17 +0800793 retries_left=retries_left,
Jon Salzbd42ce12012-09-18 08:03:59 +0800794 visible=(self.visible_test == test))
Jon Salz1acc8742012-07-17 17:45:55 +0800795 invoc.count = new_state.count
796
797 self.invocations[test] = invoc
798 if self.visible_test is None and test.has_ui:
799 self.set_visible_test(test)
Vic Yang311ddb82012-09-26 12:08:28 +0800800 self.check_exclusive()
Jon Salz1acc8742012-07-17 17:45:55 +0800801 invoc.start()
Jon Salz5f2a0672012-05-22 17:14:06 +0800802
Vic Yang311ddb82012-09-26 12:08:28 +0800803 def check_exclusive(self):
804 current_exclusive_items = set([
805 item
806 for item in factory.FactoryTest.EXCLUSIVE_OPTIONS
807 if any([test.is_exclusive(item) for test in self.invocations])])
808
809 new_exclusive_items = current_exclusive_items - self.exclusive_items
810 if factory.FactoryTest.EXCLUSIVE_OPTIONS.NETWORKING in new_exclusive_items:
811 logging.info('Disabling network')
812 self.connection_manager.DisableNetworking()
813 if factory.FactoryTest.EXCLUSIVE_OPTIONS.CHARGER in new_exclusive_items:
814 logging.info('Stop controlling charger')
815
816 new_non_exclusive_items = self.exclusive_items - current_exclusive_items
817 if (factory.FactoryTest.EXCLUSIVE_OPTIONS.NETWORKING in
818 new_non_exclusive_items):
819 logging.info('Re-enabling network')
820 self.connection_manager.EnableNetworking()
821 if factory.FactoryTest.EXCLUSIVE_OPTIONS.CHARGER in new_non_exclusive_items:
822 logging.info('Start controlling charger')
823
824 # Only adjust charge state if not excluded
Cheng-Yi Chiangd8186952013-04-04 23:41:14 +0800825 if (factory.FactoryTest.EXCLUSIVE_OPTIONS.CHARGER not in
Vic Yange83d9a12013-04-19 20:00:20 +0800826 current_exclusive_items and not utils.in_chroot()):
Cheng-Yi Chiangd8186952013-04-04 23:41:14 +0800827 if self.charge_manager:
828 self.charge_manager.AdjustChargeState()
829 else:
830 try:
831 system.GetBoard().SetChargeState(Board.ChargeState.CHARGE)
832 except BoardException:
833 logging.exception('Unable to set charge state on this board')
Vic Yang311ddb82012-09-26 12:08:28 +0800834
835 self.exclusive_items = current_exclusive_items
Jon Salz5da61e62012-05-31 13:06:22 +0800836
cychiang21886742012-07-05 15:16:32 +0800837 def check_for_updates(self):
838 '''
839 Schedules an asynchronous check for updates if necessary.
840 '''
841 if not self.test_list.options.update_period_secs:
842 # Not enabled.
843 return
844
845 now = time.time()
846 if self.last_update_check and (
847 now - self.last_update_check <
848 self.test_list.options.update_period_secs):
849 # Not yet time for another check.
850 return
851
852 self.last_update_check = now
853
854 def handle_check_for_update(reached_shopfloor, md5sum, needs_update):
855 if reached_shopfloor:
856 new_update_md5sum = md5sum if needs_update else None
857 if system.SystemInfo.update_md5sum != new_update_md5sum:
858 logging.info('Received new update MD5SUM: %s', new_update_md5sum)
859 system.SystemInfo.update_md5sum = new_update_md5sum
860 self.run_queue.put(self.update_system_info)
861
862 updater.CheckForUpdateAsync(
863 handle_check_for_update,
864 self.test_list.options.shopfloor_timeout_secs)
865
Jon Salza6711d72012-07-18 14:33:03 +0800866 def cancel_pending_tests(self):
867 '''Cancels any tests in the run queue.'''
868 self.run_tests([])
869
Jon Salz0697cbf2012-07-04 15:14:04 +0800870 def run_tests(self, subtrees, untested_only=False):
871 '''
872 Runs tests under subtree.
Jon Salz258a40c2012-04-19 12:34:01 +0800873
Jon Salz0697cbf2012-07-04 15:14:04 +0800874 The tests are run in order unless one fails (then stops).
875 Backgroundable tests are run simultaneously; when a foreground test is
876 encountered, we wait for all active tests to finish before continuing.
Jon Salzb1b39092012-05-03 02:05:09 +0800877
Jon Salz0697cbf2012-07-04 15:14:04 +0800878 @param subtrees: Node or nodes containing tests to run (may either be
879 a single test or a list). Duplicates will be ignored.
880 '''
881 if type(subtrees) != list:
882 subtrees = [subtrees]
Jon Salz258a40c2012-04-19 12:34:01 +0800883
Jon Salz0697cbf2012-07-04 15:14:04 +0800884 # Nodes we've seen so far, to avoid duplicates.
885 seen = set()
Jon Salz94eb56f2012-06-12 18:01:12 +0800886
Jon Salz0697cbf2012-07-04 15:14:04 +0800887 self.tests_to_run = deque()
888 for subtree in subtrees:
889 for test in subtree.walk():
890 if test in seen:
891 continue
892 seen.add(test)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800893
Jon Salz0697cbf2012-07-04 15:14:04 +0800894 if not test.is_leaf():
895 continue
896 if (untested_only and
897 test.get_state().status != TestState.UNTESTED):
898 continue
899 self.tests_to_run.append(test)
900 self.run_next_test()
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800901
Jon Salz0697cbf2012-07-04 15:14:04 +0800902 def reap_completed_tests(self):
903 '''
904 Removes completed tests from the set of active tests.
905
906 Also updates the visible test if it was reaped.
907 '''
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +0800908 test_completed = False
Jon Salz0697cbf2012-07-04 15:14:04 +0800909 for t, v in dict(self.invocations).iteritems():
910 if v.is_completed():
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +0800911 test_completed = True
Jon Salz1acc8742012-07-17 17:45:55 +0800912 new_state = t.update_state(**v.update_state_on_completion)
Jon Salz0697cbf2012-07-04 15:14:04 +0800913 del self.invocations[t]
914
Chun-Ta Lin54e17e42012-09-06 22:05:13 +0800915 # Stop on failure if flag is true.
916 if (self.test_list.options.stop_on_failure and
917 new_state.status == TestState.FAILED):
918 # Clean all the tests to cause goofy to stop.
919 self.tests_to_run = []
920 factory.console.info("Stop on failure triggered. Empty the queue.")
921
Jon Salz1acc8742012-07-17 17:45:55 +0800922 if new_state.iterations_left and new_state.status == TestState.PASSED:
923 # Play it again, Sam!
924 self._run_test(t)
Cheng-Yi Chiangce05c002013-04-04 02:13:17 +0800925 # new_state.retries_left is obtained after update.
926 # For retries_left == 0, test can still be run for the last time.
927 elif (new_state.retries_left >= 0 and
928 new_state.status == TestState.FAILED):
929 # Still have to retry, Sam!
930 self._run_test(t)
Jon Salz1acc8742012-07-17 17:45:55 +0800931
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +0800932 if test_completed:
Vic Yangf01c59f2013-04-19 17:37:56 +0800933 self.log_watcher.KickWatchThread()
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +0800934
Jon Salz0697cbf2012-07-04 15:14:04 +0800935 if (self.visible_test is None or
Jon Salz85a39882012-07-05 16:45:04 +0800936 self.visible_test not in self.invocations):
Jon Salz0697cbf2012-07-04 15:14:04 +0800937 self.set_visible_test(None)
938 # Make the first running test, if any, the visible test
939 for t in self.test_list.walk():
940 if t in self.invocations:
941 self.set_visible_test(t)
942 break
943
Jon Salz85a39882012-07-05 16:45:04 +0800944 def kill_active_tests(self, abort, root=None):
Jon Salz0697cbf2012-07-04 15:14:04 +0800945 '''
946 Kills and waits for all active tests.
947
Jon Salz85a39882012-07-05 16:45:04 +0800948 Args:
949 abort: True to change state of killed tests to FAILED, False for
Jon Salz0697cbf2012-07-04 15:14:04 +0800950 UNTESTED.
Jon Salz85a39882012-07-05 16:45:04 +0800951 root: If set, only kills tests with root as an ancestor.
Jon Salz0697cbf2012-07-04 15:14:04 +0800952 '''
953 self.reap_completed_tests()
954 for test, invoc in self.invocations.items():
Jon Salz85a39882012-07-05 16:45:04 +0800955 if root and not test.has_ancestor(root):
956 continue
957
Jon Salz0697cbf2012-07-04 15:14:04 +0800958 factory.console.info('Killing active test %s...' % test.path)
959 invoc.abort_and_join()
960 factory.console.info('Killed %s' % test.path)
Jon Salz1acc8742012-07-17 17:45:55 +0800961 test.update_state(**invoc.update_state_on_completion)
Jon Salz0697cbf2012-07-04 15:14:04 +0800962 del self.invocations[test]
Jon Salz1acc8742012-07-17 17:45:55 +0800963
Jon Salz0697cbf2012-07-04 15:14:04 +0800964 if not abort:
965 test.update_state(status=TestState.UNTESTED)
966 self.reap_completed_tests()
967
Jon Salz85a39882012-07-05 16:45:04 +0800968 def stop(self, root=None, fail=False):
969 self.kill_active_tests(fail, root)
970 # Remove any tests in the run queue under the root.
971 self.tests_to_run = deque([x for x in self.tests_to_run
972 if root and not x.has_ancestor(root)])
973 self.run_next_test()
Jon Salz0697cbf2012-07-04 15:14:04 +0800974
Jon Salz4712ac72013-02-07 17:12:05 +0800975 def clear_state(self, root=None):
976 self.stop(root)
977 for f in root.walk():
978 if f.is_leaf():
979 f.update_state(status=TestState.UNTESTED)
980
Jon Salz0697cbf2012-07-04 15:14:04 +0800981 def abort_active_tests(self):
982 self.kill_active_tests(True)
983
984 def main(self):
985 try:
986 self.init()
987 self.event_log.Log('goofy_init',
988 success=True)
989 except:
990 if self.event_log:
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800991 try:
Jon Salz0697cbf2012-07-04 15:14:04 +0800992 self.event_log.Log('goofy_init',
993 success=False,
994 trace=traceback.format_exc())
995 except: # pylint: disable=W0702
996 pass
997 raise
998
999 self.run()
1000
1001 def update_system_info(self):
1002 '''Updates system info.'''
1003 system_info = system.SystemInfo()
1004 self.state_instance.set_shared_data('system_info', system_info.__dict__)
1005 self.event_client.post_event(Event(Event.Type.SYSTEM_INFO,
1006 system_info=system_info.__dict__))
1007 logging.info('System info: %r', system_info.__dict__)
1008
Jon Salzeb42f0d2012-07-27 19:14:04 +08001009 def update_factory(self, auto_run_on_restart=False, post_update_hook=None):
1010 '''Commences updating factory software.
1011
1012 Args:
1013 auto_run_on_restart: Auto-run when the machine comes back up.
1014 post_update_hook: Code to call after update but immediately before
1015 restart.
1016
1017 Returns:
1018 Never if the update was successful (we just reboot).
1019 False if the update was unnecessary (no update available).
1020 '''
Jon Salz0697cbf2012-07-04 15:14:04 +08001021 self.kill_active_tests(False)
Jon Salza6711d72012-07-18 14:33:03 +08001022 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +08001023
Jon Salz5c344f62012-07-13 14:31:16 +08001024 def pre_update_hook():
1025 if auto_run_on_restart:
1026 self.state_instance.set_shared_data('tests_after_shutdown',
1027 FORCE_AUTO_RUN)
1028 self.state_instance.close()
1029
Jon Salzeb42f0d2012-07-27 19:14:04 +08001030 if updater.TryUpdate(pre_update_hook=pre_update_hook):
1031 if post_update_hook:
1032 post_update_hook()
1033 self.env.shutdown('reboot')
Jon Salz0697cbf2012-07-04 15:14:04 +08001034
Jon Salzcef132a2012-08-30 04:58:08 +08001035 def handle_sigint(self, dummy_signum, dummy_frame):
Jon Salz77c151e2012-08-28 07:20:37 +08001036 logging.error('Received SIGINT')
1037 self.run_queue.put(None)
1038 raise KeyboardInterrupt()
1039
Jon Salz0697cbf2012-07-04 15:14:04 +08001040 def init(self, args=None, env=None):
1041 '''Initializes Goofy.
1042
1043 Args:
1044 args: A list of command-line arguments. Uses sys.argv if
1045 args is None.
1046 env: An Environment instance to use (or None to choose
1047 FakeChrootEnvironment or DUTEnvironment as appropriate).
1048 '''
Jon Salz77c151e2012-08-28 07:20:37 +08001049 signal.signal(signal.SIGINT, self.handle_sigint)
1050
Jon Salz0697cbf2012-07-04 15:14:04 +08001051 parser = OptionParser()
1052 parser.add_option('-v', '--verbose', dest='verbose',
Jon Salz8fa8e832012-07-13 19:04:09 +08001053 action='store_true',
1054 help='Enable debug logging')
Jon Salz0697cbf2012-07-04 15:14:04 +08001055 parser.add_option('--print_test_list', dest='print_test_list',
Jon Salz8fa8e832012-07-13 19:04:09 +08001056 metavar='FILE',
1057 help='Read and print test list FILE, and exit')
Jon Salz0697cbf2012-07-04 15:14:04 +08001058 parser.add_option('--restart', dest='restart',
Jon Salz8fa8e832012-07-13 19:04:09 +08001059 action='store_true',
1060 help='Clear all test state')
Jon Salz0697cbf2012-07-04 15:14:04 +08001061 parser.add_option('--ui', dest='ui', type='choice',
Jon Salz8fa8e832012-07-13 19:04:09 +08001062 choices=['none', 'gtk', 'chrome'],
Jon Salz2f881df2013-02-01 17:00:35 +08001063 default='chrome',
Jon Salz8fa8e832012-07-13 19:04:09 +08001064 help='UI to use')
Jon Salz0697cbf2012-07-04 15:14:04 +08001065 parser.add_option('--ui_scale_factor', dest='ui_scale_factor',
Jon Salz8fa8e832012-07-13 19:04:09 +08001066 type='int', default=1,
1067 help=('Factor by which to scale UI '
1068 '(Chrome UI only)'))
Jon Salz0697cbf2012-07-04 15:14:04 +08001069 parser.add_option('--test_list', dest='test_list',
Jon Salz8fa8e832012-07-13 19:04:09 +08001070 metavar='FILE',
1071 help='Use FILE as test list')
Jon Salzc79a9982012-08-30 04:42:01 +08001072 parser.add_option('--dummy_shopfloor', action='store_true',
1073 help='Use a dummy shopfloor server')
chungyiafe8f772012-08-15 19:36:29 +08001074 parser.add_option('--automation', dest='automation',
1075 action='store_true',
1076 help='Enable automation on running factory test')
Ricky Liang09216dc2013-02-22 17:26:45 +08001077 parser.add_option('--one_pixel_less', dest='one_pixel_less',
1078 action='store_true',
1079 help=('Start Chrome one pixel less than the full screen.'
1080 'Needed by Exynos platform to run GTK.'))
Jon Salz0697cbf2012-07-04 15:14:04 +08001081 (self.options, self.args) = parser.parse_args(args)
1082
Jon Salz46b89562012-07-05 11:49:22 +08001083 # Make sure factory directories exist.
1084 factory.get_log_root()
1085 factory.get_state_root()
1086 factory.get_test_data_root()
1087
Jon Salz0697cbf2012-07-04 15:14:04 +08001088 global _inited_logging # pylint: disable=W0603
1089 if not _inited_logging:
1090 factory.init_logging('goofy', verbose=self.options.verbose)
1091 _inited_logging = True
Jon Salz8fa8e832012-07-13 19:04:09 +08001092
Jon Salz0f996602012-10-03 15:26:48 +08001093 if self.options.print_test_list:
1094 print factory.read_test_list(
1095 self.options.print_test_list).__repr__(recursive=True)
1096 sys.exit(0)
1097
Jon Salzee85d522012-07-17 14:34:46 +08001098 event_log.IncrementBootSequence()
Jon Salz0697cbf2012-07-04 15:14:04 +08001099 self.event_log = EventLog('goofy')
1100
1101 if (not suppress_chroot_warning and
1102 factory.in_chroot() and
1103 self.options.ui == 'gtk' and
1104 os.environ.get('DISPLAY') in [None, '', ':0', ':0.0']):
1105 # That's not going to work! Tell the user how to run
1106 # this way.
1107 logging.warn(GOOFY_IN_CHROOT_WARNING)
1108 time.sleep(1)
1109
1110 if env:
1111 self.env = env
1112 elif factory.in_chroot():
1113 self.env = test_environment.FakeChrootEnvironment()
1114 logging.warn(
1115 'Using chroot environment: will not actually run autotests')
1116 else:
1117 self.env = test_environment.DUTEnvironment()
1118 self.env.goofy = self
1119
1120 if self.options.restart:
1121 state.clear_state()
1122
Jon Salz0697cbf2012-07-04 15:14:04 +08001123 if self.options.ui_scale_factor != 1 and utils.in_qemu():
1124 logging.warn(
1125 'In QEMU; ignoring ui_scale_factor argument')
1126 self.options.ui_scale_factor = 1
1127
1128 logging.info('Started')
1129
1130 self.start_state_server()
1131 self.state_instance.set_shared_data('hwid_cfg', get_hwid_cfg())
1132 self.state_instance.set_shared_data('ui_scale_factor',
Ricky Liang09216dc2013-02-22 17:26:45 +08001133 self.options.ui_scale_factor)
1134 self.state_instance.set_shared_data('one_pixel_less',
1135 self.options.one_pixel_less)
Jon Salz0697cbf2012-07-04 15:14:04 +08001136 self.last_shutdown_time = (
1137 self.state_instance.get_shared_data('shutdown_time', optional=True))
1138 self.state_instance.del_shared_data('shutdown_time', optional=True)
1139
Jon Salzb19ea072013-02-07 16:35:00 +08001140 self.state_instance.del_shared_data('startup_error', optional=True)
Jon Salz0697cbf2012-07-04 15:14:04 +08001141 if not self.options.test_list:
1142 self.options.test_list = find_test_list()
Jon Salzb19ea072013-02-07 16:35:00 +08001143 if self.options.test_list:
Jon Salz0697cbf2012-07-04 15:14:04 +08001144 logging.info('Using test list %s', self.options.test_list)
Jon Salzb19ea072013-02-07 16:35:00 +08001145 try:
1146 self.test_list = factory.read_test_list(
1147 self.options.test_list,
1148 self.state_instance)
1149 except: # pylint: disable=W0702
1150 logging.exception('Unable to read test list %r', self.options.test_list)
1151 self.state_instance.set_shared_data('startup_error',
1152 'Unable to read test list %s\n%s' % (
1153 self.options.test_list,
1154 traceback.format_exc()))
1155 else:
1156 logging.error('No test list found.')
1157 self.state_instance.set_shared_data('startup_error',
1158 'No test list found.')
Jon Salz0697cbf2012-07-04 15:14:04 +08001159
Jon Salzb19ea072013-02-07 16:35:00 +08001160 if not self.test_list:
1161 if self.options.ui == 'chrome':
1162 # Create an empty test list with default options so that the rest of
1163 # startup can proceed.
1164 self.test_list = factory.FactoryTestList(
1165 [], self.state_instance, factory.Options())
1166 else:
1167 # Bail with an error; no point in starting up.
1168 sys.exit('No valid test list; exiting.')
1169
Jon Salz822838b2013-03-25 17:32:33 +08001170 if self.test_list.options.clear_state_on_start:
1171 self.state_instance.clear_test_state()
1172
Jon Salz0697cbf2012-07-04 15:14:04 +08001173 if not self.state_instance.has_shared_data('ui_lang'):
1174 self.state_instance.set_shared_data('ui_lang',
1175 self.test_list.options.ui_lang)
1176 self.state_instance.set_shared_data(
1177 'test_list_options',
1178 self.test_list.options.__dict__)
1179 self.state_instance.test_list = self.test_list
1180
Jon Salz83ef34b2012-11-01 19:46:35 +08001181 if not utils.in_chroot() and self.test_list.options.disable_log_rotation:
1182 open('/var/lib/cleanup_logs_paused', 'w').close()
1183
Jon Salz23926422012-09-01 03:38:13 +08001184 if self.options.dummy_shopfloor:
1185 os.environ[shopfloor.SHOPFLOOR_SERVER_ENV_VAR_NAME] = (
1186 'http://localhost:%d/' % shopfloor.DEFAULT_SERVER_PORT)
1187 self.dummy_shopfloor = Spawn(
1188 [os.path.join(factory.FACTORY_PATH, 'bin', 'shopfloor_server'),
1189 '--dummy'])
1190 elif self.test_list.options.shopfloor_server_url:
1191 shopfloor.set_server_url(self.test_list.options.shopfloor_server_url)
Jon Salz2bf2f6b2013-03-28 18:49:26 +08001192 shopfloor.set_enabled(True)
Jon Salz23926422012-09-01 03:38:13 +08001193
Jon Salz0f996602012-10-03 15:26:48 +08001194 if self.test_list.options.time_sanitizer and not utils.in_chroot():
Jon Salz8fa8e832012-07-13 19:04:09 +08001195 self.time_sanitizer = time_sanitizer.TimeSanitizer(
1196 base_time=time_sanitizer.GetBaseTimeFromFile(
1197 # lsb-factory is written by the factory install shim during
1198 # installation, so it should have a good time obtained from
Jon Salz54882d02012-08-31 01:57:54 +08001199 # the mini-Omaha server. If it's not available, we'll use
1200 # /etc/lsb-factory (which will be much older, but reasonably
1201 # sane) and rely on a shopfloor sync to set a more accurate
1202 # time.
1203 '/usr/local/etc/lsb-factory',
1204 '/etc/lsb-release'))
Jon Salz8fa8e832012-07-13 19:04:09 +08001205 self.time_sanitizer.RunOnce()
1206
Jon Salz0697cbf2012-07-04 15:14:04 +08001207 self.init_states()
1208 self.start_event_server()
1209 self.connection_manager = self.env.create_connection_manager(
Tai-Hsu Lin371351a2012-08-27 14:17:14 +08001210 self.test_list.options.wlans,
1211 self.test_list.options.scan_wifi_period_secs)
Jon Salz0697cbf2012-07-04 15:14:04 +08001212 # Note that we create a log watcher even if
1213 # sync_event_log_period_secs isn't set (no background
1214 # syncing), since we may use it to flush event logs as well.
1215 self.log_watcher = EventLogWatcher(
1216 self.test_list.options.sync_event_log_period_secs,
Jon Salz16d10542012-07-23 12:18:45 +08001217 handle_event_logs_callback=self.handle_event_logs)
Jon Salz0697cbf2012-07-04 15:14:04 +08001218 if self.test_list.options.sync_event_log_period_secs:
1219 self.log_watcher.StartWatchThread()
1220
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +08001221 # Note that we create a system log manager even if
1222 # sync_log_period_secs isn't set (no background
1223 # syncing), since we may kick it to sync logs in its
1224 # thread.
1225 self.system_log_manager = SystemLogManager(
1226 self.test_list.options.sync_log_paths,
1227 self.test_list.options.sync_log_period_secs)
1228 self.system_log_manager.StartSyncThread()
1229
Jon Salz0697cbf2012-07-04 15:14:04 +08001230 self.update_system_info()
1231
Vic Yang4953fc12012-07-26 16:19:53 +08001232 assert ((self.test_list.options.min_charge_pct is None) ==
1233 (self.test_list.options.max_charge_pct is None))
Vic Yange83d9a12013-04-19 20:00:20 +08001234 if utils.in_chroot():
1235 logging.info('In chroot, ignoring charge manager and charge state')
1236 elif self.test_list.options.min_charge_pct is not None:
Vic Yang4953fc12012-07-26 16:19:53 +08001237 self.charge_manager = ChargeManager(self.test_list.options.min_charge_pct,
1238 self.test_list.options.max_charge_pct)
Jon Salzad7353b2012-10-15 16:22:46 +08001239 system.SystemStatus.charge_manager = self.charge_manager
Cheng-Yi Chiangd8186952013-04-04 23:41:14 +08001240 else:
1241 # Goofy should set charger state to charge if charge_manager is disabled.
1242 try:
1243 system.GetBoard().SetChargeState(Board.ChargeState.CHARGE)
1244 except BoardException:
1245 logging.exception('Unable to set charge state on this board')
Vic Yang4953fc12012-07-26 16:19:53 +08001246
Jon Salz0697cbf2012-07-04 15:14:04 +08001247 os.environ['CROS_FACTORY'] = '1'
1248 os.environ['CROS_DISABLE_SITE_SYSINFO'] = '1'
1249
1250 # Set CROS_UI since some behaviors in ui.py depend on the
1251 # particular UI in use. TODO(jsalz): Remove this (and all
1252 # places it is used) when the GTK UI is removed.
1253 os.environ['CROS_UI'] = self.options.ui
1254
1255 if self.options.ui == 'chrome':
1256 self.env.launch_chrome()
1257 logging.info('Waiting for a web socket connection')
Cheng-Yi Chiangfd8ed392013-03-08 21:37:31 +08001258 self.web_socket_manager.wait()
Jon Salz0697cbf2012-07-04 15:14:04 +08001259
1260 # Wait for the test widget size to be set; this is done in
1261 # an asynchronous RPC so there is a small chance that the
1262 # web socket might be opened first.
1263 for _ in range(100): # 10 s
1264 try:
1265 if self.state_instance.get_shared_data('test_widget_size'):
1266 break
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001267 except KeyError:
Jon Salz0697cbf2012-07-04 15:14:04 +08001268 pass # Retry
1269 time.sleep(0.1) # 100 ms
1270 else:
1271 logging.warn('Never received test_widget_size from UI')
1272 elif self.options.ui == 'gtk':
1273 self.start_ui()
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001274
Ricky Liang650f6bf2012-09-28 13:22:54 +08001275 # Create download path for autotest beforehand or autotests run at
1276 # the same time might fail due to race condition.
1277 if not factory.in_chroot():
1278 utils.TryMakeDirs(os.path.join('/usr/local/autotest', 'tests',
1279 'download'))
1280
Jon Salz0697cbf2012-07-04 15:14:04 +08001281 def state_change_callback(test, test_state):
1282 self.event_client.post_event(
1283 Event(Event.Type.STATE_CHANGE,
1284 path=test.path, state=test_state))
1285 self.test_list.state_change_callback = state_change_callback
Jon Salz73e0fd02012-04-04 11:46:38 +08001286
Jon Salza6711d72012-07-18 14:33:03 +08001287 for handler in self.on_ui_startup:
1288 handler()
1289
1290 self.prespawner = Prespawner()
1291 self.prespawner.start()
1292
Jon Salz0697cbf2012-07-04 15:14:04 +08001293 try:
1294 tests_after_shutdown = self.state_instance.get_shared_data(
1295 'tests_after_shutdown')
1296 except KeyError:
1297 tests_after_shutdown = None
Jon Salz57717ca2012-04-04 16:47:25 +08001298
Jon Salz5c344f62012-07-13 14:31:16 +08001299 force_auto_run = (tests_after_shutdown == FORCE_AUTO_RUN)
1300 if not force_auto_run and tests_after_shutdown is not None:
Jon Salz0697cbf2012-07-04 15:14:04 +08001301 logging.info('Resuming tests after shutdown: %s',
1302 tests_after_shutdown)
Jon Salz0697cbf2012-07-04 15:14:04 +08001303 self.tests_to_run.extend(
1304 self.test_list.lookup_path(t) for t in tests_after_shutdown)
1305 self.run_queue.put(self.run_next_test)
1306 else:
Jon Salz5c344f62012-07-13 14:31:16 +08001307 if force_auto_run or self.test_list.options.auto_run_on_start:
Jon Salz0697cbf2012-07-04 15:14:04 +08001308 self.run_queue.put(
1309 lambda: self.run_tests(self.test_list, untested_only=True))
Jon Salz5c344f62012-07-13 14:31:16 +08001310 self.state_instance.set_shared_data('tests_after_shutdown', None)
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001311
Dean Liao592e4d52013-01-10 20:06:39 +08001312 self.may_disable_cros_shortcut_keys()
1313
1314 def may_disable_cros_shortcut_keys(self):
1315 test_options = self.test_list.options
1316 if test_options.disable_cros_shortcut_keys:
1317 logging.info('Filter ChromeOS shortcut keys.')
1318 self.key_filter = KeyFilter(
1319 unmap_caps_lock=test_options.disable_caps_lock,
1320 caps_lock_keycode=test_options.caps_lock_keycode)
1321 self.key_filter.Start()
1322
Jon Salz0697cbf2012-07-04 15:14:04 +08001323 def run(self):
1324 '''Runs Goofy.'''
1325 # Process events forever.
1326 while self.run_once(True):
1327 pass
Jon Salz73e0fd02012-04-04 11:46:38 +08001328
Jon Salz0697cbf2012-07-04 15:14:04 +08001329 def run_once(self, block=False):
1330 '''Runs all items pending in the event loop.
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001331
Jon Salz0697cbf2012-07-04 15:14:04 +08001332 Args:
1333 block: If true, block until at least one event is processed.
Jon Salz7c15e8b2012-06-19 17:10:37 +08001334
Jon Salz0697cbf2012-07-04 15:14:04 +08001335 Returns:
1336 True to keep going or False to shut down.
1337 '''
1338 events = utils.DrainQueue(self.run_queue)
cychiang21886742012-07-05 15:16:32 +08001339 while not events:
Jon Salz0697cbf2012-07-04 15:14:04 +08001340 # Nothing on the run queue.
1341 self._run_queue_idle()
1342 if block:
1343 # Block for at least one event...
cychiang21886742012-07-05 15:16:32 +08001344 try:
1345 events.append(self.run_queue.get(timeout=RUN_QUEUE_TIMEOUT_SECS))
1346 except Queue.Empty:
1347 # Keep going (calling _run_queue_idle() again at the top of
1348 # the loop)
1349 continue
Jon Salz0697cbf2012-07-04 15:14:04 +08001350 # ...and grab anything else that showed up at the same
1351 # time.
1352 events.extend(utils.DrainQueue(self.run_queue))
cychiang21886742012-07-05 15:16:32 +08001353 else:
1354 break
Jon Salz51528e12012-07-02 18:54:45 +08001355
Jon Salz0697cbf2012-07-04 15:14:04 +08001356 for event in events:
1357 if not event:
1358 # Shutdown request.
1359 self.run_queue.task_done()
1360 return False
Jon Salz51528e12012-07-02 18:54:45 +08001361
Jon Salz0697cbf2012-07-04 15:14:04 +08001362 try:
1363 event()
Jon Salz85a39882012-07-05 16:45:04 +08001364 except: # pylint: disable=W0702
1365 logging.exception('Error in event loop')
Jon Salz0697cbf2012-07-04 15:14:04 +08001366 self.record_exception(traceback.format_exception_only(
1367 *sys.exc_info()[:2]))
1368 # But keep going
1369 finally:
1370 self.run_queue.task_done()
1371 return True
Jon Salz0405ab52012-03-16 15:26:52 +08001372
Jon Salz0e6532d2012-10-25 16:30:11 +08001373 def _should_sync_time(self, foreground=False):
1374 '''Returns True if we should attempt syncing time with shopfloor.
1375
1376 Args:
1377 foreground: If True, synchronizes even if background syncing
1378 is disabled (e.g., in explicit sync requests from the
1379 SyncShopfloor test).
1380 '''
1381 return ((foreground or
1382 self.test_list.options.sync_time_period_secs) and
Jon Salz54882d02012-08-31 01:57:54 +08001383 self.time_sanitizer and
1384 (not self.time_synced) and
1385 (not factory.in_chroot()))
1386
Jon Salz0e6532d2012-10-25 16:30:11 +08001387 def sync_time_with_shopfloor_server(self, foreground=False):
Jon Salz54882d02012-08-31 01:57:54 +08001388 '''Syncs time with shopfloor server, if not yet synced.
1389
Jon Salz0e6532d2012-10-25 16:30:11 +08001390 Args:
1391 foreground: If True, synchronizes even if background syncing
1392 is disabled (e.g., in explicit sync requests from the
1393 SyncShopfloor test).
1394
Jon Salz54882d02012-08-31 01:57:54 +08001395 Returns:
1396 False if no time sanitizer is available, or True if this sync (or a
1397 previous sync) succeeded.
1398
1399 Raises:
1400 Exception if unable to contact the shopfloor server.
1401 '''
Jon Salz0e6532d2012-10-25 16:30:11 +08001402 if self._should_sync_time(foreground):
Jon Salz54882d02012-08-31 01:57:54 +08001403 self.time_sanitizer.SyncWithShopfloor()
1404 self.time_synced = True
1405 return self.time_synced
1406
Jon Salzb92c5112012-09-21 15:40:11 +08001407 def log_disk_space_stats(self):
1408 if not self.test_list.options.log_disk_space_period_secs:
1409 return
1410
1411 now = time.time()
1412 if (self.last_log_disk_space_time and
1413 now - self.last_log_disk_space_time <
1414 self.test_list.options.log_disk_space_period_secs):
1415 return
1416 self.last_log_disk_space_time = now
1417
1418 try:
Jon Salz3c493bb2013-02-07 17:24:58 +08001419 message = disk_space.FormatSpaceUsedAll()
1420 if message != self.last_log_disk_space_message:
1421 logging.info(message)
1422 self.last_log_disk_space_message = message
Jon Salzb92c5112012-09-21 15:40:11 +08001423 except: # pylint: disable=W0702
1424 logging.exception('Unable to get disk space used')
1425
Jon Salz8fa8e832012-07-13 19:04:09 +08001426 def sync_time_in_background(self):
Jon Salzb22d1172012-08-06 10:38:57 +08001427 '''Writes out current time and tries to sync with shopfloor server.'''
1428 if not self.time_sanitizer:
1429 return
1430
1431 # Write out the current time.
1432 self.time_sanitizer.SaveTime()
1433
Jon Salz54882d02012-08-31 01:57:54 +08001434 if not self._should_sync_time():
Jon Salz8fa8e832012-07-13 19:04:09 +08001435 return
1436
1437 now = time.time()
1438 if self.last_sync_time and (
1439 now - self.last_sync_time <
1440 self.test_list.options.sync_time_period_secs):
1441 # Not yet time for another check.
1442 return
1443 self.last_sync_time = now
1444
1445 def target():
1446 try:
Jon Salz54882d02012-08-31 01:57:54 +08001447 self.sync_time_with_shopfloor_server()
Jon Salz8fa8e832012-07-13 19:04:09 +08001448 except: # pylint: disable=W0702
1449 # Oh well. Log an error (but no trace)
1450 logging.info(
1451 'Unable to get time from shopfloor server: %s',
1452 utils.FormatExceptionOnly())
1453
1454 thread = threading.Thread(target=target)
1455 thread.daemon = True
1456 thread.start()
1457
Jon Salz0697cbf2012-07-04 15:14:04 +08001458 def _run_queue_idle(self):
Vic Yang4953fc12012-07-26 16:19:53 +08001459 '''Invoked when the run queue has no events.
1460
1461 This method must not raise exception.
1462 '''
Jon Salzb22d1172012-08-06 10:38:57 +08001463 now = time.time()
1464 if (self.last_idle and
1465 now < (self.last_idle + RUN_QUEUE_TIMEOUT_SECS - 1)):
1466 # Don't run more often than once every (RUN_QUEUE_TIMEOUT_SECS -
1467 # 1) seconds.
1468 return
1469
1470 self.last_idle = now
1471
Vic Yang311ddb82012-09-26 12:08:28 +08001472 self.check_exclusive()
cychiang21886742012-07-05 15:16:32 +08001473 self.check_for_updates()
Jon Salz8fa8e832012-07-13 19:04:09 +08001474 self.sync_time_in_background()
Jon Salzb92c5112012-09-21 15:40:11 +08001475 self.log_disk_space_stats()
Jon Salz57717ca2012-04-04 16:47:25 +08001476
Jon Salz16d10542012-07-23 12:18:45 +08001477 def handle_event_logs(self, log_name, chunk):
Jon Salz0697cbf2012-07-04 15:14:04 +08001478 '''Callback for event watcher.
Jon Salz258a40c2012-04-19 12:34:01 +08001479
Jon Salz0697cbf2012-07-04 15:14:04 +08001480 Attempts to upload the event logs to the shopfloor server.
1481 '''
1482 description = 'event logs (%s, %d bytes)' % (log_name, len(chunk))
1483 start_time = time.time()
Jon Salz0697cbf2012-07-04 15:14:04 +08001484 shopfloor_client = shopfloor.get_instance(
1485 detect=True,
1486 timeout=self.test_list.options.shopfloor_timeout_secs)
Jon Salzb10cf512012-08-09 17:29:21 +08001487 shopfloor_client.UploadEvent(log_name, Binary(chunk))
Jon Salz0697cbf2012-07-04 15:14:04 +08001488 logging.info(
1489 'Successfully synced %s in %.03f s',
1490 description, time.time() - start_time)
Jon Salz57717ca2012-04-04 16:47:25 +08001491
Jon Salz0697cbf2012-07-04 15:14:04 +08001492 def run_tests_with_status(self, statuses_to_run, starting_at=None,
1493 root=None):
1494 '''Runs all top-level tests with a particular status.
Jon Salz0405ab52012-03-16 15:26:52 +08001495
Jon Salz0697cbf2012-07-04 15:14:04 +08001496 All active tests, plus any tests to re-run, are reset.
Jon Salz57717ca2012-04-04 16:47:25 +08001497
Jon Salz0697cbf2012-07-04 15:14:04 +08001498 Args:
1499 starting_at: If provided, only auto-runs tests beginning with
1500 this test.
1501 '''
1502 root = root or self.test_list
Jon Salz57717ca2012-04-04 16:47:25 +08001503
Jon Salz0697cbf2012-07-04 15:14:04 +08001504 if starting_at:
1505 # Make sure they passed a test, not a string.
1506 assert isinstance(starting_at, factory.FactoryTest)
Jon Salz0405ab52012-03-16 15:26:52 +08001507
Jon Salz0697cbf2012-07-04 15:14:04 +08001508 tests_to_reset = []
1509 tests_to_run = []
Jon Salz0405ab52012-03-16 15:26:52 +08001510
Jon Salz0697cbf2012-07-04 15:14:04 +08001511 found_starting_at = False
Jon Salz0405ab52012-03-16 15:26:52 +08001512
Jon Salz0697cbf2012-07-04 15:14:04 +08001513 for test in root.get_top_level_tests():
1514 if starting_at:
1515 if test == starting_at:
1516 # We've found starting_at; do auto-run on all
1517 # subsequent tests.
1518 found_starting_at = True
1519 if not found_starting_at:
1520 # Don't start this guy yet
1521 continue
Jon Salz0405ab52012-03-16 15:26:52 +08001522
Jon Salz0697cbf2012-07-04 15:14:04 +08001523 status = test.get_state().status
1524 if status == TestState.ACTIVE or status in statuses_to_run:
1525 # Reset the test (later; we will need to abort
1526 # all active tests first).
1527 tests_to_reset.append(test)
1528 if status in statuses_to_run:
1529 tests_to_run.append(test)
Jon Salz0405ab52012-03-16 15:26:52 +08001530
Jon Salz0697cbf2012-07-04 15:14:04 +08001531 self.abort_active_tests()
Jon Salz258a40c2012-04-19 12:34:01 +08001532
Jon Salz0697cbf2012-07-04 15:14:04 +08001533 # Reset all statuses of the tests to run (in case any tests were active;
1534 # we want them to be run again).
1535 for test_to_reset in tests_to_reset:
1536 for test in test_to_reset.walk():
1537 test.update_state(status=TestState.UNTESTED)
Jon Salz57717ca2012-04-04 16:47:25 +08001538
Jon Salz0697cbf2012-07-04 15:14:04 +08001539 self.run_tests(tests_to_run, untested_only=True)
Jon Salz0405ab52012-03-16 15:26:52 +08001540
Jon Salz0697cbf2012-07-04 15:14:04 +08001541 def restart_tests(self, root=None):
1542 '''Restarts all tests.'''
1543 root = root or self.test_list
Jon Salz0405ab52012-03-16 15:26:52 +08001544
Jon Salz0697cbf2012-07-04 15:14:04 +08001545 self.abort_active_tests()
1546 for test in root.walk():
1547 test.update_state(status=TestState.UNTESTED)
1548 self.run_tests(root)
Hung-Te Lin96632362012-03-20 21:14:18 +08001549
Jon Salz0697cbf2012-07-04 15:14:04 +08001550 def auto_run(self, starting_at=None, root=None):
1551 '''"Auto-runs" tests that have not been run yet.
Hung-Te Lin96632362012-03-20 21:14:18 +08001552
Jon Salz0697cbf2012-07-04 15:14:04 +08001553 Args:
1554 starting_at: If provide, only auto-runs tests beginning with
1555 this test.
1556 '''
1557 root = root or self.test_list
1558 self.run_tests_with_status([TestState.UNTESTED, TestState.ACTIVE],
1559 starting_at=starting_at,
1560 root=root)
Jon Salz968e90b2012-03-18 16:12:43 +08001561
Jon Salz0697cbf2012-07-04 15:14:04 +08001562 def re_run_failed(self, root=None):
1563 '''Re-runs failed tests.'''
1564 root = root or self.test_list
1565 self.run_tests_with_status([TestState.FAILED], root=root)
Jon Salz57717ca2012-04-04 16:47:25 +08001566
Jon Salz0697cbf2012-07-04 15:14:04 +08001567 def show_review_information(self):
1568 '''Event handler for showing review information screen.
Jon Salz57717ca2012-04-04 16:47:25 +08001569
Jon Salz0697cbf2012-07-04 15:14:04 +08001570 The information screene is rendered by main UI program (ui.py), so in
1571 goofy we only need to kill all active tests, set them as untested, and
1572 clear remaining tests.
1573 '''
1574 self.kill_active_tests(False)
Jon Salza6711d72012-07-18 14:33:03 +08001575 self.cancel_pending_tests()
Jon Salz57717ca2012-04-04 16:47:25 +08001576
Jon Salz0697cbf2012-07-04 15:14:04 +08001577 def handle_switch_test(self, event):
1578 '''Switches to a particular test.
Jon Salz0405ab52012-03-16 15:26:52 +08001579
Jon Salz0697cbf2012-07-04 15:14:04 +08001580 @param event: The SWITCH_TEST event.
1581 '''
1582 test = self.test_list.lookup_path(event.path)
1583 if not test:
1584 logging.error('Unknown test %r', event.key)
1585 return
Jon Salz73e0fd02012-04-04 11:46:38 +08001586
Jon Salz0697cbf2012-07-04 15:14:04 +08001587 invoc = self.invocations.get(test)
1588 if invoc and test.backgroundable:
1589 # Already running: just bring to the front if it
1590 # has a UI.
1591 logging.info('Setting visible test to %s', test.path)
Jon Salz36fbbb52012-07-05 13:45:06 +08001592 self.set_visible_test(test)
Jon Salz0697cbf2012-07-04 15:14:04 +08001593 return
Jon Salz73e0fd02012-04-04 11:46:38 +08001594
Jon Salz0697cbf2012-07-04 15:14:04 +08001595 self.abort_active_tests()
1596 for t in test.walk():
1597 t.update_state(status=TestState.UNTESTED)
Jon Salz73e0fd02012-04-04 11:46:38 +08001598
Jon Salz0697cbf2012-07-04 15:14:04 +08001599 if self.test_list.options.auto_run_on_keypress:
1600 self.auto_run(starting_at=test)
1601 else:
1602 self.run_tests(test)
Jon Salz73e0fd02012-04-04 11:46:38 +08001603
Jon Salz0697cbf2012-07-04 15:14:04 +08001604 def wait(self):
1605 '''Waits for all pending invocations.
1606
1607 Useful for testing.
1608 '''
Jon Salz1acc8742012-07-17 17:45:55 +08001609 while self.invocations:
1610 for k, v in self.invocations.iteritems():
1611 logging.info('Waiting for %s to complete...', k)
1612 v.thread.join()
1613 self.reap_completed_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +08001614
1615 def check_exceptions(self):
1616 '''Raises an error if any exceptions have occurred in
1617 invocation threads.'''
1618 if self.exceptions:
1619 raise RuntimeError('Exception in invocation thread: %r' %
1620 self.exceptions)
1621
1622 def record_exception(self, msg):
1623 '''Records an exception in an invocation thread.
1624
1625 An exception with the given message will be rethrown when
1626 Goofy is destroyed.'''
1627 self.exceptions.append(msg)
Jon Salz73e0fd02012-04-04 11:46:38 +08001628
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001629
1630if __name__ == '__main__':
Jon Salz77c151e2012-08-28 07:20:37 +08001631 goofy = Goofy()
1632 try:
1633 goofy.main()
Jon Salz0f996602012-10-03 15:26:48 +08001634 except SystemExit:
1635 # Propagate SystemExit without logging.
1636 raise
Jon Salz31373eb2012-09-21 16:19:49 +08001637 except:
Jon Salz0f996602012-10-03 15:26:48 +08001638 # Log the error before trying to shut down (unless it's a graceful
1639 # exit).
Jon Salz31373eb2012-09-21 16:19:49 +08001640 logging.exception('Error in main loop')
1641 raise
Jon Salz77c151e2012-08-28 07:20:37 +08001642 finally:
1643 goofy.destroy()