blob: d50d56dcc2aab6e6a14e50d10abd2adbdf8e1c9f [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
Vic Yang3e1cf5d2013-06-05 18:50:24 +08001191 if system.SystemInfo().firmware_version is None and not utils.in_chroot():
Vic Yang9bd4f772013-06-04 17:34:00 +08001192 self.state_instance.set_shared_data('startup_error',
1193 'Netboot firmware detected\n'
1194 'Connect Ethernet and reboot to re-image.\n'
1195 u'侦测到网路开机固件\n'
1196 u'请连接乙太网并重启')
1197
Jon Salz0697cbf2012-07-04 15:14:04 +08001198 if not self.state_instance.has_shared_data('ui_lang'):
1199 self.state_instance.set_shared_data('ui_lang',
1200 self.test_list.options.ui_lang)
1201 self.state_instance.set_shared_data(
1202 'test_list_options',
1203 self.test_list.options.__dict__)
1204 self.state_instance.test_list = self.test_list
1205
Jon Salz83ef34b2012-11-01 19:46:35 +08001206 if not utils.in_chroot() and self.test_list.options.disable_log_rotation:
1207 open('/var/lib/cleanup_logs_paused', 'w').close()
1208
Jon Salz23926422012-09-01 03:38:13 +08001209 if self.options.dummy_shopfloor:
1210 os.environ[shopfloor.SHOPFLOOR_SERVER_ENV_VAR_NAME] = (
1211 'http://localhost:%d/' % shopfloor.DEFAULT_SERVER_PORT)
1212 self.dummy_shopfloor = Spawn(
1213 [os.path.join(factory.FACTORY_PATH, 'bin', 'shopfloor_server'),
1214 '--dummy'])
1215 elif self.test_list.options.shopfloor_server_url:
1216 shopfloor.set_server_url(self.test_list.options.shopfloor_server_url)
Jon Salz2bf2f6b2013-03-28 18:49:26 +08001217 shopfloor.set_enabled(True)
Jon Salz23926422012-09-01 03:38:13 +08001218
Jon Salz0f996602012-10-03 15:26:48 +08001219 if self.test_list.options.time_sanitizer and not utils.in_chroot():
Jon Salz8fa8e832012-07-13 19:04:09 +08001220 self.time_sanitizer = time_sanitizer.TimeSanitizer(
1221 base_time=time_sanitizer.GetBaseTimeFromFile(
1222 # lsb-factory is written by the factory install shim during
1223 # installation, so it should have a good time obtained from
Jon Salz54882d02012-08-31 01:57:54 +08001224 # the mini-Omaha server. If it's not available, we'll use
1225 # /etc/lsb-factory (which will be much older, but reasonably
1226 # sane) and rely on a shopfloor sync to set a more accurate
1227 # time.
1228 '/usr/local/etc/lsb-factory',
1229 '/etc/lsb-release'))
Jon Salz8fa8e832012-07-13 19:04:09 +08001230 self.time_sanitizer.RunOnce()
1231
Jon Salz0697cbf2012-07-04 15:14:04 +08001232 self.init_states()
1233 self.start_event_server()
1234 self.connection_manager = self.env.create_connection_manager(
Tai-Hsu Lin371351a2012-08-27 14:17:14 +08001235 self.test_list.options.wlans,
1236 self.test_list.options.scan_wifi_period_secs)
Jon Salz0697cbf2012-07-04 15:14:04 +08001237 # Note that we create a log watcher even if
1238 # sync_event_log_period_secs isn't set (no background
1239 # syncing), since we may use it to flush event logs as well.
1240 self.log_watcher = EventLogWatcher(
1241 self.test_list.options.sync_event_log_period_secs,
Jon Salzd15bbcf2013-05-21 17:33:57 +08001242 event_log_db_file=None,
Jon Salz16d10542012-07-23 12:18:45 +08001243 handle_event_logs_callback=self.handle_event_logs)
Jon Salz0697cbf2012-07-04 15:14:04 +08001244 if self.test_list.options.sync_event_log_period_secs:
1245 self.log_watcher.StartWatchThread()
1246
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +08001247 # Note that we create a system log manager even if
1248 # sync_log_period_secs isn't set (no background
1249 # syncing), since we may kick it to sync logs in its
1250 # thread.
1251 self.system_log_manager = SystemLogManager(
Cheng-Yi Chiang835f2682013-05-06 22:15:48 +08001252 sync_log_paths=self.test_list.options.sync_log_paths,
1253 sync_period_sec=self.test_list.options.sync_log_period_secs,
1254 clear_log_paths=self.test_list.options.clear_log_paths)
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +08001255 self.system_log_manager.StartSyncThread()
1256
Jon Salz0697cbf2012-07-04 15:14:04 +08001257 self.update_system_info()
1258
Vic Yang4953fc12012-07-26 16:19:53 +08001259 assert ((self.test_list.options.min_charge_pct is None) ==
1260 (self.test_list.options.max_charge_pct is None))
Vic Yange83d9a12013-04-19 20:00:20 +08001261 if utils.in_chroot():
1262 logging.info('In chroot, ignoring charge manager and charge state')
1263 elif self.test_list.options.min_charge_pct is not None:
Vic Yang4953fc12012-07-26 16:19:53 +08001264 self.charge_manager = ChargeManager(self.test_list.options.min_charge_pct,
1265 self.test_list.options.max_charge_pct)
Jon Salzad7353b2012-10-15 16:22:46 +08001266 system.SystemStatus.charge_manager = self.charge_manager
Cheng-Yi Chiangd8186952013-04-04 23:41:14 +08001267 else:
1268 # Goofy should set charger state to charge if charge_manager is disabled.
1269 try:
1270 system.GetBoard().SetChargeState(Board.ChargeState.CHARGE)
1271 except BoardException:
1272 logging.exception('Unable to set charge state on this board')
Vic Yang4953fc12012-07-26 16:19:53 +08001273
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001274 self.core_dump_manager = CoreDumpManager(
1275 self.test_list.options.core_dump_watchlist)
1276
Jon Salz0697cbf2012-07-04 15:14:04 +08001277 os.environ['CROS_FACTORY'] = '1'
1278 os.environ['CROS_DISABLE_SITE_SYSINFO'] = '1'
1279
1280 # Set CROS_UI since some behaviors in ui.py depend on the
1281 # particular UI in use. TODO(jsalz): Remove this (and all
1282 # places it is used) when the GTK UI is removed.
1283 os.environ['CROS_UI'] = self.options.ui
1284
Jon Salz416f9cc2013-05-10 18:32:50 +08001285 # Initialize hooks.
1286 module, cls = self.test_list.options.hooks_class.rsplit('.', 1)
1287 self.hooks = getattr(__import__(module, fromlist=[cls]), cls)()
1288 assert isinstance(self.hooks, factory.Hooks), (
1289 "hooks should be of type Hooks but is %r" % type(self.hooks))
1290 self.hooks.test_list = self.test_list
1291
1292 # Call startup hook.
1293 self.hooks.OnStartup()
1294
Jon Salz0697cbf2012-07-04 15:14:04 +08001295 if self.options.ui == 'chrome':
1296 self.env.launch_chrome()
1297 logging.info('Waiting for a web socket connection')
Cheng-Yi Chiangfd8ed392013-03-08 21:37:31 +08001298 self.web_socket_manager.wait()
Jon Salz0697cbf2012-07-04 15:14:04 +08001299
1300 # Wait for the test widget size to be set; this is done in
1301 # an asynchronous RPC so there is a small chance that the
1302 # web socket might be opened first.
1303 for _ in range(100): # 10 s
1304 try:
1305 if self.state_instance.get_shared_data('test_widget_size'):
1306 break
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001307 except KeyError:
Jon Salz0697cbf2012-07-04 15:14:04 +08001308 pass # Retry
1309 time.sleep(0.1) # 100 ms
1310 else:
1311 logging.warn('Never received test_widget_size from UI')
Jon Salz45297282013-05-18 14:31:47 +08001312
1313 # Send Chrome a Tab to get focus to the factory UI
1314 # (http://crosbug.com/p/19444). TODO(jsalz): remove this hack
1315 # and figure out the right way to get the focus to Chrome.
1316 if not utils.in_chroot():
1317 Spawn(
1318 [os.path.join(factory.FACTORY_PATH, 'bin', 'send_key'), 'Tab'],
1319 check_call=True, log=True)
Jon Salz0697cbf2012-07-04 15:14:04 +08001320 elif self.options.ui == 'gtk':
1321 self.start_ui()
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001322
Ricky Liang650f6bf2012-09-28 13:22:54 +08001323 # Create download path for autotest beforehand or autotests run at
1324 # the same time might fail due to race condition.
1325 if not factory.in_chroot():
1326 utils.TryMakeDirs(os.path.join('/usr/local/autotest', 'tests',
1327 'download'))
1328
Jon Salz0697cbf2012-07-04 15:14:04 +08001329 def state_change_callback(test, test_state):
1330 self.event_client.post_event(
1331 Event(Event.Type.STATE_CHANGE,
1332 path=test.path, state=test_state))
1333 self.test_list.state_change_callback = state_change_callback
Jon Salz73e0fd02012-04-04 11:46:38 +08001334
Jon Salza6711d72012-07-18 14:33:03 +08001335 for handler in self.on_ui_startup:
1336 handler()
1337
1338 self.prespawner = Prespawner()
1339 self.prespawner.start()
1340
Jon Salz0697cbf2012-07-04 15:14:04 +08001341 try:
1342 tests_after_shutdown = self.state_instance.get_shared_data(
1343 'tests_after_shutdown')
1344 except KeyError:
1345 tests_after_shutdown = None
Jon Salz57717ca2012-04-04 16:47:25 +08001346
Jon Salz5c344f62012-07-13 14:31:16 +08001347 force_auto_run = (tests_after_shutdown == FORCE_AUTO_RUN)
1348 if not force_auto_run and tests_after_shutdown is not None:
Jon Salz0697cbf2012-07-04 15:14:04 +08001349 logging.info('Resuming tests after shutdown: %s',
1350 tests_after_shutdown)
Jon Salz0697cbf2012-07-04 15:14:04 +08001351 self.tests_to_run.extend(
1352 self.test_list.lookup_path(t) for t in tests_after_shutdown)
1353 self.run_queue.put(self.run_next_test)
1354 else:
Jon Salz5c344f62012-07-13 14:31:16 +08001355 if force_auto_run or self.test_list.options.auto_run_on_start:
Jon Salz0697cbf2012-07-04 15:14:04 +08001356 self.run_queue.put(
1357 lambda: self.run_tests(self.test_list, untested_only=True))
Jon Salz5c344f62012-07-13 14:31:16 +08001358 self.state_instance.set_shared_data('tests_after_shutdown', None)
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001359
Dean Liao592e4d52013-01-10 20:06:39 +08001360 self.may_disable_cros_shortcut_keys()
1361
1362 def may_disable_cros_shortcut_keys(self):
1363 test_options = self.test_list.options
1364 if test_options.disable_cros_shortcut_keys:
1365 logging.info('Filter ChromeOS shortcut keys.')
1366 self.key_filter = KeyFilter(
1367 unmap_caps_lock=test_options.disable_caps_lock,
1368 caps_lock_keycode=test_options.caps_lock_keycode)
1369 self.key_filter.Start()
1370
Jon Salz0697cbf2012-07-04 15:14:04 +08001371 def run(self):
1372 '''Runs Goofy.'''
1373 # Process events forever.
1374 while self.run_once(True):
1375 pass
Jon Salz73e0fd02012-04-04 11:46:38 +08001376
Jon Salz0697cbf2012-07-04 15:14:04 +08001377 def run_once(self, block=False):
1378 '''Runs all items pending in the event loop.
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001379
Jon Salz0697cbf2012-07-04 15:14:04 +08001380 Args:
1381 block: If true, block until at least one event is processed.
Jon Salz7c15e8b2012-06-19 17:10:37 +08001382
Jon Salz0697cbf2012-07-04 15:14:04 +08001383 Returns:
1384 True to keep going or False to shut down.
1385 '''
1386 events = utils.DrainQueue(self.run_queue)
cychiang21886742012-07-05 15:16:32 +08001387 while not events:
Jon Salz0697cbf2012-07-04 15:14:04 +08001388 # Nothing on the run queue.
1389 self._run_queue_idle()
1390 if block:
1391 # Block for at least one event...
cychiang21886742012-07-05 15:16:32 +08001392 try:
1393 events.append(self.run_queue.get(timeout=RUN_QUEUE_TIMEOUT_SECS))
1394 except Queue.Empty:
1395 # Keep going (calling _run_queue_idle() again at the top of
1396 # the loop)
1397 continue
Jon Salz0697cbf2012-07-04 15:14:04 +08001398 # ...and grab anything else that showed up at the same
1399 # time.
1400 events.extend(utils.DrainQueue(self.run_queue))
cychiang21886742012-07-05 15:16:32 +08001401 else:
1402 break
Jon Salz51528e12012-07-02 18:54:45 +08001403
Jon Salz0697cbf2012-07-04 15:14:04 +08001404 for event in events:
1405 if not event:
1406 # Shutdown request.
1407 self.run_queue.task_done()
1408 return False
Jon Salz51528e12012-07-02 18:54:45 +08001409
Jon Salz0697cbf2012-07-04 15:14:04 +08001410 try:
1411 event()
Jon Salz85a39882012-07-05 16:45:04 +08001412 except: # pylint: disable=W0702
1413 logging.exception('Error in event loop')
Jon Salz0697cbf2012-07-04 15:14:04 +08001414 self.record_exception(traceback.format_exception_only(
1415 *sys.exc_info()[:2]))
1416 # But keep going
1417 finally:
1418 self.run_queue.task_done()
1419 return True
Jon Salz0405ab52012-03-16 15:26:52 +08001420
Jon Salz0e6532d2012-10-25 16:30:11 +08001421 def _should_sync_time(self, foreground=False):
1422 '''Returns True if we should attempt syncing time with shopfloor.
1423
1424 Args:
1425 foreground: If True, synchronizes even if background syncing
1426 is disabled (e.g., in explicit sync requests from the
1427 SyncShopfloor test).
1428 '''
1429 return ((foreground or
1430 self.test_list.options.sync_time_period_secs) and
Jon Salz54882d02012-08-31 01:57:54 +08001431 self.time_sanitizer and
1432 (not self.time_synced) and
1433 (not factory.in_chroot()))
1434
Jon Salz0e6532d2012-10-25 16:30:11 +08001435 def sync_time_with_shopfloor_server(self, foreground=False):
Jon Salz54882d02012-08-31 01:57:54 +08001436 '''Syncs time with shopfloor server, if not yet synced.
1437
Jon Salz0e6532d2012-10-25 16:30:11 +08001438 Args:
1439 foreground: If True, synchronizes even if background syncing
1440 is disabled (e.g., in explicit sync requests from the
1441 SyncShopfloor test).
1442
Jon Salz54882d02012-08-31 01:57:54 +08001443 Returns:
1444 False if no time sanitizer is available, or True if this sync (or a
1445 previous sync) succeeded.
1446
1447 Raises:
1448 Exception if unable to contact the shopfloor server.
1449 '''
Jon Salz0e6532d2012-10-25 16:30:11 +08001450 if self._should_sync_time(foreground):
Jon Salz54882d02012-08-31 01:57:54 +08001451 self.time_sanitizer.SyncWithShopfloor()
1452 self.time_synced = True
1453 return self.time_synced
1454
Jon Salzb92c5112012-09-21 15:40:11 +08001455 def log_disk_space_stats(self):
1456 if not self.test_list.options.log_disk_space_period_secs:
1457 return
1458
1459 now = time.time()
1460 if (self.last_log_disk_space_time and
1461 now - self.last_log_disk_space_time <
1462 self.test_list.options.log_disk_space_period_secs):
1463 return
1464 self.last_log_disk_space_time = now
1465
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001466 # Upload event if stateful partition usage is above threshold.
1467 # Stateful partition is mounted on /usr/local, while
1468 # encrypted stateful partition is mounted on /var.
1469 # If there are too much logs in the factory process,
1470 # these two partitions might get full.
Jon Salzb92c5112012-09-21 15:40:11 +08001471 try:
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001472 vfs_infos = disk_space.GetAllVFSInfo()
1473 stateful_info, encrypted_info = None, None
1474 for vfs_info in vfs_infos.values():
1475 if '/usr/local' in vfs_info.mount_points:
1476 stateful_info = vfs_info
1477 if '/var' in vfs_info.mount_points:
1478 encrypted_info = vfs_info
1479
1480 stateful = disk_space.GetPartitionUsage(stateful_info)
1481 encrypted = disk_space.GetPartitionUsage(encrypted_info)
1482
1483 above_threshold = (
1484 self.test_list.options.stateful_usage_threshold and
1485 max(stateful.bytes_used_pct,
1486 stateful.inodes_used_pct,
1487 encrypted.bytes_used_pct,
1488 encrypted.inodes_used_pct) >
1489 self.test_list.options.stateful_usage_threshold)
1490
1491 if above_threshold:
1492 self.event_log.Log('stateful_partition_usage',
1493 partitions={
1494 'stateful': {
1495 'bytes_used_pct': FloatDigit(stateful.bytes_used_pct, 2),
1496 'inodes_used_pct': FloatDigit(stateful.inodes_used_pct, 2)},
1497 'encrypted_stateful': {
1498 'bytes_used_pct': FloatDigit(encrypted.bytes_used_pct, 2),
1499 'inodes_used_pct': FloatDigit(encrypted.inodes_used_pct, 2)}
1500 })
1501 self.log_watcher.ScanEventLogs()
1502
1503 message = disk_space.FormatSpaceUsedAll(vfs_infos)
Jon Salz3c493bb2013-02-07 17:24:58 +08001504 if message != self.last_log_disk_space_message:
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001505 if above_threshold:
1506 logging.warning(message)
1507 else:
1508 logging.info(message)
Jon Salz3c493bb2013-02-07 17:24:58 +08001509 self.last_log_disk_space_message = message
Jon Salzb92c5112012-09-21 15:40:11 +08001510 except: # pylint: disable=W0702
1511 logging.exception('Unable to get disk space used')
1512
Justin Chuang83813982013-05-13 01:26:32 +08001513 def check_battery(self):
1514 '''Checks the current battery status.
1515
1516 Logs current battery charging level and status to log. If the battery level
1517 is lower below warning_low_battery_pct, send warning event to shopfloor.
1518 If the battery level is lower below critical_low_battery_pct, flush disks.
1519 '''
1520 if not self.test_list.options.check_battery_period_secs:
1521 return
1522
1523 now = time.time()
1524 if (self.last_check_battery_time and
1525 now - self.last_check_battery_time <
1526 self.test_list.options.check_battery_period_secs):
1527 return
1528 self.last_check_battery_time = now
1529
1530 message = ''
1531 log_level = logging.INFO
1532 try:
1533 power = system.GetBoard().power
1534 if not power.CheckBatteryPresent():
1535 message = 'Battery is not present'
1536 else:
1537 ac_present = power.CheckACPresent()
1538 charge_pct = power.GetChargePct(get_float=True)
1539 message = ('Current battery level %.1f%%, AC charger is %s' %
1540 (charge_pct, 'connected' if ac_present else 'disconnected'))
1541
1542 if charge_pct > self.test_list.options.critical_low_battery_pct:
1543 critical_low_battery = False
1544 else:
1545 critical_low_battery = True
1546 # Only sync disks when battery level is still above minimum
1547 # value. This can be used for offline analysis when shopfloor cannot
1548 # be connected.
1549 if charge_pct > MIN_BATTERY_LEVEL_FOR_DISK_SYNC:
1550 logging.warning('disk syncing for critical low battery situation')
1551 os.system('sync; sync; sync')
1552 else:
1553 logging.warning('disk syncing is cancelled '
1554 'because battery level is lower than %.1f',
1555 MIN_BATTERY_LEVEL_FOR_DISK_SYNC)
1556
1557 # Notify shopfloor server
1558 if (critical_low_battery or
1559 (not ac_present and
1560 charge_pct <= self.test_list.options.warning_low_battery_pct)):
1561 log_level = logging.WARNING
1562
1563 self.event_log.Log('low_battery',
1564 battery_level=charge_pct,
1565 charger_connected=ac_present,
1566 critical=critical_low_battery)
1567 self.log_watcher.KickWatchThread()
1568 self.system_log_manager.KickSyncThread()
1569 except: # pylint: disable=W0702
1570 logging.exception('Unable to check battery or notify shopfloor')
1571 finally:
1572 if message != self.last_check_battery_message:
1573 logging.log(log_level, message)
1574 self.last_check_battery_message = message
1575
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001576 def check_core_dump(self):
1577 '''Checks if there is any core dumped file.
1578
1579 Removes unwanted core dump files immediately.
1580 Syncs those files matching watch list to server with a delay between
1581 each sync. After the files have been synced to server, deletes the files.
1582 '''
1583 core_dump_files = self.core_dump_manager.ScanFiles()
1584 if core_dump_files:
1585 now = time.time()
1586 if (self.last_kick_sync_time and now - self.last_kick_sync_time <
1587 self.test_list.options.kick_sync_min_interval_secs):
1588 return
1589 self.last_kick_sync_time = now
1590
1591 # Sends event to server
1592 self.event_log.Log('core_dumped', files=core_dump_files)
1593 self.log_watcher.KickWatchThread()
1594
1595 # Syncs files to server
1596 self.system_log_manager.KickSyncThread(
1597 core_dump_files, self.core_dump_manager.ClearFiles)
1598
Jon Salz8fa8e832012-07-13 19:04:09 +08001599 def sync_time_in_background(self):
Jon Salzb22d1172012-08-06 10:38:57 +08001600 '''Writes out current time and tries to sync with shopfloor server.'''
1601 if not self.time_sanitizer:
1602 return
1603
1604 # Write out the current time.
1605 self.time_sanitizer.SaveTime()
1606
Jon Salz54882d02012-08-31 01:57:54 +08001607 if not self._should_sync_time():
Jon Salz8fa8e832012-07-13 19:04:09 +08001608 return
1609
1610 now = time.time()
1611 if self.last_sync_time and (
1612 now - self.last_sync_time <
1613 self.test_list.options.sync_time_period_secs):
1614 # Not yet time for another check.
1615 return
1616 self.last_sync_time = now
1617
1618 def target():
1619 try:
Jon Salz54882d02012-08-31 01:57:54 +08001620 self.sync_time_with_shopfloor_server()
Jon Salz8fa8e832012-07-13 19:04:09 +08001621 except: # pylint: disable=W0702
1622 # Oh well. Log an error (but no trace)
1623 logging.info(
1624 'Unable to get time from shopfloor server: %s',
1625 utils.FormatExceptionOnly())
1626
1627 thread = threading.Thread(target=target)
1628 thread.daemon = True
1629 thread.start()
1630
Jon Salz0697cbf2012-07-04 15:14:04 +08001631 def _run_queue_idle(self):
Vic Yang4953fc12012-07-26 16:19:53 +08001632 '''Invoked when the run queue has no events.
1633
1634 This method must not raise exception.
1635 '''
Jon Salzb22d1172012-08-06 10:38:57 +08001636 now = time.time()
1637 if (self.last_idle and
1638 now < (self.last_idle + RUN_QUEUE_TIMEOUT_SECS - 1)):
1639 # Don't run more often than once every (RUN_QUEUE_TIMEOUT_SECS -
1640 # 1) seconds.
1641 return
1642
1643 self.last_idle = now
1644
Vic Yang311ddb82012-09-26 12:08:28 +08001645 self.check_exclusive()
cychiang21886742012-07-05 15:16:32 +08001646 self.check_for_updates()
Jon Salz8fa8e832012-07-13 19:04:09 +08001647 self.sync_time_in_background()
Jon Salzb92c5112012-09-21 15:40:11 +08001648 self.log_disk_space_stats()
Justin Chuang83813982013-05-13 01:26:32 +08001649 self.check_battery()
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001650 self.check_core_dump()
Jon Salz57717ca2012-04-04 16:47:25 +08001651
Jon Salzd15bbcf2013-05-21 17:33:57 +08001652 def handle_event_logs(self, chunks):
Jon Salz0697cbf2012-07-04 15:14:04 +08001653 '''Callback for event watcher.
Jon Salz258a40c2012-04-19 12:34:01 +08001654
Jon Salz0697cbf2012-07-04 15:14:04 +08001655 Attempts to upload the event logs to the shopfloor server.
Vic Yang93027612013-05-06 02:42:49 +08001656
1657 Args:
Jon Salzd15bbcf2013-05-21 17:33:57 +08001658 chunks: A list of Chunk objects.
Jon Salz0697cbf2012-07-04 15:14:04 +08001659 '''
Vic Yang93027612013-05-06 02:42:49 +08001660 first_exception = None
1661 exception_count = 0
1662
Jon Salzd15bbcf2013-05-21 17:33:57 +08001663 for chunk in chunks:
Vic Yang93027612013-05-06 02:42:49 +08001664 try:
Jon Salzcddb6402013-05-23 12:56:42 +08001665 description = 'event logs (%s)' % str(chunk)
Vic Yang93027612013-05-06 02:42:49 +08001666 start_time = time.time()
1667 shopfloor_client = shopfloor.get_instance(
1668 detect=True,
1669 timeout=self.test_list.options.shopfloor_timeout_secs)
Jon Salzd15bbcf2013-05-21 17:33:57 +08001670 shopfloor_client.UploadEvent(chunk.log_name + "." +
1671 event_log.GetReimageId(),
1672 Binary(chunk.chunk))
Vic Yang93027612013-05-06 02:42:49 +08001673 logging.info(
1674 'Successfully synced %s in %.03f s',
1675 description, time.time() - start_time)
1676 except: # pylint: disable=W0702
Jon Salzd15bbcf2013-05-21 17:33:57 +08001677 first_exception = (first_exception or (chunk.log_name + ': ' +
Vic Yang93027612013-05-06 02:42:49 +08001678 utils.FormatExceptionOnly()))
1679 exception_count += 1
1680
1681 if exception_count:
1682 if exception_count == 1:
1683 msg = 'Log upload failed: %s' % first_exception
1684 else:
1685 msg = '%d log upload failed; first is: %s' % (
1686 exception_count, first_exception)
1687 raise Exception(msg)
1688
Jon Salz57717ca2012-04-04 16:47:25 +08001689
Jon Salz0697cbf2012-07-04 15:14:04 +08001690 def run_tests_with_status(self, statuses_to_run, starting_at=None,
1691 root=None):
1692 '''Runs all top-level tests with a particular status.
Jon Salz0405ab52012-03-16 15:26:52 +08001693
Jon Salz0697cbf2012-07-04 15:14:04 +08001694 All active tests, plus any tests to re-run, are reset.
Jon Salz57717ca2012-04-04 16:47:25 +08001695
Jon Salz0697cbf2012-07-04 15:14:04 +08001696 Args:
1697 starting_at: If provided, only auto-runs tests beginning with
1698 this test.
1699 '''
1700 root = root or self.test_list
Jon Salz57717ca2012-04-04 16:47:25 +08001701
Jon Salz0697cbf2012-07-04 15:14:04 +08001702 if starting_at:
1703 # Make sure they passed a test, not a string.
1704 assert isinstance(starting_at, factory.FactoryTest)
Jon Salz0405ab52012-03-16 15:26:52 +08001705
Jon Salz0697cbf2012-07-04 15:14:04 +08001706 tests_to_reset = []
1707 tests_to_run = []
Jon Salz0405ab52012-03-16 15:26:52 +08001708
Jon Salz0697cbf2012-07-04 15:14:04 +08001709 found_starting_at = False
Jon Salz0405ab52012-03-16 15:26:52 +08001710
Jon Salz0697cbf2012-07-04 15:14:04 +08001711 for test in root.get_top_level_tests():
1712 if starting_at:
1713 if test == starting_at:
1714 # We've found starting_at; do auto-run on all
1715 # subsequent tests.
1716 found_starting_at = True
1717 if not found_starting_at:
1718 # Don't start this guy yet
1719 continue
Jon Salz0405ab52012-03-16 15:26:52 +08001720
Jon Salz0697cbf2012-07-04 15:14:04 +08001721 status = test.get_state().status
1722 if status == TestState.ACTIVE or status in statuses_to_run:
1723 # Reset the test (later; we will need to abort
1724 # all active tests first).
1725 tests_to_reset.append(test)
1726 if status in statuses_to_run:
1727 tests_to_run.append(test)
Jon Salz0405ab52012-03-16 15:26:52 +08001728
Jon Salz0697cbf2012-07-04 15:14:04 +08001729 self.abort_active_tests()
Jon Salz258a40c2012-04-19 12:34:01 +08001730
Jon Salz0697cbf2012-07-04 15:14:04 +08001731 # Reset all statuses of the tests to run (in case any tests were active;
1732 # we want them to be run again).
1733 for test_to_reset in tests_to_reset:
1734 for test in test_to_reset.walk():
1735 test.update_state(status=TestState.UNTESTED)
Jon Salz57717ca2012-04-04 16:47:25 +08001736
Jon Salz0697cbf2012-07-04 15:14:04 +08001737 self.run_tests(tests_to_run, untested_only=True)
Jon Salz0405ab52012-03-16 15:26:52 +08001738
Jon Salz0697cbf2012-07-04 15:14:04 +08001739 def restart_tests(self, root=None):
1740 '''Restarts all tests.'''
1741 root = root or self.test_list
Jon Salz0405ab52012-03-16 15:26:52 +08001742
Jon Salz0697cbf2012-07-04 15:14:04 +08001743 self.abort_active_tests()
1744 for test in root.walk():
1745 test.update_state(status=TestState.UNTESTED)
1746 self.run_tests(root)
Hung-Te Lin96632362012-03-20 21:14:18 +08001747
Jon Salz0697cbf2012-07-04 15:14:04 +08001748 def auto_run(self, starting_at=None, root=None):
1749 '''"Auto-runs" tests that have not been run yet.
Hung-Te Lin96632362012-03-20 21:14:18 +08001750
Jon Salz0697cbf2012-07-04 15:14:04 +08001751 Args:
1752 starting_at: If provide, only auto-runs tests beginning with
1753 this test.
1754 '''
1755 root = root or self.test_list
1756 self.run_tests_with_status([TestState.UNTESTED, TestState.ACTIVE],
1757 starting_at=starting_at,
1758 root=root)
Jon Salz968e90b2012-03-18 16:12:43 +08001759
Jon Salz0697cbf2012-07-04 15:14:04 +08001760 def re_run_failed(self, root=None):
1761 '''Re-runs failed tests.'''
1762 root = root or self.test_list
1763 self.run_tests_with_status([TestState.FAILED], root=root)
Jon Salz57717ca2012-04-04 16:47:25 +08001764
Jon Salz0697cbf2012-07-04 15:14:04 +08001765 def show_review_information(self):
1766 '''Event handler for showing review information screen.
Jon Salz57717ca2012-04-04 16:47:25 +08001767
Jon Salz0697cbf2012-07-04 15:14:04 +08001768 The information screene is rendered by main UI program (ui.py), so in
1769 goofy we only need to kill all active tests, set them as untested, and
1770 clear remaining tests.
1771 '''
1772 self.kill_active_tests(False)
Jon Salza6711d72012-07-18 14:33:03 +08001773 self.cancel_pending_tests()
Jon Salz57717ca2012-04-04 16:47:25 +08001774
Jon Salz0697cbf2012-07-04 15:14:04 +08001775 def handle_switch_test(self, event):
1776 '''Switches to a particular test.
Jon Salz0405ab52012-03-16 15:26:52 +08001777
Jon Salz0697cbf2012-07-04 15:14:04 +08001778 @param event: The SWITCH_TEST event.
1779 '''
1780 test = self.test_list.lookup_path(event.path)
1781 if not test:
1782 logging.error('Unknown test %r', event.key)
1783 return
Jon Salz73e0fd02012-04-04 11:46:38 +08001784
Jon Salz0697cbf2012-07-04 15:14:04 +08001785 invoc = self.invocations.get(test)
1786 if invoc and test.backgroundable:
1787 # Already running: just bring to the front if it
1788 # has a UI.
1789 logging.info('Setting visible test to %s', test.path)
Jon Salz36fbbb52012-07-05 13:45:06 +08001790 self.set_visible_test(test)
Jon Salz0697cbf2012-07-04 15:14:04 +08001791 return
Jon Salz73e0fd02012-04-04 11:46:38 +08001792
Jon Salz0697cbf2012-07-04 15:14:04 +08001793 self.abort_active_tests()
1794 for t in test.walk():
1795 t.update_state(status=TestState.UNTESTED)
Jon Salz73e0fd02012-04-04 11:46:38 +08001796
Jon Salz0697cbf2012-07-04 15:14:04 +08001797 if self.test_list.options.auto_run_on_keypress:
1798 self.auto_run(starting_at=test)
1799 else:
1800 self.run_tests(test)
Jon Salz73e0fd02012-04-04 11:46:38 +08001801
Jon Salz0697cbf2012-07-04 15:14:04 +08001802 def wait(self):
1803 '''Waits for all pending invocations.
1804
1805 Useful for testing.
1806 '''
Jon Salz1acc8742012-07-17 17:45:55 +08001807 while self.invocations:
1808 for k, v in self.invocations.iteritems():
1809 logging.info('Waiting for %s to complete...', k)
1810 v.thread.join()
1811 self.reap_completed_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +08001812
1813 def check_exceptions(self):
1814 '''Raises an error if any exceptions have occurred in
1815 invocation threads.'''
1816 if self.exceptions:
1817 raise RuntimeError('Exception in invocation thread: %r' %
1818 self.exceptions)
1819
1820 def record_exception(self, msg):
1821 '''Records an exception in an invocation thread.
1822
1823 An exception with the given message will be rethrown when
1824 Goofy is destroyed.'''
1825 self.exceptions.append(msg)
Jon Salz73e0fd02012-04-04 11:46:38 +08001826
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001827
1828if __name__ == '__main__':
Jon Salz77c151e2012-08-28 07:20:37 +08001829 goofy = Goofy()
1830 try:
1831 goofy.main()
Jon Salz0f996602012-10-03 15:26:48 +08001832 except SystemExit:
1833 # Propagate SystemExit without logging.
1834 raise
Jon Salz31373eb2012-09-21 16:19:49 +08001835 except:
Jon Salz0f996602012-10-03 15:26:48 +08001836 # Log the error before trying to shut down (unless it's a graceful
1837 # exit).
Jon Salz31373eb2012-09-21 16:19:49 +08001838 logging.exception('Error in main loop')
1839 raise
Jon Salz77c151e2012-08-28 07:20:37 +08001840 finally:
1841 goofy.destroy()