blob: 354d4f4b0b8462238a1df51a2b46a46f16a59571 [file] [log] [blame]
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001#!/usr/bin/python -u
Hung-Te Linf2f78f72012-02-08 19:27:11 +08002# -*- coding: utf-8 -*-
3#
Jon Salz37eccbd2012-05-25 16:06:52 +08004# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
Hung-Te Linf2f78f72012-02-08 19:27:11 +08005# Use of this source code is governed by a BSD-style license that can be
6# found in the LICENSE file.
7
8'''
9The main factory flow that runs the factory test and finalizes a device.
10'''
11
Jon Salz0405ab52012-03-16 15:26:52 +080012import logging
13import os
Jon Salz73e0fd02012-04-04 11:46:38 +080014import Queue
Jon Salz77c151e2012-08-28 07:20:37 +080015import signal
Jon Salz0405ab52012-03-16 15:26:52 +080016import sys
Jon Salz0405ab52012-03-16 15:26:52 +080017import threading
18import time
19import traceback
Jon Salz258a40c2012-04-19 12:34:01 +080020import uuid
Jon Salzb10cf512012-08-09 17:29:21 +080021from xmlrpclib import Binary
Hung-Te Linf2f78f72012-02-08 19:27:11 +080022from collections import deque
23from optparse import OptionParser
Hung-Te Linf2f78f72012-02-08 19:27:11 +080024
Jon Salz0697cbf2012-07-04 15:14:04 +080025import factory_common # pylint: disable=W0611
jcliangcd688182012-08-20 21:01:26 +080026from cros.factory import event_log
27from cros.factory import system
28from cros.factory.event_log import EventLog
29from cros.factory.goofy import test_environment
30from cros.factory.goofy import time_sanitizer
Jon Salz83591782012-06-26 11:09:58 +080031from cros.factory.goofy import updater
Jon Salz51528e12012-07-02 18:54:45 +080032from cros.factory.goofy.event_log_watcher import EventLogWatcher
jcliangcd688182012-08-20 21:01:26 +080033from cros.factory.goofy.goofy_rpc import GoofyRPC
34from cros.factory.goofy.invocation import TestInvocation
35from cros.factory.goofy.prespawner import Prespawner
36from cros.factory.goofy.web_socket_manager import WebSocketManager
37from cros.factory.system.charge_manager import ChargeManager
38from cros.factory.test import factory
39from cros.factory.test import state
Jon Salz51528e12012-07-02 18:54:45 +080040from cros.factory.test import shopfloor
Jon Salz83591782012-06-26 11:09:58 +080041from cros.factory.test import utils
42from cros.factory.test.event import Event
43from cros.factory.test.event import EventClient
44from cros.factory.test.event import EventServer
jcliangcd688182012-08-20 21:01:26 +080045from cros.factory.test.factory import TestState
Jon Salz78c32392012-07-25 14:18:29 +080046from cros.factory.utils.process_utils import Spawn
Hung-Te Linf2f78f72012-02-08 19:27:11 +080047
48
Jon Salz2f757d42012-06-27 17:06:42 +080049DEFAULT_TEST_LISTS_DIR = os.path.join(factory.FACTORY_PATH, 'test_lists')
50CUSTOM_DIR = os.path.join(factory.FACTORY_PATH, 'custom')
Hung-Te Linf2f78f72012-02-08 19:27:11 +080051HWID_CFG_PATH = '/usr/local/share/chromeos-hwid/cfg'
52
Jon Salz8796e362012-05-24 11:39:09 +080053# File that suppresses reboot if present (e.g., for development).
54NO_REBOOT_FILE = '/var/log/factory.noreboot'
55
Jon Salz5c344f62012-07-13 14:31:16 +080056# Value for tests_after_shutdown that forces auto-run (e.g., after
57# a factory update, when the available set of tests might change).
58FORCE_AUTO_RUN = 'force_auto_run'
59
cychiang21886742012-07-05 15:16:32 +080060RUN_QUEUE_TIMEOUT_SECS = 10
61
Jon Salz758e6cc2012-04-03 15:47:07 +080062GOOFY_IN_CHROOT_WARNING = '\n' + ('*' * 70) + '''
63You are running Goofy inside the chroot. Autotests are not supported.
64
65To use Goofy in the chroot, first install an Xvnc server:
66
Jon Salz0697cbf2012-07-04 15:14:04 +080067 sudo apt-get install tightvncserver
Jon Salz758e6cc2012-04-03 15:47:07 +080068
69...and then start a VNC X server outside the chroot:
70
Jon Salz0697cbf2012-07-04 15:14:04 +080071 vncserver :10 &
72 vncviewer :10
Jon Salz758e6cc2012-04-03 15:47:07 +080073
74...and run Goofy as follows:
75
Jon Salz0697cbf2012-07-04 15:14:04 +080076 env --unset=XAUTHORITY DISPLAY=localhost:10 python goofy.py
Jon Salz758e6cc2012-04-03 15:47:07 +080077''' + ('*' * 70)
Jon Salz73e0fd02012-04-04 11:46:38 +080078suppress_chroot_warning = False
Hung-Te Linf2f78f72012-02-08 19:27:11 +080079
80def get_hwid_cfg():
Jon Salz0697cbf2012-07-04 15:14:04 +080081 '''
82 Returns the HWID config tag, or an empty string if none can be found.
83 '''
84 if 'CROS_HWID' in os.environ:
85 return os.environ['CROS_HWID']
86 if os.path.exists(HWID_CFG_PATH):
87 with open(HWID_CFG_PATH, 'rt') as hwid_cfg_handle:
88 return hwid_cfg_handle.read().strip()
89 return ''
Hung-Te Linf2f78f72012-02-08 19:27:11 +080090
91
92def find_test_list():
Jon Salz0697cbf2012-07-04 15:14:04 +080093 '''
94 Returns the path to the active test list, based on the HWID config tag.
95 '''
96 hwid_cfg = get_hwid_cfg()
Hung-Te Linf2f78f72012-02-08 19:27:11 +080097
Jon Salz0697cbf2012-07-04 15:14:04 +080098 search_dirs = [CUSTOM_DIR, DEFAULT_TEST_LISTS_DIR]
Jon Salz2f757d42012-06-27 17:06:42 +080099
Jon Salz0697cbf2012-07-04 15:14:04 +0800100 # Try in order: test_list_${hwid_cfg}, test_list, test_list.all
101 search_files = ['test_list', 'test_list.all']
102 if hwid_cfg:
103 search_files.insert(0, hwid_cfg)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800104
Jon Salz0697cbf2012-07-04 15:14:04 +0800105 for d in search_dirs:
106 for f in search_files:
107 test_list = os.path.join(d, f)
108 if os.path.exists(test_list):
109 return test_list
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800110
Jon Salz0697cbf2012-07-04 15:14:04 +0800111 logging.warn('Cannot find test lists named any of %s in any of %s',
112 search_files, search_dirs)
113 return None
Jon Salz73e0fd02012-04-04 11:46:38 +0800114
Jon Salz73e0fd02012-04-04 11:46:38 +0800115_inited_logging = False
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800116
117class Goofy(object):
Jon Salz0697cbf2012-07-04 15:14:04 +0800118 '''
119 The main factory flow.
120
121 Note that all methods in this class must be invoked from the main
122 (event) thread. Other threads, such as callbacks and TestInvocation
123 methods, should instead post events on the run queue.
124
125 TODO: Unit tests. (chrome-os-partner:7409)
126
127 Properties:
128 uuid: A unique UUID for this invocation of Goofy.
129 state_instance: An instance of FactoryState.
130 state_server: The FactoryState XML/RPC server.
131 state_server_thread: A thread running state_server.
132 event_server: The EventServer socket server.
133 event_server_thread: A thread running event_server.
134 event_client: A client to the event server.
135 connection_manager: The connection_manager object.
136 network_enabled: Whether the connection_manager is currently
137 enabling connections.
138 ui_process: The factory ui process object.
139 run_queue: A queue of callbacks to invoke from the main thread.
140 invocations: A map from FactoryTest objects to the corresponding
141 TestInvocations objects representing active tests.
142 tests_to_run: A deque of tests that should be run when the current
143 test(s) complete.
144 options: Command-line options.
145 args: Command-line args.
146 test_list: The test list.
147 event_handlers: Map of Event.Type to the method used to handle that
148 event. If the method has an 'event' argument, the event is passed
149 to the handler.
150 exceptions: Exceptions encountered in invocation threads.
151 '''
152 def __init__(self):
153 self.uuid = str(uuid.uuid4())
154 self.state_instance = None
155 self.state_server = None
156 self.state_server_thread = None
Jon Salz16d10542012-07-23 12:18:45 +0800157 self.goofy_rpc = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800158 self.event_server = None
159 self.event_server_thread = None
160 self.event_client = None
161 self.connection_manager = None
Vic Yang4953fc12012-07-26 16:19:53 +0800162 self.charge_manager = None
Jon Salz8fa8e832012-07-13 19:04:09 +0800163 self.time_sanitizer = None
164 self.time_synced = False
Jon Salz0697cbf2012-07-04 15:14:04 +0800165 self.log_watcher = None
166 self.network_enabled = True
167 self.event_log = None
168 self.prespawner = None
169 self.ui_process = None
Jon Salzc79a9982012-08-30 04:42:01 +0800170 self.dummy_shopfloor = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800171 self.run_queue = Queue.Queue()
172 self.invocations = {}
173 self.tests_to_run = deque()
174 self.visible_test = None
175 self.chrome = None
176
177 self.options = None
178 self.args = None
179 self.test_list = None
180 self.on_ui_startup = []
181 self.env = None
Jon Salzb22d1172012-08-06 10:38:57 +0800182 self.last_idle = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800183 self.last_shutdown_time = None
cychiang21886742012-07-05 15:16:32 +0800184 self.last_update_check = None
Jon Salz8fa8e832012-07-13 19:04:09 +0800185 self.last_sync_time = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800186
Jon Salz85a39882012-07-05 16:45:04 +0800187 def test_or_root(event, parent_or_group=True):
188 '''Returns the test affected by a particular event.
189
190 Args:
191 event: The event containing an optional 'path' attribute.
192 parent_on_group: If True, returns the top-level parent for a test (the
193 root node of the tests that need to be run together if the given test
194 path is to be run).
195 '''
Jon Salz0697cbf2012-07-04 15:14:04 +0800196 try:
197 path = event.path
198 except AttributeError:
199 path = None
200
201 if path:
Jon Salz85a39882012-07-05 16:45:04 +0800202 test = self.test_list.lookup_path(path)
203 if parent_or_group:
204 test = test.get_top_level_parent_or_group()
205 return test
Jon Salz0697cbf2012-07-04 15:14:04 +0800206 else:
207 return self.test_list
208
209 self.event_handlers = {
210 Event.Type.SWITCH_TEST: self.handle_switch_test,
211 Event.Type.SHOW_NEXT_ACTIVE_TEST:
212 lambda event: self.show_next_active_test(),
213 Event.Type.RESTART_TESTS:
214 lambda event: self.restart_tests(root=test_or_root(event)),
215 Event.Type.AUTO_RUN:
216 lambda event: self.auto_run(root=test_or_root(event)),
217 Event.Type.RE_RUN_FAILED:
218 lambda event: self.re_run_failed(root=test_or_root(event)),
219 Event.Type.RUN_TESTS_WITH_STATUS:
220 lambda event: self.run_tests_with_status(
221 event.status,
222 root=test_or_root(event)),
223 Event.Type.REVIEW:
224 lambda event: self.show_review_information(),
225 Event.Type.UPDATE_SYSTEM_INFO:
226 lambda event: self.update_system_info(),
Jon Salz0697cbf2012-07-04 15:14:04 +0800227 Event.Type.STOP:
Jon Salz85a39882012-07-05 16:45:04 +0800228 lambda event: self.stop(root=test_or_root(event, False),
229 fail=getattr(event, 'fail', False)),
Jon Salz36fbbb52012-07-05 13:45:06 +0800230 Event.Type.SET_VISIBLE_TEST:
231 lambda event: self.set_visible_test(
232 self.test_list.lookup_path(event.path)),
Jon Salz0697cbf2012-07-04 15:14:04 +0800233 }
234
235 self.exceptions = []
236 self.web_socket_manager = None
237
238 def destroy(self):
239 if self.chrome:
240 self.chrome.kill()
241 self.chrome = None
Jon Salzc79a9982012-08-30 04:42:01 +0800242 if self.dummy_shopfloor:
243 self.dummy_shopfloor.kill()
244 self.dummy_shopfloor = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800245 if self.ui_process:
246 utils.kill_process_tree(self.ui_process, 'ui')
247 self.ui_process = None
248 if self.web_socket_manager:
249 logging.info('Stopping web sockets')
250 self.web_socket_manager.close()
251 self.web_socket_manager = None
252 if self.state_server_thread:
253 logging.info('Stopping state server')
254 self.state_server.shutdown()
255 self.state_server_thread.join()
256 self.state_server.server_close()
257 self.state_server_thread = None
258 if self.state_instance:
259 self.state_instance.close()
260 if self.event_server_thread:
261 logging.info('Stopping event server')
262 self.event_server.shutdown() # pylint: disable=E1101
263 self.event_server_thread.join()
264 self.event_server.server_close()
265 self.event_server_thread = None
266 if self.log_watcher:
267 if self.log_watcher.IsThreadStarted():
268 self.log_watcher.StopWatchThread()
269 self.log_watcher = None
270 if self.prespawner:
271 logging.info('Stopping prespawner')
272 self.prespawner.stop()
273 self.prespawner = None
274 if self.event_client:
275 logging.info('Closing event client')
276 self.event_client.close()
277 self.event_client = None
278 if self.event_log:
279 self.event_log.Close()
280 self.event_log = None
281 self.check_exceptions()
282 logging.info('Done destroying Goofy')
283
284 def start_state_server(self):
285 self.state_instance, self.state_server = (
286 state.create_server(bind_address='0.0.0.0'))
Jon Salz16d10542012-07-23 12:18:45 +0800287 self.goofy_rpc = GoofyRPC(self)
288 self.goofy_rpc.RegisterMethods(self.state_instance)
Jon Salz0697cbf2012-07-04 15:14:04 +0800289 logging.info('Starting state server')
290 self.state_server_thread = threading.Thread(
291 target=self.state_server.serve_forever,
292 name='StateServer')
293 self.state_server_thread.start()
294
295 def start_event_server(self):
296 self.event_server = EventServer()
297 logging.info('Starting factory event server')
298 self.event_server_thread = threading.Thread(
299 target=self.event_server.serve_forever,
300 name='EventServer') # pylint: disable=E1101
301 self.event_server_thread.start()
302
303 self.event_client = EventClient(
304 callback=self.handle_event, event_loop=self.run_queue)
305
306 self.web_socket_manager = WebSocketManager(self.uuid)
307 self.state_server.add_handler("/event",
308 self.web_socket_manager.handle_web_socket)
309
310 def start_ui(self):
311 ui_proc_args = [
312 os.path.join(factory.FACTORY_PACKAGE_PATH, 'test', 'ui.py'),
313 self.options.test_list]
314 if self.options.verbose:
315 ui_proc_args.append('-v')
316 logging.info('Starting ui %s', ui_proc_args)
Jon Salz78c32392012-07-25 14:18:29 +0800317 self.ui_process = Spawn(ui_proc_args)
Jon Salz0697cbf2012-07-04 15:14:04 +0800318 logging.info('Waiting for UI to come up...')
319 self.event_client.wait(
320 lambda event: event.type == Event.Type.UI_READY)
321 logging.info('UI has started')
322
323 def set_visible_test(self, test):
324 if self.visible_test == test:
325 return
Jon Salz2f2d42c2012-07-30 12:30:34 +0800326 if test and not test.has_ui:
327 return
Jon Salz0697cbf2012-07-04 15:14:04 +0800328
329 if test:
330 test.update_state(visible=True)
331 if self.visible_test:
332 self.visible_test.update_state(visible=False)
333 self.visible_test = test
334
335 def handle_shutdown_complete(self, test, test_state):
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800336 '''
Jon Salz0697cbf2012-07-04 15:14:04 +0800337 Handles the case where a shutdown was detected during a shutdown step.
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800338
Jon Salz0697cbf2012-07-04 15:14:04 +0800339 @param test: The ShutdownStep.
340 @param test_state: The test state.
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800341 '''
Jon Salz0697cbf2012-07-04 15:14:04 +0800342 test_state = test.update_state(increment_shutdown_count=1)
343 logging.info('Detected shutdown (%d of %d)',
344 test_state.shutdown_count, test.iterations)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800345
Jon Salz0697cbf2012-07-04 15:14:04 +0800346 def log_and_update_state(status, error_msg, **kw):
347 self.event_log.Log('rebooted',
348 status=status, error_msg=error_msg, **kw)
349 test.update_state(status=status, error_msg=error_msg)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800350
Jon Salz0697cbf2012-07-04 15:14:04 +0800351 if not self.last_shutdown_time:
352 log_and_update_state(status=TestState.FAILED,
353 error_msg='Unable to read shutdown_time')
354 return
Jon Salz258a40c2012-04-19 12:34:01 +0800355
Jon Salz0697cbf2012-07-04 15:14:04 +0800356 now = time.time()
357 logging.info('%.03f s passed since reboot',
358 now - self.last_shutdown_time)
Jon Salz258a40c2012-04-19 12:34:01 +0800359
Jon Salz0697cbf2012-07-04 15:14:04 +0800360 if self.last_shutdown_time > now:
361 test.update_state(status=TestState.FAILED,
362 error_msg='Time moved backward during reboot')
363 elif (isinstance(test, factory.RebootStep) and
364 self.test_list.options.max_reboot_time_secs and
365 (now - self.last_shutdown_time >
366 self.test_list.options.max_reboot_time_secs)):
367 # A reboot took too long; fail. (We don't check this for
368 # HaltSteps, because the machine could be halted for a
369 # very long time, and even unplugged with battery backup,
370 # thus hosing the clock.)
371 log_and_update_state(
372 status=TestState.FAILED,
373 error_msg=('More than %d s elapsed during reboot '
374 '(%.03f s, from %s to %s)' % (
375 self.test_list.options.max_reboot_time_secs,
376 now - self.last_shutdown_time,
377 utils.TimeString(self.last_shutdown_time),
378 utils.TimeString(now))),
379 duration=(now-self.last_shutdown_time))
380 elif test_state.shutdown_count == test.iterations:
381 # Good!
382 log_and_update_state(status=TestState.PASSED,
383 duration=(now - self.last_shutdown_time),
384 error_msg='')
385 elif test_state.shutdown_count > test.iterations:
386 # Shut down too many times
387 log_and_update_state(status=TestState.FAILED,
388 error_msg='Too many shutdowns')
389 elif utils.are_shift_keys_depressed():
390 logging.info('Shift keys are depressed; cancelling restarts')
391 # Abort shutdown
392 log_and_update_state(
393 status=TestState.FAILED,
394 error_msg='Shutdown aborted with double shift keys')
Jon Salza6711d72012-07-18 14:33:03 +0800395 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +0800396 else:
397 def handler():
398 if self._prompt_cancel_shutdown(
399 test, test_state.shutdown_count + 1):
Jon Salza6711d72012-07-18 14:33:03 +0800400 factory.console.info('Shutdown aborted by operator')
Jon Salz0697cbf2012-07-04 15:14:04 +0800401 log_and_update_state(
402 status=TestState.FAILED,
403 error_msg='Shutdown aborted by operator')
Jon Salza6711d72012-07-18 14:33:03 +0800404 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +0800405 return
Jon Salz0405ab52012-03-16 15:26:52 +0800406
Jon Salz0697cbf2012-07-04 15:14:04 +0800407 # Time to shutdown again
408 log_and_update_state(
409 status=TestState.ACTIVE,
410 error_msg='',
411 iteration=test_state.shutdown_count)
Jon Salz73e0fd02012-04-04 11:46:38 +0800412
Jon Salz0697cbf2012-07-04 15:14:04 +0800413 self.event_log.Log('shutdown', operation='reboot')
414 self.state_instance.set_shared_data('shutdown_time',
415 time.time())
416 self.env.shutdown('reboot')
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800417
Jon Salz0697cbf2012-07-04 15:14:04 +0800418 self.on_ui_startup.append(handler)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800419
Jon Salz0697cbf2012-07-04 15:14:04 +0800420 def _prompt_cancel_shutdown(self, test, iteration):
421 if self.options.ui != 'chrome':
422 return False
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800423
Jon Salz0697cbf2012-07-04 15:14:04 +0800424 pending_shutdown_data = {
425 'delay_secs': test.delay_secs,
426 'time': time.time() + test.delay_secs,
427 'operation': test.operation,
428 'iteration': iteration,
429 'iterations': test.iterations,
430 }
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800431
Jon Salz0697cbf2012-07-04 15:14:04 +0800432 # Create a new (threaded) event client since we
433 # don't want to use the event loop for this.
434 with EventClient() as event_client:
435 event_client.post_event(Event(Event.Type.PENDING_SHUTDOWN,
436 **pending_shutdown_data))
437 aborted = event_client.wait(
438 lambda event: event.type == Event.Type.CANCEL_SHUTDOWN,
439 timeout=test.delay_secs) is not None
440 if aborted:
441 event_client.post_event(Event(Event.Type.PENDING_SHUTDOWN))
442 return aborted
Jon Salz258a40c2012-04-19 12:34:01 +0800443
Jon Salz0697cbf2012-07-04 15:14:04 +0800444 def init_states(self):
445 '''
446 Initializes all states on startup.
447 '''
448 for test in self.test_list.get_all_tests():
449 # Make sure the state server knows about all the tests,
450 # defaulting to an untested state.
451 test.update_state(update_parent=False, visible=False)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800452
Jon Salz0697cbf2012-07-04 15:14:04 +0800453 var_log_messages = None
Vic Yanga9c32212012-08-16 20:07:54 +0800454 mosys_log = None
Vic Yange4c275d2012-08-28 01:50:20 +0800455 ec_console_log = None
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800456
Jon Salz0697cbf2012-07-04 15:14:04 +0800457 # Any 'active' tests should be marked as failed now.
458 for test in self.test_list.walk():
Jon Salza6711d72012-07-18 14:33:03 +0800459 if not test.is_leaf():
460 # Don't bother with parents; they will be updated when their
461 # children are updated.
462 continue
463
Jon Salz0697cbf2012-07-04 15:14:04 +0800464 test_state = test.get_state()
465 if test_state.status != TestState.ACTIVE:
466 continue
467 if isinstance(test, factory.ShutdownStep):
468 # Shutdown while the test was active - that's good.
469 self.handle_shutdown_complete(test, test_state)
470 else:
471 # Unexpected shutdown. Grab /var/log/messages for context.
472 if var_log_messages is None:
473 try:
474 var_log_messages = (
475 utils.var_log_messages_before_reboot())
476 # Write it to the log, to make it easier to
477 # correlate with /var/log/messages.
478 logging.info(
479 'Unexpected shutdown. '
480 'Tail of /var/log/messages before last reboot:\n'
481 '%s', ('\n'.join(
482 ' ' + x for x in var_log_messages)))
483 except: # pylint: disable=W0702
484 logging.exception('Unable to grok /var/log/messages')
485 var_log_messages = []
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800486
Jon Salz008f4ea2012-08-28 05:39:45 +0800487 if mosys_log is None and not utils.in_chroot():
488 try:
489 mosys_log = utils.Spawn(
490 ['mosys', 'eventlog', 'list'],
491 read_stdout=True, log_stderr_on_error=True).stdout_data
492 # Write it to the log also.
493 logging.info('System eventlog from mosys:\n%s\n', mosys_log)
494 except: # pylint: disable=W0702
495 logging.exception('Unable to read mosys eventlog')
Vic Yanga9c32212012-08-16 20:07:54 +0800496
Vic Yange4c275d2012-08-28 01:50:20 +0800497 if ec_console_log is None:
498 try:
499 ec = system.GetEC()
500 ec_console_log = ec.GetConsoleLog()
501 logging.info('EC console log after reboot:\n%s\n', ec_console_log)
502 except:
503 logging.exception('Error retrieving EC console log')
504
505
Jon Salz0697cbf2012-07-04 15:14:04 +0800506 error_msg = 'Unexpected shutdown while test was running'
507 self.event_log.Log('end_test',
508 path=test.path,
509 status=TestState.FAILED,
510 invocation=test.get_state().invocation,
511 error_msg=error_msg,
Vic Yanga9c32212012-08-16 20:07:54 +0800512 var_log_messages='\n'.join(var_log_messages),
513 mosys_log=mosys_log)
Jon Salz0697cbf2012-07-04 15:14:04 +0800514 test.update_state(
515 status=TestState.FAILED,
516 error_msg=error_msg)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800517
Jon Salz50efe942012-07-26 11:54:10 +0800518 if not test.never_fails:
519 # For "never_fails" tests (such as "Start"), don't cancel
520 # pending tests, since reboot is expected.
521 factory.console.info('Unexpected shutdown while test %s '
522 'running; cancelling any pending tests',
523 test.path)
524 self.state_instance.set_shared_data('tests_after_shutdown', [])
Jon Salz69806bb2012-07-20 18:05:02 +0800525
Jon Salz008f4ea2012-08-28 05:39:45 +0800526 self.update_skipped_tests()
527
528 def update_skipped_tests(self):
529 '''
530 Updates skipped states based on run_if.
531 '''
532 for t in self.test_list.walk():
533 if t.is_leaf() and t.run_if_table_name:
534 skip = False
535 try:
536 aux = shopfloor.get_selected_aux_data(t.run_if_table_name)
537 value = aux.get(t.run_if_col)
538 if value is not None:
539 skip = (not value) ^ t.run_if_not
540 except ValueError:
541 # Not available; assume it shouldn't be skipped
542 pass
543
544 test_state = t.get_state()
545 if ((not skip) and
546 (test_state.status == TestState.PASSED) and
547 (test_state.error_msg == TestState.SKIPPED_MSG)):
548 # It was marked as skipped before, but now we need to run it.
549 # Mark as untested.
550 t.update_state(skip=skip, status=TestState.UNTESTED, error_msg='')
551 else:
552 t.update_state(skip=skip)
553
Jon Salz0697cbf2012-07-04 15:14:04 +0800554 def show_next_active_test(self):
555 '''
556 Rotates to the next visible active test.
557 '''
558 self.reap_completed_tests()
559 active_tests = [
560 t for t in self.test_list.walk()
561 if t.is_leaf() and t.get_state().status == TestState.ACTIVE]
562 if not active_tests:
563 return
Jon Salz4f6c7172012-06-11 20:45:36 +0800564
Jon Salz0697cbf2012-07-04 15:14:04 +0800565 try:
566 next_test = active_tests[
567 (active_tests.index(self.visible_test) + 1) % len(active_tests)]
568 except ValueError: # visible_test not present in active_tests
569 next_test = active_tests[0]
Jon Salz4f6c7172012-06-11 20:45:36 +0800570
Jon Salz0697cbf2012-07-04 15:14:04 +0800571 self.set_visible_test(next_test)
Jon Salz4f6c7172012-06-11 20:45:36 +0800572
Jon Salz0697cbf2012-07-04 15:14:04 +0800573 def handle_event(self, event):
574 '''
575 Handles an event from the event server.
576 '''
577 handler = self.event_handlers.get(event.type)
578 if handler:
579 handler(event)
580 else:
581 # We don't register handlers for all event types - just ignore
582 # this event.
583 logging.debug('Unbound event type %s', event.type)
Jon Salz4f6c7172012-06-11 20:45:36 +0800584
Jon Salz0697cbf2012-07-04 15:14:04 +0800585 def run_next_test(self):
586 '''
587 Runs the next eligible test (or tests) in self.tests_to_run.
588 '''
589 self.reap_completed_tests()
590 while self.tests_to_run:
591 logging.debug('Tests to run: %s',
592 [x.path for x in self.tests_to_run])
Jon Salz94eb56f2012-06-12 18:01:12 +0800593
Jon Salz0697cbf2012-07-04 15:14:04 +0800594 test = self.tests_to_run[0]
Jon Salz94eb56f2012-06-12 18:01:12 +0800595
Jon Salz0697cbf2012-07-04 15:14:04 +0800596 if test in self.invocations:
597 logging.info('Next test %s is already running', test.path)
598 self.tests_to_run.popleft()
599 return
Jon Salz94eb56f2012-06-12 18:01:12 +0800600
Jon Salz008f4ea2012-08-28 05:39:45 +0800601 if test.get_state().skip:
602 factory.console.info('Skipping test %s', test.path)
603 test.update_state(status=TestState.PASSED,
604 error_msg=TestState.SKIPPED_MSG)
605 self.tests_to_run.popleft()
606 return
607
Jon Salza1412922012-07-23 16:04:17 +0800608 for requirement in test.require_run:
609 for i in requirement.test.walk():
610 if i.get_state().status == TestState.ACTIVE:
Jon Salz304a75d2012-07-06 11:14:15 +0800611 logging.info('Waiting for active test %s to complete '
Jon Salza1412922012-07-23 16:04:17 +0800612 'before running %s', i.path, test.path)
Jon Salz304a75d2012-07-06 11:14:15 +0800613 return
614
Jon Salz0697cbf2012-07-04 15:14:04 +0800615 if self.invocations and not (test.backgroundable and all(
616 [x.backgroundable for x in self.invocations])):
617 logging.debug('Waiting for non-backgroundable tests to '
618 'complete before running %s', test.path)
619 return
Jon Salz94eb56f2012-06-12 18:01:12 +0800620
Jon Salz0697cbf2012-07-04 15:14:04 +0800621 self.tests_to_run.popleft()
Jon Salz94eb56f2012-06-12 18:01:12 +0800622
Jon Salz304a75d2012-07-06 11:14:15 +0800623 untested = set()
Jon Salza1412922012-07-23 16:04:17 +0800624 for requirement in test.require_run:
625 for i in requirement.test.walk():
626 if i == test:
Jon Salz304a75d2012-07-06 11:14:15 +0800627 # We've hit this test itself; stop checking
628 break
Jon Salza1412922012-07-23 16:04:17 +0800629 if ((i.get_state().status == TestState.UNTESTED) or
630 (requirement.passed and i.get_state().status !=
631 TestState.PASSED)):
Jon Salz304a75d2012-07-06 11:14:15 +0800632 # Found an untested test; move on to the next
633 # element in require_run.
Jon Salza1412922012-07-23 16:04:17 +0800634 untested.add(i)
Jon Salz304a75d2012-07-06 11:14:15 +0800635 break
636
637 if untested:
638 untested_paths = ', '.join(sorted([x.path for x in untested]))
639 if self.state_instance.get_shared_data('engineering_mode',
640 optional=True):
641 # In engineering mode, we'll let it go.
642 factory.console.warn('In engineering mode; running '
643 '%s even though required tests '
644 '[%s] have not completed',
645 test.path, untested_paths)
646 else:
647 # Not in engineering mode; mark it failed.
648 error_msg = ('Required tests [%s] have not been run yet'
649 % untested_paths)
650 factory.console.error('Not running %s: %s',
651 test.path, error_msg)
652 test.update_state(status=TestState.FAILED,
653 error_msg=error_msg)
654 continue
655
Jon Salz0697cbf2012-07-04 15:14:04 +0800656 if isinstance(test, factory.ShutdownStep):
657 if os.path.exists(NO_REBOOT_FILE):
658 test.update_state(
659 status=TestState.FAILED, increment_count=1,
660 error_msg=('Skipped shutdown since %s is present' %
Jon Salz304a75d2012-07-06 11:14:15 +0800661 NO_REBOOT_FILE))
Jon Salz0697cbf2012-07-04 15:14:04 +0800662 continue
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800663
Jon Salz0697cbf2012-07-04 15:14:04 +0800664 test.update_state(status=TestState.ACTIVE, increment_count=1,
665 error_msg='', shutdown_count=0)
666 if self._prompt_cancel_shutdown(test, 1):
667 self.event_log.Log('reboot_cancelled')
668 test.update_state(
669 status=TestState.FAILED, increment_count=1,
670 error_msg='Shutdown aborted by operator',
671 shutdown_count=0)
672 return
Jon Salz2f757d42012-06-27 17:06:42 +0800673
Jon Salz0697cbf2012-07-04 15:14:04 +0800674 # Save pending test list in the state server
Jon Salzdbf398f2012-06-14 17:30:01 +0800675 self.state_instance.set_shared_data(
Jon Salz0697cbf2012-07-04 15:14:04 +0800676 'tests_after_shutdown',
677 [t.path for t in self.tests_to_run])
678 # Save shutdown time
679 self.state_instance.set_shared_data('shutdown_time',
680 time.time())
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800681
Jon Salz0697cbf2012-07-04 15:14:04 +0800682 with self.env.lock:
683 self.event_log.Log('shutdown', operation=test.operation)
684 shutdown_result = self.env.shutdown(test.operation)
685 if shutdown_result:
686 # That's all, folks!
687 self.run_queue.put(None)
688 return
689 else:
690 # Just pass (e.g., in the chroot).
691 test.update_state(status=TestState.PASSED)
692 self.state_instance.set_shared_data(
693 'tests_after_shutdown', None)
694 # Send event with no fields to indicate that there is no
695 # longer a pending shutdown.
696 self.event_client.post_event(Event(
697 Event.Type.PENDING_SHUTDOWN))
698 continue
Jon Salz258a40c2012-04-19 12:34:01 +0800699
Jon Salz1acc8742012-07-17 17:45:55 +0800700 self._run_test(test, test.iterations)
701
702 def _run_test(self, test, iterations_left=None):
703 invoc = TestInvocation(self, test, on_completion=self.run_next_test)
704 new_state = test.update_state(
705 status=TestState.ACTIVE, increment_count=1, error_msg='',
706 invocation=invoc.uuid, iterations_left=iterations_left)
707 invoc.count = new_state.count
708
709 self.invocations[test] = invoc
710 if self.visible_test is None and test.has_ui:
711 self.set_visible_test(test)
712 self.check_connection_manager()
713 invoc.start()
Jon Salz5f2a0672012-05-22 17:14:06 +0800714
Jon Salz0697cbf2012-07-04 15:14:04 +0800715 def check_connection_manager(self):
716 exclusive_tests = [
717 test.path
718 for test in self.invocations
719 if test.is_exclusive(
720 factory.FactoryTest.EXCLUSIVE_OPTIONS.NETWORKING)]
721 if exclusive_tests:
722 # Make sure networking is disabled.
723 if self.network_enabled:
724 logging.info('Disabling network, as requested by %s',
725 exclusive_tests)
726 self.connection_manager.DisableNetworking()
727 self.network_enabled = False
728 else:
729 # Make sure networking is enabled.
730 if not self.network_enabled:
731 logging.info('Re-enabling network')
732 self.connection_manager.EnableNetworking()
733 self.network_enabled = True
Jon Salz5da61e62012-05-31 13:06:22 +0800734
cychiang21886742012-07-05 15:16:32 +0800735 def check_for_updates(self):
736 '''
737 Schedules an asynchronous check for updates if necessary.
738 '''
739 if not self.test_list.options.update_period_secs:
740 # Not enabled.
741 return
742
743 now = time.time()
744 if self.last_update_check and (
745 now - self.last_update_check <
746 self.test_list.options.update_period_secs):
747 # Not yet time for another check.
748 return
749
750 self.last_update_check = now
751
752 def handle_check_for_update(reached_shopfloor, md5sum, needs_update):
753 if reached_shopfloor:
754 new_update_md5sum = md5sum if needs_update else None
755 if system.SystemInfo.update_md5sum != new_update_md5sum:
756 logging.info('Received new update MD5SUM: %s', new_update_md5sum)
757 system.SystemInfo.update_md5sum = new_update_md5sum
758 self.run_queue.put(self.update_system_info)
759
760 updater.CheckForUpdateAsync(
761 handle_check_for_update,
762 self.test_list.options.shopfloor_timeout_secs)
763
Jon Salza6711d72012-07-18 14:33:03 +0800764 def cancel_pending_tests(self):
765 '''Cancels any tests in the run queue.'''
766 self.run_tests([])
767
Jon Salz0697cbf2012-07-04 15:14:04 +0800768 def run_tests(self, subtrees, untested_only=False):
769 '''
770 Runs tests under subtree.
Jon Salz258a40c2012-04-19 12:34:01 +0800771
Jon Salz0697cbf2012-07-04 15:14:04 +0800772 The tests are run in order unless one fails (then stops).
773 Backgroundable tests are run simultaneously; when a foreground test is
774 encountered, we wait for all active tests to finish before continuing.
Jon Salzb1b39092012-05-03 02:05:09 +0800775
Jon Salz0697cbf2012-07-04 15:14:04 +0800776 @param subtrees: Node or nodes containing tests to run (may either be
777 a single test or a list). Duplicates will be ignored.
778 '''
779 if type(subtrees) != list:
780 subtrees = [subtrees]
Jon Salz258a40c2012-04-19 12:34:01 +0800781
Jon Salz0697cbf2012-07-04 15:14:04 +0800782 # Nodes we've seen so far, to avoid duplicates.
783 seen = set()
Jon Salz94eb56f2012-06-12 18:01:12 +0800784
Jon Salz0697cbf2012-07-04 15:14:04 +0800785 self.tests_to_run = deque()
786 for subtree in subtrees:
787 for test in subtree.walk():
788 if test in seen:
789 continue
790 seen.add(test)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800791
Jon Salz0697cbf2012-07-04 15:14:04 +0800792 if not test.is_leaf():
793 continue
794 if (untested_only and
795 test.get_state().status != TestState.UNTESTED):
796 continue
797 self.tests_to_run.append(test)
798 self.run_next_test()
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800799
Jon Salz0697cbf2012-07-04 15:14:04 +0800800 def reap_completed_tests(self):
801 '''
802 Removes completed tests from the set of active tests.
803
804 Also updates the visible test if it was reaped.
805 '''
806 for t, v in dict(self.invocations).iteritems():
807 if v.is_completed():
Jon Salz1acc8742012-07-17 17:45:55 +0800808 new_state = t.update_state(**v.update_state_on_completion)
Jon Salz0697cbf2012-07-04 15:14:04 +0800809 del self.invocations[t]
810
Jon Salz1acc8742012-07-17 17:45:55 +0800811 if new_state.iterations_left and new_state.status == TestState.PASSED:
812 # Play it again, Sam!
813 self._run_test(t)
814
Jon Salz0697cbf2012-07-04 15:14:04 +0800815 if (self.visible_test is None or
Jon Salz85a39882012-07-05 16:45:04 +0800816 self.visible_test not in self.invocations):
Jon Salz0697cbf2012-07-04 15:14:04 +0800817 self.set_visible_test(None)
818 # Make the first running test, if any, the visible test
819 for t in self.test_list.walk():
820 if t in self.invocations:
821 self.set_visible_test(t)
822 break
823
Jon Salz85a39882012-07-05 16:45:04 +0800824 def kill_active_tests(self, abort, root=None):
Jon Salz0697cbf2012-07-04 15:14:04 +0800825 '''
826 Kills and waits for all active tests.
827
Jon Salz85a39882012-07-05 16:45:04 +0800828 Args:
829 abort: True to change state of killed tests to FAILED, False for
Jon Salz0697cbf2012-07-04 15:14:04 +0800830 UNTESTED.
Jon Salz85a39882012-07-05 16:45:04 +0800831 root: If set, only kills tests with root as an ancestor.
Jon Salz0697cbf2012-07-04 15:14:04 +0800832 '''
833 self.reap_completed_tests()
834 for test, invoc in self.invocations.items():
Jon Salz85a39882012-07-05 16:45:04 +0800835 if root and not test.has_ancestor(root):
836 continue
837
Jon Salz0697cbf2012-07-04 15:14:04 +0800838 factory.console.info('Killing active test %s...' % test.path)
839 invoc.abort_and_join()
840 factory.console.info('Killed %s' % test.path)
Jon Salz1acc8742012-07-17 17:45:55 +0800841 test.update_state(**invoc.update_state_on_completion)
Jon Salz0697cbf2012-07-04 15:14:04 +0800842 del self.invocations[test]
Jon Salz1acc8742012-07-17 17:45:55 +0800843
Jon Salz0697cbf2012-07-04 15:14:04 +0800844 if not abort:
845 test.update_state(status=TestState.UNTESTED)
846 self.reap_completed_tests()
847
Jon Salz85a39882012-07-05 16:45:04 +0800848 def stop(self, root=None, fail=False):
849 self.kill_active_tests(fail, root)
850 # Remove any tests in the run queue under the root.
851 self.tests_to_run = deque([x for x in self.tests_to_run
852 if root and not x.has_ancestor(root)])
853 self.run_next_test()
Jon Salz0697cbf2012-07-04 15:14:04 +0800854
855 def abort_active_tests(self):
856 self.kill_active_tests(True)
857
858 def main(self):
859 try:
860 self.init()
861 self.event_log.Log('goofy_init',
862 success=True)
863 except:
864 if self.event_log:
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800865 try:
Jon Salz0697cbf2012-07-04 15:14:04 +0800866 self.event_log.Log('goofy_init',
867 success=False,
868 trace=traceback.format_exc())
869 except: # pylint: disable=W0702
870 pass
871 raise
872
873 self.run()
874
875 def update_system_info(self):
876 '''Updates system info.'''
877 system_info = system.SystemInfo()
878 self.state_instance.set_shared_data('system_info', system_info.__dict__)
879 self.event_client.post_event(Event(Event.Type.SYSTEM_INFO,
880 system_info=system_info.__dict__))
881 logging.info('System info: %r', system_info.__dict__)
882
Jon Salzeb42f0d2012-07-27 19:14:04 +0800883 def update_factory(self, auto_run_on_restart=False, post_update_hook=None):
884 '''Commences updating factory software.
885
886 Args:
887 auto_run_on_restart: Auto-run when the machine comes back up.
888 post_update_hook: Code to call after update but immediately before
889 restart.
890
891 Returns:
892 Never if the update was successful (we just reboot).
893 False if the update was unnecessary (no update available).
894 '''
Jon Salz0697cbf2012-07-04 15:14:04 +0800895 self.kill_active_tests(False)
Jon Salza6711d72012-07-18 14:33:03 +0800896 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +0800897
Jon Salz5c344f62012-07-13 14:31:16 +0800898 def pre_update_hook():
899 if auto_run_on_restart:
900 self.state_instance.set_shared_data('tests_after_shutdown',
901 FORCE_AUTO_RUN)
902 self.state_instance.close()
903
Jon Salzeb42f0d2012-07-27 19:14:04 +0800904 if updater.TryUpdate(pre_update_hook=pre_update_hook):
905 if post_update_hook:
906 post_update_hook()
907 self.env.shutdown('reboot')
Jon Salz0697cbf2012-07-04 15:14:04 +0800908
Jon Salzcef132a2012-08-30 04:58:08 +0800909 def handle_sigint(self, dummy_signum, dummy_frame):
Jon Salz77c151e2012-08-28 07:20:37 +0800910 logging.error('Received SIGINT')
911 self.run_queue.put(None)
912 raise KeyboardInterrupt()
913
Jon Salz0697cbf2012-07-04 15:14:04 +0800914 def init(self, args=None, env=None):
915 '''Initializes Goofy.
916
917 Args:
918 args: A list of command-line arguments. Uses sys.argv if
919 args is None.
920 env: An Environment instance to use (or None to choose
921 FakeChrootEnvironment or DUTEnvironment as appropriate).
922 '''
Jon Salz77c151e2012-08-28 07:20:37 +0800923 signal.signal(signal.SIGINT, self.handle_sigint)
924
Jon Salz0697cbf2012-07-04 15:14:04 +0800925 parser = OptionParser()
926 parser.add_option('-v', '--verbose', dest='verbose',
Jon Salz8fa8e832012-07-13 19:04:09 +0800927 action='store_true',
928 help='Enable debug logging')
Jon Salz0697cbf2012-07-04 15:14:04 +0800929 parser.add_option('--print_test_list', dest='print_test_list',
Jon Salz8fa8e832012-07-13 19:04:09 +0800930 metavar='FILE',
931 help='Read and print test list FILE, and exit')
Jon Salz0697cbf2012-07-04 15:14:04 +0800932 parser.add_option('--restart', dest='restart',
Jon Salz8fa8e832012-07-13 19:04:09 +0800933 action='store_true',
934 help='Clear all test state')
Jon Salz0697cbf2012-07-04 15:14:04 +0800935 parser.add_option('--ui', dest='ui', type='choice',
Jon Salz8fa8e832012-07-13 19:04:09 +0800936 choices=['none', 'gtk', 'chrome'],
937 default=('chrome' if utils.in_chroot() else 'gtk'),
938 help='UI to use')
Jon Salz0697cbf2012-07-04 15:14:04 +0800939 parser.add_option('--ui_scale_factor', dest='ui_scale_factor',
Jon Salz8fa8e832012-07-13 19:04:09 +0800940 type='int', default=1,
941 help=('Factor by which to scale UI '
942 '(Chrome UI only)'))
Jon Salz0697cbf2012-07-04 15:14:04 +0800943 parser.add_option('--test_list', dest='test_list',
Jon Salz8fa8e832012-07-13 19:04:09 +0800944 metavar='FILE',
945 help='Use FILE as test list')
Jon Salzc79a9982012-08-30 04:42:01 +0800946 parser.add_option('--dummy_shopfloor', action='store_true',
947 help='Use a dummy shopfloor server')
Jon Salz0697cbf2012-07-04 15:14:04 +0800948 (self.options, self.args) = parser.parse_args(args)
949
Jon Salz46b89562012-07-05 11:49:22 +0800950 # Make sure factory directories exist.
951 factory.get_log_root()
952 factory.get_state_root()
953 factory.get_test_data_root()
954
Jon Salz0697cbf2012-07-04 15:14:04 +0800955 global _inited_logging # pylint: disable=W0603
956 if not _inited_logging:
957 factory.init_logging('goofy', verbose=self.options.verbose)
958 _inited_logging = True
Jon Salz8fa8e832012-07-13 19:04:09 +0800959
Jon Salzee85d522012-07-17 14:34:46 +0800960 event_log.IncrementBootSequence()
Jon Salz0697cbf2012-07-04 15:14:04 +0800961 self.event_log = EventLog('goofy')
962
963 if (not suppress_chroot_warning and
964 factory.in_chroot() and
965 self.options.ui == 'gtk' and
966 os.environ.get('DISPLAY') in [None, '', ':0', ':0.0']):
967 # That's not going to work! Tell the user how to run
968 # this way.
969 logging.warn(GOOFY_IN_CHROOT_WARNING)
970 time.sleep(1)
971
972 if env:
973 self.env = env
974 elif factory.in_chroot():
975 self.env = test_environment.FakeChrootEnvironment()
976 logging.warn(
977 'Using chroot environment: will not actually run autotests')
978 else:
979 self.env = test_environment.DUTEnvironment()
980 self.env.goofy = self
981
982 if self.options.restart:
983 state.clear_state()
984
985 if self.options.print_test_list:
Jon Salzeb42f0d2012-07-27 19:14:04 +0800986 print factory.read_test_list(
987 self.options.print_test_list).__repr__(recursive=True)
Jon Salz0697cbf2012-07-04 15:14:04 +0800988 return
989
990 if self.options.ui_scale_factor != 1 and utils.in_qemu():
991 logging.warn(
992 'In QEMU; ignoring ui_scale_factor argument')
993 self.options.ui_scale_factor = 1
994
Jon Salzc79a9982012-08-30 04:42:01 +0800995 if self.options.dummy_shopfloor:
996 os.environ[shopfloor.SHOPFLOOR_SERVER_ENV_VAR_NAME] = (
997 'http://localhost:%d/' % shopfloor.DEFAULT_SERVER_PORT)
998 self.dummy_shopfloor = Spawn(
999 [os.path.join(factory.FACTORY_PATH, 'bin', 'shopfloor_server'),
1000 '--dummy'])
1001
Jon Salz0697cbf2012-07-04 15:14:04 +08001002 logging.info('Started')
1003
1004 self.start_state_server()
1005 self.state_instance.set_shared_data('hwid_cfg', get_hwid_cfg())
1006 self.state_instance.set_shared_data('ui_scale_factor',
1007 self.options.ui_scale_factor)
1008 self.last_shutdown_time = (
1009 self.state_instance.get_shared_data('shutdown_time', optional=True))
1010 self.state_instance.del_shared_data('shutdown_time', optional=True)
1011
1012 if not self.options.test_list:
1013 self.options.test_list = find_test_list()
1014 if not self.options.test_list:
1015 logging.error('No test list. Aborting.')
1016 sys.exit(1)
1017 logging.info('Using test list %s', self.options.test_list)
1018
1019 self.test_list = factory.read_test_list(
1020 self.options.test_list,
Jon Salzeb42f0d2012-07-27 19:14:04 +08001021 self.state_instance)
Jon Salz0697cbf2012-07-04 15:14:04 +08001022 if not self.state_instance.has_shared_data('ui_lang'):
1023 self.state_instance.set_shared_data('ui_lang',
1024 self.test_list.options.ui_lang)
1025 self.state_instance.set_shared_data(
1026 'test_list_options',
1027 self.test_list.options.__dict__)
1028 self.state_instance.test_list = self.test_list
1029
Jon Salz8fa8e832012-07-13 19:04:09 +08001030 if self.test_list.options.time_sanitizer:
1031 self.time_sanitizer = time_sanitizer.TimeSanitizer(
1032 base_time=time_sanitizer.GetBaseTimeFromFile(
1033 # lsb-factory is written by the factory install shim during
1034 # installation, so it should have a good time obtained from
Jon Salz54882d02012-08-31 01:57:54 +08001035 # the mini-Omaha server. If it's not available, we'll use
1036 # /etc/lsb-factory (which will be much older, but reasonably
1037 # sane) and rely on a shopfloor sync to set a more accurate
1038 # time.
1039 '/usr/local/etc/lsb-factory',
1040 '/etc/lsb-release'))
Jon Salz8fa8e832012-07-13 19:04:09 +08001041 self.time_sanitizer.RunOnce()
1042
Jon Salz0697cbf2012-07-04 15:14:04 +08001043 self.init_states()
1044 self.start_event_server()
1045 self.connection_manager = self.env.create_connection_manager(
1046 self.test_list.options.wlans)
1047 # Note that we create a log watcher even if
1048 # sync_event_log_period_secs isn't set (no background
1049 # syncing), since we may use it to flush event logs as well.
1050 self.log_watcher = EventLogWatcher(
1051 self.test_list.options.sync_event_log_period_secs,
Jon Salz16d10542012-07-23 12:18:45 +08001052 handle_event_logs_callback=self.handle_event_logs)
Jon Salz0697cbf2012-07-04 15:14:04 +08001053 if self.test_list.options.sync_event_log_period_secs:
1054 self.log_watcher.StartWatchThread()
1055
1056 self.update_system_info()
1057
Vic Yang4953fc12012-07-26 16:19:53 +08001058 assert ((self.test_list.options.min_charge_pct is None) ==
1059 (self.test_list.options.max_charge_pct is None))
1060 if (self.test_list.options.min_charge_pct and
1061 self.test_list.options.max_charge_pct):
1062 self.charge_manager = ChargeManager(self.test_list.options.min_charge_pct,
1063 self.test_list.options.max_charge_pct)
1064
Jon Salz0697cbf2012-07-04 15:14:04 +08001065 os.environ['CROS_FACTORY'] = '1'
1066 os.environ['CROS_DISABLE_SITE_SYSINFO'] = '1'
1067
1068 # Set CROS_UI since some behaviors in ui.py depend on the
1069 # particular UI in use. TODO(jsalz): Remove this (and all
1070 # places it is used) when the GTK UI is removed.
1071 os.environ['CROS_UI'] = self.options.ui
1072
1073 if self.options.ui == 'chrome':
1074 self.env.launch_chrome()
1075 logging.info('Waiting for a web socket connection')
1076 self.web_socket_manager.wait()
1077
1078 # Wait for the test widget size to be set; this is done in
1079 # an asynchronous RPC so there is a small chance that the
1080 # web socket might be opened first.
1081 for _ in range(100): # 10 s
1082 try:
1083 if self.state_instance.get_shared_data('test_widget_size'):
1084 break
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001085 except KeyError:
Jon Salz0697cbf2012-07-04 15:14:04 +08001086 pass # Retry
1087 time.sleep(0.1) # 100 ms
1088 else:
1089 logging.warn('Never received test_widget_size from UI')
1090 elif self.options.ui == 'gtk':
1091 self.start_ui()
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001092
Jon Salz0697cbf2012-07-04 15:14:04 +08001093 def state_change_callback(test, test_state):
1094 self.event_client.post_event(
1095 Event(Event.Type.STATE_CHANGE,
1096 path=test.path, state=test_state))
1097 self.test_list.state_change_callback = state_change_callback
Jon Salz73e0fd02012-04-04 11:46:38 +08001098
Jon Salza6711d72012-07-18 14:33:03 +08001099 for handler in self.on_ui_startup:
1100 handler()
1101
1102 self.prespawner = Prespawner()
1103 self.prespawner.start()
1104
Jon Salz0697cbf2012-07-04 15:14:04 +08001105 try:
1106 tests_after_shutdown = self.state_instance.get_shared_data(
1107 'tests_after_shutdown')
1108 except KeyError:
1109 tests_after_shutdown = None
Jon Salz57717ca2012-04-04 16:47:25 +08001110
Jon Salz5c344f62012-07-13 14:31:16 +08001111 force_auto_run = (tests_after_shutdown == FORCE_AUTO_RUN)
1112 if not force_auto_run and tests_after_shutdown is not None:
Jon Salz0697cbf2012-07-04 15:14:04 +08001113 logging.info('Resuming tests after shutdown: %s',
1114 tests_after_shutdown)
Jon Salz0697cbf2012-07-04 15:14:04 +08001115 self.tests_to_run.extend(
1116 self.test_list.lookup_path(t) for t in tests_after_shutdown)
1117 self.run_queue.put(self.run_next_test)
1118 else:
Jon Salz5c344f62012-07-13 14:31:16 +08001119 if force_auto_run or self.test_list.options.auto_run_on_start:
Jon Salz0697cbf2012-07-04 15:14:04 +08001120 self.run_queue.put(
1121 lambda: self.run_tests(self.test_list, untested_only=True))
Jon Salz5c344f62012-07-13 14:31:16 +08001122 self.state_instance.set_shared_data('tests_after_shutdown', None)
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001123
Jon Salz0697cbf2012-07-04 15:14:04 +08001124 def run(self):
1125 '''Runs Goofy.'''
1126 # Process events forever.
1127 while self.run_once(True):
1128 pass
Jon Salz73e0fd02012-04-04 11:46:38 +08001129
Jon Salz0697cbf2012-07-04 15:14:04 +08001130 def run_once(self, block=False):
1131 '''Runs all items pending in the event loop.
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001132
Jon Salz0697cbf2012-07-04 15:14:04 +08001133 Args:
1134 block: If true, block until at least one event is processed.
Jon Salz7c15e8b2012-06-19 17:10:37 +08001135
Jon Salz0697cbf2012-07-04 15:14:04 +08001136 Returns:
1137 True to keep going or False to shut down.
1138 '''
1139 events = utils.DrainQueue(self.run_queue)
cychiang21886742012-07-05 15:16:32 +08001140 while not events:
Jon Salz0697cbf2012-07-04 15:14:04 +08001141 # Nothing on the run queue.
1142 self._run_queue_idle()
1143 if block:
1144 # Block for at least one event...
cychiang21886742012-07-05 15:16:32 +08001145 try:
1146 events.append(self.run_queue.get(timeout=RUN_QUEUE_TIMEOUT_SECS))
1147 except Queue.Empty:
1148 # Keep going (calling _run_queue_idle() again at the top of
1149 # the loop)
1150 continue
Jon Salz0697cbf2012-07-04 15:14:04 +08001151 # ...and grab anything else that showed up at the same
1152 # time.
1153 events.extend(utils.DrainQueue(self.run_queue))
cychiang21886742012-07-05 15:16:32 +08001154 else:
1155 break
Jon Salz51528e12012-07-02 18:54:45 +08001156
Jon Salz0697cbf2012-07-04 15:14:04 +08001157 for event in events:
1158 if not event:
1159 # Shutdown request.
1160 self.run_queue.task_done()
1161 return False
Jon Salz51528e12012-07-02 18:54:45 +08001162
Jon Salz0697cbf2012-07-04 15:14:04 +08001163 try:
1164 event()
Jon Salz85a39882012-07-05 16:45:04 +08001165 except: # pylint: disable=W0702
1166 logging.exception('Error in event loop')
Jon Salz0697cbf2012-07-04 15:14:04 +08001167 self.record_exception(traceback.format_exception_only(
1168 *sys.exc_info()[:2]))
1169 # But keep going
1170 finally:
1171 self.run_queue.task_done()
1172 return True
Jon Salz0405ab52012-03-16 15:26:52 +08001173
Jon Salz54882d02012-08-31 01:57:54 +08001174 def _should_sync_time(self):
1175 '''Returns True if we should attempt syncing time with shopfloor.'''
1176 return (self.test_list.options.sync_time_period_secs and
1177 self.time_sanitizer and
1178 (not self.time_synced) and
1179 (not factory.in_chroot()))
1180
1181 def sync_time_with_shopfloor_server(self):
1182 '''Syncs time with shopfloor server, if not yet synced.
1183
1184 Returns:
1185 False if no time sanitizer is available, or True if this sync (or a
1186 previous sync) succeeded.
1187
1188 Raises:
1189 Exception if unable to contact the shopfloor server.
1190 '''
1191 if self._should_sync_time():
1192 self.time_sanitizer.SyncWithShopfloor()
1193 self.time_synced = True
1194 return self.time_synced
1195
Jon Salz8fa8e832012-07-13 19:04:09 +08001196 def sync_time_in_background(self):
Jon Salzb22d1172012-08-06 10:38:57 +08001197 '''Writes out current time and tries to sync with shopfloor server.'''
1198 if not self.time_sanitizer:
1199 return
1200
1201 # Write out the current time.
1202 self.time_sanitizer.SaveTime()
1203
Jon Salz54882d02012-08-31 01:57:54 +08001204 if not self._should_sync_time():
Jon Salz8fa8e832012-07-13 19:04:09 +08001205 return
1206
1207 now = time.time()
1208 if self.last_sync_time and (
1209 now - self.last_sync_time <
1210 self.test_list.options.sync_time_period_secs):
1211 # Not yet time for another check.
1212 return
1213 self.last_sync_time = now
1214
1215 def target():
1216 try:
Jon Salz54882d02012-08-31 01:57:54 +08001217 self.sync_time_with_shopfloor_server()
Jon Salz8fa8e832012-07-13 19:04:09 +08001218 except: # pylint: disable=W0702
1219 # Oh well. Log an error (but no trace)
1220 logging.info(
1221 'Unable to get time from shopfloor server: %s',
1222 utils.FormatExceptionOnly())
1223
1224 thread = threading.Thread(target=target)
1225 thread.daemon = True
1226 thread.start()
1227
Jon Salz0697cbf2012-07-04 15:14:04 +08001228 def _run_queue_idle(self):
Vic Yang4953fc12012-07-26 16:19:53 +08001229 '''Invoked when the run queue has no events.
1230
1231 This method must not raise exception.
1232 '''
Jon Salzb22d1172012-08-06 10:38:57 +08001233 now = time.time()
1234 if (self.last_idle and
1235 now < (self.last_idle + RUN_QUEUE_TIMEOUT_SECS - 1)):
1236 # Don't run more often than once every (RUN_QUEUE_TIMEOUT_SECS -
1237 # 1) seconds.
1238 return
1239
1240 self.last_idle = now
1241
Jon Salz0697cbf2012-07-04 15:14:04 +08001242 self.check_connection_manager()
cychiang21886742012-07-05 15:16:32 +08001243 self.check_for_updates()
Jon Salz8fa8e832012-07-13 19:04:09 +08001244 self.sync_time_in_background()
Vic Yang4953fc12012-07-26 16:19:53 +08001245 if self.charge_manager:
1246 self.charge_manager.AdjustChargeState()
Jon Salz57717ca2012-04-04 16:47:25 +08001247
Jon Salz16d10542012-07-23 12:18:45 +08001248 def handle_event_logs(self, log_name, chunk):
Jon Salz0697cbf2012-07-04 15:14:04 +08001249 '''Callback for event watcher.
Jon Salz258a40c2012-04-19 12:34:01 +08001250
Jon Salz0697cbf2012-07-04 15:14:04 +08001251 Attempts to upload the event logs to the shopfloor server.
1252 '''
1253 description = 'event logs (%s, %d bytes)' % (log_name, len(chunk))
1254 start_time = time.time()
1255 logging.info('Syncing %s', description)
1256 shopfloor_client = shopfloor.get_instance(
1257 detect=True,
1258 timeout=self.test_list.options.shopfloor_timeout_secs)
Jon Salzb10cf512012-08-09 17:29:21 +08001259 shopfloor_client.UploadEvent(log_name, Binary(chunk))
Jon Salz0697cbf2012-07-04 15:14:04 +08001260 logging.info(
1261 'Successfully synced %s in %.03f s',
1262 description, time.time() - start_time)
Jon Salz57717ca2012-04-04 16:47:25 +08001263
Jon Salz0697cbf2012-07-04 15:14:04 +08001264 def run_tests_with_status(self, statuses_to_run, starting_at=None,
1265 root=None):
1266 '''Runs all top-level tests with a particular status.
Jon Salz0405ab52012-03-16 15:26:52 +08001267
Jon Salz0697cbf2012-07-04 15:14:04 +08001268 All active tests, plus any tests to re-run, are reset.
Jon Salz57717ca2012-04-04 16:47:25 +08001269
Jon Salz0697cbf2012-07-04 15:14:04 +08001270 Args:
1271 starting_at: If provided, only auto-runs tests beginning with
1272 this test.
1273 '''
1274 root = root or self.test_list
Jon Salz57717ca2012-04-04 16:47:25 +08001275
Jon Salz0697cbf2012-07-04 15:14:04 +08001276 if starting_at:
1277 # Make sure they passed a test, not a string.
1278 assert isinstance(starting_at, factory.FactoryTest)
Jon Salz0405ab52012-03-16 15:26:52 +08001279
Jon Salz0697cbf2012-07-04 15:14:04 +08001280 tests_to_reset = []
1281 tests_to_run = []
Jon Salz0405ab52012-03-16 15:26:52 +08001282
Jon Salz0697cbf2012-07-04 15:14:04 +08001283 found_starting_at = False
Jon Salz0405ab52012-03-16 15:26:52 +08001284
Jon Salz0697cbf2012-07-04 15:14:04 +08001285 for test in root.get_top_level_tests():
1286 if starting_at:
1287 if test == starting_at:
1288 # We've found starting_at; do auto-run on all
1289 # subsequent tests.
1290 found_starting_at = True
1291 if not found_starting_at:
1292 # Don't start this guy yet
1293 continue
Jon Salz0405ab52012-03-16 15:26:52 +08001294
Jon Salz0697cbf2012-07-04 15:14:04 +08001295 status = test.get_state().status
1296 if status == TestState.ACTIVE or status in statuses_to_run:
1297 # Reset the test (later; we will need to abort
1298 # all active tests first).
1299 tests_to_reset.append(test)
1300 if status in statuses_to_run:
1301 tests_to_run.append(test)
Jon Salz0405ab52012-03-16 15:26:52 +08001302
Jon Salz0697cbf2012-07-04 15:14:04 +08001303 self.abort_active_tests()
Jon Salz258a40c2012-04-19 12:34:01 +08001304
Jon Salz0697cbf2012-07-04 15:14:04 +08001305 # Reset all statuses of the tests to run (in case any tests were active;
1306 # we want them to be run again).
1307 for test_to_reset in tests_to_reset:
1308 for test in test_to_reset.walk():
1309 test.update_state(status=TestState.UNTESTED)
Jon Salz57717ca2012-04-04 16:47:25 +08001310
Jon Salz0697cbf2012-07-04 15:14:04 +08001311 self.run_tests(tests_to_run, untested_only=True)
Jon Salz0405ab52012-03-16 15:26:52 +08001312
Jon Salz0697cbf2012-07-04 15:14:04 +08001313 def restart_tests(self, root=None):
1314 '''Restarts all tests.'''
1315 root = root or self.test_list
Jon Salz0405ab52012-03-16 15:26:52 +08001316
Jon Salz0697cbf2012-07-04 15:14:04 +08001317 self.abort_active_tests()
1318 for test in root.walk():
1319 test.update_state(status=TestState.UNTESTED)
1320 self.run_tests(root)
Hung-Te Lin96632362012-03-20 21:14:18 +08001321
Jon Salz0697cbf2012-07-04 15:14:04 +08001322 def auto_run(self, starting_at=None, root=None):
1323 '''"Auto-runs" tests that have not been run yet.
Hung-Te Lin96632362012-03-20 21:14:18 +08001324
Jon Salz0697cbf2012-07-04 15:14:04 +08001325 Args:
1326 starting_at: If provide, only auto-runs tests beginning with
1327 this test.
1328 '''
1329 root = root or self.test_list
1330 self.run_tests_with_status([TestState.UNTESTED, TestState.ACTIVE],
1331 starting_at=starting_at,
1332 root=root)
Jon Salz968e90b2012-03-18 16:12:43 +08001333
Jon Salz0697cbf2012-07-04 15:14:04 +08001334 def re_run_failed(self, root=None):
1335 '''Re-runs failed tests.'''
1336 root = root or self.test_list
1337 self.run_tests_with_status([TestState.FAILED], root=root)
Jon Salz57717ca2012-04-04 16:47:25 +08001338
Jon Salz0697cbf2012-07-04 15:14:04 +08001339 def show_review_information(self):
1340 '''Event handler for showing review information screen.
Jon Salz57717ca2012-04-04 16:47:25 +08001341
Jon Salz0697cbf2012-07-04 15:14:04 +08001342 The information screene is rendered by main UI program (ui.py), so in
1343 goofy we only need to kill all active tests, set them as untested, and
1344 clear remaining tests.
1345 '''
1346 self.kill_active_tests(False)
Jon Salza6711d72012-07-18 14:33:03 +08001347 self.cancel_pending_tests()
Jon Salz57717ca2012-04-04 16:47:25 +08001348
Jon Salz0697cbf2012-07-04 15:14:04 +08001349 def handle_switch_test(self, event):
1350 '''Switches to a particular test.
Jon Salz0405ab52012-03-16 15:26:52 +08001351
Jon Salz0697cbf2012-07-04 15:14:04 +08001352 @param event: The SWITCH_TEST event.
1353 '''
1354 test = self.test_list.lookup_path(event.path)
1355 if not test:
1356 logging.error('Unknown test %r', event.key)
1357 return
Jon Salz73e0fd02012-04-04 11:46:38 +08001358
Jon Salz0697cbf2012-07-04 15:14:04 +08001359 invoc = self.invocations.get(test)
1360 if invoc and test.backgroundable:
1361 # Already running: just bring to the front if it
1362 # has a UI.
1363 logging.info('Setting visible test to %s', test.path)
Jon Salz36fbbb52012-07-05 13:45:06 +08001364 self.set_visible_test(test)
Jon Salz0697cbf2012-07-04 15:14:04 +08001365 return
Jon Salz73e0fd02012-04-04 11:46:38 +08001366
Jon Salz0697cbf2012-07-04 15:14:04 +08001367 self.abort_active_tests()
1368 for t in test.walk():
1369 t.update_state(status=TestState.UNTESTED)
Jon Salz73e0fd02012-04-04 11:46:38 +08001370
Jon Salz0697cbf2012-07-04 15:14:04 +08001371 if self.test_list.options.auto_run_on_keypress:
1372 self.auto_run(starting_at=test)
1373 else:
1374 self.run_tests(test)
Jon Salz73e0fd02012-04-04 11:46:38 +08001375
Jon Salz0697cbf2012-07-04 15:14:04 +08001376 def wait(self):
1377 '''Waits for all pending invocations.
1378
1379 Useful for testing.
1380 '''
Jon Salz1acc8742012-07-17 17:45:55 +08001381 while self.invocations:
1382 for k, v in self.invocations.iteritems():
1383 logging.info('Waiting for %s to complete...', k)
1384 v.thread.join()
1385 self.reap_completed_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +08001386
1387 def check_exceptions(self):
1388 '''Raises an error if any exceptions have occurred in
1389 invocation threads.'''
1390 if self.exceptions:
1391 raise RuntimeError('Exception in invocation thread: %r' %
1392 self.exceptions)
1393
1394 def record_exception(self, msg):
1395 '''Records an exception in an invocation thread.
1396
1397 An exception with the given message will be rethrown when
1398 Goofy is destroyed.'''
1399 self.exceptions.append(msg)
Jon Salz73e0fd02012-04-04 11:46:38 +08001400
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001401
1402if __name__ == '__main__':
Jon Salz77c151e2012-08-28 07:20:37 +08001403 goofy = Goofy()
1404 try:
1405 goofy.main()
1406 finally:
1407 goofy.destroy()