blob: 4960fcdc066c3769b1261e60c05798586852bb80 [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
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +080028from cros.factory.event_log import EventLog, FloatDigit
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
Justin Chuang83813982013-05-13 01:26:32 +080067# Sync disks when battery level is higher than this value.
68# Otherwise, power loss during disk sync operation may incur even worse outcome.
69MIN_BATTERY_LEVEL_FOR_DISK_SYNC = 1.0
70
Jon Salz758e6cc2012-04-03 15:47:07 +080071GOOFY_IN_CHROOT_WARNING = '\n' + ('*' * 70) + '''
72You are running Goofy inside the chroot. Autotests are not supported.
73
74To use Goofy in the chroot, first install an Xvnc server:
75
Jon Salz0697cbf2012-07-04 15:14:04 +080076 sudo apt-get install tightvncserver
Jon Salz758e6cc2012-04-03 15:47:07 +080077
78...and then start a VNC X server outside the chroot:
79
Jon Salz0697cbf2012-07-04 15:14:04 +080080 vncserver :10 &
81 vncviewer :10
Jon Salz758e6cc2012-04-03 15:47:07 +080082
83...and run Goofy as follows:
84
Jon Salz0697cbf2012-07-04 15:14:04 +080085 env --unset=XAUTHORITY DISPLAY=localhost:10 python goofy.py
Jon Salz758e6cc2012-04-03 15:47:07 +080086''' + ('*' * 70)
Jon Salz73e0fd02012-04-04 11:46:38 +080087suppress_chroot_warning = False
Hung-Te Linf2f78f72012-02-08 19:27:11 +080088
89def get_hwid_cfg():
Jon Salz0697cbf2012-07-04 15:14:04 +080090 '''
91 Returns the HWID config tag, or an empty string if none can be found.
92 '''
93 if 'CROS_HWID' in os.environ:
94 return os.environ['CROS_HWID']
95 if os.path.exists(HWID_CFG_PATH):
96 with open(HWID_CFG_PATH, 'rt') as hwid_cfg_handle:
97 return hwid_cfg_handle.read().strip()
98 return ''
Hung-Te Linf2f78f72012-02-08 19:27:11 +080099
100
101def find_test_list():
Jon Salz0697cbf2012-07-04 15:14:04 +0800102 '''
103 Returns the path to the active test list, based on the HWID config tag.
Jon Salzfb615892013-02-01 18:04:35 +0800104
105 The algorithm is:
106
107 - Try $FACTORY/test_lists/active (the symlink reflecting the option chosen
108 in the UI).
109 - For each of $FACTORY/custom, $FACTORY/test_lists (and
110 autotest/site_tests/suite_Factory for backward compatibility):
111 - Try test_list_${hwid_cfg} (if hwid_cfg is set)
112 - Try test_list
113 - Try test_list.generic
Jon Salz0697cbf2012-07-04 15:14:04 +0800114 '''
Jon Salzfb615892013-02-01 18:04:35 +0800115 # If the 'active' symlink is present, that trumps everything else.
116 if os.path.lexists(factory.ACTIVE_TEST_LIST_SYMLINK):
117 return os.path.realpath(factory.ACTIVE_TEST_LIST_SYMLINK)
118
Jon Salz0697cbf2012-07-04 15:14:04 +0800119 hwid_cfg = get_hwid_cfg()
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800120
Jon Salzfb615892013-02-01 18:04:35 +0800121 search_dirs = [CUSTOM_DIR, factory.TEST_LISTS_PATH]
Jon Salz4be56b02012-12-22 07:30:46 +0800122 if not utils.in_chroot():
123 # Also look in suite_Factory. For backward compatibility only;
124 # new boards should just put the test list in the "test_lists"
125 # directory.
126 search_dirs.insert(0, os.path.join(
127 os.path.dirname(factory.FACTORY_PATH),
128 'autotest', 'site_tests', 'suite_Factory'))
Jon Salz2f757d42012-06-27 17:06:42 +0800129
Jon Salzfb615892013-02-01 18:04:35 +0800130
131 search_files = []
Jon Salz0697cbf2012-07-04 15:14:04 +0800132 if hwid_cfg:
Jon Salzfb615892013-02-01 18:04:35 +0800133 search_files += [hwid_cfg]
134 search_files += ['test_list', 'test_list.generic']
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800135
Jon Salz0697cbf2012-07-04 15:14:04 +0800136 for d in search_dirs:
137 for f in search_files:
138 test_list = os.path.join(d, f)
139 if os.path.exists(test_list):
140 return test_list
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800141
Jon Salz0697cbf2012-07-04 15:14:04 +0800142 logging.warn('Cannot find test lists named any of %s in any of %s',
143 search_files, search_dirs)
144 return None
Jon Salz73e0fd02012-04-04 11:46:38 +0800145
Jon Salzfb615892013-02-01 18:04:35 +0800146
Jon Salz73e0fd02012-04-04 11:46:38 +0800147_inited_logging = False
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800148
149class Goofy(object):
Jon Salz0697cbf2012-07-04 15:14:04 +0800150 '''
151 The main factory flow.
152
153 Note that all methods in this class must be invoked from the main
154 (event) thread. Other threads, such as callbacks and TestInvocation
155 methods, should instead post events on the run queue.
156
157 TODO: Unit tests. (chrome-os-partner:7409)
158
159 Properties:
160 uuid: A unique UUID for this invocation of Goofy.
161 state_instance: An instance of FactoryState.
162 state_server: The FactoryState XML/RPC server.
163 state_server_thread: A thread running state_server.
164 event_server: The EventServer socket server.
165 event_server_thread: A thread running event_server.
166 event_client: A client to the event server.
167 connection_manager: The connection_manager object.
Cheng-Yi Chiang835f2682013-05-06 22:15:48 +0800168 system_log_manager: The SystemLogManager object.
169 core_dump_manager: The CoreDumpManager object.
Jon Salz0697cbf2012-07-04 15:14:04 +0800170 ui_process: The factory ui process object.
171 run_queue: A queue of callbacks to invoke from the main thread.
172 invocations: A map from FactoryTest objects to the corresponding
173 TestInvocations objects representing active tests.
174 tests_to_run: A deque of tests that should be run when the current
175 test(s) complete.
176 options: Command-line options.
177 args: Command-line args.
178 test_list: The test list.
179 event_handlers: Map of Event.Type to the method used to handle that
180 event. If the method has an 'event' argument, the event is passed
181 to the handler.
182 exceptions: Exceptions encountered in invocation threads.
Jon Salz3c493bb2013-02-07 17:24:58 +0800183 last_log_disk_space_message: The last message we logged about disk space
184 (to avoid duplication).
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +0800185 last_kick_sync_time: The last time to kick system_log_manager to sync
186 because of core dump files (to avoid kicking too soon then abort the
187 sync.)
Jon Salz416f9cc2013-05-10 18:32:50 +0800188 hooks: A Hooks object containing hooks for various Goofy actions.
Jon Salz0697cbf2012-07-04 15:14:04 +0800189 '''
190 def __init__(self):
191 self.uuid = str(uuid.uuid4())
192 self.state_instance = None
193 self.state_server = None
194 self.state_server_thread = None
Jon Salz16d10542012-07-23 12:18:45 +0800195 self.goofy_rpc = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800196 self.event_server = None
197 self.event_server_thread = None
198 self.event_client = None
199 self.connection_manager = None
Vic Yang4953fc12012-07-26 16:19:53 +0800200 self.charge_manager = None
Jon Salz8fa8e832012-07-13 19:04:09 +0800201 self.time_sanitizer = None
202 self.time_synced = False
Jon Salz0697cbf2012-07-04 15:14:04 +0800203 self.log_watcher = None
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +0800204 self.system_log_manager = None
Cheng-Yi Chiang835f2682013-05-06 22:15:48 +0800205 self.core_dump_manager = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800206 self.event_log = None
207 self.prespawner = None
208 self.ui_process = None
Jon Salzc79a9982012-08-30 04:42:01 +0800209 self.dummy_shopfloor = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800210 self.run_queue = Queue.Queue()
211 self.invocations = {}
212 self.tests_to_run = deque()
213 self.visible_test = None
214 self.chrome = None
Jon Salz416f9cc2013-05-10 18:32:50 +0800215 self.hooks = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800216
217 self.options = None
218 self.args = None
219 self.test_list = None
220 self.on_ui_startup = []
221 self.env = None
Jon Salzb22d1172012-08-06 10:38:57 +0800222 self.last_idle = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800223 self.last_shutdown_time = None
cychiang21886742012-07-05 15:16:32 +0800224 self.last_update_check = None
Jon Salz8fa8e832012-07-13 19:04:09 +0800225 self.last_sync_time = None
Jon Salzb92c5112012-09-21 15:40:11 +0800226 self.last_log_disk_space_time = None
Jon Salz3c493bb2013-02-07 17:24:58 +0800227 self.last_log_disk_space_message = None
Justin Chuang83813982013-05-13 01:26:32 +0800228 self.last_check_battery_time = None
229 self.last_check_battery_message = None
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +0800230 self.last_kick_sync_time = None
Vic Yang311ddb82012-09-26 12:08:28 +0800231 self.exclusive_items = set()
Jon Salz0f996602012-10-03 15:26:48 +0800232 self.event_log = None
Dean Liao592e4d52013-01-10 20:06:39 +0800233 self.key_filter = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800234
Jon Salz85a39882012-07-05 16:45:04 +0800235 def test_or_root(event, parent_or_group=True):
236 '''Returns the test affected by a particular event.
237
238 Args:
239 event: The event containing an optional 'path' attribute.
240 parent_on_group: If True, returns the top-level parent for a test (the
241 root node of the tests that need to be run together if the given test
242 path is to be run).
243 '''
Jon Salz0697cbf2012-07-04 15:14:04 +0800244 try:
245 path = event.path
246 except AttributeError:
247 path = None
248
249 if path:
Jon Salz85a39882012-07-05 16:45:04 +0800250 test = self.test_list.lookup_path(path)
251 if parent_or_group:
252 test = test.get_top_level_parent_or_group()
253 return test
Jon Salz0697cbf2012-07-04 15:14:04 +0800254 else:
255 return self.test_list
256
257 self.event_handlers = {
258 Event.Type.SWITCH_TEST: self.handle_switch_test,
259 Event.Type.SHOW_NEXT_ACTIVE_TEST:
260 lambda event: self.show_next_active_test(),
261 Event.Type.RESTART_TESTS:
262 lambda event: self.restart_tests(root=test_or_root(event)),
263 Event.Type.AUTO_RUN:
264 lambda event: self.auto_run(root=test_or_root(event)),
265 Event.Type.RE_RUN_FAILED:
266 lambda event: self.re_run_failed(root=test_or_root(event)),
267 Event.Type.RUN_TESTS_WITH_STATUS:
268 lambda event: self.run_tests_with_status(
269 event.status,
270 root=test_or_root(event)),
271 Event.Type.REVIEW:
272 lambda event: self.show_review_information(),
273 Event.Type.UPDATE_SYSTEM_INFO:
274 lambda event: self.update_system_info(),
Jon Salz0697cbf2012-07-04 15:14:04 +0800275 Event.Type.STOP:
Jon Salz85a39882012-07-05 16:45:04 +0800276 lambda event: self.stop(root=test_or_root(event, False),
277 fail=getattr(event, 'fail', False)),
Jon Salz36fbbb52012-07-05 13:45:06 +0800278 Event.Type.SET_VISIBLE_TEST:
279 lambda event: self.set_visible_test(
280 self.test_list.lookup_path(event.path)),
Jon Salz4712ac72013-02-07 17:12:05 +0800281 Event.Type.CLEAR_STATE:
282 lambda event: self.clear_state(self.test_list.lookup_path(event.path)),
Jon Salz0697cbf2012-07-04 15:14:04 +0800283 }
284
285 self.exceptions = []
286 self.web_socket_manager = None
287
288 def destroy(self):
289 if self.chrome:
290 self.chrome.kill()
291 self.chrome = None
Jon Salzc79a9982012-08-30 04:42:01 +0800292 if self.dummy_shopfloor:
293 self.dummy_shopfloor.kill()
294 self.dummy_shopfloor = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800295 if self.ui_process:
296 utils.kill_process_tree(self.ui_process, 'ui')
297 self.ui_process = None
298 if self.web_socket_manager:
299 logging.info('Stopping web sockets')
300 self.web_socket_manager.close()
301 self.web_socket_manager = None
302 if self.state_server_thread:
303 logging.info('Stopping state server')
304 self.state_server.shutdown()
305 self.state_server_thread.join()
306 self.state_server.server_close()
307 self.state_server_thread = None
308 if self.state_instance:
309 self.state_instance.close()
310 if self.event_server_thread:
311 logging.info('Stopping event server')
312 self.event_server.shutdown() # pylint: disable=E1101
313 self.event_server_thread.join()
314 self.event_server.server_close()
315 self.event_server_thread = None
316 if self.log_watcher:
317 if self.log_watcher.IsThreadStarted():
318 self.log_watcher.StopWatchThread()
319 self.log_watcher = None
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +0800320 if self.system_log_manager:
321 if self.system_log_manager.IsThreadRunning():
322 self.system_log_manager.StopSyncThread()
323 self.system_log_manager = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800324 if self.prespawner:
325 logging.info('Stopping prespawner')
326 self.prespawner.stop()
327 self.prespawner = None
328 if self.event_client:
329 logging.info('Closing event client')
330 self.event_client.close()
331 self.event_client = None
332 if self.event_log:
333 self.event_log.Close()
334 self.event_log = None
Dean Liao592e4d52013-01-10 20:06:39 +0800335 if self.key_filter:
336 self.key_filter.Stop()
337
Jon Salz0697cbf2012-07-04 15:14:04 +0800338 self.check_exceptions()
339 logging.info('Done destroying Goofy')
340
341 def start_state_server(self):
342 self.state_instance, self.state_server = (
343 state.create_server(bind_address='0.0.0.0'))
Jon Salz16d10542012-07-23 12:18:45 +0800344 self.goofy_rpc = GoofyRPC(self)
345 self.goofy_rpc.RegisterMethods(self.state_instance)
Jon Salz0697cbf2012-07-04 15:14:04 +0800346 logging.info('Starting state server')
347 self.state_server_thread = threading.Thread(
348 target=self.state_server.serve_forever,
349 name='StateServer')
350 self.state_server_thread.start()
351
352 def start_event_server(self):
353 self.event_server = EventServer()
354 logging.info('Starting factory event server')
355 self.event_server_thread = threading.Thread(
356 target=self.event_server.serve_forever,
357 name='EventServer') # pylint: disable=E1101
358 self.event_server_thread.start()
359
360 self.event_client = EventClient(
361 callback=self.handle_event, event_loop=self.run_queue)
362
363 self.web_socket_manager = WebSocketManager(self.uuid)
364 self.state_server.add_handler("/event",
365 self.web_socket_manager.handle_web_socket)
366
367 def start_ui(self):
368 ui_proc_args = [
369 os.path.join(factory.FACTORY_PACKAGE_PATH, 'test', 'ui.py'),
370 self.options.test_list]
371 if self.options.verbose:
372 ui_proc_args.append('-v')
373 logging.info('Starting ui %s', ui_proc_args)
Jon Salz78c32392012-07-25 14:18:29 +0800374 self.ui_process = Spawn(ui_proc_args)
Jon Salz0697cbf2012-07-04 15:14:04 +0800375 logging.info('Waiting for UI to come up...')
376 self.event_client.wait(
377 lambda event: event.type == Event.Type.UI_READY)
378 logging.info('UI has started')
379
380 def set_visible_test(self, test):
381 if self.visible_test == test:
382 return
Jon Salz2f2d42c2012-07-30 12:30:34 +0800383 if test and not test.has_ui:
384 return
Jon Salz0697cbf2012-07-04 15:14:04 +0800385
386 if test:
387 test.update_state(visible=True)
388 if self.visible_test:
389 self.visible_test.update_state(visible=False)
390 self.visible_test = test
391
Jon Salzd4306c82012-11-30 15:16:36 +0800392 def _log_startup_messages(self):
393 '''Logs the tail of var/log/messages and mosys and EC console logs.'''
394 # TODO(jsalz): This is mostly a copy-and-paste of code in init_states,
395 # for factory-3004.B only. Consolidate and merge back to ToT.
396 if utils.in_chroot():
397 return
398
399 try:
400 var_log_messages = (
401 utils.var_log_messages_before_reboot())
402 logging.info(
403 'Tail of /var/log/messages before last reboot:\n'
404 '%s', ('\n'.join(
405 ' ' + x for x in var_log_messages)))
406 except: # pylint: disable=W0702
407 logging.exception('Unable to grok /var/log/messages')
408
409 try:
410 mosys_log = utils.Spawn(
411 ['mosys', 'eventlog', 'list'],
412 read_stdout=True, log_stderr_on_error=True).stdout_data
413 logging.info('System eventlog from mosys:\n%s\n', mosys_log)
414 except: # pylint: disable=W0702
415 logging.exception('Unable to read mosys eventlog')
416
417 try:
Vic Yang8341dde2013-01-29 16:48:52 +0800418 board = system.GetBoard()
419 ec_console_log = board.GetECConsoleLog()
Jon Salzd4306c82012-11-30 15:16:36 +0800420 logging.info('EC console log after reboot:\n%s\n', ec_console_log)
421 except: # pylint: disable=W0702
422 logging.exception('Error retrieving EC console log')
423
Jon Salz0697cbf2012-07-04 15:14:04 +0800424 def handle_shutdown_complete(self, test, test_state):
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800425 '''
Jon Salz0697cbf2012-07-04 15:14:04 +0800426 Handles the case where a shutdown was detected during a shutdown step.
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800427
Jon Salz0697cbf2012-07-04 15:14:04 +0800428 @param test: The ShutdownStep.
429 @param test_state: The test state.
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800430 '''
Jon Salz0697cbf2012-07-04 15:14:04 +0800431 test_state = test.update_state(increment_shutdown_count=1)
432 logging.info('Detected shutdown (%d of %d)',
433 test_state.shutdown_count, test.iterations)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800434
Jon Salz0697cbf2012-07-04 15:14:04 +0800435 def log_and_update_state(status, error_msg, **kw):
436 self.event_log.Log('rebooted',
437 status=status, error_msg=error_msg, **kw)
Jon Salzd4306c82012-11-30 15:16:36 +0800438 logging.info('Rebooted: status=%s, %s', status,
439 (('error_msg=%s' % error_msg) if error_msg else None))
Jon Salz0697cbf2012-07-04 15:14:04 +0800440 test.update_state(status=status, error_msg=error_msg)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800441
Jon Salz0697cbf2012-07-04 15:14:04 +0800442 if not self.last_shutdown_time:
443 log_and_update_state(status=TestState.FAILED,
444 error_msg='Unable to read shutdown_time')
445 return
Jon Salz258a40c2012-04-19 12:34:01 +0800446
Jon Salz0697cbf2012-07-04 15:14:04 +0800447 now = time.time()
448 logging.info('%.03f s passed since reboot',
449 now - self.last_shutdown_time)
Jon Salz258a40c2012-04-19 12:34:01 +0800450
Jon Salz0697cbf2012-07-04 15:14:04 +0800451 if self.last_shutdown_time > now:
452 test.update_state(status=TestState.FAILED,
453 error_msg='Time moved backward during reboot')
454 elif (isinstance(test, factory.RebootStep) and
455 self.test_list.options.max_reboot_time_secs and
456 (now - self.last_shutdown_time >
457 self.test_list.options.max_reboot_time_secs)):
458 # A reboot took too long; fail. (We don't check this for
459 # HaltSteps, because the machine could be halted for a
460 # very long time, and even unplugged with battery backup,
461 # thus hosing the clock.)
462 log_and_update_state(
463 status=TestState.FAILED,
464 error_msg=('More than %d s elapsed during reboot '
465 '(%.03f s, from %s to %s)' % (
466 self.test_list.options.max_reboot_time_secs,
467 now - self.last_shutdown_time,
468 utils.TimeString(self.last_shutdown_time),
469 utils.TimeString(now))),
470 duration=(now-self.last_shutdown_time))
Jon Salzd4306c82012-11-30 15:16:36 +0800471 self._log_startup_messages()
Jon Salz0697cbf2012-07-04 15:14:04 +0800472 elif test_state.shutdown_count == test.iterations:
473 # Good!
474 log_and_update_state(status=TestState.PASSED,
475 duration=(now - self.last_shutdown_time),
476 error_msg='')
477 elif test_state.shutdown_count > test.iterations:
478 # Shut down too many times
479 log_and_update_state(status=TestState.FAILED,
480 error_msg='Too many shutdowns')
Jon Salzd4306c82012-11-30 15:16:36 +0800481 self._log_startup_messages()
Jon Salz0697cbf2012-07-04 15:14:04 +0800482 elif utils.are_shift_keys_depressed():
483 logging.info('Shift keys are depressed; cancelling restarts')
484 # Abort shutdown
485 log_and_update_state(
486 status=TestState.FAILED,
487 error_msg='Shutdown aborted with double shift keys')
Jon Salza6711d72012-07-18 14:33:03 +0800488 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +0800489 else:
490 def handler():
491 if self._prompt_cancel_shutdown(
492 test, test_state.shutdown_count + 1):
Jon Salza6711d72012-07-18 14:33:03 +0800493 factory.console.info('Shutdown aborted by operator')
Jon Salz0697cbf2012-07-04 15:14:04 +0800494 log_and_update_state(
495 status=TestState.FAILED,
496 error_msg='Shutdown aborted by operator')
Jon Salza6711d72012-07-18 14:33:03 +0800497 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +0800498 return
Jon Salz0405ab52012-03-16 15:26:52 +0800499
Jon Salz0697cbf2012-07-04 15:14:04 +0800500 # Time to shutdown again
501 log_and_update_state(
502 status=TestState.ACTIVE,
503 error_msg='',
504 iteration=test_state.shutdown_count)
Jon Salz73e0fd02012-04-04 11:46:38 +0800505
Jon Salz0697cbf2012-07-04 15:14:04 +0800506 self.event_log.Log('shutdown', operation='reboot')
507 self.state_instance.set_shared_data('shutdown_time',
508 time.time())
509 self.env.shutdown('reboot')
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800510
Jon Salz0697cbf2012-07-04 15:14:04 +0800511 self.on_ui_startup.append(handler)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800512
Jon Salz0697cbf2012-07-04 15:14:04 +0800513 def _prompt_cancel_shutdown(self, test, iteration):
514 if self.options.ui != 'chrome':
515 return False
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800516
Jon Salz0697cbf2012-07-04 15:14:04 +0800517 pending_shutdown_data = {
518 'delay_secs': test.delay_secs,
519 'time': time.time() + test.delay_secs,
520 'operation': test.operation,
521 'iteration': iteration,
522 'iterations': test.iterations,
523 }
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800524
Jon Salz0697cbf2012-07-04 15:14:04 +0800525 # Create a new (threaded) event client since we
526 # don't want to use the event loop for this.
527 with EventClient() as event_client:
528 event_client.post_event(Event(Event.Type.PENDING_SHUTDOWN,
529 **pending_shutdown_data))
530 aborted = event_client.wait(
531 lambda event: event.type == Event.Type.CANCEL_SHUTDOWN,
532 timeout=test.delay_secs) is not None
533 if aborted:
534 event_client.post_event(Event(Event.Type.PENDING_SHUTDOWN))
535 return aborted
Jon Salz258a40c2012-04-19 12:34:01 +0800536
Jon Salz0697cbf2012-07-04 15:14:04 +0800537 def init_states(self):
538 '''
539 Initializes all states on startup.
540 '''
541 for test in self.test_list.get_all_tests():
542 # Make sure the state server knows about all the tests,
543 # defaulting to an untested state.
544 test.update_state(update_parent=False, visible=False)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800545
Jon Salz0697cbf2012-07-04 15:14:04 +0800546 var_log_messages = None
Vic Yanga9c32212012-08-16 20:07:54 +0800547 mosys_log = None
Vic Yange4c275d2012-08-28 01:50:20 +0800548 ec_console_log = None
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800549
Jon Salz0697cbf2012-07-04 15:14:04 +0800550 # Any 'active' tests should be marked as failed now.
551 for test in self.test_list.walk():
Jon Salza6711d72012-07-18 14:33:03 +0800552 if not test.is_leaf():
553 # Don't bother with parents; they will be updated when their
554 # children are updated.
555 continue
556
Jon Salz0697cbf2012-07-04 15:14:04 +0800557 test_state = test.get_state()
558 if test_state.status != TestState.ACTIVE:
559 continue
560 if isinstance(test, factory.ShutdownStep):
561 # Shutdown while the test was active - that's good.
562 self.handle_shutdown_complete(test, test_state)
563 else:
564 # Unexpected shutdown. Grab /var/log/messages for context.
565 if var_log_messages is None:
566 try:
567 var_log_messages = (
568 utils.var_log_messages_before_reboot())
569 # Write it to the log, to make it easier to
570 # correlate with /var/log/messages.
571 logging.info(
572 'Unexpected shutdown. '
573 'Tail of /var/log/messages before last reboot:\n'
574 '%s', ('\n'.join(
575 ' ' + x for x in var_log_messages)))
576 except: # pylint: disable=W0702
577 logging.exception('Unable to grok /var/log/messages')
578 var_log_messages = []
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800579
Jon Salz008f4ea2012-08-28 05:39:45 +0800580 if mosys_log is None and not utils.in_chroot():
581 try:
582 mosys_log = utils.Spawn(
583 ['mosys', 'eventlog', 'list'],
584 read_stdout=True, log_stderr_on_error=True).stdout_data
585 # Write it to the log also.
586 logging.info('System eventlog from mosys:\n%s\n', mosys_log)
587 except: # pylint: disable=W0702
588 logging.exception('Unable to read mosys eventlog')
Vic Yanga9c32212012-08-16 20:07:54 +0800589
Vic Yange4c275d2012-08-28 01:50:20 +0800590 if ec_console_log is None:
591 try:
Vic Yang8341dde2013-01-29 16:48:52 +0800592 board = system.GetBoard()
593 ec_console_log = board.GetECConsoleLog()
Vic Yange4c275d2012-08-28 01:50:20 +0800594 logging.info('EC console log after reboot:\n%s\n', ec_console_log)
Jon Salzfe1f6652012-09-07 05:40:14 +0800595 except: # pylint: disable=W0702
Vic Yange4c275d2012-08-28 01:50:20 +0800596 logging.exception('Error retrieving EC console log')
597
Jon Salz0697cbf2012-07-04 15:14:04 +0800598 error_msg = 'Unexpected shutdown while test was running'
599 self.event_log.Log('end_test',
600 path=test.path,
601 status=TestState.FAILED,
602 invocation=test.get_state().invocation,
603 error_msg=error_msg,
Vic Yanga9c32212012-08-16 20:07:54 +0800604 var_log_messages='\n'.join(var_log_messages),
605 mosys_log=mosys_log)
Jon Salz0697cbf2012-07-04 15:14:04 +0800606 test.update_state(
607 status=TestState.FAILED,
608 error_msg=error_msg)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800609
Jon Salz50efe942012-07-26 11:54:10 +0800610 if not test.never_fails:
611 # For "never_fails" tests (such as "Start"), don't cancel
612 # pending tests, since reboot is expected.
613 factory.console.info('Unexpected shutdown while test %s '
614 'running; cancelling any pending tests',
615 test.path)
616 self.state_instance.set_shared_data('tests_after_shutdown', [])
Jon Salz69806bb2012-07-20 18:05:02 +0800617
Jon Salz008f4ea2012-08-28 05:39:45 +0800618 self.update_skipped_tests()
619
620 def update_skipped_tests(self):
621 '''
622 Updates skipped states based on run_if.
623 '''
624 for t in self.test_list.walk():
625 if t.is_leaf() and t.run_if_table_name:
626 skip = False
627 try:
628 aux = shopfloor.get_selected_aux_data(t.run_if_table_name)
629 value = aux.get(t.run_if_col)
630 if value is not None:
631 skip = (not value) ^ t.run_if_not
632 except ValueError:
633 # Not available; assume it shouldn't be skipped
634 pass
635
636 test_state = t.get_state()
637 if ((not skip) and
638 (test_state.status == TestState.PASSED) and
639 (test_state.error_msg == TestState.SKIPPED_MSG)):
640 # It was marked as skipped before, but now we need to run it.
641 # Mark as untested.
642 t.update_state(skip=skip, status=TestState.UNTESTED, error_msg='')
643 else:
644 t.update_state(skip=skip)
645
Jon Salz0697cbf2012-07-04 15:14:04 +0800646 def show_next_active_test(self):
647 '''
648 Rotates to the next visible active test.
649 '''
650 self.reap_completed_tests()
651 active_tests = [
652 t for t in self.test_list.walk()
653 if t.is_leaf() and t.get_state().status == TestState.ACTIVE]
654 if not active_tests:
655 return
Jon Salz4f6c7172012-06-11 20:45:36 +0800656
Jon Salz0697cbf2012-07-04 15:14:04 +0800657 try:
658 next_test = active_tests[
659 (active_tests.index(self.visible_test) + 1) % len(active_tests)]
660 except ValueError: # visible_test not present in active_tests
661 next_test = active_tests[0]
Jon Salz4f6c7172012-06-11 20:45:36 +0800662
Jon Salz0697cbf2012-07-04 15:14:04 +0800663 self.set_visible_test(next_test)
Jon Salz4f6c7172012-06-11 20:45:36 +0800664
Jon Salz0697cbf2012-07-04 15:14:04 +0800665 def handle_event(self, event):
666 '''
667 Handles an event from the event server.
668 '''
669 handler = self.event_handlers.get(event.type)
670 if handler:
671 handler(event)
672 else:
673 # We don't register handlers for all event types - just ignore
674 # this event.
675 logging.debug('Unbound event type %s', event.type)
Jon Salz4f6c7172012-06-11 20:45:36 +0800676
Vic Yangaabf9fd2013-04-09 18:56:13 +0800677 def check_critical_factory_note(self):
678 '''
679 Returns True if the last factory note is critical.
680 '''
681 notes = self.state_instance.get_shared_data('factory_note', True)
682 return notes and notes[-1]['level'] == 'CRITICAL'
683
Jon Salz0697cbf2012-07-04 15:14:04 +0800684 def run_next_test(self):
685 '''
686 Runs the next eligible test (or tests) in self.tests_to_run.
687 '''
688 self.reap_completed_tests()
Vic Yangaabf9fd2013-04-09 18:56:13 +0800689 if self.tests_to_run and self.check_critical_factory_note():
690 self.tests_to_run.clear()
691 return
Jon Salz0697cbf2012-07-04 15:14:04 +0800692 while self.tests_to_run:
693 logging.debug('Tests to run: %s',
694 [x.path for x in self.tests_to_run])
Jon Salz94eb56f2012-06-12 18:01:12 +0800695
Jon Salz0697cbf2012-07-04 15:14:04 +0800696 test = self.tests_to_run[0]
Jon Salz94eb56f2012-06-12 18:01:12 +0800697
Jon Salz0697cbf2012-07-04 15:14:04 +0800698 if test in self.invocations:
699 logging.info('Next test %s is already running', test.path)
700 self.tests_to_run.popleft()
701 return
Jon Salz94eb56f2012-06-12 18:01:12 +0800702
Jon Salza1412922012-07-23 16:04:17 +0800703 for requirement in test.require_run:
704 for i in requirement.test.walk():
705 if i.get_state().status == TestState.ACTIVE:
Jon Salz304a75d2012-07-06 11:14:15 +0800706 logging.info('Waiting for active test %s to complete '
Jon Salza1412922012-07-23 16:04:17 +0800707 'before running %s', i.path, test.path)
Jon Salz304a75d2012-07-06 11:14:15 +0800708 return
709
Jon Salz0697cbf2012-07-04 15:14:04 +0800710 if self.invocations and not (test.backgroundable and all(
711 [x.backgroundable for x in self.invocations])):
712 logging.debug('Waiting for non-backgroundable tests to '
713 'complete before running %s', test.path)
714 return
Jon Salz94eb56f2012-06-12 18:01:12 +0800715
Jon Salz3e6f5202012-10-15 15:08:29 +0800716 if test.get_state().skip:
717 factory.console.info('Skipping test %s', test.path)
718 test.update_state(status=TestState.PASSED,
719 error_msg=TestState.SKIPPED_MSG)
720 self.tests_to_run.popleft()
721 continue
722
Jon Salz0697cbf2012-07-04 15:14:04 +0800723 self.tests_to_run.popleft()
Jon Salz94eb56f2012-06-12 18:01:12 +0800724
Jon Salz304a75d2012-07-06 11:14:15 +0800725 untested = set()
Jon Salza1412922012-07-23 16:04:17 +0800726 for requirement in test.require_run:
727 for i in requirement.test.walk():
728 if i == test:
Jon Salz304a75d2012-07-06 11:14:15 +0800729 # We've hit this test itself; stop checking
730 break
Jon Salza1412922012-07-23 16:04:17 +0800731 if ((i.get_state().status == TestState.UNTESTED) or
732 (requirement.passed and i.get_state().status !=
733 TestState.PASSED)):
Jon Salz304a75d2012-07-06 11:14:15 +0800734 # Found an untested test; move on to the next
735 # element in require_run.
Jon Salza1412922012-07-23 16:04:17 +0800736 untested.add(i)
Jon Salz304a75d2012-07-06 11:14:15 +0800737 break
738
739 if untested:
740 untested_paths = ', '.join(sorted([x.path for x in untested]))
741 if self.state_instance.get_shared_data('engineering_mode',
742 optional=True):
743 # In engineering mode, we'll let it go.
744 factory.console.warn('In engineering mode; running '
745 '%s even though required tests '
746 '[%s] have not completed',
747 test.path, untested_paths)
748 else:
749 # Not in engineering mode; mark it failed.
750 error_msg = ('Required tests [%s] have not been run yet'
751 % untested_paths)
752 factory.console.error('Not running %s: %s',
753 test.path, error_msg)
754 test.update_state(status=TestState.FAILED,
755 error_msg=error_msg)
756 continue
757
Jon Salz0697cbf2012-07-04 15:14:04 +0800758 if isinstance(test, factory.ShutdownStep):
759 if os.path.exists(NO_REBOOT_FILE):
760 test.update_state(
761 status=TestState.FAILED, increment_count=1,
762 error_msg=('Skipped shutdown since %s is present' %
Jon Salz304a75d2012-07-06 11:14:15 +0800763 NO_REBOOT_FILE))
Jon Salz0697cbf2012-07-04 15:14:04 +0800764 continue
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800765
Jon Salz0697cbf2012-07-04 15:14:04 +0800766 test.update_state(status=TestState.ACTIVE, increment_count=1,
767 error_msg='', shutdown_count=0)
768 if self._prompt_cancel_shutdown(test, 1):
769 self.event_log.Log('reboot_cancelled')
770 test.update_state(
771 status=TestState.FAILED, increment_count=1,
772 error_msg='Shutdown aborted by operator',
773 shutdown_count=0)
chungyiafe8f772012-08-15 19:36:29 +0800774 continue
Jon Salz2f757d42012-06-27 17:06:42 +0800775
Jon Salz0697cbf2012-07-04 15:14:04 +0800776 # Save pending test list in the state server
Jon Salzdbf398f2012-06-14 17:30:01 +0800777 self.state_instance.set_shared_data(
Jon Salz0697cbf2012-07-04 15:14:04 +0800778 'tests_after_shutdown',
779 [t.path for t in self.tests_to_run])
780 # Save shutdown time
781 self.state_instance.set_shared_data('shutdown_time',
782 time.time())
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800783
Jon Salz0697cbf2012-07-04 15:14:04 +0800784 with self.env.lock:
785 self.event_log.Log('shutdown', operation=test.operation)
786 shutdown_result = self.env.shutdown(test.operation)
787 if shutdown_result:
788 # That's all, folks!
789 self.run_queue.put(None)
790 return
791 else:
792 # Just pass (e.g., in the chroot).
793 test.update_state(status=TestState.PASSED)
794 self.state_instance.set_shared_data(
795 'tests_after_shutdown', None)
796 # Send event with no fields to indicate that there is no
797 # longer a pending shutdown.
798 self.event_client.post_event(Event(
799 Event.Type.PENDING_SHUTDOWN))
800 continue
Jon Salz258a40c2012-04-19 12:34:01 +0800801
Cheng-Yi Chiangce05c002013-04-04 02:13:17 +0800802 self._run_test(test, test.iterations, test.retries)
Jon Salz1acc8742012-07-17 17:45:55 +0800803
Cheng-Yi Chiangce05c002013-04-04 02:13:17 +0800804 def _run_test(self, test, iterations_left=None, retries_left=None):
Jon Salz1acc8742012-07-17 17:45:55 +0800805 invoc = TestInvocation(self, test, on_completion=self.run_next_test)
806 new_state = test.update_state(
807 status=TestState.ACTIVE, increment_count=1, error_msg='',
Jon Salzbd42ce12012-09-18 08:03:59 +0800808 invocation=invoc.uuid, iterations_left=iterations_left,
Cheng-Yi Chiangce05c002013-04-04 02:13:17 +0800809 retries_left=retries_left,
Jon Salzbd42ce12012-09-18 08:03:59 +0800810 visible=(self.visible_test == test))
Jon Salz1acc8742012-07-17 17:45:55 +0800811 invoc.count = new_state.count
812
813 self.invocations[test] = invoc
814 if self.visible_test is None and test.has_ui:
815 self.set_visible_test(test)
Vic Yang311ddb82012-09-26 12:08:28 +0800816 self.check_exclusive()
Jon Salz1acc8742012-07-17 17:45:55 +0800817 invoc.start()
Jon Salz5f2a0672012-05-22 17:14:06 +0800818
Vic Yang311ddb82012-09-26 12:08:28 +0800819 def check_exclusive(self):
820 current_exclusive_items = set([
821 item
822 for item in factory.FactoryTest.EXCLUSIVE_OPTIONS
823 if any([test.is_exclusive(item) for test in self.invocations])])
824
825 new_exclusive_items = current_exclusive_items - self.exclusive_items
826 if factory.FactoryTest.EXCLUSIVE_OPTIONS.NETWORKING in new_exclusive_items:
827 logging.info('Disabling network')
828 self.connection_manager.DisableNetworking()
829 if factory.FactoryTest.EXCLUSIVE_OPTIONS.CHARGER in new_exclusive_items:
830 logging.info('Stop controlling charger')
831
832 new_non_exclusive_items = self.exclusive_items - current_exclusive_items
833 if (factory.FactoryTest.EXCLUSIVE_OPTIONS.NETWORKING in
834 new_non_exclusive_items):
835 logging.info('Re-enabling network')
836 self.connection_manager.EnableNetworking()
837 if factory.FactoryTest.EXCLUSIVE_OPTIONS.CHARGER in new_non_exclusive_items:
838 logging.info('Start controlling charger')
839
840 # Only adjust charge state if not excluded
Cheng-Yi Chiangd8186952013-04-04 23:41:14 +0800841 if (factory.FactoryTest.EXCLUSIVE_OPTIONS.CHARGER not in
Vic Yange83d9a12013-04-19 20:00:20 +0800842 current_exclusive_items and not utils.in_chroot()):
Cheng-Yi Chiangd8186952013-04-04 23:41:14 +0800843 if self.charge_manager:
844 self.charge_manager.AdjustChargeState()
845 else:
846 try:
847 system.GetBoard().SetChargeState(Board.ChargeState.CHARGE)
848 except BoardException:
849 logging.exception('Unable to set charge state on this board')
Vic Yang311ddb82012-09-26 12:08:28 +0800850
851 self.exclusive_items = current_exclusive_items
Jon Salz5da61e62012-05-31 13:06:22 +0800852
cychiang21886742012-07-05 15:16:32 +0800853 def check_for_updates(self):
854 '''
855 Schedules an asynchronous check for updates if necessary.
856 '''
857 if not self.test_list.options.update_period_secs:
858 # Not enabled.
859 return
860
861 now = time.time()
862 if self.last_update_check and (
863 now - self.last_update_check <
864 self.test_list.options.update_period_secs):
865 # Not yet time for another check.
866 return
867
868 self.last_update_check = now
869
870 def handle_check_for_update(reached_shopfloor, md5sum, needs_update):
871 if reached_shopfloor:
872 new_update_md5sum = md5sum if needs_update else None
873 if system.SystemInfo.update_md5sum != new_update_md5sum:
874 logging.info('Received new update MD5SUM: %s', new_update_md5sum)
875 system.SystemInfo.update_md5sum = new_update_md5sum
876 self.run_queue.put(self.update_system_info)
877
878 updater.CheckForUpdateAsync(
879 handle_check_for_update,
880 self.test_list.options.shopfloor_timeout_secs)
881
Jon Salza6711d72012-07-18 14:33:03 +0800882 def cancel_pending_tests(self):
883 '''Cancels any tests in the run queue.'''
884 self.run_tests([])
885
Jon Salz0697cbf2012-07-04 15:14:04 +0800886 def run_tests(self, subtrees, untested_only=False):
887 '''
888 Runs tests under subtree.
Jon Salz258a40c2012-04-19 12:34:01 +0800889
Jon Salz0697cbf2012-07-04 15:14:04 +0800890 The tests are run in order unless one fails (then stops).
891 Backgroundable tests are run simultaneously; when a foreground test is
892 encountered, we wait for all active tests to finish before continuing.
Jon Salzb1b39092012-05-03 02:05:09 +0800893
Jon Salz0697cbf2012-07-04 15:14:04 +0800894 @param subtrees: Node or nodes containing tests to run (may either be
895 a single test or a list). Duplicates will be ignored.
896 '''
897 if type(subtrees) != list:
898 subtrees = [subtrees]
Jon Salz258a40c2012-04-19 12:34:01 +0800899
Jon Salz0697cbf2012-07-04 15:14:04 +0800900 # Nodes we've seen so far, to avoid duplicates.
901 seen = set()
Jon Salz94eb56f2012-06-12 18:01:12 +0800902
Jon Salz0697cbf2012-07-04 15:14:04 +0800903 self.tests_to_run = deque()
904 for subtree in subtrees:
905 for test in subtree.walk():
906 if test in seen:
907 continue
908 seen.add(test)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800909
Jon Salz0697cbf2012-07-04 15:14:04 +0800910 if not test.is_leaf():
911 continue
912 if (untested_only and
913 test.get_state().status != TestState.UNTESTED):
914 continue
915 self.tests_to_run.append(test)
916 self.run_next_test()
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800917
Jon Salz0697cbf2012-07-04 15:14:04 +0800918 def reap_completed_tests(self):
919 '''
920 Removes completed tests from the set of active tests.
921
922 Also updates the visible test if it was reaped.
923 '''
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +0800924 test_completed = False
Jon Salz0697cbf2012-07-04 15:14:04 +0800925 for t, v in dict(self.invocations).iteritems():
926 if v.is_completed():
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +0800927 test_completed = True
Jon Salz1acc8742012-07-17 17:45:55 +0800928 new_state = t.update_state(**v.update_state_on_completion)
Jon Salz0697cbf2012-07-04 15:14:04 +0800929 del self.invocations[t]
930
Chun-Ta Lin54e17e42012-09-06 22:05:13 +0800931 # Stop on failure if flag is true.
932 if (self.test_list.options.stop_on_failure and
933 new_state.status == TestState.FAILED):
934 # Clean all the tests to cause goofy to stop.
935 self.tests_to_run = []
936 factory.console.info("Stop on failure triggered. Empty the queue.")
937
Jon Salz1acc8742012-07-17 17:45:55 +0800938 if new_state.iterations_left and new_state.status == TestState.PASSED:
939 # Play it again, Sam!
940 self._run_test(t)
Cheng-Yi Chiangce05c002013-04-04 02:13:17 +0800941 # new_state.retries_left is obtained after update.
942 # For retries_left == 0, test can still be run for the last time.
943 elif (new_state.retries_left >= 0 and
944 new_state.status == TestState.FAILED):
945 # Still have to retry, Sam!
946 self._run_test(t)
Jon Salz1acc8742012-07-17 17:45:55 +0800947
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +0800948 if test_completed:
Vic Yangf01c59f2013-04-19 17:37:56 +0800949 self.log_watcher.KickWatchThread()
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +0800950
Jon Salz0697cbf2012-07-04 15:14:04 +0800951 if (self.visible_test is None or
Jon Salz85a39882012-07-05 16:45:04 +0800952 self.visible_test not in self.invocations):
Jon Salz0697cbf2012-07-04 15:14:04 +0800953 self.set_visible_test(None)
954 # Make the first running test, if any, the visible test
955 for t in self.test_list.walk():
956 if t in self.invocations:
957 self.set_visible_test(t)
958 break
959
Jon Salz85a39882012-07-05 16:45:04 +0800960 def kill_active_tests(self, abort, root=None):
Jon Salz0697cbf2012-07-04 15:14:04 +0800961 '''
962 Kills and waits for all active tests.
963
Jon Salz85a39882012-07-05 16:45:04 +0800964 Args:
965 abort: True to change state of killed tests to FAILED, False for
Jon Salz0697cbf2012-07-04 15:14:04 +0800966 UNTESTED.
Jon Salz85a39882012-07-05 16:45:04 +0800967 root: If set, only kills tests with root as an ancestor.
Jon Salz0697cbf2012-07-04 15:14:04 +0800968 '''
969 self.reap_completed_tests()
970 for test, invoc in self.invocations.items():
Jon Salz85a39882012-07-05 16:45:04 +0800971 if root and not test.has_ancestor(root):
972 continue
973
Jon Salz0697cbf2012-07-04 15:14:04 +0800974 factory.console.info('Killing active test %s...' % test.path)
975 invoc.abort_and_join()
976 factory.console.info('Killed %s' % test.path)
Jon Salz1acc8742012-07-17 17:45:55 +0800977 test.update_state(**invoc.update_state_on_completion)
Jon Salz0697cbf2012-07-04 15:14:04 +0800978 del self.invocations[test]
Jon Salz1acc8742012-07-17 17:45:55 +0800979
Jon Salz0697cbf2012-07-04 15:14:04 +0800980 if not abort:
981 test.update_state(status=TestState.UNTESTED)
982 self.reap_completed_tests()
983
Jon Salz85a39882012-07-05 16:45:04 +0800984 def stop(self, root=None, fail=False):
985 self.kill_active_tests(fail, root)
986 # Remove any tests in the run queue under the root.
987 self.tests_to_run = deque([x for x in self.tests_to_run
988 if root and not x.has_ancestor(root)])
989 self.run_next_test()
Jon Salz0697cbf2012-07-04 15:14:04 +0800990
Jon Salz4712ac72013-02-07 17:12:05 +0800991 def clear_state(self, root=None):
992 self.stop(root)
993 for f in root.walk():
994 if f.is_leaf():
995 f.update_state(status=TestState.UNTESTED)
996
Jon Salz0697cbf2012-07-04 15:14:04 +0800997 def abort_active_tests(self):
998 self.kill_active_tests(True)
999
1000 def main(self):
1001 try:
1002 self.init()
1003 self.event_log.Log('goofy_init',
1004 success=True)
1005 except:
1006 if self.event_log:
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001007 try:
Jon Salz0697cbf2012-07-04 15:14:04 +08001008 self.event_log.Log('goofy_init',
1009 success=False,
1010 trace=traceback.format_exc())
1011 except: # pylint: disable=W0702
1012 pass
1013 raise
1014
1015 self.run()
1016
1017 def update_system_info(self):
1018 '''Updates system info.'''
1019 system_info = system.SystemInfo()
1020 self.state_instance.set_shared_data('system_info', system_info.__dict__)
1021 self.event_client.post_event(Event(Event.Type.SYSTEM_INFO,
1022 system_info=system_info.__dict__))
1023 logging.info('System info: %r', system_info.__dict__)
1024
Jon Salzeb42f0d2012-07-27 19:14:04 +08001025 def update_factory(self, auto_run_on_restart=False, post_update_hook=None):
1026 '''Commences updating factory software.
1027
1028 Args:
1029 auto_run_on_restart: Auto-run when the machine comes back up.
1030 post_update_hook: Code to call after update but immediately before
1031 restart.
1032
1033 Returns:
1034 Never if the update was successful (we just reboot).
1035 False if the update was unnecessary (no update available).
1036 '''
Jon Salz0697cbf2012-07-04 15:14:04 +08001037 self.kill_active_tests(False)
Jon Salza6711d72012-07-18 14:33:03 +08001038 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +08001039
Jon Salz5c344f62012-07-13 14:31:16 +08001040 def pre_update_hook():
1041 if auto_run_on_restart:
1042 self.state_instance.set_shared_data('tests_after_shutdown',
1043 FORCE_AUTO_RUN)
1044 self.state_instance.close()
1045
Jon Salzeb42f0d2012-07-27 19:14:04 +08001046 if updater.TryUpdate(pre_update_hook=pre_update_hook):
1047 if post_update_hook:
1048 post_update_hook()
1049 self.env.shutdown('reboot')
Jon Salz0697cbf2012-07-04 15:14:04 +08001050
Jon Salzcef132a2012-08-30 04:58:08 +08001051 def handle_sigint(self, dummy_signum, dummy_frame):
Jon Salz77c151e2012-08-28 07:20:37 +08001052 logging.error('Received SIGINT')
1053 self.run_queue.put(None)
1054 raise KeyboardInterrupt()
1055
Jon Salz0697cbf2012-07-04 15:14:04 +08001056 def init(self, args=None, env=None):
1057 '''Initializes Goofy.
1058
1059 Args:
1060 args: A list of command-line arguments. Uses sys.argv if
1061 args is None.
1062 env: An Environment instance to use (or None to choose
1063 FakeChrootEnvironment or DUTEnvironment as appropriate).
1064 '''
Jon Salz77c151e2012-08-28 07:20:37 +08001065 signal.signal(signal.SIGINT, self.handle_sigint)
1066
Jon Salz0697cbf2012-07-04 15:14:04 +08001067 parser = OptionParser()
1068 parser.add_option('-v', '--verbose', dest='verbose',
Jon Salz8fa8e832012-07-13 19:04:09 +08001069 action='store_true',
1070 help='Enable debug logging')
Jon Salz0697cbf2012-07-04 15:14:04 +08001071 parser.add_option('--print_test_list', dest='print_test_list',
Jon Salz8fa8e832012-07-13 19:04:09 +08001072 metavar='FILE',
1073 help='Read and print test list FILE, and exit')
Jon Salz0697cbf2012-07-04 15:14:04 +08001074 parser.add_option('--restart', dest='restart',
Jon Salz8fa8e832012-07-13 19:04:09 +08001075 action='store_true',
1076 help='Clear all test state')
Jon Salz0697cbf2012-07-04 15:14:04 +08001077 parser.add_option('--ui', dest='ui', type='choice',
Jon Salz8fa8e832012-07-13 19:04:09 +08001078 choices=['none', 'gtk', 'chrome'],
Jon Salz2f881df2013-02-01 17:00:35 +08001079 default='chrome',
Jon Salz8fa8e832012-07-13 19:04:09 +08001080 help='UI to use')
Jon Salz0697cbf2012-07-04 15:14:04 +08001081 parser.add_option('--ui_scale_factor', dest='ui_scale_factor',
Jon Salz8fa8e832012-07-13 19:04:09 +08001082 type='int', default=1,
1083 help=('Factor by which to scale UI '
1084 '(Chrome UI only)'))
Jon Salz0697cbf2012-07-04 15:14:04 +08001085 parser.add_option('--test_list', dest='test_list',
Jon Salz8fa8e832012-07-13 19:04:09 +08001086 metavar='FILE',
1087 help='Use FILE as test list')
Jon Salzc79a9982012-08-30 04:42:01 +08001088 parser.add_option('--dummy_shopfloor', action='store_true',
1089 help='Use a dummy shopfloor server')
chungyiafe8f772012-08-15 19:36:29 +08001090 parser.add_option('--automation', dest='automation',
1091 action='store_true',
1092 help='Enable automation on running factory test')
Ricky Liang09216dc2013-02-22 17:26:45 +08001093 parser.add_option('--one_pixel_less', dest='one_pixel_less',
1094 action='store_true',
1095 help=('Start Chrome one pixel less than the full screen.'
1096 'Needed by Exynos platform to run GTK.'))
Jon Salz0697cbf2012-07-04 15:14:04 +08001097 (self.options, self.args) = parser.parse_args(args)
1098
Jon Salz46b89562012-07-05 11:49:22 +08001099 # Make sure factory directories exist.
1100 factory.get_log_root()
1101 factory.get_state_root()
1102 factory.get_test_data_root()
1103
Jon Salz0697cbf2012-07-04 15:14:04 +08001104 global _inited_logging # pylint: disable=W0603
1105 if not _inited_logging:
1106 factory.init_logging('goofy', verbose=self.options.verbose)
1107 _inited_logging = True
Jon Salz8fa8e832012-07-13 19:04:09 +08001108
Jon Salz0f996602012-10-03 15:26:48 +08001109 if self.options.print_test_list:
1110 print factory.read_test_list(
1111 self.options.print_test_list).__repr__(recursive=True)
1112 sys.exit(0)
1113
Jon Salzee85d522012-07-17 14:34:46 +08001114 event_log.IncrementBootSequence()
Jon Salzd15bbcf2013-05-21 17:33:57 +08001115 # Don't defer logging the initial event, so we can make sure
1116 # that device_id, reimage_id, etc. are all set up.
1117 self.event_log = EventLog('goofy', defer=False)
Jon Salz0697cbf2012-07-04 15:14:04 +08001118
1119 if (not suppress_chroot_warning and
1120 factory.in_chroot() and
1121 self.options.ui == 'gtk' and
1122 os.environ.get('DISPLAY') in [None, '', ':0', ':0.0']):
1123 # That's not going to work! Tell the user how to run
1124 # this way.
1125 logging.warn(GOOFY_IN_CHROOT_WARNING)
1126 time.sleep(1)
1127
1128 if env:
1129 self.env = env
1130 elif factory.in_chroot():
1131 self.env = test_environment.FakeChrootEnvironment()
1132 logging.warn(
1133 'Using chroot environment: will not actually run autotests')
1134 else:
1135 self.env = test_environment.DUTEnvironment()
1136 self.env.goofy = self
1137
1138 if self.options.restart:
1139 state.clear_state()
1140
Jon Salz0697cbf2012-07-04 15:14:04 +08001141 if self.options.ui_scale_factor != 1 and utils.in_qemu():
1142 logging.warn(
1143 'In QEMU; ignoring ui_scale_factor argument')
1144 self.options.ui_scale_factor = 1
1145
1146 logging.info('Started')
1147
1148 self.start_state_server()
1149 self.state_instance.set_shared_data('hwid_cfg', get_hwid_cfg())
1150 self.state_instance.set_shared_data('ui_scale_factor',
Ricky Liang09216dc2013-02-22 17:26:45 +08001151 self.options.ui_scale_factor)
1152 self.state_instance.set_shared_data('one_pixel_less',
1153 self.options.one_pixel_less)
Jon Salz0697cbf2012-07-04 15:14:04 +08001154 self.last_shutdown_time = (
1155 self.state_instance.get_shared_data('shutdown_time', optional=True))
1156 self.state_instance.del_shared_data('shutdown_time', optional=True)
1157
Jon Salzb19ea072013-02-07 16:35:00 +08001158 self.state_instance.del_shared_data('startup_error', optional=True)
Jon Salz0697cbf2012-07-04 15:14:04 +08001159 if not self.options.test_list:
1160 self.options.test_list = find_test_list()
Jon Salzb19ea072013-02-07 16:35:00 +08001161 if self.options.test_list:
Jon Salz0697cbf2012-07-04 15:14:04 +08001162 logging.info('Using test list %s', self.options.test_list)
Jon Salzb19ea072013-02-07 16:35:00 +08001163 try:
1164 self.test_list = factory.read_test_list(
1165 self.options.test_list,
1166 self.state_instance)
1167 except: # pylint: disable=W0702
1168 logging.exception('Unable to read test list %r', self.options.test_list)
1169 self.state_instance.set_shared_data('startup_error',
1170 'Unable to read test list %s\n%s' % (
1171 self.options.test_list,
1172 traceback.format_exc()))
1173 else:
1174 logging.error('No test list found.')
1175 self.state_instance.set_shared_data('startup_error',
1176 'No test list found.')
Jon Salz0697cbf2012-07-04 15:14:04 +08001177
Jon Salzb19ea072013-02-07 16:35:00 +08001178 if not self.test_list:
1179 if self.options.ui == 'chrome':
1180 # Create an empty test list with default options so that the rest of
1181 # startup can proceed.
1182 self.test_list = factory.FactoryTestList(
1183 [], self.state_instance, factory.Options())
1184 else:
1185 # Bail with an error; no point in starting up.
1186 sys.exit('No valid test list; exiting.')
1187
Jon Salz822838b2013-03-25 17:32:33 +08001188 if self.test_list.options.clear_state_on_start:
1189 self.state_instance.clear_test_state()
1190
Jon Salz0697cbf2012-07-04 15:14:04 +08001191 if not self.state_instance.has_shared_data('ui_lang'):
1192 self.state_instance.set_shared_data('ui_lang',
1193 self.test_list.options.ui_lang)
1194 self.state_instance.set_shared_data(
1195 'test_list_options',
1196 self.test_list.options.__dict__)
1197 self.state_instance.test_list = self.test_list
1198
Jon Salz83ef34b2012-11-01 19:46:35 +08001199 if not utils.in_chroot() and self.test_list.options.disable_log_rotation:
1200 open('/var/lib/cleanup_logs_paused', 'w').close()
1201
Jon Salz23926422012-09-01 03:38:13 +08001202 if self.options.dummy_shopfloor:
1203 os.environ[shopfloor.SHOPFLOOR_SERVER_ENV_VAR_NAME] = (
1204 'http://localhost:%d/' % shopfloor.DEFAULT_SERVER_PORT)
1205 self.dummy_shopfloor = Spawn(
1206 [os.path.join(factory.FACTORY_PATH, 'bin', 'shopfloor_server'),
1207 '--dummy'])
1208 elif self.test_list.options.shopfloor_server_url:
1209 shopfloor.set_server_url(self.test_list.options.shopfloor_server_url)
Jon Salz2bf2f6b2013-03-28 18:49:26 +08001210 shopfloor.set_enabled(True)
Jon Salz23926422012-09-01 03:38:13 +08001211
Jon Salz0f996602012-10-03 15:26:48 +08001212 if self.test_list.options.time_sanitizer and not utils.in_chroot():
Jon Salz8fa8e832012-07-13 19:04:09 +08001213 self.time_sanitizer = time_sanitizer.TimeSanitizer(
1214 base_time=time_sanitizer.GetBaseTimeFromFile(
1215 # lsb-factory is written by the factory install shim during
1216 # installation, so it should have a good time obtained from
Jon Salz54882d02012-08-31 01:57:54 +08001217 # the mini-Omaha server. If it's not available, we'll use
1218 # /etc/lsb-factory (which will be much older, but reasonably
1219 # sane) and rely on a shopfloor sync to set a more accurate
1220 # time.
1221 '/usr/local/etc/lsb-factory',
1222 '/etc/lsb-release'))
Jon Salz8fa8e832012-07-13 19:04:09 +08001223 self.time_sanitizer.RunOnce()
1224
Jon Salz0697cbf2012-07-04 15:14:04 +08001225 self.init_states()
1226 self.start_event_server()
1227 self.connection_manager = self.env.create_connection_manager(
Tai-Hsu Lin371351a2012-08-27 14:17:14 +08001228 self.test_list.options.wlans,
1229 self.test_list.options.scan_wifi_period_secs)
Jon Salz0697cbf2012-07-04 15:14:04 +08001230 # Note that we create a log watcher even if
1231 # sync_event_log_period_secs isn't set (no background
1232 # syncing), since we may use it to flush event logs as well.
1233 self.log_watcher = EventLogWatcher(
1234 self.test_list.options.sync_event_log_period_secs,
Jon Salzd15bbcf2013-05-21 17:33:57 +08001235 event_log_db_file=None,
Jon Salz16d10542012-07-23 12:18:45 +08001236 handle_event_logs_callback=self.handle_event_logs)
Jon Salz0697cbf2012-07-04 15:14:04 +08001237 if self.test_list.options.sync_event_log_period_secs:
1238 self.log_watcher.StartWatchThread()
1239
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +08001240 # Note that we create a system log manager even if
1241 # sync_log_period_secs isn't set (no background
1242 # syncing), since we may kick it to sync logs in its
1243 # thread.
1244 self.system_log_manager = SystemLogManager(
Cheng-Yi Chiang835f2682013-05-06 22:15:48 +08001245 sync_log_paths=self.test_list.options.sync_log_paths,
1246 sync_period_sec=self.test_list.options.sync_log_period_secs,
1247 clear_log_paths=self.test_list.options.clear_log_paths)
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +08001248 self.system_log_manager.StartSyncThread()
1249
Jon Salz0697cbf2012-07-04 15:14:04 +08001250 self.update_system_info()
1251
Vic Yang4953fc12012-07-26 16:19:53 +08001252 assert ((self.test_list.options.min_charge_pct is None) ==
1253 (self.test_list.options.max_charge_pct is None))
Vic Yange83d9a12013-04-19 20:00:20 +08001254 if utils.in_chroot():
1255 logging.info('In chroot, ignoring charge manager and charge state')
1256 elif self.test_list.options.min_charge_pct is not None:
Vic Yang4953fc12012-07-26 16:19:53 +08001257 self.charge_manager = ChargeManager(self.test_list.options.min_charge_pct,
1258 self.test_list.options.max_charge_pct)
Jon Salzad7353b2012-10-15 16:22:46 +08001259 system.SystemStatus.charge_manager = self.charge_manager
Cheng-Yi Chiangd8186952013-04-04 23:41:14 +08001260 else:
1261 # Goofy should set charger state to charge if charge_manager is disabled.
1262 try:
1263 system.GetBoard().SetChargeState(Board.ChargeState.CHARGE)
1264 except BoardException:
1265 logging.exception('Unable to set charge state on this board')
Vic Yang4953fc12012-07-26 16:19:53 +08001266
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001267 self.core_dump_manager = CoreDumpManager(
1268 self.test_list.options.core_dump_watchlist)
1269
Jon Salz0697cbf2012-07-04 15:14:04 +08001270 os.environ['CROS_FACTORY'] = '1'
1271 os.environ['CROS_DISABLE_SITE_SYSINFO'] = '1'
1272
1273 # Set CROS_UI since some behaviors in ui.py depend on the
1274 # particular UI in use. TODO(jsalz): Remove this (and all
1275 # places it is used) when the GTK UI is removed.
1276 os.environ['CROS_UI'] = self.options.ui
1277
Jon Salz416f9cc2013-05-10 18:32:50 +08001278 # Initialize hooks.
1279 module, cls = self.test_list.options.hooks_class.rsplit('.', 1)
1280 self.hooks = getattr(__import__(module, fromlist=[cls]), cls)()
1281 assert isinstance(self.hooks, factory.Hooks), (
1282 "hooks should be of type Hooks but is %r" % type(self.hooks))
1283 self.hooks.test_list = self.test_list
1284
1285 # Call startup hook.
1286 self.hooks.OnStartup()
1287
Jon Salz0697cbf2012-07-04 15:14:04 +08001288 if self.options.ui == 'chrome':
1289 self.env.launch_chrome()
1290 logging.info('Waiting for a web socket connection')
Cheng-Yi Chiangfd8ed392013-03-08 21:37:31 +08001291 self.web_socket_manager.wait()
Jon Salz0697cbf2012-07-04 15:14:04 +08001292
1293 # Wait for the test widget size to be set; this is done in
1294 # an asynchronous RPC so there is a small chance that the
1295 # web socket might be opened first.
1296 for _ in range(100): # 10 s
1297 try:
1298 if self.state_instance.get_shared_data('test_widget_size'):
1299 break
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001300 except KeyError:
Jon Salz0697cbf2012-07-04 15:14:04 +08001301 pass # Retry
1302 time.sleep(0.1) # 100 ms
1303 else:
1304 logging.warn('Never received test_widget_size from UI')
Jon Salz45297282013-05-18 14:31:47 +08001305
1306 # Send Chrome a Tab to get focus to the factory UI
1307 # (http://crosbug.com/p/19444). TODO(jsalz): remove this hack
1308 # and figure out the right way to get the focus to Chrome.
1309 if not utils.in_chroot():
1310 Spawn(
1311 [os.path.join(factory.FACTORY_PATH, 'bin', 'send_key'), 'Tab'],
1312 check_call=True, log=True)
Jon Salz0697cbf2012-07-04 15:14:04 +08001313 elif self.options.ui == 'gtk':
1314 self.start_ui()
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001315
Ricky Liang650f6bf2012-09-28 13:22:54 +08001316 # Create download path for autotest beforehand or autotests run at
1317 # the same time might fail due to race condition.
1318 if not factory.in_chroot():
1319 utils.TryMakeDirs(os.path.join('/usr/local/autotest', 'tests',
1320 'download'))
1321
Jon Salz0697cbf2012-07-04 15:14:04 +08001322 def state_change_callback(test, test_state):
1323 self.event_client.post_event(
1324 Event(Event.Type.STATE_CHANGE,
1325 path=test.path, state=test_state))
1326 self.test_list.state_change_callback = state_change_callback
Jon Salz73e0fd02012-04-04 11:46:38 +08001327
Jon Salza6711d72012-07-18 14:33:03 +08001328 for handler in self.on_ui_startup:
1329 handler()
1330
1331 self.prespawner = Prespawner()
1332 self.prespawner.start()
1333
Jon Salz0697cbf2012-07-04 15:14:04 +08001334 try:
1335 tests_after_shutdown = self.state_instance.get_shared_data(
1336 'tests_after_shutdown')
1337 except KeyError:
1338 tests_after_shutdown = None
Jon Salz57717ca2012-04-04 16:47:25 +08001339
Jon Salz5c344f62012-07-13 14:31:16 +08001340 force_auto_run = (tests_after_shutdown == FORCE_AUTO_RUN)
1341 if not force_auto_run and tests_after_shutdown is not None:
Jon Salz0697cbf2012-07-04 15:14:04 +08001342 logging.info('Resuming tests after shutdown: %s',
1343 tests_after_shutdown)
Jon Salz0697cbf2012-07-04 15:14:04 +08001344 self.tests_to_run.extend(
1345 self.test_list.lookup_path(t) for t in tests_after_shutdown)
1346 self.run_queue.put(self.run_next_test)
1347 else:
Jon Salz5c344f62012-07-13 14:31:16 +08001348 if force_auto_run or self.test_list.options.auto_run_on_start:
Jon Salz0697cbf2012-07-04 15:14:04 +08001349 self.run_queue.put(
1350 lambda: self.run_tests(self.test_list, untested_only=True))
Jon Salz5c344f62012-07-13 14:31:16 +08001351 self.state_instance.set_shared_data('tests_after_shutdown', None)
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001352
Dean Liao592e4d52013-01-10 20:06:39 +08001353 self.may_disable_cros_shortcut_keys()
1354
1355 def may_disable_cros_shortcut_keys(self):
1356 test_options = self.test_list.options
1357 if test_options.disable_cros_shortcut_keys:
1358 logging.info('Filter ChromeOS shortcut keys.')
1359 self.key_filter = KeyFilter(
1360 unmap_caps_lock=test_options.disable_caps_lock,
1361 caps_lock_keycode=test_options.caps_lock_keycode)
1362 self.key_filter.Start()
1363
Jon Salz0697cbf2012-07-04 15:14:04 +08001364 def run(self):
1365 '''Runs Goofy.'''
1366 # Process events forever.
1367 while self.run_once(True):
1368 pass
Jon Salz73e0fd02012-04-04 11:46:38 +08001369
Jon Salz0697cbf2012-07-04 15:14:04 +08001370 def run_once(self, block=False):
1371 '''Runs all items pending in the event loop.
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001372
Jon Salz0697cbf2012-07-04 15:14:04 +08001373 Args:
1374 block: If true, block until at least one event is processed.
Jon Salz7c15e8b2012-06-19 17:10:37 +08001375
Jon Salz0697cbf2012-07-04 15:14:04 +08001376 Returns:
1377 True to keep going or False to shut down.
1378 '''
1379 events = utils.DrainQueue(self.run_queue)
cychiang21886742012-07-05 15:16:32 +08001380 while not events:
Jon Salz0697cbf2012-07-04 15:14:04 +08001381 # Nothing on the run queue.
1382 self._run_queue_idle()
1383 if block:
1384 # Block for at least one event...
cychiang21886742012-07-05 15:16:32 +08001385 try:
1386 events.append(self.run_queue.get(timeout=RUN_QUEUE_TIMEOUT_SECS))
1387 except Queue.Empty:
1388 # Keep going (calling _run_queue_idle() again at the top of
1389 # the loop)
1390 continue
Jon Salz0697cbf2012-07-04 15:14:04 +08001391 # ...and grab anything else that showed up at the same
1392 # time.
1393 events.extend(utils.DrainQueue(self.run_queue))
cychiang21886742012-07-05 15:16:32 +08001394 else:
1395 break
Jon Salz51528e12012-07-02 18:54:45 +08001396
Jon Salz0697cbf2012-07-04 15:14:04 +08001397 for event in events:
1398 if not event:
1399 # Shutdown request.
1400 self.run_queue.task_done()
1401 return False
Jon Salz51528e12012-07-02 18:54:45 +08001402
Jon Salz0697cbf2012-07-04 15:14:04 +08001403 try:
1404 event()
Jon Salz85a39882012-07-05 16:45:04 +08001405 except: # pylint: disable=W0702
1406 logging.exception('Error in event loop')
Jon Salz0697cbf2012-07-04 15:14:04 +08001407 self.record_exception(traceback.format_exception_only(
1408 *sys.exc_info()[:2]))
1409 # But keep going
1410 finally:
1411 self.run_queue.task_done()
1412 return True
Jon Salz0405ab52012-03-16 15:26:52 +08001413
Jon Salz0e6532d2012-10-25 16:30:11 +08001414 def _should_sync_time(self, foreground=False):
1415 '''Returns True if we should attempt syncing time with shopfloor.
1416
1417 Args:
1418 foreground: If True, synchronizes even if background syncing
1419 is disabled (e.g., in explicit sync requests from the
1420 SyncShopfloor test).
1421 '''
1422 return ((foreground or
1423 self.test_list.options.sync_time_period_secs) and
Jon Salz54882d02012-08-31 01:57:54 +08001424 self.time_sanitizer and
1425 (not self.time_synced) and
1426 (not factory.in_chroot()))
1427
Jon Salz0e6532d2012-10-25 16:30:11 +08001428 def sync_time_with_shopfloor_server(self, foreground=False):
Jon Salz54882d02012-08-31 01:57:54 +08001429 '''Syncs time with shopfloor server, if not yet synced.
1430
Jon Salz0e6532d2012-10-25 16:30:11 +08001431 Args:
1432 foreground: If True, synchronizes even if background syncing
1433 is disabled (e.g., in explicit sync requests from the
1434 SyncShopfloor test).
1435
Jon Salz54882d02012-08-31 01:57:54 +08001436 Returns:
1437 False if no time sanitizer is available, or True if this sync (or a
1438 previous sync) succeeded.
1439
1440 Raises:
1441 Exception if unable to contact the shopfloor server.
1442 '''
Jon Salz0e6532d2012-10-25 16:30:11 +08001443 if self._should_sync_time(foreground):
Jon Salz54882d02012-08-31 01:57:54 +08001444 self.time_sanitizer.SyncWithShopfloor()
1445 self.time_synced = True
1446 return self.time_synced
1447
Jon Salzb92c5112012-09-21 15:40:11 +08001448 def log_disk_space_stats(self):
1449 if not self.test_list.options.log_disk_space_period_secs:
1450 return
1451
1452 now = time.time()
1453 if (self.last_log_disk_space_time and
1454 now - self.last_log_disk_space_time <
1455 self.test_list.options.log_disk_space_period_secs):
1456 return
1457 self.last_log_disk_space_time = now
1458
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001459 # Upload event if stateful partition usage is above threshold.
1460 # Stateful partition is mounted on /usr/local, while
1461 # encrypted stateful partition is mounted on /var.
1462 # If there are too much logs in the factory process,
1463 # these two partitions might get full.
Jon Salzb92c5112012-09-21 15:40:11 +08001464 try:
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001465 vfs_infos = disk_space.GetAllVFSInfo()
1466 stateful_info, encrypted_info = None, None
1467 for vfs_info in vfs_infos.values():
1468 if '/usr/local' in vfs_info.mount_points:
1469 stateful_info = vfs_info
1470 if '/var' in vfs_info.mount_points:
1471 encrypted_info = vfs_info
1472
1473 stateful = disk_space.GetPartitionUsage(stateful_info)
1474 encrypted = disk_space.GetPartitionUsage(encrypted_info)
1475
1476 above_threshold = (
1477 self.test_list.options.stateful_usage_threshold and
1478 max(stateful.bytes_used_pct,
1479 stateful.inodes_used_pct,
1480 encrypted.bytes_used_pct,
1481 encrypted.inodes_used_pct) >
1482 self.test_list.options.stateful_usage_threshold)
1483
1484 if above_threshold:
1485 self.event_log.Log('stateful_partition_usage',
1486 partitions={
1487 'stateful': {
1488 'bytes_used_pct': FloatDigit(stateful.bytes_used_pct, 2),
1489 'inodes_used_pct': FloatDigit(stateful.inodes_used_pct, 2)},
1490 'encrypted_stateful': {
1491 'bytes_used_pct': FloatDigit(encrypted.bytes_used_pct, 2),
1492 'inodes_used_pct': FloatDigit(encrypted.inodes_used_pct, 2)}
1493 })
1494 self.log_watcher.ScanEventLogs()
1495
1496 message = disk_space.FormatSpaceUsedAll(vfs_infos)
Jon Salz3c493bb2013-02-07 17:24:58 +08001497 if message != self.last_log_disk_space_message:
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001498 if above_threshold:
1499 logging.warning(message)
1500 else:
1501 logging.info(message)
Jon Salz3c493bb2013-02-07 17:24:58 +08001502 self.last_log_disk_space_message = message
Jon Salzb92c5112012-09-21 15:40:11 +08001503 except: # pylint: disable=W0702
1504 logging.exception('Unable to get disk space used')
1505
Justin Chuang83813982013-05-13 01:26:32 +08001506 def check_battery(self):
1507 '''Checks the current battery status.
1508
1509 Logs current battery charging level and status to log. If the battery level
1510 is lower below warning_low_battery_pct, send warning event to shopfloor.
1511 If the battery level is lower below critical_low_battery_pct, flush disks.
1512 '''
1513 if not self.test_list.options.check_battery_period_secs:
1514 return
1515
1516 now = time.time()
1517 if (self.last_check_battery_time and
1518 now - self.last_check_battery_time <
1519 self.test_list.options.check_battery_period_secs):
1520 return
1521 self.last_check_battery_time = now
1522
1523 message = ''
1524 log_level = logging.INFO
1525 try:
1526 power = system.GetBoard().power
1527 if not power.CheckBatteryPresent():
1528 message = 'Battery is not present'
1529 else:
1530 ac_present = power.CheckACPresent()
1531 charge_pct = power.GetChargePct(get_float=True)
1532 message = ('Current battery level %.1f%%, AC charger is %s' %
1533 (charge_pct, 'connected' if ac_present else 'disconnected'))
1534
1535 if charge_pct > self.test_list.options.critical_low_battery_pct:
1536 critical_low_battery = False
1537 else:
1538 critical_low_battery = True
1539 # Only sync disks when battery level is still above minimum
1540 # value. This can be used for offline analysis when shopfloor cannot
1541 # be connected.
1542 if charge_pct > MIN_BATTERY_LEVEL_FOR_DISK_SYNC:
1543 logging.warning('disk syncing for critical low battery situation')
1544 os.system('sync; sync; sync')
1545 else:
1546 logging.warning('disk syncing is cancelled '
1547 'because battery level is lower than %.1f',
1548 MIN_BATTERY_LEVEL_FOR_DISK_SYNC)
1549
1550 # Notify shopfloor server
1551 if (critical_low_battery or
1552 (not ac_present and
1553 charge_pct <= self.test_list.options.warning_low_battery_pct)):
1554 log_level = logging.WARNING
1555
1556 self.event_log.Log('low_battery',
1557 battery_level=charge_pct,
1558 charger_connected=ac_present,
1559 critical=critical_low_battery)
1560 self.log_watcher.KickWatchThread()
1561 self.system_log_manager.KickSyncThread()
1562 except: # pylint: disable=W0702
1563 logging.exception('Unable to check battery or notify shopfloor')
1564 finally:
1565 if message != self.last_check_battery_message:
1566 logging.log(log_level, message)
1567 self.last_check_battery_message = message
1568
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001569 def check_core_dump(self):
1570 '''Checks if there is any core dumped file.
1571
1572 Removes unwanted core dump files immediately.
1573 Syncs those files matching watch list to server with a delay between
1574 each sync. After the files have been synced to server, deletes the files.
1575 '''
1576 core_dump_files = self.core_dump_manager.ScanFiles()
1577 if core_dump_files:
1578 now = time.time()
1579 if (self.last_kick_sync_time and now - self.last_kick_sync_time <
1580 self.test_list.options.kick_sync_min_interval_secs):
1581 return
1582 self.last_kick_sync_time = now
1583
1584 # Sends event to server
1585 self.event_log.Log('core_dumped', files=core_dump_files)
1586 self.log_watcher.KickWatchThread()
1587
1588 # Syncs files to server
1589 self.system_log_manager.KickSyncThread(
1590 core_dump_files, self.core_dump_manager.ClearFiles)
1591
Jon Salz8fa8e832012-07-13 19:04:09 +08001592 def sync_time_in_background(self):
Jon Salzb22d1172012-08-06 10:38:57 +08001593 '''Writes out current time and tries to sync with shopfloor server.'''
1594 if not self.time_sanitizer:
1595 return
1596
1597 # Write out the current time.
1598 self.time_sanitizer.SaveTime()
1599
Jon Salz54882d02012-08-31 01:57:54 +08001600 if not self._should_sync_time():
Jon Salz8fa8e832012-07-13 19:04:09 +08001601 return
1602
1603 now = time.time()
1604 if self.last_sync_time and (
1605 now - self.last_sync_time <
1606 self.test_list.options.sync_time_period_secs):
1607 # Not yet time for another check.
1608 return
1609 self.last_sync_time = now
1610
1611 def target():
1612 try:
Jon Salz54882d02012-08-31 01:57:54 +08001613 self.sync_time_with_shopfloor_server()
Jon Salz8fa8e832012-07-13 19:04:09 +08001614 except: # pylint: disable=W0702
1615 # Oh well. Log an error (but no trace)
1616 logging.info(
1617 'Unable to get time from shopfloor server: %s',
1618 utils.FormatExceptionOnly())
1619
1620 thread = threading.Thread(target=target)
1621 thread.daemon = True
1622 thread.start()
1623
Jon Salz0697cbf2012-07-04 15:14:04 +08001624 def _run_queue_idle(self):
Vic Yang4953fc12012-07-26 16:19:53 +08001625 '''Invoked when the run queue has no events.
1626
1627 This method must not raise exception.
1628 '''
Jon Salzb22d1172012-08-06 10:38:57 +08001629 now = time.time()
1630 if (self.last_idle and
1631 now < (self.last_idle + RUN_QUEUE_TIMEOUT_SECS - 1)):
1632 # Don't run more often than once every (RUN_QUEUE_TIMEOUT_SECS -
1633 # 1) seconds.
1634 return
1635
1636 self.last_idle = now
1637
Vic Yang311ddb82012-09-26 12:08:28 +08001638 self.check_exclusive()
cychiang21886742012-07-05 15:16:32 +08001639 self.check_for_updates()
Jon Salz8fa8e832012-07-13 19:04:09 +08001640 self.sync_time_in_background()
Jon Salzb92c5112012-09-21 15:40:11 +08001641 self.log_disk_space_stats()
Justin Chuang83813982013-05-13 01:26:32 +08001642 self.check_battery()
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001643 self.check_core_dump()
Jon Salz57717ca2012-04-04 16:47:25 +08001644
Jon Salzd15bbcf2013-05-21 17:33:57 +08001645 def handle_event_logs(self, chunks):
Jon Salz0697cbf2012-07-04 15:14:04 +08001646 '''Callback for event watcher.
Jon Salz258a40c2012-04-19 12:34:01 +08001647
Jon Salz0697cbf2012-07-04 15:14:04 +08001648 Attempts to upload the event logs to the shopfloor server.
Vic Yang93027612013-05-06 02:42:49 +08001649
1650 Args:
Jon Salzd15bbcf2013-05-21 17:33:57 +08001651 chunks: A list of Chunk objects.
Jon Salz0697cbf2012-07-04 15:14:04 +08001652 '''
Vic Yang93027612013-05-06 02:42:49 +08001653 first_exception = None
1654 exception_count = 0
1655
Jon Salzd15bbcf2013-05-21 17:33:57 +08001656 for chunk in chunks:
Vic Yang93027612013-05-06 02:42:49 +08001657 try:
Jon Salzd15bbcf2013-05-21 17:33:57 +08001658 description = 'event logs (%s)' % chunk
Vic Yang93027612013-05-06 02:42:49 +08001659 start_time = time.time()
1660 shopfloor_client = shopfloor.get_instance(
1661 detect=True,
1662 timeout=self.test_list.options.shopfloor_timeout_secs)
Jon Salzd15bbcf2013-05-21 17:33:57 +08001663 shopfloor_client.UploadEvent(chunk.log_name + "." +
1664 event_log.GetReimageId(),
1665 Binary(chunk.chunk))
Vic Yang93027612013-05-06 02:42:49 +08001666 logging.info(
1667 'Successfully synced %s in %.03f s',
1668 description, time.time() - start_time)
1669 except: # pylint: disable=W0702
Jon Salzd15bbcf2013-05-21 17:33:57 +08001670 first_exception = (first_exception or (chunk.log_name + ': ' +
Vic Yang93027612013-05-06 02:42:49 +08001671 utils.FormatExceptionOnly()))
1672 exception_count += 1
1673
1674 if exception_count:
1675 if exception_count == 1:
1676 msg = 'Log upload failed: %s' % first_exception
1677 else:
1678 msg = '%d log upload failed; first is: %s' % (
1679 exception_count, first_exception)
1680 raise Exception(msg)
1681
Jon Salz57717ca2012-04-04 16:47:25 +08001682
Jon Salz0697cbf2012-07-04 15:14:04 +08001683 def run_tests_with_status(self, statuses_to_run, starting_at=None,
1684 root=None):
1685 '''Runs all top-level tests with a particular status.
Jon Salz0405ab52012-03-16 15:26:52 +08001686
Jon Salz0697cbf2012-07-04 15:14:04 +08001687 All active tests, plus any tests to re-run, are reset.
Jon Salz57717ca2012-04-04 16:47:25 +08001688
Jon Salz0697cbf2012-07-04 15:14:04 +08001689 Args:
1690 starting_at: If provided, only auto-runs tests beginning with
1691 this test.
1692 '''
1693 root = root or self.test_list
Jon Salz57717ca2012-04-04 16:47:25 +08001694
Jon Salz0697cbf2012-07-04 15:14:04 +08001695 if starting_at:
1696 # Make sure they passed a test, not a string.
1697 assert isinstance(starting_at, factory.FactoryTest)
Jon Salz0405ab52012-03-16 15:26:52 +08001698
Jon Salz0697cbf2012-07-04 15:14:04 +08001699 tests_to_reset = []
1700 tests_to_run = []
Jon Salz0405ab52012-03-16 15:26:52 +08001701
Jon Salz0697cbf2012-07-04 15:14:04 +08001702 found_starting_at = False
Jon Salz0405ab52012-03-16 15:26:52 +08001703
Jon Salz0697cbf2012-07-04 15:14:04 +08001704 for test in root.get_top_level_tests():
1705 if starting_at:
1706 if test == starting_at:
1707 # We've found starting_at; do auto-run on all
1708 # subsequent tests.
1709 found_starting_at = True
1710 if not found_starting_at:
1711 # Don't start this guy yet
1712 continue
Jon Salz0405ab52012-03-16 15:26:52 +08001713
Jon Salz0697cbf2012-07-04 15:14:04 +08001714 status = test.get_state().status
1715 if status == TestState.ACTIVE or status in statuses_to_run:
1716 # Reset the test (later; we will need to abort
1717 # all active tests first).
1718 tests_to_reset.append(test)
1719 if status in statuses_to_run:
1720 tests_to_run.append(test)
Jon Salz0405ab52012-03-16 15:26:52 +08001721
Jon Salz0697cbf2012-07-04 15:14:04 +08001722 self.abort_active_tests()
Jon Salz258a40c2012-04-19 12:34:01 +08001723
Jon Salz0697cbf2012-07-04 15:14:04 +08001724 # Reset all statuses of the tests to run (in case any tests were active;
1725 # we want them to be run again).
1726 for test_to_reset in tests_to_reset:
1727 for test in test_to_reset.walk():
1728 test.update_state(status=TestState.UNTESTED)
Jon Salz57717ca2012-04-04 16:47:25 +08001729
Jon Salz0697cbf2012-07-04 15:14:04 +08001730 self.run_tests(tests_to_run, untested_only=True)
Jon Salz0405ab52012-03-16 15:26:52 +08001731
Jon Salz0697cbf2012-07-04 15:14:04 +08001732 def restart_tests(self, root=None):
1733 '''Restarts all tests.'''
1734 root = root or self.test_list
Jon Salz0405ab52012-03-16 15:26:52 +08001735
Jon Salz0697cbf2012-07-04 15:14:04 +08001736 self.abort_active_tests()
1737 for test in root.walk():
1738 test.update_state(status=TestState.UNTESTED)
1739 self.run_tests(root)
Hung-Te Lin96632362012-03-20 21:14:18 +08001740
Jon Salz0697cbf2012-07-04 15:14:04 +08001741 def auto_run(self, starting_at=None, root=None):
1742 '''"Auto-runs" tests that have not been run yet.
Hung-Te Lin96632362012-03-20 21:14:18 +08001743
Jon Salz0697cbf2012-07-04 15:14:04 +08001744 Args:
1745 starting_at: If provide, only auto-runs tests beginning with
1746 this test.
1747 '''
1748 root = root or self.test_list
1749 self.run_tests_with_status([TestState.UNTESTED, TestState.ACTIVE],
1750 starting_at=starting_at,
1751 root=root)
Jon Salz968e90b2012-03-18 16:12:43 +08001752
Jon Salz0697cbf2012-07-04 15:14:04 +08001753 def re_run_failed(self, root=None):
1754 '''Re-runs failed tests.'''
1755 root = root or self.test_list
1756 self.run_tests_with_status([TestState.FAILED], root=root)
Jon Salz57717ca2012-04-04 16:47:25 +08001757
Jon Salz0697cbf2012-07-04 15:14:04 +08001758 def show_review_information(self):
1759 '''Event handler for showing review information screen.
Jon Salz57717ca2012-04-04 16:47:25 +08001760
Jon Salz0697cbf2012-07-04 15:14:04 +08001761 The information screene is rendered by main UI program (ui.py), so in
1762 goofy we only need to kill all active tests, set them as untested, and
1763 clear remaining tests.
1764 '''
1765 self.kill_active_tests(False)
Jon Salza6711d72012-07-18 14:33:03 +08001766 self.cancel_pending_tests()
Jon Salz57717ca2012-04-04 16:47:25 +08001767
Jon Salz0697cbf2012-07-04 15:14:04 +08001768 def handle_switch_test(self, event):
1769 '''Switches to a particular test.
Jon Salz0405ab52012-03-16 15:26:52 +08001770
Jon Salz0697cbf2012-07-04 15:14:04 +08001771 @param event: The SWITCH_TEST event.
1772 '''
1773 test = self.test_list.lookup_path(event.path)
1774 if not test:
1775 logging.error('Unknown test %r', event.key)
1776 return
Jon Salz73e0fd02012-04-04 11:46:38 +08001777
Jon Salz0697cbf2012-07-04 15:14:04 +08001778 invoc = self.invocations.get(test)
1779 if invoc and test.backgroundable:
1780 # Already running: just bring to the front if it
1781 # has a UI.
1782 logging.info('Setting visible test to %s', test.path)
Jon Salz36fbbb52012-07-05 13:45:06 +08001783 self.set_visible_test(test)
Jon Salz0697cbf2012-07-04 15:14:04 +08001784 return
Jon Salz73e0fd02012-04-04 11:46:38 +08001785
Jon Salz0697cbf2012-07-04 15:14:04 +08001786 self.abort_active_tests()
1787 for t in test.walk():
1788 t.update_state(status=TestState.UNTESTED)
Jon Salz73e0fd02012-04-04 11:46:38 +08001789
Jon Salz0697cbf2012-07-04 15:14:04 +08001790 if self.test_list.options.auto_run_on_keypress:
1791 self.auto_run(starting_at=test)
1792 else:
1793 self.run_tests(test)
Jon Salz73e0fd02012-04-04 11:46:38 +08001794
Jon Salz0697cbf2012-07-04 15:14:04 +08001795 def wait(self):
1796 '''Waits for all pending invocations.
1797
1798 Useful for testing.
1799 '''
Jon Salz1acc8742012-07-17 17:45:55 +08001800 while self.invocations:
1801 for k, v in self.invocations.iteritems():
1802 logging.info('Waiting for %s to complete...', k)
1803 v.thread.join()
1804 self.reap_completed_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +08001805
1806 def check_exceptions(self):
1807 '''Raises an error if any exceptions have occurred in
1808 invocation threads.'''
1809 if self.exceptions:
1810 raise RuntimeError('Exception in invocation thread: %r' %
1811 self.exceptions)
1812
1813 def record_exception(self, msg):
1814 '''Records an exception in an invocation thread.
1815
1816 An exception with the given message will be rethrown when
1817 Goofy is destroyed.'''
1818 self.exceptions.append(msg)
Jon Salz73e0fd02012-04-04 11:46:38 +08001819
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001820
1821if __name__ == '__main__':
Jon Salz77c151e2012-08-28 07:20:37 +08001822 goofy = Goofy()
1823 try:
1824 goofy.main()
Jon Salz0f996602012-10-03 15:26:48 +08001825 except SystemExit:
1826 # Propagate SystemExit without logging.
1827 raise
Jon Salz31373eb2012-09-21 16:19:49 +08001828 except:
Jon Salz0f996602012-10-03 15:26:48 +08001829 # Log the error before trying to shut down (unless it's a graceful
1830 # exit).
Jon Salz31373eb2012-09-21 16:19:49 +08001831 logging.exception('Error in main loop')
1832 raise
Jon Salz77c151e2012-08-28 07:20:37 +08001833 finally:
1834 goofy.destroy()