blob: f059b8d678dd96693cf556eb76d178795bf1874c [file] [log] [blame]
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001#!/usr/bin/python -u
Hung-Te Linf2f78f72012-02-08 19:27:11 +08002# -*- coding: utf-8 -*-
3#
Jon Salz37eccbd2012-05-25 16:06:52 +08004# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
Hung-Te Linf2f78f72012-02-08 19:27:11 +08005# Use of this source code is governed by a BSD-style license that can be
6# found in the LICENSE file.
7
8'''
9The main factory flow that runs the factory test and finalizes a device.
10'''
11
Jon Salz0405ab52012-03-16 15:26:52 +080012import logging
13import os
Jon Salz73e0fd02012-04-04 11:46:38 +080014import Queue
Jon Salz77c151e2012-08-28 07:20:37 +080015import signal
Jon Salz0405ab52012-03-16 15:26:52 +080016import sys
Jon Salz0405ab52012-03-16 15:26:52 +080017import threading
18import time
19import traceback
Jon Salz258a40c2012-04-19 12:34:01 +080020import uuid
Jon Salzb10cf512012-08-09 17:29:21 +080021from xmlrpclib import Binary
Hung-Te Linf2f78f72012-02-08 19:27:11 +080022from collections import deque
23from optparse import OptionParser
Hung-Te Linf2f78f72012-02-08 19:27:11 +080024
Jon Salz0697cbf2012-07-04 15:14:04 +080025import factory_common # pylint: disable=W0611
jcliangcd688182012-08-20 21:01:26 +080026from cros.factory import event_log
27from cros.factory import system
28from cros.factory.event_log import EventLog
29from cros.factory.goofy import test_environment
30from cros.factory.goofy import time_sanitizer
Jon Salz83591782012-06-26 11:09:58 +080031from cros.factory.goofy import updater
Jon Salz51528e12012-07-02 18:54:45 +080032from cros.factory.goofy.event_log_watcher import EventLogWatcher
jcliangcd688182012-08-20 21:01:26 +080033from cros.factory.goofy.goofy_rpc import GoofyRPC
34from cros.factory.goofy.invocation import TestInvocation
35from cros.factory.goofy.prespawner import Prespawner
36from cros.factory.goofy.web_socket_manager import WebSocketManager
37from cros.factory.system.charge_manager import ChargeManager
Jon Salzb92c5112012-09-21 15:40:11 +080038from cros.factory.system import disk_space
jcliangcd688182012-08-20 21:01:26 +080039from cros.factory.test import factory
40from cros.factory.test import state
Jon Salz51528e12012-07-02 18:54:45 +080041from cros.factory.test import shopfloor
Jon Salz83591782012-06-26 11:09:58 +080042from cros.factory.test import utils
43from cros.factory.test.event import Event
44from cros.factory.test.event import EventClient
45from cros.factory.test.event import EventServer
jcliangcd688182012-08-20 21:01:26 +080046from cros.factory.test.factory import TestState
Dean Liao592e4d52013-01-10 20:06:39 +080047from cros.factory.tools.key_filter import KeyFilter
Jon Salz78c32392012-07-25 14:18:29 +080048from cros.factory.utils.process_utils import Spawn
Hung-Te Linf2f78f72012-02-08 19:27:11 +080049
50
Jon Salz2f757d42012-06-27 17:06:42 +080051DEFAULT_TEST_LISTS_DIR = os.path.join(factory.FACTORY_PATH, 'test_lists')
52CUSTOM_DIR = os.path.join(factory.FACTORY_PATH, 'custom')
Hung-Te Linf2f78f72012-02-08 19:27:11 +080053HWID_CFG_PATH = '/usr/local/share/chromeos-hwid/cfg'
Chun-ta Lin279e7e92013-02-19 17:40:39 +080054CACHES_DIR = os.path.join(factory.get_state_root(), "caches")
Hung-Te Linf2f78f72012-02-08 19:27:11 +080055
Jon Salz8796e362012-05-24 11:39:09 +080056# File that suppresses reboot if present (e.g., for development).
57NO_REBOOT_FILE = '/var/log/factory.noreboot'
58
Jon Salz5c344f62012-07-13 14:31:16 +080059# Value for tests_after_shutdown that forces auto-run (e.g., after
60# a factory update, when the available set of tests might change).
61FORCE_AUTO_RUN = 'force_auto_run'
62
cychiang21886742012-07-05 15:16:32 +080063RUN_QUEUE_TIMEOUT_SECS = 10
64
Jon Salz758e6cc2012-04-03 15:47:07 +080065GOOFY_IN_CHROOT_WARNING = '\n' + ('*' * 70) + '''
66You are running Goofy inside the chroot. Autotests are not supported.
67
68To use Goofy in the chroot, first install an Xvnc server:
69
Jon Salz0697cbf2012-07-04 15:14:04 +080070 sudo apt-get install tightvncserver
Jon Salz758e6cc2012-04-03 15:47:07 +080071
72...and then start a VNC X server outside the chroot:
73
Jon Salz0697cbf2012-07-04 15:14:04 +080074 vncserver :10 &
75 vncviewer :10
Jon Salz758e6cc2012-04-03 15:47:07 +080076
77...and run Goofy as follows:
78
Jon Salz0697cbf2012-07-04 15:14:04 +080079 env --unset=XAUTHORITY DISPLAY=localhost:10 python goofy.py
Jon Salz758e6cc2012-04-03 15:47:07 +080080''' + ('*' * 70)
Jon Salz73e0fd02012-04-04 11:46:38 +080081suppress_chroot_warning = False
Hung-Te Linf2f78f72012-02-08 19:27:11 +080082
83def get_hwid_cfg():
Jon Salz0697cbf2012-07-04 15:14:04 +080084 '''
85 Returns the HWID config tag, or an empty string if none can be found.
86 '''
87 if 'CROS_HWID' in os.environ:
88 return os.environ['CROS_HWID']
89 if os.path.exists(HWID_CFG_PATH):
90 with open(HWID_CFG_PATH, 'rt') as hwid_cfg_handle:
91 return hwid_cfg_handle.read().strip()
92 return ''
Hung-Te Linf2f78f72012-02-08 19:27:11 +080093
94
95def find_test_list():
Jon Salz0697cbf2012-07-04 15:14:04 +080096 '''
97 Returns the path to the active test list, based on the HWID config tag.
98 '''
99 hwid_cfg = get_hwid_cfg()
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800100
Jon Salz4be56b02012-12-22 07:30:46 +0800101 search_dirs = [DEFAULT_TEST_LISTS_DIR]
102 if not utils.in_chroot():
103 # Also look in suite_Factory. For backward compatibility only;
104 # new boards should just put the test list in the "test_lists"
105 # directory.
106 search_dirs.insert(0, os.path.join(
107 os.path.dirname(factory.FACTORY_PATH),
108 'autotest', 'site_tests', 'suite_Factory'))
Jon Salz2f757d42012-06-27 17:06:42 +0800109
Jon Salz0697cbf2012-07-04 15:14:04 +0800110 # Try in order: test_list_${hwid_cfg}, test_list, test_list.all
111 search_files = ['test_list', 'test_list.all']
112 if hwid_cfg:
113 search_files.insert(0, hwid_cfg)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800114
Jon Salz0697cbf2012-07-04 15:14:04 +0800115 for d in search_dirs:
116 for f in search_files:
117 test_list = os.path.join(d, f)
118 if os.path.exists(test_list):
119 return test_list
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800120
Jon Salz0697cbf2012-07-04 15:14:04 +0800121 logging.warn('Cannot find test lists named any of %s in any of %s',
122 search_files, search_dirs)
123 return None
Jon Salz73e0fd02012-04-04 11:46:38 +0800124
Jon Salz73e0fd02012-04-04 11:46:38 +0800125_inited_logging = False
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800126
127class Goofy(object):
Jon Salz0697cbf2012-07-04 15:14:04 +0800128 '''
129 The main factory flow.
130
131 Note that all methods in this class must be invoked from the main
132 (event) thread. Other threads, such as callbacks and TestInvocation
133 methods, should instead post events on the run queue.
134
135 TODO: Unit tests. (chrome-os-partner:7409)
136
137 Properties:
138 uuid: A unique UUID for this invocation of Goofy.
139 state_instance: An instance of FactoryState.
140 state_server: The FactoryState XML/RPC server.
141 state_server_thread: A thread running state_server.
142 event_server: The EventServer socket server.
143 event_server_thread: A thread running event_server.
144 event_client: A client to the event server.
145 connection_manager: The connection_manager object.
Jon Salz0697cbf2012-07-04 15:14:04 +0800146 ui_process: The factory ui process object.
147 run_queue: A queue of callbacks to invoke from the main thread.
148 invocations: A map from FactoryTest objects to the corresponding
149 TestInvocations objects representing active tests.
150 tests_to_run: A deque of tests that should be run when the current
151 test(s) complete.
152 options: Command-line options.
153 args: Command-line args.
154 test_list: The test list.
155 event_handlers: Map of Event.Type to the method used to handle that
156 event. If the method has an 'event' argument, the event is passed
157 to the handler.
158 exceptions: Exceptions encountered in invocation threads.
Jon Salz3c493bb2013-02-07 17:24:58 +0800159 last_log_disk_space_message: The last message we logged about disk space
160 (to avoid duplication).
Jon Salz0697cbf2012-07-04 15:14:04 +0800161 '''
162 def __init__(self):
163 self.uuid = str(uuid.uuid4())
164 self.state_instance = None
165 self.state_server = None
166 self.state_server_thread = None
Jon Salz16d10542012-07-23 12:18:45 +0800167 self.goofy_rpc = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800168 self.event_server = None
169 self.event_server_thread = None
170 self.event_client = None
171 self.connection_manager = None
Vic Yang4953fc12012-07-26 16:19:53 +0800172 self.charge_manager = None
Jon Salz8fa8e832012-07-13 19:04:09 +0800173 self.time_sanitizer = None
174 self.time_synced = False
Jon Salz0697cbf2012-07-04 15:14:04 +0800175 self.log_watcher = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800176 self.event_log = None
177 self.prespawner = None
178 self.ui_process = None
Jon Salzc79a9982012-08-30 04:42:01 +0800179 self.dummy_shopfloor = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800180 self.run_queue = Queue.Queue()
181 self.invocations = {}
182 self.tests_to_run = deque()
183 self.visible_test = None
184 self.chrome = None
185
186 self.options = None
187 self.args = None
188 self.test_list = None
189 self.on_ui_startup = []
190 self.env = None
Jon Salzb22d1172012-08-06 10:38:57 +0800191 self.last_idle = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800192 self.last_shutdown_time = None
cychiang21886742012-07-05 15:16:32 +0800193 self.last_update_check = None
Jon Salz8fa8e832012-07-13 19:04:09 +0800194 self.last_sync_time = None
Jon Salzb92c5112012-09-21 15:40:11 +0800195 self.last_log_disk_space_time = None
Jon Salz3c493bb2013-02-07 17:24:58 +0800196 self.last_log_disk_space_message = None
Vic Yang311ddb82012-09-26 12:08:28 +0800197 self.exclusive_items = set()
Jon Salz0f996602012-10-03 15:26:48 +0800198 self.event_log = None
Dean Liao592e4d52013-01-10 20:06:39 +0800199 self.key_filter = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800200
Jon Salz85a39882012-07-05 16:45:04 +0800201 def test_or_root(event, parent_or_group=True):
202 '''Returns the test affected by a particular event.
203
204 Args:
205 event: The event containing an optional 'path' attribute.
206 parent_on_group: If True, returns the top-level parent for a test (the
207 root node of the tests that need to be run together if the given test
208 path is to be run).
209 '''
Jon Salz0697cbf2012-07-04 15:14:04 +0800210 try:
211 path = event.path
212 except AttributeError:
213 path = None
214
215 if path:
Jon Salz85a39882012-07-05 16:45:04 +0800216 test = self.test_list.lookup_path(path)
217 if parent_or_group:
218 test = test.get_top_level_parent_or_group()
219 return test
Jon Salz0697cbf2012-07-04 15:14:04 +0800220 else:
221 return self.test_list
222
223 self.event_handlers = {
224 Event.Type.SWITCH_TEST: self.handle_switch_test,
225 Event.Type.SHOW_NEXT_ACTIVE_TEST:
226 lambda event: self.show_next_active_test(),
227 Event.Type.RESTART_TESTS:
228 lambda event: self.restart_tests(root=test_or_root(event)),
229 Event.Type.AUTO_RUN:
230 lambda event: self.auto_run(root=test_or_root(event)),
231 Event.Type.RE_RUN_FAILED:
232 lambda event: self.re_run_failed(root=test_or_root(event)),
233 Event.Type.RUN_TESTS_WITH_STATUS:
234 lambda event: self.run_tests_with_status(
235 event.status,
236 root=test_or_root(event)),
237 Event.Type.REVIEW:
238 lambda event: self.show_review_information(),
239 Event.Type.UPDATE_SYSTEM_INFO:
240 lambda event: self.update_system_info(),
Jon Salz0697cbf2012-07-04 15:14:04 +0800241 Event.Type.STOP:
Jon Salz85a39882012-07-05 16:45:04 +0800242 lambda event: self.stop(root=test_or_root(event, False),
243 fail=getattr(event, 'fail', False)),
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
286 if self.prespawner:
287 logging.info('Stopping prespawner')
288 self.prespawner.stop()
289 self.prespawner = None
290 if self.event_client:
291 logging.info('Closing event client')
292 self.event_client.close()
293 self.event_client = None
294 if self.event_log:
295 self.event_log.Close()
296 self.event_log = None
Dean Liao592e4d52013-01-10 20:06:39 +0800297 if self.key_filter:
298 self.key_filter.Stop()
299
Jon Salz0697cbf2012-07-04 15:14:04 +0800300 self.check_exceptions()
301 logging.info('Done destroying Goofy')
302
303 def start_state_server(self):
304 self.state_instance, self.state_server = (
305 state.create_server(bind_address='0.0.0.0'))
Jon Salz16d10542012-07-23 12:18:45 +0800306 self.goofy_rpc = GoofyRPC(self)
307 self.goofy_rpc.RegisterMethods(self.state_instance)
Jon Salz0697cbf2012-07-04 15:14:04 +0800308 logging.info('Starting state server')
309 self.state_server_thread = threading.Thread(
310 target=self.state_server.serve_forever,
311 name='StateServer')
312 self.state_server_thread.start()
313
314 def start_event_server(self):
315 self.event_server = EventServer()
316 logging.info('Starting factory event server')
317 self.event_server_thread = threading.Thread(
318 target=self.event_server.serve_forever,
319 name='EventServer') # pylint: disable=E1101
320 self.event_server_thread.start()
321
322 self.event_client = EventClient(
323 callback=self.handle_event, event_loop=self.run_queue)
324
325 self.web_socket_manager = WebSocketManager(self.uuid)
326 self.state_server.add_handler("/event",
327 self.web_socket_manager.handle_web_socket)
328
329 def start_ui(self):
330 ui_proc_args = [
331 os.path.join(factory.FACTORY_PACKAGE_PATH, 'test', 'ui.py'),
332 self.options.test_list]
333 if self.options.verbose:
334 ui_proc_args.append('-v')
335 logging.info('Starting ui %s', ui_proc_args)
Jon Salz78c32392012-07-25 14:18:29 +0800336 self.ui_process = Spawn(ui_proc_args)
Jon Salz0697cbf2012-07-04 15:14:04 +0800337 logging.info('Waiting for UI to come up...')
338 self.event_client.wait(
339 lambda event: event.type == Event.Type.UI_READY)
340 logging.info('UI has started')
341
342 def set_visible_test(self, test):
343 if self.visible_test == test:
344 return
Jon Salz2f2d42c2012-07-30 12:30:34 +0800345 if test and not test.has_ui:
346 return
Jon Salz0697cbf2012-07-04 15:14:04 +0800347
348 if test:
349 test.update_state(visible=True)
350 if self.visible_test:
351 self.visible_test.update_state(visible=False)
352 self.visible_test = test
353
Jon Salzd4306c82012-11-30 15:16:36 +0800354 def _log_startup_messages(self):
355 '''Logs the tail of var/log/messages and mosys and EC console logs.'''
356 # TODO(jsalz): This is mostly a copy-and-paste of code in init_states,
357 # for factory-3004.B only. Consolidate and merge back to ToT.
358 if utils.in_chroot():
359 return
360
361 try:
362 var_log_messages = (
363 utils.var_log_messages_before_reboot())
364 logging.info(
365 'Tail of /var/log/messages before last reboot:\n'
366 '%s', ('\n'.join(
367 ' ' + x for x in var_log_messages)))
368 except: # pylint: disable=W0702
369 logging.exception('Unable to grok /var/log/messages')
370
371 try:
372 mosys_log = utils.Spawn(
373 ['mosys', 'eventlog', 'list'],
374 read_stdout=True, log_stderr_on_error=True).stdout_data
375 logging.info('System eventlog from mosys:\n%s\n', mosys_log)
376 except: # pylint: disable=W0702
377 logging.exception('Unable to read mosys eventlog')
378
379 try:
Vic Yang8341dde2013-01-29 16:48:52 +0800380 board = system.GetBoard()
381 ec_console_log = board.GetECConsoleLog()
Jon Salzd4306c82012-11-30 15:16:36 +0800382 logging.info('EC console log after reboot:\n%s\n', ec_console_log)
383 except: # pylint: disable=W0702
384 logging.exception('Error retrieving EC console log')
385
Jon Salz0697cbf2012-07-04 15:14:04 +0800386 def handle_shutdown_complete(self, test, test_state):
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800387 '''
Jon Salz0697cbf2012-07-04 15:14:04 +0800388 Handles the case where a shutdown was detected during a shutdown step.
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800389
Jon Salz0697cbf2012-07-04 15:14:04 +0800390 @param test: The ShutdownStep.
391 @param test_state: The test state.
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800392 '''
Jon Salz0697cbf2012-07-04 15:14:04 +0800393 test_state = test.update_state(increment_shutdown_count=1)
394 logging.info('Detected shutdown (%d of %d)',
395 test_state.shutdown_count, test.iterations)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800396
Jon Salz0697cbf2012-07-04 15:14:04 +0800397 def log_and_update_state(status, error_msg, **kw):
398 self.event_log.Log('rebooted',
399 status=status, error_msg=error_msg, **kw)
Jon Salzd4306c82012-11-30 15:16:36 +0800400 logging.info('Rebooted: status=%s, %s', status,
401 (('error_msg=%s' % error_msg) if error_msg else None))
Jon Salz0697cbf2012-07-04 15:14:04 +0800402 test.update_state(status=status, error_msg=error_msg)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800403
Jon Salz0697cbf2012-07-04 15:14:04 +0800404 if not self.last_shutdown_time:
405 log_and_update_state(status=TestState.FAILED,
406 error_msg='Unable to read shutdown_time')
407 return
Jon Salz258a40c2012-04-19 12:34:01 +0800408
Jon Salz0697cbf2012-07-04 15:14:04 +0800409 now = time.time()
410 logging.info('%.03f s passed since reboot',
411 now - self.last_shutdown_time)
Jon Salz258a40c2012-04-19 12:34:01 +0800412
Jon Salz0697cbf2012-07-04 15:14:04 +0800413 if self.last_shutdown_time > now:
414 test.update_state(status=TestState.FAILED,
415 error_msg='Time moved backward during reboot')
416 elif (isinstance(test, factory.RebootStep) and
417 self.test_list.options.max_reboot_time_secs and
418 (now - self.last_shutdown_time >
419 self.test_list.options.max_reboot_time_secs)):
420 # A reboot took too long; fail. (We don't check this for
421 # HaltSteps, because the machine could be halted for a
422 # very long time, and even unplugged with battery backup,
423 # thus hosing the clock.)
424 log_and_update_state(
425 status=TestState.FAILED,
426 error_msg=('More than %d s elapsed during reboot '
427 '(%.03f s, from %s to %s)' % (
428 self.test_list.options.max_reboot_time_secs,
429 now - self.last_shutdown_time,
430 utils.TimeString(self.last_shutdown_time),
431 utils.TimeString(now))),
432 duration=(now-self.last_shutdown_time))
Jon Salzd4306c82012-11-30 15:16:36 +0800433 self._log_startup_messages()
Jon Salz0697cbf2012-07-04 15:14:04 +0800434 elif test_state.shutdown_count == test.iterations:
435 # Good!
436 log_and_update_state(status=TestState.PASSED,
437 duration=(now - self.last_shutdown_time),
438 error_msg='')
439 elif test_state.shutdown_count > test.iterations:
440 # Shut down too many times
441 log_and_update_state(status=TestState.FAILED,
442 error_msg='Too many shutdowns')
Jon Salzd4306c82012-11-30 15:16:36 +0800443 self._log_startup_messages()
Jon Salz0697cbf2012-07-04 15:14:04 +0800444 elif utils.are_shift_keys_depressed():
445 logging.info('Shift keys are depressed; cancelling restarts')
446 # Abort shutdown
447 log_and_update_state(
448 status=TestState.FAILED,
449 error_msg='Shutdown aborted with double shift keys')
Jon Salza6711d72012-07-18 14:33:03 +0800450 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +0800451 else:
452 def handler():
453 if self._prompt_cancel_shutdown(
454 test, test_state.shutdown_count + 1):
Jon Salza6711d72012-07-18 14:33:03 +0800455 factory.console.info('Shutdown aborted by operator')
Jon Salz0697cbf2012-07-04 15:14:04 +0800456 log_and_update_state(
457 status=TestState.FAILED,
458 error_msg='Shutdown aborted by operator')
Jon Salza6711d72012-07-18 14:33:03 +0800459 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +0800460 return
Jon Salz0405ab52012-03-16 15:26:52 +0800461
Jon Salz0697cbf2012-07-04 15:14:04 +0800462 # Time to shutdown again
463 log_and_update_state(
464 status=TestState.ACTIVE,
465 error_msg='',
466 iteration=test_state.shutdown_count)
Jon Salz73e0fd02012-04-04 11:46:38 +0800467
Jon Salz0697cbf2012-07-04 15:14:04 +0800468 self.event_log.Log('shutdown', operation='reboot')
469 self.state_instance.set_shared_data('shutdown_time',
470 time.time())
471 self.env.shutdown('reboot')
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800472
Jon Salz0697cbf2012-07-04 15:14:04 +0800473 self.on_ui_startup.append(handler)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800474
Jon Salz0697cbf2012-07-04 15:14:04 +0800475 def _prompt_cancel_shutdown(self, test, iteration):
476 if self.options.ui != 'chrome':
477 return False
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800478
Jon Salz0697cbf2012-07-04 15:14:04 +0800479 pending_shutdown_data = {
480 'delay_secs': test.delay_secs,
481 'time': time.time() + test.delay_secs,
482 'operation': test.operation,
483 'iteration': iteration,
484 'iterations': test.iterations,
485 }
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800486
Jon Salz0697cbf2012-07-04 15:14:04 +0800487 # Create a new (threaded) event client since we
488 # don't want to use the event loop for this.
489 with EventClient() as event_client:
490 event_client.post_event(Event(Event.Type.PENDING_SHUTDOWN,
491 **pending_shutdown_data))
492 aborted = event_client.wait(
493 lambda event: event.type == Event.Type.CANCEL_SHUTDOWN,
494 timeout=test.delay_secs) is not None
495 if aborted:
496 event_client.post_event(Event(Event.Type.PENDING_SHUTDOWN))
497 return aborted
Jon Salz258a40c2012-04-19 12:34:01 +0800498
Jon Salz0697cbf2012-07-04 15:14:04 +0800499 def init_states(self):
500 '''
501 Initializes all states on startup.
502 '''
503 for test in self.test_list.get_all_tests():
504 # Make sure the state server knows about all the tests,
505 # defaulting to an untested state.
506 test.update_state(update_parent=False, visible=False)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800507
Jon Salz0697cbf2012-07-04 15:14:04 +0800508 var_log_messages = None
Vic Yanga9c32212012-08-16 20:07:54 +0800509 mosys_log = None
Vic Yange4c275d2012-08-28 01:50:20 +0800510 ec_console_log = None
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800511
Jon Salz0697cbf2012-07-04 15:14:04 +0800512 # Any 'active' tests should be marked as failed now.
513 for test in self.test_list.walk():
Jon Salza6711d72012-07-18 14:33:03 +0800514 if not test.is_leaf():
515 # Don't bother with parents; they will be updated when their
516 # children are updated.
517 continue
518
Jon Salz0697cbf2012-07-04 15:14:04 +0800519 test_state = test.get_state()
520 if test_state.status != TestState.ACTIVE:
521 continue
522 if isinstance(test, factory.ShutdownStep):
523 # Shutdown while the test was active - that's good.
524 self.handle_shutdown_complete(test, test_state)
525 else:
526 # Unexpected shutdown. Grab /var/log/messages for context.
527 if var_log_messages is None:
528 try:
529 var_log_messages = (
530 utils.var_log_messages_before_reboot())
531 # Write it to the log, to make it easier to
532 # correlate with /var/log/messages.
533 logging.info(
534 'Unexpected shutdown. '
535 'Tail of /var/log/messages before last reboot:\n'
536 '%s', ('\n'.join(
537 ' ' + x for x in var_log_messages)))
538 except: # pylint: disable=W0702
539 logging.exception('Unable to grok /var/log/messages')
540 var_log_messages = []
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800541
Jon Salz008f4ea2012-08-28 05:39:45 +0800542 if mosys_log is None and not utils.in_chroot():
543 try:
544 mosys_log = utils.Spawn(
545 ['mosys', 'eventlog', 'list'],
546 read_stdout=True, log_stderr_on_error=True).stdout_data
547 # Write it to the log also.
548 logging.info('System eventlog from mosys:\n%s\n', mosys_log)
549 except: # pylint: disable=W0702
550 logging.exception('Unable to read mosys eventlog')
Vic Yanga9c32212012-08-16 20:07:54 +0800551
Vic Yange4c275d2012-08-28 01:50:20 +0800552 if ec_console_log is None:
553 try:
Vic Yang8341dde2013-01-29 16:48:52 +0800554 board = system.GetBoard()
555 ec_console_log = board.GetECConsoleLog()
Vic Yange4c275d2012-08-28 01:50:20 +0800556 logging.info('EC console log after reboot:\n%s\n', ec_console_log)
Jon Salzfe1f6652012-09-07 05:40:14 +0800557 except: # pylint: disable=W0702
Vic Yange4c275d2012-08-28 01:50:20 +0800558 logging.exception('Error retrieving EC console log')
559
Jon Salz0697cbf2012-07-04 15:14:04 +0800560 error_msg = 'Unexpected shutdown while test was running'
561 self.event_log.Log('end_test',
562 path=test.path,
563 status=TestState.FAILED,
564 invocation=test.get_state().invocation,
565 error_msg=error_msg,
Vic Yanga9c32212012-08-16 20:07:54 +0800566 var_log_messages='\n'.join(var_log_messages),
567 mosys_log=mosys_log)
Jon Salz0697cbf2012-07-04 15:14:04 +0800568 test.update_state(
569 status=TestState.FAILED,
570 error_msg=error_msg)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800571
Jon Salz50efe942012-07-26 11:54:10 +0800572 if not test.never_fails:
573 # For "never_fails" tests (such as "Start"), don't cancel
574 # pending tests, since reboot is expected.
575 factory.console.info('Unexpected shutdown while test %s '
576 'running; cancelling any pending tests',
577 test.path)
578 self.state_instance.set_shared_data('tests_after_shutdown', [])
Jon Salz69806bb2012-07-20 18:05:02 +0800579
Jon Salz008f4ea2012-08-28 05:39:45 +0800580 self.update_skipped_tests()
581
582 def update_skipped_tests(self):
583 '''
584 Updates skipped states based on run_if.
585 '''
586 for t in self.test_list.walk():
587 if t.is_leaf() and t.run_if_table_name:
588 skip = False
589 try:
590 aux = shopfloor.get_selected_aux_data(t.run_if_table_name)
591 value = aux.get(t.run_if_col)
592 if value is not None:
593 skip = (not value) ^ t.run_if_not
594 except ValueError:
595 # Not available; assume it shouldn't be skipped
596 pass
597
598 test_state = t.get_state()
599 if ((not skip) and
600 (test_state.status == TestState.PASSED) and
601 (test_state.error_msg == TestState.SKIPPED_MSG)):
602 # It was marked as skipped before, but now we need to run it.
603 # Mark as untested.
604 t.update_state(skip=skip, status=TestState.UNTESTED, error_msg='')
605 else:
606 t.update_state(skip=skip)
607
Jon Salz0697cbf2012-07-04 15:14:04 +0800608 def show_next_active_test(self):
609 '''
610 Rotates to the next visible active test.
611 '''
612 self.reap_completed_tests()
613 active_tests = [
614 t for t in self.test_list.walk()
615 if t.is_leaf() and t.get_state().status == TestState.ACTIVE]
616 if not active_tests:
617 return
Jon Salz4f6c7172012-06-11 20:45:36 +0800618
Jon Salz0697cbf2012-07-04 15:14:04 +0800619 try:
620 next_test = active_tests[
621 (active_tests.index(self.visible_test) + 1) % len(active_tests)]
622 except ValueError: # visible_test not present in active_tests
623 next_test = active_tests[0]
Jon Salz4f6c7172012-06-11 20:45:36 +0800624
Jon Salz0697cbf2012-07-04 15:14:04 +0800625 self.set_visible_test(next_test)
Jon Salz4f6c7172012-06-11 20:45:36 +0800626
Jon Salz0697cbf2012-07-04 15:14:04 +0800627 def handle_event(self, event):
628 '''
629 Handles an event from the event server.
630 '''
631 handler = self.event_handlers.get(event.type)
632 if handler:
633 handler(event)
634 else:
635 # We don't register handlers for all event types - just ignore
636 # this event.
637 logging.debug('Unbound event type %s', event.type)
Jon Salz4f6c7172012-06-11 20:45:36 +0800638
Jon Salz0697cbf2012-07-04 15:14:04 +0800639 def run_next_test(self):
640 '''
641 Runs the next eligible test (or tests) in self.tests_to_run.
642 '''
643 self.reap_completed_tests()
644 while self.tests_to_run:
645 logging.debug('Tests to run: %s',
646 [x.path for x in self.tests_to_run])
Jon Salz94eb56f2012-06-12 18:01:12 +0800647
Jon Salz0697cbf2012-07-04 15:14:04 +0800648 test = self.tests_to_run[0]
Jon Salz94eb56f2012-06-12 18:01:12 +0800649
Jon Salz0697cbf2012-07-04 15:14:04 +0800650 if test in self.invocations:
651 logging.info('Next test %s is already running', test.path)
652 self.tests_to_run.popleft()
653 return
Jon Salz94eb56f2012-06-12 18:01:12 +0800654
Jon Salza1412922012-07-23 16:04:17 +0800655 for requirement in test.require_run:
656 for i in requirement.test.walk():
657 if i.get_state().status == TestState.ACTIVE:
Jon Salz304a75d2012-07-06 11:14:15 +0800658 logging.info('Waiting for active test %s to complete '
Jon Salza1412922012-07-23 16:04:17 +0800659 'before running %s', i.path, test.path)
Jon Salz304a75d2012-07-06 11:14:15 +0800660 return
661
Jon Salz0697cbf2012-07-04 15:14:04 +0800662 if self.invocations and not (test.backgroundable and all(
663 [x.backgroundable for x in self.invocations])):
664 logging.debug('Waiting for non-backgroundable tests to '
665 'complete before running %s', test.path)
666 return
Jon Salz94eb56f2012-06-12 18:01:12 +0800667
Jon Salz3e6f5202012-10-15 15:08:29 +0800668 if test.get_state().skip:
669 factory.console.info('Skipping test %s', test.path)
670 test.update_state(status=TestState.PASSED,
671 error_msg=TestState.SKIPPED_MSG)
672 self.tests_to_run.popleft()
673 continue
674
Jon Salz0697cbf2012-07-04 15:14:04 +0800675 self.tests_to_run.popleft()
Jon Salz94eb56f2012-06-12 18:01:12 +0800676
Jon Salz304a75d2012-07-06 11:14:15 +0800677 untested = set()
Jon Salza1412922012-07-23 16:04:17 +0800678 for requirement in test.require_run:
679 for i in requirement.test.walk():
680 if i == test:
Jon Salz304a75d2012-07-06 11:14:15 +0800681 # We've hit this test itself; stop checking
682 break
Jon Salza1412922012-07-23 16:04:17 +0800683 if ((i.get_state().status == TestState.UNTESTED) or
684 (requirement.passed and i.get_state().status !=
685 TestState.PASSED)):
Jon Salz304a75d2012-07-06 11:14:15 +0800686 # Found an untested test; move on to the next
687 # element in require_run.
Jon Salza1412922012-07-23 16:04:17 +0800688 untested.add(i)
Jon Salz304a75d2012-07-06 11:14:15 +0800689 break
690
691 if untested:
692 untested_paths = ', '.join(sorted([x.path for x in untested]))
693 if self.state_instance.get_shared_data('engineering_mode',
694 optional=True):
695 # In engineering mode, we'll let it go.
696 factory.console.warn('In engineering mode; running '
697 '%s even though required tests '
698 '[%s] have not completed',
699 test.path, untested_paths)
700 else:
701 # Not in engineering mode; mark it failed.
702 error_msg = ('Required tests [%s] have not been run yet'
703 % untested_paths)
704 factory.console.error('Not running %s: %s',
705 test.path, error_msg)
706 test.update_state(status=TestState.FAILED,
707 error_msg=error_msg)
708 continue
709
Jon Salz0697cbf2012-07-04 15:14:04 +0800710 if isinstance(test, factory.ShutdownStep):
711 if os.path.exists(NO_REBOOT_FILE):
712 test.update_state(
713 status=TestState.FAILED, increment_count=1,
714 error_msg=('Skipped shutdown since %s is present' %
Jon Salz304a75d2012-07-06 11:14:15 +0800715 NO_REBOOT_FILE))
Jon Salz0697cbf2012-07-04 15:14:04 +0800716 continue
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800717
Jon Salz0697cbf2012-07-04 15:14:04 +0800718 test.update_state(status=TestState.ACTIVE, increment_count=1,
719 error_msg='', shutdown_count=0)
720 if self._prompt_cancel_shutdown(test, 1):
721 self.event_log.Log('reboot_cancelled')
722 test.update_state(
723 status=TestState.FAILED, increment_count=1,
724 error_msg='Shutdown aborted by operator',
725 shutdown_count=0)
chungyiafe8f772012-08-15 19:36:29 +0800726 continue
Jon Salz2f757d42012-06-27 17:06:42 +0800727
Jon Salz0697cbf2012-07-04 15:14:04 +0800728 # Save pending test list in the state server
Jon Salzdbf398f2012-06-14 17:30:01 +0800729 self.state_instance.set_shared_data(
Jon Salz0697cbf2012-07-04 15:14:04 +0800730 'tests_after_shutdown',
731 [t.path for t in self.tests_to_run])
732 # Save shutdown time
733 self.state_instance.set_shared_data('shutdown_time',
734 time.time())
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800735
Jon Salz0697cbf2012-07-04 15:14:04 +0800736 with self.env.lock:
737 self.event_log.Log('shutdown', operation=test.operation)
738 shutdown_result = self.env.shutdown(test.operation)
739 if shutdown_result:
740 # That's all, folks!
741 self.run_queue.put(None)
742 return
743 else:
744 # Just pass (e.g., in the chroot).
745 test.update_state(status=TestState.PASSED)
746 self.state_instance.set_shared_data(
747 'tests_after_shutdown', None)
748 # Send event with no fields to indicate that there is no
749 # longer a pending shutdown.
750 self.event_client.post_event(Event(
751 Event.Type.PENDING_SHUTDOWN))
752 continue
Jon Salz258a40c2012-04-19 12:34:01 +0800753
Jon Salz1acc8742012-07-17 17:45:55 +0800754 self._run_test(test, test.iterations)
755
756 def _run_test(self, test, iterations_left=None):
757 invoc = TestInvocation(self, test, on_completion=self.run_next_test)
758 new_state = test.update_state(
759 status=TestState.ACTIVE, increment_count=1, error_msg='',
Jon Salzbd42ce12012-09-18 08:03:59 +0800760 invocation=invoc.uuid, iterations_left=iterations_left,
761 visible=(self.visible_test == test))
Jon Salz1acc8742012-07-17 17:45:55 +0800762 invoc.count = new_state.count
763
764 self.invocations[test] = invoc
765 if self.visible_test is None and test.has_ui:
766 self.set_visible_test(test)
Vic Yang311ddb82012-09-26 12:08:28 +0800767 self.check_exclusive()
Jon Salz1acc8742012-07-17 17:45:55 +0800768 invoc.start()
Jon Salz5f2a0672012-05-22 17:14:06 +0800769
Vic Yang311ddb82012-09-26 12:08:28 +0800770 def check_exclusive(self):
771 current_exclusive_items = set([
772 item
773 for item in factory.FactoryTest.EXCLUSIVE_OPTIONS
774 if any([test.is_exclusive(item) for test in self.invocations])])
775
776 new_exclusive_items = current_exclusive_items - self.exclusive_items
777 if factory.FactoryTest.EXCLUSIVE_OPTIONS.NETWORKING in new_exclusive_items:
778 logging.info('Disabling network')
779 self.connection_manager.DisableNetworking()
780 if factory.FactoryTest.EXCLUSIVE_OPTIONS.CHARGER in new_exclusive_items:
781 logging.info('Stop controlling charger')
782
783 new_non_exclusive_items = self.exclusive_items - current_exclusive_items
784 if (factory.FactoryTest.EXCLUSIVE_OPTIONS.NETWORKING in
785 new_non_exclusive_items):
786 logging.info('Re-enabling network')
787 self.connection_manager.EnableNetworking()
788 if factory.FactoryTest.EXCLUSIVE_OPTIONS.CHARGER in new_non_exclusive_items:
789 logging.info('Start controlling charger')
790
791 # Only adjust charge state if not excluded
792 if (self.charge_manager and
793 not factory.FactoryTest.EXCLUSIVE_OPTIONS.CHARGER in
794 current_exclusive_items):
795 self.charge_manager.AdjustChargeState()
796
797 self.exclusive_items = current_exclusive_items
Jon Salz5da61e62012-05-31 13:06:22 +0800798
cychiang21886742012-07-05 15:16:32 +0800799 def check_for_updates(self):
800 '''
801 Schedules an asynchronous check for updates if necessary.
802 '''
803 if not self.test_list.options.update_period_secs:
804 # Not enabled.
805 return
806
807 now = time.time()
808 if self.last_update_check and (
809 now - self.last_update_check <
810 self.test_list.options.update_period_secs):
811 # Not yet time for another check.
812 return
813
814 self.last_update_check = now
815
816 def handle_check_for_update(reached_shopfloor, md5sum, needs_update):
817 if reached_shopfloor:
818 new_update_md5sum = md5sum if needs_update else None
819 if system.SystemInfo.update_md5sum != new_update_md5sum:
820 logging.info('Received new update MD5SUM: %s', new_update_md5sum)
821 system.SystemInfo.update_md5sum = new_update_md5sum
822 self.run_queue.put(self.update_system_info)
823
824 updater.CheckForUpdateAsync(
825 handle_check_for_update,
826 self.test_list.options.shopfloor_timeout_secs)
827
Jon Salza6711d72012-07-18 14:33:03 +0800828 def cancel_pending_tests(self):
829 '''Cancels any tests in the run queue.'''
830 self.run_tests([])
831
Jon Salz0697cbf2012-07-04 15:14:04 +0800832 def run_tests(self, subtrees, untested_only=False):
833 '''
834 Runs tests under subtree.
Jon Salz258a40c2012-04-19 12:34:01 +0800835
Jon Salz0697cbf2012-07-04 15:14:04 +0800836 The tests are run in order unless one fails (then stops).
837 Backgroundable tests are run simultaneously; when a foreground test is
838 encountered, we wait for all active tests to finish before continuing.
Jon Salzb1b39092012-05-03 02:05:09 +0800839
Jon Salz0697cbf2012-07-04 15:14:04 +0800840 @param subtrees: Node or nodes containing tests to run (may either be
841 a single test or a list). Duplicates will be ignored.
842 '''
843 if type(subtrees) != list:
844 subtrees = [subtrees]
Jon Salz258a40c2012-04-19 12:34:01 +0800845
Jon Salz0697cbf2012-07-04 15:14:04 +0800846 # Nodes we've seen so far, to avoid duplicates.
847 seen = set()
Jon Salz94eb56f2012-06-12 18:01:12 +0800848
Jon Salz0697cbf2012-07-04 15:14:04 +0800849 self.tests_to_run = deque()
850 for subtree in subtrees:
851 for test in subtree.walk():
852 if test in seen:
853 continue
854 seen.add(test)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800855
Jon Salz0697cbf2012-07-04 15:14:04 +0800856 if not test.is_leaf():
857 continue
858 if (untested_only and
859 test.get_state().status != TestState.UNTESTED):
860 continue
861 self.tests_to_run.append(test)
862 self.run_next_test()
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800863
Jon Salz0697cbf2012-07-04 15:14:04 +0800864 def reap_completed_tests(self):
865 '''
866 Removes completed tests from the set of active tests.
867
868 Also updates the visible test if it was reaped.
869 '''
870 for t, v in dict(self.invocations).iteritems():
871 if v.is_completed():
Jon Salz1acc8742012-07-17 17:45:55 +0800872 new_state = t.update_state(**v.update_state_on_completion)
Jon Salz0697cbf2012-07-04 15:14:04 +0800873 del self.invocations[t]
874
Chun-Ta Lin54e17e42012-09-06 22:05:13 +0800875 # Stop on failure if flag is true.
876 if (self.test_list.options.stop_on_failure and
877 new_state.status == TestState.FAILED):
878 # Clean all the tests to cause goofy to stop.
879 self.tests_to_run = []
880 factory.console.info("Stop on failure triggered. Empty the queue.")
881
Jon Salz1acc8742012-07-17 17:45:55 +0800882 if new_state.iterations_left and new_state.status == TestState.PASSED:
883 # Play it again, Sam!
884 self._run_test(t)
885
Jon Salz0697cbf2012-07-04 15:14:04 +0800886 if (self.visible_test is None or
Jon Salz85a39882012-07-05 16:45:04 +0800887 self.visible_test not in self.invocations):
Jon Salz0697cbf2012-07-04 15:14:04 +0800888 self.set_visible_test(None)
889 # Make the first running test, if any, the visible test
890 for t in self.test_list.walk():
891 if t in self.invocations:
892 self.set_visible_test(t)
893 break
894
Jon Salz85a39882012-07-05 16:45:04 +0800895 def kill_active_tests(self, abort, root=None):
Jon Salz0697cbf2012-07-04 15:14:04 +0800896 '''
897 Kills and waits for all active tests.
898
Jon Salz85a39882012-07-05 16:45:04 +0800899 Args:
900 abort: True to change state of killed tests to FAILED, False for
Jon Salz0697cbf2012-07-04 15:14:04 +0800901 UNTESTED.
Jon Salz85a39882012-07-05 16:45:04 +0800902 root: If set, only kills tests with root as an ancestor.
Jon Salz0697cbf2012-07-04 15:14:04 +0800903 '''
904 self.reap_completed_tests()
905 for test, invoc in self.invocations.items():
Jon Salz85a39882012-07-05 16:45:04 +0800906 if root and not test.has_ancestor(root):
907 continue
908
Jon Salz0697cbf2012-07-04 15:14:04 +0800909 factory.console.info('Killing active test %s...' % test.path)
910 invoc.abort_and_join()
911 factory.console.info('Killed %s' % test.path)
Jon Salz1acc8742012-07-17 17:45:55 +0800912 test.update_state(**invoc.update_state_on_completion)
Jon Salz0697cbf2012-07-04 15:14:04 +0800913 del self.invocations[test]
Jon Salz1acc8742012-07-17 17:45:55 +0800914
Jon Salz0697cbf2012-07-04 15:14:04 +0800915 if not abort:
916 test.update_state(status=TestState.UNTESTED)
917 self.reap_completed_tests()
918
Jon Salz85a39882012-07-05 16:45:04 +0800919 def stop(self, root=None, fail=False):
920 self.kill_active_tests(fail, root)
921 # Remove any tests in the run queue under the root.
922 self.tests_to_run = deque([x for x in self.tests_to_run
923 if root and not x.has_ancestor(root)])
924 self.run_next_test()
Jon Salz0697cbf2012-07-04 15:14:04 +0800925
Jon Salz4712ac72013-02-07 17:12:05 +0800926 def clear_state(self, root=None):
927 self.stop(root)
928 for f in root.walk():
929 if f.is_leaf():
930 f.update_state(status=TestState.UNTESTED)
931
Jon Salz0697cbf2012-07-04 15:14:04 +0800932 def abort_active_tests(self):
933 self.kill_active_tests(True)
934
935 def main(self):
936 try:
937 self.init()
938 self.event_log.Log('goofy_init',
939 success=True)
940 except:
941 if self.event_log:
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800942 try:
Jon Salz0697cbf2012-07-04 15:14:04 +0800943 self.event_log.Log('goofy_init',
944 success=False,
945 trace=traceback.format_exc())
946 except: # pylint: disable=W0702
947 pass
948 raise
949
950 self.run()
951
952 def update_system_info(self):
953 '''Updates system info.'''
954 system_info = system.SystemInfo()
955 self.state_instance.set_shared_data('system_info', system_info.__dict__)
956 self.event_client.post_event(Event(Event.Type.SYSTEM_INFO,
957 system_info=system_info.__dict__))
958 logging.info('System info: %r', system_info.__dict__)
959
Jon Salzeb42f0d2012-07-27 19:14:04 +0800960 def update_factory(self, auto_run_on_restart=False, post_update_hook=None):
961 '''Commences updating factory software.
962
963 Args:
964 auto_run_on_restart: Auto-run when the machine comes back up.
965 post_update_hook: Code to call after update but immediately before
966 restart.
967
968 Returns:
969 Never if the update was successful (we just reboot).
970 False if the update was unnecessary (no update available).
971 '''
Jon Salz0697cbf2012-07-04 15:14:04 +0800972 self.kill_active_tests(False)
Jon Salza6711d72012-07-18 14:33:03 +0800973 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +0800974
Jon Salz5c344f62012-07-13 14:31:16 +0800975 def pre_update_hook():
976 if auto_run_on_restart:
977 self.state_instance.set_shared_data('tests_after_shutdown',
978 FORCE_AUTO_RUN)
979 self.state_instance.close()
980
Jon Salzeb42f0d2012-07-27 19:14:04 +0800981 if updater.TryUpdate(pre_update_hook=pre_update_hook):
982 if post_update_hook:
983 post_update_hook()
984 self.env.shutdown('reboot')
Jon Salz0697cbf2012-07-04 15:14:04 +0800985
Jon Salzcef132a2012-08-30 04:58:08 +0800986 def handle_sigint(self, dummy_signum, dummy_frame):
Jon Salz77c151e2012-08-28 07:20:37 +0800987 logging.error('Received SIGINT')
988 self.run_queue.put(None)
989 raise KeyboardInterrupt()
990
Jon Salz0697cbf2012-07-04 15:14:04 +0800991 def init(self, args=None, env=None):
992 '''Initializes Goofy.
993
994 Args:
995 args: A list of command-line arguments. Uses sys.argv if
996 args is None.
997 env: An Environment instance to use (or None to choose
998 FakeChrootEnvironment or DUTEnvironment as appropriate).
999 '''
Jon Salz77c151e2012-08-28 07:20:37 +08001000 signal.signal(signal.SIGINT, self.handle_sigint)
1001
Jon Salz0697cbf2012-07-04 15:14:04 +08001002 parser = OptionParser()
1003 parser.add_option('-v', '--verbose', dest='verbose',
Jon Salz8fa8e832012-07-13 19:04:09 +08001004 action='store_true',
1005 help='Enable debug logging')
Jon Salz0697cbf2012-07-04 15:14:04 +08001006 parser.add_option('--print_test_list', dest='print_test_list',
Jon Salz8fa8e832012-07-13 19:04:09 +08001007 metavar='FILE',
1008 help='Read and print test list FILE, and exit')
Jon Salz0697cbf2012-07-04 15:14:04 +08001009 parser.add_option('--restart', dest='restart',
Jon Salz8fa8e832012-07-13 19:04:09 +08001010 action='store_true',
1011 help='Clear all test state')
Jon Salz0697cbf2012-07-04 15:14:04 +08001012 parser.add_option('--ui', dest='ui', type='choice',
Jon Salz8fa8e832012-07-13 19:04:09 +08001013 choices=['none', 'gtk', 'chrome'],
Jon Salz2f881df2013-02-01 17:00:35 +08001014 default='chrome',
Jon Salz8fa8e832012-07-13 19:04:09 +08001015 help='UI to use')
Jon Salz0697cbf2012-07-04 15:14:04 +08001016 parser.add_option('--ui_scale_factor', dest='ui_scale_factor',
Jon Salz8fa8e832012-07-13 19:04:09 +08001017 type='int', default=1,
1018 help=('Factor by which to scale UI '
1019 '(Chrome UI only)'))
Jon Salz0697cbf2012-07-04 15:14:04 +08001020 parser.add_option('--test_list', dest='test_list',
Jon Salz8fa8e832012-07-13 19:04:09 +08001021 metavar='FILE',
1022 help='Use FILE as test list')
Jon Salzc79a9982012-08-30 04:42:01 +08001023 parser.add_option('--dummy_shopfloor', action='store_true',
1024 help='Use a dummy shopfloor server')
chungyiafe8f772012-08-15 19:36:29 +08001025 parser.add_option('--automation', dest='automation',
1026 action='store_true',
1027 help='Enable automation on running factory test')
Ricky Liang09216dc2013-02-22 17:26:45 +08001028 parser.add_option('--one_pixel_less', dest='one_pixel_less',
1029 action='store_true',
1030 help=('Start Chrome one pixel less than the full screen.'
1031 'Needed by Exynos platform to run GTK.'))
Jon Salz0697cbf2012-07-04 15:14:04 +08001032 (self.options, self.args) = parser.parse_args(args)
1033
Jon Salz46b89562012-07-05 11:49:22 +08001034 # Make sure factory directories exist.
1035 factory.get_log_root()
1036 factory.get_state_root()
1037 factory.get_test_data_root()
1038
Jon Salz0697cbf2012-07-04 15:14:04 +08001039 global _inited_logging # pylint: disable=W0603
1040 if not _inited_logging:
1041 factory.init_logging('goofy', verbose=self.options.verbose)
1042 _inited_logging = True
Jon Salz8fa8e832012-07-13 19:04:09 +08001043
Jon Salz0f996602012-10-03 15:26:48 +08001044 if self.options.print_test_list:
1045 print factory.read_test_list(
1046 self.options.print_test_list).__repr__(recursive=True)
1047 sys.exit(0)
1048
Jon Salzee85d522012-07-17 14:34:46 +08001049 event_log.IncrementBootSequence()
Jon Salz0697cbf2012-07-04 15:14:04 +08001050 self.event_log = EventLog('goofy')
1051
1052 if (not suppress_chroot_warning and
1053 factory.in_chroot() and
1054 self.options.ui == 'gtk' and
1055 os.environ.get('DISPLAY') in [None, '', ':0', ':0.0']):
1056 # That's not going to work! Tell the user how to run
1057 # this way.
1058 logging.warn(GOOFY_IN_CHROOT_WARNING)
1059 time.sleep(1)
1060
1061 if env:
1062 self.env = env
1063 elif factory.in_chroot():
1064 self.env = test_environment.FakeChrootEnvironment()
1065 logging.warn(
1066 'Using chroot environment: will not actually run autotests')
1067 else:
1068 self.env = test_environment.DUTEnvironment()
1069 self.env.goofy = self
1070
1071 if self.options.restart:
1072 state.clear_state()
1073
Jon Salz0697cbf2012-07-04 15:14:04 +08001074 if self.options.ui_scale_factor != 1 and utils.in_qemu():
1075 logging.warn(
1076 'In QEMU; ignoring ui_scale_factor argument')
1077 self.options.ui_scale_factor = 1
1078
1079 logging.info('Started')
1080
1081 self.start_state_server()
1082 self.state_instance.set_shared_data('hwid_cfg', get_hwid_cfg())
1083 self.state_instance.set_shared_data('ui_scale_factor',
Ricky Liang09216dc2013-02-22 17:26:45 +08001084 self.options.ui_scale_factor)
1085 self.state_instance.set_shared_data('one_pixel_less',
1086 self.options.one_pixel_less)
Jon Salz0697cbf2012-07-04 15:14:04 +08001087 self.last_shutdown_time = (
1088 self.state_instance.get_shared_data('shutdown_time', optional=True))
1089 self.state_instance.del_shared_data('shutdown_time', optional=True)
1090
Jon Salzb19ea072013-02-07 16:35:00 +08001091 self.state_instance.del_shared_data('startup_error', optional=True)
Jon Salz0697cbf2012-07-04 15:14:04 +08001092 if not self.options.test_list:
1093 self.options.test_list = find_test_list()
Jon Salzb19ea072013-02-07 16:35:00 +08001094 if self.options.test_list:
Jon Salz0697cbf2012-07-04 15:14:04 +08001095 logging.info('Using test list %s', self.options.test_list)
Jon Salzb19ea072013-02-07 16:35:00 +08001096 try:
1097 self.test_list = factory.read_test_list(
1098 self.options.test_list,
1099 self.state_instance)
1100 except: # pylint: disable=W0702
1101 logging.exception('Unable to read test list %r', self.options.test_list)
1102 self.state_instance.set_shared_data('startup_error',
1103 'Unable to read test list %s\n%s' % (
1104 self.options.test_list,
1105 traceback.format_exc()))
1106 else:
1107 logging.error('No test list found.')
1108 self.state_instance.set_shared_data('startup_error',
1109 'No test list found.')
Jon Salz0697cbf2012-07-04 15:14:04 +08001110
Jon Salzb19ea072013-02-07 16:35:00 +08001111 if not self.test_list:
1112 if self.options.ui == 'chrome':
1113 # Create an empty test list with default options so that the rest of
1114 # startup can proceed.
1115 self.test_list = factory.FactoryTestList(
1116 [], self.state_instance, factory.Options())
1117 else:
1118 # Bail with an error; no point in starting up.
1119 sys.exit('No valid test list; exiting.')
1120
Jon Salz0697cbf2012-07-04 15:14:04 +08001121 if not self.state_instance.has_shared_data('ui_lang'):
1122 self.state_instance.set_shared_data('ui_lang',
1123 self.test_list.options.ui_lang)
1124 self.state_instance.set_shared_data(
1125 'test_list_options',
1126 self.test_list.options.__dict__)
1127 self.state_instance.test_list = self.test_list
1128
Jon Salz83ef34b2012-11-01 19:46:35 +08001129 if not utils.in_chroot() and self.test_list.options.disable_log_rotation:
1130 open('/var/lib/cleanup_logs_paused', 'w').close()
1131
Jon Salz23926422012-09-01 03:38:13 +08001132 if self.options.dummy_shopfloor:
1133 os.environ[shopfloor.SHOPFLOOR_SERVER_ENV_VAR_NAME] = (
1134 'http://localhost:%d/' % shopfloor.DEFAULT_SERVER_PORT)
1135 self.dummy_shopfloor = Spawn(
1136 [os.path.join(factory.FACTORY_PATH, 'bin', 'shopfloor_server'),
1137 '--dummy'])
1138 elif self.test_list.options.shopfloor_server_url:
1139 shopfloor.set_server_url(self.test_list.options.shopfloor_server_url)
1140
Jon Salz0f996602012-10-03 15:26:48 +08001141 if self.test_list.options.time_sanitizer and not utils.in_chroot():
Jon Salz8fa8e832012-07-13 19:04:09 +08001142 self.time_sanitizer = time_sanitizer.TimeSanitizer(
1143 base_time=time_sanitizer.GetBaseTimeFromFile(
1144 # lsb-factory is written by the factory install shim during
1145 # installation, so it should have a good time obtained from
Jon Salz54882d02012-08-31 01:57:54 +08001146 # the mini-Omaha server. If it's not available, we'll use
1147 # /etc/lsb-factory (which will be much older, but reasonably
1148 # sane) and rely on a shopfloor sync to set a more accurate
1149 # time.
1150 '/usr/local/etc/lsb-factory',
1151 '/etc/lsb-release'))
Jon Salz8fa8e832012-07-13 19:04:09 +08001152 self.time_sanitizer.RunOnce()
1153
Jon Salz0697cbf2012-07-04 15:14:04 +08001154 self.init_states()
1155 self.start_event_server()
1156 self.connection_manager = self.env.create_connection_manager(
Tai-Hsu Lin371351a2012-08-27 14:17:14 +08001157 self.test_list.options.wlans,
1158 self.test_list.options.scan_wifi_period_secs)
Jon Salz0697cbf2012-07-04 15:14:04 +08001159 # Note that we create a log watcher even if
1160 # sync_event_log_period_secs isn't set (no background
1161 # syncing), since we may use it to flush event logs as well.
1162 self.log_watcher = EventLogWatcher(
1163 self.test_list.options.sync_event_log_period_secs,
Jon Salz16d10542012-07-23 12:18:45 +08001164 handle_event_logs_callback=self.handle_event_logs)
Jon Salz0697cbf2012-07-04 15:14:04 +08001165 if self.test_list.options.sync_event_log_period_secs:
1166 self.log_watcher.StartWatchThread()
1167
1168 self.update_system_info()
1169
Vic Yang4953fc12012-07-26 16:19:53 +08001170 assert ((self.test_list.options.min_charge_pct is None) ==
1171 (self.test_list.options.max_charge_pct is None))
Jon Salzad7353b2012-10-15 16:22:46 +08001172 if self.test_list.options.min_charge_pct is not None:
Vic Yang4953fc12012-07-26 16:19:53 +08001173 self.charge_manager = ChargeManager(self.test_list.options.min_charge_pct,
1174 self.test_list.options.max_charge_pct)
Jon Salzad7353b2012-10-15 16:22:46 +08001175 system.SystemStatus.charge_manager = self.charge_manager
Vic Yang4953fc12012-07-26 16:19:53 +08001176
Jon Salz0697cbf2012-07-04 15:14:04 +08001177 os.environ['CROS_FACTORY'] = '1'
1178 os.environ['CROS_DISABLE_SITE_SYSINFO'] = '1'
1179
1180 # Set CROS_UI since some behaviors in ui.py depend on the
1181 # particular UI in use. TODO(jsalz): Remove this (and all
1182 # places it is used) when the GTK UI is removed.
1183 os.environ['CROS_UI'] = self.options.ui
1184
1185 if self.options.ui == 'chrome':
1186 self.env.launch_chrome()
1187 logging.info('Waiting for a web socket connection')
Cheng-Yi Chiangfd8ed392013-03-08 21:37:31 +08001188 self.web_socket_manager.wait()
Jon Salz0697cbf2012-07-04 15:14:04 +08001189
1190 # Wait for the test widget size to be set; this is done in
1191 # an asynchronous RPC so there is a small chance that the
1192 # web socket might be opened first.
1193 for _ in range(100): # 10 s
1194 try:
1195 if self.state_instance.get_shared_data('test_widget_size'):
1196 break
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001197 except KeyError:
Jon Salz0697cbf2012-07-04 15:14:04 +08001198 pass # Retry
1199 time.sleep(0.1) # 100 ms
1200 else:
1201 logging.warn('Never received test_widget_size from UI')
1202 elif self.options.ui == 'gtk':
1203 self.start_ui()
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001204
Ricky Liang650f6bf2012-09-28 13:22:54 +08001205 # Create download path for autotest beforehand or autotests run at
1206 # the same time might fail due to race condition.
1207 if not factory.in_chroot():
1208 utils.TryMakeDirs(os.path.join('/usr/local/autotest', 'tests',
1209 'download'))
1210
Jon Salz0697cbf2012-07-04 15:14:04 +08001211 def state_change_callback(test, test_state):
1212 self.event_client.post_event(
1213 Event(Event.Type.STATE_CHANGE,
1214 path=test.path, state=test_state))
1215 self.test_list.state_change_callback = state_change_callback
Jon Salz73e0fd02012-04-04 11:46:38 +08001216
Jon Salza6711d72012-07-18 14:33:03 +08001217 for handler in self.on_ui_startup:
1218 handler()
1219
1220 self.prespawner = Prespawner()
1221 self.prespawner.start()
1222
Jon Salz0697cbf2012-07-04 15:14:04 +08001223 try:
1224 tests_after_shutdown = self.state_instance.get_shared_data(
1225 'tests_after_shutdown')
1226 except KeyError:
1227 tests_after_shutdown = None
Jon Salz57717ca2012-04-04 16:47:25 +08001228
Jon Salz5c344f62012-07-13 14:31:16 +08001229 force_auto_run = (tests_after_shutdown == FORCE_AUTO_RUN)
1230 if not force_auto_run and tests_after_shutdown is not None:
Jon Salz0697cbf2012-07-04 15:14:04 +08001231 logging.info('Resuming tests after shutdown: %s',
1232 tests_after_shutdown)
Jon Salz0697cbf2012-07-04 15:14:04 +08001233 self.tests_to_run.extend(
1234 self.test_list.lookup_path(t) for t in tests_after_shutdown)
1235 self.run_queue.put(self.run_next_test)
1236 else:
Jon Salz5c344f62012-07-13 14:31:16 +08001237 if force_auto_run or self.test_list.options.auto_run_on_start:
Jon Salz0697cbf2012-07-04 15:14:04 +08001238 self.run_queue.put(
1239 lambda: self.run_tests(self.test_list, untested_only=True))
Jon Salz5c344f62012-07-13 14:31:16 +08001240 self.state_instance.set_shared_data('tests_after_shutdown', None)
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001241
Dean Liao592e4d52013-01-10 20:06:39 +08001242 self.may_disable_cros_shortcut_keys()
1243
1244 def may_disable_cros_shortcut_keys(self):
1245 test_options = self.test_list.options
1246 if test_options.disable_cros_shortcut_keys:
1247 logging.info('Filter ChromeOS shortcut keys.')
1248 self.key_filter = KeyFilter(
1249 unmap_caps_lock=test_options.disable_caps_lock,
1250 caps_lock_keycode=test_options.caps_lock_keycode)
1251 self.key_filter.Start()
1252
Jon Salz0697cbf2012-07-04 15:14:04 +08001253 def run(self):
1254 '''Runs Goofy.'''
1255 # Process events forever.
1256 while self.run_once(True):
1257 pass
Jon Salz73e0fd02012-04-04 11:46:38 +08001258
Jon Salz0697cbf2012-07-04 15:14:04 +08001259 def run_once(self, block=False):
1260 '''Runs all items pending in the event loop.
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001261
Jon Salz0697cbf2012-07-04 15:14:04 +08001262 Args:
1263 block: If true, block until at least one event is processed.
Jon Salz7c15e8b2012-06-19 17:10:37 +08001264
Jon Salz0697cbf2012-07-04 15:14:04 +08001265 Returns:
1266 True to keep going or False to shut down.
1267 '''
1268 events = utils.DrainQueue(self.run_queue)
cychiang21886742012-07-05 15:16:32 +08001269 while not events:
Jon Salz0697cbf2012-07-04 15:14:04 +08001270 # Nothing on the run queue.
1271 self._run_queue_idle()
1272 if block:
1273 # Block for at least one event...
cychiang21886742012-07-05 15:16:32 +08001274 try:
1275 events.append(self.run_queue.get(timeout=RUN_QUEUE_TIMEOUT_SECS))
1276 except Queue.Empty:
1277 # Keep going (calling _run_queue_idle() again at the top of
1278 # the loop)
1279 continue
Jon Salz0697cbf2012-07-04 15:14:04 +08001280 # ...and grab anything else that showed up at the same
1281 # time.
1282 events.extend(utils.DrainQueue(self.run_queue))
cychiang21886742012-07-05 15:16:32 +08001283 else:
1284 break
Jon Salz51528e12012-07-02 18:54:45 +08001285
Jon Salz0697cbf2012-07-04 15:14:04 +08001286 for event in events:
1287 if not event:
1288 # Shutdown request.
1289 self.run_queue.task_done()
1290 return False
Jon Salz51528e12012-07-02 18:54:45 +08001291
Jon Salz0697cbf2012-07-04 15:14:04 +08001292 try:
1293 event()
Jon Salz85a39882012-07-05 16:45:04 +08001294 except: # pylint: disable=W0702
1295 logging.exception('Error in event loop')
Jon Salz0697cbf2012-07-04 15:14:04 +08001296 self.record_exception(traceback.format_exception_only(
1297 *sys.exc_info()[:2]))
1298 # But keep going
1299 finally:
1300 self.run_queue.task_done()
1301 return True
Jon Salz0405ab52012-03-16 15:26:52 +08001302
Jon Salz0e6532d2012-10-25 16:30:11 +08001303 def _should_sync_time(self, foreground=False):
1304 '''Returns True if we should attempt syncing time with shopfloor.
1305
1306 Args:
1307 foreground: If True, synchronizes even if background syncing
1308 is disabled (e.g., in explicit sync requests from the
1309 SyncShopfloor test).
1310 '''
1311 return ((foreground or
1312 self.test_list.options.sync_time_period_secs) and
Jon Salz54882d02012-08-31 01:57:54 +08001313 self.time_sanitizer and
1314 (not self.time_synced) and
1315 (not factory.in_chroot()))
1316
Jon Salz0e6532d2012-10-25 16:30:11 +08001317 def sync_time_with_shopfloor_server(self, foreground=False):
Jon Salz54882d02012-08-31 01:57:54 +08001318 '''Syncs time with shopfloor server, if not yet synced.
1319
Jon Salz0e6532d2012-10-25 16:30:11 +08001320 Args:
1321 foreground: If True, synchronizes even if background syncing
1322 is disabled (e.g., in explicit sync requests from the
1323 SyncShopfloor test).
1324
Jon Salz54882d02012-08-31 01:57:54 +08001325 Returns:
1326 False if no time sanitizer is available, or True if this sync (or a
1327 previous sync) succeeded.
1328
1329 Raises:
1330 Exception if unable to contact the shopfloor server.
1331 '''
Jon Salz0e6532d2012-10-25 16:30:11 +08001332 if self._should_sync_time(foreground):
Jon Salz54882d02012-08-31 01:57:54 +08001333 self.time_sanitizer.SyncWithShopfloor()
1334 self.time_synced = True
1335 return self.time_synced
1336
Jon Salzb92c5112012-09-21 15:40:11 +08001337 def log_disk_space_stats(self):
1338 if not self.test_list.options.log_disk_space_period_secs:
1339 return
1340
1341 now = time.time()
1342 if (self.last_log_disk_space_time and
1343 now - self.last_log_disk_space_time <
1344 self.test_list.options.log_disk_space_period_secs):
1345 return
1346 self.last_log_disk_space_time = now
1347
1348 try:
Jon Salz3c493bb2013-02-07 17:24:58 +08001349 message = disk_space.FormatSpaceUsedAll()
1350 if message != self.last_log_disk_space_message:
1351 logging.info(message)
1352 self.last_log_disk_space_message = message
Jon Salzb92c5112012-09-21 15:40:11 +08001353 except: # pylint: disable=W0702
1354 logging.exception('Unable to get disk space used')
1355
Jon Salz8fa8e832012-07-13 19:04:09 +08001356 def sync_time_in_background(self):
Jon Salzb22d1172012-08-06 10:38:57 +08001357 '''Writes out current time and tries to sync with shopfloor server.'''
1358 if not self.time_sanitizer:
1359 return
1360
1361 # Write out the current time.
1362 self.time_sanitizer.SaveTime()
1363
Jon Salz54882d02012-08-31 01:57:54 +08001364 if not self._should_sync_time():
Jon Salz8fa8e832012-07-13 19:04:09 +08001365 return
1366
1367 now = time.time()
1368 if self.last_sync_time and (
1369 now - self.last_sync_time <
1370 self.test_list.options.sync_time_period_secs):
1371 # Not yet time for another check.
1372 return
1373 self.last_sync_time = now
1374
1375 def target():
1376 try:
Jon Salz54882d02012-08-31 01:57:54 +08001377 self.sync_time_with_shopfloor_server()
Jon Salz8fa8e832012-07-13 19:04:09 +08001378 except: # pylint: disable=W0702
1379 # Oh well. Log an error (but no trace)
1380 logging.info(
1381 'Unable to get time from shopfloor server: %s',
1382 utils.FormatExceptionOnly())
1383
1384 thread = threading.Thread(target=target)
1385 thread.daemon = True
1386 thread.start()
1387
Jon Salz0697cbf2012-07-04 15:14:04 +08001388 def _run_queue_idle(self):
Vic Yang4953fc12012-07-26 16:19:53 +08001389 '''Invoked when the run queue has no events.
1390
1391 This method must not raise exception.
1392 '''
Jon Salzb22d1172012-08-06 10:38:57 +08001393 now = time.time()
1394 if (self.last_idle and
1395 now < (self.last_idle + RUN_QUEUE_TIMEOUT_SECS - 1)):
1396 # Don't run more often than once every (RUN_QUEUE_TIMEOUT_SECS -
1397 # 1) seconds.
1398 return
1399
1400 self.last_idle = now
1401
Vic Yang311ddb82012-09-26 12:08:28 +08001402 self.check_exclusive()
cychiang21886742012-07-05 15:16:32 +08001403 self.check_for_updates()
Jon Salz8fa8e832012-07-13 19:04:09 +08001404 self.sync_time_in_background()
Jon Salzb92c5112012-09-21 15:40:11 +08001405 self.log_disk_space_stats()
Jon Salz57717ca2012-04-04 16:47:25 +08001406
Jon Salz16d10542012-07-23 12:18:45 +08001407 def handle_event_logs(self, log_name, chunk):
Jon Salz0697cbf2012-07-04 15:14:04 +08001408 '''Callback for event watcher.
Jon Salz258a40c2012-04-19 12:34:01 +08001409
Jon Salz0697cbf2012-07-04 15:14:04 +08001410 Attempts to upload the event logs to the shopfloor server.
1411 '''
1412 description = 'event logs (%s, %d bytes)' % (log_name, len(chunk))
1413 start_time = time.time()
Jon Salz0697cbf2012-07-04 15:14:04 +08001414 shopfloor_client = shopfloor.get_instance(
1415 detect=True,
1416 timeout=self.test_list.options.shopfloor_timeout_secs)
Jon Salzb10cf512012-08-09 17:29:21 +08001417 shopfloor_client.UploadEvent(log_name, Binary(chunk))
Jon Salz0697cbf2012-07-04 15:14:04 +08001418 logging.info(
1419 'Successfully synced %s in %.03f s',
1420 description, time.time() - start_time)
Jon Salz57717ca2012-04-04 16:47:25 +08001421
Jon Salz0697cbf2012-07-04 15:14:04 +08001422 def run_tests_with_status(self, statuses_to_run, starting_at=None,
1423 root=None):
1424 '''Runs all top-level tests with a particular status.
Jon Salz0405ab52012-03-16 15:26:52 +08001425
Jon Salz0697cbf2012-07-04 15:14:04 +08001426 All active tests, plus any tests to re-run, are reset.
Jon Salz57717ca2012-04-04 16:47:25 +08001427
Jon Salz0697cbf2012-07-04 15:14:04 +08001428 Args:
1429 starting_at: If provided, only auto-runs tests beginning with
1430 this test.
1431 '''
1432 root = root or self.test_list
Jon Salz57717ca2012-04-04 16:47:25 +08001433
Jon Salz0697cbf2012-07-04 15:14:04 +08001434 if starting_at:
1435 # Make sure they passed a test, not a string.
1436 assert isinstance(starting_at, factory.FactoryTest)
Jon Salz0405ab52012-03-16 15:26:52 +08001437
Jon Salz0697cbf2012-07-04 15:14:04 +08001438 tests_to_reset = []
1439 tests_to_run = []
Jon Salz0405ab52012-03-16 15:26:52 +08001440
Jon Salz0697cbf2012-07-04 15:14:04 +08001441 found_starting_at = False
Jon Salz0405ab52012-03-16 15:26:52 +08001442
Jon Salz0697cbf2012-07-04 15:14:04 +08001443 for test in root.get_top_level_tests():
1444 if starting_at:
1445 if test == starting_at:
1446 # We've found starting_at; do auto-run on all
1447 # subsequent tests.
1448 found_starting_at = True
1449 if not found_starting_at:
1450 # Don't start this guy yet
1451 continue
Jon Salz0405ab52012-03-16 15:26:52 +08001452
Jon Salz0697cbf2012-07-04 15:14:04 +08001453 status = test.get_state().status
1454 if status == TestState.ACTIVE or status in statuses_to_run:
1455 # Reset the test (later; we will need to abort
1456 # all active tests first).
1457 tests_to_reset.append(test)
1458 if status in statuses_to_run:
1459 tests_to_run.append(test)
Jon Salz0405ab52012-03-16 15:26:52 +08001460
Jon Salz0697cbf2012-07-04 15:14:04 +08001461 self.abort_active_tests()
Jon Salz258a40c2012-04-19 12:34:01 +08001462
Jon Salz0697cbf2012-07-04 15:14:04 +08001463 # Reset all statuses of the tests to run (in case any tests were active;
1464 # we want them to be run again).
1465 for test_to_reset in tests_to_reset:
1466 for test in test_to_reset.walk():
1467 test.update_state(status=TestState.UNTESTED)
Jon Salz57717ca2012-04-04 16:47:25 +08001468
Jon Salz0697cbf2012-07-04 15:14:04 +08001469 self.run_tests(tests_to_run, untested_only=True)
Jon Salz0405ab52012-03-16 15:26:52 +08001470
Jon Salz0697cbf2012-07-04 15:14:04 +08001471 def restart_tests(self, root=None):
1472 '''Restarts all tests.'''
1473 root = root or self.test_list
Jon Salz0405ab52012-03-16 15:26:52 +08001474
Jon Salz0697cbf2012-07-04 15:14:04 +08001475 self.abort_active_tests()
1476 for test in root.walk():
1477 test.update_state(status=TestState.UNTESTED)
1478 self.run_tests(root)
Hung-Te Lin96632362012-03-20 21:14:18 +08001479
Jon Salz0697cbf2012-07-04 15:14:04 +08001480 def auto_run(self, starting_at=None, root=None):
1481 '''"Auto-runs" tests that have not been run yet.
Hung-Te Lin96632362012-03-20 21:14:18 +08001482
Jon Salz0697cbf2012-07-04 15:14:04 +08001483 Args:
1484 starting_at: If provide, only auto-runs tests beginning with
1485 this test.
1486 '''
1487 root = root or self.test_list
1488 self.run_tests_with_status([TestState.UNTESTED, TestState.ACTIVE],
1489 starting_at=starting_at,
1490 root=root)
Jon Salz968e90b2012-03-18 16:12:43 +08001491
Jon Salz0697cbf2012-07-04 15:14:04 +08001492 def re_run_failed(self, root=None):
1493 '''Re-runs failed tests.'''
1494 root = root or self.test_list
1495 self.run_tests_with_status([TestState.FAILED], root=root)
Jon Salz57717ca2012-04-04 16:47:25 +08001496
Jon Salz0697cbf2012-07-04 15:14:04 +08001497 def show_review_information(self):
1498 '''Event handler for showing review information screen.
Jon Salz57717ca2012-04-04 16:47:25 +08001499
Jon Salz0697cbf2012-07-04 15:14:04 +08001500 The information screene is rendered by main UI program (ui.py), so in
1501 goofy we only need to kill all active tests, set them as untested, and
1502 clear remaining tests.
1503 '''
1504 self.kill_active_tests(False)
Jon Salza6711d72012-07-18 14:33:03 +08001505 self.cancel_pending_tests()
Jon Salz57717ca2012-04-04 16:47:25 +08001506
Jon Salz0697cbf2012-07-04 15:14:04 +08001507 def handle_switch_test(self, event):
1508 '''Switches to a particular test.
Jon Salz0405ab52012-03-16 15:26:52 +08001509
Jon Salz0697cbf2012-07-04 15:14:04 +08001510 @param event: The SWITCH_TEST event.
1511 '''
1512 test = self.test_list.lookup_path(event.path)
1513 if not test:
1514 logging.error('Unknown test %r', event.key)
1515 return
Jon Salz73e0fd02012-04-04 11:46:38 +08001516
Jon Salz0697cbf2012-07-04 15:14:04 +08001517 invoc = self.invocations.get(test)
1518 if invoc and test.backgroundable:
1519 # Already running: just bring to the front if it
1520 # has a UI.
1521 logging.info('Setting visible test to %s', test.path)
Jon Salz36fbbb52012-07-05 13:45:06 +08001522 self.set_visible_test(test)
Jon Salz0697cbf2012-07-04 15:14:04 +08001523 return
Jon Salz73e0fd02012-04-04 11:46:38 +08001524
Jon Salz0697cbf2012-07-04 15:14:04 +08001525 self.abort_active_tests()
1526 for t in test.walk():
1527 t.update_state(status=TestState.UNTESTED)
Jon Salz73e0fd02012-04-04 11:46:38 +08001528
Jon Salz0697cbf2012-07-04 15:14:04 +08001529 if self.test_list.options.auto_run_on_keypress:
1530 self.auto_run(starting_at=test)
1531 else:
1532 self.run_tests(test)
Jon Salz73e0fd02012-04-04 11:46:38 +08001533
Jon Salz0697cbf2012-07-04 15:14:04 +08001534 def wait(self):
1535 '''Waits for all pending invocations.
1536
1537 Useful for testing.
1538 '''
Jon Salz1acc8742012-07-17 17:45:55 +08001539 while self.invocations:
1540 for k, v in self.invocations.iteritems():
1541 logging.info('Waiting for %s to complete...', k)
1542 v.thread.join()
1543 self.reap_completed_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +08001544
1545 def check_exceptions(self):
1546 '''Raises an error if any exceptions have occurred in
1547 invocation threads.'''
1548 if self.exceptions:
1549 raise RuntimeError('Exception in invocation thread: %r' %
1550 self.exceptions)
1551
1552 def record_exception(self, msg):
1553 '''Records an exception in an invocation thread.
1554
1555 An exception with the given message will be rethrown when
1556 Goofy is destroyed.'''
1557 self.exceptions.append(msg)
Jon Salz73e0fd02012-04-04 11:46:38 +08001558
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001559
1560if __name__ == '__main__':
Jon Salz77c151e2012-08-28 07:20:37 +08001561 goofy = Goofy()
1562 try:
1563 goofy.main()
Jon Salz0f996602012-10-03 15:26:48 +08001564 except SystemExit:
1565 # Propagate SystemExit without logging.
1566 raise
Jon Salz31373eb2012-09-21 16:19:49 +08001567 except:
Jon Salz0f996602012-10-03 15:26:48 +08001568 # Log the error before trying to shut down (unless it's a graceful
1569 # exit).
Jon Salz31373eb2012-09-21 16:19:49 +08001570 logging.exception('Error in main loop')
1571 raise
Jon Salz77c151e2012-08-28 07:20:37 +08001572 finally:
1573 goofy.destroy()