blob: 0d8cb75e2874dd8622e08be5da9bf8d52f4e1c7e [file] [log] [blame]
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001#!/usr/bin/python -u
Hung-Te Linf2f78f72012-02-08 19:27:11 +08002# -*- coding: utf-8 -*-
3#
Jon Salz37eccbd2012-05-25 16:06:52 +08004# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
Hung-Te Linf2f78f72012-02-08 19:27:11 +08005# Use of this source code is governed by a BSD-style license that can be
6# found in the LICENSE file.
7
8'''
9The main factory flow that runs the factory test and finalizes a device.
10'''
11
Jon Salze12c2b32013-06-25 16:24:34 +080012import glob
Jon Salz0405ab52012-03-16 15:26:52 +080013import logging
14import os
Jon Salz73e0fd02012-04-04 11:46:38 +080015import Queue
Jon Salze12c2b32013-06-25 16:24:34 +080016import shutil
Jon Salz77c151e2012-08-28 07:20:37 +080017import signal
Jon Salz0405ab52012-03-16 15:26:52 +080018import sys
Jon Salzeff94182013-06-19 15:06:28 +080019import syslog
Jon Salz0405ab52012-03-16 15:26:52 +080020import threading
21import time
22import traceback
Jon Salz258a40c2012-04-19 12:34:01 +080023import uuid
Jon Salzb10cf512012-08-09 17:29:21 +080024from xmlrpclib import Binary
Hung-Te Linf2f78f72012-02-08 19:27:11 +080025from collections import deque
26from optparse import OptionParser
Hung-Te Linf2f78f72012-02-08 19:27:11 +080027
Jon Salz0697cbf2012-07-04 15:14:04 +080028import factory_common # pylint: disable=W0611
jcliangcd688182012-08-20 21:01:26 +080029from cros.factory import event_log
30from cros.factory import system
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +080031from cros.factory.event_log import EventLog, FloatDigit
Tom Wai-Hong Tamd33723e2013-04-10 21:14:37 +080032from cros.factory.event_log_watcher import EventLogWatcher
jcliangcd688182012-08-20 21:01:26 +080033from cros.factory.goofy import test_environment
34from cros.factory.goofy import time_sanitizer
Jon Salz83591782012-06-26 11:09:58 +080035from cros.factory.goofy import updater
jcliangcd688182012-08-20 21:01:26 +080036from cros.factory.goofy.goofy_rpc import GoofyRPC
37from cros.factory.goofy.invocation import TestInvocation
38from cros.factory.goofy.prespawner import Prespawner
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +080039from cros.factory.goofy.system_log_manager import SystemLogManager
jcliangcd688182012-08-20 21:01:26 +080040from cros.factory.goofy.web_socket_manager import WebSocketManager
Cheng-Yi Chiangd8186952013-04-04 23:41:14 +080041from cros.factory.system.board import Board, BoardException
jcliangcd688182012-08-20 21:01:26 +080042from cros.factory.system.charge_manager import ChargeManager
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +080043from cros.factory.system.core_dump_manager import CoreDumpManager
Jon Salzce6a7f82013-06-10 18:22:54 +080044from cros.factory.system.cpufreq_manager import CpufreqManager
Jon Salzb92c5112012-09-21 15:40:11 +080045from cros.factory.system import disk_space
jcliangcd688182012-08-20 21:01:26 +080046from cros.factory.test import factory
47from cros.factory.test import state
Jon Salz51528e12012-07-02 18:54:45 +080048from cros.factory.test import shopfloor
Jon Salz83591782012-06-26 11:09:58 +080049from cros.factory.test import utils
Jon Salz128b0932013-07-03 16:55:26 +080050from cros.factory.test.test_lists import test_lists
Jon Salz83591782012-06-26 11:09:58 +080051from cros.factory.test.event import Event
52from cros.factory.test.event import EventClient
53from cros.factory.test.event import EventServer
jcliangcd688182012-08-20 21:01:26 +080054from cros.factory.test.factory import TestState
Dean Liao592e4d52013-01-10 20:06:39 +080055from cros.factory.tools.key_filter import KeyFilter
Jon Salz2af235d2013-06-24 14:47:21 +080056from cros.factory.utils import file_utils
Jon Salz78c32392012-07-25 14:18:29 +080057from cros.factory.utils.process_utils import Spawn
Hung-Te Linf2f78f72012-02-08 19:27:11 +080058
59
Hung-Te Linf2f78f72012-02-08 19:27:11 +080060HWID_CFG_PATH = '/usr/local/share/chromeos-hwid/cfg'
Chun-ta Lin279e7e92013-02-19 17:40:39 +080061CACHES_DIR = os.path.join(factory.get_state_root(), "caches")
Hung-Te Linf2f78f72012-02-08 19:27:11 +080062
Jon Salz8796e362012-05-24 11:39:09 +080063# File that suppresses reboot if present (e.g., for development).
64NO_REBOOT_FILE = '/var/log/factory.noreboot'
65
Jon Salz5c344f62012-07-13 14:31:16 +080066# Value for tests_after_shutdown that forces auto-run (e.g., after
67# a factory update, when the available set of tests might change).
68FORCE_AUTO_RUN = 'force_auto_run'
69
cychiang21886742012-07-05 15:16:32 +080070RUN_QUEUE_TIMEOUT_SECS = 10
71
Justin Chuang83813982013-05-13 01:26:32 +080072# Sync disks when battery level is higher than this value.
73# Otherwise, power loss during disk sync operation may incur even worse outcome.
74MIN_BATTERY_LEVEL_FOR_DISK_SYNC = 1.0
75
Jon Salze12c2b32013-06-25 16:24:34 +080076MAX_CRASH_FILE_SIZE = 64*1024
77
Jon Salz758e6cc2012-04-03 15:47:07 +080078GOOFY_IN_CHROOT_WARNING = '\n' + ('*' * 70) + '''
79You are running Goofy inside the chroot. Autotests are not supported.
80
81To use Goofy in the chroot, first install an Xvnc server:
82
Jon Salz0697cbf2012-07-04 15:14:04 +080083 sudo apt-get install tightvncserver
Jon Salz758e6cc2012-04-03 15:47:07 +080084
85...and then start a VNC X server outside the chroot:
86
Jon Salz0697cbf2012-07-04 15:14:04 +080087 vncserver :10 &
88 vncviewer :10
Jon Salz758e6cc2012-04-03 15:47:07 +080089
90...and run Goofy as follows:
91
Jon Salz0697cbf2012-07-04 15:14:04 +080092 env --unset=XAUTHORITY DISPLAY=localhost:10 python goofy.py
Jon Salz758e6cc2012-04-03 15:47:07 +080093''' + ('*' * 70)
Jon Salz73e0fd02012-04-04 11:46:38 +080094suppress_chroot_warning = False
Hung-Te Linf2f78f72012-02-08 19:27:11 +080095
96def get_hwid_cfg():
Jon Salz0697cbf2012-07-04 15:14:04 +080097 '''
98 Returns the HWID config tag, or an empty string if none can be found.
99 '''
100 if 'CROS_HWID' in os.environ:
101 return os.environ['CROS_HWID']
102 if os.path.exists(HWID_CFG_PATH):
103 with open(HWID_CFG_PATH, 'rt') as hwid_cfg_handle:
104 return hwid_cfg_handle.read().strip()
105 return ''
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800106
107
Jon Salz73e0fd02012-04-04 11:46:38 +0800108_inited_logging = False
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800109
110class Goofy(object):
Jon Salz0697cbf2012-07-04 15:14:04 +0800111 '''
112 The main factory flow.
113
114 Note that all methods in this class must be invoked from the main
115 (event) thread. Other threads, such as callbacks and TestInvocation
116 methods, should instead post events on the run queue.
117
118 TODO: Unit tests. (chrome-os-partner:7409)
119
120 Properties:
121 uuid: A unique UUID for this invocation of Goofy.
122 state_instance: An instance of FactoryState.
123 state_server: The FactoryState XML/RPC server.
124 state_server_thread: A thread running state_server.
125 event_server: The EventServer socket server.
126 event_server_thread: A thread running event_server.
127 event_client: A client to the event server.
128 connection_manager: The connection_manager object.
Cheng-Yi Chiang835f2682013-05-06 22:15:48 +0800129 system_log_manager: The SystemLogManager object.
130 core_dump_manager: The CoreDumpManager object.
Jon Salz0697cbf2012-07-04 15:14:04 +0800131 ui_process: The factory ui process object.
132 run_queue: A queue of callbacks to invoke from the main thread.
133 invocations: A map from FactoryTest objects to the corresponding
134 TestInvocations objects representing active tests.
135 tests_to_run: A deque of tests that should be run when the current
136 test(s) complete.
137 options: Command-line options.
138 args: Command-line args.
139 test_list: The test list.
Jon Salz128b0932013-07-03 16:55:26 +0800140 test_lists: All new-style test lists.
Jon Salz0697cbf2012-07-04 15:14:04 +0800141 event_handlers: Map of Event.Type to the method used to handle that
142 event. If the method has an 'event' argument, the event is passed
143 to the handler.
144 exceptions: Exceptions encountered in invocation threads.
Jon Salz3c493bb2013-02-07 17:24:58 +0800145 last_log_disk_space_message: The last message we logged about disk space
146 (to avoid duplication).
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +0800147 last_kick_sync_time: The last time to kick system_log_manager to sync
148 because of core dump files (to avoid kicking too soon then abort the
149 sync.)
Jon Salz416f9cc2013-05-10 18:32:50 +0800150 hooks: A Hooks object containing hooks for various Goofy actions.
Jon Salz0697cbf2012-07-04 15:14:04 +0800151 '''
152 def __init__(self):
153 self.uuid = str(uuid.uuid4())
154 self.state_instance = None
155 self.state_server = None
156 self.state_server_thread = None
Jon Salz16d10542012-07-23 12:18:45 +0800157 self.goofy_rpc = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800158 self.event_server = None
159 self.event_server_thread = None
160 self.event_client = None
161 self.connection_manager = None
Vic Yang4953fc12012-07-26 16:19:53 +0800162 self.charge_manager = None
Jon Salz8fa8e832012-07-13 19:04:09 +0800163 self.time_sanitizer = None
164 self.time_synced = False
Jon Salz0697cbf2012-07-04 15:14:04 +0800165 self.log_watcher = None
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +0800166 self.system_log_manager = None
Cheng-Yi Chiang835f2682013-05-06 22:15:48 +0800167 self.core_dump_manager = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800168 self.event_log = None
169 self.prespawner = None
170 self.ui_process = None
Jon Salzc79a9982012-08-30 04:42:01 +0800171 self.dummy_shopfloor = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800172 self.run_queue = Queue.Queue()
173 self.invocations = {}
174 self.tests_to_run = deque()
175 self.visible_test = None
176 self.chrome = None
Jon Salz416f9cc2013-05-10 18:32:50 +0800177 self.hooks = None
Vic Yangd8990da2013-06-27 16:57:43 +0800178 self.cpu_usage_watcher = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800179
180 self.options = None
181 self.args = None
182 self.test_list = None
Jon Salz128b0932013-07-03 16:55:26 +0800183 self.test_lists = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800184 self.on_ui_startup = []
185 self.env = None
Jon Salzb22d1172012-08-06 10:38:57 +0800186 self.last_idle = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800187 self.last_shutdown_time = None
cychiang21886742012-07-05 15:16:32 +0800188 self.last_update_check = None
Jon Salz8fa8e832012-07-13 19:04:09 +0800189 self.last_sync_time = None
Jon Salzb92c5112012-09-21 15:40:11 +0800190 self.last_log_disk_space_time = None
Jon Salz3c493bb2013-02-07 17:24:58 +0800191 self.last_log_disk_space_message = None
Justin Chuang83813982013-05-13 01:26:32 +0800192 self.last_check_battery_time = None
193 self.last_check_battery_message = None
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +0800194 self.last_kick_sync_time = None
Vic Yang311ddb82012-09-26 12:08:28 +0800195 self.exclusive_items = set()
Jon Salz0f996602012-10-03 15:26:48 +0800196 self.event_log = None
Dean Liao592e4d52013-01-10 20:06:39 +0800197 self.key_filter = None
Jon Salzce6a7f82013-06-10 18:22:54 +0800198 self.cpufreq_manager = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800199
Jon Salz85a39882012-07-05 16:45:04 +0800200 def test_or_root(event, parent_or_group=True):
201 '''Returns the test affected by a particular event.
202
203 Args:
204 event: The event containing an optional 'path' attribute.
205 parent_on_group: If True, returns the top-level parent for a test (the
206 root node of the tests that need to be run together if the given test
207 path is to be run).
208 '''
Jon Salz0697cbf2012-07-04 15:14:04 +0800209 try:
210 path = event.path
211 except AttributeError:
212 path = None
213
214 if path:
Jon Salz85a39882012-07-05 16:45:04 +0800215 test = self.test_list.lookup_path(path)
216 if parent_or_group:
217 test = test.get_top_level_parent_or_group()
218 return test
Jon Salz0697cbf2012-07-04 15:14:04 +0800219 else:
220 return self.test_list
221
222 self.event_handlers = {
223 Event.Type.SWITCH_TEST: self.handle_switch_test,
224 Event.Type.SHOW_NEXT_ACTIVE_TEST:
225 lambda event: self.show_next_active_test(),
226 Event.Type.RESTART_TESTS:
227 lambda event: self.restart_tests(root=test_or_root(event)),
228 Event.Type.AUTO_RUN:
229 lambda event: self.auto_run(root=test_or_root(event)),
230 Event.Type.RE_RUN_FAILED:
231 lambda event: self.re_run_failed(root=test_or_root(event)),
232 Event.Type.RUN_TESTS_WITH_STATUS:
233 lambda event: self.run_tests_with_status(
234 event.status,
235 root=test_or_root(event)),
236 Event.Type.REVIEW:
237 lambda event: self.show_review_information(),
238 Event.Type.UPDATE_SYSTEM_INFO:
239 lambda event: self.update_system_info(),
Jon Salz0697cbf2012-07-04 15:14:04 +0800240 Event.Type.STOP:
Jon Salz85a39882012-07-05 16:45:04 +0800241 lambda event: self.stop(root=test_or_root(event, False),
Jon Salz6dc031d2013-06-19 13:06:23 +0800242 fail=getattr(event, 'fail', False),
243 reason=getattr(event, 'reason', None)),
Jon Salz36fbbb52012-07-05 13:45:06 +0800244 Event.Type.SET_VISIBLE_TEST:
245 lambda event: self.set_visible_test(
246 self.test_list.lookup_path(event.path)),
Jon Salz4712ac72013-02-07 17:12:05 +0800247 Event.Type.CLEAR_STATE:
248 lambda event: self.clear_state(self.test_list.lookup_path(event.path)),
Jon Salz0697cbf2012-07-04 15:14:04 +0800249 }
250
251 self.exceptions = []
252 self.web_socket_manager = None
253
254 def destroy(self):
255 if self.chrome:
256 self.chrome.kill()
257 self.chrome = None
Jon Salzc79a9982012-08-30 04:42:01 +0800258 if self.dummy_shopfloor:
259 self.dummy_shopfloor.kill()
260 self.dummy_shopfloor = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800261 if self.ui_process:
262 utils.kill_process_tree(self.ui_process, 'ui')
263 self.ui_process = None
264 if self.web_socket_manager:
265 logging.info('Stopping web sockets')
266 self.web_socket_manager.close()
267 self.web_socket_manager = None
268 if self.state_server_thread:
269 logging.info('Stopping state server')
270 self.state_server.shutdown()
271 self.state_server_thread.join()
272 self.state_server.server_close()
273 self.state_server_thread = None
274 if self.state_instance:
275 self.state_instance.close()
276 if self.event_server_thread:
277 logging.info('Stopping event server')
278 self.event_server.shutdown() # pylint: disable=E1101
279 self.event_server_thread.join()
280 self.event_server.server_close()
281 self.event_server_thread = None
282 if self.log_watcher:
283 if self.log_watcher.IsThreadStarted():
284 self.log_watcher.StopWatchThread()
285 self.log_watcher = None
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +0800286 if self.system_log_manager:
287 if self.system_log_manager.IsThreadRunning():
288 self.system_log_manager.StopSyncThread()
289 self.system_log_manager = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800290 if self.prespawner:
291 logging.info('Stopping prespawner')
292 self.prespawner.stop()
293 self.prespawner = None
294 if self.event_client:
295 logging.info('Closing event client')
296 self.event_client.close()
297 self.event_client = None
Jon Salzddf0d052013-06-18 12:52:44 +0800298 if self.cpufreq_manager:
299 self.cpufreq_manager.Stop()
Jon Salz0697cbf2012-07-04 15:14:04 +0800300 if self.event_log:
301 self.event_log.Close()
302 self.event_log = None
Dean Liao592e4d52013-01-10 20:06:39 +0800303 if self.key_filter:
304 self.key_filter.Stop()
Vic Yangd8990da2013-06-27 16:57:43 +0800305 if self.cpu_usage_watcher:
306 self.cpu_usage_watcher.terminate()
Dean Liao592e4d52013-01-10 20:06:39 +0800307
Jon Salz0697cbf2012-07-04 15:14:04 +0800308 self.check_exceptions()
309 logging.info('Done destroying Goofy')
310
311 def start_state_server(self):
Jon Salz2af235d2013-06-24 14:47:21 +0800312 # Before starting state server, remount stateful partitions with
313 # no commit flag. The default commit time (commit=600) makes corruption
314 # too likely.
315 file_utils.ResetCommitTime()
316
Jon Salz0697cbf2012-07-04 15:14:04 +0800317 self.state_instance, self.state_server = (
318 state.create_server(bind_address='0.0.0.0'))
Jon Salz16d10542012-07-23 12:18:45 +0800319 self.goofy_rpc = GoofyRPC(self)
320 self.goofy_rpc.RegisterMethods(self.state_instance)
Jon Salz0697cbf2012-07-04 15:14:04 +0800321 logging.info('Starting state server')
322 self.state_server_thread = threading.Thread(
323 target=self.state_server.serve_forever,
324 name='StateServer')
325 self.state_server_thread.start()
326
327 def start_event_server(self):
328 self.event_server = EventServer()
329 logging.info('Starting factory event server')
330 self.event_server_thread = threading.Thread(
331 target=self.event_server.serve_forever,
332 name='EventServer') # pylint: disable=E1101
333 self.event_server_thread.start()
334
335 self.event_client = EventClient(
336 callback=self.handle_event, event_loop=self.run_queue)
337
338 self.web_socket_manager = WebSocketManager(self.uuid)
339 self.state_server.add_handler("/event",
340 self.web_socket_manager.handle_web_socket)
341
342 def start_ui(self):
343 ui_proc_args = [
344 os.path.join(factory.FACTORY_PACKAGE_PATH, 'test', 'ui.py'),
345 self.options.test_list]
346 if self.options.verbose:
347 ui_proc_args.append('-v')
348 logging.info('Starting ui %s', ui_proc_args)
Jon Salz78c32392012-07-25 14:18:29 +0800349 self.ui_process = Spawn(ui_proc_args)
Jon Salz0697cbf2012-07-04 15:14:04 +0800350 logging.info('Waiting for UI to come up...')
351 self.event_client.wait(
352 lambda event: event.type == Event.Type.UI_READY)
353 logging.info('UI has started')
354
355 def set_visible_test(self, test):
356 if self.visible_test == test:
357 return
Jon Salz2f2d42c2012-07-30 12:30:34 +0800358 if test and not test.has_ui:
359 return
Jon Salz0697cbf2012-07-04 15:14:04 +0800360
361 if test:
362 test.update_state(visible=True)
363 if self.visible_test:
364 self.visible_test.update_state(visible=False)
365 self.visible_test = test
366
Jon Salzd4306c82012-11-30 15:16:36 +0800367 def _log_startup_messages(self):
368 '''Logs the tail of var/log/messages and mosys and EC console logs.'''
369 # TODO(jsalz): This is mostly a copy-and-paste of code in init_states,
370 # for factory-3004.B only. Consolidate and merge back to ToT.
371 if utils.in_chroot():
372 return
373
374 try:
375 var_log_messages = (
376 utils.var_log_messages_before_reboot())
377 logging.info(
378 'Tail of /var/log/messages before last reboot:\n'
379 '%s', ('\n'.join(
380 ' ' + x for x in var_log_messages)))
381 except: # pylint: disable=W0702
382 logging.exception('Unable to grok /var/log/messages')
383
384 try:
385 mosys_log = utils.Spawn(
386 ['mosys', 'eventlog', 'list'],
387 read_stdout=True, log_stderr_on_error=True).stdout_data
388 logging.info('System eventlog from mosys:\n%s\n', mosys_log)
389 except: # pylint: disable=W0702
390 logging.exception('Unable to read mosys eventlog')
391
392 try:
Vic Yang8341dde2013-01-29 16:48:52 +0800393 board = system.GetBoard()
394 ec_console_log = board.GetECConsoleLog()
Jon Salzd4306c82012-11-30 15:16:36 +0800395 logging.info('EC console log after reboot:\n%s\n', ec_console_log)
396 except: # pylint: disable=W0702
397 logging.exception('Error retrieving EC console log')
398
Vic Yang079f9872013-07-01 11:32:00 +0800399 try:
400 board = system.GetBoard()
401 ec_panic_info = board.GetECPanicInfo()
402 logging.info('EC panic info after reboot:\n%s\n', ec_panic_info)
403 except: # pylint: disable=W0702
404 logging.exception('Error retrieving EC panic info')
405
Jon Salz0697cbf2012-07-04 15:14:04 +0800406 def handle_shutdown_complete(self, test, test_state):
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800407 '''
Jon Salz0697cbf2012-07-04 15:14:04 +0800408 Handles the case where a shutdown was detected during a shutdown step.
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800409
Jon Salz0697cbf2012-07-04 15:14:04 +0800410 @param test: The ShutdownStep.
411 @param test_state: The test state.
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800412 '''
Jon Salz0697cbf2012-07-04 15:14:04 +0800413 test_state = test.update_state(increment_shutdown_count=1)
414 logging.info('Detected shutdown (%d of %d)',
415 test_state.shutdown_count, test.iterations)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800416
Jon Salz0697cbf2012-07-04 15:14:04 +0800417 def log_and_update_state(status, error_msg, **kw):
418 self.event_log.Log('rebooted',
419 status=status, error_msg=error_msg, **kw)
Jon Salzd4306c82012-11-30 15:16:36 +0800420 logging.info('Rebooted: status=%s, %s', status,
421 (('error_msg=%s' % error_msg) if error_msg else None))
Jon Salz0697cbf2012-07-04 15:14:04 +0800422 test.update_state(status=status, error_msg=error_msg)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800423
Jon Salz0697cbf2012-07-04 15:14:04 +0800424 if not self.last_shutdown_time:
425 log_and_update_state(status=TestState.FAILED,
426 error_msg='Unable to read shutdown_time')
427 return
Jon Salz258a40c2012-04-19 12:34:01 +0800428
Jon Salz0697cbf2012-07-04 15:14:04 +0800429 now = time.time()
430 logging.info('%.03f s passed since reboot',
431 now - self.last_shutdown_time)
Jon Salz258a40c2012-04-19 12:34:01 +0800432
Jon Salz0697cbf2012-07-04 15:14:04 +0800433 if self.last_shutdown_time > now:
434 test.update_state(status=TestState.FAILED,
435 error_msg='Time moved backward during reboot')
436 elif (isinstance(test, factory.RebootStep) and
437 self.test_list.options.max_reboot_time_secs and
438 (now - self.last_shutdown_time >
439 self.test_list.options.max_reboot_time_secs)):
440 # A reboot took too long; fail. (We don't check this for
441 # HaltSteps, because the machine could be halted for a
442 # very long time, and even unplugged with battery backup,
443 # thus hosing the clock.)
444 log_and_update_state(
445 status=TestState.FAILED,
446 error_msg=('More than %d s elapsed during reboot '
447 '(%.03f s, from %s to %s)' % (
448 self.test_list.options.max_reboot_time_secs,
449 now - self.last_shutdown_time,
450 utils.TimeString(self.last_shutdown_time),
451 utils.TimeString(now))),
452 duration=(now-self.last_shutdown_time))
Jon Salzd4306c82012-11-30 15:16:36 +0800453 self._log_startup_messages()
Jon Salz0697cbf2012-07-04 15:14:04 +0800454 elif test_state.shutdown_count == test.iterations:
455 # Good!
456 log_and_update_state(status=TestState.PASSED,
457 duration=(now - self.last_shutdown_time),
458 error_msg='')
459 elif test_state.shutdown_count > test.iterations:
460 # Shut down too many times
461 log_and_update_state(status=TestState.FAILED,
462 error_msg='Too many shutdowns')
Jon Salzd4306c82012-11-30 15:16:36 +0800463 self._log_startup_messages()
Jon Salz0697cbf2012-07-04 15:14:04 +0800464 elif utils.are_shift_keys_depressed():
465 logging.info('Shift keys are depressed; cancelling restarts')
466 # Abort shutdown
467 log_and_update_state(
468 status=TestState.FAILED,
469 error_msg='Shutdown aborted with double shift keys')
Jon Salza6711d72012-07-18 14:33:03 +0800470 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +0800471 else:
472 def handler():
473 if self._prompt_cancel_shutdown(
474 test, test_state.shutdown_count + 1):
Jon Salza6711d72012-07-18 14:33:03 +0800475 factory.console.info('Shutdown aborted by operator')
Jon Salz0697cbf2012-07-04 15:14:04 +0800476 log_and_update_state(
477 status=TestState.FAILED,
478 error_msg='Shutdown aborted by operator')
Jon Salza6711d72012-07-18 14:33:03 +0800479 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +0800480 return
Jon Salz0405ab52012-03-16 15:26:52 +0800481
Jon Salz0697cbf2012-07-04 15:14:04 +0800482 # Time to shutdown again
483 log_and_update_state(
484 status=TestState.ACTIVE,
485 error_msg='',
486 iteration=test_state.shutdown_count)
Jon Salz73e0fd02012-04-04 11:46:38 +0800487
Jon Salz0697cbf2012-07-04 15:14:04 +0800488 self.event_log.Log('shutdown', operation='reboot')
489 self.state_instance.set_shared_data('shutdown_time',
490 time.time())
491 self.env.shutdown('reboot')
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800492
Jon Salz0697cbf2012-07-04 15:14:04 +0800493 self.on_ui_startup.append(handler)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800494
Jon Salz0697cbf2012-07-04 15:14:04 +0800495 def _prompt_cancel_shutdown(self, test, iteration):
496 if self.options.ui != 'chrome':
497 return False
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800498
Jon Salz0697cbf2012-07-04 15:14:04 +0800499 pending_shutdown_data = {
500 'delay_secs': test.delay_secs,
501 'time': time.time() + test.delay_secs,
502 'operation': test.operation,
503 'iteration': iteration,
504 'iterations': test.iterations,
505 }
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800506
Jon Salz0697cbf2012-07-04 15:14:04 +0800507 # Create a new (threaded) event client since we
508 # don't want to use the event loop for this.
509 with EventClient() as event_client:
510 event_client.post_event(Event(Event.Type.PENDING_SHUTDOWN,
511 **pending_shutdown_data))
512 aborted = event_client.wait(
513 lambda event: event.type == Event.Type.CANCEL_SHUTDOWN,
514 timeout=test.delay_secs) is not None
515 if aborted:
516 event_client.post_event(Event(Event.Type.PENDING_SHUTDOWN))
517 return aborted
Jon Salz258a40c2012-04-19 12:34:01 +0800518
Jon Salz0697cbf2012-07-04 15:14:04 +0800519 def init_states(self):
520 '''
521 Initializes all states on startup.
522 '''
523 for test in self.test_list.get_all_tests():
524 # Make sure the state server knows about all the tests,
525 # defaulting to an untested state.
526 test.update_state(update_parent=False, visible=False)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800527
Jon Salz0697cbf2012-07-04 15:14:04 +0800528 var_log_messages = None
Vic Yanga9c32212012-08-16 20:07:54 +0800529 mosys_log = None
Vic Yange4c275d2012-08-28 01:50:20 +0800530 ec_console_log = None
Vic Yang079f9872013-07-01 11:32:00 +0800531 ec_panic_info = None
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800532
Jon Salz0697cbf2012-07-04 15:14:04 +0800533 # Any 'active' tests should be marked as failed now.
534 for test in self.test_list.walk():
Jon Salza6711d72012-07-18 14:33:03 +0800535 if not test.is_leaf():
536 # Don't bother with parents; they will be updated when their
537 # children are updated.
538 continue
539
Jon Salz0697cbf2012-07-04 15:14:04 +0800540 test_state = test.get_state()
541 if test_state.status != TestState.ACTIVE:
542 continue
543 if isinstance(test, factory.ShutdownStep):
544 # Shutdown while the test was active - that's good.
545 self.handle_shutdown_complete(test, test_state)
546 else:
547 # Unexpected shutdown. Grab /var/log/messages for context.
548 if var_log_messages is None:
549 try:
550 var_log_messages = (
551 utils.var_log_messages_before_reboot())
552 # Write it to the log, to make it easier to
553 # correlate with /var/log/messages.
554 logging.info(
555 'Unexpected shutdown. '
556 'Tail of /var/log/messages before last reboot:\n'
557 '%s', ('\n'.join(
558 ' ' + x for x in var_log_messages)))
559 except: # pylint: disable=W0702
560 logging.exception('Unable to grok /var/log/messages')
561 var_log_messages = []
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800562
Jon Salz008f4ea2012-08-28 05:39:45 +0800563 if mosys_log is None and not utils.in_chroot():
564 try:
565 mosys_log = utils.Spawn(
566 ['mosys', 'eventlog', 'list'],
567 read_stdout=True, log_stderr_on_error=True).stdout_data
568 # Write it to the log also.
569 logging.info('System eventlog from mosys:\n%s\n', mosys_log)
570 except: # pylint: disable=W0702
571 logging.exception('Unable to read mosys eventlog')
Vic Yanga9c32212012-08-16 20:07:54 +0800572
Vic Yange4c275d2012-08-28 01:50:20 +0800573 if ec_console_log is None:
574 try:
Vic Yang8341dde2013-01-29 16:48:52 +0800575 board = system.GetBoard()
576 ec_console_log = board.GetECConsoleLog()
Vic Yange4c275d2012-08-28 01:50:20 +0800577 logging.info('EC console log after reboot:\n%s\n', ec_console_log)
Jon Salzfe1f6652012-09-07 05:40:14 +0800578 except: # pylint: disable=W0702
Vic Yange4c275d2012-08-28 01:50:20 +0800579 logging.exception('Error retrieving EC console log')
580
Vic Yang079f9872013-07-01 11:32:00 +0800581 if ec_panic_info is None:
582 try:
583 board = system.GetBoard()
584 ec_panic_info = board.GetECPanicInfo()
585 logging.info('EC panic info after reboot:\n%s\n', ec_panic_info)
586 except: # pylint: disable=W0702
587 logging.exception('Error retrieving EC panic info')
588
Jon Salz0697cbf2012-07-04 15:14:04 +0800589 error_msg = 'Unexpected shutdown while test was running'
590 self.event_log.Log('end_test',
591 path=test.path,
592 status=TestState.FAILED,
593 invocation=test.get_state().invocation,
594 error_msg=error_msg,
Vic Yanga9c32212012-08-16 20:07:54 +0800595 var_log_messages='\n'.join(var_log_messages),
596 mosys_log=mosys_log)
Jon Salz0697cbf2012-07-04 15:14:04 +0800597 test.update_state(
598 status=TestState.FAILED,
599 error_msg=error_msg)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800600
Jon Salz50efe942012-07-26 11:54:10 +0800601 if not test.never_fails:
602 # For "never_fails" tests (such as "Start"), don't cancel
603 # pending tests, since reboot is expected.
604 factory.console.info('Unexpected shutdown while test %s '
605 'running; cancelling any pending tests',
606 test.path)
607 self.state_instance.set_shared_data('tests_after_shutdown', [])
Jon Salz69806bb2012-07-20 18:05:02 +0800608
Jon Salz008f4ea2012-08-28 05:39:45 +0800609 self.update_skipped_tests()
610
611 def update_skipped_tests(self):
612 '''
613 Updates skipped states based on run_if.
614 '''
615 for t in self.test_list.walk():
616 if t.is_leaf() and t.run_if_table_name:
617 skip = False
618 try:
619 aux = shopfloor.get_selected_aux_data(t.run_if_table_name)
620 value = aux.get(t.run_if_col)
621 if value is not None:
622 skip = (not value) ^ t.run_if_not
623 except ValueError:
624 # Not available; assume it shouldn't be skipped
625 pass
626
627 test_state = t.get_state()
628 if ((not skip) and
629 (test_state.status == TestState.PASSED) and
630 (test_state.error_msg == TestState.SKIPPED_MSG)):
631 # It was marked as skipped before, but now we need to run it.
632 # Mark as untested.
633 t.update_state(skip=skip, status=TestState.UNTESTED, error_msg='')
634 else:
635 t.update_state(skip=skip)
636
Jon Salz0697cbf2012-07-04 15:14:04 +0800637 def show_next_active_test(self):
638 '''
639 Rotates to the next visible active test.
640 '''
641 self.reap_completed_tests()
642 active_tests = [
643 t for t in self.test_list.walk()
644 if t.is_leaf() and t.get_state().status == TestState.ACTIVE]
645 if not active_tests:
646 return
Jon Salz4f6c7172012-06-11 20:45:36 +0800647
Jon Salz0697cbf2012-07-04 15:14:04 +0800648 try:
649 next_test = active_tests[
650 (active_tests.index(self.visible_test) + 1) % len(active_tests)]
651 except ValueError: # visible_test not present in active_tests
652 next_test = active_tests[0]
Jon Salz4f6c7172012-06-11 20:45:36 +0800653
Jon Salz0697cbf2012-07-04 15:14:04 +0800654 self.set_visible_test(next_test)
Jon Salz4f6c7172012-06-11 20:45:36 +0800655
Jon Salz0697cbf2012-07-04 15:14:04 +0800656 def handle_event(self, event):
657 '''
658 Handles an event from the event server.
659 '''
660 handler = self.event_handlers.get(event.type)
661 if handler:
662 handler(event)
663 else:
664 # We don't register handlers for all event types - just ignore
665 # this event.
666 logging.debug('Unbound event type %s', event.type)
Jon Salz4f6c7172012-06-11 20:45:36 +0800667
Vic Yangaabf9fd2013-04-09 18:56:13 +0800668 def check_critical_factory_note(self):
669 '''
670 Returns True if the last factory note is critical.
671 '''
672 notes = self.state_instance.get_shared_data('factory_note', True)
673 return notes and notes[-1]['level'] == 'CRITICAL'
674
Jon Salz0697cbf2012-07-04 15:14:04 +0800675 def run_next_test(self):
676 '''
677 Runs the next eligible test (or tests) in self.tests_to_run.
678 '''
679 self.reap_completed_tests()
Vic Yangaabf9fd2013-04-09 18:56:13 +0800680 if self.tests_to_run and self.check_critical_factory_note():
681 self.tests_to_run.clear()
682 return
Jon Salz0697cbf2012-07-04 15:14:04 +0800683 while self.tests_to_run:
684 logging.debug('Tests to run: %s',
685 [x.path for x in self.tests_to_run])
Jon Salz94eb56f2012-06-12 18:01:12 +0800686
Jon Salz0697cbf2012-07-04 15:14:04 +0800687 test = self.tests_to_run[0]
Jon Salz94eb56f2012-06-12 18:01:12 +0800688
Jon Salz0697cbf2012-07-04 15:14:04 +0800689 if test in self.invocations:
690 logging.info('Next test %s is already running', test.path)
691 self.tests_to_run.popleft()
692 return
Jon Salz94eb56f2012-06-12 18:01:12 +0800693
Jon Salza1412922012-07-23 16:04:17 +0800694 for requirement in test.require_run:
695 for i in requirement.test.walk():
696 if i.get_state().status == TestState.ACTIVE:
Jon Salz304a75d2012-07-06 11:14:15 +0800697 logging.info('Waiting for active test %s to complete '
Jon Salza1412922012-07-23 16:04:17 +0800698 'before running %s', i.path, test.path)
Jon Salz304a75d2012-07-06 11:14:15 +0800699 return
700
Jon Salz0697cbf2012-07-04 15:14:04 +0800701 if self.invocations and not (test.backgroundable and all(
702 [x.backgroundable for x in self.invocations])):
703 logging.debug('Waiting for non-backgroundable tests to '
704 'complete before running %s', test.path)
705 return
Jon Salz94eb56f2012-06-12 18:01:12 +0800706
Jon Salz3e6f5202012-10-15 15:08:29 +0800707 if test.get_state().skip:
708 factory.console.info('Skipping test %s', test.path)
709 test.update_state(status=TestState.PASSED,
710 error_msg=TestState.SKIPPED_MSG)
711 self.tests_to_run.popleft()
712 continue
713
Jon Salz0697cbf2012-07-04 15:14:04 +0800714 self.tests_to_run.popleft()
Jon Salz94eb56f2012-06-12 18:01:12 +0800715
Jon Salz304a75d2012-07-06 11:14:15 +0800716 untested = set()
Jon Salza1412922012-07-23 16:04:17 +0800717 for requirement in test.require_run:
718 for i in requirement.test.walk():
719 if i == test:
Jon Salz304a75d2012-07-06 11:14:15 +0800720 # We've hit this test itself; stop checking
721 break
Jon Salza1412922012-07-23 16:04:17 +0800722 if ((i.get_state().status == TestState.UNTESTED) or
723 (requirement.passed and i.get_state().status !=
724 TestState.PASSED)):
Jon Salz304a75d2012-07-06 11:14:15 +0800725 # Found an untested test; move on to the next
726 # element in require_run.
Jon Salza1412922012-07-23 16:04:17 +0800727 untested.add(i)
Jon Salz304a75d2012-07-06 11:14:15 +0800728 break
729
730 if untested:
731 untested_paths = ', '.join(sorted([x.path for x in untested]))
732 if self.state_instance.get_shared_data('engineering_mode',
733 optional=True):
734 # In engineering mode, we'll let it go.
735 factory.console.warn('In engineering mode; running '
736 '%s even though required tests '
737 '[%s] have not completed',
738 test.path, untested_paths)
739 else:
740 # Not in engineering mode; mark it failed.
741 error_msg = ('Required tests [%s] have not been run yet'
742 % untested_paths)
743 factory.console.error('Not running %s: %s',
744 test.path, error_msg)
745 test.update_state(status=TestState.FAILED,
746 error_msg=error_msg)
747 continue
748
Jon Salz0697cbf2012-07-04 15:14:04 +0800749 if isinstance(test, factory.ShutdownStep):
750 if os.path.exists(NO_REBOOT_FILE):
751 test.update_state(
752 status=TestState.FAILED, increment_count=1,
753 error_msg=('Skipped shutdown since %s is present' %
Jon Salz304a75d2012-07-06 11:14:15 +0800754 NO_REBOOT_FILE))
Jon Salz0697cbf2012-07-04 15:14:04 +0800755 continue
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800756
Jon Salz0697cbf2012-07-04 15:14:04 +0800757 test.update_state(status=TestState.ACTIVE, increment_count=1,
758 error_msg='', shutdown_count=0)
759 if self._prompt_cancel_shutdown(test, 1):
760 self.event_log.Log('reboot_cancelled')
761 test.update_state(
762 status=TestState.FAILED, increment_count=1,
763 error_msg='Shutdown aborted by operator',
764 shutdown_count=0)
chungyiafe8f772012-08-15 19:36:29 +0800765 continue
Jon Salz2f757d42012-06-27 17:06:42 +0800766
Jon Salz0697cbf2012-07-04 15:14:04 +0800767 # Save pending test list in the state server
Jon Salzdbf398f2012-06-14 17:30:01 +0800768 self.state_instance.set_shared_data(
Jon Salz0697cbf2012-07-04 15:14:04 +0800769 'tests_after_shutdown',
770 [t.path for t in self.tests_to_run])
771 # Save shutdown time
772 self.state_instance.set_shared_data('shutdown_time',
773 time.time())
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800774
Jon Salz0697cbf2012-07-04 15:14:04 +0800775 with self.env.lock:
776 self.event_log.Log('shutdown', operation=test.operation)
777 shutdown_result = self.env.shutdown(test.operation)
778 if shutdown_result:
779 # That's all, folks!
780 self.run_queue.put(None)
781 return
782 else:
783 # Just pass (e.g., in the chroot).
784 test.update_state(status=TestState.PASSED)
785 self.state_instance.set_shared_data(
786 'tests_after_shutdown', None)
787 # Send event with no fields to indicate that there is no
788 # longer a pending shutdown.
789 self.event_client.post_event(Event(
790 Event.Type.PENDING_SHUTDOWN))
791 continue
Jon Salz258a40c2012-04-19 12:34:01 +0800792
Cheng-Yi Chiangce05c002013-04-04 02:13:17 +0800793 self._run_test(test, test.iterations, test.retries)
Jon Salz1acc8742012-07-17 17:45:55 +0800794
Cheng-Yi Chiangce05c002013-04-04 02:13:17 +0800795 def _run_test(self, test, iterations_left=None, retries_left=None):
Jon Salz1acc8742012-07-17 17:45:55 +0800796 invoc = TestInvocation(self, test, on_completion=self.run_next_test)
797 new_state = test.update_state(
798 status=TestState.ACTIVE, increment_count=1, error_msg='',
Jon Salzbd42ce12012-09-18 08:03:59 +0800799 invocation=invoc.uuid, iterations_left=iterations_left,
Cheng-Yi Chiangce05c002013-04-04 02:13:17 +0800800 retries_left=retries_left,
Jon Salzbd42ce12012-09-18 08:03:59 +0800801 visible=(self.visible_test == test))
Jon Salz1acc8742012-07-17 17:45:55 +0800802 invoc.count = new_state.count
803
804 self.invocations[test] = invoc
805 if self.visible_test is None and test.has_ui:
806 self.set_visible_test(test)
Vic Yang311ddb82012-09-26 12:08:28 +0800807 self.check_exclusive()
Jon Salz1acc8742012-07-17 17:45:55 +0800808 invoc.start()
Jon Salz5f2a0672012-05-22 17:14:06 +0800809
Vic Yang311ddb82012-09-26 12:08:28 +0800810 def check_exclusive(self):
Jon Salzce6a7f82013-06-10 18:22:54 +0800811 # alias since this is really long
812 EXCL_OPT = factory.FactoryTest.EXCLUSIVE_OPTIONS
813
Vic Yang311ddb82012-09-26 12:08:28 +0800814 current_exclusive_items = set([
Jon Salzce6a7f82013-06-10 18:22:54 +0800815 item for item in EXCL_OPT
Vic Yang311ddb82012-09-26 12:08:28 +0800816 if any([test.is_exclusive(item) for test in self.invocations])])
817
818 new_exclusive_items = current_exclusive_items - self.exclusive_items
Jon Salzce6a7f82013-06-10 18:22:54 +0800819 if EXCL_OPT.NETWORKING in new_exclusive_items:
Vic Yang311ddb82012-09-26 12:08:28 +0800820 logging.info('Disabling network')
821 self.connection_manager.DisableNetworking()
Jon Salzce6a7f82013-06-10 18:22:54 +0800822 if EXCL_OPT.CHARGER in new_exclusive_items:
Vic Yang311ddb82012-09-26 12:08:28 +0800823 logging.info('Stop controlling charger')
824
825 new_non_exclusive_items = self.exclusive_items - current_exclusive_items
Jon Salzce6a7f82013-06-10 18:22:54 +0800826 if EXCL_OPT.NETWORKING in new_non_exclusive_items:
Vic Yang311ddb82012-09-26 12:08:28 +0800827 logging.info('Re-enabling network')
828 self.connection_manager.EnableNetworking()
Jon Salzce6a7f82013-06-10 18:22:54 +0800829 if EXCL_OPT.CHARGER in new_non_exclusive_items:
Vic Yang311ddb82012-09-26 12:08:28 +0800830 logging.info('Start controlling charger')
831
Jon Salzce6a7f82013-06-10 18:22:54 +0800832 if self.cpufreq_manager:
833 enabled = EXCL_OPT.CPUFREQ not in current_exclusive_items
834 try:
835 self.cpufreq_manager.SetEnabled(enabled)
836 except: # pylint: disable=W0702
837 logging.exception('Unable to %s cpufreq services',
838 'enable' if enabled else 'disable')
839
Vic Yang311ddb82012-09-26 12:08:28 +0800840 # Only adjust charge state if not excluded
Jon Salzce6a7f82013-06-10 18:22:54 +0800841 if (EXCL_OPT.CHARGER not in current_exclusive_items and
842 not utils.in_chroot()):
Cheng-Yi Chiangd8186952013-04-04 23:41:14 +0800843 if self.charge_manager:
844 self.charge_manager.AdjustChargeState()
845 else:
846 try:
847 system.GetBoard().SetChargeState(Board.ChargeState.CHARGE)
848 except BoardException:
849 logging.exception('Unable to set charge state on this board')
Vic Yang311ddb82012-09-26 12:08:28 +0800850
851 self.exclusive_items = current_exclusive_items
Jon Salz5da61e62012-05-31 13:06:22 +0800852
cychiang21886742012-07-05 15:16:32 +0800853 def check_for_updates(self):
854 '''
855 Schedules an asynchronous check for updates if necessary.
856 '''
857 if not self.test_list.options.update_period_secs:
858 # Not enabled.
859 return
860
861 now = time.time()
862 if self.last_update_check and (
863 now - self.last_update_check <
864 self.test_list.options.update_period_secs):
865 # Not yet time for another check.
866 return
867
868 self.last_update_check = now
869
870 def handle_check_for_update(reached_shopfloor, md5sum, needs_update):
871 if reached_shopfloor:
872 new_update_md5sum = md5sum if needs_update else None
873 if system.SystemInfo.update_md5sum != new_update_md5sum:
874 logging.info('Received new update MD5SUM: %s', new_update_md5sum)
875 system.SystemInfo.update_md5sum = new_update_md5sum
876 self.run_queue.put(self.update_system_info)
877
878 updater.CheckForUpdateAsync(
879 handle_check_for_update,
880 self.test_list.options.shopfloor_timeout_secs)
881
Jon Salza6711d72012-07-18 14:33:03 +0800882 def cancel_pending_tests(self):
883 '''Cancels any tests in the run queue.'''
884 self.run_tests([])
885
Jon Salz0697cbf2012-07-04 15:14:04 +0800886 def run_tests(self, subtrees, untested_only=False):
887 '''
888 Runs tests under subtree.
Jon Salz258a40c2012-04-19 12:34:01 +0800889
Jon Salz0697cbf2012-07-04 15:14:04 +0800890 The tests are run in order unless one fails (then stops).
891 Backgroundable tests are run simultaneously; when a foreground test is
892 encountered, we wait for all active tests to finish before continuing.
Jon Salzb1b39092012-05-03 02:05:09 +0800893
Jon Salz0697cbf2012-07-04 15:14:04 +0800894 @param subtrees: Node or nodes containing tests to run (may either be
895 a single test or a list). Duplicates will be ignored.
896 '''
897 if type(subtrees) != list:
898 subtrees = [subtrees]
Jon Salz258a40c2012-04-19 12:34:01 +0800899
Jon Salz0697cbf2012-07-04 15:14:04 +0800900 # Nodes we've seen so far, to avoid duplicates.
901 seen = set()
Jon Salz94eb56f2012-06-12 18:01:12 +0800902
Jon Salz0697cbf2012-07-04 15:14:04 +0800903 self.tests_to_run = deque()
904 for subtree in subtrees:
905 for test in subtree.walk():
906 if test in seen:
907 continue
908 seen.add(test)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800909
Jon Salz0697cbf2012-07-04 15:14:04 +0800910 if not test.is_leaf():
911 continue
912 if (untested_only and
913 test.get_state().status != TestState.UNTESTED):
914 continue
915 self.tests_to_run.append(test)
916 self.run_next_test()
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800917
Jon Salz0697cbf2012-07-04 15:14:04 +0800918 def reap_completed_tests(self):
919 '''
920 Removes completed tests from the set of active tests.
921
922 Also updates the visible test if it was reaped.
923 '''
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +0800924 test_completed = False
Jon Salz0697cbf2012-07-04 15:14:04 +0800925 for t, v in dict(self.invocations).iteritems():
926 if v.is_completed():
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +0800927 test_completed = True
Jon Salz1acc8742012-07-17 17:45:55 +0800928 new_state = t.update_state(**v.update_state_on_completion)
Jon Salz0697cbf2012-07-04 15:14:04 +0800929 del self.invocations[t]
930
Chun-Ta Lin54e17e42012-09-06 22:05:13 +0800931 # Stop on failure if flag is true.
932 if (self.test_list.options.stop_on_failure and
933 new_state.status == TestState.FAILED):
934 # Clean all the tests to cause goofy to stop.
935 self.tests_to_run = []
936 factory.console.info("Stop on failure triggered. Empty the queue.")
937
Jon Salz1acc8742012-07-17 17:45:55 +0800938 if new_state.iterations_left and new_state.status == TestState.PASSED:
939 # Play it again, Sam!
940 self._run_test(t)
Cheng-Yi Chiangce05c002013-04-04 02:13:17 +0800941 # new_state.retries_left is obtained after update.
942 # For retries_left == 0, test can still be run for the last time.
943 elif (new_state.retries_left >= 0 and
944 new_state.status == TestState.FAILED):
945 # Still have to retry, Sam!
946 self._run_test(t)
Jon Salz1acc8742012-07-17 17:45:55 +0800947
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +0800948 if test_completed:
Vic Yangf01c59f2013-04-19 17:37:56 +0800949 self.log_watcher.KickWatchThread()
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +0800950
Jon Salz0697cbf2012-07-04 15:14:04 +0800951 if (self.visible_test is None or
Jon Salz85a39882012-07-05 16:45:04 +0800952 self.visible_test not in self.invocations):
Jon Salz0697cbf2012-07-04 15:14:04 +0800953 self.set_visible_test(None)
954 # Make the first running test, if any, the visible test
955 for t in self.test_list.walk():
956 if t in self.invocations:
957 self.set_visible_test(t)
958 break
959
Jon Salz6dc031d2013-06-19 13:06:23 +0800960 def kill_active_tests(self, abort, root=None, reason=None):
Jon Salz0697cbf2012-07-04 15:14:04 +0800961 '''
962 Kills and waits for all active tests.
963
Jon Salz85a39882012-07-05 16:45:04 +0800964 Args:
965 abort: True to change state of killed tests to FAILED, False for
Jon Salz0697cbf2012-07-04 15:14:04 +0800966 UNTESTED.
Jon Salz85a39882012-07-05 16:45:04 +0800967 root: If set, only kills tests with root as an ancestor.
Jon Salz0697cbf2012-07-04 15:14:04 +0800968 '''
969 self.reap_completed_tests()
970 for test, invoc in self.invocations.items():
Jon Salz85a39882012-07-05 16:45:04 +0800971 if root and not test.has_ancestor(root):
972 continue
973
Jon Salz0697cbf2012-07-04 15:14:04 +0800974 factory.console.info('Killing active test %s...' % test.path)
Jon Salz6dc031d2013-06-19 13:06:23 +0800975 invoc.abort_and_join(reason)
Jon Salz0697cbf2012-07-04 15:14:04 +0800976 factory.console.info('Killed %s' % test.path)
Jon Salz1acc8742012-07-17 17:45:55 +0800977 test.update_state(**invoc.update_state_on_completion)
Jon Salz0697cbf2012-07-04 15:14:04 +0800978 del self.invocations[test]
Jon Salz1acc8742012-07-17 17:45:55 +0800979
Jon Salz0697cbf2012-07-04 15:14:04 +0800980 if not abort:
981 test.update_state(status=TestState.UNTESTED)
982 self.reap_completed_tests()
983
Jon Salz6dc031d2013-06-19 13:06:23 +0800984 def stop(self, root=None, fail=False, reason=None):
985 self.kill_active_tests(fail, root, reason)
Jon Salz85a39882012-07-05 16:45:04 +0800986 # Remove any tests in the run queue under the root.
987 self.tests_to_run = deque([x for x in self.tests_to_run
988 if root and not x.has_ancestor(root)])
989 self.run_next_test()
Jon Salz0697cbf2012-07-04 15:14:04 +0800990
Jon Salz4712ac72013-02-07 17:12:05 +0800991 def clear_state(self, root=None):
Jon Salz6dc031d2013-06-19 13:06:23 +0800992 self.stop(root, reason='Clearing test state')
Jon Salz4712ac72013-02-07 17:12:05 +0800993 for f in root.walk():
994 if f.is_leaf():
995 f.update_state(status=TestState.UNTESTED)
996
Jon Salz6dc031d2013-06-19 13:06:23 +0800997 def abort_active_tests(self, reason=None):
998 self.kill_active_tests(True, reason=reason)
Jon Salz0697cbf2012-07-04 15:14:04 +0800999
1000 def main(self):
Jon Salzeff94182013-06-19 15:06:28 +08001001 syslog.openlog('goofy')
1002
Jon Salz0697cbf2012-07-04 15:14:04 +08001003 try:
1004 self.init()
1005 self.event_log.Log('goofy_init',
1006 success=True)
1007 except:
1008 if self.event_log:
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001009 try:
Jon Salz0697cbf2012-07-04 15:14:04 +08001010 self.event_log.Log('goofy_init',
1011 success=False,
1012 trace=traceback.format_exc())
1013 except: # pylint: disable=W0702
1014 pass
1015 raise
1016
Jon Salzeff94182013-06-19 15:06:28 +08001017 syslog.syslog('Goofy (factory test harness) starting')
Jon Salz0697cbf2012-07-04 15:14:04 +08001018 self.run()
1019
1020 def update_system_info(self):
1021 '''Updates system info.'''
1022 system_info = system.SystemInfo()
1023 self.state_instance.set_shared_data('system_info', system_info.__dict__)
1024 self.event_client.post_event(Event(Event.Type.SYSTEM_INFO,
1025 system_info=system_info.__dict__))
1026 logging.info('System info: %r', system_info.__dict__)
1027
Jon Salzeb42f0d2012-07-27 19:14:04 +08001028 def update_factory(self, auto_run_on_restart=False, post_update_hook=None):
1029 '''Commences updating factory software.
1030
1031 Args:
1032 auto_run_on_restart: Auto-run when the machine comes back up.
1033 post_update_hook: Code to call after update but immediately before
1034 restart.
1035
1036 Returns:
1037 Never if the update was successful (we just reboot).
1038 False if the update was unnecessary (no update available).
1039 '''
Jon Salz6dc031d2013-06-19 13:06:23 +08001040 self.kill_active_tests(False, reason='Factory software update')
Jon Salza6711d72012-07-18 14:33:03 +08001041 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +08001042
Jon Salz5c344f62012-07-13 14:31:16 +08001043 def pre_update_hook():
1044 if auto_run_on_restart:
1045 self.state_instance.set_shared_data('tests_after_shutdown',
1046 FORCE_AUTO_RUN)
1047 self.state_instance.close()
1048
Jon Salzeb42f0d2012-07-27 19:14:04 +08001049 if updater.TryUpdate(pre_update_hook=pre_update_hook):
1050 if post_update_hook:
1051 post_update_hook()
1052 self.env.shutdown('reboot')
Jon Salz0697cbf2012-07-04 15:14:04 +08001053
Jon Salzcef132a2012-08-30 04:58:08 +08001054 def handle_sigint(self, dummy_signum, dummy_frame):
Jon Salz77c151e2012-08-28 07:20:37 +08001055 logging.error('Received SIGINT')
1056 self.run_queue.put(None)
1057 raise KeyboardInterrupt()
1058
Jon Salze12c2b32013-06-25 16:24:34 +08001059 def find_kcrashes(self):
1060 """Finds kcrash files, logs them, and marks them as seen."""
1061 seen_crashes = set(
1062 self.state_instance.get_shared_data('seen_crashes', optional=True)
1063 or [])
1064
1065 for path in glob.glob('/var/spool/crash/*'):
1066 if not os.path.isfile(path):
1067 continue
1068 if path in seen_crashes:
1069 continue
1070 try:
1071 stat = os.stat(path)
1072 mtime = utils.TimeString(stat.st_mtime)
1073 logging.info(
1074 'Found new crash file %s (%d bytes at %s)',
1075 path, stat.st_size, mtime)
1076 extra_log_args = {}
1077
1078 try:
1079 _, ext = os.path.splitext(path)
1080 if ext in ['.kcrash', '.meta']:
1081 ext = ext.replace('.', '')
1082 with open(path) as f:
1083 data = f.read(MAX_CRASH_FILE_SIZE)
1084 tell = f.tell()
1085 logging.info(
1086 'Contents of %s%s:%s',
1087 path,
1088 ('' if tell == stat.st_size
1089 else '(truncated to %d bytes)' % MAX_CRASH_FILE_SIZE),
1090 ('\n' + data).replace('\n', '\n ' + ext + '> '))
1091 extra_log_args['data'] = data
1092
1093 # Copy to /var/factory/kcrash for posterity
1094 kcrash_dir = factory.get_factory_root('kcrash')
1095 utils.TryMakeDirs(kcrash_dir)
1096 shutil.copy(path, kcrash_dir)
1097 logging.info('Copied to %s',
1098 os.path.join(kcrash_dir, os.path.basename(path)))
1099 finally:
1100 # Even if something goes wrong with the above, still try to
1101 # log to event log
1102 self.event_log.Log('crash_file',
1103 path=path, size=stat.st_size, mtime=mtime,
1104 **extra_log_args)
1105 except: # pylint: disable=W0702
1106 logging.exception('Unable to handle crash files %s', path)
1107 seen_crashes.add(path)
1108
1109 self.state_instance.set_shared_data('seen_crashes', list(seen_crashes))
1110
Jon Salz128b0932013-07-03 16:55:26 +08001111 def GetTestList(self, test_list_id):
1112 """Returns the test list with the given ID.
1113
1114 Raises:
1115 TestListError: The test list ID is not valid.
1116 """
1117 try:
1118 return self.test_lists[test_list_id]
1119 except KeyError:
1120 raise test_lists.TestListError(
1121 '%r is not a valid test list ID (available IDs are [%s])' % (
1122 test_list_id, ', '.join(sorted(self.test_lists.keys()))))
1123
1124 def InitTestLists(self):
1125 """Reads in all test lists and sets the active test list."""
1126 self.test_lists = test_lists.BuildAllTestLists()
1127
1128 if not self.options.test_list:
1129 self.options.test_list = test_lists.GetActiveTestListId()
1130
1131 if os.sep in self.options.test_list:
1132 # It's a path pointing to an old-style test list; use it.
1133 self.test_list = factory.read_test_list(self.options.test_list)
1134 else:
1135 self.test_list = self.GetTestList(self.options.test_list)
1136
1137 logging.info('Active test list: %s', self.test_list.test_list_id)
1138
1139 if isinstance(self.test_list, test_lists.OldStyleTestList):
1140 # Actually load it in. (See OldStyleTestList for an explanation
1141 # of why this is necessary.)
1142 self.test_list = self.test_list.Load()
1143
1144 self.test_list.state_instance = self.state_instance
1145
Jon Salz0697cbf2012-07-04 15:14:04 +08001146 def init(self, args=None, env=None):
1147 '''Initializes Goofy.
1148
1149 Args:
1150 args: A list of command-line arguments. Uses sys.argv if
1151 args is None.
1152 env: An Environment instance to use (or None to choose
1153 FakeChrootEnvironment or DUTEnvironment as appropriate).
1154 '''
Jon Salz77c151e2012-08-28 07:20:37 +08001155 signal.signal(signal.SIGINT, self.handle_sigint)
1156
Jon Salz0697cbf2012-07-04 15:14:04 +08001157 parser = OptionParser()
1158 parser.add_option('-v', '--verbose', dest='verbose',
Jon Salz8fa8e832012-07-13 19:04:09 +08001159 action='store_true',
1160 help='Enable debug logging')
Jon Salz0697cbf2012-07-04 15:14:04 +08001161 parser.add_option('--print_test_list', dest='print_test_list',
Jon Salz8fa8e832012-07-13 19:04:09 +08001162 metavar='FILE',
1163 help='Read and print test list FILE, and exit')
Jon Salz0697cbf2012-07-04 15:14:04 +08001164 parser.add_option('--restart', dest='restart',
Jon Salz8fa8e832012-07-13 19:04:09 +08001165 action='store_true',
1166 help='Clear all test state')
Jon Salz0697cbf2012-07-04 15:14:04 +08001167 parser.add_option('--ui', dest='ui', type='choice',
Jon Salz8fa8e832012-07-13 19:04:09 +08001168 choices=['none', 'gtk', 'chrome'],
Jon Salz2f881df2013-02-01 17:00:35 +08001169 default='chrome',
Jon Salz8fa8e832012-07-13 19:04:09 +08001170 help='UI to use')
Jon Salz0697cbf2012-07-04 15:14:04 +08001171 parser.add_option('--ui_scale_factor', dest='ui_scale_factor',
Jon Salz8fa8e832012-07-13 19:04:09 +08001172 type='int', default=1,
1173 help=('Factor by which to scale UI '
1174 '(Chrome UI only)'))
Jon Salz0697cbf2012-07-04 15:14:04 +08001175 parser.add_option('--test_list', dest='test_list',
Jon Salz8fa8e832012-07-13 19:04:09 +08001176 metavar='FILE',
1177 help='Use FILE as test list')
Jon Salzc79a9982012-08-30 04:42:01 +08001178 parser.add_option('--dummy_shopfloor', action='store_true',
1179 help='Use a dummy shopfloor server')
chungyiafe8f772012-08-15 19:36:29 +08001180 parser.add_option('--automation', dest='automation',
1181 action='store_true',
1182 help='Enable automation on running factory test')
Ricky Liang09216dc2013-02-22 17:26:45 +08001183 parser.add_option('--one_pixel_less', dest='one_pixel_less',
1184 action='store_true',
1185 help=('Start Chrome one pixel less than the full screen.'
1186 'Needed by Exynos platform to run GTK.'))
Jon Salz0697cbf2012-07-04 15:14:04 +08001187 (self.options, self.args) = parser.parse_args(args)
1188
Jon Salz46b89562012-07-05 11:49:22 +08001189 # Make sure factory directories exist.
1190 factory.get_log_root()
1191 factory.get_state_root()
1192 factory.get_test_data_root()
1193
Jon Salz0697cbf2012-07-04 15:14:04 +08001194 global _inited_logging # pylint: disable=W0603
1195 if not _inited_logging:
1196 factory.init_logging('goofy', verbose=self.options.verbose)
1197 _inited_logging = True
Jon Salz8fa8e832012-07-13 19:04:09 +08001198
Jon Salz0f996602012-10-03 15:26:48 +08001199 if self.options.print_test_list:
1200 print factory.read_test_list(
1201 self.options.print_test_list).__repr__(recursive=True)
1202 sys.exit(0)
1203
Jon Salzee85d522012-07-17 14:34:46 +08001204 event_log.IncrementBootSequence()
Jon Salzd15bbcf2013-05-21 17:33:57 +08001205 # Don't defer logging the initial event, so we can make sure
1206 # that device_id, reimage_id, etc. are all set up.
1207 self.event_log = EventLog('goofy', defer=False)
Jon Salz0697cbf2012-07-04 15:14:04 +08001208
1209 if (not suppress_chroot_warning and
1210 factory.in_chroot() and
1211 self.options.ui == 'gtk' and
1212 os.environ.get('DISPLAY') in [None, '', ':0', ':0.0']):
1213 # That's not going to work! Tell the user how to run
1214 # this way.
1215 logging.warn(GOOFY_IN_CHROOT_WARNING)
1216 time.sleep(1)
1217
1218 if env:
1219 self.env = env
1220 elif factory.in_chroot():
1221 self.env = test_environment.FakeChrootEnvironment()
1222 logging.warn(
1223 'Using chroot environment: will not actually run autotests')
1224 else:
1225 self.env = test_environment.DUTEnvironment()
1226 self.env.goofy = self
1227
1228 if self.options.restart:
1229 state.clear_state()
1230
Jon Salz0697cbf2012-07-04 15:14:04 +08001231 if self.options.ui_scale_factor != 1 and utils.in_qemu():
1232 logging.warn(
1233 'In QEMU; ignoring ui_scale_factor argument')
1234 self.options.ui_scale_factor = 1
1235
1236 logging.info('Started')
1237
1238 self.start_state_server()
1239 self.state_instance.set_shared_data('hwid_cfg', get_hwid_cfg())
1240 self.state_instance.set_shared_data('ui_scale_factor',
Ricky Liang09216dc2013-02-22 17:26:45 +08001241 self.options.ui_scale_factor)
1242 self.state_instance.set_shared_data('one_pixel_less',
1243 self.options.one_pixel_less)
Jon Salz0697cbf2012-07-04 15:14:04 +08001244 self.last_shutdown_time = (
1245 self.state_instance.get_shared_data('shutdown_time', optional=True))
1246 self.state_instance.del_shared_data('shutdown_time', optional=True)
Jon Salzb19ea072013-02-07 16:35:00 +08001247 self.state_instance.del_shared_data('startup_error', optional=True)
Jon Salz0697cbf2012-07-04 15:14:04 +08001248
Jon Salz128b0932013-07-03 16:55:26 +08001249 try:
1250 self.InitTestLists()
1251 except: # pylint: disable=W0702
1252 logging.exception('Unable to initialize test lists')
1253 self.state_instance.set_shared_data(
1254 'startup_error',
1255 'Unable to initialize test lists\n%s' % (
1256 traceback.format_exc()))
Jon Salzb19ea072013-02-07 16:35:00 +08001257 if self.options.ui == 'chrome':
1258 # Create an empty test list with default options so that the rest of
1259 # startup can proceed.
1260 self.test_list = factory.FactoryTestList(
1261 [], self.state_instance, factory.Options())
1262 else:
1263 # Bail with an error; no point in starting up.
1264 sys.exit('No valid test list; exiting.')
1265
Jon Salz822838b2013-03-25 17:32:33 +08001266 if self.test_list.options.clear_state_on_start:
1267 self.state_instance.clear_test_state()
1268
Vic Yang3e1cf5d2013-06-05 18:50:24 +08001269 if system.SystemInfo().firmware_version is None and not utils.in_chroot():
Vic Yang9bd4f772013-06-04 17:34:00 +08001270 self.state_instance.set_shared_data('startup_error',
1271 'Netboot firmware detected\n'
1272 'Connect Ethernet and reboot to re-image.\n'
1273 u'侦测到网路开机固件\n'
1274 u'请连接乙太网并重启')
1275
Jon Salz0697cbf2012-07-04 15:14:04 +08001276 if not self.state_instance.has_shared_data('ui_lang'):
1277 self.state_instance.set_shared_data('ui_lang',
1278 self.test_list.options.ui_lang)
1279 self.state_instance.set_shared_data(
1280 'test_list_options',
1281 self.test_list.options.__dict__)
1282 self.state_instance.test_list = self.test_list
1283
Cheng-Yi Chiangeb398df2013-07-19 14:30:45 +08001284 if not utils.in_chroot():
1285 cleanup_logs_paused_path = '/var/lib/cleanup_logs_paused'
1286 if self.test_list.options.disable_log_rotation:
1287 open(cleanup_logs_paused_path, 'w').close()
1288 else:
1289 file_utils.TryUnlink(cleanup_logs_paused_path)
Jon Salz83ef34b2012-11-01 19:46:35 +08001290
Jon Salz23926422012-09-01 03:38:13 +08001291 if self.options.dummy_shopfloor:
1292 os.environ[shopfloor.SHOPFLOOR_SERVER_ENV_VAR_NAME] = (
1293 'http://localhost:%d/' % shopfloor.DEFAULT_SERVER_PORT)
1294 self.dummy_shopfloor = Spawn(
1295 [os.path.join(factory.FACTORY_PATH, 'bin', 'shopfloor_server'),
1296 '--dummy'])
1297 elif self.test_list.options.shopfloor_server_url:
1298 shopfloor.set_server_url(self.test_list.options.shopfloor_server_url)
Jon Salz2bf2f6b2013-03-28 18:49:26 +08001299 shopfloor.set_enabled(True)
Jon Salz23926422012-09-01 03:38:13 +08001300
Jon Salz0f996602012-10-03 15:26:48 +08001301 if self.test_list.options.time_sanitizer and not utils.in_chroot():
Jon Salz8fa8e832012-07-13 19:04:09 +08001302 self.time_sanitizer = time_sanitizer.TimeSanitizer(
1303 base_time=time_sanitizer.GetBaseTimeFromFile(
1304 # lsb-factory is written by the factory install shim during
1305 # installation, so it should have a good time obtained from
Jon Salz54882d02012-08-31 01:57:54 +08001306 # the mini-Omaha server. If it's not available, we'll use
1307 # /etc/lsb-factory (which will be much older, but reasonably
1308 # sane) and rely on a shopfloor sync to set a more accurate
1309 # time.
1310 '/usr/local/etc/lsb-factory',
1311 '/etc/lsb-release'))
Jon Salz8fa8e832012-07-13 19:04:09 +08001312 self.time_sanitizer.RunOnce()
1313
Vic Yangd8990da2013-06-27 16:57:43 +08001314 if self.test_list.options.check_cpu_usage_period_secs:
1315 self.cpu_usage_watcher = Spawn(['py/tools/cpu_usage_monitor.py',
1316 '-p', str(self.test_list.options.check_cpu_usage_period_secs)],
1317 cwd=factory.FACTORY_PATH)
1318
Jon Salz0697cbf2012-07-04 15:14:04 +08001319 self.init_states()
1320 self.start_event_server()
1321 self.connection_manager = self.env.create_connection_manager(
Tai-Hsu Lin371351a2012-08-27 14:17:14 +08001322 self.test_list.options.wlans,
1323 self.test_list.options.scan_wifi_period_secs)
Jon Salz0697cbf2012-07-04 15:14:04 +08001324 # Note that we create a log watcher even if
1325 # sync_event_log_period_secs isn't set (no background
1326 # syncing), since we may use it to flush event logs as well.
1327 self.log_watcher = EventLogWatcher(
1328 self.test_list.options.sync_event_log_period_secs,
Jon Salzd15bbcf2013-05-21 17:33:57 +08001329 event_log_db_file=None,
Jon Salz16d10542012-07-23 12:18:45 +08001330 handle_event_logs_callback=self.handle_event_logs)
Jon Salz0697cbf2012-07-04 15:14:04 +08001331 if self.test_list.options.sync_event_log_period_secs:
1332 self.log_watcher.StartWatchThread()
1333
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +08001334 # Note that we create a system log manager even if
1335 # sync_log_period_secs isn't set (no background
1336 # syncing), since we may kick it to sync logs in its
1337 # thread.
Cheng-Yi Chiangd3516a32013-07-17 15:30:47 +08001338 if self.test_list.options.enable_sync_log:
1339 self.system_log_manager = SystemLogManager(
1340 sync_log_paths=self.test_list.options.sync_log_paths,
1341 sync_period_sec=self.test_list.options.sync_log_period_secs,
1342 clear_log_paths=self.test_list.options.clear_log_paths)
1343 self.system_log_manager.StartSyncThread()
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +08001344
Jon Salz0697cbf2012-07-04 15:14:04 +08001345 self.update_system_info()
1346
Vic Yang4953fc12012-07-26 16:19:53 +08001347 assert ((self.test_list.options.min_charge_pct is None) ==
1348 (self.test_list.options.max_charge_pct is None))
Vic Yange83d9a12013-04-19 20:00:20 +08001349 if utils.in_chroot():
1350 logging.info('In chroot, ignoring charge manager and charge state')
1351 elif self.test_list.options.min_charge_pct is not None:
Vic Yang4953fc12012-07-26 16:19:53 +08001352 self.charge_manager = ChargeManager(self.test_list.options.min_charge_pct,
1353 self.test_list.options.max_charge_pct)
Jon Salzad7353b2012-10-15 16:22:46 +08001354 system.SystemStatus.charge_manager = self.charge_manager
Cheng-Yi Chiangd8186952013-04-04 23:41:14 +08001355 else:
1356 # Goofy should set charger state to charge if charge_manager is disabled.
1357 try:
1358 system.GetBoard().SetChargeState(Board.ChargeState.CHARGE)
1359 except BoardException:
1360 logging.exception('Unable to set charge state on this board')
Vic Yang4953fc12012-07-26 16:19:53 +08001361
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001362 self.core_dump_manager = CoreDumpManager(
1363 self.test_list.options.core_dump_watchlist)
1364
Jon Salz0697cbf2012-07-04 15:14:04 +08001365 os.environ['CROS_FACTORY'] = '1'
1366 os.environ['CROS_DISABLE_SITE_SYSINFO'] = '1'
1367
1368 # Set CROS_UI since some behaviors in ui.py depend on the
1369 # particular UI in use. TODO(jsalz): Remove this (and all
1370 # places it is used) when the GTK UI is removed.
1371 os.environ['CROS_UI'] = self.options.ui
1372
Jon Salz416f9cc2013-05-10 18:32:50 +08001373 # Initialize hooks.
1374 module, cls = self.test_list.options.hooks_class.rsplit('.', 1)
1375 self.hooks = getattr(__import__(module, fromlist=[cls]), cls)()
1376 assert isinstance(self.hooks, factory.Hooks), (
1377 "hooks should be of type Hooks but is %r" % type(self.hooks))
1378 self.hooks.test_list = self.test_list
1379
Jon Salzce6a7f82013-06-10 18:22:54 +08001380 if not utils.in_chroot():
Jon Salzddf0d052013-06-18 12:52:44 +08001381 self.cpufreq_manager = CpufreqManager(event_log=self.event_log)
Jon Salzce6a7f82013-06-10 18:22:54 +08001382
Jon Salz416f9cc2013-05-10 18:32:50 +08001383 # Call startup hook.
1384 self.hooks.OnStartup()
Justin Chuang31b02432013-06-27 15:16:51 +08001385 # Startup hooks may want to skip some tests.
1386 self.update_skipped_tests()
Jon Salz416f9cc2013-05-10 18:32:50 +08001387
Jon Salze12c2b32013-06-25 16:24:34 +08001388 self.find_kcrashes()
1389
Jon Salz0697cbf2012-07-04 15:14:04 +08001390 if self.options.ui == 'chrome':
1391 self.env.launch_chrome()
1392 logging.info('Waiting for a web socket connection')
Cheng-Yi Chiangfd8ed392013-03-08 21:37:31 +08001393 self.web_socket_manager.wait()
Jon Salz0697cbf2012-07-04 15:14:04 +08001394
1395 # Wait for the test widget size to be set; this is done in
1396 # an asynchronous RPC so there is a small chance that the
1397 # web socket might be opened first.
1398 for _ in range(100): # 10 s
1399 try:
1400 if self.state_instance.get_shared_data('test_widget_size'):
1401 break
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001402 except KeyError:
Jon Salz0697cbf2012-07-04 15:14:04 +08001403 pass # Retry
1404 time.sleep(0.1) # 100 ms
1405 else:
1406 logging.warn('Never received test_widget_size from UI')
Jon Salz45297282013-05-18 14:31:47 +08001407
1408 # Send Chrome a Tab to get focus to the factory UI
1409 # (http://crosbug.com/p/19444). TODO(jsalz): remove this hack
1410 # and figure out the right way to get the focus to Chrome.
1411 if not utils.in_chroot():
1412 Spawn(
1413 [os.path.join(factory.FACTORY_PATH, 'bin', 'send_key'), 'Tab'],
1414 check_call=True, log=True)
Jon Salz0697cbf2012-07-04 15:14:04 +08001415 elif self.options.ui == 'gtk':
1416 self.start_ui()
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001417
Ricky Liang650f6bf2012-09-28 13:22:54 +08001418 # Create download path for autotest beforehand or autotests run at
1419 # the same time might fail due to race condition.
1420 if not factory.in_chroot():
1421 utils.TryMakeDirs(os.path.join('/usr/local/autotest', 'tests',
1422 'download'))
1423
Jon Salz0697cbf2012-07-04 15:14:04 +08001424 def state_change_callback(test, test_state):
1425 self.event_client.post_event(
1426 Event(Event.Type.STATE_CHANGE,
1427 path=test.path, state=test_state))
1428 self.test_list.state_change_callback = state_change_callback
Jon Salz73e0fd02012-04-04 11:46:38 +08001429
Jon Salza6711d72012-07-18 14:33:03 +08001430 for handler in self.on_ui_startup:
1431 handler()
1432
1433 self.prespawner = Prespawner()
1434 self.prespawner.start()
1435
Jon Salz0697cbf2012-07-04 15:14:04 +08001436 try:
1437 tests_after_shutdown = self.state_instance.get_shared_data(
1438 'tests_after_shutdown')
1439 except KeyError:
1440 tests_after_shutdown = None
Jon Salz57717ca2012-04-04 16:47:25 +08001441
Jon Salz5c344f62012-07-13 14:31:16 +08001442 force_auto_run = (tests_after_shutdown == FORCE_AUTO_RUN)
1443 if not force_auto_run and tests_after_shutdown is not None:
Jon Salz0697cbf2012-07-04 15:14:04 +08001444 logging.info('Resuming tests after shutdown: %s',
1445 tests_after_shutdown)
Jon Salz0697cbf2012-07-04 15:14:04 +08001446 self.tests_to_run.extend(
1447 self.test_list.lookup_path(t) for t in tests_after_shutdown)
1448 self.run_queue.put(self.run_next_test)
1449 else:
Jon Salz5c344f62012-07-13 14:31:16 +08001450 if force_auto_run or self.test_list.options.auto_run_on_start:
Jon Salz0697cbf2012-07-04 15:14:04 +08001451 self.run_queue.put(
1452 lambda: self.run_tests(self.test_list, untested_only=True))
Jon Salz5c344f62012-07-13 14:31:16 +08001453 self.state_instance.set_shared_data('tests_after_shutdown', None)
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001454
Dean Liao592e4d52013-01-10 20:06:39 +08001455 self.may_disable_cros_shortcut_keys()
1456
1457 def may_disable_cros_shortcut_keys(self):
1458 test_options = self.test_list.options
1459 if test_options.disable_cros_shortcut_keys:
1460 logging.info('Filter ChromeOS shortcut keys.')
1461 self.key_filter = KeyFilter(
1462 unmap_caps_lock=test_options.disable_caps_lock,
1463 caps_lock_keycode=test_options.caps_lock_keycode)
1464 self.key_filter.Start()
1465
Jon Salz0697cbf2012-07-04 15:14:04 +08001466 def run(self):
1467 '''Runs Goofy.'''
1468 # Process events forever.
1469 while self.run_once(True):
1470 pass
Jon Salz73e0fd02012-04-04 11:46:38 +08001471
Jon Salz0697cbf2012-07-04 15:14:04 +08001472 def run_once(self, block=False):
1473 '''Runs all items pending in the event loop.
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001474
Jon Salz0697cbf2012-07-04 15:14:04 +08001475 Args:
1476 block: If true, block until at least one event is processed.
Jon Salz7c15e8b2012-06-19 17:10:37 +08001477
Jon Salz0697cbf2012-07-04 15:14:04 +08001478 Returns:
1479 True to keep going or False to shut down.
1480 '''
1481 events = utils.DrainQueue(self.run_queue)
cychiang21886742012-07-05 15:16:32 +08001482 while not events:
Jon Salz0697cbf2012-07-04 15:14:04 +08001483 # Nothing on the run queue.
1484 self._run_queue_idle()
1485 if block:
1486 # Block for at least one event...
cychiang21886742012-07-05 15:16:32 +08001487 try:
1488 events.append(self.run_queue.get(timeout=RUN_QUEUE_TIMEOUT_SECS))
1489 except Queue.Empty:
1490 # Keep going (calling _run_queue_idle() again at the top of
1491 # the loop)
1492 continue
Jon Salz0697cbf2012-07-04 15:14:04 +08001493 # ...and grab anything else that showed up at the same
1494 # time.
1495 events.extend(utils.DrainQueue(self.run_queue))
cychiang21886742012-07-05 15:16:32 +08001496 else:
1497 break
Jon Salz51528e12012-07-02 18:54:45 +08001498
Jon Salz0697cbf2012-07-04 15:14:04 +08001499 for event in events:
1500 if not event:
1501 # Shutdown request.
1502 self.run_queue.task_done()
1503 return False
Jon Salz51528e12012-07-02 18:54:45 +08001504
Jon Salz0697cbf2012-07-04 15:14:04 +08001505 try:
1506 event()
Jon Salz85a39882012-07-05 16:45:04 +08001507 except: # pylint: disable=W0702
1508 logging.exception('Error in event loop')
Jon Salz0697cbf2012-07-04 15:14:04 +08001509 self.record_exception(traceback.format_exception_only(
1510 *sys.exc_info()[:2]))
1511 # But keep going
1512 finally:
1513 self.run_queue.task_done()
1514 return True
Jon Salz0405ab52012-03-16 15:26:52 +08001515
Jon Salz0e6532d2012-10-25 16:30:11 +08001516 def _should_sync_time(self, foreground=False):
1517 '''Returns True if we should attempt syncing time with shopfloor.
1518
1519 Args:
1520 foreground: If True, synchronizes even if background syncing
1521 is disabled (e.g., in explicit sync requests from the
1522 SyncShopfloor test).
1523 '''
1524 return ((foreground or
1525 self.test_list.options.sync_time_period_secs) and
Jon Salz54882d02012-08-31 01:57:54 +08001526 self.time_sanitizer and
1527 (not self.time_synced) and
1528 (not factory.in_chroot()))
1529
Jon Salz0e6532d2012-10-25 16:30:11 +08001530 def sync_time_with_shopfloor_server(self, foreground=False):
Jon Salz54882d02012-08-31 01:57:54 +08001531 '''Syncs time with shopfloor server, if not yet synced.
1532
Jon Salz0e6532d2012-10-25 16:30:11 +08001533 Args:
1534 foreground: If True, synchronizes even if background syncing
1535 is disabled (e.g., in explicit sync requests from the
1536 SyncShopfloor test).
1537
Jon Salz54882d02012-08-31 01:57:54 +08001538 Returns:
1539 False if no time sanitizer is available, or True if this sync (or a
1540 previous sync) succeeded.
1541
1542 Raises:
1543 Exception if unable to contact the shopfloor server.
1544 '''
Jon Salz0e6532d2012-10-25 16:30:11 +08001545 if self._should_sync_time(foreground):
Jon Salz54882d02012-08-31 01:57:54 +08001546 self.time_sanitizer.SyncWithShopfloor()
1547 self.time_synced = True
1548 return self.time_synced
1549
Jon Salzb92c5112012-09-21 15:40:11 +08001550 def log_disk_space_stats(self):
Jon Salz18e0e022013-06-11 17:13:39 +08001551 if (utils.in_chroot() or
1552 not self.test_list.options.log_disk_space_period_secs):
Jon Salzb92c5112012-09-21 15:40:11 +08001553 return
1554
1555 now = time.time()
1556 if (self.last_log_disk_space_time and
1557 now - self.last_log_disk_space_time <
1558 self.test_list.options.log_disk_space_period_secs):
1559 return
1560 self.last_log_disk_space_time = now
1561
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001562 # Upload event if stateful partition usage is above threshold.
1563 # Stateful partition is mounted on /usr/local, while
1564 # encrypted stateful partition is mounted on /var.
1565 # If there are too much logs in the factory process,
1566 # these two partitions might get full.
Jon Salzb92c5112012-09-21 15:40:11 +08001567 try:
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001568 vfs_infos = disk_space.GetAllVFSInfo()
1569 stateful_info, encrypted_info = None, None
1570 for vfs_info in vfs_infos.values():
1571 if '/usr/local' in vfs_info.mount_points:
1572 stateful_info = vfs_info
1573 if '/var' in vfs_info.mount_points:
1574 encrypted_info = vfs_info
1575
1576 stateful = disk_space.GetPartitionUsage(stateful_info)
1577 encrypted = disk_space.GetPartitionUsage(encrypted_info)
1578
1579 above_threshold = (
1580 self.test_list.options.stateful_usage_threshold and
1581 max(stateful.bytes_used_pct,
1582 stateful.inodes_used_pct,
1583 encrypted.bytes_used_pct,
1584 encrypted.inodes_used_pct) >
1585 self.test_list.options.stateful_usage_threshold)
1586
1587 if above_threshold:
1588 self.event_log.Log('stateful_partition_usage',
1589 partitions={
1590 'stateful': {
1591 'bytes_used_pct': FloatDigit(stateful.bytes_used_pct, 2),
1592 'inodes_used_pct': FloatDigit(stateful.inodes_used_pct, 2)},
1593 'encrypted_stateful': {
1594 'bytes_used_pct': FloatDigit(encrypted.bytes_used_pct, 2),
1595 'inodes_used_pct': FloatDigit(encrypted.inodes_used_pct, 2)}
1596 })
1597 self.log_watcher.ScanEventLogs()
Cheng-Yi Chiang00798e72013-06-20 18:16:39 +08001598 if (not utils.in_chroot() and
1599 self.test_list.options.stateful_usage_above_threshold_action):
1600 Spawn(self.test_list.options.stateful_usage_above_threshold_action,
1601 call=True)
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001602
1603 message = disk_space.FormatSpaceUsedAll(vfs_infos)
Jon Salz3c493bb2013-02-07 17:24:58 +08001604 if message != self.last_log_disk_space_message:
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001605 if above_threshold:
1606 logging.warning(message)
1607 else:
1608 logging.info(message)
Jon Salz3c493bb2013-02-07 17:24:58 +08001609 self.last_log_disk_space_message = message
Jon Salzb92c5112012-09-21 15:40:11 +08001610 except: # pylint: disable=W0702
1611 logging.exception('Unable to get disk space used')
1612
Justin Chuang83813982013-05-13 01:26:32 +08001613 def check_battery(self):
1614 '''Checks the current battery status.
1615
1616 Logs current battery charging level and status to log. If the battery level
1617 is lower below warning_low_battery_pct, send warning event to shopfloor.
1618 If the battery level is lower below critical_low_battery_pct, flush disks.
1619 '''
1620 if not self.test_list.options.check_battery_period_secs:
1621 return
1622
1623 now = time.time()
1624 if (self.last_check_battery_time and
1625 now - self.last_check_battery_time <
1626 self.test_list.options.check_battery_period_secs):
1627 return
1628 self.last_check_battery_time = now
1629
1630 message = ''
1631 log_level = logging.INFO
1632 try:
1633 power = system.GetBoard().power
1634 if not power.CheckBatteryPresent():
1635 message = 'Battery is not present'
1636 else:
1637 ac_present = power.CheckACPresent()
1638 charge_pct = power.GetChargePct(get_float=True)
1639 message = ('Current battery level %.1f%%, AC charger is %s' %
1640 (charge_pct, 'connected' if ac_present else 'disconnected'))
1641
1642 if charge_pct > self.test_list.options.critical_low_battery_pct:
1643 critical_low_battery = False
1644 else:
1645 critical_low_battery = True
1646 # Only sync disks when battery level is still above minimum
1647 # value. This can be used for offline analysis when shopfloor cannot
1648 # be connected.
1649 if charge_pct > MIN_BATTERY_LEVEL_FOR_DISK_SYNC:
1650 logging.warning('disk syncing for critical low battery situation')
1651 os.system('sync; sync; sync')
1652 else:
1653 logging.warning('disk syncing is cancelled '
1654 'because battery level is lower than %.1f',
1655 MIN_BATTERY_LEVEL_FOR_DISK_SYNC)
1656
1657 # Notify shopfloor server
1658 if (critical_low_battery or
1659 (not ac_present and
1660 charge_pct <= self.test_list.options.warning_low_battery_pct)):
1661 log_level = logging.WARNING
1662
1663 self.event_log.Log('low_battery',
1664 battery_level=charge_pct,
1665 charger_connected=ac_present,
1666 critical=critical_low_battery)
1667 self.log_watcher.KickWatchThread()
Cheng-Yi Chiangd3516a32013-07-17 15:30:47 +08001668 if self.system_log_manager:
1669 self.system_log_manager.KickSyncThread()
Justin Chuang83813982013-05-13 01:26:32 +08001670 except: # pylint: disable=W0702
1671 logging.exception('Unable to check battery or notify shopfloor')
1672 finally:
1673 if message != self.last_check_battery_message:
1674 logging.log(log_level, message)
1675 self.last_check_battery_message = message
1676
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001677 def check_core_dump(self):
1678 '''Checks if there is any core dumped file.
1679
1680 Removes unwanted core dump files immediately.
1681 Syncs those files matching watch list to server with a delay between
1682 each sync. After the files have been synced to server, deletes the files.
1683 '''
1684 core_dump_files = self.core_dump_manager.ScanFiles()
1685 if core_dump_files:
1686 now = time.time()
1687 if (self.last_kick_sync_time and now - self.last_kick_sync_time <
1688 self.test_list.options.kick_sync_min_interval_secs):
1689 return
1690 self.last_kick_sync_time = now
1691
1692 # Sends event to server
1693 self.event_log.Log('core_dumped', files=core_dump_files)
1694 self.log_watcher.KickWatchThread()
1695
1696 # Syncs files to server
Cheng-Yi Chiangd3516a32013-07-17 15:30:47 +08001697 if self.system_log_manager:
1698 self.system_log_manager.KickSyncThread(
1699 core_dump_files, self.core_dump_manager.ClearFiles)
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001700
Jon Salz8fa8e832012-07-13 19:04:09 +08001701 def sync_time_in_background(self):
Jon Salzb22d1172012-08-06 10:38:57 +08001702 '''Writes out current time and tries to sync with shopfloor server.'''
1703 if not self.time_sanitizer:
1704 return
1705
1706 # Write out the current time.
1707 self.time_sanitizer.SaveTime()
1708
Jon Salz54882d02012-08-31 01:57:54 +08001709 if not self._should_sync_time():
Jon Salz8fa8e832012-07-13 19:04:09 +08001710 return
1711
1712 now = time.time()
1713 if self.last_sync_time and (
1714 now - self.last_sync_time <
1715 self.test_list.options.sync_time_period_secs):
1716 # Not yet time for another check.
1717 return
1718 self.last_sync_time = now
1719
1720 def target():
1721 try:
Jon Salz54882d02012-08-31 01:57:54 +08001722 self.sync_time_with_shopfloor_server()
Jon Salz8fa8e832012-07-13 19:04:09 +08001723 except: # pylint: disable=W0702
1724 # Oh well. Log an error (but no trace)
1725 logging.info(
1726 'Unable to get time from shopfloor server: %s',
1727 utils.FormatExceptionOnly())
1728
1729 thread = threading.Thread(target=target)
1730 thread.daemon = True
1731 thread.start()
1732
Jon Salz0697cbf2012-07-04 15:14:04 +08001733 def _run_queue_idle(self):
Vic Yang4953fc12012-07-26 16:19:53 +08001734 '''Invoked when the run queue has no events.
1735
1736 This method must not raise exception.
1737 '''
Jon Salzb22d1172012-08-06 10:38:57 +08001738 now = time.time()
1739 if (self.last_idle and
1740 now < (self.last_idle + RUN_QUEUE_TIMEOUT_SECS - 1)):
1741 # Don't run more often than once every (RUN_QUEUE_TIMEOUT_SECS -
1742 # 1) seconds.
1743 return
1744
1745 self.last_idle = now
1746
Vic Yang311ddb82012-09-26 12:08:28 +08001747 self.check_exclusive()
cychiang21886742012-07-05 15:16:32 +08001748 self.check_for_updates()
Jon Salz8fa8e832012-07-13 19:04:09 +08001749 self.sync_time_in_background()
Jon Salzb92c5112012-09-21 15:40:11 +08001750 self.log_disk_space_stats()
Justin Chuang83813982013-05-13 01:26:32 +08001751 self.check_battery()
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001752 self.check_core_dump()
Jon Salz57717ca2012-04-04 16:47:25 +08001753
Jon Salzd15bbcf2013-05-21 17:33:57 +08001754 def handle_event_logs(self, chunks):
Jon Salz0697cbf2012-07-04 15:14:04 +08001755 '''Callback for event watcher.
Jon Salz258a40c2012-04-19 12:34:01 +08001756
Jon Salz0697cbf2012-07-04 15:14:04 +08001757 Attempts to upload the event logs to the shopfloor server.
Vic Yang93027612013-05-06 02:42:49 +08001758
1759 Args:
Jon Salzd15bbcf2013-05-21 17:33:57 +08001760 chunks: A list of Chunk objects.
Jon Salz0697cbf2012-07-04 15:14:04 +08001761 '''
Cheng-Yi Chiang3e5ec7b2013-07-17 12:44:46 +08001762 if not self.test_list.options.sync_event_log:
1763 logging.info('Skipped syncing event logs %s',
1764 ', '.join([str(chunk) for chunk in chunks]))
1765 return
1766
Vic Yang93027612013-05-06 02:42:49 +08001767 first_exception = None
1768 exception_count = 0
1769
Jon Salzd15bbcf2013-05-21 17:33:57 +08001770 for chunk in chunks:
Vic Yang93027612013-05-06 02:42:49 +08001771 try:
Jon Salzcddb6402013-05-23 12:56:42 +08001772 description = 'event logs (%s)' % str(chunk)
Vic Yang93027612013-05-06 02:42:49 +08001773 start_time = time.time()
1774 shopfloor_client = shopfloor.get_instance(
1775 detect=True,
1776 timeout=self.test_list.options.shopfloor_timeout_secs)
Jon Salzd15bbcf2013-05-21 17:33:57 +08001777 shopfloor_client.UploadEvent(chunk.log_name + "." +
1778 event_log.GetReimageId(),
1779 Binary(chunk.chunk))
Vic Yang93027612013-05-06 02:42:49 +08001780 logging.info(
1781 'Successfully synced %s in %.03f s',
1782 description, time.time() - start_time)
1783 except: # pylint: disable=W0702
Jon Salzd15bbcf2013-05-21 17:33:57 +08001784 first_exception = (first_exception or (chunk.log_name + ': ' +
Vic Yang93027612013-05-06 02:42:49 +08001785 utils.FormatExceptionOnly()))
1786 exception_count += 1
1787
1788 if exception_count:
1789 if exception_count == 1:
1790 msg = 'Log upload failed: %s' % first_exception
1791 else:
1792 msg = '%d log upload failed; first is: %s' % (
1793 exception_count, first_exception)
1794 raise Exception(msg)
1795
Jon Salz57717ca2012-04-04 16:47:25 +08001796
Jon Salz0697cbf2012-07-04 15:14:04 +08001797 def run_tests_with_status(self, statuses_to_run, starting_at=None,
1798 root=None):
1799 '''Runs all top-level tests with a particular status.
Jon Salz0405ab52012-03-16 15:26:52 +08001800
Jon Salz0697cbf2012-07-04 15:14:04 +08001801 All active tests, plus any tests to re-run, are reset.
Jon Salz57717ca2012-04-04 16:47:25 +08001802
Jon Salz0697cbf2012-07-04 15:14:04 +08001803 Args:
1804 starting_at: If provided, only auto-runs tests beginning with
1805 this test.
1806 '''
1807 root = root or self.test_list
Jon Salz57717ca2012-04-04 16:47:25 +08001808
Jon Salz0697cbf2012-07-04 15:14:04 +08001809 if starting_at:
1810 # Make sure they passed a test, not a string.
1811 assert isinstance(starting_at, factory.FactoryTest)
Jon Salz0405ab52012-03-16 15:26:52 +08001812
Jon Salz0697cbf2012-07-04 15:14:04 +08001813 tests_to_reset = []
1814 tests_to_run = []
Jon Salz0405ab52012-03-16 15:26:52 +08001815
Jon Salz0697cbf2012-07-04 15:14:04 +08001816 found_starting_at = False
Jon Salz0405ab52012-03-16 15:26:52 +08001817
Jon Salz0697cbf2012-07-04 15:14:04 +08001818 for test in root.get_top_level_tests():
1819 if starting_at:
1820 if test == starting_at:
1821 # We've found starting_at; do auto-run on all
1822 # subsequent tests.
1823 found_starting_at = True
1824 if not found_starting_at:
1825 # Don't start this guy yet
1826 continue
Jon Salz0405ab52012-03-16 15:26:52 +08001827
Jon Salz0697cbf2012-07-04 15:14:04 +08001828 status = test.get_state().status
1829 if status == TestState.ACTIVE or status in statuses_to_run:
1830 # Reset the test (later; we will need to abort
1831 # all active tests first).
1832 tests_to_reset.append(test)
1833 if status in statuses_to_run:
1834 tests_to_run.append(test)
Jon Salz0405ab52012-03-16 15:26:52 +08001835
Jon Salz6dc031d2013-06-19 13:06:23 +08001836 self.abort_active_tests('Operator requested run/re-run of certain tests')
Jon Salz258a40c2012-04-19 12:34:01 +08001837
Jon Salz0697cbf2012-07-04 15:14:04 +08001838 # Reset all statuses of the tests to run (in case any tests were active;
1839 # we want them to be run again).
1840 for test_to_reset in tests_to_reset:
1841 for test in test_to_reset.walk():
1842 test.update_state(status=TestState.UNTESTED)
Jon Salz57717ca2012-04-04 16:47:25 +08001843
Jon Salz0697cbf2012-07-04 15:14:04 +08001844 self.run_tests(tests_to_run, untested_only=True)
Jon Salz0405ab52012-03-16 15:26:52 +08001845
Jon Salz0697cbf2012-07-04 15:14:04 +08001846 def restart_tests(self, root=None):
1847 '''Restarts all tests.'''
1848 root = root or self.test_list
Jon Salz0405ab52012-03-16 15:26:52 +08001849
Jon Salz6dc031d2013-06-19 13:06:23 +08001850 self.abort_active_tests('Operator requested restart of certain tests')
Jon Salz0697cbf2012-07-04 15:14:04 +08001851 for test in root.walk():
1852 test.update_state(status=TestState.UNTESTED)
1853 self.run_tests(root)
Hung-Te Lin96632362012-03-20 21:14:18 +08001854
Jon Salz0697cbf2012-07-04 15:14:04 +08001855 def auto_run(self, starting_at=None, root=None):
1856 '''"Auto-runs" tests that have not been run yet.
Hung-Te Lin96632362012-03-20 21:14:18 +08001857
Jon Salz0697cbf2012-07-04 15:14:04 +08001858 Args:
1859 starting_at: If provide, only auto-runs tests beginning with
1860 this test.
1861 '''
1862 root = root or self.test_list
1863 self.run_tests_with_status([TestState.UNTESTED, TestState.ACTIVE],
1864 starting_at=starting_at,
1865 root=root)
Jon Salz968e90b2012-03-18 16:12:43 +08001866
Jon Salz0697cbf2012-07-04 15:14:04 +08001867 def re_run_failed(self, root=None):
1868 '''Re-runs failed tests.'''
1869 root = root or self.test_list
1870 self.run_tests_with_status([TestState.FAILED], root=root)
Jon Salz57717ca2012-04-04 16:47:25 +08001871
Jon Salz0697cbf2012-07-04 15:14:04 +08001872 def show_review_information(self):
1873 '''Event handler for showing review information screen.
Jon Salz57717ca2012-04-04 16:47:25 +08001874
Jon Salz0697cbf2012-07-04 15:14:04 +08001875 The information screene is rendered by main UI program (ui.py), so in
1876 goofy we only need to kill all active tests, set them as untested, and
1877 clear remaining tests.
1878 '''
1879 self.kill_active_tests(False)
Jon Salza6711d72012-07-18 14:33:03 +08001880 self.cancel_pending_tests()
Jon Salz57717ca2012-04-04 16:47:25 +08001881
Jon Salz0697cbf2012-07-04 15:14:04 +08001882 def handle_switch_test(self, event):
1883 '''Switches to a particular test.
Jon Salz0405ab52012-03-16 15:26:52 +08001884
Jon Salz0697cbf2012-07-04 15:14:04 +08001885 @param event: The SWITCH_TEST event.
1886 '''
1887 test = self.test_list.lookup_path(event.path)
1888 if not test:
1889 logging.error('Unknown test %r', event.key)
1890 return
Jon Salz73e0fd02012-04-04 11:46:38 +08001891
Jon Salz0697cbf2012-07-04 15:14:04 +08001892 invoc = self.invocations.get(test)
1893 if invoc and test.backgroundable:
1894 # Already running: just bring to the front if it
1895 # has a UI.
1896 logging.info('Setting visible test to %s', test.path)
Jon Salz36fbbb52012-07-05 13:45:06 +08001897 self.set_visible_test(test)
Jon Salz0697cbf2012-07-04 15:14:04 +08001898 return
Jon Salz73e0fd02012-04-04 11:46:38 +08001899
Jon Salz6dc031d2013-06-19 13:06:23 +08001900 self.abort_active_tests('Operator requested abort (switch_test)')
Jon Salz0697cbf2012-07-04 15:14:04 +08001901 for t in test.walk():
1902 t.update_state(status=TestState.UNTESTED)
Jon Salz73e0fd02012-04-04 11:46:38 +08001903
Jon Salz0697cbf2012-07-04 15:14:04 +08001904 if self.test_list.options.auto_run_on_keypress:
1905 self.auto_run(starting_at=test)
1906 else:
1907 self.run_tests(test)
Jon Salz73e0fd02012-04-04 11:46:38 +08001908
Jon Salz0697cbf2012-07-04 15:14:04 +08001909 def wait(self):
1910 '''Waits for all pending invocations.
1911
1912 Useful for testing.
1913 '''
Jon Salz1acc8742012-07-17 17:45:55 +08001914 while self.invocations:
1915 for k, v in self.invocations.iteritems():
1916 logging.info('Waiting for %s to complete...', k)
1917 v.thread.join()
1918 self.reap_completed_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +08001919
1920 def check_exceptions(self):
1921 '''Raises an error if any exceptions have occurred in
1922 invocation threads.'''
1923 if self.exceptions:
1924 raise RuntimeError('Exception in invocation thread: %r' %
1925 self.exceptions)
1926
1927 def record_exception(self, msg):
1928 '''Records an exception in an invocation thread.
1929
1930 An exception with the given message will be rethrown when
1931 Goofy is destroyed.'''
1932 self.exceptions.append(msg)
Jon Salz73e0fd02012-04-04 11:46:38 +08001933
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001934
1935if __name__ == '__main__':
Jon Salz77c151e2012-08-28 07:20:37 +08001936 goofy = Goofy()
1937 try:
1938 goofy.main()
Jon Salz0f996602012-10-03 15:26:48 +08001939 except SystemExit:
1940 # Propagate SystemExit without logging.
1941 raise
Jon Salz31373eb2012-09-21 16:19:49 +08001942 except:
Jon Salz0f996602012-10-03 15:26:48 +08001943 # Log the error before trying to shut down (unless it's a graceful
1944 # exit).
Jon Salz31373eb2012-09-21 16:19:49 +08001945 logging.exception('Error in main loop')
1946 raise
Jon Salz77c151e2012-08-28 07:20:37 +08001947 finally:
1948 goofy.destroy()