blob: 8a5031616895db358bdd25bdc1aa091ebacd052c [file] [log] [blame]
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001#!/usr/bin/python -u
Hung-Te Linf2f78f72012-02-08 19:27:11 +08002# -*- coding: utf-8 -*-
3#
Jon Salz37eccbd2012-05-25 16:06:52 +08004# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
Hung-Te Linf2f78f72012-02-08 19:27:11 +08005# Use of this source code is governed by a BSD-style license that can be
6# found in the LICENSE file.
7
8'''
9The main factory flow that runs the factory test and finalizes a device.
10'''
11
Jon Salz0405ab52012-03-16 15:26:52 +080012import logging
13import os
Jon Salz73e0fd02012-04-04 11:46:38 +080014import Queue
Jon Salz77c151e2012-08-28 07:20:37 +080015import signal
Jon Salz0405ab52012-03-16 15:26:52 +080016import sys
Jon Salz0405ab52012-03-16 15:26:52 +080017import threading
18import time
19import traceback
Jon Salz258a40c2012-04-19 12:34:01 +080020import uuid
Jon Salzb10cf512012-08-09 17:29:21 +080021from xmlrpclib import Binary
Hung-Te Linf2f78f72012-02-08 19:27:11 +080022from collections import deque
23from optparse import OptionParser
Hung-Te Linf2f78f72012-02-08 19:27:11 +080024
Jon Salz0697cbf2012-07-04 15:14:04 +080025import factory_common # pylint: disable=W0611
jcliangcd688182012-08-20 21:01:26 +080026from cros.factory import event_log
27from cros.factory import system
28from cros.factory.event_log import EventLog
29from cros.factory.goofy import test_environment
30from cros.factory.goofy import time_sanitizer
Jon Salz83591782012-06-26 11:09:58 +080031from cros.factory.goofy import updater
Jon Salz51528e12012-07-02 18:54:45 +080032from cros.factory.goofy.event_log_watcher import EventLogWatcher
jcliangcd688182012-08-20 21:01:26 +080033from cros.factory.goofy.goofy_rpc import GoofyRPC
34from cros.factory.goofy.invocation import TestInvocation
35from cros.factory.goofy.prespawner import Prespawner
36from cros.factory.goofy.web_socket_manager import WebSocketManager
37from cros.factory.system.charge_manager import ChargeManager
Jon Salzb92c5112012-09-21 15:40:11 +080038from cros.factory.system import disk_space
jcliangcd688182012-08-20 21:01:26 +080039from cros.factory.test import factory
40from cros.factory.test import state
Jon Salz51528e12012-07-02 18:54:45 +080041from cros.factory.test import shopfloor
Jon Salz83591782012-06-26 11:09:58 +080042from cros.factory.test import utils
43from cros.factory.test.event import Event
44from cros.factory.test.event import EventClient
45from cros.factory.test.event import EventServer
jcliangcd688182012-08-20 21:01:26 +080046from cros.factory.test.factory import TestState
Jon Salz78c32392012-07-25 14:18:29 +080047from cros.factory.utils.process_utils import Spawn
Hung-Te Linf2f78f72012-02-08 19:27:11 +080048
49
Jon Salz2f757d42012-06-27 17:06:42 +080050DEFAULT_TEST_LISTS_DIR = os.path.join(factory.FACTORY_PATH, 'test_lists')
51CUSTOM_DIR = os.path.join(factory.FACTORY_PATH, 'custom')
Hung-Te Linf2f78f72012-02-08 19:27:11 +080052HWID_CFG_PATH = '/usr/local/share/chromeos-hwid/cfg'
53
Jon Salz8796e362012-05-24 11:39:09 +080054# File that suppresses reboot if present (e.g., for development).
55NO_REBOOT_FILE = '/var/log/factory.noreboot'
56
Jon Salz5c344f62012-07-13 14:31:16 +080057# Value for tests_after_shutdown that forces auto-run (e.g., after
58# a factory update, when the available set of tests might change).
59FORCE_AUTO_RUN = 'force_auto_run'
60
cychiang21886742012-07-05 15:16:32 +080061RUN_QUEUE_TIMEOUT_SECS = 10
62
Jon Salz758e6cc2012-04-03 15:47:07 +080063GOOFY_IN_CHROOT_WARNING = '\n' + ('*' * 70) + '''
64You are running Goofy inside the chroot. Autotests are not supported.
65
66To use Goofy in the chroot, first install an Xvnc server:
67
Jon Salz0697cbf2012-07-04 15:14:04 +080068 sudo apt-get install tightvncserver
Jon Salz758e6cc2012-04-03 15:47:07 +080069
70...and then start a VNC X server outside the chroot:
71
Jon Salz0697cbf2012-07-04 15:14:04 +080072 vncserver :10 &
73 vncviewer :10
Jon Salz758e6cc2012-04-03 15:47:07 +080074
75...and run Goofy as follows:
76
Jon Salz0697cbf2012-07-04 15:14:04 +080077 env --unset=XAUTHORITY DISPLAY=localhost:10 python goofy.py
Jon Salz758e6cc2012-04-03 15:47:07 +080078''' + ('*' * 70)
Jon Salz73e0fd02012-04-04 11:46:38 +080079suppress_chroot_warning = False
Hung-Te Linf2f78f72012-02-08 19:27:11 +080080
81def get_hwid_cfg():
Jon Salz0697cbf2012-07-04 15:14:04 +080082 '''
83 Returns the HWID config tag, or an empty string if none can be found.
84 '''
85 if 'CROS_HWID' in os.environ:
86 return os.environ['CROS_HWID']
87 if os.path.exists(HWID_CFG_PATH):
88 with open(HWID_CFG_PATH, 'rt') as hwid_cfg_handle:
89 return hwid_cfg_handle.read().strip()
90 return ''
Hung-Te Linf2f78f72012-02-08 19:27:11 +080091
92
93def find_test_list():
Jon Salz0697cbf2012-07-04 15:14:04 +080094 '''
95 Returns the path to the active test list, based on the HWID config tag.
96 '''
97 hwid_cfg = get_hwid_cfg()
Hung-Te Linf2f78f72012-02-08 19:27:11 +080098
Jon Salz0697cbf2012-07-04 15:14:04 +080099 search_dirs = [CUSTOM_DIR, DEFAULT_TEST_LISTS_DIR]
Jon Salz2f757d42012-06-27 17:06:42 +0800100
Jon Salz0697cbf2012-07-04 15:14:04 +0800101 # Try in order: test_list_${hwid_cfg}, test_list, test_list.all
102 search_files = ['test_list', 'test_list.all']
103 if hwid_cfg:
104 search_files.insert(0, hwid_cfg)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800105
Jon Salz0697cbf2012-07-04 15:14:04 +0800106 for d in search_dirs:
107 for f in search_files:
108 test_list = os.path.join(d, f)
109 if os.path.exists(test_list):
110 return test_list
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800111
Jon Salz0697cbf2012-07-04 15:14:04 +0800112 logging.warn('Cannot find test lists named any of %s in any of %s',
113 search_files, search_dirs)
114 return None
Jon Salz73e0fd02012-04-04 11:46:38 +0800115
Jon Salz73e0fd02012-04-04 11:46:38 +0800116_inited_logging = False
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800117
118class Goofy(object):
Jon Salz0697cbf2012-07-04 15:14:04 +0800119 '''
120 The main factory flow.
121
122 Note that all methods in this class must be invoked from the main
123 (event) thread. Other threads, such as callbacks and TestInvocation
124 methods, should instead post events on the run queue.
125
126 TODO: Unit tests. (chrome-os-partner:7409)
127
128 Properties:
129 uuid: A unique UUID for this invocation of Goofy.
130 state_instance: An instance of FactoryState.
131 state_server: The FactoryState XML/RPC server.
132 state_server_thread: A thread running state_server.
133 event_server: The EventServer socket server.
134 event_server_thread: A thread running event_server.
135 event_client: A client to the event server.
136 connection_manager: The connection_manager object.
Jon Salz0697cbf2012-07-04 15:14:04 +0800137 ui_process: The factory ui process object.
138 run_queue: A queue of callbacks to invoke from the main thread.
139 invocations: A map from FactoryTest objects to the corresponding
140 TestInvocations objects representing active tests.
141 tests_to_run: A deque of tests that should be run when the current
142 test(s) complete.
143 options: Command-line options.
144 args: Command-line args.
145 test_list: The test list.
146 event_handlers: Map of Event.Type to the method used to handle that
147 event. If the method has an 'event' argument, the event is passed
148 to the handler.
149 exceptions: Exceptions encountered in invocation threads.
150 '''
151 def __init__(self):
152 self.uuid = str(uuid.uuid4())
153 self.state_instance = None
154 self.state_server = None
155 self.state_server_thread = None
Jon Salz16d10542012-07-23 12:18:45 +0800156 self.goofy_rpc = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800157 self.event_server = None
158 self.event_server_thread = None
159 self.event_client = None
160 self.connection_manager = None
Vic Yang4953fc12012-07-26 16:19:53 +0800161 self.charge_manager = None
Jon Salz8fa8e832012-07-13 19:04:09 +0800162 self.time_sanitizer = None
163 self.time_synced = False
Jon Salz0697cbf2012-07-04 15:14:04 +0800164 self.log_watcher = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800165 self.event_log = None
166 self.prespawner = None
167 self.ui_process = None
Jon Salzc79a9982012-08-30 04:42:01 +0800168 self.dummy_shopfloor = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800169 self.run_queue = Queue.Queue()
170 self.invocations = {}
171 self.tests_to_run = deque()
172 self.visible_test = None
173 self.chrome = None
174
175 self.options = None
176 self.args = None
177 self.test_list = None
178 self.on_ui_startup = []
179 self.env = None
Jon Salzb22d1172012-08-06 10:38:57 +0800180 self.last_idle = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800181 self.last_shutdown_time = None
cychiang21886742012-07-05 15:16:32 +0800182 self.last_update_check = None
Jon Salz8fa8e832012-07-13 19:04:09 +0800183 self.last_sync_time = None
Jon Salzb92c5112012-09-21 15:40:11 +0800184 self.last_log_disk_space_time = None
Vic Yang311ddb82012-09-26 12:08:28 +0800185 self.exclusive_items = set()
Jon Salz0697cbf2012-07-04 15:14:04 +0800186
Jon Salz85a39882012-07-05 16:45:04 +0800187 def test_or_root(event, parent_or_group=True):
188 '''Returns the test affected by a particular event.
189
190 Args:
191 event: The event containing an optional 'path' attribute.
192 parent_on_group: If True, returns the top-level parent for a test (the
193 root node of the tests that need to be run together if the given test
194 path is to be run).
195 '''
Jon Salz0697cbf2012-07-04 15:14:04 +0800196 try:
197 path = event.path
198 except AttributeError:
199 path = None
200
201 if path:
Jon Salz85a39882012-07-05 16:45:04 +0800202 test = self.test_list.lookup_path(path)
203 if parent_or_group:
204 test = test.get_top_level_parent_or_group()
205 return test
Jon Salz0697cbf2012-07-04 15:14:04 +0800206 else:
207 return self.test_list
208
209 self.event_handlers = {
210 Event.Type.SWITCH_TEST: self.handle_switch_test,
211 Event.Type.SHOW_NEXT_ACTIVE_TEST:
212 lambda event: self.show_next_active_test(),
213 Event.Type.RESTART_TESTS:
214 lambda event: self.restart_tests(root=test_or_root(event)),
215 Event.Type.AUTO_RUN:
216 lambda event: self.auto_run(root=test_or_root(event)),
217 Event.Type.RE_RUN_FAILED:
218 lambda event: self.re_run_failed(root=test_or_root(event)),
219 Event.Type.RUN_TESTS_WITH_STATUS:
220 lambda event: self.run_tests_with_status(
221 event.status,
222 root=test_or_root(event)),
223 Event.Type.REVIEW:
224 lambda event: self.show_review_information(),
225 Event.Type.UPDATE_SYSTEM_INFO:
226 lambda event: self.update_system_info(),
Jon Salz0697cbf2012-07-04 15:14:04 +0800227 Event.Type.STOP:
Jon Salz85a39882012-07-05 16:45:04 +0800228 lambda event: self.stop(root=test_or_root(event, False),
229 fail=getattr(event, 'fail', False)),
Jon Salz36fbbb52012-07-05 13:45:06 +0800230 Event.Type.SET_VISIBLE_TEST:
231 lambda event: self.set_visible_test(
232 self.test_list.lookup_path(event.path)),
Jon Salz0697cbf2012-07-04 15:14:04 +0800233 }
234
235 self.exceptions = []
236 self.web_socket_manager = None
237
238 def destroy(self):
239 if self.chrome:
240 self.chrome.kill()
241 self.chrome = None
Jon Salzc79a9982012-08-30 04:42:01 +0800242 if self.dummy_shopfloor:
243 self.dummy_shopfloor.kill()
244 self.dummy_shopfloor = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800245 if self.ui_process:
246 utils.kill_process_tree(self.ui_process, 'ui')
247 self.ui_process = None
248 if self.web_socket_manager:
249 logging.info('Stopping web sockets')
250 self.web_socket_manager.close()
251 self.web_socket_manager = None
252 if self.state_server_thread:
253 logging.info('Stopping state server')
254 self.state_server.shutdown()
255 self.state_server_thread.join()
256 self.state_server.server_close()
257 self.state_server_thread = None
258 if self.state_instance:
259 self.state_instance.close()
260 if self.event_server_thread:
261 logging.info('Stopping event server')
262 self.event_server.shutdown() # pylint: disable=E1101
263 self.event_server_thread.join()
264 self.event_server.server_close()
265 self.event_server_thread = None
266 if self.log_watcher:
267 if self.log_watcher.IsThreadStarted():
268 self.log_watcher.StopWatchThread()
269 self.log_watcher = None
270 if self.prespawner:
271 logging.info('Stopping prespawner')
272 self.prespawner.stop()
273 self.prespawner = None
274 if self.event_client:
275 logging.info('Closing event client')
276 self.event_client.close()
277 self.event_client = None
278 if self.event_log:
279 self.event_log.Close()
280 self.event_log = None
281 self.check_exceptions()
282 logging.info('Done destroying Goofy')
283
284 def start_state_server(self):
285 self.state_instance, self.state_server = (
286 state.create_server(bind_address='0.0.0.0'))
Jon Salz16d10542012-07-23 12:18:45 +0800287 self.goofy_rpc = GoofyRPC(self)
288 self.goofy_rpc.RegisterMethods(self.state_instance)
Jon Salz0697cbf2012-07-04 15:14:04 +0800289 logging.info('Starting state server')
290 self.state_server_thread = threading.Thread(
291 target=self.state_server.serve_forever,
292 name='StateServer')
293 self.state_server_thread.start()
294
295 def start_event_server(self):
296 self.event_server = EventServer()
297 logging.info('Starting factory event server')
298 self.event_server_thread = threading.Thread(
299 target=self.event_server.serve_forever,
300 name='EventServer') # pylint: disable=E1101
301 self.event_server_thread.start()
302
303 self.event_client = EventClient(
304 callback=self.handle_event, event_loop=self.run_queue)
305
306 self.web_socket_manager = WebSocketManager(self.uuid)
307 self.state_server.add_handler("/event",
308 self.web_socket_manager.handle_web_socket)
309
310 def start_ui(self):
311 ui_proc_args = [
312 os.path.join(factory.FACTORY_PACKAGE_PATH, 'test', 'ui.py'),
313 self.options.test_list]
314 if self.options.verbose:
315 ui_proc_args.append('-v')
316 logging.info('Starting ui %s', ui_proc_args)
Jon Salz78c32392012-07-25 14:18:29 +0800317 self.ui_process = Spawn(ui_proc_args)
Jon Salz0697cbf2012-07-04 15:14:04 +0800318 logging.info('Waiting for UI to come up...')
319 self.event_client.wait(
320 lambda event: event.type == Event.Type.UI_READY)
321 logging.info('UI has started')
322
323 def set_visible_test(self, test):
324 if self.visible_test == test:
325 return
Jon Salz2f2d42c2012-07-30 12:30:34 +0800326 if test and not test.has_ui:
327 return
Jon Salz0697cbf2012-07-04 15:14:04 +0800328
329 if test:
330 test.update_state(visible=True)
331 if self.visible_test:
332 self.visible_test.update_state(visible=False)
333 self.visible_test = test
334
335 def handle_shutdown_complete(self, test, test_state):
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800336 '''
Jon Salz0697cbf2012-07-04 15:14:04 +0800337 Handles the case where a shutdown was detected during a shutdown step.
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800338
Jon Salz0697cbf2012-07-04 15:14:04 +0800339 @param test: The ShutdownStep.
340 @param test_state: The test state.
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800341 '''
Jon Salz0697cbf2012-07-04 15:14:04 +0800342 test_state = test.update_state(increment_shutdown_count=1)
343 logging.info('Detected shutdown (%d of %d)',
344 test_state.shutdown_count, test.iterations)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800345
Jon Salz0697cbf2012-07-04 15:14:04 +0800346 def log_and_update_state(status, error_msg, **kw):
347 self.event_log.Log('rebooted',
348 status=status, error_msg=error_msg, **kw)
349 test.update_state(status=status, error_msg=error_msg)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800350
Jon Salz0697cbf2012-07-04 15:14:04 +0800351 if not self.last_shutdown_time:
352 log_and_update_state(status=TestState.FAILED,
353 error_msg='Unable to read shutdown_time')
354 return
Jon Salz258a40c2012-04-19 12:34:01 +0800355
Jon Salz0697cbf2012-07-04 15:14:04 +0800356 now = time.time()
357 logging.info('%.03f s passed since reboot',
358 now - self.last_shutdown_time)
Jon Salz258a40c2012-04-19 12:34:01 +0800359
Jon Salz0697cbf2012-07-04 15:14:04 +0800360 if self.last_shutdown_time > now:
361 test.update_state(status=TestState.FAILED,
362 error_msg='Time moved backward during reboot')
363 elif (isinstance(test, factory.RebootStep) and
364 self.test_list.options.max_reboot_time_secs and
365 (now - self.last_shutdown_time >
366 self.test_list.options.max_reboot_time_secs)):
367 # A reboot took too long; fail. (We don't check this for
368 # HaltSteps, because the machine could be halted for a
369 # very long time, and even unplugged with battery backup,
370 # thus hosing the clock.)
371 log_and_update_state(
372 status=TestState.FAILED,
373 error_msg=('More than %d s elapsed during reboot '
374 '(%.03f s, from %s to %s)' % (
375 self.test_list.options.max_reboot_time_secs,
376 now - self.last_shutdown_time,
377 utils.TimeString(self.last_shutdown_time),
378 utils.TimeString(now))),
379 duration=(now-self.last_shutdown_time))
380 elif test_state.shutdown_count == test.iterations:
381 # Good!
382 log_and_update_state(status=TestState.PASSED,
383 duration=(now - self.last_shutdown_time),
384 error_msg='')
385 elif test_state.shutdown_count > test.iterations:
386 # Shut down too many times
387 log_and_update_state(status=TestState.FAILED,
388 error_msg='Too many shutdowns')
389 elif utils.are_shift_keys_depressed():
390 logging.info('Shift keys are depressed; cancelling restarts')
391 # Abort shutdown
392 log_and_update_state(
393 status=TestState.FAILED,
394 error_msg='Shutdown aborted with double shift keys')
Jon Salza6711d72012-07-18 14:33:03 +0800395 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +0800396 else:
397 def handler():
398 if self._prompt_cancel_shutdown(
399 test, test_state.shutdown_count + 1):
Jon Salza6711d72012-07-18 14:33:03 +0800400 factory.console.info('Shutdown aborted by operator')
Jon Salz0697cbf2012-07-04 15:14:04 +0800401 log_and_update_state(
402 status=TestState.FAILED,
403 error_msg='Shutdown aborted by operator')
Jon Salza6711d72012-07-18 14:33:03 +0800404 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +0800405 return
Jon Salz0405ab52012-03-16 15:26:52 +0800406
Jon Salz0697cbf2012-07-04 15:14:04 +0800407 # Time to shutdown again
408 log_and_update_state(
409 status=TestState.ACTIVE,
410 error_msg='',
411 iteration=test_state.shutdown_count)
Jon Salz73e0fd02012-04-04 11:46:38 +0800412
Jon Salz0697cbf2012-07-04 15:14:04 +0800413 self.event_log.Log('shutdown', operation='reboot')
414 self.state_instance.set_shared_data('shutdown_time',
415 time.time())
416 self.env.shutdown('reboot')
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800417
Jon Salz0697cbf2012-07-04 15:14:04 +0800418 self.on_ui_startup.append(handler)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800419
Jon Salz0697cbf2012-07-04 15:14:04 +0800420 def _prompt_cancel_shutdown(self, test, iteration):
421 if self.options.ui != 'chrome':
422 return False
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800423
Jon Salz0697cbf2012-07-04 15:14:04 +0800424 pending_shutdown_data = {
425 'delay_secs': test.delay_secs,
426 'time': time.time() + test.delay_secs,
427 'operation': test.operation,
428 'iteration': iteration,
429 'iterations': test.iterations,
430 }
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800431
Jon Salz0697cbf2012-07-04 15:14:04 +0800432 # Create a new (threaded) event client since we
433 # don't want to use the event loop for this.
434 with EventClient() as event_client:
435 event_client.post_event(Event(Event.Type.PENDING_SHUTDOWN,
436 **pending_shutdown_data))
437 aborted = event_client.wait(
438 lambda event: event.type == Event.Type.CANCEL_SHUTDOWN,
439 timeout=test.delay_secs) is not None
440 if aborted:
441 event_client.post_event(Event(Event.Type.PENDING_SHUTDOWN))
442 return aborted
Jon Salz258a40c2012-04-19 12:34:01 +0800443
Jon Salz0697cbf2012-07-04 15:14:04 +0800444 def init_states(self):
445 '''
446 Initializes all states on startup.
447 '''
448 for test in self.test_list.get_all_tests():
449 # Make sure the state server knows about all the tests,
450 # defaulting to an untested state.
451 test.update_state(update_parent=False, visible=False)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800452
Jon Salz0697cbf2012-07-04 15:14:04 +0800453 var_log_messages = None
Vic Yanga9c32212012-08-16 20:07:54 +0800454 mosys_log = None
Vic Yange4c275d2012-08-28 01:50:20 +0800455 ec_console_log = None
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800456
Jon Salz0697cbf2012-07-04 15:14:04 +0800457 # Any 'active' tests should be marked as failed now.
458 for test in self.test_list.walk():
Jon Salza6711d72012-07-18 14:33:03 +0800459 if not test.is_leaf():
460 # Don't bother with parents; they will be updated when their
461 # children are updated.
462 continue
463
Jon Salz0697cbf2012-07-04 15:14:04 +0800464 test_state = test.get_state()
465 if test_state.status != TestState.ACTIVE:
466 continue
467 if isinstance(test, factory.ShutdownStep):
468 # Shutdown while the test was active - that's good.
469 self.handle_shutdown_complete(test, test_state)
470 else:
471 # Unexpected shutdown. Grab /var/log/messages for context.
472 if var_log_messages is None:
473 try:
474 var_log_messages = (
475 utils.var_log_messages_before_reboot())
476 # Write it to the log, to make it easier to
477 # correlate with /var/log/messages.
478 logging.info(
479 'Unexpected shutdown. '
480 'Tail of /var/log/messages before last reboot:\n'
481 '%s', ('\n'.join(
482 ' ' + x for x in var_log_messages)))
483 except: # pylint: disable=W0702
484 logging.exception('Unable to grok /var/log/messages')
485 var_log_messages = []
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800486
Jon Salz008f4ea2012-08-28 05:39:45 +0800487 if mosys_log is None and not utils.in_chroot():
488 try:
489 mosys_log = utils.Spawn(
490 ['mosys', 'eventlog', 'list'],
491 read_stdout=True, log_stderr_on_error=True).stdout_data
492 # Write it to the log also.
493 logging.info('System eventlog from mosys:\n%s\n', mosys_log)
494 except: # pylint: disable=W0702
495 logging.exception('Unable to read mosys eventlog')
Vic Yanga9c32212012-08-16 20:07:54 +0800496
Vic Yange4c275d2012-08-28 01:50:20 +0800497 if ec_console_log is None:
498 try:
499 ec = system.GetEC()
500 ec_console_log = ec.GetConsoleLog()
501 logging.info('EC console log after reboot:\n%s\n', ec_console_log)
Jon Salzfe1f6652012-09-07 05:40:14 +0800502 except: # pylint: disable=W0702
Vic Yange4c275d2012-08-28 01:50:20 +0800503 logging.exception('Error retrieving EC console log')
504
Jon Salz0697cbf2012-07-04 15:14:04 +0800505 error_msg = 'Unexpected shutdown while test was running'
506 self.event_log.Log('end_test',
507 path=test.path,
508 status=TestState.FAILED,
509 invocation=test.get_state().invocation,
510 error_msg=error_msg,
Vic Yanga9c32212012-08-16 20:07:54 +0800511 var_log_messages='\n'.join(var_log_messages),
512 mosys_log=mosys_log)
Jon Salz0697cbf2012-07-04 15:14:04 +0800513 test.update_state(
514 status=TestState.FAILED,
515 error_msg=error_msg)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800516
Jon Salz50efe942012-07-26 11:54:10 +0800517 if not test.never_fails:
518 # For "never_fails" tests (such as "Start"), don't cancel
519 # pending tests, since reboot is expected.
520 factory.console.info('Unexpected shutdown while test %s '
521 'running; cancelling any pending tests',
522 test.path)
523 self.state_instance.set_shared_data('tests_after_shutdown', [])
Jon Salz69806bb2012-07-20 18:05:02 +0800524
Jon Salz008f4ea2012-08-28 05:39:45 +0800525 self.update_skipped_tests()
526
527 def update_skipped_tests(self):
528 '''
529 Updates skipped states based on run_if.
530 '''
531 for t in self.test_list.walk():
532 if t.is_leaf() and t.run_if_table_name:
533 skip = False
534 try:
535 aux = shopfloor.get_selected_aux_data(t.run_if_table_name)
536 value = aux.get(t.run_if_col)
537 if value is not None:
538 skip = (not value) ^ t.run_if_not
539 except ValueError:
540 # Not available; assume it shouldn't be skipped
541 pass
542
543 test_state = t.get_state()
544 if ((not skip) and
545 (test_state.status == TestState.PASSED) and
546 (test_state.error_msg == TestState.SKIPPED_MSG)):
547 # It was marked as skipped before, but now we need to run it.
548 # Mark as untested.
549 t.update_state(skip=skip, status=TestState.UNTESTED, error_msg='')
550 else:
551 t.update_state(skip=skip)
552
Jon Salz0697cbf2012-07-04 15:14:04 +0800553 def show_next_active_test(self):
554 '''
555 Rotates to the next visible active test.
556 '''
557 self.reap_completed_tests()
558 active_tests = [
559 t for t in self.test_list.walk()
560 if t.is_leaf() and t.get_state().status == TestState.ACTIVE]
561 if not active_tests:
562 return
Jon Salz4f6c7172012-06-11 20:45:36 +0800563
Jon Salz0697cbf2012-07-04 15:14:04 +0800564 try:
565 next_test = active_tests[
566 (active_tests.index(self.visible_test) + 1) % len(active_tests)]
567 except ValueError: # visible_test not present in active_tests
568 next_test = active_tests[0]
Jon Salz4f6c7172012-06-11 20:45:36 +0800569
Jon Salz0697cbf2012-07-04 15:14:04 +0800570 self.set_visible_test(next_test)
Jon Salz4f6c7172012-06-11 20:45:36 +0800571
Jon Salz0697cbf2012-07-04 15:14:04 +0800572 def handle_event(self, event):
573 '''
574 Handles an event from the event server.
575 '''
576 handler = self.event_handlers.get(event.type)
577 if handler:
578 handler(event)
579 else:
580 # We don't register handlers for all event types - just ignore
581 # this event.
582 logging.debug('Unbound event type %s', event.type)
Jon Salz4f6c7172012-06-11 20:45:36 +0800583
Jon Salz0697cbf2012-07-04 15:14:04 +0800584 def run_next_test(self):
585 '''
586 Runs the next eligible test (or tests) in self.tests_to_run.
587 '''
588 self.reap_completed_tests()
589 while self.tests_to_run:
590 logging.debug('Tests to run: %s',
591 [x.path for x in self.tests_to_run])
Jon Salz94eb56f2012-06-12 18:01:12 +0800592
Jon Salz0697cbf2012-07-04 15:14:04 +0800593 test = self.tests_to_run[0]
Jon Salz94eb56f2012-06-12 18:01:12 +0800594
Jon Salz0697cbf2012-07-04 15:14:04 +0800595 if test in self.invocations:
596 logging.info('Next test %s is already running', test.path)
597 self.tests_to_run.popleft()
598 return
Jon Salz94eb56f2012-06-12 18:01:12 +0800599
Jon Salz008f4ea2012-08-28 05:39:45 +0800600 if test.get_state().skip:
601 factory.console.info('Skipping test %s', test.path)
602 test.update_state(status=TestState.PASSED,
603 error_msg=TestState.SKIPPED_MSG)
604 self.tests_to_run.popleft()
605 return
606
Jon Salza1412922012-07-23 16:04:17 +0800607 for requirement in test.require_run:
608 for i in requirement.test.walk():
609 if i.get_state().status == TestState.ACTIVE:
Jon Salz304a75d2012-07-06 11:14:15 +0800610 logging.info('Waiting for active test %s to complete '
Jon Salza1412922012-07-23 16:04:17 +0800611 'before running %s', i.path, test.path)
Jon Salz304a75d2012-07-06 11:14:15 +0800612 return
613
Jon Salz0697cbf2012-07-04 15:14:04 +0800614 if self.invocations and not (test.backgroundable and all(
615 [x.backgroundable for x in self.invocations])):
616 logging.debug('Waiting for non-backgroundable tests to '
617 'complete before running %s', test.path)
618 return
Jon Salz94eb56f2012-06-12 18:01:12 +0800619
Jon Salz0697cbf2012-07-04 15:14:04 +0800620 self.tests_to_run.popleft()
Jon Salz94eb56f2012-06-12 18:01:12 +0800621
Jon Salz304a75d2012-07-06 11:14:15 +0800622 untested = set()
Jon Salza1412922012-07-23 16:04:17 +0800623 for requirement in test.require_run:
624 for i in requirement.test.walk():
625 if i == test:
Jon Salz304a75d2012-07-06 11:14:15 +0800626 # We've hit this test itself; stop checking
627 break
Jon Salza1412922012-07-23 16:04:17 +0800628 if ((i.get_state().status == TestState.UNTESTED) or
629 (requirement.passed and i.get_state().status !=
630 TestState.PASSED)):
Jon Salz304a75d2012-07-06 11:14:15 +0800631 # Found an untested test; move on to the next
632 # element in require_run.
Jon Salza1412922012-07-23 16:04:17 +0800633 untested.add(i)
Jon Salz304a75d2012-07-06 11:14:15 +0800634 break
635
636 if untested:
637 untested_paths = ', '.join(sorted([x.path for x in untested]))
638 if self.state_instance.get_shared_data('engineering_mode',
639 optional=True):
640 # In engineering mode, we'll let it go.
641 factory.console.warn('In engineering mode; running '
642 '%s even though required tests '
643 '[%s] have not completed',
644 test.path, untested_paths)
645 else:
646 # Not in engineering mode; mark it failed.
647 error_msg = ('Required tests [%s] have not been run yet'
648 % untested_paths)
649 factory.console.error('Not running %s: %s',
650 test.path, error_msg)
651 test.update_state(status=TestState.FAILED,
652 error_msg=error_msg)
653 continue
654
Jon Salz0697cbf2012-07-04 15:14:04 +0800655 if isinstance(test, factory.ShutdownStep):
656 if os.path.exists(NO_REBOOT_FILE):
657 test.update_state(
658 status=TestState.FAILED, increment_count=1,
659 error_msg=('Skipped shutdown since %s is present' %
Jon Salz304a75d2012-07-06 11:14:15 +0800660 NO_REBOOT_FILE))
Jon Salz0697cbf2012-07-04 15:14:04 +0800661 continue
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800662
Jon Salz0697cbf2012-07-04 15:14:04 +0800663 test.update_state(status=TestState.ACTIVE, increment_count=1,
664 error_msg='', shutdown_count=0)
665 if self._prompt_cancel_shutdown(test, 1):
666 self.event_log.Log('reboot_cancelled')
667 test.update_state(
668 status=TestState.FAILED, increment_count=1,
669 error_msg='Shutdown aborted by operator',
670 shutdown_count=0)
chungyiafe8f772012-08-15 19:36:29 +0800671 continue
Jon Salz2f757d42012-06-27 17:06:42 +0800672
Jon Salz0697cbf2012-07-04 15:14:04 +0800673 # Save pending test list in the state server
Jon Salzdbf398f2012-06-14 17:30:01 +0800674 self.state_instance.set_shared_data(
Jon Salz0697cbf2012-07-04 15:14:04 +0800675 'tests_after_shutdown',
676 [t.path for t in self.tests_to_run])
677 # Save shutdown time
678 self.state_instance.set_shared_data('shutdown_time',
679 time.time())
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800680
Jon Salz0697cbf2012-07-04 15:14:04 +0800681 with self.env.lock:
682 self.event_log.Log('shutdown', operation=test.operation)
683 shutdown_result = self.env.shutdown(test.operation)
684 if shutdown_result:
685 # That's all, folks!
686 self.run_queue.put(None)
687 return
688 else:
689 # Just pass (e.g., in the chroot).
690 test.update_state(status=TestState.PASSED)
691 self.state_instance.set_shared_data(
692 'tests_after_shutdown', None)
693 # Send event with no fields to indicate that there is no
694 # longer a pending shutdown.
695 self.event_client.post_event(Event(
696 Event.Type.PENDING_SHUTDOWN))
697 continue
Jon Salz258a40c2012-04-19 12:34:01 +0800698
Jon Salz1acc8742012-07-17 17:45:55 +0800699 self._run_test(test, test.iterations)
700
701 def _run_test(self, test, iterations_left=None):
702 invoc = TestInvocation(self, test, on_completion=self.run_next_test)
703 new_state = test.update_state(
704 status=TestState.ACTIVE, increment_count=1, error_msg='',
Jon Salzbd42ce12012-09-18 08:03:59 +0800705 invocation=invoc.uuid, iterations_left=iterations_left,
706 visible=(self.visible_test == test))
Jon Salz1acc8742012-07-17 17:45:55 +0800707 invoc.count = new_state.count
708
709 self.invocations[test] = invoc
710 if self.visible_test is None and test.has_ui:
711 self.set_visible_test(test)
Vic Yang311ddb82012-09-26 12:08:28 +0800712 self.check_exclusive()
Jon Salz1acc8742012-07-17 17:45:55 +0800713 invoc.start()
Jon Salz5f2a0672012-05-22 17:14:06 +0800714
Vic Yang311ddb82012-09-26 12:08:28 +0800715 def check_exclusive(self):
716 current_exclusive_items = set([
717 item
718 for item in factory.FactoryTest.EXCLUSIVE_OPTIONS
719 if any([test.is_exclusive(item) for test in self.invocations])])
720
721 new_exclusive_items = current_exclusive_items - self.exclusive_items
722 if factory.FactoryTest.EXCLUSIVE_OPTIONS.NETWORKING in new_exclusive_items:
723 logging.info('Disabling network')
724 self.connection_manager.DisableNetworking()
725 if factory.FactoryTest.EXCLUSIVE_OPTIONS.CHARGER in new_exclusive_items:
726 logging.info('Stop controlling charger')
727
728 new_non_exclusive_items = self.exclusive_items - current_exclusive_items
729 if (factory.FactoryTest.EXCLUSIVE_OPTIONS.NETWORKING in
730 new_non_exclusive_items):
731 logging.info('Re-enabling network')
732 self.connection_manager.EnableNetworking()
733 if factory.FactoryTest.EXCLUSIVE_OPTIONS.CHARGER in new_non_exclusive_items:
734 logging.info('Start controlling charger')
735
736 # Only adjust charge state if not excluded
737 if (self.charge_manager and
738 not factory.FactoryTest.EXCLUSIVE_OPTIONS.CHARGER in
739 current_exclusive_items):
740 self.charge_manager.AdjustChargeState()
741
742 self.exclusive_items = current_exclusive_items
Jon Salz5da61e62012-05-31 13:06:22 +0800743
cychiang21886742012-07-05 15:16:32 +0800744 def check_for_updates(self):
745 '''
746 Schedules an asynchronous check for updates if necessary.
747 '''
748 if not self.test_list.options.update_period_secs:
749 # Not enabled.
750 return
751
752 now = time.time()
753 if self.last_update_check and (
754 now - self.last_update_check <
755 self.test_list.options.update_period_secs):
756 # Not yet time for another check.
757 return
758
759 self.last_update_check = now
760
761 def handle_check_for_update(reached_shopfloor, md5sum, needs_update):
762 if reached_shopfloor:
763 new_update_md5sum = md5sum if needs_update else None
764 if system.SystemInfo.update_md5sum != new_update_md5sum:
765 logging.info('Received new update MD5SUM: %s', new_update_md5sum)
766 system.SystemInfo.update_md5sum = new_update_md5sum
767 self.run_queue.put(self.update_system_info)
768
769 updater.CheckForUpdateAsync(
770 handle_check_for_update,
771 self.test_list.options.shopfloor_timeout_secs)
772
Jon Salza6711d72012-07-18 14:33:03 +0800773 def cancel_pending_tests(self):
774 '''Cancels any tests in the run queue.'''
775 self.run_tests([])
776
Jon Salz0697cbf2012-07-04 15:14:04 +0800777 def run_tests(self, subtrees, untested_only=False):
778 '''
779 Runs tests under subtree.
Jon Salz258a40c2012-04-19 12:34:01 +0800780
Jon Salz0697cbf2012-07-04 15:14:04 +0800781 The tests are run in order unless one fails (then stops).
782 Backgroundable tests are run simultaneously; when a foreground test is
783 encountered, we wait for all active tests to finish before continuing.
Jon Salzb1b39092012-05-03 02:05:09 +0800784
Jon Salz0697cbf2012-07-04 15:14:04 +0800785 @param subtrees: Node or nodes containing tests to run (may either be
786 a single test or a list). Duplicates will be ignored.
787 '''
788 if type(subtrees) != list:
789 subtrees = [subtrees]
Jon Salz258a40c2012-04-19 12:34:01 +0800790
Jon Salz0697cbf2012-07-04 15:14:04 +0800791 # Nodes we've seen so far, to avoid duplicates.
792 seen = set()
Jon Salz94eb56f2012-06-12 18:01:12 +0800793
Jon Salz0697cbf2012-07-04 15:14:04 +0800794 self.tests_to_run = deque()
795 for subtree in subtrees:
796 for test in subtree.walk():
797 if test in seen:
798 continue
799 seen.add(test)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800800
Jon Salz0697cbf2012-07-04 15:14:04 +0800801 if not test.is_leaf():
802 continue
803 if (untested_only and
804 test.get_state().status != TestState.UNTESTED):
805 continue
806 self.tests_to_run.append(test)
807 self.run_next_test()
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800808
Jon Salz0697cbf2012-07-04 15:14:04 +0800809 def reap_completed_tests(self):
810 '''
811 Removes completed tests from the set of active tests.
812
813 Also updates the visible test if it was reaped.
814 '''
815 for t, v in dict(self.invocations).iteritems():
816 if v.is_completed():
Jon Salz1acc8742012-07-17 17:45:55 +0800817 new_state = t.update_state(**v.update_state_on_completion)
Jon Salz0697cbf2012-07-04 15:14:04 +0800818 del self.invocations[t]
819
Chun-Ta Lin54e17e42012-09-06 22:05:13 +0800820 # Stop on failure if flag is true.
821 if (self.test_list.options.stop_on_failure and
822 new_state.status == TestState.FAILED):
823 # Clean all the tests to cause goofy to stop.
824 self.tests_to_run = []
825 factory.console.info("Stop on failure triggered. Empty the queue.")
826
Jon Salz1acc8742012-07-17 17:45:55 +0800827 if new_state.iterations_left and new_state.status == TestState.PASSED:
828 # Play it again, Sam!
829 self._run_test(t)
830
Jon Salz0697cbf2012-07-04 15:14:04 +0800831 if (self.visible_test is None or
Jon Salz85a39882012-07-05 16:45:04 +0800832 self.visible_test not in self.invocations):
Jon Salz0697cbf2012-07-04 15:14:04 +0800833 self.set_visible_test(None)
834 # Make the first running test, if any, the visible test
835 for t in self.test_list.walk():
836 if t in self.invocations:
837 self.set_visible_test(t)
838 break
839
Jon Salz85a39882012-07-05 16:45:04 +0800840 def kill_active_tests(self, abort, root=None):
Jon Salz0697cbf2012-07-04 15:14:04 +0800841 '''
842 Kills and waits for all active tests.
843
Jon Salz85a39882012-07-05 16:45:04 +0800844 Args:
845 abort: True to change state of killed tests to FAILED, False for
Jon Salz0697cbf2012-07-04 15:14:04 +0800846 UNTESTED.
Jon Salz85a39882012-07-05 16:45:04 +0800847 root: If set, only kills tests with root as an ancestor.
Jon Salz0697cbf2012-07-04 15:14:04 +0800848 '''
849 self.reap_completed_tests()
850 for test, invoc in self.invocations.items():
Jon Salz85a39882012-07-05 16:45:04 +0800851 if root and not test.has_ancestor(root):
852 continue
853
Jon Salz0697cbf2012-07-04 15:14:04 +0800854 factory.console.info('Killing active test %s...' % test.path)
855 invoc.abort_and_join()
856 factory.console.info('Killed %s' % test.path)
Jon Salz1acc8742012-07-17 17:45:55 +0800857 test.update_state(**invoc.update_state_on_completion)
Jon Salz0697cbf2012-07-04 15:14:04 +0800858 del self.invocations[test]
Jon Salz1acc8742012-07-17 17:45:55 +0800859
Jon Salz0697cbf2012-07-04 15:14:04 +0800860 if not abort:
861 test.update_state(status=TestState.UNTESTED)
862 self.reap_completed_tests()
863
Jon Salz85a39882012-07-05 16:45:04 +0800864 def stop(self, root=None, fail=False):
865 self.kill_active_tests(fail, root)
866 # Remove any tests in the run queue under the root.
867 self.tests_to_run = deque([x for x in self.tests_to_run
868 if root and not x.has_ancestor(root)])
869 self.run_next_test()
Jon Salz0697cbf2012-07-04 15:14:04 +0800870
871 def abort_active_tests(self):
872 self.kill_active_tests(True)
873
874 def main(self):
875 try:
876 self.init()
877 self.event_log.Log('goofy_init',
878 success=True)
879 except:
880 if self.event_log:
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800881 try:
Jon Salz0697cbf2012-07-04 15:14:04 +0800882 self.event_log.Log('goofy_init',
883 success=False,
884 trace=traceback.format_exc())
885 except: # pylint: disable=W0702
886 pass
887 raise
888
889 self.run()
890
891 def update_system_info(self):
892 '''Updates system info.'''
893 system_info = system.SystemInfo()
894 self.state_instance.set_shared_data('system_info', system_info.__dict__)
895 self.event_client.post_event(Event(Event.Type.SYSTEM_INFO,
896 system_info=system_info.__dict__))
897 logging.info('System info: %r', system_info.__dict__)
898
Jon Salzeb42f0d2012-07-27 19:14:04 +0800899 def update_factory(self, auto_run_on_restart=False, post_update_hook=None):
900 '''Commences updating factory software.
901
902 Args:
903 auto_run_on_restart: Auto-run when the machine comes back up.
904 post_update_hook: Code to call after update but immediately before
905 restart.
906
907 Returns:
908 Never if the update was successful (we just reboot).
909 False if the update was unnecessary (no update available).
910 '''
Jon Salz0697cbf2012-07-04 15:14:04 +0800911 self.kill_active_tests(False)
Jon Salza6711d72012-07-18 14:33:03 +0800912 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +0800913
Jon Salz5c344f62012-07-13 14:31:16 +0800914 def pre_update_hook():
915 if auto_run_on_restart:
916 self.state_instance.set_shared_data('tests_after_shutdown',
917 FORCE_AUTO_RUN)
918 self.state_instance.close()
919
Jon Salzeb42f0d2012-07-27 19:14:04 +0800920 if updater.TryUpdate(pre_update_hook=pre_update_hook):
921 if post_update_hook:
922 post_update_hook()
923 self.env.shutdown('reboot')
Jon Salz0697cbf2012-07-04 15:14:04 +0800924
Jon Salzcef132a2012-08-30 04:58:08 +0800925 def handle_sigint(self, dummy_signum, dummy_frame):
Jon Salz77c151e2012-08-28 07:20:37 +0800926 logging.error('Received SIGINT')
927 self.run_queue.put(None)
928 raise KeyboardInterrupt()
929
Jon Salz0697cbf2012-07-04 15:14:04 +0800930 def init(self, args=None, env=None):
931 '''Initializes Goofy.
932
933 Args:
934 args: A list of command-line arguments. Uses sys.argv if
935 args is None.
936 env: An Environment instance to use (or None to choose
937 FakeChrootEnvironment or DUTEnvironment as appropriate).
938 '''
Jon Salz77c151e2012-08-28 07:20:37 +0800939 signal.signal(signal.SIGINT, self.handle_sigint)
940
Jon Salz0697cbf2012-07-04 15:14:04 +0800941 parser = OptionParser()
942 parser.add_option('-v', '--verbose', dest='verbose',
Jon Salz8fa8e832012-07-13 19:04:09 +0800943 action='store_true',
944 help='Enable debug logging')
Jon Salz0697cbf2012-07-04 15:14:04 +0800945 parser.add_option('--print_test_list', dest='print_test_list',
Jon Salz8fa8e832012-07-13 19:04:09 +0800946 metavar='FILE',
947 help='Read and print test list FILE, and exit')
Jon Salz0697cbf2012-07-04 15:14:04 +0800948 parser.add_option('--restart', dest='restart',
Jon Salz8fa8e832012-07-13 19:04:09 +0800949 action='store_true',
950 help='Clear all test state')
Jon Salz0697cbf2012-07-04 15:14:04 +0800951 parser.add_option('--ui', dest='ui', type='choice',
Jon Salz8fa8e832012-07-13 19:04:09 +0800952 choices=['none', 'gtk', 'chrome'],
953 default=('chrome' if utils.in_chroot() else 'gtk'),
954 help='UI to use')
Jon Salz0697cbf2012-07-04 15:14:04 +0800955 parser.add_option('--ui_scale_factor', dest='ui_scale_factor',
Jon Salz8fa8e832012-07-13 19:04:09 +0800956 type='int', default=1,
957 help=('Factor by which to scale UI '
958 '(Chrome UI only)'))
Jon Salz0697cbf2012-07-04 15:14:04 +0800959 parser.add_option('--test_list', dest='test_list',
Jon Salz8fa8e832012-07-13 19:04:09 +0800960 metavar='FILE',
961 help='Use FILE as test list')
Jon Salzc79a9982012-08-30 04:42:01 +0800962 parser.add_option('--dummy_shopfloor', action='store_true',
963 help='Use a dummy shopfloor server')
chungyiafe8f772012-08-15 19:36:29 +0800964 parser.add_option('--automation', dest='automation',
965 action='store_true',
966 help='Enable automation on running factory test')
Jon Salz0697cbf2012-07-04 15:14:04 +0800967 (self.options, self.args) = parser.parse_args(args)
968
Jon Salz46b89562012-07-05 11:49:22 +0800969 # Make sure factory directories exist.
970 factory.get_log_root()
971 factory.get_state_root()
972 factory.get_test_data_root()
973
Jon Salz0697cbf2012-07-04 15:14:04 +0800974 global _inited_logging # pylint: disable=W0603
975 if not _inited_logging:
976 factory.init_logging('goofy', verbose=self.options.verbose)
977 _inited_logging = True
Jon Salz8fa8e832012-07-13 19:04:09 +0800978
Jon Salzee85d522012-07-17 14:34:46 +0800979 event_log.IncrementBootSequence()
Jon Salz0697cbf2012-07-04 15:14:04 +0800980 self.event_log = EventLog('goofy')
981
982 if (not suppress_chroot_warning and
983 factory.in_chroot() and
984 self.options.ui == 'gtk' and
985 os.environ.get('DISPLAY') in [None, '', ':0', ':0.0']):
986 # That's not going to work! Tell the user how to run
987 # this way.
988 logging.warn(GOOFY_IN_CHROOT_WARNING)
989 time.sleep(1)
990
991 if env:
992 self.env = env
993 elif factory.in_chroot():
994 self.env = test_environment.FakeChrootEnvironment()
995 logging.warn(
996 'Using chroot environment: will not actually run autotests')
997 else:
998 self.env = test_environment.DUTEnvironment()
999 self.env.goofy = self
1000
1001 if self.options.restart:
1002 state.clear_state()
1003
1004 if self.options.print_test_list:
Jon Salzeb42f0d2012-07-27 19:14:04 +08001005 print factory.read_test_list(
1006 self.options.print_test_list).__repr__(recursive=True)
Jon Salz0697cbf2012-07-04 15:14:04 +08001007 return
1008
1009 if self.options.ui_scale_factor != 1 and utils.in_qemu():
1010 logging.warn(
1011 'In QEMU; ignoring ui_scale_factor argument')
1012 self.options.ui_scale_factor = 1
1013
1014 logging.info('Started')
1015
1016 self.start_state_server()
1017 self.state_instance.set_shared_data('hwid_cfg', get_hwid_cfg())
1018 self.state_instance.set_shared_data('ui_scale_factor',
1019 self.options.ui_scale_factor)
1020 self.last_shutdown_time = (
1021 self.state_instance.get_shared_data('shutdown_time', optional=True))
1022 self.state_instance.del_shared_data('shutdown_time', optional=True)
1023
1024 if not self.options.test_list:
1025 self.options.test_list = find_test_list()
1026 if not self.options.test_list:
1027 logging.error('No test list. Aborting.')
1028 sys.exit(1)
1029 logging.info('Using test list %s', self.options.test_list)
1030
1031 self.test_list = factory.read_test_list(
1032 self.options.test_list,
Jon Salzeb42f0d2012-07-27 19:14:04 +08001033 self.state_instance)
Jon Salz0697cbf2012-07-04 15:14:04 +08001034 if not self.state_instance.has_shared_data('ui_lang'):
1035 self.state_instance.set_shared_data('ui_lang',
1036 self.test_list.options.ui_lang)
1037 self.state_instance.set_shared_data(
1038 'test_list_options',
1039 self.test_list.options.__dict__)
1040 self.state_instance.test_list = self.test_list
1041
Jon Salz23926422012-09-01 03:38:13 +08001042 if self.options.dummy_shopfloor:
1043 os.environ[shopfloor.SHOPFLOOR_SERVER_ENV_VAR_NAME] = (
1044 'http://localhost:%d/' % shopfloor.DEFAULT_SERVER_PORT)
1045 self.dummy_shopfloor = Spawn(
1046 [os.path.join(factory.FACTORY_PATH, 'bin', 'shopfloor_server'),
1047 '--dummy'])
1048 elif self.test_list.options.shopfloor_server_url:
1049 shopfloor.set_server_url(self.test_list.options.shopfloor_server_url)
1050
Jon Salz8fa8e832012-07-13 19:04:09 +08001051 if self.test_list.options.time_sanitizer:
1052 self.time_sanitizer = time_sanitizer.TimeSanitizer(
1053 base_time=time_sanitizer.GetBaseTimeFromFile(
1054 # lsb-factory is written by the factory install shim during
1055 # installation, so it should have a good time obtained from
Jon Salz54882d02012-08-31 01:57:54 +08001056 # the mini-Omaha server. If it's not available, we'll use
1057 # /etc/lsb-factory (which will be much older, but reasonably
1058 # sane) and rely on a shopfloor sync to set a more accurate
1059 # time.
1060 '/usr/local/etc/lsb-factory',
1061 '/etc/lsb-release'))
Jon Salz8fa8e832012-07-13 19:04:09 +08001062 self.time_sanitizer.RunOnce()
1063
Jon Salz0697cbf2012-07-04 15:14:04 +08001064 self.init_states()
1065 self.start_event_server()
1066 self.connection_manager = self.env.create_connection_manager(
Tai-Hsu Lin371351a2012-08-27 14:17:14 +08001067 self.test_list.options.wlans,
1068 self.test_list.options.scan_wifi_period_secs)
Jon Salz0697cbf2012-07-04 15:14:04 +08001069 # Note that we create a log watcher even if
1070 # sync_event_log_period_secs isn't set (no background
1071 # syncing), since we may use it to flush event logs as well.
1072 self.log_watcher = EventLogWatcher(
1073 self.test_list.options.sync_event_log_period_secs,
Jon Salz16d10542012-07-23 12:18:45 +08001074 handle_event_logs_callback=self.handle_event_logs)
Jon Salz0697cbf2012-07-04 15:14:04 +08001075 if self.test_list.options.sync_event_log_period_secs:
1076 self.log_watcher.StartWatchThread()
1077
1078 self.update_system_info()
1079
Vic Yang4953fc12012-07-26 16:19:53 +08001080 assert ((self.test_list.options.min_charge_pct is None) ==
1081 (self.test_list.options.max_charge_pct is None))
1082 if (self.test_list.options.min_charge_pct and
1083 self.test_list.options.max_charge_pct):
1084 self.charge_manager = ChargeManager(self.test_list.options.min_charge_pct,
1085 self.test_list.options.max_charge_pct)
1086
Jon Salz0697cbf2012-07-04 15:14:04 +08001087 os.environ['CROS_FACTORY'] = '1'
1088 os.environ['CROS_DISABLE_SITE_SYSINFO'] = '1'
1089
1090 # Set CROS_UI since some behaviors in ui.py depend on the
1091 # particular UI in use. TODO(jsalz): Remove this (and all
1092 # places it is used) when the GTK UI is removed.
1093 os.environ['CROS_UI'] = self.options.ui
1094
1095 if self.options.ui == 'chrome':
1096 self.env.launch_chrome()
1097 logging.info('Waiting for a web socket connection')
1098 self.web_socket_manager.wait()
1099
1100 # Wait for the test widget size to be set; this is done in
1101 # an asynchronous RPC so there is a small chance that the
1102 # web socket might be opened first.
1103 for _ in range(100): # 10 s
1104 try:
1105 if self.state_instance.get_shared_data('test_widget_size'):
1106 break
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001107 except KeyError:
Jon Salz0697cbf2012-07-04 15:14:04 +08001108 pass # Retry
1109 time.sleep(0.1) # 100 ms
1110 else:
1111 logging.warn('Never received test_widget_size from UI')
1112 elif self.options.ui == 'gtk':
1113 self.start_ui()
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001114
Jon Salz0697cbf2012-07-04 15:14:04 +08001115 def state_change_callback(test, test_state):
1116 self.event_client.post_event(
1117 Event(Event.Type.STATE_CHANGE,
1118 path=test.path, state=test_state))
1119 self.test_list.state_change_callback = state_change_callback
Jon Salz73e0fd02012-04-04 11:46:38 +08001120
Jon Salza6711d72012-07-18 14:33:03 +08001121 for handler in self.on_ui_startup:
1122 handler()
1123
1124 self.prespawner = Prespawner()
1125 self.prespawner.start()
1126
Jon Salz0697cbf2012-07-04 15:14:04 +08001127 try:
1128 tests_after_shutdown = self.state_instance.get_shared_data(
1129 'tests_after_shutdown')
1130 except KeyError:
1131 tests_after_shutdown = None
Jon Salz57717ca2012-04-04 16:47:25 +08001132
Jon Salz5c344f62012-07-13 14:31:16 +08001133 force_auto_run = (tests_after_shutdown == FORCE_AUTO_RUN)
1134 if not force_auto_run and tests_after_shutdown is not None:
Jon Salz0697cbf2012-07-04 15:14:04 +08001135 logging.info('Resuming tests after shutdown: %s',
1136 tests_after_shutdown)
Jon Salz0697cbf2012-07-04 15:14:04 +08001137 self.tests_to_run.extend(
1138 self.test_list.lookup_path(t) for t in tests_after_shutdown)
1139 self.run_queue.put(self.run_next_test)
1140 else:
Jon Salz5c344f62012-07-13 14:31:16 +08001141 if force_auto_run or self.test_list.options.auto_run_on_start:
Jon Salz0697cbf2012-07-04 15:14:04 +08001142 self.run_queue.put(
1143 lambda: self.run_tests(self.test_list, untested_only=True))
Jon Salz5c344f62012-07-13 14:31:16 +08001144 self.state_instance.set_shared_data('tests_after_shutdown', None)
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001145
Jon Salz0697cbf2012-07-04 15:14:04 +08001146 def run(self):
1147 '''Runs Goofy.'''
1148 # Process events forever.
1149 while self.run_once(True):
1150 pass
Jon Salz73e0fd02012-04-04 11:46:38 +08001151
Jon Salz0697cbf2012-07-04 15:14:04 +08001152 def run_once(self, block=False):
1153 '''Runs all items pending in the event loop.
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001154
Jon Salz0697cbf2012-07-04 15:14:04 +08001155 Args:
1156 block: If true, block until at least one event is processed.
Jon Salz7c15e8b2012-06-19 17:10:37 +08001157
Jon Salz0697cbf2012-07-04 15:14:04 +08001158 Returns:
1159 True to keep going or False to shut down.
1160 '''
1161 events = utils.DrainQueue(self.run_queue)
cychiang21886742012-07-05 15:16:32 +08001162 while not events:
Jon Salz0697cbf2012-07-04 15:14:04 +08001163 # Nothing on the run queue.
1164 self._run_queue_idle()
1165 if block:
1166 # Block for at least one event...
cychiang21886742012-07-05 15:16:32 +08001167 try:
1168 events.append(self.run_queue.get(timeout=RUN_QUEUE_TIMEOUT_SECS))
1169 except Queue.Empty:
1170 # Keep going (calling _run_queue_idle() again at the top of
1171 # the loop)
1172 continue
Jon Salz0697cbf2012-07-04 15:14:04 +08001173 # ...and grab anything else that showed up at the same
1174 # time.
1175 events.extend(utils.DrainQueue(self.run_queue))
cychiang21886742012-07-05 15:16:32 +08001176 else:
1177 break
Jon Salz51528e12012-07-02 18:54:45 +08001178
Jon Salz0697cbf2012-07-04 15:14:04 +08001179 for event in events:
1180 if not event:
1181 # Shutdown request.
1182 self.run_queue.task_done()
1183 return False
Jon Salz51528e12012-07-02 18:54:45 +08001184
Jon Salz0697cbf2012-07-04 15:14:04 +08001185 try:
1186 event()
Jon Salz85a39882012-07-05 16:45:04 +08001187 except: # pylint: disable=W0702
1188 logging.exception('Error in event loop')
Jon Salz0697cbf2012-07-04 15:14:04 +08001189 self.record_exception(traceback.format_exception_only(
1190 *sys.exc_info()[:2]))
1191 # But keep going
1192 finally:
1193 self.run_queue.task_done()
1194 return True
Jon Salz0405ab52012-03-16 15:26:52 +08001195
Jon Salz54882d02012-08-31 01:57:54 +08001196 def _should_sync_time(self):
1197 '''Returns True if we should attempt syncing time with shopfloor.'''
1198 return (self.test_list.options.sync_time_period_secs and
1199 self.time_sanitizer and
1200 (not self.time_synced) and
1201 (not factory.in_chroot()))
1202
1203 def sync_time_with_shopfloor_server(self):
1204 '''Syncs time with shopfloor server, if not yet synced.
1205
1206 Returns:
1207 False if no time sanitizer is available, or True if this sync (or a
1208 previous sync) succeeded.
1209
1210 Raises:
1211 Exception if unable to contact the shopfloor server.
1212 '''
1213 if self._should_sync_time():
1214 self.time_sanitizer.SyncWithShopfloor()
1215 self.time_synced = True
1216 return self.time_synced
1217
Jon Salzb92c5112012-09-21 15:40:11 +08001218 def log_disk_space_stats(self):
1219 if not self.test_list.options.log_disk_space_period_secs:
1220 return
1221
1222 now = time.time()
1223 if (self.last_log_disk_space_time and
1224 now - self.last_log_disk_space_time <
1225 self.test_list.options.log_disk_space_period_secs):
1226 return
1227 self.last_log_disk_space_time = now
1228
1229 try:
1230 logging.info(disk_space.FormatSpaceUsedAll())
1231 except: # pylint: disable=W0702
1232 logging.exception('Unable to get disk space used')
1233
Jon Salz8fa8e832012-07-13 19:04:09 +08001234 def sync_time_in_background(self):
Jon Salzb22d1172012-08-06 10:38:57 +08001235 '''Writes out current time and tries to sync with shopfloor server.'''
1236 if not self.time_sanitizer:
1237 return
1238
1239 # Write out the current time.
1240 self.time_sanitizer.SaveTime()
1241
Jon Salz54882d02012-08-31 01:57:54 +08001242 if not self._should_sync_time():
Jon Salz8fa8e832012-07-13 19:04:09 +08001243 return
1244
1245 now = time.time()
1246 if self.last_sync_time and (
1247 now - self.last_sync_time <
1248 self.test_list.options.sync_time_period_secs):
1249 # Not yet time for another check.
1250 return
1251 self.last_sync_time = now
1252
1253 def target():
1254 try:
Jon Salz54882d02012-08-31 01:57:54 +08001255 self.sync_time_with_shopfloor_server()
Jon Salz8fa8e832012-07-13 19:04:09 +08001256 except: # pylint: disable=W0702
1257 # Oh well. Log an error (but no trace)
1258 logging.info(
1259 'Unable to get time from shopfloor server: %s',
1260 utils.FormatExceptionOnly())
1261
1262 thread = threading.Thread(target=target)
1263 thread.daemon = True
1264 thread.start()
1265
Jon Salz0697cbf2012-07-04 15:14:04 +08001266 def _run_queue_idle(self):
Vic Yang4953fc12012-07-26 16:19:53 +08001267 '''Invoked when the run queue has no events.
1268
1269 This method must not raise exception.
1270 '''
Jon Salzb22d1172012-08-06 10:38:57 +08001271 now = time.time()
1272 if (self.last_idle and
1273 now < (self.last_idle + RUN_QUEUE_TIMEOUT_SECS - 1)):
1274 # Don't run more often than once every (RUN_QUEUE_TIMEOUT_SECS -
1275 # 1) seconds.
1276 return
1277
1278 self.last_idle = now
1279
Vic Yang311ddb82012-09-26 12:08:28 +08001280 self.check_exclusive()
cychiang21886742012-07-05 15:16:32 +08001281 self.check_for_updates()
Jon Salz8fa8e832012-07-13 19:04:09 +08001282 self.sync_time_in_background()
Jon Salzb92c5112012-09-21 15:40:11 +08001283 self.log_disk_space_stats()
Jon Salz57717ca2012-04-04 16:47:25 +08001284
Jon Salz16d10542012-07-23 12:18:45 +08001285 def handle_event_logs(self, log_name, chunk):
Jon Salz0697cbf2012-07-04 15:14:04 +08001286 '''Callback for event watcher.
Jon Salz258a40c2012-04-19 12:34:01 +08001287
Jon Salz0697cbf2012-07-04 15:14:04 +08001288 Attempts to upload the event logs to the shopfloor server.
1289 '''
1290 description = 'event logs (%s, %d bytes)' % (log_name, len(chunk))
1291 start_time = time.time()
Jon Salz0697cbf2012-07-04 15:14:04 +08001292 shopfloor_client = shopfloor.get_instance(
1293 detect=True,
1294 timeout=self.test_list.options.shopfloor_timeout_secs)
Jon Salzb10cf512012-08-09 17:29:21 +08001295 shopfloor_client.UploadEvent(log_name, Binary(chunk))
Jon Salz0697cbf2012-07-04 15:14:04 +08001296 logging.info(
1297 'Successfully synced %s in %.03f s',
1298 description, time.time() - start_time)
Jon Salz57717ca2012-04-04 16:47:25 +08001299
Jon Salz0697cbf2012-07-04 15:14:04 +08001300 def run_tests_with_status(self, statuses_to_run, starting_at=None,
1301 root=None):
1302 '''Runs all top-level tests with a particular status.
Jon Salz0405ab52012-03-16 15:26:52 +08001303
Jon Salz0697cbf2012-07-04 15:14:04 +08001304 All active tests, plus any tests to re-run, are reset.
Jon Salz57717ca2012-04-04 16:47:25 +08001305
Jon Salz0697cbf2012-07-04 15:14:04 +08001306 Args:
1307 starting_at: If provided, only auto-runs tests beginning with
1308 this test.
1309 '''
1310 root = root or self.test_list
Jon Salz57717ca2012-04-04 16:47:25 +08001311
Jon Salz0697cbf2012-07-04 15:14:04 +08001312 if starting_at:
1313 # Make sure they passed a test, not a string.
1314 assert isinstance(starting_at, factory.FactoryTest)
Jon Salz0405ab52012-03-16 15:26:52 +08001315
Jon Salz0697cbf2012-07-04 15:14:04 +08001316 tests_to_reset = []
1317 tests_to_run = []
Jon Salz0405ab52012-03-16 15:26:52 +08001318
Jon Salz0697cbf2012-07-04 15:14:04 +08001319 found_starting_at = False
Jon Salz0405ab52012-03-16 15:26:52 +08001320
Jon Salz0697cbf2012-07-04 15:14:04 +08001321 for test in root.get_top_level_tests():
1322 if starting_at:
1323 if test == starting_at:
1324 # We've found starting_at; do auto-run on all
1325 # subsequent tests.
1326 found_starting_at = True
1327 if not found_starting_at:
1328 # Don't start this guy yet
1329 continue
Jon Salz0405ab52012-03-16 15:26:52 +08001330
Jon Salz0697cbf2012-07-04 15:14:04 +08001331 status = test.get_state().status
1332 if status == TestState.ACTIVE or status in statuses_to_run:
1333 # Reset the test (later; we will need to abort
1334 # all active tests first).
1335 tests_to_reset.append(test)
1336 if status in statuses_to_run:
1337 tests_to_run.append(test)
Jon Salz0405ab52012-03-16 15:26:52 +08001338
Jon Salz0697cbf2012-07-04 15:14:04 +08001339 self.abort_active_tests()
Jon Salz258a40c2012-04-19 12:34:01 +08001340
Jon Salz0697cbf2012-07-04 15:14:04 +08001341 # Reset all statuses of the tests to run (in case any tests were active;
1342 # we want them to be run again).
1343 for test_to_reset in tests_to_reset:
1344 for test in test_to_reset.walk():
1345 test.update_state(status=TestState.UNTESTED)
Jon Salz57717ca2012-04-04 16:47:25 +08001346
Jon Salz0697cbf2012-07-04 15:14:04 +08001347 self.run_tests(tests_to_run, untested_only=True)
Jon Salz0405ab52012-03-16 15:26:52 +08001348
Jon Salz0697cbf2012-07-04 15:14:04 +08001349 def restart_tests(self, root=None):
1350 '''Restarts all tests.'''
1351 root = root or self.test_list
Jon Salz0405ab52012-03-16 15:26:52 +08001352
Jon Salz0697cbf2012-07-04 15:14:04 +08001353 self.abort_active_tests()
1354 for test in root.walk():
1355 test.update_state(status=TestState.UNTESTED)
1356 self.run_tests(root)
Hung-Te Lin96632362012-03-20 21:14:18 +08001357
Jon Salz0697cbf2012-07-04 15:14:04 +08001358 def auto_run(self, starting_at=None, root=None):
1359 '''"Auto-runs" tests that have not been run yet.
Hung-Te Lin96632362012-03-20 21:14:18 +08001360
Jon Salz0697cbf2012-07-04 15:14:04 +08001361 Args:
1362 starting_at: If provide, only auto-runs tests beginning with
1363 this test.
1364 '''
1365 root = root or self.test_list
1366 self.run_tests_with_status([TestState.UNTESTED, TestState.ACTIVE],
1367 starting_at=starting_at,
1368 root=root)
Jon Salz968e90b2012-03-18 16:12:43 +08001369
Jon Salz0697cbf2012-07-04 15:14:04 +08001370 def re_run_failed(self, root=None):
1371 '''Re-runs failed tests.'''
1372 root = root or self.test_list
1373 self.run_tests_with_status([TestState.FAILED], root=root)
Jon Salz57717ca2012-04-04 16:47:25 +08001374
Jon Salz0697cbf2012-07-04 15:14:04 +08001375 def show_review_information(self):
1376 '''Event handler for showing review information screen.
Jon Salz57717ca2012-04-04 16:47:25 +08001377
Jon Salz0697cbf2012-07-04 15:14:04 +08001378 The information screene is rendered by main UI program (ui.py), so in
1379 goofy we only need to kill all active tests, set them as untested, and
1380 clear remaining tests.
1381 '''
1382 self.kill_active_tests(False)
Jon Salza6711d72012-07-18 14:33:03 +08001383 self.cancel_pending_tests()
Jon Salz57717ca2012-04-04 16:47:25 +08001384
Jon Salz0697cbf2012-07-04 15:14:04 +08001385 def handle_switch_test(self, event):
1386 '''Switches to a particular test.
Jon Salz0405ab52012-03-16 15:26:52 +08001387
Jon Salz0697cbf2012-07-04 15:14:04 +08001388 @param event: The SWITCH_TEST event.
1389 '''
1390 test = self.test_list.lookup_path(event.path)
1391 if not test:
1392 logging.error('Unknown test %r', event.key)
1393 return
Jon Salz73e0fd02012-04-04 11:46:38 +08001394
Jon Salz0697cbf2012-07-04 15:14:04 +08001395 invoc = self.invocations.get(test)
1396 if invoc and test.backgroundable:
1397 # Already running: just bring to the front if it
1398 # has a UI.
1399 logging.info('Setting visible test to %s', test.path)
Jon Salz36fbbb52012-07-05 13:45:06 +08001400 self.set_visible_test(test)
Jon Salz0697cbf2012-07-04 15:14:04 +08001401 return
Jon Salz73e0fd02012-04-04 11:46:38 +08001402
Jon Salz0697cbf2012-07-04 15:14:04 +08001403 self.abort_active_tests()
1404 for t in test.walk():
1405 t.update_state(status=TestState.UNTESTED)
Jon Salz73e0fd02012-04-04 11:46:38 +08001406
Jon Salz0697cbf2012-07-04 15:14:04 +08001407 if self.test_list.options.auto_run_on_keypress:
1408 self.auto_run(starting_at=test)
1409 else:
1410 self.run_tests(test)
Jon Salz73e0fd02012-04-04 11:46:38 +08001411
Jon Salz0697cbf2012-07-04 15:14:04 +08001412 def wait(self):
1413 '''Waits for all pending invocations.
1414
1415 Useful for testing.
1416 '''
Jon Salz1acc8742012-07-17 17:45:55 +08001417 while self.invocations:
1418 for k, v in self.invocations.iteritems():
1419 logging.info('Waiting for %s to complete...', k)
1420 v.thread.join()
1421 self.reap_completed_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +08001422
1423 def check_exceptions(self):
1424 '''Raises an error if any exceptions have occurred in
1425 invocation threads.'''
1426 if self.exceptions:
1427 raise RuntimeError('Exception in invocation thread: %r' %
1428 self.exceptions)
1429
1430 def record_exception(self, msg):
1431 '''Records an exception in an invocation thread.
1432
1433 An exception with the given message will be rethrown when
1434 Goofy is destroyed.'''
1435 self.exceptions.append(msg)
Jon Salz73e0fd02012-04-04 11:46:38 +08001436
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001437
1438if __name__ == '__main__':
Jon Salz77c151e2012-08-28 07:20:37 +08001439 goofy = Goofy()
1440 try:
1441 goofy.main()
Jon Salz31373eb2012-09-21 16:19:49 +08001442 except:
1443 # Log the error before trying to shut down.
1444 logging.exception('Error in main loop')
1445 raise
Jon Salz77c151e2012-08-28 07:20:37 +08001446 finally:
1447 goofy.destroy()