blob: 57260c083d419a4799ab535d90c732b81064a3a8 [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 subprocess
16import sys
Jon Salz0405ab52012-03-16 15:26:52 +080017import threading
18import time
19import traceback
Jon Salz258a40c2012-04-19 12:34:01 +080020import uuid
Hung-Te Linf2f78f72012-02-08 19:27:11 +080021from collections import deque
22from optparse import OptionParser
Hung-Te Linf2f78f72012-02-08 19:27:11 +080023
Jon Salz0697cbf2012-07-04 15:14:04 +080024import factory_common # pylint: disable=W0611
Jon Salz83591782012-06-26 11:09:58 +080025from cros.factory.goofy.prespawner import Prespawner
26from cros.factory.test import factory
27from cros.factory.test import state
28from cros.factory.test.factory import TestState
29from cros.factory.goofy import updater
Jon Salz51528e12012-07-02 18:54:45 +080030from cros.factory.goofy import test_steps
31from cros.factory.goofy.event_log_watcher import EventLogWatcher
32from cros.factory.test import shopfloor
Jon Salz83591782012-06-26 11:09:58 +080033from cros.factory.test import utils
34from cros.factory.test.event import Event
35from cros.factory.test.event import EventClient
36from cros.factory.test.event import EventServer
Jon Salzee85d522012-07-17 14:34:46 +080037from cros.factory import event_log
Jon Salz83591782012-06-26 11:09:58 +080038from cros.factory.event_log import EventLog
39from cros.factory.goofy.invocation import TestInvocation
Jon Salz16d10542012-07-23 12:18:45 +080040from cros.factory.goofy.goofy_rpc import GoofyRPC
Jon Salz83591782012-06-26 11:09:58 +080041from cros.factory.goofy import system
42from cros.factory.goofy import test_environment
Jon Salz8fa8e832012-07-13 19:04:09 +080043from cros.factory.goofy import time_sanitizer
Jon Salz83591782012-06-26 11:09:58 +080044from cros.factory.goofy.web_socket_manager import WebSocketManager
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)
311 self.ui_process = subprocess.Popen(ui_proc_args)
312 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 Salz304a75d2012-07-06 11:14:15 +0800540 for i in test.require_run:
541 for j in i.walk():
542 if j.get_state().status == TestState.ACTIVE:
543 logging.info('Waiting for active test %s to complete '
544 'before running %s', j.path, test.path)
545 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()
556 for i in test.require_run:
557 for j in i.walk():
558 if j == test:
559 # We've hit this test itself; stop checking
560 break
561 if j.get_state().status == TestState.UNTESTED:
562 # Found an untested test; move on to the next
563 # element in require_run.
564 untested.add(j)
565 break
566
567 if untested:
568 untested_paths = ', '.join(sorted([x.path for x in untested]))
569 if self.state_instance.get_shared_data('engineering_mode',
570 optional=True):
571 # In engineering mode, we'll let it go.
572 factory.console.warn('In engineering mode; running '
573 '%s even though required tests '
574 '[%s] have not completed',
575 test.path, untested_paths)
576 else:
577 # Not in engineering mode; mark it failed.
578 error_msg = ('Required tests [%s] have not been run yet'
579 % untested_paths)
580 factory.console.error('Not running %s: %s',
581 test.path, error_msg)
582 test.update_state(status=TestState.FAILED,
583 error_msg=error_msg)
584 continue
585
Jon Salz0697cbf2012-07-04 15:14:04 +0800586 if isinstance(test, factory.ShutdownStep):
587 if os.path.exists(NO_REBOOT_FILE):
588 test.update_state(
589 status=TestState.FAILED, increment_count=1,
590 error_msg=('Skipped shutdown since %s is present' %
Jon Salz304a75d2012-07-06 11:14:15 +0800591 NO_REBOOT_FILE))
Jon Salz0697cbf2012-07-04 15:14:04 +0800592 continue
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800593
Jon Salz0697cbf2012-07-04 15:14:04 +0800594 test.update_state(status=TestState.ACTIVE, increment_count=1,
595 error_msg='', shutdown_count=0)
596 if self._prompt_cancel_shutdown(test, 1):
597 self.event_log.Log('reboot_cancelled')
598 test.update_state(
599 status=TestState.FAILED, increment_count=1,
600 error_msg='Shutdown aborted by operator',
601 shutdown_count=0)
602 return
Jon Salz2f757d42012-06-27 17:06:42 +0800603
Jon Salz0697cbf2012-07-04 15:14:04 +0800604 # Save pending test list in the state server
Jon Salzdbf398f2012-06-14 17:30:01 +0800605 self.state_instance.set_shared_data(
Jon Salz0697cbf2012-07-04 15:14:04 +0800606 'tests_after_shutdown',
607 [t.path for t in self.tests_to_run])
608 # Save shutdown time
609 self.state_instance.set_shared_data('shutdown_time',
610 time.time())
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800611
Jon Salz0697cbf2012-07-04 15:14:04 +0800612 with self.env.lock:
613 self.event_log.Log('shutdown', operation=test.operation)
614 shutdown_result = self.env.shutdown(test.operation)
615 if shutdown_result:
616 # That's all, folks!
617 self.run_queue.put(None)
618 return
619 else:
620 # Just pass (e.g., in the chroot).
621 test.update_state(status=TestState.PASSED)
622 self.state_instance.set_shared_data(
623 'tests_after_shutdown', None)
624 # Send event with no fields to indicate that there is no
625 # longer a pending shutdown.
626 self.event_client.post_event(Event(
627 Event.Type.PENDING_SHUTDOWN))
628 continue
Jon Salz258a40c2012-04-19 12:34:01 +0800629
Jon Salz1acc8742012-07-17 17:45:55 +0800630 self._run_test(test, test.iterations)
631
632 def _run_test(self, test, iterations_left=None):
633 invoc = TestInvocation(self, test, on_completion=self.run_next_test)
634 new_state = test.update_state(
635 status=TestState.ACTIVE, increment_count=1, error_msg='',
636 invocation=invoc.uuid, iterations_left=iterations_left)
637 invoc.count = new_state.count
638
639 self.invocations[test] = invoc
640 if self.visible_test is None and test.has_ui:
641 self.set_visible_test(test)
642 self.check_connection_manager()
643 invoc.start()
Jon Salz5f2a0672012-05-22 17:14:06 +0800644
Jon Salz0697cbf2012-07-04 15:14:04 +0800645 def check_connection_manager(self):
646 exclusive_tests = [
647 test.path
648 for test in self.invocations
649 if test.is_exclusive(
650 factory.FactoryTest.EXCLUSIVE_OPTIONS.NETWORKING)]
651 if exclusive_tests:
652 # Make sure networking is disabled.
653 if self.network_enabled:
654 logging.info('Disabling network, as requested by %s',
655 exclusive_tests)
656 self.connection_manager.DisableNetworking()
657 self.network_enabled = False
658 else:
659 # Make sure networking is enabled.
660 if not self.network_enabled:
661 logging.info('Re-enabling network')
662 self.connection_manager.EnableNetworking()
663 self.network_enabled = True
Jon Salz5da61e62012-05-31 13:06:22 +0800664
cychiang21886742012-07-05 15:16:32 +0800665 def check_for_updates(self):
666 '''
667 Schedules an asynchronous check for updates if necessary.
668 '''
669 if not self.test_list.options.update_period_secs:
670 # Not enabled.
671 return
672
673 now = time.time()
674 if self.last_update_check and (
675 now - self.last_update_check <
676 self.test_list.options.update_period_secs):
677 # Not yet time for another check.
678 return
679
680 self.last_update_check = now
681
682 def handle_check_for_update(reached_shopfloor, md5sum, needs_update):
683 if reached_shopfloor:
684 new_update_md5sum = md5sum if needs_update else None
685 if system.SystemInfo.update_md5sum != new_update_md5sum:
686 logging.info('Received new update MD5SUM: %s', new_update_md5sum)
687 system.SystemInfo.update_md5sum = new_update_md5sum
688 self.run_queue.put(self.update_system_info)
689
690 updater.CheckForUpdateAsync(
691 handle_check_for_update,
692 self.test_list.options.shopfloor_timeout_secs)
693
Jon Salza6711d72012-07-18 14:33:03 +0800694 def cancel_pending_tests(self):
695 '''Cancels any tests in the run queue.'''
696 self.run_tests([])
697
Jon Salz0697cbf2012-07-04 15:14:04 +0800698 def run_tests(self, subtrees, untested_only=False):
699 '''
700 Runs tests under subtree.
Jon Salz258a40c2012-04-19 12:34:01 +0800701
Jon Salz0697cbf2012-07-04 15:14:04 +0800702 The tests are run in order unless one fails (then stops).
703 Backgroundable tests are run simultaneously; when a foreground test is
704 encountered, we wait for all active tests to finish before continuing.
Jon Salzb1b39092012-05-03 02:05:09 +0800705
Jon Salz0697cbf2012-07-04 15:14:04 +0800706 @param subtrees: Node or nodes containing tests to run (may either be
707 a single test or a list). Duplicates will be ignored.
708 '''
709 if type(subtrees) != list:
710 subtrees = [subtrees]
Jon Salz258a40c2012-04-19 12:34:01 +0800711
Jon Salz0697cbf2012-07-04 15:14:04 +0800712 # Nodes we've seen so far, to avoid duplicates.
713 seen = set()
Jon Salz94eb56f2012-06-12 18:01:12 +0800714
Jon Salz0697cbf2012-07-04 15:14:04 +0800715 self.tests_to_run = deque()
716 for subtree in subtrees:
717 for test in subtree.walk():
718 if test in seen:
719 continue
720 seen.add(test)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800721
Jon Salz0697cbf2012-07-04 15:14:04 +0800722 if not test.is_leaf():
723 continue
724 if (untested_only and
725 test.get_state().status != TestState.UNTESTED):
726 continue
727 self.tests_to_run.append(test)
728 self.run_next_test()
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800729
Jon Salz0697cbf2012-07-04 15:14:04 +0800730 def reap_completed_tests(self):
731 '''
732 Removes completed tests from the set of active tests.
733
734 Also updates the visible test if it was reaped.
735 '''
736 for t, v in dict(self.invocations).iteritems():
737 if v.is_completed():
Jon Salz1acc8742012-07-17 17:45:55 +0800738 new_state = t.update_state(**v.update_state_on_completion)
Jon Salz0697cbf2012-07-04 15:14:04 +0800739 del self.invocations[t]
740
Jon Salz1acc8742012-07-17 17:45:55 +0800741 if new_state.iterations_left and new_state.status == TestState.PASSED:
742 # Play it again, Sam!
743 self._run_test(t)
744
Jon Salz0697cbf2012-07-04 15:14:04 +0800745 if (self.visible_test is None or
Jon Salz85a39882012-07-05 16:45:04 +0800746 self.visible_test not in self.invocations):
Jon Salz0697cbf2012-07-04 15:14:04 +0800747 self.set_visible_test(None)
748 # Make the first running test, if any, the visible test
749 for t in self.test_list.walk():
750 if t in self.invocations:
751 self.set_visible_test(t)
752 break
753
Jon Salz85a39882012-07-05 16:45:04 +0800754 def kill_active_tests(self, abort, root=None):
Jon Salz0697cbf2012-07-04 15:14:04 +0800755 '''
756 Kills and waits for all active tests.
757
Jon Salz85a39882012-07-05 16:45:04 +0800758 Args:
759 abort: True to change state of killed tests to FAILED, False for
Jon Salz0697cbf2012-07-04 15:14:04 +0800760 UNTESTED.
Jon Salz85a39882012-07-05 16:45:04 +0800761 root: If set, only kills tests with root as an ancestor.
Jon Salz0697cbf2012-07-04 15:14:04 +0800762 '''
763 self.reap_completed_tests()
764 for test, invoc in self.invocations.items():
Jon Salz85a39882012-07-05 16:45:04 +0800765 if root and not test.has_ancestor(root):
766 continue
767
Jon Salz0697cbf2012-07-04 15:14:04 +0800768 factory.console.info('Killing active test %s...' % test.path)
769 invoc.abort_and_join()
770 factory.console.info('Killed %s' % test.path)
Jon Salz1acc8742012-07-17 17:45:55 +0800771 test.update_state(**invoc.update_state_on_completion)
Jon Salz0697cbf2012-07-04 15:14:04 +0800772 del self.invocations[test]
Jon Salz1acc8742012-07-17 17:45:55 +0800773
Jon Salz0697cbf2012-07-04 15:14:04 +0800774 if not abort:
775 test.update_state(status=TestState.UNTESTED)
776 self.reap_completed_tests()
777
Jon Salz85a39882012-07-05 16:45:04 +0800778 def stop(self, root=None, fail=False):
779 self.kill_active_tests(fail, root)
780 # Remove any tests in the run queue under the root.
781 self.tests_to_run = deque([x for x in self.tests_to_run
782 if root and not x.has_ancestor(root)])
783 self.run_next_test()
Jon Salz0697cbf2012-07-04 15:14:04 +0800784
785 def abort_active_tests(self):
786 self.kill_active_tests(True)
787
788 def main(self):
789 try:
790 self.init()
791 self.event_log.Log('goofy_init',
792 success=True)
793 except:
794 if self.event_log:
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800795 try:
Jon Salz0697cbf2012-07-04 15:14:04 +0800796 self.event_log.Log('goofy_init',
797 success=False,
798 trace=traceback.format_exc())
799 except: # pylint: disable=W0702
800 pass
801 raise
802
803 self.run()
804
805 def update_system_info(self):
806 '''Updates system info.'''
807 system_info = system.SystemInfo()
808 self.state_instance.set_shared_data('system_info', system_info.__dict__)
809 self.event_client.post_event(Event(Event.Type.SYSTEM_INFO,
810 system_info=system_info.__dict__))
811 logging.info('System info: %r', system_info.__dict__)
812
Jon Salz5c344f62012-07-13 14:31:16 +0800813 def update_factory(self, auto_run_on_restart=False):
814 '''Commences updating factory software.'''
Jon Salz0697cbf2012-07-04 15:14:04 +0800815 self.kill_active_tests(False)
Jon Salza6711d72012-07-18 14:33:03 +0800816 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +0800817
Jon Salz5c344f62012-07-13 14:31:16 +0800818 def pre_update_hook():
819 if auto_run_on_restart:
820 self.state_instance.set_shared_data('tests_after_shutdown',
821 FORCE_AUTO_RUN)
822 self.state_instance.close()
823
Jon Salz0697cbf2012-07-04 15:14:04 +0800824 try:
Jon Salz5c344f62012-07-13 14:31:16 +0800825 if updater.TryUpdate(pre_update_hook=pre_update_hook):
Jon Salz0697cbf2012-07-04 15:14:04 +0800826 self.env.shutdown('reboot')
827 except: # pylint: disable=W0702
828 factory.console.exception('Unable to update')
829
830 def init(self, args=None, env=None):
831 '''Initializes Goofy.
832
833 Args:
834 args: A list of command-line arguments. Uses sys.argv if
835 args is None.
836 env: An Environment instance to use (or None to choose
837 FakeChrootEnvironment or DUTEnvironment as appropriate).
838 '''
839 parser = OptionParser()
840 parser.add_option('-v', '--verbose', dest='verbose',
Jon Salz8fa8e832012-07-13 19:04:09 +0800841 action='store_true',
842 help='Enable debug logging')
Jon Salz0697cbf2012-07-04 15:14:04 +0800843 parser.add_option('--print_test_list', dest='print_test_list',
Jon Salz8fa8e832012-07-13 19:04:09 +0800844 metavar='FILE',
845 help='Read and print test list FILE, and exit')
Jon Salz0697cbf2012-07-04 15:14:04 +0800846 parser.add_option('--restart', dest='restart',
Jon Salz8fa8e832012-07-13 19:04:09 +0800847 action='store_true',
848 help='Clear all test state')
Jon Salz0697cbf2012-07-04 15:14:04 +0800849 parser.add_option('--ui', dest='ui', type='choice',
Jon Salz8fa8e832012-07-13 19:04:09 +0800850 choices=['none', 'gtk', 'chrome'],
851 default=('chrome' if utils.in_chroot() else 'gtk'),
852 help='UI to use')
Jon Salz0697cbf2012-07-04 15:14:04 +0800853 parser.add_option('--ui_scale_factor', dest='ui_scale_factor',
Jon Salz8fa8e832012-07-13 19:04:09 +0800854 type='int', default=1,
855 help=('Factor by which to scale UI '
856 '(Chrome UI only)'))
Jon Salz0697cbf2012-07-04 15:14:04 +0800857 parser.add_option('--test_list', dest='test_list',
Jon Salz8fa8e832012-07-13 19:04:09 +0800858 metavar='FILE',
859 help='Use FILE as test list')
Jon Salz0697cbf2012-07-04 15:14:04 +0800860 (self.options, self.args) = parser.parse_args(args)
861
Jon Salz46b89562012-07-05 11:49:22 +0800862 # Make sure factory directories exist.
863 factory.get_log_root()
864 factory.get_state_root()
865 factory.get_test_data_root()
866
Jon Salz0697cbf2012-07-04 15:14:04 +0800867 global _inited_logging # pylint: disable=W0603
868 if not _inited_logging:
869 factory.init_logging('goofy', verbose=self.options.verbose)
870 _inited_logging = True
Jon Salz8fa8e832012-07-13 19:04:09 +0800871
Jon Salzee85d522012-07-17 14:34:46 +0800872 event_log.IncrementBootSequence()
Jon Salz0697cbf2012-07-04 15:14:04 +0800873 self.event_log = EventLog('goofy')
874
875 if (not suppress_chroot_warning and
876 factory.in_chroot() and
877 self.options.ui == 'gtk' and
878 os.environ.get('DISPLAY') in [None, '', ':0', ':0.0']):
879 # That's not going to work! Tell the user how to run
880 # this way.
881 logging.warn(GOOFY_IN_CHROOT_WARNING)
882 time.sleep(1)
883
884 if env:
885 self.env = env
886 elif factory.in_chroot():
887 self.env = test_environment.FakeChrootEnvironment()
888 logging.warn(
889 'Using chroot environment: will not actually run autotests')
890 else:
891 self.env = test_environment.DUTEnvironment()
892 self.env.goofy = self
893
894 if self.options.restart:
895 state.clear_state()
896
897 if self.options.print_test_list:
898 print (factory.read_test_list(
899 self.options.print_test_list,
900 test_classes=dict(test_steps.__dict__)).
901 __repr__(recursive=True))
902 return
903
904 if self.options.ui_scale_factor != 1 and utils.in_qemu():
905 logging.warn(
906 'In QEMU; ignoring ui_scale_factor argument')
907 self.options.ui_scale_factor = 1
908
909 logging.info('Started')
910
911 self.start_state_server()
912 self.state_instance.set_shared_data('hwid_cfg', get_hwid_cfg())
913 self.state_instance.set_shared_data('ui_scale_factor',
914 self.options.ui_scale_factor)
915 self.last_shutdown_time = (
916 self.state_instance.get_shared_data('shutdown_time', optional=True))
917 self.state_instance.del_shared_data('shutdown_time', optional=True)
918
919 if not self.options.test_list:
920 self.options.test_list = find_test_list()
921 if not self.options.test_list:
922 logging.error('No test list. Aborting.')
923 sys.exit(1)
924 logging.info('Using test list %s', self.options.test_list)
925
926 self.test_list = factory.read_test_list(
927 self.options.test_list,
928 self.state_instance,
929 test_classes=dict(test_steps.__dict__))
930 if not self.state_instance.has_shared_data('ui_lang'):
931 self.state_instance.set_shared_data('ui_lang',
932 self.test_list.options.ui_lang)
933 self.state_instance.set_shared_data(
934 'test_list_options',
935 self.test_list.options.__dict__)
936 self.state_instance.test_list = self.test_list
937
Jon Salz8fa8e832012-07-13 19:04:09 +0800938 if self.test_list.options.time_sanitizer:
939 self.time_sanitizer = time_sanitizer.TimeSanitizer(
940 base_time=time_sanitizer.GetBaseTimeFromFile(
941 # lsb-factory is written by the factory install shim during
942 # installation, so it should have a good time obtained from
943 # the mini-Omaha server.
944 '/usr/local/etc/lsb-factory'))
945 self.time_sanitizer.RunOnce()
946
Jon Salz0697cbf2012-07-04 15:14:04 +0800947 self.init_states()
948 self.start_event_server()
949 self.connection_manager = self.env.create_connection_manager(
950 self.test_list.options.wlans)
951 # Note that we create a log watcher even if
952 # sync_event_log_period_secs isn't set (no background
953 # syncing), since we may use it to flush event logs as well.
954 self.log_watcher = EventLogWatcher(
955 self.test_list.options.sync_event_log_period_secs,
Jon Salz16d10542012-07-23 12:18:45 +0800956 handle_event_logs_callback=self.handle_event_logs)
Jon Salz0697cbf2012-07-04 15:14:04 +0800957 if self.test_list.options.sync_event_log_period_secs:
958 self.log_watcher.StartWatchThread()
959
960 self.update_system_info()
961
962 os.environ['CROS_FACTORY'] = '1'
963 os.environ['CROS_DISABLE_SITE_SYSINFO'] = '1'
964
965 # Set CROS_UI since some behaviors in ui.py depend on the
966 # particular UI in use. TODO(jsalz): Remove this (and all
967 # places it is used) when the GTK UI is removed.
968 os.environ['CROS_UI'] = self.options.ui
969
970 if self.options.ui == 'chrome':
971 self.env.launch_chrome()
972 logging.info('Waiting for a web socket connection')
973 self.web_socket_manager.wait()
974
975 # Wait for the test widget size to be set; this is done in
976 # an asynchronous RPC so there is a small chance that the
977 # web socket might be opened first.
978 for _ in range(100): # 10 s
979 try:
980 if self.state_instance.get_shared_data('test_widget_size'):
981 break
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800982 except KeyError:
Jon Salz0697cbf2012-07-04 15:14:04 +0800983 pass # Retry
984 time.sleep(0.1) # 100 ms
985 else:
986 logging.warn('Never received test_widget_size from UI')
987 elif self.options.ui == 'gtk':
988 self.start_ui()
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800989
Jon Salz0697cbf2012-07-04 15:14:04 +0800990 def state_change_callback(test, test_state):
991 self.event_client.post_event(
992 Event(Event.Type.STATE_CHANGE,
993 path=test.path, state=test_state))
994 self.test_list.state_change_callback = state_change_callback
Jon Salz73e0fd02012-04-04 11:46:38 +0800995
Jon Salza6711d72012-07-18 14:33:03 +0800996 for handler in self.on_ui_startup:
997 handler()
998
999 self.prespawner = Prespawner()
1000 self.prespawner.start()
1001
Jon Salz0697cbf2012-07-04 15:14:04 +08001002 try:
1003 tests_after_shutdown = self.state_instance.get_shared_data(
1004 'tests_after_shutdown')
1005 except KeyError:
1006 tests_after_shutdown = None
Jon Salz57717ca2012-04-04 16:47:25 +08001007
Jon Salz5c344f62012-07-13 14:31:16 +08001008 force_auto_run = (tests_after_shutdown == FORCE_AUTO_RUN)
1009 if not force_auto_run and tests_after_shutdown is not None:
Jon Salz0697cbf2012-07-04 15:14:04 +08001010 logging.info('Resuming tests after shutdown: %s',
1011 tests_after_shutdown)
Jon Salz0697cbf2012-07-04 15:14:04 +08001012 self.tests_to_run.extend(
1013 self.test_list.lookup_path(t) for t in tests_after_shutdown)
1014 self.run_queue.put(self.run_next_test)
1015 else:
Jon Salz5c344f62012-07-13 14:31:16 +08001016 if force_auto_run or self.test_list.options.auto_run_on_start:
Jon Salz0697cbf2012-07-04 15:14:04 +08001017 self.run_queue.put(
1018 lambda: self.run_tests(self.test_list, untested_only=True))
Jon Salz5c344f62012-07-13 14:31:16 +08001019 self.state_instance.set_shared_data('tests_after_shutdown', None)
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001020
Jon Salz0697cbf2012-07-04 15:14:04 +08001021 def run(self):
1022 '''Runs Goofy.'''
1023 # Process events forever.
1024 while self.run_once(True):
1025 pass
Jon Salz73e0fd02012-04-04 11:46:38 +08001026
Jon Salz0697cbf2012-07-04 15:14:04 +08001027 def run_once(self, block=False):
1028 '''Runs all items pending in the event loop.
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001029
Jon Salz0697cbf2012-07-04 15:14:04 +08001030 Args:
1031 block: If true, block until at least one event is processed.
Jon Salz7c15e8b2012-06-19 17:10:37 +08001032
Jon Salz0697cbf2012-07-04 15:14:04 +08001033 Returns:
1034 True to keep going or False to shut down.
1035 '''
1036 events = utils.DrainQueue(self.run_queue)
cychiang21886742012-07-05 15:16:32 +08001037 while not events:
Jon Salz0697cbf2012-07-04 15:14:04 +08001038 # Nothing on the run queue.
1039 self._run_queue_idle()
1040 if block:
1041 # Block for at least one event...
cychiang21886742012-07-05 15:16:32 +08001042 try:
1043 events.append(self.run_queue.get(timeout=RUN_QUEUE_TIMEOUT_SECS))
1044 except Queue.Empty:
1045 # Keep going (calling _run_queue_idle() again at the top of
1046 # the loop)
1047 continue
Jon Salz0697cbf2012-07-04 15:14:04 +08001048 # ...and grab anything else that showed up at the same
1049 # time.
1050 events.extend(utils.DrainQueue(self.run_queue))
cychiang21886742012-07-05 15:16:32 +08001051 else:
1052 break
Jon Salz51528e12012-07-02 18:54:45 +08001053
Jon Salz0697cbf2012-07-04 15:14:04 +08001054 for event in events:
1055 if not event:
1056 # Shutdown request.
1057 self.run_queue.task_done()
1058 return False
Jon Salz51528e12012-07-02 18:54:45 +08001059
Jon Salz0697cbf2012-07-04 15:14:04 +08001060 try:
1061 event()
Jon Salz85a39882012-07-05 16:45:04 +08001062 except: # pylint: disable=W0702
1063 logging.exception('Error in event loop')
Jon Salz0697cbf2012-07-04 15:14:04 +08001064 self.record_exception(traceback.format_exception_only(
1065 *sys.exc_info()[:2]))
1066 # But keep going
1067 finally:
1068 self.run_queue.task_done()
1069 return True
Jon Salz0405ab52012-03-16 15:26:52 +08001070
Jon Salz8fa8e832012-07-13 19:04:09 +08001071 def sync_time_in_background(self):
1072 '''Attempts to sync time with the shopfloor server.'''
1073 if ((not self.test_list.options.sync_time_period_secs) or
1074 (not self.time_sanitizer) or
1075 self.time_synced or
1076 factory.in_chroot()):
1077 # Not enabled or already succeeded.
1078 return
1079
1080 now = time.time()
1081 if self.last_sync_time and (
1082 now - self.last_sync_time <
1083 self.test_list.options.sync_time_period_secs):
1084 # Not yet time for another check.
1085 return
1086 self.last_sync_time = now
1087
1088 def target():
1089 try:
1090 self.time_sanitizer.SyncWithShopfloor()
1091 self.time_synced = True
1092 except: # pylint: disable=W0702
1093 # Oh well. Log an error (but no trace)
1094 logging.info(
1095 'Unable to get time from shopfloor server: %s',
1096 utils.FormatExceptionOnly())
1097
1098 thread = threading.Thread(target=target)
1099 thread.daemon = True
1100 thread.start()
1101
Jon Salz0697cbf2012-07-04 15:14:04 +08001102 def _run_queue_idle(self):
1103 '''Invoked when the run queue has no events.'''
1104 self.check_connection_manager()
cychiang21886742012-07-05 15:16:32 +08001105 self.check_for_updates()
Jon Salz8fa8e832012-07-13 19:04:09 +08001106 self.sync_time_in_background()
Jon Salz57717ca2012-04-04 16:47:25 +08001107
Jon Salz16d10542012-07-23 12:18:45 +08001108 def handle_event_logs(self, log_name, chunk):
Jon Salz0697cbf2012-07-04 15:14:04 +08001109 '''Callback for event watcher.
Jon Salz258a40c2012-04-19 12:34:01 +08001110
Jon Salz0697cbf2012-07-04 15:14:04 +08001111 Attempts to upload the event logs to the shopfloor server.
1112 '''
1113 description = 'event logs (%s, %d bytes)' % (log_name, len(chunk))
1114 start_time = time.time()
1115 logging.info('Syncing %s', description)
1116 shopfloor_client = shopfloor.get_instance(
1117 detect=True,
1118 timeout=self.test_list.options.shopfloor_timeout_secs)
1119 shopfloor_client.UploadEvent(log_name, chunk)
1120 logging.info(
1121 'Successfully synced %s in %.03f s',
1122 description, time.time() - start_time)
Jon Salz57717ca2012-04-04 16:47:25 +08001123
Jon Salz0697cbf2012-07-04 15:14:04 +08001124 def run_tests_with_status(self, statuses_to_run, starting_at=None,
1125 root=None):
1126 '''Runs all top-level tests with a particular status.
Jon Salz0405ab52012-03-16 15:26:52 +08001127
Jon Salz0697cbf2012-07-04 15:14:04 +08001128 All active tests, plus any tests to re-run, are reset.
Jon Salz57717ca2012-04-04 16:47:25 +08001129
Jon Salz0697cbf2012-07-04 15:14:04 +08001130 Args:
1131 starting_at: If provided, only auto-runs tests beginning with
1132 this test.
1133 '''
1134 root = root or self.test_list
Jon Salz57717ca2012-04-04 16:47:25 +08001135
Jon Salz0697cbf2012-07-04 15:14:04 +08001136 if starting_at:
1137 # Make sure they passed a test, not a string.
1138 assert isinstance(starting_at, factory.FactoryTest)
Jon Salz0405ab52012-03-16 15:26:52 +08001139
Jon Salz0697cbf2012-07-04 15:14:04 +08001140 tests_to_reset = []
1141 tests_to_run = []
Jon Salz0405ab52012-03-16 15:26:52 +08001142
Jon Salz0697cbf2012-07-04 15:14:04 +08001143 found_starting_at = False
Jon Salz0405ab52012-03-16 15:26:52 +08001144
Jon Salz0697cbf2012-07-04 15:14:04 +08001145 for test in root.get_top_level_tests():
1146 if starting_at:
1147 if test == starting_at:
1148 # We've found starting_at; do auto-run on all
1149 # subsequent tests.
1150 found_starting_at = True
1151 if not found_starting_at:
1152 # Don't start this guy yet
1153 continue
Jon Salz0405ab52012-03-16 15:26:52 +08001154
Jon Salz0697cbf2012-07-04 15:14:04 +08001155 status = test.get_state().status
1156 if status == TestState.ACTIVE or status in statuses_to_run:
1157 # Reset the test (later; we will need to abort
1158 # all active tests first).
1159 tests_to_reset.append(test)
1160 if status in statuses_to_run:
1161 tests_to_run.append(test)
Jon Salz0405ab52012-03-16 15:26:52 +08001162
Jon Salz0697cbf2012-07-04 15:14:04 +08001163 self.abort_active_tests()
Jon Salz258a40c2012-04-19 12:34:01 +08001164
Jon Salz0697cbf2012-07-04 15:14:04 +08001165 # Reset all statuses of the tests to run (in case any tests were active;
1166 # we want them to be run again).
1167 for test_to_reset in tests_to_reset:
1168 for test in test_to_reset.walk():
1169 test.update_state(status=TestState.UNTESTED)
Jon Salz57717ca2012-04-04 16:47:25 +08001170
Jon Salz0697cbf2012-07-04 15:14:04 +08001171 self.run_tests(tests_to_run, untested_only=True)
Jon Salz0405ab52012-03-16 15:26:52 +08001172
Jon Salz0697cbf2012-07-04 15:14:04 +08001173 def restart_tests(self, root=None):
1174 '''Restarts all tests.'''
1175 root = root or self.test_list
Jon Salz0405ab52012-03-16 15:26:52 +08001176
Jon Salz0697cbf2012-07-04 15:14:04 +08001177 self.abort_active_tests()
1178 for test in root.walk():
1179 test.update_state(status=TestState.UNTESTED)
1180 self.run_tests(root)
Hung-Te Lin96632362012-03-20 21:14:18 +08001181
Jon Salz0697cbf2012-07-04 15:14:04 +08001182 def auto_run(self, starting_at=None, root=None):
1183 '''"Auto-runs" tests that have not been run yet.
Hung-Te Lin96632362012-03-20 21:14:18 +08001184
Jon Salz0697cbf2012-07-04 15:14:04 +08001185 Args:
1186 starting_at: If provide, only auto-runs tests beginning with
1187 this test.
1188 '''
1189 root = root or self.test_list
1190 self.run_tests_with_status([TestState.UNTESTED, TestState.ACTIVE],
1191 starting_at=starting_at,
1192 root=root)
Jon Salz968e90b2012-03-18 16:12:43 +08001193
Jon Salz0697cbf2012-07-04 15:14:04 +08001194 def re_run_failed(self, root=None):
1195 '''Re-runs failed tests.'''
1196 root = root or self.test_list
1197 self.run_tests_with_status([TestState.FAILED], root=root)
Jon Salz57717ca2012-04-04 16:47:25 +08001198
Jon Salz0697cbf2012-07-04 15:14:04 +08001199 def show_review_information(self):
1200 '''Event handler for showing review information screen.
Jon Salz57717ca2012-04-04 16:47:25 +08001201
Jon Salz0697cbf2012-07-04 15:14:04 +08001202 The information screene is rendered by main UI program (ui.py), so in
1203 goofy we only need to kill all active tests, set them as untested, and
1204 clear remaining tests.
1205 '''
1206 self.kill_active_tests(False)
Jon Salza6711d72012-07-18 14:33:03 +08001207 self.cancel_pending_tests()
Jon Salz57717ca2012-04-04 16:47:25 +08001208
Jon Salz0697cbf2012-07-04 15:14:04 +08001209 def handle_switch_test(self, event):
1210 '''Switches to a particular test.
Jon Salz0405ab52012-03-16 15:26:52 +08001211
Jon Salz0697cbf2012-07-04 15:14:04 +08001212 @param event: The SWITCH_TEST event.
1213 '''
1214 test = self.test_list.lookup_path(event.path)
1215 if not test:
1216 logging.error('Unknown test %r', event.key)
1217 return
Jon Salz73e0fd02012-04-04 11:46:38 +08001218
Jon Salz0697cbf2012-07-04 15:14:04 +08001219 invoc = self.invocations.get(test)
1220 if invoc and test.backgroundable:
1221 # Already running: just bring to the front if it
1222 # has a UI.
1223 logging.info('Setting visible test to %s', test.path)
Jon Salz36fbbb52012-07-05 13:45:06 +08001224 self.set_visible_test(test)
Jon Salz0697cbf2012-07-04 15:14:04 +08001225 return
Jon Salz73e0fd02012-04-04 11:46:38 +08001226
Jon Salz0697cbf2012-07-04 15:14:04 +08001227 self.abort_active_tests()
1228 for t in test.walk():
1229 t.update_state(status=TestState.UNTESTED)
Jon Salz73e0fd02012-04-04 11:46:38 +08001230
Jon Salz0697cbf2012-07-04 15:14:04 +08001231 if self.test_list.options.auto_run_on_keypress:
1232 self.auto_run(starting_at=test)
1233 else:
1234 self.run_tests(test)
Jon Salz73e0fd02012-04-04 11:46:38 +08001235
Jon Salz0697cbf2012-07-04 15:14:04 +08001236 def wait(self):
1237 '''Waits for all pending invocations.
1238
1239 Useful for testing.
1240 '''
Jon Salz1acc8742012-07-17 17:45:55 +08001241 while self.invocations:
1242 for k, v in self.invocations.iteritems():
1243 logging.info('Waiting for %s to complete...', k)
1244 v.thread.join()
1245 self.reap_completed_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +08001246
1247 def check_exceptions(self):
1248 '''Raises an error if any exceptions have occurred in
1249 invocation threads.'''
1250 if self.exceptions:
1251 raise RuntimeError('Exception in invocation thread: %r' %
1252 self.exceptions)
1253
1254 def record_exception(self, msg):
1255 '''Records an exception in an invocation thread.
1256
1257 An exception with the given message will be rethrown when
1258 Goofy is destroyed.'''
1259 self.exceptions.append(msg)
Jon Salz73e0fd02012-04-04 11:46:38 +08001260
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001261
1262if __name__ == '__main__':
Jon Salz0697cbf2012-07-04 15:14:04 +08001263 Goofy().main()