blob: b36e496c86924d261fd3913fbc567658ac863725 [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
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08008"""The main factory flow that runs the factory test and finalizes a device."""
Hung-Te Linf2f78f72012-02-08 19:27:11 +08009
Jon Salze12c2b32013-06-25 16:24:34 +080010import glob
Jon Salz0405ab52012-03-16 15:26:52 +080011import logging
12import os
Jon Salz73e0fd02012-04-04 11:46:38 +080013import Queue
Jon Salze12c2b32013-06-25 16:24:34 +080014import shutil
Jon Salz77c151e2012-08-28 07:20:37 +080015import signal
Jon Salz0405ab52012-03-16 15:26:52 +080016import sys
Jon Salzeff94182013-06-19 15:06:28 +080017import syslog
Jon Salz0405ab52012-03-16 15:26:52 +080018import threading
19import time
20import traceback
Jon Salz258a40c2012-04-19 12:34:01 +080021import uuid
Jon Salzb10cf512012-08-09 17:29:21 +080022from xmlrpclib import Binary
Hung-Te Linf2f78f72012-02-08 19:27:11 +080023from collections import deque
24from optparse import OptionParser
Hung-Te Linf2f78f72012-02-08 19:27:11 +080025
Jon Salz0697cbf2012-07-04 15:14:04 +080026import factory_common # pylint: disable=W0611
jcliangcd688182012-08-20 21:01:26 +080027from cros.factory import event_log
28from cros.factory import system
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +080029from cros.factory.event_log import EventLog, FloatDigit
Tom Wai-Hong Tamd33723e2013-04-10 21:14:37 +080030from cros.factory.event_log_watcher import EventLogWatcher
jcliangcd688182012-08-20 21:01:26 +080031from cros.factory.goofy import test_environment
32from cros.factory.goofy import time_sanitizer
Jon Salz83591782012-06-26 11:09:58 +080033from cros.factory.goofy import updater
jcliangcd688182012-08-20 21:01:26 +080034from cros.factory.goofy.goofy_rpc import GoofyRPC
Jon Salz885dcac2013-07-23 16:39:50 +080035from cros.factory.goofy.invocation import TestArgEnv
jcliangcd688182012-08-20 21:01:26 +080036from cros.factory.goofy.invocation import TestInvocation
37from cros.factory.goofy.prespawner import Prespawner
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +080038from cros.factory.goofy.system_log_manager import SystemLogManager
jcliangcd688182012-08-20 21:01:26 +080039from cros.factory.goofy.web_socket_manager import WebSocketManager
Cheng-Yi Chiangd8186952013-04-04 23:41:14 +080040from cros.factory.system.board import Board, BoardException
jcliangcd688182012-08-20 21:01:26 +080041from cros.factory.system.charge_manager import ChargeManager
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +080042from cros.factory.system.core_dump_manager import CoreDumpManager
Jon Salzce6a7f82013-06-10 18:22:54 +080043from cros.factory.system.cpufreq_manager import CpufreqManager
Jon Salzb92c5112012-09-21 15:40:11 +080044from cros.factory.system import disk_space
jcliangcd688182012-08-20 21:01:26 +080045from cros.factory.test import factory
46from cros.factory.test import state
Jon Salz51528e12012-07-02 18:54:45 +080047from cros.factory.test import shopfloor
Jon Salz83591782012-06-26 11:09:58 +080048from cros.factory.test import utils
Jon Salz128b0932013-07-03 16:55:26 +080049from cros.factory.test.test_lists import test_lists
Ricky Liang6fe218c2013-12-27 15:17:17 +080050from cros.factory.test.e2e_test.common import (
51 AutomationMode, AutomationModePrompt, ParseAutomationMode)
Jon Salz83591782012-06-26 11:09:58 +080052from cros.factory.test.event import Event
53from cros.factory.test.event import EventClient
54from cros.factory.test.event import EventServer
jcliangcd688182012-08-20 21:01:26 +080055from cros.factory.test.factory import TestState
Jon Salzd7550792013-07-12 05:49:27 +080056from cros.factory.test.utils import Enum
Dean Liao592e4d52013-01-10 20:06:39 +080057from cros.factory.tools.key_filter import KeyFilter
Jon Salz2af235d2013-06-24 14:47:21 +080058from cros.factory.utils import file_utils
Jon Salz78c32392012-07-25 14:18:29 +080059from cros.factory.utils.process_utils import Spawn
Hung-Te Linf2f78f72012-02-08 19:27:11 +080060
61
Hung-Te Linf2f78f72012-02-08 19:27:11 +080062HWID_CFG_PATH = '/usr/local/share/chromeos-hwid/cfg'
Chun-ta Lin279e7e92013-02-19 17:40:39 +080063CACHES_DIR = os.path.join(factory.get_state_root(), "caches")
Hung-Te Linf2f78f72012-02-08 19:27:11 +080064
Cheng-Yi Chiang39d32ad2013-07-23 15:02:38 +080065CLEANUP_LOGS_PAUSED = '/var/lib/cleanup_logs_paused'
66
Jon Salz8796e362012-05-24 11:39:09 +080067# File that suppresses reboot if present (e.g., for development).
68NO_REBOOT_FILE = '/var/log/factory.noreboot'
69
Jon Salz5c344f62012-07-13 14:31:16 +080070# Value for tests_after_shutdown that forces auto-run (e.g., after
71# a factory update, when the available set of tests might change).
72FORCE_AUTO_RUN = 'force_auto_run'
73
cychiang21886742012-07-05 15:16:32 +080074RUN_QUEUE_TIMEOUT_SECS = 10
75
Justin Chuang83813982013-05-13 01:26:32 +080076# Sync disks when battery level is higher than this value.
77# Otherwise, power loss during disk sync operation may incur even worse outcome.
78MIN_BATTERY_LEVEL_FOR_DISK_SYNC = 1.0
79
Jon Salze12c2b32013-06-25 16:24:34 +080080MAX_CRASH_FILE_SIZE = 64*1024
81
Jon Salz758e6cc2012-04-03 15:47:07 +080082GOOFY_IN_CHROOT_WARNING = '\n' + ('*' * 70) + '''
83You are running Goofy inside the chroot. Autotests are not supported.
84
85To use Goofy in the chroot, first install an Xvnc server:
86
Jon Salz0697cbf2012-07-04 15:14:04 +080087 sudo apt-get install tightvncserver
Jon Salz758e6cc2012-04-03 15:47:07 +080088
89...and then start a VNC X server outside the chroot:
90
Jon Salz0697cbf2012-07-04 15:14:04 +080091 vncserver :10 &
92 vncviewer :10
Jon Salz758e6cc2012-04-03 15:47:07 +080093
94...and run Goofy as follows:
95
Jon Salz0697cbf2012-07-04 15:14:04 +080096 env --unset=XAUTHORITY DISPLAY=localhost:10 python goofy.py
Jon Salz758e6cc2012-04-03 15:47:07 +080097''' + ('*' * 70)
Jon Salz73e0fd02012-04-04 11:46:38 +080098suppress_chroot_warning = False
Hung-Te Linf2f78f72012-02-08 19:27:11 +080099
Jon Salzd7550792013-07-12 05:49:27 +0800100Status = Enum(['UNINITIALIZED', 'INITIALIZING', 'RUNNING',
101 'TERMINATING', 'TERMINATED'])
102
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800103def get_hwid_cfg():
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800104 """Returns the HWID config tag, or an empty string if none can be found."""
Jon Salz0697cbf2012-07-04 15:14:04 +0800105 if 'CROS_HWID' in os.environ:
106 return os.environ['CROS_HWID']
107 if os.path.exists(HWID_CFG_PATH):
108 with open(HWID_CFG_PATH, 'rt') as hwid_cfg_handle:
109 return hwid_cfg_handle.read().strip()
110 return ''
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800111
112
Jon Salz73e0fd02012-04-04 11:46:38 +0800113_inited_logging = False
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800114
115class Goofy(object):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800116 """The main factory flow.
Jon Salz0697cbf2012-07-04 15:14:04 +0800117
118 Note that all methods in this class must be invoked from the main
119 (event) thread. Other threads, such as callbacks and TestInvocation
120 methods, should instead post events on the run queue.
121
122 TODO: Unit tests. (chrome-os-partner:7409)
123
124 Properties:
125 uuid: A unique UUID for this invocation of Goofy.
126 state_instance: An instance of FactoryState.
127 state_server: The FactoryState XML/RPC server.
128 state_server_thread: A thread running state_server.
129 event_server: The EventServer socket server.
130 event_server_thread: A thread running event_server.
131 event_client: A client to the event server.
132 connection_manager: The connection_manager object.
Cheng-Yi Chiang835f2682013-05-06 22:15:48 +0800133 system_log_manager: The SystemLogManager object.
134 core_dump_manager: The CoreDumpManager object.
Jon Salz0697cbf2012-07-04 15:14:04 +0800135 ui_process: The factory ui process object.
136 run_queue: A queue of callbacks to invoke from the main thread.
137 invocations: A map from FactoryTest objects to the corresponding
138 TestInvocations objects representing active tests.
139 tests_to_run: A deque of tests that should be run when the current
140 test(s) complete.
141 options: Command-line options.
142 args: Command-line args.
143 test_list: The test list.
Jon Salz128b0932013-07-03 16:55:26 +0800144 test_lists: All new-style test lists.
Ricky Liang4bff3e32014-02-20 18:46:11 +0800145 run_id: The identifier for latest test run.
146 scheduled_run_tests: The list of tests scheduled for latest test run.
Jon Salz0697cbf2012-07-04 15:14:04 +0800147 event_handlers: Map of Event.Type to the method used to handle that
148 event. If the method has an 'event' argument, the event is passed
149 to the handler.
150 exceptions: Exceptions encountered in invocation threads.
Jon Salz3c493bb2013-02-07 17:24:58 +0800151 last_log_disk_space_message: The last message we logged about disk space
152 (to avoid duplication).
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +0800153 last_kick_sync_time: The last time to kick system_log_manager to sync
154 because of core dump files (to avoid kicking too soon then abort the
155 sync.)
Jon Salz416f9cc2013-05-10 18:32:50 +0800156 hooks: A Hooks object containing hooks for various Goofy actions.
Jon Salzd7550792013-07-12 05:49:27 +0800157 status: The current Goofy status (a member of the Status enum).
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800158 """
Jon Salz0697cbf2012-07-04 15:14:04 +0800159 def __init__(self):
160 self.uuid = str(uuid.uuid4())
161 self.state_instance = None
162 self.state_server = None
163 self.state_server_thread = None
Jon Salz16d10542012-07-23 12:18:45 +0800164 self.goofy_rpc = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800165 self.event_server = None
166 self.event_server_thread = None
167 self.event_client = None
168 self.connection_manager = None
Vic Yang4953fc12012-07-26 16:19:53 +0800169 self.charge_manager = None
Jon Salz8fa8e832012-07-13 19:04:09 +0800170 self.time_sanitizer = None
171 self.time_synced = False
Jon Salz0697cbf2012-07-04 15:14:04 +0800172 self.log_watcher = None
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +0800173 self.system_log_manager = None
Cheng-Yi Chiang835f2682013-05-06 22:15:48 +0800174 self.core_dump_manager = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800175 self.event_log = None
176 self.prespawner = None
177 self.ui_process = None
Jon Salzc79a9982012-08-30 04:42:01 +0800178 self.dummy_shopfloor = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800179 self.run_queue = Queue.Queue()
180 self.invocations = {}
181 self.tests_to_run = deque()
182 self.visible_test = None
183 self.chrome = None
Jon Salz416f9cc2013-05-10 18:32:50 +0800184 self.hooks = None
Vic Yangd8990da2013-06-27 16:57:43 +0800185 self.cpu_usage_watcher = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800186
187 self.options = None
188 self.args = None
189 self.test_list = None
Jon Salz128b0932013-07-03 16:55:26 +0800190 self.test_lists = None
Ricky Liang4bff3e32014-02-20 18:46:11 +0800191 self.run_id = None
192 self.scheduled_run_tests = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800193 self.on_ui_startup = []
194 self.env = None
Jon Salzb22d1172012-08-06 10:38:57 +0800195 self.last_idle = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800196 self.last_shutdown_time = None
cychiang21886742012-07-05 15:16:32 +0800197 self.last_update_check = None
Jon Salz8fa8e832012-07-13 19:04:09 +0800198 self.last_sync_time = None
Jon Salzb92c5112012-09-21 15:40:11 +0800199 self.last_log_disk_space_time = None
Jon Salz3c493bb2013-02-07 17:24:58 +0800200 self.last_log_disk_space_message = None
Justin Chuang83813982013-05-13 01:26:32 +0800201 self.last_check_battery_time = None
202 self.last_check_battery_message = None
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +0800203 self.last_kick_sync_time = None
Vic Yang311ddb82012-09-26 12:08:28 +0800204 self.exclusive_items = set()
Jon Salz0f996602012-10-03 15:26:48 +0800205 self.event_log = None
Dean Liao592e4d52013-01-10 20:06:39 +0800206 self.key_filter = None
Jon Salzce6a7f82013-06-10 18:22:54 +0800207 self.cpufreq_manager = None
Jon Salzd7550792013-07-12 05:49:27 +0800208 self.status = Status.UNINITIALIZED
Jon Salz0697cbf2012-07-04 15:14:04 +0800209
Jon Salz85a39882012-07-05 16:45:04 +0800210 def test_or_root(event, parent_or_group=True):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800211 """Returns the test affected by a particular event.
Jon Salz85a39882012-07-05 16:45:04 +0800212
213 Args:
214 event: The event containing an optional 'path' attribute.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800215 parent_or_group: If True, returns the top-level parent for a test (the
Jon Salz85a39882012-07-05 16:45:04 +0800216 root node of the tests that need to be run together if the given test
217 path is to be run).
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800218 """
Jon Salz0697cbf2012-07-04 15:14:04 +0800219 try:
220 path = event.path
221 except AttributeError:
222 path = None
223
224 if path:
Jon Salz85a39882012-07-05 16:45:04 +0800225 test = self.test_list.lookup_path(path)
226 if parent_or_group:
227 test = test.get_top_level_parent_or_group()
228 return test
Jon Salz0697cbf2012-07-04 15:14:04 +0800229 else:
230 return self.test_list
231
232 self.event_handlers = {
233 Event.Type.SWITCH_TEST: self.handle_switch_test,
234 Event.Type.SHOW_NEXT_ACTIVE_TEST:
235 lambda event: self.show_next_active_test(),
236 Event.Type.RESTART_TESTS:
237 lambda event: self.restart_tests(root=test_or_root(event)),
238 Event.Type.AUTO_RUN:
239 lambda event: self.auto_run(root=test_or_root(event)),
240 Event.Type.RE_RUN_FAILED:
241 lambda event: self.re_run_failed(root=test_or_root(event)),
242 Event.Type.RUN_TESTS_WITH_STATUS:
243 lambda event: self.run_tests_with_status(
244 event.status,
245 root=test_or_root(event)),
246 Event.Type.REVIEW:
247 lambda event: self.show_review_information(),
248 Event.Type.UPDATE_SYSTEM_INFO:
249 lambda event: self.update_system_info(),
Jon Salz0697cbf2012-07-04 15:14:04 +0800250 Event.Type.STOP:
Jon Salz85a39882012-07-05 16:45:04 +0800251 lambda event: self.stop(root=test_or_root(event, False),
Jon Salz6dc031d2013-06-19 13:06:23 +0800252 fail=getattr(event, 'fail', False),
253 reason=getattr(event, 'reason', None)),
Jon Salz36fbbb52012-07-05 13:45:06 +0800254 Event.Type.SET_VISIBLE_TEST:
255 lambda event: self.set_visible_test(
256 self.test_list.lookup_path(event.path)),
Jon Salz4712ac72013-02-07 17:12:05 +0800257 Event.Type.CLEAR_STATE:
258 lambda event: self.clear_state(self.test_list.lookup_path(event.path)),
Jon Salz0697cbf2012-07-04 15:14:04 +0800259 }
260
261 self.exceptions = []
262 self.web_socket_manager = None
263
264 def destroy(self):
Jon Salzd7550792013-07-12 05:49:27 +0800265 self.status = Status.TERMINATING
Jon Salz0697cbf2012-07-04 15:14:04 +0800266 if self.chrome:
267 self.chrome.kill()
268 self.chrome = None
Jon Salzc79a9982012-08-30 04:42:01 +0800269 if self.dummy_shopfloor:
270 self.dummy_shopfloor.kill()
271 self.dummy_shopfloor = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800272 if self.ui_process:
273 utils.kill_process_tree(self.ui_process, 'ui')
274 self.ui_process = None
275 if self.web_socket_manager:
276 logging.info('Stopping web sockets')
277 self.web_socket_manager.close()
278 self.web_socket_manager = None
279 if self.state_server_thread:
280 logging.info('Stopping state server')
281 self.state_server.shutdown()
282 self.state_server_thread.join()
283 self.state_server.server_close()
284 self.state_server_thread = None
285 if self.state_instance:
286 self.state_instance.close()
287 if self.event_server_thread:
288 logging.info('Stopping event server')
289 self.event_server.shutdown() # pylint: disable=E1101
290 self.event_server_thread.join()
291 self.event_server.server_close()
292 self.event_server_thread = None
293 if self.log_watcher:
294 if self.log_watcher.IsThreadStarted():
295 self.log_watcher.StopWatchThread()
296 self.log_watcher = None
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +0800297 if self.system_log_manager:
298 if self.system_log_manager.IsThreadRunning():
Cheng-Yi Chianga0f6eff2014-01-09 18:27:22 +0800299 self.system_log_manager.Stop()
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +0800300 self.system_log_manager = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800301 if self.prespawner:
302 logging.info('Stopping prespawner')
303 self.prespawner.stop()
304 self.prespawner = None
305 if self.event_client:
306 logging.info('Closing event client')
307 self.event_client.close()
308 self.event_client = None
Jon Salzddf0d052013-06-18 12:52:44 +0800309 if self.cpufreq_manager:
310 self.cpufreq_manager.Stop()
Jon Salz0697cbf2012-07-04 15:14:04 +0800311 if self.event_log:
312 self.event_log.Close()
313 self.event_log = None
Dean Liao592e4d52013-01-10 20:06:39 +0800314 if self.key_filter:
315 self.key_filter.Stop()
Vic Yangd8990da2013-06-27 16:57:43 +0800316 if self.cpu_usage_watcher:
317 self.cpu_usage_watcher.terminate()
Dean Liao592e4d52013-01-10 20:06:39 +0800318
Jon Salz0697cbf2012-07-04 15:14:04 +0800319 self.check_exceptions()
320 logging.info('Done destroying Goofy')
Jon Salzd7550792013-07-12 05:49:27 +0800321 self.status = Status.TERMINATED
Jon Salz0697cbf2012-07-04 15:14:04 +0800322
323 def start_state_server(self):
Jon Salz2af235d2013-06-24 14:47:21 +0800324 # Before starting state server, remount stateful partitions with
325 # no commit flag. The default commit time (commit=600) makes corruption
326 # too likely.
327 file_utils.ResetCommitTime()
328
Jon Salz0697cbf2012-07-04 15:14:04 +0800329 self.state_instance, self.state_server = (
330 state.create_server(bind_address='0.0.0.0'))
Jon Salz16d10542012-07-23 12:18:45 +0800331 self.goofy_rpc = GoofyRPC(self)
332 self.goofy_rpc.RegisterMethods(self.state_instance)
Jon Salz0697cbf2012-07-04 15:14:04 +0800333 logging.info('Starting state server')
334 self.state_server_thread = threading.Thread(
335 target=self.state_server.serve_forever,
336 name='StateServer')
337 self.state_server_thread.start()
338
339 def start_event_server(self):
340 self.event_server = EventServer()
341 logging.info('Starting factory event server')
342 self.event_server_thread = threading.Thread(
343 target=self.event_server.serve_forever,
344 name='EventServer') # pylint: disable=E1101
345 self.event_server_thread.start()
346
347 self.event_client = EventClient(
348 callback=self.handle_event, event_loop=self.run_queue)
349
350 self.web_socket_manager = WebSocketManager(self.uuid)
351 self.state_server.add_handler("/event",
352 self.web_socket_manager.handle_web_socket)
353
354 def start_ui(self):
355 ui_proc_args = [
356 os.path.join(factory.FACTORY_PACKAGE_PATH, 'test', 'ui.py'),
357 self.options.test_list]
358 if self.options.verbose:
359 ui_proc_args.append('-v')
360 logging.info('Starting ui %s', ui_proc_args)
Jon Salz78c32392012-07-25 14:18:29 +0800361 self.ui_process = Spawn(ui_proc_args)
Jon Salz0697cbf2012-07-04 15:14:04 +0800362 logging.info('Waiting for UI to come up...')
363 self.event_client.wait(
364 lambda event: event.type == Event.Type.UI_READY)
365 logging.info('UI has started')
366
367 def set_visible_test(self, test):
368 if self.visible_test == test:
369 return
Jon Salz2f2d42c2012-07-30 12:30:34 +0800370 if test and not test.has_ui:
371 return
Jon Salz0697cbf2012-07-04 15:14:04 +0800372
373 if test:
374 test.update_state(visible=True)
375 if self.visible_test:
376 self.visible_test.update_state(visible=False)
377 self.visible_test = test
378
Jon Salzd4306c82012-11-30 15:16:36 +0800379 def _log_startup_messages(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800380 """Logs the tail of var/log/messages and mosys and EC console logs."""
Jon Salzd4306c82012-11-30 15:16:36 +0800381 # TODO(jsalz): This is mostly a copy-and-paste of code in init_states,
382 # for factory-3004.B only. Consolidate and merge back to ToT.
383 if utils.in_chroot():
384 return
385
386 try:
387 var_log_messages = (
388 utils.var_log_messages_before_reboot())
389 logging.info(
390 'Tail of /var/log/messages before last reboot:\n'
391 '%s', ('\n'.join(
392 ' ' + x for x in var_log_messages)))
393 except: # pylint: disable=W0702
394 logging.exception('Unable to grok /var/log/messages')
395
396 try:
397 mosys_log = utils.Spawn(
398 ['mosys', 'eventlog', 'list'],
399 read_stdout=True, log_stderr_on_error=True).stdout_data
400 logging.info('System eventlog from mosys:\n%s\n', mosys_log)
401 except: # pylint: disable=W0702
402 logging.exception('Unable to read mosys eventlog')
403
404 try:
Vic Yang8341dde2013-01-29 16:48:52 +0800405 board = system.GetBoard()
406 ec_console_log = board.GetECConsoleLog()
Jon Salzd4306c82012-11-30 15:16:36 +0800407 logging.info('EC console log after reboot:\n%s\n', ec_console_log)
408 except: # pylint: disable=W0702
409 logging.exception('Error retrieving EC console log')
410
Vic Yang079f9872013-07-01 11:32:00 +0800411 try:
412 board = system.GetBoard()
413 ec_panic_info = board.GetECPanicInfo()
414 logging.info('EC panic info after reboot:\n%s\n', ec_panic_info)
415 except: # pylint: disable=W0702
416 logging.exception('Error retrieving EC panic info')
417
Jon Salz0697cbf2012-07-04 15:14:04 +0800418 def handle_shutdown_complete(self, test, test_state):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800419 """Handles the case where a shutdown was detected during a shutdown step.
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800420
Ricky Liang6fe218c2013-12-27 15:17:17 +0800421 Args:
422 test: The ShutdownStep.
423 test_state: The test state.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800424 """
Jon Salz0697cbf2012-07-04 15:14:04 +0800425 test_state = test.update_state(increment_shutdown_count=1)
426 logging.info('Detected shutdown (%d of %d)',
427 test_state.shutdown_count, test.iterations)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800428
Jon Salz0697cbf2012-07-04 15:14:04 +0800429 def log_and_update_state(status, error_msg, **kw):
430 self.event_log.Log('rebooted',
431 status=status, error_msg=error_msg, **kw)
Jon Salzd4306c82012-11-30 15:16:36 +0800432 logging.info('Rebooted: status=%s, %s', status,
433 (('error_msg=%s' % error_msg) if error_msg else None))
Jon Salz0697cbf2012-07-04 15:14:04 +0800434 test.update_state(status=status, error_msg=error_msg)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800435
Jon Salz0697cbf2012-07-04 15:14:04 +0800436 if not self.last_shutdown_time:
437 log_and_update_state(status=TestState.FAILED,
438 error_msg='Unable to read shutdown_time')
439 return
Jon Salz258a40c2012-04-19 12:34:01 +0800440
Jon Salz0697cbf2012-07-04 15:14:04 +0800441 now = time.time()
442 logging.info('%.03f s passed since reboot',
443 now - self.last_shutdown_time)
Jon Salz258a40c2012-04-19 12:34:01 +0800444
Jon Salz0697cbf2012-07-04 15:14:04 +0800445 if self.last_shutdown_time > now:
446 test.update_state(status=TestState.FAILED,
447 error_msg='Time moved backward during reboot')
448 elif (isinstance(test, factory.RebootStep) and
449 self.test_list.options.max_reboot_time_secs and
450 (now - self.last_shutdown_time >
451 self.test_list.options.max_reboot_time_secs)):
452 # A reboot took too long; fail. (We don't check this for
453 # HaltSteps, because the machine could be halted for a
454 # very long time, and even unplugged with battery backup,
455 # thus hosing the clock.)
456 log_and_update_state(
457 status=TestState.FAILED,
458 error_msg=('More than %d s elapsed during reboot '
459 '(%.03f s, from %s to %s)' % (
460 self.test_list.options.max_reboot_time_secs,
461 now - self.last_shutdown_time,
462 utils.TimeString(self.last_shutdown_time),
463 utils.TimeString(now))),
464 duration=(now-self.last_shutdown_time))
Jon Salzd4306c82012-11-30 15:16:36 +0800465 self._log_startup_messages()
Jon Salz0697cbf2012-07-04 15:14:04 +0800466 elif test_state.shutdown_count == test.iterations:
467 # Good!
468 log_and_update_state(status=TestState.PASSED,
469 duration=(now - self.last_shutdown_time),
470 error_msg='')
471 elif test_state.shutdown_count > test.iterations:
472 # Shut down too many times
473 log_and_update_state(status=TestState.FAILED,
474 error_msg='Too many shutdowns')
Jon Salzd4306c82012-11-30 15:16:36 +0800475 self._log_startup_messages()
Jon Salz0697cbf2012-07-04 15:14:04 +0800476 elif utils.are_shift_keys_depressed():
477 logging.info('Shift keys are depressed; cancelling restarts')
478 # Abort shutdown
479 log_and_update_state(
480 status=TestState.FAILED,
481 error_msg='Shutdown aborted with double shift keys')
Jon Salza6711d72012-07-18 14:33:03 +0800482 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +0800483 else:
484 def handler():
485 if self._prompt_cancel_shutdown(
486 test, test_state.shutdown_count + 1):
Jon Salza6711d72012-07-18 14:33:03 +0800487 factory.console.info('Shutdown aborted by operator')
Jon Salz0697cbf2012-07-04 15:14:04 +0800488 log_and_update_state(
489 status=TestState.FAILED,
490 error_msg='Shutdown aborted by operator')
Jon Salza6711d72012-07-18 14:33:03 +0800491 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +0800492 return
Jon Salz0405ab52012-03-16 15:26:52 +0800493
Jon Salz0697cbf2012-07-04 15:14:04 +0800494 # Time to shutdown again
495 log_and_update_state(
496 status=TestState.ACTIVE,
497 error_msg='',
498 iteration=test_state.shutdown_count)
Jon Salz73e0fd02012-04-04 11:46:38 +0800499
Jon Salz0697cbf2012-07-04 15:14:04 +0800500 self.event_log.Log('shutdown', operation='reboot')
501 self.state_instance.set_shared_data('shutdown_time',
502 time.time())
503 self.env.shutdown('reboot')
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800504
Jon Salz0697cbf2012-07-04 15:14:04 +0800505 self.on_ui_startup.append(handler)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800506
Jon Salz0697cbf2012-07-04 15:14:04 +0800507 def _prompt_cancel_shutdown(self, test, iteration):
508 if self.options.ui != 'chrome':
509 return False
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800510
Jon Salz0697cbf2012-07-04 15:14:04 +0800511 pending_shutdown_data = {
512 'delay_secs': test.delay_secs,
Ricky Liang8c2c6c32013-11-02 23:02:44 +0800513 'enable_guest_mode': test.enable_guest_mode,
Jon Salz0697cbf2012-07-04 15:14:04 +0800514 'time': time.time() + test.delay_secs,
515 'operation': test.operation,
516 'iteration': iteration,
517 'iterations': test.iterations,
518 }
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800519
Jon Salz0697cbf2012-07-04 15:14:04 +0800520 # Create a new (threaded) event client since we
521 # don't want to use the event loop for this.
522 with EventClient() as event_client:
523 event_client.post_event(Event(Event.Type.PENDING_SHUTDOWN,
524 **pending_shutdown_data))
525 aborted = event_client.wait(
526 lambda event: event.type == Event.Type.CANCEL_SHUTDOWN,
527 timeout=test.delay_secs) is not None
528 if aborted:
529 event_client.post_event(Event(Event.Type.PENDING_SHUTDOWN))
530 return aborted
Jon Salz258a40c2012-04-19 12:34:01 +0800531
Jon Salz0697cbf2012-07-04 15:14:04 +0800532 def init_states(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800533 """Initializes all states on startup."""
Jon Salz0697cbf2012-07-04 15:14:04 +0800534 for test in self.test_list.get_all_tests():
535 # Make sure the state server knows about all the tests,
536 # defaulting to an untested state.
537 test.update_state(update_parent=False, visible=False)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800538
Jon Salz0697cbf2012-07-04 15:14:04 +0800539 var_log_messages = None
Vic Yanga9c32212012-08-16 20:07:54 +0800540 mosys_log = None
Vic Yange4c275d2012-08-28 01:50:20 +0800541 ec_console_log = None
Vic Yang079f9872013-07-01 11:32:00 +0800542 ec_panic_info = None
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800543
Jon Salz0697cbf2012-07-04 15:14:04 +0800544 # Any 'active' tests should be marked as failed now.
545 for test in self.test_list.walk():
Jon Salza6711d72012-07-18 14:33:03 +0800546 if not test.is_leaf():
547 # Don't bother with parents; they will be updated when their
548 # children are updated.
549 continue
550
Jon Salz0697cbf2012-07-04 15:14:04 +0800551 test_state = test.get_state()
552 if test_state.status != TestState.ACTIVE:
553 continue
554 if isinstance(test, factory.ShutdownStep):
555 # Shutdown while the test was active - that's good.
556 self.handle_shutdown_complete(test, test_state)
557 else:
558 # Unexpected shutdown. Grab /var/log/messages for context.
559 if var_log_messages is None:
560 try:
561 var_log_messages = (
562 utils.var_log_messages_before_reboot())
563 # Write it to the log, to make it easier to
564 # correlate with /var/log/messages.
565 logging.info(
566 'Unexpected shutdown. '
567 'Tail of /var/log/messages before last reboot:\n'
568 '%s', ('\n'.join(
569 ' ' + x for x in var_log_messages)))
570 except: # pylint: disable=W0702
571 logging.exception('Unable to grok /var/log/messages')
572 var_log_messages = []
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800573
Jon Salz008f4ea2012-08-28 05:39:45 +0800574 if mosys_log is None and not utils.in_chroot():
575 try:
576 mosys_log = utils.Spawn(
577 ['mosys', 'eventlog', 'list'],
578 read_stdout=True, log_stderr_on_error=True).stdout_data
579 # Write it to the log also.
580 logging.info('System eventlog from mosys:\n%s\n', mosys_log)
581 except: # pylint: disable=W0702
582 logging.exception('Unable to read mosys eventlog')
Vic Yanga9c32212012-08-16 20:07:54 +0800583
Vic Yange4c275d2012-08-28 01:50:20 +0800584 if ec_console_log is None:
585 try:
Vic Yang8341dde2013-01-29 16:48:52 +0800586 board = system.GetBoard()
587 ec_console_log = board.GetECConsoleLog()
Vic Yange4c275d2012-08-28 01:50:20 +0800588 logging.info('EC console log after reboot:\n%s\n', ec_console_log)
Jon Salzfe1f6652012-09-07 05:40:14 +0800589 except: # pylint: disable=W0702
Vic Yange4c275d2012-08-28 01:50:20 +0800590 logging.exception('Error retrieving EC console log')
591
Vic Yang079f9872013-07-01 11:32:00 +0800592 if ec_panic_info is None:
593 try:
594 board = system.GetBoard()
595 ec_panic_info = board.GetECPanicInfo()
596 logging.info('EC panic info after reboot:\n%s\n', ec_panic_info)
597 except: # pylint: disable=W0702
598 logging.exception('Error retrieving EC panic info')
599
Jon Salz0697cbf2012-07-04 15:14:04 +0800600 error_msg = 'Unexpected shutdown while test was running'
601 self.event_log.Log('end_test',
602 path=test.path,
603 status=TestState.FAILED,
604 invocation=test.get_state().invocation,
605 error_msg=error_msg,
Vic Yanga9c32212012-08-16 20:07:54 +0800606 var_log_messages='\n'.join(var_log_messages),
607 mosys_log=mosys_log)
Jon Salz0697cbf2012-07-04 15:14:04 +0800608 test.update_state(
609 status=TestState.FAILED,
610 error_msg=error_msg)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800611
Jon Salz50efe942012-07-26 11:54:10 +0800612 if not test.never_fails:
613 # For "never_fails" tests (such as "Start"), don't cancel
614 # pending tests, since reboot is expected.
615 factory.console.info('Unexpected shutdown while test %s '
616 'running; cancelling any pending tests',
617 test.path)
618 self.state_instance.set_shared_data('tests_after_shutdown', [])
Jon Salz69806bb2012-07-20 18:05:02 +0800619
Jon Salz008f4ea2012-08-28 05:39:45 +0800620 self.update_skipped_tests()
621
622 def update_skipped_tests(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800623 """Updates skipped states based on run_if."""
Jon Salz885dcac2013-07-23 16:39:50 +0800624 env = TestArgEnv()
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800625 def _evaluate_skip_from_run_if(test):
626 """Returns the run_if evaluation of the test.
627
628 Args:
629 test: A FactoryTest object.
630
631 Returns:
632 The run_if evaluation result. Returns False if the test has no
633 run_if argument.
634 """
635 value = None
636 if test.run_if_expr:
637 try:
638 value = test.run_if_expr(env)
639 except: # pylint: disable=W0702
640 logging.exception('Unable to evaluate run_if expression for %s',
641 test.path)
642 # But keep going; we have no choice. This will end up
643 # always activating the test.
644 elif test.run_if_table_name:
645 try:
646 aux = shopfloor.get_selected_aux_data(test.run_if_table_name)
647 value = aux.get(test.run_if_col)
648 except ValueError:
649 # Not available; assume it shouldn't be skipped
650 pass
651
652 if value is None:
653 skip = False
654 else:
655 skip = (not value) ^ t.run_if_not
656 return skip
657
658 # Gets all run_if evaluation, and stores results in skip_map.
659 skip_map = dict()
Jon Salz008f4ea2012-08-28 05:39:45 +0800660 for t in self.test_list.walk():
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800661 skip_map[t.path] = _evaluate_skip_from_run_if(t)
Jon Salz885dcac2013-07-23 16:39:50 +0800662
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800663 # Propagates the skip value from root of tree and updates skip_map.
664 def _update_skip_map_from_node(test, skip_from_parent):
665 """Updates skip_map from a given node.
Jon Salz885dcac2013-07-23 16:39:50 +0800666
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800667 Given a FactoryTest node and the skip value from parent, updates the
668 skip value of current node in the skip_map if skip value from parent is
669 True. If this node has children, recursively propagate this value to all
670 its children, that is, all its subtests.
671 Note that this function only updates value in skip_map, not the actual
672 test_list tree.
Jon Salz008f4ea2012-08-28 05:39:45 +0800673
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800674 Args:
675 test: The given FactoryTest object. It is a node in the test_list tree.
676 skip_from_parent: The skip value which propagates from the parent of
677 input node.
678 """
679 skip_this_tree = skip_from_parent or skip_map[test.path]
680 if skip_this_tree:
681 logging.info('Skip from node %r', test.path)
682 skip_map[test.path] = True
683 if test.is_leaf():
684 return
685 # Propagates skip value to its subtests
686 for subtest in test.subtests:
687 _update_skip_map_from_node(subtest, skip_this_tree)
688
689 _update_skip_map_from_node(self.test_list, False)
690
691 # Updates the skip value from skip_map to test_list tree. Also, updates test
692 # status if needed.
693 for t in self.test_list.walk():
694 skip = skip_map[t.path]
695 test_state = t.get_state()
696 if ((not skip) and
697 (test_state.status == TestState.PASSED) and
698 (test_state.error_msg == TestState.SKIPPED_MSG)):
699 # It was marked as skipped before, but now we need to run it.
700 # Mark as untested.
701 t.update_state(skip=skip, status=TestState.UNTESTED, error_msg='')
702 else:
703 t.update_state(skip=skip)
Jon Salz008f4ea2012-08-28 05:39:45 +0800704
Jon Salz0697cbf2012-07-04 15:14:04 +0800705 def show_next_active_test(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800706 """Rotates to the next visible active test."""
Jon Salz0697cbf2012-07-04 15:14:04 +0800707 self.reap_completed_tests()
708 active_tests = [
709 t for t in self.test_list.walk()
710 if t.is_leaf() and t.get_state().status == TestState.ACTIVE]
711 if not active_tests:
712 return
Jon Salz4f6c7172012-06-11 20:45:36 +0800713
Jon Salz0697cbf2012-07-04 15:14:04 +0800714 try:
715 next_test = active_tests[
716 (active_tests.index(self.visible_test) + 1) % len(active_tests)]
717 except ValueError: # visible_test not present in active_tests
718 next_test = active_tests[0]
Jon Salz4f6c7172012-06-11 20:45:36 +0800719
Jon Salz0697cbf2012-07-04 15:14:04 +0800720 self.set_visible_test(next_test)
Jon Salz4f6c7172012-06-11 20:45:36 +0800721
Jon Salz0697cbf2012-07-04 15:14:04 +0800722 def handle_event(self, event):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800723 """Handles an event from the event server."""
Jon Salz0697cbf2012-07-04 15:14:04 +0800724 handler = self.event_handlers.get(event.type)
725 if handler:
726 handler(event)
727 else:
728 # We don't register handlers for all event types - just ignore
729 # this event.
730 logging.debug('Unbound event type %s', event.type)
Jon Salz4f6c7172012-06-11 20:45:36 +0800731
Vic Yangaabf9fd2013-04-09 18:56:13 +0800732 def check_critical_factory_note(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800733 """Returns True if the last factory note is critical."""
Vic Yangaabf9fd2013-04-09 18:56:13 +0800734 notes = self.state_instance.get_shared_data('factory_note', True)
735 return notes and notes[-1]['level'] == 'CRITICAL'
736
Jon Salz0697cbf2012-07-04 15:14:04 +0800737 def run_next_test(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800738 """Runs the next eligible test (or tests) in self.tests_to_run."""
Jon Salz0697cbf2012-07-04 15:14:04 +0800739 self.reap_completed_tests()
Vic Yangaabf9fd2013-04-09 18:56:13 +0800740 if self.tests_to_run and self.check_critical_factory_note():
741 self.tests_to_run.clear()
742 return
Jon Salz0697cbf2012-07-04 15:14:04 +0800743 while self.tests_to_run:
Ricky Liang6fe218c2013-12-27 15:17:17 +0800744 logging.debug('Tests to run: %s', [x.path for x in self.tests_to_run])
Jon Salz94eb56f2012-06-12 18:01:12 +0800745
Jon Salz0697cbf2012-07-04 15:14:04 +0800746 test = self.tests_to_run[0]
Jon Salz94eb56f2012-06-12 18:01:12 +0800747
Jon Salz0697cbf2012-07-04 15:14:04 +0800748 if test in self.invocations:
749 logging.info('Next test %s is already running', test.path)
750 self.tests_to_run.popleft()
751 return
Jon Salz94eb56f2012-06-12 18:01:12 +0800752
Jon Salza1412922012-07-23 16:04:17 +0800753 for requirement in test.require_run:
754 for i in requirement.test.walk():
755 if i.get_state().status == TestState.ACTIVE:
Jon Salz304a75d2012-07-06 11:14:15 +0800756 logging.info('Waiting for active test %s to complete '
Jon Salza1412922012-07-23 16:04:17 +0800757 'before running %s', i.path, test.path)
Jon Salz304a75d2012-07-06 11:14:15 +0800758 return
759
Jon Salz0697cbf2012-07-04 15:14:04 +0800760 if self.invocations and not (test.backgroundable and all(
761 [x.backgroundable for x in self.invocations])):
762 logging.debug('Waiting for non-backgroundable tests to '
Ricky Liang6fe218c2013-12-27 15:17:17 +0800763 'complete before running %s', test.path)
Jon Salz0697cbf2012-07-04 15:14:04 +0800764 return
Jon Salz94eb56f2012-06-12 18:01:12 +0800765
Jon Salz3e6f5202012-10-15 15:08:29 +0800766 if test.get_state().skip:
767 factory.console.info('Skipping test %s', test.path)
768 test.update_state(status=TestState.PASSED,
769 error_msg=TestState.SKIPPED_MSG)
770 self.tests_to_run.popleft()
771 continue
772
Jon Salz0697cbf2012-07-04 15:14:04 +0800773 self.tests_to_run.popleft()
Jon Salz94eb56f2012-06-12 18:01:12 +0800774
Jon Salz304a75d2012-07-06 11:14:15 +0800775 untested = set()
Jon Salza1412922012-07-23 16:04:17 +0800776 for requirement in test.require_run:
777 for i in requirement.test.walk():
778 if i == test:
Jon Salz304a75d2012-07-06 11:14:15 +0800779 # We've hit this test itself; stop checking
780 break
Jon Salza1412922012-07-23 16:04:17 +0800781 if ((i.get_state().status == TestState.UNTESTED) or
782 (requirement.passed and i.get_state().status !=
783 TestState.PASSED)):
Jon Salz304a75d2012-07-06 11:14:15 +0800784 # Found an untested test; move on to the next
785 # element in require_run.
Jon Salza1412922012-07-23 16:04:17 +0800786 untested.add(i)
Jon Salz304a75d2012-07-06 11:14:15 +0800787 break
788
789 if untested:
790 untested_paths = ', '.join(sorted([x.path for x in untested]))
791 if self.state_instance.get_shared_data('engineering_mode',
792 optional=True):
793 # In engineering mode, we'll let it go.
794 factory.console.warn('In engineering mode; running '
795 '%s even though required tests '
796 '[%s] have not completed',
797 test.path, untested_paths)
798 else:
799 # Not in engineering mode; mark it failed.
800 error_msg = ('Required tests [%s] have not been run yet'
801 % untested_paths)
802 factory.console.error('Not running %s: %s',
803 test.path, error_msg)
804 test.update_state(status=TestState.FAILED,
805 error_msg=error_msg)
806 continue
807
Jon Salz0697cbf2012-07-04 15:14:04 +0800808 if isinstance(test, factory.ShutdownStep):
809 if os.path.exists(NO_REBOOT_FILE):
810 test.update_state(
Ricky Liang6fe218c2013-12-27 15:17:17 +0800811 status=TestState.FAILED, increment_count=1,
812 error_msg=('Skipped shutdown since %s is present' %
813 NO_REBOOT_FILE))
814 continue
815
816 if (test.operation == factory.ShutdownStep.HALT and
817 self.options.automation_mode == AutomationMode.FULL):
818 logging.info('Skip halt in full automation mode.')
819 test.update_state(status=TestState.PASSED)
Jon Salz0697cbf2012-07-04 15:14:04 +0800820 continue
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800821
Jon Salz0697cbf2012-07-04 15:14:04 +0800822 test.update_state(status=TestState.ACTIVE, increment_count=1,
Ricky Liang6fe218c2013-12-27 15:17:17 +0800823 error_msg='', shutdown_count=0)
Jon Salz0697cbf2012-07-04 15:14:04 +0800824 if self._prompt_cancel_shutdown(test, 1):
825 self.event_log.Log('reboot_cancelled')
826 test.update_state(
Ricky Liang6fe218c2013-12-27 15:17:17 +0800827 status=TestState.FAILED, increment_count=1,
828 error_msg='Shutdown aborted by operator',
829 shutdown_count=0)
chungyiafe8f772012-08-15 19:36:29 +0800830 continue
Jon Salz2f757d42012-06-27 17:06:42 +0800831
Jon Salz0697cbf2012-07-04 15:14:04 +0800832 # Save pending test list in the state server
Jon Salzdbf398f2012-06-14 17:30:01 +0800833 self.state_instance.set_shared_data(
Ricky Liang6fe218c2013-12-27 15:17:17 +0800834 'tests_after_shutdown',
835 [t.path for t in self.tests_to_run])
Jon Salz0697cbf2012-07-04 15:14:04 +0800836 # Save shutdown time
Ricky Liang6fe218c2013-12-27 15:17:17 +0800837 self.state_instance.set_shared_data('shutdown_time', time.time())
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800838
Jon Salz0697cbf2012-07-04 15:14:04 +0800839 with self.env.lock:
840 self.event_log.Log('shutdown', operation=test.operation)
Ricky Liang8c2c6c32013-11-02 23:02:44 +0800841 if (test.enable_guest_mode and
842 not os.path.exists(
843 test_environment.DUTEnvironment.GUEST_MODE_TAG_FILE)):
844 # Create a temporary file GUEST_MODE_TAG_FILE to enable guest mode
845 # on next boot.
846 os.mknod(test_environment.DUTEnvironment.GUEST_MODE_TAG_FILE)
Jon Salz0697cbf2012-07-04 15:14:04 +0800847 shutdown_result = self.env.shutdown(test.operation)
848 if shutdown_result:
849 # That's all, folks!
850 self.run_queue.put(None)
851 return
852 else:
853 # Just pass (e.g., in the chroot).
854 test.update_state(status=TestState.PASSED)
Ricky Liang6fe218c2013-12-27 15:17:17 +0800855 self.state_instance.set_shared_data('tests_after_shutdown', None)
Jon Salz0697cbf2012-07-04 15:14:04 +0800856 # Send event with no fields to indicate that there is no
857 # longer a pending shutdown.
Ricky Liang6fe218c2013-12-27 15:17:17 +0800858 self.event_client.post_event(Event(Event.Type.PENDING_SHUTDOWN))
Jon Salz0697cbf2012-07-04 15:14:04 +0800859 continue
Jon Salz258a40c2012-04-19 12:34:01 +0800860
Cheng-Yi Chiangce05c002013-04-04 02:13:17 +0800861 self._run_test(test, test.iterations, test.retries)
Jon Salz1acc8742012-07-17 17:45:55 +0800862
Cheng-Yi Chiangce05c002013-04-04 02:13:17 +0800863 def _run_test(self, test, iterations_left=None, retries_left=None):
Jon Salz1acc8742012-07-17 17:45:55 +0800864 invoc = TestInvocation(self, test, on_completion=self.run_next_test)
865 new_state = test.update_state(
866 status=TestState.ACTIVE, increment_count=1, error_msg='',
Jon Salzbd42ce12012-09-18 08:03:59 +0800867 invocation=invoc.uuid, iterations_left=iterations_left,
Cheng-Yi Chiangce05c002013-04-04 02:13:17 +0800868 retries_left=retries_left,
Jon Salzbd42ce12012-09-18 08:03:59 +0800869 visible=(self.visible_test == test))
Jon Salz1acc8742012-07-17 17:45:55 +0800870 invoc.count = new_state.count
871
872 self.invocations[test] = invoc
873 if self.visible_test is None and test.has_ui:
874 self.set_visible_test(test)
Vic Yang311ddb82012-09-26 12:08:28 +0800875 self.check_exclusive()
Jon Salz1acc8742012-07-17 17:45:55 +0800876 invoc.start()
Jon Salz5f2a0672012-05-22 17:14:06 +0800877
Vic Yang311ddb82012-09-26 12:08:28 +0800878 def check_exclusive(self):
Jon Salzce6a7f82013-06-10 18:22:54 +0800879 # alias since this is really long
880 EXCL_OPT = factory.FactoryTest.EXCLUSIVE_OPTIONS
881
Vic Yang311ddb82012-09-26 12:08:28 +0800882 current_exclusive_items = set([
Jon Salzce6a7f82013-06-10 18:22:54 +0800883 item for item in EXCL_OPT
Vic Yang311ddb82012-09-26 12:08:28 +0800884 if any([test.is_exclusive(item) for test in self.invocations])])
885
886 new_exclusive_items = current_exclusive_items - self.exclusive_items
Jon Salzce6a7f82013-06-10 18:22:54 +0800887 if EXCL_OPT.NETWORKING in new_exclusive_items:
Vic Yang311ddb82012-09-26 12:08:28 +0800888 logging.info('Disabling network')
889 self.connection_manager.DisableNetworking()
Jon Salzce6a7f82013-06-10 18:22:54 +0800890 if EXCL_OPT.CHARGER in new_exclusive_items:
Vic Yang311ddb82012-09-26 12:08:28 +0800891 logging.info('Stop controlling charger')
892
893 new_non_exclusive_items = self.exclusive_items - current_exclusive_items
Jon Salzce6a7f82013-06-10 18:22:54 +0800894 if EXCL_OPT.NETWORKING in new_non_exclusive_items:
Vic Yang311ddb82012-09-26 12:08:28 +0800895 logging.info('Re-enabling network')
896 self.connection_manager.EnableNetworking()
Jon Salzce6a7f82013-06-10 18:22:54 +0800897 if EXCL_OPT.CHARGER in new_non_exclusive_items:
Vic Yang311ddb82012-09-26 12:08:28 +0800898 logging.info('Start controlling charger')
899
Jon Salzce6a7f82013-06-10 18:22:54 +0800900 if self.cpufreq_manager:
901 enabled = EXCL_OPT.CPUFREQ not in current_exclusive_items
902 try:
903 self.cpufreq_manager.SetEnabled(enabled)
904 except: # pylint: disable=W0702
905 logging.exception('Unable to %s cpufreq services',
906 'enable' if enabled else 'disable')
907
Vic Yang311ddb82012-09-26 12:08:28 +0800908 # Only adjust charge state if not excluded
Jon Salzce6a7f82013-06-10 18:22:54 +0800909 if (EXCL_OPT.CHARGER not in current_exclusive_items and
910 not utils.in_chroot()):
Cheng-Yi Chiangd8186952013-04-04 23:41:14 +0800911 if self.charge_manager:
912 self.charge_manager.AdjustChargeState()
913 else:
914 try:
915 system.GetBoard().SetChargeState(Board.ChargeState.CHARGE)
916 except BoardException:
917 logging.exception('Unable to set charge state on this board')
Vic Yang311ddb82012-09-26 12:08:28 +0800918
919 self.exclusive_items = current_exclusive_items
Jon Salz5da61e62012-05-31 13:06:22 +0800920
cychiang21886742012-07-05 15:16:32 +0800921 def check_for_updates(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800922 """Schedules an asynchronous check for updates if necessary."""
cychiang21886742012-07-05 15:16:32 +0800923 if not self.test_list.options.update_period_secs:
924 # Not enabled.
925 return
926
927 now = time.time()
928 if self.last_update_check and (
929 now - self.last_update_check <
930 self.test_list.options.update_period_secs):
931 # Not yet time for another check.
932 return
933
934 self.last_update_check = now
935
936 def handle_check_for_update(reached_shopfloor, md5sum, needs_update):
937 if reached_shopfloor:
938 new_update_md5sum = md5sum if needs_update else None
939 if system.SystemInfo.update_md5sum != new_update_md5sum:
940 logging.info('Received new update MD5SUM: %s', new_update_md5sum)
941 system.SystemInfo.update_md5sum = new_update_md5sum
942 self.run_queue.put(self.update_system_info)
943
944 updater.CheckForUpdateAsync(
945 handle_check_for_update,
946 self.test_list.options.shopfloor_timeout_secs)
947
Jon Salza6711d72012-07-18 14:33:03 +0800948 def cancel_pending_tests(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800949 """Cancels any tests in the run queue."""
Jon Salza6711d72012-07-18 14:33:03 +0800950 self.run_tests([])
951
Ricky Liang4bff3e32014-02-20 18:46:11 +0800952 def restore_active_run_state(self):
953 """Restores active run id and the list of scheduled tests."""
954 self.run_id = self.state_instance.get_shared_data('run_id', optional=True)
955 self.scheduled_run_tests = self.state_instance.get_shared_data(
956 'scheduled_run_tests', optional=True)
957
958 def set_active_run_state(self):
959 """Sets active run id and the list of scheduled tests."""
960 self.run_id = str(uuid.uuid4())
961 self.scheduled_run_tests = [test.path for test in self.tests_to_run]
962 self.state_instance.set_shared_data('run_id', self.run_id)
963 self.state_instance.set_shared_data('scheduled_run_tests',
964 self.scheduled_run_tests)
965
Jon Salz0697cbf2012-07-04 15:14:04 +0800966 def run_tests(self, subtrees, untested_only=False):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800967 """Runs tests under subtree.
Jon Salz258a40c2012-04-19 12:34:01 +0800968
Jon Salz0697cbf2012-07-04 15:14:04 +0800969 The tests are run in order unless one fails (then stops).
970 Backgroundable tests are run simultaneously; when a foreground test is
971 encountered, we wait for all active tests to finish before continuing.
Jon Salzb1b39092012-05-03 02:05:09 +0800972
Ricky Liang6fe218c2013-12-27 15:17:17 +0800973 Args:
974 subtrees: Node or nodes containing tests to run (may either be
975 a single test or a list). Duplicates will be ignored.
976 untested_only: True to run untested tests only.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800977 """
Jon Salz0697cbf2012-07-04 15:14:04 +0800978 if type(subtrees) != list:
979 subtrees = [subtrees]
Jon Salz258a40c2012-04-19 12:34:01 +0800980
Jon Salz0697cbf2012-07-04 15:14:04 +0800981 # Nodes we've seen so far, to avoid duplicates.
982 seen = set()
Jon Salz94eb56f2012-06-12 18:01:12 +0800983
Jon Salz0697cbf2012-07-04 15:14:04 +0800984 self.tests_to_run = deque()
985 for subtree in subtrees:
986 for test in subtree.walk():
987 if test in seen:
988 continue
989 seen.add(test)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800990
Jon Salz0697cbf2012-07-04 15:14:04 +0800991 if not test.is_leaf():
992 continue
Ricky Liang4bff3e32014-02-20 18:46:11 +0800993 if (untested_only and test.get_state().status != TestState.UNTESTED):
Jon Salz0697cbf2012-07-04 15:14:04 +0800994 continue
995 self.tests_to_run.append(test)
Ricky Liang4bff3e32014-02-20 18:46:11 +0800996 if subtrees:
997 self.set_active_run_state()
Jon Salz0697cbf2012-07-04 15:14:04 +0800998 self.run_next_test()
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800999
Jon Salz0697cbf2012-07-04 15:14:04 +08001000 def reap_completed_tests(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001001 """Removes completed tests from the set of active tests.
Jon Salz0697cbf2012-07-04 15:14:04 +08001002
1003 Also updates the visible test if it was reaped.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001004 """
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +08001005 test_completed = False
Jon Salz0697cbf2012-07-04 15:14:04 +08001006 for t, v in dict(self.invocations).iteritems():
1007 if v.is_completed():
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +08001008 test_completed = True
Jon Salz1acc8742012-07-17 17:45:55 +08001009 new_state = t.update_state(**v.update_state_on_completion)
Jon Salz0697cbf2012-07-04 15:14:04 +08001010 del self.invocations[t]
1011
Chun-Ta Lin54e17e42012-09-06 22:05:13 +08001012 # Stop on failure if flag is true.
1013 if (self.test_list.options.stop_on_failure and
1014 new_state.status == TestState.FAILED):
1015 # Clean all the tests to cause goofy to stop.
1016 self.tests_to_run = []
1017 factory.console.info("Stop on failure triggered. Empty the queue.")
1018
Jon Salz1acc8742012-07-17 17:45:55 +08001019 if new_state.iterations_left and new_state.status == TestState.PASSED:
1020 # Play it again, Sam!
1021 self._run_test(t)
Cheng-Yi Chiangce05c002013-04-04 02:13:17 +08001022 # new_state.retries_left is obtained after update.
1023 # For retries_left == 0, test can still be run for the last time.
1024 elif (new_state.retries_left >= 0 and
1025 new_state.status == TestState.FAILED):
1026 # Still have to retry, Sam!
1027 self._run_test(t)
Jon Salz1acc8742012-07-17 17:45:55 +08001028
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +08001029 if test_completed:
Vic Yangf01c59f2013-04-19 17:37:56 +08001030 self.log_watcher.KickWatchThread()
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +08001031
Jon Salz0697cbf2012-07-04 15:14:04 +08001032 if (self.visible_test is None or
Jon Salz85a39882012-07-05 16:45:04 +08001033 self.visible_test not in self.invocations):
Jon Salz0697cbf2012-07-04 15:14:04 +08001034 self.set_visible_test(None)
1035 # Make the first running test, if any, the visible test
1036 for t in self.test_list.walk():
1037 if t in self.invocations:
1038 self.set_visible_test(t)
1039 break
1040
Jon Salz6dc031d2013-06-19 13:06:23 +08001041 def kill_active_tests(self, abort, root=None, reason=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001042 """Kills and waits for all active tests.
Jon Salz0697cbf2012-07-04 15:14:04 +08001043
Jon Salz85a39882012-07-05 16:45:04 +08001044 Args:
1045 abort: True to change state of killed tests to FAILED, False for
Jon Salz0697cbf2012-07-04 15:14:04 +08001046 UNTESTED.
Jon Salz85a39882012-07-05 16:45:04 +08001047 root: If set, only kills tests with root as an ancestor.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001048 reason: If set, the abort reason.
1049 """
Jon Salz0697cbf2012-07-04 15:14:04 +08001050 self.reap_completed_tests()
1051 for test, invoc in self.invocations.items():
Jon Salz85a39882012-07-05 16:45:04 +08001052 if root and not test.has_ancestor(root):
1053 continue
1054
Jon Salz0697cbf2012-07-04 15:14:04 +08001055 factory.console.info('Killing active test %s...' % test.path)
Jon Salz6dc031d2013-06-19 13:06:23 +08001056 invoc.abort_and_join(reason)
Jon Salz0697cbf2012-07-04 15:14:04 +08001057 factory.console.info('Killed %s' % test.path)
Jon Salz1acc8742012-07-17 17:45:55 +08001058 test.update_state(**invoc.update_state_on_completion)
Jon Salz0697cbf2012-07-04 15:14:04 +08001059 del self.invocations[test]
Jon Salz1acc8742012-07-17 17:45:55 +08001060
Jon Salz0697cbf2012-07-04 15:14:04 +08001061 if not abort:
1062 test.update_state(status=TestState.UNTESTED)
1063 self.reap_completed_tests()
1064
Jon Salz6dc031d2013-06-19 13:06:23 +08001065 def stop(self, root=None, fail=False, reason=None):
1066 self.kill_active_tests(fail, root, reason)
Jon Salz85a39882012-07-05 16:45:04 +08001067 # Remove any tests in the run queue under the root.
1068 self.tests_to_run = deque([x for x in self.tests_to_run
1069 if root and not x.has_ancestor(root)])
1070 self.run_next_test()
Jon Salz0697cbf2012-07-04 15:14:04 +08001071
Jon Salz4712ac72013-02-07 17:12:05 +08001072 def clear_state(self, root=None):
Jon Salzd7550792013-07-12 05:49:27 +08001073 if root is None:
1074 root = self.test_list
Jon Salz6dc031d2013-06-19 13:06:23 +08001075 self.stop(root, reason='Clearing test state')
Jon Salz4712ac72013-02-07 17:12:05 +08001076 for f in root.walk():
1077 if f.is_leaf():
1078 f.update_state(status=TestState.UNTESTED)
1079
Jon Salz6dc031d2013-06-19 13:06:23 +08001080 def abort_active_tests(self, reason=None):
1081 self.kill_active_tests(True, reason=reason)
Jon Salz0697cbf2012-07-04 15:14:04 +08001082
1083 def main(self):
Jon Salzeff94182013-06-19 15:06:28 +08001084 syslog.openlog('goofy')
1085
Jon Salz0697cbf2012-07-04 15:14:04 +08001086 try:
Jon Salzd7550792013-07-12 05:49:27 +08001087 self.status = Status.INITIALIZING
Jon Salz0697cbf2012-07-04 15:14:04 +08001088 self.init()
1089 self.event_log.Log('goofy_init',
1090 success=True)
1091 except:
1092 if self.event_log:
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001093 try:
Jon Salz0697cbf2012-07-04 15:14:04 +08001094 self.event_log.Log('goofy_init',
1095 success=False,
1096 trace=traceback.format_exc())
1097 except: # pylint: disable=W0702
1098 pass
1099 raise
1100
Jon Salzd7550792013-07-12 05:49:27 +08001101 self.status = Status.RUNNING
Jon Salzeff94182013-06-19 15:06:28 +08001102 syslog.syslog('Goofy (factory test harness) starting')
Jon Salz0697cbf2012-07-04 15:14:04 +08001103 self.run()
1104
1105 def update_system_info(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001106 """Updates system info."""
Jon Salz0697cbf2012-07-04 15:14:04 +08001107 system_info = system.SystemInfo()
1108 self.state_instance.set_shared_data('system_info', system_info.__dict__)
1109 self.event_client.post_event(Event(Event.Type.SYSTEM_INFO,
1110 system_info=system_info.__dict__))
1111 logging.info('System info: %r', system_info.__dict__)
1112
Jon Salzeb42f0d2012-07-27 19:14:04 +08001113 def update_factory(self, auto_run_on_restart=False, post_update_hook=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001114 """Commences updating factory software.
Jon Salzeb42f0d2012-07-27 19:14:04 +08001115
1116 Args:
1117 auto_run_on_restart: Auto-run when the machine comes back up.
1118 post_update_hook: Code to call after update but immediately before
1119 restart.
1120
1121 Returns:
1122 Never if the update was successful (we just reboot).
1123 False if the update was unnecessary (no update available).
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001124 """
Jon Salz6dc031d2013-06-19 13:06:23 +08001125 self.kill_active_tests(False, reason='Factory software update')
Jon Salza6711d72012-07-18 14:33:03 +08001126 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +08001127
Jon Salz5c344f62012-07-13 14:31:16 +08001128 def pre_update_hook():
1129 if auto_run_on_restart:
1130 self.state_instance.set_shared_data('tests_after_shutdown',
1131 FORCE_AUTO_RUN)
1132 self.state_instance.close()
1133
Jon Salzeb42f0d2012-07-27 19:14:04 +08001134 if updater.TryUpdate(pre_update_hook=pre_update_hook):
1135 if post_update_hook:
1136 post_update_hook()
1137 self.env.shutdown('reboot')
Jon Salz0697cbf2012-07-04 15:14:04 +08001138
Jon Salzcef132a2012-08-30 04:58:08 +08001139 def handle_sigint(self, dummy_signum, dummy_frame):
Jon Salz77c151e2012-08-28 07:20:37 +08001140 logging.error('Received SIGINT')
1141 self.run_queue.put(None)
1142 raise KeyboardInterrupt()
1143
Jon Salze12c2b32013-06-25 16:24:34 +08001144 def find_kcrashes(self):
1145 """Finds kcrash files, logs them, and marks them as seen."""
1146 seen_crashes = set(
1147 self.state_instance.get_shared_data('seen_crashes', optional=True)
1148 or [])
1149
1150 for path in glob.glob('/var/spool/crash/*'):
1151 if not os.path.isfile(path):
1152 continue
1153 if path in seen_crashes:
1154 continue
1155 try:
1156 stat = os.stat(path)
1157 mtime = utils.TimeString(stat.st_mtime)
1158 logging.info(
1159 'Found new crash file %s (%d bytes at %s)',
1160 path, stat.st_size, mtime)
1161 extra_log_args = {}
1162
1163 try:
1164 _, ext = os.path.splitext(path)
1165 if ext in ['.kcrash', '.meta']:
1166 ext = ext.replace('.', '')
1167 with open(path) as f:
1168 data = f.read(MAX_CRASH_FILE_SIZE)
1169 tell = f.tell()
1170 logging.info(
1171 'Contents of %s%s:%s',
1172 path,
1173 ('' if tell == stat.st_size
1174 else '(truncated to %d bytes)' % MAX_CRASH_FILE_SIZE),
1175 ('\n' + data).replace('\n', '\n ' + ext + '> '))
1176 extra_log_args['data'] = data
1177
1178 # Copy to /var/factory/kcrash for posterity
1179 kcrash_dir = factory.get_factory_root('kcrash')
1180 utils.TryMakeDirs(kcrash_dir)
1181 shutil.copy(path, kcrash_dir)
1182 logging.info('Copied to %s',
1183 os.path.join(kcrash_dir, os.path.basename(path)))
1184 finally:
1185 # Even if something goes wrong with the above, still try to
1186 # log to event log
1187 self.event_log.Log('crash_file',
1188 path=path, size=stat.st_size, mtime=mtime,
1189 **extra_log_args)
1190 except: # pylint: disable=W0702
1191 logging.exception('Unable to handle crash files %s', path)
1192 seen_crashes.add(path)
1193
1194 self.state_instance.set_shared_data('seen_crashes', list(seen_crashes))
1195
Jon Salz128b0932013-07-03 16:55:26 +08001196 def GetTestList(self, test_list_id):
1197 """Returns the test list with the given ID.
1198
1199 Raises:
1200 TestListError: The test list ID is not valid.
1201 """
1202 try:
1203 return self.test_lists[test_list_id]
1204 except KeyError:
1205 raise test_lists.TestListError(
1206 '%r is not a valid test list ID (available IDs are [%s])' % (
1207 test_list_id, ', '.join(sorted(self.test_lists.keys()))))
1208
1209 def InitTestLists(self):
1210 """Reads in all test lists and sets the active test list."""
1211 self.test_lists = test_lists.BuildAllTestLists()
Jon Salzd7550792013-07-12 05:49:27 +08001212 logging.info('Loaded test lists: [%s]',
1213 test_lists.DescribeTestLists(self.test_lists))
Jon Salz128b0932013-07-03 16:55:26 +08001214
1215 if not self.options.test_list:
1216 self.options.test_list = test_lists.GetActiveTestListId()
1217
1218 if os.sep in self.options.test_list:
1219 # It's a path pointing to an old-style test list; use it.
1220 self.test_list = factory.read_test_list(self.options.test_list)
1221 else:
1222 self.test_list = self.GetTestList(self.options.test_list)
1223
1224 logging.info('Active test list: %s', self.test_list.test_list_id)
1225
1226 if isinstance(self.test_list, test_lists.OldStyleTestList):
1227 # Actually load it in. (See OldStyleTestList for an explanation
1228 # of why this is necessary.)
1229 self.test_list = self.test_list.Load()
1230
1231 self.test_list.state_instance = self.state_instance
1232
Shuo-Peng Liao268b40b2013-07-01 15:58:59 +08001233 def init_hooks(self):
1234 """Initializes hooks.
1235
1236 Must run after self.test_list ready.
1237 """
Shuo-Peng Liao52b90da2013-06-30 17:00:06 +08001238 module, cls = self.test_list.options.hooks_class.rsplit('.', 1)
1239 self.hooks = getattr(__import__(module, fromlist=[cls]), cls)()
1240 assert isinstance(self.hooks, factory.Hooks), (
1241 "hooks should be of type Hooks but is %r" % type(self.hooks))
1242 self.hooks.test_list = self.test_list
Shuo-Peng Liao268b40b2013-07-01 15:58:59 +08001243 self.hooks.OnCreatedTestList()
Shuo-Peng Liao52b90da2013-06-30 17:00:06 +08001244
Jon Salz0697cbf2012-07-04 15:14:04 +08001245 def init(self, args=None, env=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001246 """Initializes Goofy.
Jon Salz0697cbf2012-07-04 15:14:04 +08001247
1248 Args:
1249 args: A list of command-line arguments. Uses sys.argv if
1250 args is None.
1251 env: An Environment instance to use (or None to choose
1252 FakeChrootEnvironment or DUTEnvironment as appropriate).
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001253 """
Jon Salz77c151e2012-08-28 07:20:37 +08001254 signal.signal(signal.SIGINT, self.handle_sigint)
1255
Jon Salz0697cbf2012-07-04 15:14:04 +08001256 parser = OptionParser()
1257 parser.add_option('-v', '--verbose', dest='verbose',
Jon Salz8fa8e832012-07-13 19:04:09 +08001258 action='store_true',
1259 help='Enable debug logging')
Jon Salz0697cbf2012-07-04 15:14:04 +08001260 parser.add_option('--print_test_list', dest='print_test_list',
Jon Salz8fa8e832012-07-13 19:04:09 +08001261 metavar='FILE',
1262 help='Read and print test list FILE, and exit')
Jon Salz0697cbf2012-07-04 15:14:04 +08001263 parser.add_option('--restart', dest='restart',
Jon Salz8fa8e832012-07-13 19:04:09 +08001264 action='store_true',
1265 help='Clear all test state')
Jon Salz0697cbf2012-07-04 15:14:04 +08001266 parser.add_option('--ui', dest='ui', type='choice',
Jon Salz8fa8e832012-07-13 19:04:09 +08001267 choices=['none', 'gtk', 'chrome'],
Jon Salz2f881df2013-02-01 17:00:35 +08001268 default='chrome',
Jon Salz8fa8e832012-07-13 19:04:09 +08001269 help='UI to use')
Jon Salz0697cbf2012-07-04 15:14:04 +08001270 parser.add_option('--ui_scale_factor', dest='ui_scale_factor',
Jon Salz8fa8e832012-07-13 19:04:09 +08001271 type='int', default=1,
1272 help=('Factor by which to scale UI '
1273 '(Chrome UI only)'))
Jon Salz0697cbf2012-07-04 15:14:04 +08001274 parser.add_option('--test_list', dest='test_list',
Jon Salz8fa8e832012-07-13 19:04:09 +08001275 metavar='FILE',
1276 help='Use FILE as test list')
Jon Salzc79a9982012-08-30 04:42:01 +08001277 parser.add_option('--dummy_shopfloor', action='store_true',
1278 help='Use a dummy shopfloor server')
Ricky Liang6fe218c2013-12-27 15:17:17 +08001279 parser.add_option('--automation-mode',
1280 choices=[m.lower() for m in AutomationMode],
1281 default='none', help="Factory test automation mode.")
Ricky Liang8c2c6c32013-11-02 23:02:44 +08001282 parser.add_option('--guest_login', dest='guest_login', default=False,
Ricky Liangb2432362013-10-02 13:12:41 +08001283 action='store_true',
Ricky Liang8c2c6c32013-11-02 23:02:44 +08001284 help='Log in as guest. This will not own the TPM.')
Jon Salz0697cbf2012-07-04 15:14:04 +08001285 (self.options, self.args) = parser.parse_args(args)
1286
Jon Salz46b89562012-07-05 11:49:22 +08001287 # Make sure factory directories exist.
1288 factory.get_log_root()
1289 factory.get_state_root()
1290 factory.get_test_data_root()
1291
Jon Salz0697cbf2012-07-04 15:14:04 +08001292 global _inited_logging # pylint: disable=W0603
1293 if not _inited_logging:
1294 factory.init_logging('goofy', verbose=self.options.verbose)
1295 _inited_logging = True
Jon Salz8fa8e832012-07-13 19:04:09 +08001296
Jon Salz0f996602012-10-03 15:26:48 +08001297 if self.options.print_test_list:
1298 print factory.read_test_list(
1299 self.options.print_test_list).__repr__(recursive=True)
1300 sys.exit(0)
1301
Jon Salzee85d522012-07-17 14:34:46 +08001302 event_log.IncrementBootSequence()
Jon Salzd15bbcf2013-05-21 17:33:57 +08001303 # Don't defer logging the initial event, so we can make sure
1304 # that device_id, reimage_id, etc. are all set up.
1305 self.event_log = EventLog('goofy', defer=False)
Jon Salz0697cbf2012-07-04 15:14:04 +08001306
1307 if (not suppress_chroot_warning and
1308 factory.in_chroot() and
1309 self.options.ui == 'gtk' and
1310 os.environ.get('DISPLAY') in [None, '', ':0', ':0.0']):
1311 # That's not going to work! Tell the user how to run
1312 # this way.
1313 logging.warn(GOOFY_IN_CHROOT_WARNING)
1314 time.sleep(1)
1315
1316 if env:
1317 self.env = env
1318 elif factory.in_chroot():
1319 self.env = test_environment.FakeChrootEnvironment()
1320 logging.warn(
1321 'Using chroot environment: will not actually run autotests')
1322 else:
Ricky Liang8c2c6c32013-11-02 23:02:44 +08001323 if self.options.guest_login:
1324 os.mknod(test_environment.DUTEnvironment.GUEST_MODE_TAG_FILE)
1325 self.env = test_environment.DUTEnvironment()
Jon Salz0697cbf2012-07-04 15:14:04 +08001326 self.env.goofy = self
1327
1328 if self.options.restart:
1329 state.clear_state()
1330
Jon Salz0697cbf2012-07-04 15:14:04 +08001331 if self.options.ui_scale_factor != 1 and utils.in_qemu():
1332 logging.warn(
1333 'In QEMU; ignoring ui_scale_factor argument')
1334 self.options.ui_scale_factor = 1
1335
1336 logging.info('Started')
1337
1338 self.start_state_server()
1339 self.state_instance.set_shared_data('hwid_cfg', get_hwid_cfg())
1340 self.state_instance.set_shared_data('ui_scale_factor',
Ricky Liang09216dc2013-02-22 17:26:45 +08001341 self.options.ui_scale_factor)
Jon Salz0697cbf2012-07-04 15:14:04 +08001342 self.last_shutdown_time = (
1343 self.state_instance.get_shared_data('shutdown_time', optional=True))
1344 self.state_instance.del_shared_data('shutdown_time', optional=True)
Jon Salzb19ea072013-02-07 16:35:00 +08001345 self.state_instance.del_shared_data('startup_error', optional=True)
Jon Salz0697cbf2012-07-04 15:14:04 +08001346
Ricky Liang6fe218c2013-12-27 15:17:17 +08001347 self.options.automation_mode = ParseAutomationMode(
1348 self.options.automation_mode)
1349 self.state_instance.set_shared_data('automation_mode',
1350 self.options.automation_mode)
1351 self.state_instance.set_shared_data(
1352 'automation_mode_prompt',
1353 AutomationModePrompt[self.options.automation_mode])
1354
Jon Salz128b0932013-07-03 16:55:26 +08001355 try:
1356 self.InitTestLists()
1357 except: # pylint: disable=W0702
1358 logging.exception('Unable to initialize test lists')
1359 self.state_instance.set_shared_data(
1360 'startup_error',
1361 'Unable to initialize test lists\n%s' % (
1362 traceback.format_exc()))
Jon Salzb19ea072013-02-07 16:35:00 +08001363 if self.options.ui == 'chrome':
1364 # Create an empty test list with default options so that the rest of
1365 # startup can proceed.
1366 self.test_list = factory.FactoryTestList(
1367 [], self.state_instance, factory.Options())
1368 else:
1369 # Bail with an error; no point in starting up.
1370 sys.exit('No valid test list; exiting.')
1371
Shuo-Peng Liao268b40b2013-07-01 15:58:59 +08001372 self.init_hooks()
1373
Jon Salz822838b2013-03-25 17:32:33 +08001374 if self.test_list.options.clear_state_on_start:
1375 self.state_instance.clear_test_state()
1376
Vic Yang3e1cf5d2013-06-05 18:50:24 +08001377 if system.SystemInfo().firmware_version is None and not utils.in_chroot():
Vic Yang9bd4f772013-06-04 17:34:00 +08001378 self.state_instance.set_shared_data('startup_error',
1379 'Netboot firmware detected\n'
1380 'Connect Ethernet and reboot to re-image.\n'
1381 u'侦测到网路开机固件\n'
1382 u'请连接乙太网并重启')
1383
Jon Salz0697cbf2012-07-04 15:14:04 +08001384 if not self.state_instance.has_shared_data('ui_lang'):
1385 self.state_instance.set_shared_data('ui_lang',
1386 self.test_list.options.ui_lang)
1387 self.state_instance.set_shared_data(
1388 'test_list_options',
1389 self.test_list.options.__dict__)
1390 self.state_instance.test_list = self.test_list
1391
Cheng-Yi Chiang39d32ad2013-07-23 15:02:38 +08001392 self.check_log_rotation()
Jon Salz83ef34b2012-11-01 19:46:35 +08001393
Jon Salz23926422012-09-01 03:38:13 +08001394 if self.options.dummy_shopfloor:
1395 os.environ[shopfloor.SHOPFLOOR_SERVER_ENV_VAR_NAME] = (
1396 'http://localhost:%d/' % shopfloor.DEFAULT_SERVER_PORT)
1397 self.dummy_shopfloor = Spawn(
1398 [os.path.join(factory.FACTORY_PATH, 'bin', 'shopfloor_server'),
1399 '--dummy'])
1400 elif self.test_list.options.shopfloor_server_url:
1401 shopfloor.set_server_url(self.test_list.options.shopfloor_server_url)
Jon Salz2bf2f6b2013-03-28 18:49:26 +08001402 shopfloor.set_enabled(True)
Jon Salz23926422012-09-01 03:38:13 +08001403
Jon Salz0f996602012-10-03 15:26:48 +08001404 if self.test_list.options.time_sanitizer and not utils.in_chroot():
Jon Salz8fa8e832012-07-13 19:04:09 +08001405 self.time_sanitizer = time_sanitizer.TimeSanitizer(
1406 base_time=time_sanitizer.GetBaseTimeFromFile(
1407 # lsb-factory is written by the factory install shim during
1408 # installation, so it should have a good time obtained from
Jon Salz54882d02012-08-31 01:57:54 +08001409 # the mini-Omaha server. If it's not available, we'll use
1410 # /etc/lsb-factory (which will be much older, but reasonably
1411 # sane) and rely on a shopfloor sync to set a more accurate
1412 # time.
1413 '/usr/local/etc/lsb-factory',
1414 '/etc/lsb-release'))
Jon Salz8fa8e832012-07-13 19:04:09 +08001415 self.time_sanitizer.RunOnce()
1416
Vic Yangd8990da2013-06-27 16:57:43 +08001417 if self.test_list.options.check_cpu_usage_period_secs:
1418 self.cpu_usage_watcher = Spawn(['py/tools/cpu_usage_monitor.py',
1419 '-p', str(self.test_list.options.check_cpu_usage_period_secs)],
1420 cwd=factory.FACTORY_PATH)
1421
Jon Salz0697cbf2012-07-04 15:14:04 +08001422 self.init_states()
1423 self.start_event_server()
1424 self.connection_manager = self.env.create_connection_manager(
Tai-Hsu Lin371351a2012-08-27 14:17:14 +08001425 self.test_list.options.wlans,
1426 self.test_list.options.scan_wifi_period_secs)
Jon Salz0697cbf2012-07-04 15:14:04 +08001427 # Note that we create a log watcher even if
1428 # sync_event_log_period_secs isn't set (no background
1429 # syncing), since we may use it to flush event logs as well.
1430 self.log_watcher = EventLogWatcher(
1431 self.test_list.options.sync_event_log_period_secs,
Jon Salzd15bbcf2013-05-21 17:33:57 +08001432 event_log_db_file=None,
Jon Salz16d10542012-07-23 12:18:45 +08001433 handle_event_logs_callback=self.handle_event_logs)
Jon Salz0697cbf2012-07-04 15:14:04 +08001434 if self.test_list.options.sync_event_log_period_secs:
1435 self.log_watcher.StartWatchThread()
1436
Cheng-Yi Chianga0f6eff2014-01-09 18:27:22 +08001437 # Creates a system log manager to scan logs periocially.
1438 # A scan includes clearing logs and optionally syncing logs if
1439 # enable_syng_log is True. We kick it to sync logs.
1440 self.system_log_manager = SystemLogManager(
1441 sync_log_paths=self.test_list.options.sync_log_paths,
1442 sync_log_period_secs=self.test_list.options.sync_log_period_secs,
1443 scan_log_period_secs=self.test_list.options.scan_log_period_secs,
Cheng-Yi Chiangb8a491c2014-01-20 14:37:57 +08001444 clear_log_paths=self.test_list.options.clear_log_paths,
1445 clear_log_excluded_paths=self.test_list.options.clear_log_excluded_paths)
Cheng-Yi Chianga0f6eff2014-01-09 18:27:22 +08001446 self.system_log_manager.Start()
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +08001447
Jon Salz0697cbf2012-07-04 15:14:04 +08001448 self.update_system_info()
1449
Vic Yang4953fc12012-07-26 16:19:53 +08001450 assert ((self.test_list.options.min_charge_pct is None) ==
1451 (self.test_list.options.max_charge_pct is None))
Vic Yange83d9a12013-04-19 20:00:20 +08001452 if utils.in_chroot():
1453 logging.info('In chroot, ignoring charge manager and charge state')
1454 elif self.test_list.options.min_charge_pct is not None:
Vic Yang4953fc12012-07-26 16:19:53 +08001455 self.charge_manager = ChargeManager(self.test_list.options.min_charge_pct,
1456 self.test_list.options.max_charge_pct)
Jon Salzad7353b2012-10-15 16:22:46 +08001457 system.SystemStatus.charge_manager = self.charge_manager
Cheng-Yi Chiangd8186952013-04-04 23:41:14 +08001458 else:
1459 # Goofy should set charger state to charge if charge_manager is disabled.
1460 try:
1461 system.GetBoard().SetChargeState(Board.ChargeState.CHARGE)
1462 except BoardException:
1463 logging.exception('Unable to set charge state on this board')
Vic Yang4953fc12012-07-26 16:19:53 +08001464
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001465 self.core_dump_manager = CoreDumpManager(
1466 self.test_list.options.core_dump_watchlist)
1467
Jon Salz0697cbf2012-07-04 15:14:04 +08001468 os.environ['CROS_FACTORY'] = '1'
1469 os.environ['CROS_DISABLE_SITE_SYSINFO'] = '1'
1470
1471 # Set CROS_UI since some behaviors in ui.py depend on the
1472 # particular UI in use. TODO(jsalz): Remove this (and all
1473 # places it is used) when the GTK UI is removed.
1474 os.environ['CROS_UI'] = self.options.ui
1475
Shuo-Peng Liao1ff502e2013-06-30 18:37:02 +08001476 if not utils.in_chroot() and self.test_list.options.use_cpufreq_manager:
Jon Salzddf0d052013-06-18 12:52:44 +08001477 self.cpufreq_manager = CpufreqManager(event_log=self.event_log)
Jon Salzce6a7f82013-06-10 18:22:54 +08001478
Justin Chuang31b02432013-06-27 15:16:51 +08001479 # Startup hooks may want to skip some tests.
1480 self.update_skipped_tests()
Jon Salz416f9cc2013-05-10 18:32:50 +08001481
Jon Salze12c2b32013-06-25 16:24:34 +08001482 self.find_kcrashes()
1483
Shuo-Peng Liao268b40b2013-07-01 15:58:59 +08001484 # Should not move earlier.
1485 self.hooks.OnStartup()
1486
Jon Salz0697cbf2012-07-04 15:14:04 +08001487 if self.options.ui == 'chrome':
1488 self.env.launch_chrome()
1489 logging.info('Waiting for a web socket connection')
Cheng-Yi Chiangfd8ed392013-03-08 21:37:31 +08001490 self.web_socket_manager.wait()
Jon Salz0697cbf2012-07-04 15:14:04 +08001491
1492 # Wait for the test widget size to be set; this is done in
1493 # an asynchronous RPC so there is a small chance that the
1494 # web socket might be opened first.
1495 for _ in range(100): # 10 s
1496 try:
1497 if self.state_instance.get_shared_data('test_widget_size'):
1498 break
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001499 except KeyError:
Jon Salz0697cbf2012-07-04 15:14:04 +08001500 pass # Retry
1501 time.sleep(0.1) # 100 ms
1502 else:
1503 logging.warn('Never received test_widget_size from UI')
Jon Salz45297282013-05-18 14:31:47 +08001504
1505 # Send Chrome a Tab to get focus to the factory UI
1506 # (http://crosbug.com/p/19444). TODO(jsalz): remove this hack
1507 # and figure out the right way to get the focus to Chrome.
1508 if not utils.in_chroot():
Ricky Liangb97f3652013-08-20 17:30:28 +08001509 utils.SendKey('Tab')
Jon Salz0697cbf2012-07-04 15:14:04 +08001510 elif self.options.ui == 'gtk':
1511 self.start_ui()
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001512
Ricky Liang650f6bf2012-09-28 13:22:54 +08001513 # Create download path for autotest beforehand or autotests run at
1514 # the same time might fail due to race condition.
1515 if not factory.in_chroot():
1516 utils.TryMakeDirs(os.path.join('/usr/local/autotest', 'tests',
1517 'download'))
1518
Jon Salz0697cbf2012-07-04 15:14:04 +08001519 def state_change_callback(test, test_state):
1520 self.event_client.post_event(
Ricky Liang4bff3e32014-02-20 18:46:11 +08001521 Event(Event.Type.STATE_CHANGE, path=test.path, state=test_state))
Jon Salz0697cbf2012-07-04 15:14:04 +08001522 self.test_list.state_change_callback = state_change_callback
Jon Salz73e0fd02012-04-04 11:46:38 +08001523
Jon Salza6711d72012-07-18 14:33:03 +08001524 for handler in self.on_ui_startup:
1525 handler()
1526
1527 self.prespawner = Prespawner()
1528 self.prespawner.start()
1529
Jon Salz0697cbf2012-07-04 15:14:04 +08001530 try:
1531 tests_after_shutdown = self.state_instance.get_shared_data(
1532 'tests_after_shutdown')
1533 except KeyError:
1534 tests_after_shutdown = None
Jon Salz57717ca2012-04-04 16:47:25 +08001535
Jon Salz5c344f62012-07-13 14:31:16 +08001536 force_auto_run = (tests_after_shutdown == FORCE_AUTO_RUN)
1537 if not force_auto_run and tests_after_shutdown is not None:
Jon Salz0697cbf2012-07-04 15:14:04 +08001538 logging.info('Resuming tests after shutdown: %s',
1539 tests_after_shutdown)
Jon Salz0697cbf2012-07-04 15:14:04 +08001540 self.tests_to_run.extend(
Ricky Liang4bff3e32014-02-20 18:46:11 +08001541 self.test_list.lookup_path(t) for t in tests_after_shutdown)
Jon Salz0697cbf2012-07-04 15:14:04 +08001542 self.run_queue.put(self.run_next_test)
1543 else:
Jon Salz5c344f62012-07-13 14:31:16 +08001544 if force_auto_run or self.test_list.options.auto_run_on_start:
Jon Salz0697cbf2012-07-04 15:14:04 +08001545 self.run_queue.put(
Ricky Liang4bff3e32014-02-20 18:46:11 +08001546 lambda: self.run_tests(self.test_list, untested_only=True))
Jon Salz5c344f62012-07-13 14:31:16 +08001547 self.state_instance.set_shared_data('tests_after_shutdown', None)
Ricky Liang4bff3e32014-02-20 18:46:11 +08001548 self.restore_active_run_state()
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001549
Dean Liao592e4d52013-01-10 20:06:39 +08001550 self.may_disable_cros_shortcut_keys()
1551
1552 def may_disable_cros_shortcut_keys(self):
1553 test_options = self.test_list.options
1554 if test_options.disable_cros_shortcut_keys:
1555 logging.info('Filter ChromeOS shortcut keys.')
1556 self.key_filter = KeyFilter(
1557 unmap_caps_lock=test_options.disable_caps_lock,
1558 caps_lock_keycode=test_options.caps_lock_keycode)
1559 self.key_filter.Start()
1560
Jon Salz0697cbf2012-07-04 15:14:04 +08001561 def run(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001562 """Runs Goofy."""
Jon Salz0697cbf2012-07-04 15:14:04 +08001563 # Process events forever.
1564 while self.run_once(True):
1565 pass
Jon Salz73e0fd02012-04-04 11:46:38 +08001566
Jon Salz0697cbf2012-07-04 15:14:04 +08001567 def run_once(self, block=False):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001568 """Runs all items pending in the event loop.
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001569
Jon Salz0697cbf2012-07-04 15:14:04 +08001570 Args:
1571 block: If true, block until at least one event is processed.
Jon Salz7c15e8b2012-06-19 17:10:37 +08001572
Jon Salz0697cbf2012-07-04 15:14:04 +08001573 Returns:
1574 True to keep going or False to shut down.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001575 """
Jon Salz0697cbf2012-07-04 15:14:04 +08001576 events = utils.DrainQueue(self.run_queue)
cychiang21886742012-07-05 15:16:32 +08001577 while not events:
Jon Salz0697cbf2012-07-04 15:14:04 +08001578 # Nothing on the run queue.
1579 self._run_queue_idle()
1580 if block:
1581 # Block for at least one event...
cychiang21886742012-07-05 15:16:32 +08001582 try:
1583 events.append(self.run_queue.get(timeout=RUN_QUEUE_TIMEOUT_SECS))
1584 except Queue.Empty:
1585 # Keep going (calling _run_queue_idle() again at the top of
1586 # the loop)
1587 continue
Jon Salz0697cbf2012-07-04 15:14:04 +08001588 # ...and grab anything else that showed up at the same
1589 # time.
1590 events.extend(utils.DrainQueue(self.run_queue))
cychiang21886742012-07-05 15:16:32 +08001591 else:
1592 break
Jon Salz51528e12012-07-02 18:54:45 +08001593
Jon Salz0697cbf2012-07-04 15:14:04 +08001594 for event in events:
1595 if not event:
1596 # Shutdown request.
1597 self.run_queue.task_done()
1598 return False
Jon Salz51528e12012-07-02 18:54:45 +08001599
Jon Salz0697cbf2012-07-04 15:14:04 +08001600 try:
1601 event()
Jon Salz85a39882012-07-05 16:45:04 +08001602 except: # pylint: disable=W0702
1603 logging.exception('Error in event loop')
Jon Salz0697cbf2012-07-04 15:14:04 +08001604 self.record_exception(traceback.format_exception_only(
1605 *sys.exc_info()[:2]))
1606 # But keep going
1607 finally:
1608 self.run_queue.task_done()
1609 return True
Jon Salz0405ab52012-03-16 15:26:52 +08001610
Jon Salz0e6532d2012-10-25 16:30:11 +08001611 def _should_sync_time(self, foreground=False):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001612 """Returns True if we should attempt syncing time with shopfloor.
Jon Salz0e6532d2012-10-25 16:30:11 +08001613
1614 Args:
1615 foreground: If True, synchronizes even if background syncing
1616 is disabled (e.g., in explicit sync requests from the
1617 SyncShopfloor test).
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001618 """
Jon Salz0e6532d2012-10-25 16:30:11 +08001619 return ((foreground or
1620 self.test_list.options.sync_time_period_secs) and
Jon Salz54882d02012-08-31 01:57:54 +08001621 self.time_sanitizer and
1622 (not self.time_synced) and
1623 (not factory.in_chroot()))
1624
Jon Salz0e6532d2012-10-25 16:30:11 +08001625 def sync_time_with_shopfloor_server(self, foreground=False):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001626 """Syncs time with shopfloor server, if not yet synced.
Jon Salz54882d02012-08-31 01:57:54 +08001627
Jon Salz0e6532d2012-10-25 16:30:11 +08001628 Args:
1629 foreground: If True, synchronizes even if background syncing
1630 is disabled (e.g., in explicit sync requests from the
1631 SyncShopfloor test).
1632
Jon Salz54882d02012-08-31 01:57:54 +08001633 Returns:
1634 False if no time sanitizer is available, or True if this sync (or a
1635 previous sync) succeeded.
1636
1637 Raises:
1638 Exception if unable to contact the shopfloor server.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001639 """
Jon Salz0e6532d2012-10-25 16:30:11 +08001640 if self._should_sync_time(foreground):
Jon Salz54882d02012-08-31 01:57:54 +08001641 self.time_sanitizer.SyncWithShopfloor()
1642 self.time_synced = True
1643 return self.time_synced
1644
Jon Salzb92c5112012-09-21 15:40:11 +08001645 def log_disk_space_stats(self):
Jon Salz18e0e022013-06-11 17:13:39 +08001646 if (utils.in_chroot() or
1647 not self.test_list.options.log_disk_space_period_secs):
Jon Salzb92c5112012-09-21 15:40:11 +08001648 return
1649
1650 now = time.time()
1651 if (self.last_log_disk_space_time and
1652 now - self.last_log_disk_space_time <
1653 self.test_list.options.log_disk_space_period_secs):
1654 return
1655 self.last_log_disk_space_time = now
1656
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001657 # Upload event if stateful partition usage is above threshold.
1658 # Stateful partition is mounted on /usr/local, while
1659 # encrypted stateful partition is mounted on /var.
1660 # If there are too much logs in the factory process,
1661 # these two partitions might get full.
Jon Salzb92c5112012-09-21 15:40:11 +08001662 try:
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001663 vfs_infos = disk_space.GetAllVFSInfo()
1664 stateful_info, encrypted_info = None, None
1665 for vfs_info in vfs_infos.values():
1666 if '/usr/local' in vfs_info.mount_points:
1667 stateful_info = vfs_info
1668 if '/var' in vfs_info.mount_points:
1669 encrypted_info = vfs_info
1670
1671 stateful = disk_space.GetPartitionUsage(stateful_info)
1672 encrypted = disk_space.GetPartitionUsage(encrypted_info)
1673
1674 above_threshold = (
1675 self.test_list.options.stateful_usage_threshold and
1676 max(stateful.bytes_used_pct,
1677 stateful.inodes_used_pct,
1678 encrypted.bytes_used_pct,
1679 encrypted.inodes_used_pct) >
1680 self.test_list.options.stateful_usage_threshold)
1681
1682 if above_threshold:
1683 self.event_log.Log('stateful_partition_usage',
1684 partitions={
1685 'stateful': {
1686 'bytes_used_pct': FloatDigit(stateful.bytes_used_pct, 2),
1687 'inodes_used_pct': FloatDigit(stateful.inodes_used_pct, 2)},
1688 'encrypted_stateful': {
1689 'bytes_used_pct': FloatDigit(encrypted.bytes_used_pct, 2),
1690 'inodes_used_pct': FloatDigit(encrypted.inodes_used_pct, 2)}
1691 })
1692 self.log_watcher.ScanEventLogs()
Cheng-Yi Chiang00798e72013-06-20 18:16:39 +08001693 if (not utils.in_chroot() and
1694 self.test_list.options.stateful_usage_above_threshold_action):
1695 Spawn(self.test_list.options.stateful_usage_above_threshold_action,
1696 call=True)
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001697
1698 message = disk_space.FormatSpaceUsedAll(vfs_infos)
Jon Salz3c493bb2013-02-07 17:24:58 +08001699 if message != self.last_log_disk_space_message:
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001700 if above_threshold:
1701 logging.warning(message)
1702 else:
1703 logging.info(message)
Jon Salz3c493bb2013-02-07 17:24:58 +08001704 self.last_log_disk_space_message = message
Jon Salzb92c5112012-09-21 15:40:11 +08001705 except: # pylint: disable=W0702
1706 logging.exception('Unable to get disk space used')
1707
Justin Chuang83813982013-05-13 01:26:32 +08001708 def check_battery(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001709 """Checks the current battery status.
Justin Chuang83813982013-05-13 01:26:32 +08001710
1711 Logs current battery charging level and status to log. If the battery level
1712 is lower below warning_low_battery_pct, send warning event to shopfloor.
1713 If the battery level is lower below critical_low_battery_pct, flush disks.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001714 """
Justin Chuang83813982013-05-13 01:26:32 +08001715 if not self.test_list.options.check_battery_period_secs:
1716 return
1717
1718 now = time.time()
1719 if (self.last_check_battery_time and
1720 now - self.last_check_battery_time <
1721 self.test_list.options.check_battery_period_secs):
1722 return
1723 self.last_check_battery_time = now
1724
1725 message = ''
1726 log_level = logging.INFO
1727 try:
1728 power = system.GetBoard().power
1729 if not power.CheckBatteryPresent():
1730 message = 'Battery is not present'
1731 else:
1732 ac_present = power.CheckACPresent()
1733 charge_pct = power.GetChargePct(get_float=True)
1734 message = ('Current battery level %.1f%%, AC charger is %s' %
1735 (charge_pct, 'connected' if ac_present else 'disconnected'))
1736
1737 if charge_pct > self.test_list.options.critical_low_battery_pct:
1738 critical_low_battery = False
1739 else:
1740 critical_low_battery = True
1741 # Only sync disks when battery level is still above minimum
1742 # value. This can be used for offline analysis when shopfloor cannot
1743 # be connected.
1744 if charge_pct > MIN_BATTERY_LEVEL_FOR_DISK_SYNC:
1745 logging.warning('disk syncing for critical low battery situation')
1746 os.system('sync; sync; sync')
1747 else:
1748 logging.warning('disk syncing is cancelled '
1749 'because battery level is lower than %.1f',
1750 MIN_BATTERY_LEVEL_FOR_DISK_SYNC)
1751
1752 # Notify shopfloor server
1753 if (critical_low_battery or
1754 (not ac_present and
1755 charge_pct <= self.test_list.options.warning_low_battery_pct)):
1756 log_level = logging.WARNING
1757
1758 self.event_log.Log('low_battery',
1759 battery_level=charge_pct,
1760 charger_connected=ac_present,
1761 critical=critical_low_battery)
1762 self.log_watcher.KickWatchThread()
Cheng-Yi Chianga0f6eff2014-01-09 18:27:22 +08001763 if self.test_list.options.enable_sync_log:
1764 self.system_log_manager.KickToSync()
Justin Chuang83813982013-05-13 01:26:32 +08001765 except: # pylint: disable=W0702
1766 logging.exception('Unable to check battery or notify shopfloor')
1767 finally:
1768 if message != self.last_check_battery_message:
1769 logging.log(log_level, message)
1770 self.last_check_battery_message = message
1771
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001772 def check_core_dump(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001773 """Checks if there is any core dumped file.
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001774
1775 Removes unwanted core dump files immediately.
1776 Syncs those files matching watch list to server with a delay between
1777 each sync. After the files have been synced to server, deletes the files.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001778 """
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001779 core_dump_files = self.core_dump_manager.ScanFiles()
1780 if core_dump_files:
1781 now = time.time()
1782 if (self.last_kick_sync_time and now - self.last_kick_sync_time <
1783 self.test_list.options.kick_sync_min_interval_secs):
1784 return
1785 self.last_kick_sync_time = now
1786
1787 # Sends event to server
1788 self.event_log.Log('core_dumped', files=core_dump_files)
1789 self.log_watcher.KickWatchThread()
1790
1791 # Syncs files to server
Cheng-Yi Chianga0f6eff2014-01-09 18:27:22 +08001792 if self.test_list.options.enable_sync_log:
1793 self.system_log_manager.KickToSync(
Cheng-Yi Chiangd3516a32013-07-17 15:30:47 +08001794 core_dump_files, self.core_dump_manager.ClearFiles)
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001795
Cheng-Yi Chiang39d32ad2013-07-23 15:02:38 +08001796 def check_log_rotation(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001797 """Checks log rotation file presence/absence according to test_list option.
Cheng-Yi Chiang39d32ad2013-07-23 15:02:38 +08001798
1799 Touch /var/lib/cleanup_logs_paused if test_list.options.disable_log_rotation
1800 is True, delete it otherwise. This must be done in idle loop because
1801 autotest client will touch /var/lib/cleanup_logs_paused each time it runs
1802 an autotest.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001803 """
Cheng-Yi Chiang39d32ad2013-07-23 15:02:38 +08001804 if utils.in_chroot():
1805 return
1806 try:
1807 if self.test_list.options.disable_log_rotation:
1808 open(CLEANUP_LOGS_PAUSED, 'w').close()
1809 else:
1810 file_utils.TryUnlink(CLEANUP_LOGS_PAUSED)
1811 except: # pylint: disable=W0702
1812 # Oh well. Logs an error (but no trace)
1813 logging.info(
1814 'Unable to %s %s: %s',
1815 'touch' if self.test_list.options.disable_log_rotation else 'delete',
1816 CLEANUP_LOGS_PAUSED, utils.FormatExceptionOnly())
1817
Jon Salz8fa8e832012-07-13 19:04:09 +08001818 def sync_time_in_background(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001819 """Writes out current time and tries to sync with shopfloor server."""
Jon Salzb22d1172012-08-06 10:38:57 +08001820 if not self.time_sanitizer:
1821 return
1822
1823 # Write out the current time.
1824 self.time_sanitizer.SaveTime()
1825
Jon Salz54882d02012-08-31 01:57:54 +08001826 if not self._should_sync_time():
Jon Salz8fa8e832012-07-13 19:04:09 +08001827 return
1828
1829 now = time.time()
1830 if self.last_sync_time and (
1831 now - self.last_sync_time <
1832 self.test_list.options.sync_time_period_secs):
1833 # Not yet time for another check.
1834 return
1835 self.last_sync_time = now
1836
1837 def target():
1838 try:
Jon Salz54882d02012-08-31 01:57:54 +08001839 self.sync_time_with_shopfloor_server()
Jon Salz8fa8e832012-07-13 19:04:09 +08001840 except: # pylint: disable=W0702
1841 # Oh well. Log an error (but no trace)
1842 logging.info(
1843 'Unable to get time from shopfloor server: %s',
1844 utils.FormatExceptionOnly())
1845
1846 thread = threading.Thread(target=target)
1847 thread.daemon = True
1848 thread.start()
1849
Jon Salz0697cbf2012-07-04 15:14:04 +08001850 def _run_queue_idle(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001851 """Invoked when the run queue has no events.
Vic Yang4953fc12012-07-26 16:19:53 +08001852
1853 This method must not raise exception.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001854 """
Jon Salzb22d1172012-08-06 10:38:57 +08001855 now = time.time()
1856 if (self.last_idle and
1857 now < (self.last_idle + RUN_QUEUE_TIMEOUT_SECS - 1)):
1858 # Don't run more often than once every (RUN_QUEUE_TIMEOUT_SECS -
1859 # 1) seconds.
1860 return
1861
1862 self.last_idle = now
1863
Vic Yang311ddb82012-09-26 12:08:28 +08001864 self.check_exclusive()
cychiang21886742012-07-05 15:16:32 +08001865 self.check_for_updates()
Jon Salz8fa8e832012-07-13 19:04:09 +08001866 self.sync_time_in_background()
Jon Salzb92c5112012-09-21 15:40:11 +08001867 self.log_disk_space_stats()
Justin Chuang83813982013-05-13 01:26:32 +08001868 self.check_battery()
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001869 self.check_core_dump()
Cheng-Yi Chiang39d32ad2013-07-23 15:02:38 +08001870 self.check_log_rotation()
Jon Salz57717ca2012-04-04 16:47:25 +08001871
Jon Salzd15bbcf2013-05-21 17:33:57 +08001872 def handle_event_logs(self, chunks):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001873 """Callback for event watcher.
Jon Salz258a40c2012-04-19 12:34:01 +08001874
Jon Salz0697cbf2012-07-04 15:14:04 +08001875 Attempts to upload the event logs to the shopfloor server.
Vic Yang93027612013-05-06 02:42:49 +08001876
1877 Args:
Jon Salzd15bbcf2013-05-21 17:33:57 +08001878 chunks: A list of Chunk objects.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001879 """
Vic Yang93027612013-05-06 02:42:49 +08001880 first_exception = None
1881 exception_count = 0
1882
Jon Salzd15bbcf2013-05-21 17:33:57 +08001883 for chunk in chunks:
Vic Yang93027612013-05-06 02:42:49 +08001884 try:
Jon Salzcddb6402013-05-23 12:56:42 +08001885 description = 'event logs (%s)' % str(chunk)
Vic Yang93027612013-05-06 02:42:49 +08001886 start_time = time.time()
1887 shopfloor_client = shopfloor.get_instance(
1888 detect=True,
1889 timeout=self.test_list.options.shopfloor_timeout_secs)
Jon Salzd15bbcf2013-05-21 17:33:57 +08001890 shopfloor_client.UploadEvent(chunk.log_name + "." +
1891 event_log.GetReimageId(),
1892 Binary(chunk.chunk))
Vic Yang93027612013-05-06 02:42:49 +08001893 logging.info(
1894 'Successfully synced %s in %.03f s',
1895 description, time.time() - start_time)
1896 except: # pylint: disable=W0702
Jon Salzd15bbcf2013-05-21 17:33:57 +08001897 first_exception = (first_exception or (chunk.log_name + ': ' +
Vic Yang93027612013-05-06 02:42:49 +08001898 utils.FormatExceptionOnly()))
1899 exception_count += 1
1900
1901 if exception_count:
1902 if exception_count == 1:
1903 msg = 'Log upload failed: %s' % first_exception
1904 else:
1905 msg = '%d log upload failed; first is: %s' % (
1906 exception_count, first_exception)
1907 raise Exception(msg)
1908
Jon Salz57717ca2012-04-04 16:47:25 +08001909
Jon Salz0697cbf2012-07-04 15:14:04 +08001910 def run_tests_with_status(self, statuses_to_run, starting_at=None,
1911 root=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001912 """Runs all top-level tests with a particular status.
Jon Salz0405ab52012-03-16 15:26:52 +08001913
Jon Salz0697cbf2012-07-04 15:14:04 +08001914 All active tests, plus any tests to re-run, are reset.
Jon Salz57717ca2012-04-04 16:47:25 +08001915
Jon Salz0697cbf2012-07-04 15:14:04 +08001916 Args:
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001917 statuses_to_run: The particular status that caller wants to run.
Jon Salz0697cbf2012-07-04 15:14:04 +08001918 starting_at: If provided, only auto-runs tests beginning with
1919 this test.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001920 root: The root of tests to run. If not provided, it will be
1921 the root of all tests.
1922 """
Jon Salz0697cbf2012-07-04 15:14:04 +08001923 root = root or self.test_list
Jon Salz57717ca2012-04-04 16:47:25 +08001924
Jon Salz0697cbf2012-07-04 15:14:04 +08001925 if starting_at:
1926 # Make sure they passed a test, not a string.
1927 assert isinstance(starting_at, factory.FactoryTest)
Jon Salz0405ab52012-03-16 15:26:52 +08001928
Jon Salz0697cbf2012-07-04 15:14:04 +08001929 tests_to_reset = []
1930 tests_to_run = []
Jon Salz0405ab52012-03-16 15:26:52 +08001931
Jon Salz0697cbf2012-07-04 15:14:04 +08001932 found_starting_at = False
Jon Salz0405ab52012-03-16 15:26:52 +08001933
Jon Salz0697cbf2012-07-04 15:14:04 +08001934 for test in root.get_top_level_tests():
1935 if starting_at:
1936 if test == starting_at:
1937 # We've found starting_at; do auto-run on all
1938 # subsequent tests.
1939 found_starting_at = True
1940 if not found_starting_at:
1941 # Don't start this guy yet
1942 continue
Jon Salz0405ab52012-03-16 15:26:52 +08001943
Jon Salz0697cbf2012-07-04 15:14:04 +08001944 status = test.get_state().status
1945 if status == TestState.ACTIVE or status in statuses_to_run:
1946 # Reset the test (later; we will need to abort
1947 # all active tests first).
1948 tests_to_reset.append(test)
1949 if status in statuses_to_run:
1950 tests_to_run.append(test)
Jon Salz0405ab52012-03-16 15:26:52 +08001951
Jon Salz6dc031d2013-06-19 13:06:23 +08001952 self.abort_active_tests('Operator requested run/re-run of certain tests')
Jon Salz258a40c2012-04-19 12:34:01 +08001953
Jon Salz0697cbf2012-07-04 15:14:04 +08001954 # Reset all statuses of the tests to run (in case any tests were active;
1955 # we want them to be run again).
1956 for test_to_reset in tests_to_reset:
1957 for test in test_to_reset.walk():
1958 test.update_state(status=TestState.UNTESTED)
Jon Salz57717ca2012-04-04 16:47:25 +08001959
Jon Salz0697cbf2012-07-04 15:14:04 +08001960 self.run_tests(tests_to_run, untested_only=True)
Jon Salz0405ab52012-03-16 15:26:52 +08001961
Jon Salz0697cbf2012-07-04 15:14:04 +08001962 def restart_tests(self, root=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001963 """Restarts all tests."""
Jon Salz0697cbf2012-07-04 15:14:04 +08001964 root = root or self.test_list
Jon Salz0405ab52012-03-16 15:26:52 +08001965
Jon Salz6dc031d2013-06-19 13:06:23 +08001966 self.abort_active_tests('Operator requested restart of certain tests')
Jon Salz0697cbf2012-07-04 15:14:04 +08001967 for test in root.walk():
1968 test.update_state(status=TestState.UNTESTED)
1969 self.run_tests(root)
Hung-Te Lin96632362012-03-20 21:14:18 +08001970
Jon Salz0697cbf2012-07-04 15:14:04 +08001971 def auto_run(self, starting_at=None, root=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001972 """"Auto-runs" tests that have not been run yet.
Hung-Te Lin96632362012-03-20 21:14:18 +08001973
Jon Salz0697cbf2012-07-04 15:14:04 +08001974 Args:
1975 starting_at: If provide, only auto-runs tests beginning with
1976 this test.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001977 root: If provided, the root of tests to run. If not provided, the root
1978 will be test_list (root of all tests).
1979 """
Jon Salz0697cbf2012-07-04 15:14:04 +08001980 root = root or self.test_list
1981 self.run_tests_with_status([TestState.UNTESTED, TestState.ACTIVE],
1982 starting_at=starting_at,
1983 root=root)
Jon Salz968e90b2012-03-18 16:12:43 +08001984
Jon Salz0697cbf2012-07-04 15:14:04 +08001985 def re_run_failed(self, root=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001986 """Re-runs failed tests."""
Jon Salz0697cbf2012-07-04 15:14:04 +08001987 root = root or self.test_list
1988 self.run_tests_with_status([TestState.FAILED], root=root)
Jon Salz57717ca2012-04-04 16:47:25 +08001989
Jon Salz0697cbf2012-07-04 15:14:04 +08001990 def show_review_information(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001991 """Event handler for showing review information screen.
Jon Salz57717ca2012-04-04 16:47:25 +08001992
Jon Salz0697cbf2012-07-04 15:14:04 +08001993 The information screene is rendered by main UI program (ui.py), so in
1994 goofy we only need to kill all active tests, set them as untested, and
1995 clear remaining tests.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001996 """
Jon Salz0697cbf2012-07-04 15:14:04 +08001997 self.kill_active_tests(False)
Jon Salza6711d72012-07-18 14:33:03 +08001998 self.cancel_pending_tests()
Jon Salz57717ca2012-04-04 16:47:25 +08001999
Jon Salz0697cbf2012-07-04 15:14:04 +08002000 def handle_switch_test(self, event):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08002001 """Switches to a particular test.
Jon Salz0405ab52012-03-16 15:26:52 +08002002
Ricky Liang6fe218c2013-12-27 15:17:17 +08002003 Args:
2004 event: The SWITCH_TEST event.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08002005 """
Jon Salz0697cbf2012-07-04 15:14:04 +08002006 test = self.test_list.lookup_path(event.path)
2007 if not test:
2008 logging.error('Unknown test %r', event.key)
2009 return
Jon Salz73e0fd02012-04-04 11:46:38 +08002010
Jon Salz0697cbf2012-07-04 15:14:04 +08002011 invoc = self.invocations.get(test)
2012 if invoc and test.backgroundable:
2013 # Already running: just bring to the front if it
2014 # has a UI.
2015 logging.info('Setting visible test to %s', test.path)
Jon Salz36fbbb52012-07-05 13:45:06 +08002016 self.set_visible_test(test)
Jon Salz0697cbf2012-07-04 15:14:04 +08002017 return
Jon Salz73e0fd02012-04-04 11:46:38 +08002018
Jon Salz6dc031d2013-06-19 13:06:23 +08002019 self.abort_active_tests('Operator requested abort (switch_test)')
Jon Salz0697cbf2012-07-04 15:14:04 +08002020 for t in test.walk():
2021 t.update_state(status=TestState.UNTESTED)
Jon Salz73e0fd02012-04-04 11:46:38 +08002022
Jon Salz0697cbf2012-07-04 15:14:04 +08002023 if self.test_list.options.auto_run_on_keypress:
2024 self.auto_run(starting_at=test)
2025 else:
2026 self.run_tests(test)
Jon Salz73e0fd02012-04-04 11:46:38 +08002027
Jon Salz0697cbf2012-07-04 15:14:04 +08002028 def wait(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08002029 """Waits for all pending invocations.
Jon Salz0697cbf2012-07-04 15:14:04 +08002030
2031 Useful for testing.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08002032 """
Jon Salz1acc8742012-07-17 17:45:55 +08002033 while self.invocations:
2034 for k, v in self.invocations.iteritems():
2035 logging.info('Waiting for %s to complete...', k)
2036 v.thread.join()
2037 self.reap_completed_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +08002038
2039 def check_exceptions(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08002040 """Raises an error if any exceptions have occurred in
2041 invocation threads.
2042 """
Jon Salz0697cbf2012-07-04 15:14:04 +08002043 if self.exceptions:
2044 raise RuntimeError('Exception in invocation thread: %r' %
2045 self.exceptions)
2046
2047 def record_exception(self, msg):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08002048 """Records an exception in an invocation thread.
Jon Salz0697cbf2012-07-04 15:14:04 +08002049
2050 An exception with the given message will be rethrown when
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08002051 Goofy is destroyed.
2052 """
Jon Salz0697cbf2012-07-04 15:14:04 +08002053 self.exceptions.append(msg)
Jon Salz73e0fd02012-04-04 11:46:38 +08002054
Hung-Te Linf2f78f72012-02-08 19:27:11 +08002055
2056if __name__ == '__main__':
Jon Salz77c151e2012-08-28 07:20:37 +08002057 goofy = Goofy()
2058 try:
2059 goofy.main()
Jon Salz0f996602012-10-03 15:26:48 +08002060 except SystemExit:
2061 # Propagate SystemExit without logging.
2062 raise
Jon Salz31373eb2012-09-21 16:19:49 +08002063 except:
Jon Salz0f996602012-10-03 15:26:48 +08002064 # Log the error before trying to shut down (unless it's a graceful
2065 # exit).
Jon Salz31373eb2012-09-21 16:19:49 +08002066 logging.exception('Error in main loop')
2067 raise
Jon Salz77c151e2012-08-28 07:20:37 +08002068 finally:
2069 goofy.destroy()