blob: 308a1f952e28ffcd8ef292b1d01dbf50953bd189 [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 Salz0405ab52012-03-16 15:26:52 +080015import sys
Jon Salz0405ab52012-03-16 15:26:52 +080016import threading
17import time
18import traceback
Jon Salz258a40c2012-04-19 12:34:01 +080019import uuid
Hung-Te Linf2f78f72012-02-08 19:27:11 +080020from collections import deque
21from optparse import OptionParser
Hung-Te Linf2f78f72012-02-08 19:27:11 +080022
Jon Salz0697cbf2012-07-04 15:14:04 +080023import factory_common # pylint: disable=W0611
Jon Salz83591782012-06-26 11:09:58 +080024from cros.factory.goofy.prespawner import Prespawner
25from cros.factory.test import factory
26from cros.factory.test import state
27from cros.factory.test.factory import TestState
28from cros.factory.goofy import updater
Jon Salz51528e12012-07-02 18:54:45 +080029from cros.factory.goofy import test_steps
30from cros.factory.goofy.event_log_watcher import EventLogWatcher
31from cros.factory.test import shopfloor
Jon Salz83591782012-06-26 11:09:58 +080032from cros.factory.test import utils
33from cros.factory.test.event import Event
34from cros.factory.test.event import EventClient
35from cros.factory.test.event import EventServer
Jon Salzee85d522012-07-17 14:34:46 +080036from cros.factory import event_log
Jon Salz83591782012-06-26 11:09:58 +080037from cros.factory.event_log import EventLog
38from cros.factory.goofy.invocation import TestInvocation
Jon Salz16d10542012-07-23 12:18:45 +080039from cros.factory.goofy.goofy_rpc import GoofyRPC
Jon Salz83591782012-06-26 11:09:58 +080040from cros.factory.goofy import system
41from cros.factory.goofy import test_environment
Jon Salz8fa8e832012-07-13 19:04:09 +080042from cros.factory.goofy import time_sanitizer
Jon Salz83591782012-06-26 11:09:58 +080043from cros.factory.goofy.web_socket_manager import WebSocketManager
Jon Salz78c32392012-07-25 14:18:29 +080044from cros.factory.utils.process_utils import Spawn
Hung-Te Linf2f78f72012-02-08 19:27:11 +080045
46
Jon Salz2f757d42012-06-27 17:06:42 +080047DEFAULT_TEST_LISTS_DIR = os.path.join(factory.FACTORY_PATH, 'test_lists')
48CUSTOM_DIR = os.path.join(factory.FACTORY_PATH, 'custom')
Hung-Te Linf2f78f72012-02-08 19:27:11 +080049HWID_CFG_PATH = '/usr/local/share/chromeos-hwid/cfg'
50
Jon Salz8796e362012-05-24 11:39:09 +080051# File that suppresses reboot if present (e.g., for development).
52NO_REBOOT_FILE = '/var/log/factory.noreboot'
53
Jon Salz5c344f62012-07-13 14:31:16 +080054# Value for tests_after_shutdown that forces auto-run (e.g., after
55# a factory update, when the available set of tests might change).
56FORCE_AUTO_RUN = 'force_auto_run'
57
cychiang21886742012-07-05 15:16:32 +080058RUN_QUEUE_TIMEOUT_SECS = 10
59
Jon Salz758e6cc2012-04-03 15:47:07 +080060GOOFY_IN_CHROOT_WARNING = '\n' + ('*' * 70) + '''
61You are running Goofy inside the chroot. Autotests are not supported.
62
63To use Goofy in the chroot, first install an Xvnc server:
64
Jon Salz0697cbf2012-07-04 15:14:04 +080065 sudo apt-get install tightvncserver
Jon Salz758e6cc2012-04-03 15:47:07 +080066
67...and then start a VNC X server outside the chroot:
68
Jon Salz0697cbf2012-07-04 15:14:04 +080069 vncserver :10 &
70 vncviewer :10
Jon Salz758e6cc2012-04-03 15:47:07 +080071
72...and run Goofy as follows:
73
Jon Salz0697cbf2012-07-04 15:14:04 +080074 env --unset=XAUTHORITY DISPLAY=localhost:10 python goofy.py
Jon Salz758e6cc2012-04-03 15:47:07 +080075''' + ('*' * 70)
Jon Salz73e0fd02012-04-04 11:46:38 +080076suppress_chroot_warning = False
Hung-Te Linf2f78f72012-02-08 19:27:11 +080077
78def get_hwid_cfg():
Jon Salz0697cbf2012-07-04 15:14:04 +080079 '''
80 Returns the HWID config tag, or an empty string if none can be found.
81 '''
82 if 'CROS_HWID' in os.environ:
83 return os.environ['CROS_HWID']
84 if os.path.exists(HWID_CFG_PATH):
85 with open(HWID_CFG_PATH, 'rt') as hwid_cfg_handle:
86 return hwid_cfg_handle.read().strip()
87 return ''
Hung-Te Linf2f78f72012-02-08 19:27:11 +080088
89
90def find_test_list():
Jon Salz0697cbf2012-07-04 15:14:04 +080091 '''
92 Returns the path to the active test list, based on the HWID config tag.
93 '''
94 hwid_cfg = get_hwid_cfg()
Hung-Te Linf2f78f72012-02-08 19:27:11 +080095
Jon Salz0697cbf2012-07-04 15:14:04 +080096 search_dirs = [CUSTOM_DIR, DEFAULT_TEST_LISTS_DIR]
Jon Salz2f757d42012-06-27 17:06:42 +080097
Jon Salz0697cbf2012-07-04 15:14:04 +080098 # Try in order: test_list_${hwid_cfg}, test_list, test_list.all
99 search_files = ['test_list', 'test_list.all']
100 if hwid_cfg:
101 search_files.insert(0, hwid_cfg)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800102
Jon Salz0697cbf2012-07-04 15:14:04 +0800103 for d in search_dirs:
104 for f in search_files:
105 test_list = os.path.join(d, f)
106 if os.path.exists(test_list):
107 return test_list
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800108
Jon Salz0697cbf2012-07-04 15:14:04 +0800109 logging.warn('Cannot find test lists named any of %s in any of %s',
110 search_files, search_dirs)
111 return None
Jon Salz73e0fd02012-04-04 11:46:38 +0800112
Jon Salz73e0fd02012-04-04 11:46:38 +0800113_inited_logging = False
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800114
115class Goofy(object):
Jon Salz0697cbf2012-07-04 15:14:04 +0800116 '''
117 The main factory flow.
118
119 Note that all methods in this class must be invoked from the main
120 (event) thread. Other threads, such as callbacks and TestInvocation
121 methods, should instead post events on the run queue.
122
123 TODO: Unit tests. (chrome-os-partner:7409)
124
125 Properties:
126 uuid: A unique UUID for this invocation of Goofy.
127 state_instance: An instance of FactoryState.
128 state_server: The FactoryState XML/RPC server.
129 state_server_thread: A thread running state_server.
130 event_server: The EventServer socket server.
131 event_server_thread: A thread running event_server.
132 event_client: A client to the event server.
133 connection_manager: The connection_manager object.
134 network_enabled: Whether the connection_manager is currently
135 enabling connections.
136 ui_process: The factory ui process object.
137 run_queue: A queue of callbacks to invoke from the main thread.
138 invocations: A map from FactoryTest objects to the corresponding
139 TestInvocations objects representing active tests.
140 tests_to_run: A deque of tests that should be run when the current
141 test(s) complete.
142 options: Command-line options.
143 args: Command-line args.
144 test_list: The test list.
145 event_handlers: Map of Event.Type to the method used to handle that
146 event. If the method has an 'event' argument, the event is passed
147 to the handler.
148 exceptions: Exceptions encountered in invocation threads.
149 '''
150 def __init__(self):
151 self.uuid = str(uuid.uuid4())
152 self.state_instance = None
153 self.state_server = None
154 self.state_server_thread = None
Jon Salz16d10542012-07-23 12:18:45 +0800155 self.goofy_rpc = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800156 self.event_server = None
157 self.event_server_thread = None
158 self.event_client = None
159 self.connection_manager = None
Jon Salz8fa8e832012-07-13 19:04:09 +0800160 self.time_sanitizer = None
161 self.time_synced = False
Jon Salz0697cbf2012-07-04 15:14:04 +0800162 self.log_watcher = None
163 self.network_enabled = True
164 self.event_log = None
165 self.prespawner = None
166 self.ui_process = None
167 self.run_queue = Queue.Queue()
168 self.invocations = {}
169 self.tests_to_run = deque()
170 self.visible_test = None
171 self.chrome = None
172
173 self.options = None
174 self.args = None
175 self.test_list = None
176 self.on_ui_startup = []
177 self.env = None
178 self.last_shutdown_time = None
cychiang21886742012-07-05 15:16:32 +0800179 self.last_update_check = None
Jon Salz8fa8e832012-07-13 19:04:09 +0800180 self.last_sync_time = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800181
Jon Salz85a39882012-07-05 16:45:04 +0800182 def test_or_root(event, parent_or_group=True):
183 '''Returns the test affected by a particular event.
184
185 Args:
186 event: The event containing an optional 'path' attribute.
187 parent_on_group: If True, returns the top-level parent for a test (the
188 root node of the tests that need to be run together if the given test
189 path is to be run).
190 '''
Jon Salz0697cbf2012-07-04 15:14:04 +0800191 try:
192 path = event.path
193 except AttributeError:
194 path = None
195
196 if path:
Jon Salz85a39882012-07-05 16:45:04 +0800197 test = self.test_list.lookup_path(path)
198 if parent_or_group:
199 test = test.get_top_level_parent_or_group()
200 return test
Jon Salz0697cbf2012-07-04 15:14:04 +0800201 else:
202 return self.test_list
203
204 self.event_handlers = {
205 Event.Type.SWITCH_TEST: self.handle_switch_test,
206 Event.Type.SHOW_NEXT_ACTIVE_TEST:
207 lambda event: self.show_next_active_test(),
208 Event.Type.RESTART_TESTS:
209 lambda event: self.restart_tests(root=test_or_root(event)),
210 Event.Type.AUTO_RUN:
211 lambda event: self.auto_run(root=test_or_root(event)),
212 Event.Type.RE_RUN_FAILED:
213 lambda event: self.re_run_failed(root=test_or_root(event)),
214 Event.Type.RUN_TESTS_WITH_STATUS:
215 lambda event: self.run_tests_with_status(
216 event.status,
217 root=test_or_root(event)),
218 Event.Type.REVIEW:
219 lambda event: self.show_review_information(),
220 Event.Type.UPDATE_SYSTEM_INFO:
221 lambda event: self.update_system_info(),
222 Event.Type.UPDATE_FACTORY:
223 lambda event: self.update_factory(),
224 Event.Type.STOP:
Jon Salz85a39882012-07-05 16:45:04 +0800225 lambda event: self.stop(root=test_or_root(event, False),
226 fail=getattr(event, 'fail', False)),
Jon Salz36fbbb52012-07-05 13:45:06 +0800227 Event.Type.SET_VISIBLE_TEST:
228 lambda event: self.set_visible_test(
229 self.test_list.lookup_path(event.path)),
Jon Salz0697cbf2012-07-04 15:14:04 +0800230 }
231
232 self.exceptions = []
233 self.web_socket_manager = None
234
235 def destroy(self):
236 if self.chrome:
237 self.chrome.kill()
238 self.chrome = None
239 if self.ui_process:
240 utils.kill_process_tree(self.ui_process, 'ui')
241 self.ui_process = None
242 if self.web_socket_manager:
243 logging.info('Stopping web sockets')
244 self.web_socket_manager.close()
245 self.web_socket_manager = None
246 if self.state_server_thread:
247 logging.info('Stopping state server')
248 self.state_server.shutdown()
249 self.state_server_thread.join()
250 self.state_server.server_close()
251 self.state_server_thread = None
252 if self.state_instance:
253 self.state_instance.close()
254 if self.event_server_thread:
255 logging.info('Stopping event server')
256 self.event_server.shutdown() # pylint: disable=E1101
257 self.event_server_thread.join()
258 self.event_server.server_close()
259 self.event_server_thread = None
260 if self.log_watcher:
261 if self.log_watcher.IsThreadStarted():
262 self.log_watcher.StopWatchThread()
263 self.log_watcher = None
264 if self.prespawner:
265 logging.info('Stopping prespawner')
266 self.prespawner.stop()
267 self.prespawner = None
268 if self.event_client:
269 logging.info('Closing event client')
270 self.event_client.close()
271 self.event_client = None
272 if self.event_log:
273 self.event_log.Close()
274 self.event_log = None
275 self.check_exceptions()
276 logging.info('Done destroying Goofy')
277
278 def start_state_server(self):
279 self.state_instance, self.state_server = (
280 state.create_server(bind_address='0.0.0.0'))
Jon Salz16d10542012-07-23 12:18:45 +0800281 self.goofy_rpc = GoofyRPC(self)
282 self.goofy_rpc.RegisterMethods(self.state_instance)
Jon Salz0697cbf2012-07-04 15:14:04 +0800283 logging.info('Starting state server')
284 self.state_server_thread = threading.Thread(
285 target=self.state_server.serve_forever,
286 name='StateServer')
287 self.state_server_thread.start()
288
289 def start_event_server(self):
290 self.event_server = EventServer()
291 logging.info('Starting factory event server')
292 self.event_server_thread = threading.Thread(
293 target=self.event_server.serve_forever,
294 name='EventServer') # pylint: disable=E1101
295 self.event_server_thread.start()
296
297 self.event_client = EventClient(
298 callback=self.handle_event, event_loop=self.run_queue)
299
300 self.web_socket_manager = WebSocketManager(self.uuid)
301 self.state_server.add_handler("/event",
302 self.web_socket_manager.handle_web_socket)
303
304 def start_ui(self):
305 ui_proc_args = [
306 os.path.join(factory.FACTORY_PACKAGE_PATH, 'test', 'ui.py'),
307 self.options.test_list]
308 if self.options.verbose:
309 ui_proc_args.append('-v')
310 logging.info('Starting ui %s', ui_proc_args)
Jon Salz78c32392012-07-25 14:18:29 +0800311 self.ui_process = Spawn(ui_proc_args)
Jon Salz0697cbf2012-07-04 15:14:04 +0800312 logging.info('Waiting for UI to come up...')
313 self.event_client.wait(
314 lambda event: event.type == Event.Type.UI_READY)
315 logging.info('UI has started')
316
317 def set_visible_test(self, test):
318 if self.visible_test == test:
319 return
320
321 if test:
322 test.update_state(visible=True)
323 if self.visible_test:
324 self.visible_test.update_state(visible=False)
325 self.visible_test = test
326
327 def handle_shutdown_complete(self, test, test_state):
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800328 '''
Jon Salz0697cbf2012-07-04 15:14:04 +0800329 Handles the case where a shutdown was detected during a shutdown step.
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800330
Jon Salz0697cbf2012-07-04 15:14:04 +0800331 @param test: The ShutdownStep.
332 @param test_state: The test state.
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800333 '''
Jon Salz0697cbf2012-07-04 15:14:04 +0800334 test_state = test.update_state(increment_shutdown_count=1)
335 logging.info('Detected shutdown (%d of %d)',
336 test_state.shutdown_count, test.iterations)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800337
Jon Salz0697cbf2012-07-04 15:14:04 +0800338 def log_and_update_state(status, error_msg, **kw):
339 self.event_log.Log('rebooted',
340 status=status, error_msg=error_msg, **kw)
341 test.update_state(status=status, error_msg=error_msg)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800342
Jon Salz0697cbf2012-07-04 15:14:04 +0800343 if not self.last_shutdown_time:
344 log_and_update_state(status=TestState.FAILED,
345 error_msg='Unable to read shutdown_time')
346 return
Jon Salz258a40c2012-04-19 12:34:01 +0800347
Jon Salz0697cbf2012-07-04 15:14:04 +0800348 now = time.time()
349 logging.info('%.03f s passed since reboot',
350 now - self.last_shutdown_time)
Jon Salz258a40c2012-04-19 12:34:01 +0800351
Jon Salz0697cbf2012-07-04 15:14:04 +0800352 if self.last_shutdown_time > now:
353 test.update_state(status=TestState.FAILED,
354 error_msg='Time moved backward during reboot')
355 elif (isinstance(test, factory.RebootStep) and
356 self.test_list.options.max_reboot_time_secs and
357 (now - self.last_shutdown_time >
358 self.test_list.options.max_reboot_time_secs)):
359 # A reboot took too long; fail. (We don't check this for
360 # HaltSteps, because the machine could be halted for a
361 # very long time, and even unplugged with battery backup,
362 # thus hosing the clock.)
363 log_and_update_state(
364 status=TestState.FAILED,
365 error_msg=('More than %d s elapsed during reboot '
366 '(%.03f s, from %s to %s)' % (
367 self.test_list.options.max_reboot_time_secs,
368 now - self.last_shutdown_time,
369 utils.TimeString(self.last_shutdown_time),
370 utils.TimeString(now))),
371 duration=(now-self.last_shutdown_time))
372 elif test_state.shutdown_count == test.iterations:
373 # Good!
374 log_and_update_state(status=TestState.PASSED,
375 duration=(now - self.last_shutdown_time),
376 error_msg='')
377 elif test_state.shutdown_count > test.iterations:
378 # Shut down too many times
379 log_and_update_state(status=TestState.FAILED,
380 error_msg='Too many shutdowns')
381 elif utils.are_shift_keys_depressed():
382 logging.info('Shift keys are depressed; cancelling restarts')
383 # Abort shutdown
384 log_and_update_state(
385 status=TestState.FAILED,
386 error_msg='Shutdown aborted with double shift keys')
Jon Salza6711d72012-07-18 14:33:03 +0800387 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +0800388 else:
389 def handler():
390 if self._prompt_cancel_shutdown(
391 test, test_state.shutdown_count + 1):
Jon Salza6711d72012-07-18 14:33:03 +0800392 factory.console.info('Shutdown aborted by operator')
Jon Salz0697cbf2012-07-04 15:14:04 +0800393 log_and_update_state(
394 status=TestState.FAILED,
395 error_msg='Shutdown aborted by operator')
Jon Salza6711d72012-07-18 14:33:03 +0800396 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +0800397 return
Jon Salz0405ab52012-03-16 15:26:52 +0800398
Jon Salz0697cbf2012-07-04 15:14:04 +0800399 # Time to shutdown again
400 log_and_update_state(
401 status=TestState.ACTIVE,
402 error_msg='',
403 iteration=test_state.shutdown_count)
Jon Salz73e0fd02012-04-04 11:46:38 +0800404
Jon Salz0697cbf2012-07-04 15:14:04 +0800405 self.event_log.Log('shutdown', operation='reboot')
406 self.state_instance.set_shared_data('shutdown_time',
407 time.time())
408 self.env.shutdown('reboot')
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800409
Jon Salz0697cbf2012-07-04 15:14:04 +0800410 self.on_ui_startup.append(handler)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800411
Jon Salz0697cbf2012-07-04 15:14:04 +0800412 def _prompt_cancel_shutdown(self, test, iteration):
413 if self.options.ui != 'chrome':
414 return False
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800415
Jon Salz0697cbf2012-07-04 15:14:04 +0800416 pending_shutdown_data = {
417 'delay_secs': test.delay_secs,
418 'time': time.time() + test.delay_secs,
419 'operation': test.operation,
420 'iteration': iteration,
421 'iterations': test.iterations,
422 }
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800423
Jon Salz0697cbf2012-07-04 15:14:04 +0800424 # Create a new (threaded) event client since we
425 # don't want to use the event loop for this.
426 with EventClient() as event_client:
427 event_client.post_event(Event(Event.Type.PENDING_SHUTDOWN,
428 **pending_shutdown_data))
429 aborted = event_client.wait(
430 lambda event: event.type == Event.Type.CANCEL_SHUTDOWN,
431 timeout=test.delay_secs) is not None
432 if aborted:
433 event_client.post_event(Event(Event.Type.PENDING_SHUTDOWN))
434 return aborted
Jon Salz258a40c2012-04-19 12:34:01 +0800435
Jon Salz0697cbf2012-07-04 15:14:04 +0800436 def init_states(self):
437 '''
438 Initializes all states on startup.
439 '''
440 for test in self.test_list.get_all_tests():
441 # Make sure the state server knows about all the tests,
442 # defaulting to an untested state.
443 test.update_state(update_parent=False, visible=False)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800444
Jon Salz0697cbf2012-07-04 15:14:04 +0800445 var_log_messages = None
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800446
Jon Salz0697cbf2012-07-04 15:14:04 +0800447 # Any 'active' tests should be marked as failed now.
448 for test in self.test_list.walk():
Jon Salza6711d72012-07-18 14:33:03 +0800449 if not test.is_leaf():
450 # Don't bother with parents; they will be updated when their
451 # children are updated.
452 continue
453
Jon Salz0697cbf2012-07-04 15:14:04 +0800454 test_state = test.get_state()
455 if test_state.status != TestState.ACTIVE:
456 continue
457 if isinstance(test, factory.ShutdownStep):
458 # Shutdown while the test was active - that's good.
459 self.handle_shutdown_complete(test, test_state)
460 else:
461 # Unexpected shutdown. Grab /var/log/messages for context.
462 if var_log_messages is None:
463 try:
464 var_log_messages = (
465 utils.var_log_messages_before_reboot())
466 # Write it to the log, to make it easier to
467 # correlate with /var/log/messages.
468 logging.info(
469 'Unexpected shutdown. '
470 'Tail of /var/log/messages before last reboot:\n'
471 '%s', ('\n'.join(
472 ' ' + x for x in var_log_messages)))
473 except: # pylint: disable=W0702
474 logging.exception('Unable to grok /var/log/messages')
475 var_log_messages = []
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800476
Jon Salz0697cbf2012-07-04 15:14:04 +0800477 error_msg = 'Unexpected shutdown while test was running'
478 self.event_log.Log('end_test',
479 path=test.path,
480 status=TestState.FAILED,
481 invocation=test.get_state().invocation,
482 error_msg=error_msg,
483 var_log_messages='\n'.join(var_log_messages))
484 test.update_state(
485 status=TestState.FAILED,
486 error_msg=error_msg)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800487
Jon Salz69806bb2012-07-20 18:05:02 +0800488 factory.console.info('Unexpected shutdown while test %s '
489 'running; cancelling any pending tests',
490 test.path)
491 self.state_instance.set_shared_data('tests_after_shutdown', [])
492
Jon Salz0697cbf2012-07-04 15:14:04 +0800493 def show_next_active_test(self):
494 '''
495 Rotates to the next visible active test.
496 '''
497 self.reap_completed_tests()
498 active_tests = [
499 t for t in self.test_list.walk()
500 if t.is_leaf() and t.get_state().status == TestState.ACTIVE]
501 if not active_tests:
502 return
Jon Salz4f6c7172012-06-11 20:45:36 +0800503
Jon Salz0697cbf2012-07-04 15:14:04 +0800504 try:
505 next_test = active_tests[
506 (active_tests.index(self.visible_test) + 1) % len(active_tests)]
507 except ValueError: # visible_test not present in active_tests
508 next_test = active_tests[0]
Jon Salz4f6c7172012-06-11 20:45:36 +0800509
Jon Salz0697cbf2012-07-04 15:14:04 +0800510 self.set_visible_test(next_test)
Jon Salz4f6c7172012-06-11 20:45:36 +0800511
Jon Salz0697cbf2012-07-04 15:14:04 +0800512 def handle_event(self, event):
513 '''
514 Handles an event from the event server.
515 '''
516 handler = self.event_handlers.get(event.type)
517 if handler:
518 handler(event)
519 else:
520 # We don't register handlers for all event types - just ignore
521 # this event.
522 logging.debug('Unbound event type %s', event.type)
Jon Salz4f6c7172012-06-11 20:45:36 +0800523
Jon Salz0697cbf2012-07-04 15:14:04 +0800524 def run_next_test(self):
525 '''
526 Runs the next eligible test (or tests) in self.tests_to_run.
527 '''
528 self.reap_completed_tests()
529 while self.tests_to_run:
530 logging.debug('Tests to run: %s',
531 [x.path for x in self.tests_to_run])
Jon Salz94eb56f2012-06-12 18:01:12 +0800532
Jon Salz0697cbf2012-07-04 15:14:04 +0800533 test = self.tests_to_run[0]
Jon Salz94eb56f2012-06-12 18:01:12 +0800534
Jon Salz0697cbf2012-07-04 15:14:04 +0800535 if test in self.invocations:
536 logging.info('Next test %s is already running', test.path)
537 self.tests_to_run.popleft()
538 return
Jon Salz94eb56f2012-06-12 18:01:12 +0800539
Jon Salza1412922012-07-23 16:04:17 +0800540 for requirement in test.require_run:
541 for i in requirement.test.walk():
542 if i.get_state().status == TestState.ACTIVE:
Jon Salz304a75d2012-07-06 11:14:15 +0800543 logging.info('Waiting for active test %s to complete '
Jon Salza1412922012-07-23 16:04:17 +0800544 'before running %s', i.path, test.path)
Jon Salz304a75d2012-07-06 11:14:15 +0800545 return
546
Jon Salz0697cbf2012-07-04 15:14:04 +0800547 if self.invocations and not (test.backgroundable and all(
548 [x.backgroundable for x in self.invocations])):
549 logging.debug('Waiting for non-backgroundable tests to '
550 'complete before running %s', test.path)
551 return
Jon Salz94eb56f2012-06-12 18:01:12 +0800552
Jon Salz0697cbf2012-07-04 15:14:04 +0800553 self.tests_to_run.popleft()
Jon Salz94eb56f2012-06-12 18:01:12 +0800554
Jon Salz304a75d2012-07-06 11:14:15 +0800555 untested = set()
Jon Salza1412922012-07-23 16:04:17 +0800556 for requirement in test.require_run:
557 for i in requirement.test.walk():
558 if i == test:
Jon Salz304a75d2012-07-06 11:14:15 +0800559 # We've hit this test itself; stop checking
560 break
Jon Salza1412922012-07-23 16:04:17 +0800561 if ((i.get_state().status == TestState.UNTESTED) or
562 (requirement.passed and i.get_state().status !=
563 TestState.PASSED)):
Jon Salz304a75d2012-07-06 11:14:15 +0800564 # Found an untested test; move on to the next
565 # element in require_run.
Jon Salza1412922012-07-23 16:04:17 +0800566 untested.add(i)
Jon Salz304a75d2012-07-06 11:14:15 +0800567 break
568
569 if untested:
570 untested_paths = ', '.join(sorted([x.path for x in untested]))
571 if self.state_instance.get_shared_data('engineering_mode',
572 optional=True):
573 # In engineering mode, we'll let it go.
574 factory.console.warn('In engineering mode; running '
575 '%s even though required tests '
576 '[%s] have not completed',
577 test.path, untested_paths)
578 else:
579 # Not in engineering mode; mark it failed.
580 error_msg = ('Required tests [%s] have not been run yet'
581 % untested_paths)
582 factory.console.error('Not running %s: %s',
583 test.path, error_msg)
584 test.update_state(status=TestState.FAILED,
585 error_msg=error_msg)
586 continue
587
Jon Salz0697cbf2012-07-04 15:14:04 +0800588 if isinstance(test, factory.ShutdownStep):
589 if os.path.exists(NO_REBOOT_FILE):
590 test.update_state(
591 status=TestState.FAILED, increment_count=1,
592 error_msg=('Skipped shutdown since %s is present' %
Jon Salz304a75d2012-07-06 11:14:15 +0800593 NO_REBOOT_FILE))
Jon Salz0697cbf2012-07-04 15:14:04 +0800594 continue
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800595
Jon Salz0697cbf2012-07-04 15:14:04 +0800596 test.update_state(status=TestState.ACTIVE, increment_count=1,
597 error_msg='', shutdown_count=0)
598 if self._prompt_cancel_shutdown(test, 1):
599 self.event_log.Log('reboot_cancelled')
600 test.update_state(
601 status=TestState.FAILED, increment_count=1,
602 error_msg='Shutdown aborted by operator',
603 shutdown_count=0)
604 return
Jon Salz2f757d42012-06-27 17:06:42 +0800605
Jon Salz0697cbf2012-07-04 15:14:04 +0800606 # Save pending test list in the state server
Jon Salzdbf398f2012-06-14 17:30:01 +0800607 self.state_instance.set_shared_data(
Jon Salz0697cbf2012-07-04 15:14:04 +0800608 'tests_after_shutdown',
609 [t.path for t in self.tests_to_run])
610 # Save shutdown time
611 self.state_instance.set_shared_data('shutdown_time',
612 time.time())
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800613
Jon Salz0697cbf2012-07-04 15:14:04 +0800614 with self.env.lock:
615 self.event_log.Log('shutdown', operation=test.operation)
616 shutdown_result = self.env.shutdown(test.operation)
617 if shutdown_result:
618 # That's all, folks!
619 self.run_queue.put(None)
620 return
621 else:
622 # Just pass (e.g., in the chroot).
623 test.update_state(status=TestState.PASSED)
624 self.state_instance.set_shared_data(
625 'tests_after_shutdown', None)
626 # Send event with no fields to indicate that there is no
627 # longer a pending shutdown.
628 self.event_client.post_event(Event(
629 Event.Type.PENDING_SHUTDOWN))
630 continue
Jon Salz258a40c2012-04-19 12:34:01 +0800631
Jon Salz1acc8742012-07-17 17:45:55 +0800632 self._run_test(test, test.iterations)
633
634 def _run_test(self, test, iterations_left=None):
635 invoc = TestInvocation(self, test, on_completion=self.run_next_test)
636 new_state = test.update_state(
637 status=TestState.ACTIVE, increment_count=1, error_msg='',
638 invocation=invoc.uuid, iterations_left=iterations_left)
639 invoc.count = new_state.count
640
641 self.invocations[test] = invoc
642 if self.visible_test is None and test.has_ui:
643 self.set_visible_test(test)
644 self.check_connection_manager()
645 invoc.start()
Jon Salz5f2a0672012-05-22 17:14:06 +0800646
Jon Salz0697cbf2012-07-04 15:14:04 +0800647 def check_connection_manager(self):
648 exclusive_tests = [
649 test.path
650 for test in self.invocations
651 if test.is_exclusive(
652 factory.FactoryTest.EXCLUSIVE_OPTIONS.NETWORKING)]
653 if exclusive_tests:
654 # Make sure networking is disabled.
655 if self.network_enabled:
656 logging.info('Disabling network, as requested by %s',
657 exclusive_tests)
658 self.connection_manager.DisableNetworking()
659 self.network_enabled = False
660 else:
661 # Make sure networking is enabled.
662 if not self.network_enabled:
663 logging.info('Re-enabling network')
664 self.connection_manager.EnableNetworking()
665 self.network_enabled = True
Jon Salz5da61e62012-05-31 13:06:22 +0800666
cychiang21886742012-07-05 15:16:32 +0800667 def check_for_updates(self):
668 '''
669 Schedules an asynchronous check for updates if necessary.
670 '''
671 if not self.test_list.options.update_period_secs:
672 # Not enabled.
673 return
674
675 now = time.time()
676 if self.last_update_check and (
677 now - self.last_update_check <
678 self.test_list.options.update_period_secs):
679 # Not yet time for another check.
680 return
681
682 self.last_update_check = now
683
684 def handle_check_for_update(reached_shopfloor, md5sum, needs_update):
685 if reached_shopfloor:
686 new_update_md5sum = md5sum if needs_update else None
687 if system.SystemInfo.update_md5sum != new_update_md5sum:
688 logging.info('Received new update MD5SUM: %s', new_update_md5sum)
689 system.SystemInfo.update_md5sum = new_update_md5sum
690 self.run_queue.put(self.update_system_info)
691
692 updater.CheckForUpdateAsync(
693 handle_check_for_update,
694 self.test_list.options.shopfloor_timeout_secs)
695
Jon Salza6711d72012-07-18 14:33:03 +0800696 def cancel_pending_tests(self):
697 '''Cancels any tests in the run queue.'''
698 self.run_tests([])
699
Jon Salz0697cbf2012-07-04 15:14:04 +0800700 def run_tests(self, subtrees, untested_only=False):
701 '''
702 Runs tests under subtree.
Jon Salz258a40c2012-04-19 12:34:01 +0800703
Jon Salz0697cbf2012-07-04 15:14:04 +0800704 The tests are run in order unless one fails (then stops).
705 Backgroundable tests are run simultaneously; when a foreground test is
706 encountered, we wait for all active tests to finish before continuing.
Jon Salzb1b39092012-05-03 02:05:09 +0800707
Jon Salz0697cbf2012-07-04 15:14:04 +0800708 @param subtrees: Node or nodes containing tests to run (may either be
709 a single test or a list). Duplicates will be ignored.
710 '''
711 if type(subtrees) != list:
712 subtrees = [subtrees]
Jon Salz258a40c2012-04-19 12:34:01 +0800713
Jon Salz0697cbf2012-07-04 15:14:04 +0800714 # Nodes we've seen so far, to avoid duplicates.
715 seen = set()
Jon Salz94eb56f2012-06-12 18:01:12 +0800716
Jon Salz0697cbf2012-07-04 15:14:04 +0800717 self.tests_to_run = deque()
718 for subtree in subtrees:
719 for test in subtree.walk():
720 if test in seen:
721 continue
722 seen.add(test)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800723
Jon Salz0697cbf2012-07-04 15:14:04 +0800724 if not test.is_leaf():
725 continue
726 if (untested_only and
727 test.get_state().status != TestState.UNTESTED):
728 continue
729 self.tests_to_run.append(test)
730 self.run_next_test()
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800731
Jon Salz0697cbf2012-07-04 15:14:04 +0800732 def reap_completed_tests(self):
733 '''
734 Removes completed tests from the set of active tests.
735
736 Also updates the visible test if it was reaped.
737 '''
738 for t, v in dict(self.invocations).iteritems():
739 if v.is_completed():
Jon Salz1acc8742012-07-17 17:45:55 +0800740 new_state = t.update_state(**v.update_state_on_completion)
Jon Salz0697cbf2012-07-04 15:14:04 +0800741 del self.invocations[t]
742
Jon Salz1acc8742012-07-17 17:45:55 +0800743 if new_state.iterations_left and new_state.status == TestState.PASSED:
744 # Play it again, Sam!
745 self._run_test(t)
746
Jon Salz0697cbf2012-07-04 15:14:04 +0800747 if (self.visible_test is None or
Jon Salz85a39882012-07-05 16:45:04 +0800748 self.visible_test not in self.invocations):
Jon Salz0697cbf2012-07-04 15:14:04 +0800749 self.set_visible_test(None)
750 # Make the first running test, if any, the visible test
751 for t in self.test_list.walk():
752 if t in self.invocations:
753 self.set_visible_test(t)
754 break
755
Jon Salz85a39882012-07-05 16:45:04 +0800756 def kill_active_tests(self, abort, root=None):
Jon Salz0697cbf2012-07-04 15:14:04 +0800757 '''
758 Kills and waits for all active tests.
759
Jon Salz85a39882012-07-05 16:45:04 +0800760 Args:
761 abort: True to change state of killed tests to FAILED, False for
Jon Salz0697cbf2012-07-04 15:14:04 +0800762 UNTESTED.
Jon Salz85a39882012-07-05 16:45:04 +0800763 root: If set, only kills tests with root as an ancestor.
Jon Salz0697cbf2012-07-04 15:14:04 +0800764 '''
765 self.reap_completed_tests()
766 for test, invoc in self.invocations.items():
Jon Salz85a39882012-07-05 16:45:04 +0800767 if root and not test.has_ancestor(root):
768 continue
769
Jon Salz0697cbf2012-07-04 15:14:04 +0800770 factory.console.info('Killing active test %s...' % test.path)
771 invoc.abort_and_join()
772 factory.console.info('Killed %s' % test.path)
Jon Salz1acc8742012-07-17 17:45:55 +0800773 test.update_state(**invoc.update_state_on_completion)
Jon Salz0697cbf2012-07-04 15:14:04 +0800774 del self.invocations[test]
Jon Salz1acc8742012-07-17 17:45:55 +0800775
Jon Salz0697cbf2012-07-04 15:14:04 +0800776 if not abort:
777 test.update_state(status=TestState.UNTESTED)
778 self.reap_completed_tests()
779
Jon Salz85a39882012-07-05 16:45:04 +0800780 def stop(self, root=None, fail=False):
781 self.kill_active_tests(fail, root)
782 # Remove any tests in the run queue under the root.
783 self.tests_to_run = deque([x for x in self.tests_to_run
784 if root and not x.has_ancestor(root)])
785 self.run_next_test()
Jon Salz0697cbf2012-07-04 15:14:04 +0800786
787 def abort_active_tests(self):
788 self.kill_active_tests(True)
789
790 def main(self):
791 try:
792 self.init()
793 self.event_log.Log('goofy_init',
794 success=True)
795 except:
796 if self.event_log:
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800797 try:
Jon Salz0697cbf2012-07-04 15:14:04 +0800798 self.event_log.Log('goofy_init',
799 success=False,
800 trace=traceback.format_exc())
801 except: # pylint: disable=W0702
802 pass
803 raise
804
805 self.run()
806
807 def update_system_info(self):
808 '''Updates system info.'''
809 system_info = system.SystemInfo()
810 self.state_instance.set_shared_data('system_info', system_info.__dict__)
811 self.event_client.post_event(Event(Event.Type.SYSTEM_INFO,
812 system_info=system_info.__dict__))
813 logging.info('System info: %r', system_info.__dict__)
814
Jon Salz5c344f62012-07-13 14:31:16 +0800815 def update_factory(self, auto_run_on_restart=False):
816 '''Commences updating factory software.'''
Jon Salz0697cbf2012-07-04 15:14:04 +0800817 self.kill_active_tests(False)
Jon Salza6711d72012-07-18 14:33:03 +0800818 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +0800819
Jon Salz5c344f62012-07-13 14:31:16 +0800820 def pre_update_hook():
821 if auto_run_on_restart:
822 self.state_instance.set_shared_data('tests_after_shutdown',
823 FORCE_AUTO_RUN)
824 self.state_instance.close()
825
Jon Salz0697cbf2012-07-04 15:14:04 +0800826 try:
Jon Salz5c344f62012-07-13 14:31:16 +0800827 if updater.TryUpdate(pre_update_hook=pre_update_hook):
Jon Salz0697cbf2012-07-04 15:14:04 +0800828 self.env.shutdown('reboot')
829 except: # pylint: disable=W0702
830 factory.console.exception('Unable to update')
831
832 def init(self, args=None, env=None):
833 '''Initializes Goofy.
834
835 Args:
836 args: A list of command-line arguments. Uses sys.argv if
837 args is None.
838 env: An Environment instance to use (or None to choose
839 FakeChrootEnvironment or DUTEnvironment as appropriate).
840 '''
841 parser = OptionParser()
842 parser.add_option('-v', '--verbose', dest='verbose',
Jon Salz8fa8e832012-07-13 19:04:09 +0800843 action='store_true',
844 help='Enable debug logging')
Jon Salz0697cbf2012-07-04 15:14:04 +0800845 parser.add_option('--print_test_list', dest='print_test_list',
Jon Salz8fa8e832012-07-13 19:04:09 +0800846 metavar='FILE',
847 help='Read and print test list FILE, and exit')
Jon Salz0697cbf2012-07-04 15:14:04 +0800848 parser.add_option('--restart', dest='restart',
Jon Salz8fa8e832012-07-13 19:04:09 +0800849 action='store_true',
850 help='Clear all test state')
Jon Salz0697cbf2012-07-04 15:14:04 +0800851 parser.add_option('--ui', dest='ui', type='choice',
Jon Salz8fa8e832012-07-13 19:04:09 +0800852 choices=['none', 'gtk', 'chrome'],
853 default=('chrome' if utils.in_chroot() else 'gtk'),
854 help='UI to use')
Jon Salz0697cbf2012-07-04 15:14:04 +0800855 parser.add_option('--ui_scale_factor', dest='ui_scale_factor',
Jon Salz8fa8e832012-07-13 19:04:09 +0800856 type='int', default=1,
857 help=('Factor by which to scale UI '
858 '(Chrome UI only)'))
Jon Salz0697cbf2012-07-04 15:14:04 +0800859 parser.add_option('--test_list', dest='test_list',
Jon Salz8fa8e832012-07-13 19:04:09 +0800860 metavar='FILE',
861 help='Use FILE as test list')
Jon Salz0697cbf2012-07-04 15:14:04 +0800862 (self.options, self.args) = parser.parse_args(args)
863
Jon Salz46b89562012-07-05 11:49:22 +0800864 # Make sure factory directories exist.
865 factory.get_log_root()
866 factory.get_state_root()
867 factory.get_test_data_root()
868
Jon Salz0697cbf2012-07-04 15:14:04 +0800869 global _inited_logging # pylint: disable=W0603
870 if not _inited_logging:
871 factory.init_logging('goofy', verbose=self.options.verbose)
872 _inited_logging = True
Jon Salz8fa8e832012-07-13 19:04:09 +0800873
Jon Salzee85d522012-07-17 14:34:46 +0800874 event_log.IncrementBootSequence()
Jon Salz0697cbf2012-07-04 15:14:04 +0800875 self.event_log = EventLog('goofy')
876
877 if (not suppress_chroot_warning and
878 factory.in_chroot() and
879 self.options.ui == 'gtk' and
880 os.environ.get('DISPLAY') in [None, '', ':0', ':0.0']):
881 # That's not going to work! Tell the user how to run
882 # this way.
883 logging.warn(GOOFY_IN_CHROOT_WARNING)
884 time.sleep(1)
885
886 if env:
887 self.env = env
888 elif factory.in_chroot():
889 self.env = test_environment.FakeChrootEnvironment()
890 logging.warn(
891 'Using chroot environment: will not actually run autotests')
892 else:
893 self.env = test_environment.DUTEnvironment()
894 self.env.goofy = self
895
896 if self.options.restart:
897 state.clear_state()
898
899 if self.options.print_test_list:
900 print (factory.read_test_list(
901 self.options.print_test_list,
902 test_classes=dict(test_steps.__dict__)).
903 __repr__(recursive=True))
904 return
905
906 if self.options.ui_scale_factor != 1 and utils.in_qemu():
907 logging.warn(
908 'In QEMU; ignoring ui_scale_factor argument')
909 self.options.ui_scale_factor = 1
910
911 logging.info('Started')
912
913 self.start_state_server()
914 self.state_instance.set_shared_data('hwid_cfg', get_hwid_cfg())
915 self.state_instance.set_shared_data('ui_scale_factor',
916 self.options.ui_scale_factor)
917 self.last_shutdown_time = (
918 self.state_instance.get_shared_data('shutdown_time', optional=True))
919 self.state_instance.del_shared_data('shutdown_time', optional=True)
920
921 if not self.options.test_list:
922 self.options.test_list = find_test_list()
923 if not self.options.test_list:
924 logging.error('No test list. Aborting.')
925 sys.exit(1)
926 logging.info('Using test list %s', self.options.test_list)
927
928 self.test_list = factory.read_test_list(
929 self.options.test_list,
930 self.state_instance,
931 test_classes=dict(test_steps.__dict__))
932 if not self.state_instance.has_shared_data('ui_lang'):
933 self.state_instance.set_shared_data('ui_lang',
934 self.test_list.options.ui_lang)
935 self.state_instance.set_shared_data(
936 'test_list_options',
937 self.test_list.options.__dict__)
938 self.state_instance.test_list = self.test_list
939
Jon Salz8fa8e832012-07-13 19:04:09 +0800940 if self.test_list.options.time_sanitizer:
941 self.time_sanitizer = time_sanitizer.TimeSanitizer(
942 base_time=time_sanitizer.GetBaseTimeFromFile(
943 # lsb-factory is written by the factory install shim during
944 # installation, so it should have a good time obtained from
945 # the mini-Omaha server.
946 '/usr/local/etc/lsb-factory'))
947 self.time_sanitizer.RunOnce()
948
Jon Salz0697cbf2012-07-04 15:14:04 +0800949 self.init_states()
950 self.start_event_server()
951 self.connection_manager = self.env.create_connection_manager(
952 self.test_list.options.wlans)
953 # Note that we create a log watcher even if
954 # sync_event_log_period_secs isn't set (no background
955 # syncing), since we may use it to flush event logs as well.
956 self.log_watcher = EventLogWatcher(
957 self.test_list.options.sync_event_log_period_secs,
Jon Salz16d10542012-07-23 12:18:45 +0800958 handle_event_logs_callback=self.handle_event_logs)
Jon Salz0697cbf2012-07-04 15:14:04 +0800959 if self.test_list.options.sync_event_log_period_secs:
960 self.log_watcher.StartWatchThread()
961
962 self.update_system_info()
963
964 os.environ['CROS_FACTORY'] = '1'
965 os.environ['CROS_DISABLE_SITE_SYSINFO'] = '1'
966
967 # Set CROS_UI since some behaviors in ui.py depend on the
968 # particular UI in use. TODO(jsalz): Remove this (and all
969 # places it is used) when the GTK UI is removed.
970 os.environ['CROS_UI'] = self.options.ui
971
972 if self.options.ui == 'chrome':
973 self.env.launch_chrome()
974 logging.info('Waiting for a web socket connection')
975 self.web_socket_manager.wait()
976
977 # Wait for the test widget size to be set; this is done in
978 # an asynchronous RPC so there is a small chance that the
979 # web socket might be opened first.
980 for _ in range(100): # 10 s
981 try:
982 if self.state_instance.get_shared_data('test_widget_size'):
983 break
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800984 except KeyError:
Jon Salz0697cbf2012-07-04 15:14:04 +0800985 pass # Retry
986 time.sleep(0.1) # 100 ms
987 else:
988 logging.warn('Never received test_widget_size from UI')
989 elif self.options.ui == 'gtk':
990 self.start_ui()
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800991
Jon Salz0697cbf2012-07-04 15:14:04 +0800992 def state_change_callback(test, test_state):
993 self.event_client.post_event(
994 Event(Event.Type.STATE_CHANGE,
995 path=test.path, state=test_state))
996 self.test_list.state_change_callback = state_change_callback
Jon Salz73e0fd02012-04-04 11:46:38 +0800997
Jon Salza6711d72012-07-18 14:33:03 +0800998 for handler in self.on_ui_startup:
999 handler()
1000
1001 self.prespawner = Prespawner()
1002 self.prespawner.start()
1003
Jon Salz0697cbf2012-07-04 15:14:04 +08001004 try:
1005 tests_after_shutdown = self.state_instance.get_shared_data(
1006 'tests_after_shutdown')
1007 except KeyError:
1008 tests_after_shutdown = None
Jon Salz57717ca2012-04-04 16:47:25 +08001009
Jon Salz5c344f62012-07-13 14:31:16 +08001010 force_auto_run = (tests_after_shutdown == FORCE_AUTO_RUN)
1011 if not force_auto_run and tests_after_shutdown is not None:
Jon Salz0697cbf2012-07-04 15:14:04 +08001012 logging.info('Resuming tests after shutdown: %s',
1013 tests_after_shutdown)
Jon Salz0697cbf2012-07-04 15:14:04 +08001014 self.tests_to_run.extend(
1015 self.test_list.lookup_path(t) for t in tests_after_shutdown)
1016 self.run_queue.put(self.run_next_test)
1017 else:
Jon Salz5c344f62012-07-13 14:31:16 +08001018 if force_auto_run or self.test_list.options.auto_run_on_start:
Jon Salz0697cbf2012-07-04 15:14:04 +08001019 self.run_queue.put(
1020 lambda: self.run_tests(self.test_list, untested_only=True))
Jon Salz5c344f62012-07-13 14:31:16 +08001021 self.state_instance.set_shared_data('tests_after_shutdown', None)
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001022
Jon Salz0697cbf2012-07-04 15:14:04 +08001023 def run(self):
1024 '''Runs Goofy.'''
1025 # Process events forever.
1026 while self.run_once(True):
1027 pass
Jon Salz73e0fd02012-04-04 11:46:38 +08001028
Jon Salz0697cbf2012-07-04 15:14:04 +08001029 def run_once(self, block=False):
1030 '''Runs all items pending in the event loop.
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001031
Jon Salz0697cbf2012-07-04 15:14:04 +08001032 Args:
1033 block: If true, block until at least one event is processed.
Jon Salz7c15e8b2012-06-19 17:10:37 +08001034
Jon Salz0697cbf2012-07-04 15:14:04 +08001035 Returns:
1036 True to keep going or False to shut down.
1037 '''
1038 events = utils.DrainQueue(self.run_queue)
cychiang21886742012-07-05 15:16:32 +08001039 while not events:
Jon Salz0697cbf2012-07-04 15:14:04 +08001040 # Nothing on the run queue.
1041 self._run_queue_idle()
1042 if block:
1043 # Block for at least one event...
cychiang21886742012-07-05 15:16:32 +08001044 try:
1045 events.append(self.run_queue.get(timeout=RUN_QUEUE_TIMEOUT_SECS))
1046 except Queue.Empty:
1047 # Keep going (calling _run_queue_idle() again at the top of
1048 # the loop)
1049 continue
Jon Salz0697cbf2012-07-04 15:14:04 +08001050 # ...and grab anything else that showed up at the same
1051 # time.
1052 events.extend(utils.DrainQueue(self.run_queue))
cychiang21886742012-07-05 15:16:32 +08001053 else:
1054 break
Jon Salz51528e12012-07-02 18:54:45 +08001055
Jon Salz0697cbf2012-07-04 15:14:04 +08001056 for event in events:
1057 if not event:
1058 # Shutdown request.
1059 self.run_queue.task_done()
1060 return False
Jon Salz51528e12012-07-02 18:54:45 +08001061
Jon Salz0697cbf2012-07-04 15:14:04 +08001062 try:
1063 event()
Jon Salz85a39882012-07-05 16:45:04 +08001064 except: # pylint: disable=W0702
1065 logging.exception('Error in event loop')
Jon Salz0697cbf2012-07-04 15:14:04 +08001066 self.record_exception(traceback.format_exception_only(
1067 *sys.exc_info()[:2]))
1068 # But keep going
1069 finally:
1070 self.run_queue.task_done()
1071 return True
Jon Salz0405ab52012-03-16 15:26:52 +08001072
Jon Salz8fa8e832012-07-13 19:04:09 +08001073 def sync_time_in_background(self):
1074 '''Attempts to sync time with the shopfloor server.'''
1075 if ((not self.test_list.options.sync_time_period_secs) or
1076 (not self.time_sanitizer) or
1077 self.time_synced or
1078 factory.in_chroot()):
1079 # Not enabled or already succeeded.
1080 return
1081
1082 now = time.time()
1083 if self.last_sync_time and (
1084 now - self.last_sync_time <
1085 self.test_list.options.sync_time_period_secs):
1086 # Not yet time for another check.
1087 return
1088 self.last_sync_time = now
1089
1090 def target():
1091 try:
1092 self.time_sanitizer.SyncWithShopfloor()
1093 self.time_synced = True
1094 except: # pylint: disable=W0702
1095 # Oh well. Log an error (but no trace)
1096 logging.info(
1097 'Unable to get time from shopfloor server: %s',
1098 utils.FormatExceptionOnly())
1099
1100 thread = threading.Thread(target=target)
1101 thread.daemon = True
1102 thread.start()
1103
Jon Salz0697cbf2012-07-04 15:14:04 +08001104 def _run_queue_idle(self):
1105 '''Invoked when the run queue has no events.'''
1106 self.check_connection_manager()
cychiang21886742012-07-05 15:16:32 +08001107 self.check_for_updates()
Jon Salz8fa8e832012-07-13 19:04:09 +08001108 self.sync_time_in_background()
Jon Salz57717ca2012-04-04 16:47:25 +08001109
Jon Salz16d10542012-07-23 12:18:45 +08001110 def handle_event_logs(self, log_name, chunk):
Jon Salz0697cbf2012-07-04 15:14:04 +08001111 '''Callback for event watcher.
Jon Salz258a40c2012-04-19 12:34:01 +08001112
Jon Salz0697cbf2012-07-04 15:14:04 +08001113 Attempts to upload the event logs to the shopfloor server.
1114 '''
1115 description = 'event logs (%s, %d bytes)' % (log_name, len(chunk))
1116 start_time = time.time()
1117 logging.info('Syncing %s', description)
1118 shopfloor_client = shopfloor.get_instance(
1119 detect=True,
1120 timeout=self.test_list.options.shopfloor_timeout_secs)
1121 shopfloor_client.UploadEvent(log_name, chunk)
1122 logging.info(
1123 'Successfully synced %s in %.03f s',
1124 description, time.time() - start_time)
Jon Salz57717ca2012-04-04 16:47:25 +08001125
Jon Salz0697cbf2012-07-04 15:14:04 +08001126 def run_tests_with_status(self, statuses_to_run, starting_at=None,
1127 root=None):
1128 '''Runs all top-level tests with a particular status.
Jon Salz0405ab52012-03-16 15:26:52 +08001129
Jon Salz0697cbf2012-07-04 15:14:04 +08001130 All active tests, plus any tests to re-run, are reset.
Jon Salz57717ca2012-04-04 16:47:25 +08001131
Jon Salz0697cbf2012-07-04 15:14:04 +08001132 Args:
1133 starting_at: If provided, only auto-runs tests beginning with
1134 this test.
1135 '''
1136 root = root or self.test_list
Jon Salz57717ca2012-04-04 16:47:25 +08001137
Jon Salz0697cbf2012-07-04 15:14:04 +08001138 if starting_at:
1139 # Make sure they passed a test, not a string.
1140 assert isinstance(starting_at, factory.FactoryTest)
Jon Salz0405ab52012-03-16 15:26:52 +08001141
Jon Salz0697cbf2012-07-04 15:14:04 +08001142 tests_to_reset = []
1143 tests_to_run = []
Jon Salz0405ab52012-03-16 15:26:52 +08001144
Jon Salz0697cbf2012-07-04 15:14:04 +08001145 found_starting_at = False
Jon Salz0405ab52012-03-16 15:26:52 +08001146
Jon Salz0697cbf2012-07-04 15:14:04 +08001147 for test in root.get_top_level_tests():
1148 if starting_at:
1149 if test == starting_at:
1150 # We've found starting_at; do auto-run on all
1151 # subsequent tests.
1152 found_starting_at = True
1153 if not found_starting_at:
1154 # Don't start this guy yet
1155 continue
Jon Salz0405ab52012-03-16 15:26:52 +08001156
Jon Salz0697cbf2012-07-04 15:14:04 +08001157 status = test.get_state().status
1158 if status == TestState.ACTIVE or status in statuses_to_run:
1159 # Reset the test (later; we will need to abort
1160 # all active tests first).
1161 tests_to_reset.append(test)
1162 if status in statuses_to_run:
1163 tests_to_run.append(test)
Jon Salz0405ab52012-03-16 15:26:52 +08001164
Jon Salz0697cbf2012-07-04 15:14:04 +08001165 self.abort_active_tests()
Jon Salz258a40c2012-04-19 12:34:01 +08001166
Jon Salz0697cbf2012-07-04 15:14:04 +08001167 # Reset all statuses of the tests to run (in case any tests were active;
1168 # we want them to be run again).
1169 for test_to_reset in tests_to_reset:
1170 for test in test_to_reset.walk():
1171 test.update_state(status=TestState.UNTESTED)
Jon Salz57717ca2012-04-04 16:47:25 +08001172
Jon Salz0697cbf2012-07-04 15:14:04 +08001173 self.run_tests(tests_to_run, untested_only=True)
Jon Salz0405ab52012-03-16 15:26:52 +08001174
Jon Salz0697cbf2012-07-04 15:14:04 +08001175 def restart_tests(self, root=None):
1176 '''Restarts all tests.'''
1177 root = root or self.test_list
Jon Salz0405ab52012-03-16 15:26:52 +08001178
Jon Salz0697cbf2012-07-04 15:14:04 +08001179 self.abort_active_tests()
1180 for test in root.walk():
1181 test.update_state(status=TestState.UNTESTED)
1182 self.run_tests(root)
Hung-Te Lin96632362012-03-20 21:14:18 +08001183
Jon Salz0697cbf2012-07-04 15:14:04 +08001184 def auto_run(self, starting_at=None, root=None):
1185 '''"Auto-runs" tests that have not been run yet.
Hung-Te Lin96632362012-03-20 21:14:18 +08001186
Jon Salz0697cbf2012-07-04 15:14:04 +08001187 Args:
1188 starting_at: If provide, only auto-runs tests beginning with
1189 this test.
1190 '''
1191 root = root or self.test_list
1192 self.run_tests_with_status([TestState.UNTESTED, TestState.ACTIVE],
1193 starting_at=starting_at,
1194 root=root)
Jon Salz968e90b2012-03-18 16:12:43 +08001195
Jon Salz0697cbf2012-07-04 15:14:04 +08001196 def re_run_failed(self, root=None):
1197 '''Re-runs failed tests.'''
1198 root = root or self.test_list
1199 self.run_tests_with_status([TestState.FAILED], root=root)
Jon Salz57717ca2012-04-04 16:47:25 +08001200
Jon Salz0697cbf2012-07-04 15:14:04 +08001201 def show_review_information(self):
1202 '''Event handler for showing review information screen.
Jon Salz57717ca2012-04-04 16:47:25 +08001203
Jon Salz0697cbf2012-07-04 15:14:04 +08001204 The information screene is rendered by main UI program (ui.py), so in
1205 goofy we only need to kill all active tests, set them as untested, and
1206 clear remaining tests.
1207 '''
1208 self.kill_active_tests(False)
Jon Salza6711d72012-07-18 14:33:03 +08001209 self.cancel_pending_tests()
Jon Salz57717ca2012-04-04 16:47:25 +08001210
Jon Salz0697cbf2012-07-04 15:14:04 +08001211 def handle_switch_test(self, event):
1212 '''Switches to a particular test.
Jon Salz0405ab52012-03-16 15:26:52 +08001213
Jon Salz0697cbf2012-07-04 15:14:04 +08001214 @param event: The SWITCH_TEST event.
1215 '''
1216 test = self.test_list.lookup_path(event.path)
1217 if not test:
1218 logging.error('Unknown test %r', event.key)
1219 return
Jon Salz73e0fd02012-04-04 11:46:38 +08001220
Jon Salz0697cbf2012-07-04 15:14:04 +08001221 invoc = self.invocations.get(test)
1222 if invoc and test.backgroundable:
1223 # Already running: just bring to the front if it
1224 # has a UI.
1225 logging.info('Setting visible test to %s', test.path)
Jon Salz36fbbb52012-07-05 13:45:06 +08001226 self.set_visible_test(test)
Jon Salz0697cbf2012-07-04 15:14:04 +08001227 return
Jon Salz73e0fd02012-04-04 11:46:38 +08001228
Jon Salz0697cbf2012-07-04 15:14:04 +08001229 self.abort_active_tests()
1230 for t in test.walk():
1231 t.update_state(status=TestState.UNTESTED)
Jon Salz73e0fd02012-04-04 11:46:38 +08001232
Jon Salz0697cbf2012-07-04 15:14:04 +08001233 if self.test_list.options.auto_run_on_keypress:
1234 self.auto_run(starting_at=test)
1235 else:
1236 self.run_tests(test)
Jon Salz73e0fd02012-04-04 11:46:38 +08001237
Jon Salz0697cbf2012-07-04 15:14:04 +08001238 def wait(self):
1239 '''Waits for all pending invocations.
1240
1241 Useful for testing.
1242 '''
Jon Salz1acc8742012-07-17 17:45:55 +08001243 while self.invocations:
1244 for k, v in self.invocations.iteritems():
1245 logging.info('Waiting for %s to complete...', k)
1246 v.thread.join()
1247 self.reap_completed_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +08001248
1249 def check_exceptions(self):
1250 '''Raises an error if any exceptions have occurred in
1251 invocation threads.'''
1252 if self.exceptions:
1253 raise RuntimeError('Exception in invocation thread: %r' %
1254 self.exceptions)
1255
1256 def record_exception(self, msg):
1257 '''Records an exception in an invocation thread.
1258
1259 An exception with the given message will be rethrown when
1260 Goofy is destroyed.'''
1261 self.exceptions.append(msg)
Jon Salz73e0fd02012-04-04 11:46:38 +08001262
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001263
1264if __name__ == '__main__':
Jon Salz0697cbf2012-07-04 15:14:04 +08001265 Goofy().main()