blob: d179f3a3d402d8884fcc15175b12286c59412d08 [file] [log] [blame]
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001#!/usr/bin/python -u
Hung-Te Linf2f78f72012-02-08 19:27:11 +08002# -*- coding: utf-8 -*-
3#
Jon Salz37eccbd2012-05-25 16:06:52 +08004# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
Hung-Te Linf2f78f72012-02-08 19:27:11 +08005# Use of this source code is governed by a BSD-style license that can be
6# found in the LICENSE file.
7
8'''
9The main factory flow that runs the factory test and finalizes a device.
10'''
11
Jon Salz0405ab52012-03-16 15:26:52 +080012import logging
13import os
Jon Salz73e0fd02012-04-04 11:46:38 +080014import Queue
Jon Salz77c151e2012-08-28 07:20:37 +080015import signal
Jon Salz0405ab52012-03-16 15:26:52 +080016import sys
Jon Salz0405ab52012-03-16 15:26:52 +080017import threading
18import time
19import traceback
Jon Salz258a40c2012-04-19 12:34:01 +080020import uuid
Jon Salzb10cf512012-08-09 17:29:21 +080021from xmlrpclib import Binary
Hung-Te Linf2f78f72012-02-08 19:27:11 +080022from collections import deque
23from optparse import OptionParser
Hung-Te Linf2f78f72012-02-08 19:27:11 +080024
Jon Salz0697cbf2012-07-04 15:14:04 +080025import factory_common # pylint: disable=W0611
jcliangcd688182012-08-20 21:01:26 +080026from cros.factory import event_log
27from cros.factory import system
28from cros.factory.event_log import EventLog
29from cros.factory.goofy import test_environment
30from cros.factory.goofy import time_sanitizer
Jon Salz83591782012-06-26 11:09:58 +080031from cros.factory.goofy import updater
Jon Salz51528e12012-07-02 18:54:45 +080032from cros.factory.goofy.event_log_watcher import EventLogWatcher
jcliangcd688182012-08-20 21:01:26 +080033from cros.factory.goofy.goofy_rpc import GoofyRPC
34from cros.factory.goofy.invocation import TestInvocation
35from cros.factory.goofy.prespawner import Prespawner
36from cros.factory.goofy.web_socket_manager import WebSocketManager
37from cros.factory.system.charge_manager import ChargeManager
Jon Salzb92c5112012-09-21 15:40:11 +080038from cros.factory.system import disk_space
jcliangcd688182012-08-20 21:01:26 +080039from cros.factory.test import factory
40from cros.factory.test import state
Jon Salz51528e12012-07-02 18:54:45 +080041from cros.factory.test import shopfloor
Jon Salz83591782012-06-26 11:09:58 +080042from cros.factory.test import utils
43from cros.factory.test.event import Event
44from cros.factory.test.event import EventClient
45from cros.factory.test.event import EventServer
jcliangcd688182012-08-20 21:01:26 +080046from cros.factory.test.factory import TestState
Jon Salz78c32392012-07-25 14:18:29 +080047from cros.factory.utils.process_utils import Spawn
Hung-Te Linf2f78f72012-02-08 19:27:11 +080048
49
Jon Salz2f757d42012-06-27 17:06:42 +080050DEFAULT_TEST_LISTS_DIR = os.path.join(factory.FACTORY_PATH, 'test_lists')
51CUSTOM_DIR = os.path.join(factory.FACTORY_PATH, 'custom')
Hung-Te Linf2f78f72012-02-08 19:27:11 +080052HWID_CFG_PATH = '/usr/local/share/chromeos-hwid/cfg'
53
Jon Salz8796e362012-05-24 11:39:09 +080054# File that suppresses reboot if present (e.g., for development).
55NO_REBOOT_FILE = '/var/log/factory.noreboot'
56
Jon Salz5c344f62012-07-13 14:31:16 +080057# Value for tests_after_shutdown that forces auto-run (e.g., after
58# a factory update, when the available set of tests might change).
59FORCE_AUTO_RUN = 'force_auto_run'
60
cychiang21886742012-07-05 15:16:32 +080061RUN_QUEUE_TIMEOUT_SECS = 10
62
Jon Salz758e6cc2012-04-03 15:47:07 +080063GOOFY_IN_CHROOT_WARNING = '\n' + ('*' * 70) + '''
64You are running Goofy inside the chroot. Autotests are not supported.
65
66To use Goofy in the chroot, first install an Xvnc server:
67
Jon Salz0697cbf2012-07-04 15:14:04 +080068 sudo apt-get install tightvncserver
Jon Salz758e6cc2012-04-03 15:47:07 +080069
70...and then start a VNC X server outside the chroot:
71
Jon Salz0697cbf2012-07-04 15:14:04 +080072 vncserver :10 &
73 vncviewer :10
Jon Salz758e6cc2012-04-03 15:47:07 +080074
75...and run Goofy as follows:
76
Jon Salz0697cbf2012-07-04 15:14:04 +080077 env --unset=XAUTHORITY DISPLAY=localhost:10 python goofy.py
Jon Salz758e6cc2012-04-03 15:47:07 +080078''' + ('*' * 70)
Jon Salz73e0fd02012-04-04 11:46:38 +080079suppress_chroot_warning = False
Hung-Te Linf2f78f72012-02-08 19:27:11 +080080
81def get_hwid_cfg():
Jon Salz0697cbf2012-07-04 15:14:04 +080082 '''
83 Returns the HWID config tag, or an empty string if none can be found.
84 '''
85 if 'CROS_HWID' in os.environ:
86 return os.environ['CROS_HWID']
87 if os.path.exists(HWID_CFG_PATH):
88 with open(HWID_CFG_PATH, 'rt') as hwid_cfg_handle:
89 return hwid_cfg_handle.read().strip()
90 return ''
Hung-Te Linf2f78f72012-02-08 19:27:11 +080091
92
93def find_test_list():
Jon Salz0697cbf2012-07-04 15:14:04 +080094 '''
95 Returns the path to the active test list, based on the HWID config tag.
96 '''
97 hwid_cfg = get_hwid_cfg()
Hung-Te Linf2f78f72012-02-08 19:27:11 +080098
Jon Salz0697cbf2012-07-04 15:14:04 +080099 search_dirs = [CUSTOM_DIR, DEFAULT_TEST_LISTS_DIR]
Jon Salz2f757d42012-06-27 17:06:42 +0800100
Jon Salz0697cbf2012-07-04 15:14:04 +0800101 # Try in order: test_list_${hwid_cfg}, test_list, test_list.all
102 search_files = ['test_list', 'test_list.all']
103 if hwid_cfg:
104 search_files.insert(0, hwid_cfg)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800105
Jon Salz0697cbf2012-07-04 15:14:04 +0800106 for d in search_dirs:
107 for f in search_files:
108 test_list = os.path.join(d, f)
109 if os.path.exists(test_list):
110 return test_list
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800111
Jon Salz0697cbf2012-07-04 15:14:04 +0800112 logging.warn('Cannot find test lists named any of %s in any of %s',
113 search_files, search_dirs)
114 return None
Jon Salz73e0fd02012-04-04 11:46:38 +0800115
Jon Salz73e0fd02012-04-04 11:46:38 +0800116_inited_logging = False
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800117
118class Goofy(object):
Jon Salz0697cbf2012-07-04 15:14:04 +0800119 '''
120 The main factory flow.
121
122 Note that all methods in this class must be invoked from the main
123 (event) thread. Other threads, such as callbacks and TestInvocation
124 methods, should instead post events on the run queue.
125
126 TODO: Unit tests. (chrome-os-partner:7409)
127
128 Properties:
129 uuid: A unique UUID for this invocation of Goofy.
130 state_instance: An instance of FactoryState.
131 state_server: The FactoryState XML/RPC server.
132 state_server_thread: A thread running state_server.
133 event_server: The EventServer socket server.
134 event_server_thread: A thread running event_server.
135 event_client: A client to the event server.
136 connection_manager: The connection_manager object.
137 network_enabled: Whether the connection_manager is currently
138 enabling connections.
139 ui_process: The factory ui process object.
140 run_queue: A queue of callbacks to invoke from the main thread.
141 invocations: A map from FactoryTest objects to the corresponding
142 TestInvocations objects representing active tests.
143 tests_to_run: A deque of tests that should be run when the current
144 test(s) complete.
145 options: Command-line options.
146 args: Command-line args.
147 test_list: The test list.
148 event_handlers: Map of Event.Type to the method used to handle that
149 event. If the method has an 'event' argument, the event is passed
150 to the handler.
151 exceptions: Exceptions encountered in invocation threads.
152 '''
153 def __init__(self):
154 self.uuid = str(uuid.uuid4())
155 self.state_instance = None
156 self.state_server = None
157 self.state_server_thread = None
Jon Salz16d10542012-07-23 12:18:45 +0800158 self.goofy_rpc = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800159 self.event_server = None
160 self.event_server_thread = None
161 self.event_client = None
162 self.connection_manager = None
Vic Yang4953fc12012-07-26 16:19:53 +0800163 self.charge_manager = None
Jon Salz8fa8e832012-07-13 19:04:09 +0800164 self.time_sanitizer = None
165 self.time_synced = False
Jon Salz0697cbf2012-07-04 15:14:04 +0800166 self.log_watcher = None
167 self.network_enabled = True
168 self.event_log = None
169 self.prespawner = None
170 self.ui_process = None
Jon Salzc79a9982012-08-30 04:42:01 +0800171 self.dummy_shopfloor = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800172 self.run_queue = Queue.Queue()
173 self.invocations = {}
174 self.tests_to_run = deque()
175 self.visible_test = None
176 self.chrome = None
177
178 self.options = None
179 self.args = None
180 self.test_list = None
181 self.on_ui_startup = []
182 self.env = None
Jon Salzb22d1172012-08-06 10:38:57 +0800183 self.last_idle = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800184 self.last_shutdown_time = None
cychiang21886742012-07-05 15:16:32 +0800185 self.last_update_check = None
Jon Salz8fa8e832012-07-13 19:04:09 +0800186 self.last_sync_time = None
Jon Salzb92c5112012-09-21 15:40:11 +0800187 self.last_log_disk_space_time = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800188
Jon Salz85a39882012-07-05 16:45:04 +0800189 def test_or_root(event, parent_or_group=True):
190 '''Returns the test affected by a particular event.
191
192 Args:
193 event: The event containing an optional 'path' attribute.
194 parent_on_group: If True, returns the top-level parent for a test (the
195 root node of the tests that need to be run together if the given test
196 path is to be run).
197 '''
Jon Salz0697cbf2012-07-04 15:14:04 +0800198 try:
199 path = event.path
200 except AttributeError:
201 path = None
202
203 if path:
Jon Salz85a39882012-07-05 16:45:04 +0800204 test = self.test_list.lookup_path(path)
205 if parent_or_group:
206 test = test.get_top_level_parent_or_group()
207 return test
Jon Salz0697cbf2012-07-04 15:14:04 +0800208 else:
209 return self.test_list
210
211 self.event_handlers = {
212 Event.Type.SWITCH_TEST: self.handle_switch_test,
213 Event.Type.SHOW_NEXT_ACTIVE_TEST:
214 lambda event: self.show_next_active_test(),
215 Event.Type.RESTART_TESTS:
216 lambda event: self.restart_tests(root=test_or_root(event)),
217 Event.Type.AUTO_RUN:
218 lambda event: self.auto_run(root=test_or_root(event)),
219 Event.Type.RE_RUN_FAILED:
220 lambda event: self.re_run_failed(root=test_or_root(event)),
221 Event.Type.RUN_TESTS_WITH_STATUS:
222 lambda event: self.run_tests_with_status(
223 event.status,
224 root=test_or_root(event)),
225 Event.Type.REVIEW:
226 lambda event: self.show_review_information(),
227 Event.Type.UPDATE_SYSTEM_INFO:
228 lambda event: self.update_system_info(),
Jon Salz0697cbf2012-07-04 15:14:04 +0800229 Event.Type.STOP:
Jon Salz85a39882012-07-05 16:45:04 +0800230 lambda event: self.stop(root=test_or_root(event, False),
231 fail=getattr(event, 'fail', False)),
Jon Salz36fbbb52012-07-05 13:45:06 +0800232 Event.Type.SET_VISIBLE_TEST:
233 lambda event: self.set_visible_test(
234 self.test_list.lookup_path(event.path)),
Jon Salz0697cbf2012-07-04 15:14:04 +0800235 }
236
237 self.exceptions = []
238 self.web_socket_manager = None
239
240 def destroy(self):
241 if self.chrome:
242 self.chrome.kill()
243 self.chrome = None
Jon Salzc79a9982012-08-30 04:42:01 +0800244 if self.dummy_shopfloor:
245 self.dummy_shopfloor.kill()
246 self.dummy_shopfloor = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800247 if self.ui_process:
248 utils.kill_process_tree(self.ui_process, 'ui')
249 self.ui_process = None
250 if self.web_socket_manager:
251 logging.info('Stopping web sockets')
252 self.web_socket_manager.close()
253 self.web_socket_manager = None
254 if self.state_server_thread:
255 logging.info('Stopping state server')
256 self.state_server.shutdown()
257 self.state_server_thread.join()
258 self.state_server.server_close()
259 self.state_server_thread = None
260 if self.state_instance:
261 self.state_instance.close()
262 if self.event_server_thread:
263 logging.info('Stopping event server')
264 self.event_server.shutdown() # pylint: disable=E1101
265 self.event_server_thread.join()
266 self.event_server.server_close()
267 self.event_server_thread = None
268 if self.log_watcher:
269 if self.log_watcher.IsThreadStarted():
270 self.log_watcher.StopWatchThread()
271 self.log_watcher = None
272 if self.prespawner:
273 logging.info('Stopping prespawner')
274 self.prespawner.stop()
275 self.prespawner = None
276 if self.event_client:
277 logging.info('Closing event client')
278 self.event_client.close()
279 self.event_client = None
280 if self.event_log:
281 self.event_log.Close()
282 self.event_log = None
283 self.check_exceptions()
284 logging.info('Done destroying Goofy')
285
286 def start_state_server(self):
287 self.state_instance, self.state_server = (
288 state.create_server(bind_address='0.0.0.0'))
Jon Salz16d10542012-07-23 12:18:45 +0800289 self.goofy_rpc = GoofyRPC(self)
290 self.goofy_rpc.RegisterMethods(self.state_instance)
Jon Salz0697cbf2012-07-04 15:14:04 +0800291 logging.info('Starting state server')
292 self.state_server_thread = threading.Thread(
293 target=self.state_server.serve_forever,
294 name='StateServer')
295 self.state_server_thread.start()
296
297 def start_event_server(self):
298 self.event_server = EventServer()
299 logging.info('Starting factory event server')
300 self.event_server_thread = threading.Thread(
301 target=self.event_server.serve_forever,
302 name='EventServer') # pylint: disable=E1101
303 self.event_server_thread.start()
304
305 self.event_client = EventClient(
306 callback=self.handle_event, event_loop=self.run_queue)
307
308 self.web_socket_manager = WebSocketManager(self.uuid)
309 self.state_server.add_handler("/event",
310 self.web_socket_manager.handle_web_socket)
311
312 def start_ui(self):
313 ui_proc_args = [
314 os.path.join(factory.FACTORY_PACKAGE_PATH, 'test', 'ui.py'),
315 self.options.test_list]
316 if self.options.verbose:
317 ui_proc_args.append('-v')
318 logging.info('Starting ui %s', ui_proc_args)
Jon Salz78c32392012-07-25 14:18:29 +0800319 self.ui_process = Spawn(ui_proc_args)
Jon Salz0697cbf2012-07-04 15:14:04 +0800320 logging.info('Waiting for UI to come up...')
321 self.event_client.wait(
322 lambda event: event.type == Event.Type.UI_READY)
323 logging.info('UI has started')
324
325 def set_visible_test(self, test):
326 if self.visible_test == test:
327 return
Jon Salz2f2d42c2012-07-30 12:30:34 +0800328 if test and not test.has_ui:
329 return
Jon Salz0697cbf2012-07-04 15:14:04 +0800330
331 if test:
332 test.update_state(visible=True)
333 if self.visible_test:
334 self.visible_test.update_state(visible=False)
335 self.visible_test = test
336
337 def handle_shutdown_complete(self, test, test_state):
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800338 '''
Jon Salz0697cbf2012-07-04 15:14:04 +0800339 Handles the case where a shutdown was detected during a shutdown step.
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800340
Jon Salz0697cbf2012-07-04 15:14:04 +0800341 @param test: The ShutdownStep.
342 @param test_state: The test state.
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800343 '''
Jon Salz0697cbf2012-07-04 15:14:04 +0800344 test_state = test.update_state(increment_shutdown_count=1)
345 logging.info('Detected shutdown (%d of %d)',
346 test_state.shutdown_count, test.iterations)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800347
Jon Salz0697cbf2012-07-04 15:14:04 +0800348 def log_and_update_state(status, error_msg, **kw):
349 self.event_log.Log('rebooted',
350 status=status, error_msg=error_msg, **kw)
351 test.update_state(status=status, error_msg=error_msg)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800352
Jon Salz0697cbf2012-07-04 15:14:04 +0800353 if not self.last_shutdown_time:
354 log_and_update_state(status=TestState.FAILED,
355 error_msg='Unable to read shutdown_time')
356 return
Jon Salz258a40c2012-04-19 12:34:01 +0800357
Jon Salz0697cbf2012-07-04 15:14:04 +0800358 now = time.time()
359 logging.info('%.03f s passed since reboot',
360 now - self.last_shutdown_time)
Jon Salz258a40c2012-04-19 12:34:01 +0800361
Jon Salz0697cbf2012-07-04 15:14:04 +0800362 if self.last_shutdown_time > now:
363 test.update_state(status=TestState.FAILED,
364 error_msg='Time moved backward during reboot')
365 elif (isinstance(test, factory.RebootStep) and
366 self.test_list.options.max_reboot_time_secs and
367 (now - self.last_shutdown_time >
368 self.test_list.options.max_reboot_time_secs)):
369 # A reboot took too long; fail. (We don't check this for
370 # HaltSteps, because the machine could be halted for a
371 # very long time, and even unplugged with battery backup,
372 # thus hosing the clock.)
373 log_and_update_state(
374 status=TestState.FAILED,
375 error_msg=('More than %d s elapsed during reboot '
376 '(%.03f s, from %s to %s)' % (
377 self.test_list.options.max_reboot_time_secs,
378 now - self.last_shutdown_time,
379 utils.TimeString(self.last_shutdown_time),
380 utils.TimeString(now))),
381 duration=(now-self.last_shutdown_time))
382 elif test_state.shutdown_count == test.iterations:
383 # Good!
384 log_and_update_state(status=TestState.PASSED,
385 duration=(now - self.last_shutdown_time),
386 error_msg='')
387 elif test_state.shutdown_count > test.iterations:
388 # Shut down too many times
389 log_and_update_state(status=TestState.FAILED,
390 error_msg='Too many shutdowns')
391 elif utils.are_shift_keys_depressed():
392 logging.info('Shift keys are depressed; cancelling restarts')
393 # Abort shutdown
394 log_and_update_state(
395 status=TestState.FAILED,
396 error_msg='Shutdown aborted with double shift keys')
Jon Salza6711d72012-07-18 14:33:03 +0800397 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +0800398 else:
399 def handler():
400 if self._prompt_cancel_shutdown(
401 test, test_state.shutdown_count + 1):
Jon Salza6711d72012-07-18 14:33:03 +0800402 factory.console.info('Shutdown aborted by operator')
Jon Salz0697cbf2012-07-04 15:14:04 +0800403 log_and_update_state(
404 status=TestState.FAILED,
405 error_msg='Shutdown aborted by operator')
Jon Salza6711d72012-07-18 14:33:03 +0800406 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +0800407 return
Jon Salz0405ab52012-03-16 15:26:52 +0800408
Jon Salz0697cbf2012-07-04 15:14:04 +0800409 # Time to shutdown again
410 log_and_update_state(
411 status=TestState.ACTIVE,
412 error_msg='',
413 iteration=test_state.shutdown_count)
Jon Salz73e0fd02012-04-04 11:46:38 +0800414
Jon Salz0697cbf2012-07-04 15:14:04 +0800415 self.event_log.Log('shutdown', operation='reboot')
416 self.state_instance.set_shared_data('shutdown_time',
417 time.time())
418 self.env.shutdown('reboot')
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800419
Jon Salz0697cbf2012-07-04 15:14:04 +0800420 self.on_ui_startup.append(handler)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800421
Jon Salz0697cbf2012-07-04 15:14:04 +0800422 def _prompt_cancel_shutdown(self, test, iteration):
423 if self.options.ui != 'chrome':
424 return False
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800425
Jon Salz0697cbf2012-07-04 15:14:04 +0800426 pending_shutdown_data = {
427 'delay_secs': test.delay_secs,
428 'time': time.time() + test.delay_secs,
429 'operation': test.operation,
430 'iteration': iteration,
431 'iterations': test.iterations,
432 }
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800433
Jon Salz0697cbf2012-07-04 15:14:04 +0800434 # Create a new (threaded) event client since we
435 # don't want to use the event loop for this.
436 with EventClient() as event_client:
437 event_client.post_event(Event(Event.Type.PENDING_SHUTDOWN,
438 **pending_shutdown_data))
439 aborted = event_client.wait(
440 lambda event: event.type == Event.Type.CANCEL_SHUTDOWN,
441 timeout=test.delay_secs) is not None
442 if aborted:
443 event_client.post_event(Event(Event.Type.PENDING_SHUTDOWN))
444 return aborted
Jon Salz258a40c2012-04-19 12:34:01 +0800445
Jon Salz0697cbf2012-07-04 15:14:04 +0800446 def init_states(self):
447 '''
448 Initializes all states on startup.
449 '''
450 for test in self.test_list.get_all_tests():
451 # Make sure the state server knows about all the tests,
452 # defaulting to an untested state.
453 test.update_state(update_parent=False, visible=False)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800454
Jon Salz0697cbf2012-07-04 15:14:04 +0800455 var_log_messages = None
Vic Yanga9c32212012-08-16 20:07:54 +0800456 mosys_log = None
Vic Yange4c275d2012-08-28 01:50:20 +0800457 ec_console_log = None
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800458
Jon Salz0697cbf2012-07-04 15:14:04 +0800459 # Any 'active' tests should be marked as failed now.
460 for test in self.test_list.walk():
Jon Salza6711d72012-07-18 14:33:03 +0800461 if not test.is_leaf():
462 # Don't bother with parents; they will be updated when their
463 # children are updated.
464 continue
465
Jon Salz0697cbf2012-07-04 15:14:04 +0800466 test_state = test.get_state()
467 if test_state.status != TestState.ACTIVE:
468 continue
469 if isinstance(test, factory.ShutdownStep):
470 # Shutdown while the test was active - that's good.
471 self.handle_shutdown_complete(test, test_state)
472 else:
473 # Unexpected shutdown. Grab /var/log/messages for context.
474 if var_log_messages is None:
475 try:
476 var_log_messages = (
477 utils.var_log_messages_before_reboot())
478 # Write it to the log, to make it easier to
479 # correlate with /var/log/messages.
480 logging.info(
481 'Unexpected shutdown. '
482 'Tail of /var/log/messages before last reboot:\n'
483 '%s', ('\n'.join(
484 ' ' + x for x in var_log_messages)))
485 except: # pylint: disable=W0702
486 logging.exception('Unable to grok /var/log/messages')
487 var_log_messages = []
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800488
Jon Salz008f4ea2012-08-28 05:39:45 +0800489 if mosys_log is None and not utils.in_chroot():
490 try:
491 mosys_log = utils.Spawn(
492 ['mosys', 'eventlog', 'list'],
493 read_stdout=True, log_stderr_on_error=True).stdout_data
494 # Write it to the log also.
495 logging.info('System eventlog from mosys:\n%s\n', mosys_log)
496 except: # pylint: disable=W0702
497 logging.exception('Unable to read mosys eventlog')
Vic Yanga9c32212012-08-16 20:07:54 +0800498
Vic Yange4c275d2012-08-28 01:50:20 +0800499 if ec_console_log is None:
500 try:
501 ec = system.GetEC()
502 ec_console_log = ec.GetConsoleLog()
503 logging.info('EC console log after reboot:\n%s\n', ec_console_log)
Jon Salzfe1f6652012-09-07 05:40:14 +0800504 except: # pylint: disable=W0702
Vic Yange4c275d2012-08-28 01:50:20 +0800505 logging.exception('Error retrieving EC console log')
506
Jon Salz0697cbf2012-07-04 15:14:04 +0800507 error_msg = 'Unexpected shutdown while test was running'
508 self.event_log.Log('end_test',
509 path=test.path,
510 status=TestState.FAILED,
511 invocation=test.get_state().invocation,
512 error_msg=error_msg,
Vic Yanga9c32212012-08-16 20:07:54 +0800513 var_log_messages='\n'.join(var_log_messages),
514 mosys_log=mosys_log)
Jon Salz0697cbf2012-07-04 15:14:04 +0800515 test.update_state(
516 status=TestState.FAILED,
517 error_msg=error_msg)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800518
Jon Salz50efe942012-07-26 11:54:10 +0800519 if not test.never_fails:
520 # For "never_fails" tests (such as "Start"), don't cancel
521 # pending tests, since reboot is expected.
522 factory.console.info('Unexpected shutdown while test %s '
523 'running; cancelling any pending tests',
524 test.path)
525 self.state_instance.set_shared_data('tests_after_shutdown', [])
Jon Salz69806bb2012-07-20 18:05:02 +0800526
Jon Salz008f4ea2012-08-28 05:39:45 +0800527 self.update_skipped_tests()
528
529 def update_skipped_tests(self):
530 '''
531 Updates skipped states based on run_if.
532 '''
533 for t in self.test_list.walk():
534 if t.is_leaf() and t.run_if_table_name:
535 skip = False
536 try:
537 aux = shopfloor.get_selected_aux_data(t.run_if_table_name)
538 value = aux.get(t.run_if_col)
539 if value is not None:
540 skip = (not value) ^ t.run_if_not
541 except ValueError:
542 # Not available; assume it shouldn't be skipped
543 pass
544
545 test_state = t.get_state()
546 if ((not skip) and
547 (test_state.status == TestState.PASSED) and
548 (test_state.error_msg == TestState.SKIPPED_MSG)):
549 # It was marked as skipped before, but now we need to run it.
550 # Mark as untested.
551 t.update_state(skip=skip, status=TestState.UNTESTED, error_msg='')
552 else:
553 t.update_state(skip=skip)
554
Jon Salz0697cbf2012-07-04 15:14:04 +0800555 def show_next_active_test(self):
556 '''
557 Rotates to the next visible active test.
558 '''
559 self.reap_completed_tests()
560 active_tests = [
561 t for t in self.test_list.walk()
562 if t.is_leaf() and t.get_state().status == TestState.ACTIVE]
563 if not active_tests:
564 return
Jon Salz4f6c7172012-06-11 20:45:36 +0800565
Jon Salz0697cbf2012-07-04 15:14:04 +0800566 try:
567 next_test = active_tests[
568 (active_tests.index(self.visible_test) + 1) % len(active_tests)]
569 except ValueError: # visible_test not present in active_tests
570 next_test = active_tests[0]
Jon Salz4f6c7172012-06-11 20:45:36 +0800571
Jon Salz0697cbf2012-07-04 15:14:04 +0800572 self.set_visible_test(next_test)
Jon Salz4f6c7172012-06-11 20:45:36 +0800573
Jon Salz0697cbf2012-07-04 15:14:04 +0800574 def handle_event(self, event):
575 '''
576 Handles an event from the event server.
577 '''
578 handler = self.event_handlers.get(event.type)
579 if handler:
580 handler(event)
581 else:
582 # We don't register handlers for all event types - just ignore
583 # this event.
584 logging.debug('Unbound event type %s', event.type)
Jon Salz4f6c7172012-06-11 20:45:36 +0800585
Jon Salz0697cbf2012-07-04 15:14:04 +0800586 def run_next_test(self):
587 '''
588 Runs the next eligible test (or tests) in self.tests_to_run.
589 '''
590 self.reap_completed_tests()
591 while self.tests_to_run:
592 logging.debug('Tests to run: %s',
593 [x.path for x in self.tests_to_run])
Jon Salz94eb56f2012-06-12 18:01:12 +0800594
Jon Salz0697cbf2012-07-04 15:14:04 +0800595 test = self.tests_to_run[0]
Jon Salz94eb56f2012-06-12 18:01:12 +0800596
Jon Salz0697cbf2012-07-04 15:14:04 +0800597 if test in self.invocations:
598 logging.info('Next test %s is already running', test.path)
599 self.tests_to_run.popleft()
600 return
Jon Salz94eb56f2012-06-12 18:01:12 +0800601
Jon Salz008f4ea2012-08-28 05:39:45 +0800602 if test.get_state().skip:
603 factory.console.info('Skipping test %s', test.path)
604 test.update_state(status=TestState.PASSED,
605 error_msg=TestState.SKIPPED_MSG)
606 self.tests_to_run.popleft()
607 return
608
Jon Salza1412922012-07-23 16:04:17 +0800609 for requirement in test.require_run:
610 for i in requirement.test.walk():
611 if i.get_state().status == TestState.ACTIVE:
Jon Salz304a75d2012-07-06 11:14:15 +0800612 logging.info('Waiting for active test %s to complete '
Jon Salza1412922012-07-23 16:04:17 +0800613 'before running %s', i.path, test.path)
Jon Salz304a75d2012-07-06 11:14:15 +0800614 return
615
Jon Salz0697cbf2012-07-04 15:14:04 +0800616 if self.invocations and not (test.backgroundable and all(
617 [x.backgroundable for x in self.invocations])):
618 logging.debug('Waiting for non-backgroundable tests to '
619 'complete before running %s', test.path)
620 return
Jon Salz94eb56f2012-06-12 18:01:12 +0800621
Jon Salz0697cbf2012-07-04 15:14:04 +0800622 self.tests_to_run.popleft()
Jon Salz94eb56f2012-06-12 18:01:12 +0800623
Jon Salz304a75d2012-07-06 11:14:15 +0800624 untested = set()
Jon Salza1412922012-07-23 16:04:17 +0800625 for requirement in test.require_run:
626 for i in requirement.test.walk():
627 if i == test:
Jon Salz304a75d2012-07-06 11:14:15 +0800628 # We've hit this test itself; stop checking
629 break
Jon Salza1412922012-07-23 16:04:17 +0800630 if ((i.get_state().status == TestState.UNTESTED) or
631 (requirement.passed and i.get_state().status !=
632 TestState.PASSED)):
Jon Salz304a75d2012-07-06 11:14:15 +0800633 # Found an untested test; move on to the next
634 # element in require_run.
Jon Salza1412922012-07-23 16:04:17 +0800635 untested.add(i)
Jon Salz304a75d2012-07-06 11:14:15 +0800636 break
637
638 if untested:
639 untested_paths = ', '.join(sorted([x.path for x in untested]))
640 if self.state_instance.get_shared_data('engineering_mode',
641 optional=True):
642 # In engineering mode, we'll let it go.
643 factory.console.warn('In engineering mode; running '
644 '%s even though required tests '
645 '[%s] have not completed',
646 test.path, untested_paths)
647 else:
648 # Not in engineering mode; mark it failed.
649 error_msg = ('Required tests [%s] have not been run yet'
650 % untested_paths)
651 factory.console.error('Not running %s: %s',
652 test.path, error_msg)
653 test.update_state(status=TestState.FAILED,
654 error_msg=error_msg)
655 continue
656
Jon Salz0697cbf2012-07-04 15:14:04 +0800657 if isinstance(test, factory.ShutdownStep):
658 if os.path.exists(NO_REBOOT_FILE):
659 test.update_state(
660 status=TestState.FAILED, increment_count=1,
661 error_msg=('Skipped shutdown since %s is present' %
Jon Salz304a75d2012-07-06 11:14:15 +0800662 NO_REBOOT_FILE))
Jon Salz0697cbf2012-07-04 15:14:04 +0800663 continue
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800664
Jon Salz0697cbf2012-07-04 15:14:04 +0800665 test.update_state(status=TestState.ACTIVE, increment_count=1,
666 error_msg='', shutdown_count=0)
667 if self._prompt_cancel_shutdown(test, 1):
668 self.event_log.Log('reboot_cancelled')
669 test.update_state(
670 status=TestState.FAILED, increment_count=1,
671 error_msg='Shutdown aborted by operator',
672 shutdown_count=0)
chungyiafe8f772012-08-15 19:36:29 +0800673 continue
Jon Salz2f757d42012-06-27 17:06:42 +0800674
Jon Salz0697cbf2012-07-04 15:14:04 +0800675 # Save pending test list in the state server
Jon Salzdbf398f2012-06-14 17:30:01 +0800676 self.state_instance.set_shared_data(
Jon Salz0697cbf2012-07-04 15:14:04 +0800677 'tests_after_shutdown',
678 [t.path for t in self.tests_to_run])
679 # Save shutdown time
680 self.state_instance.set_shared_data('shutdown_time',
681 time.time())
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800682
Jon Salz0697cbf2012-07-04 15:14:04 +0800683 with self.env.lock:
684 self.event_log.Log('shutdown', operation=test.operation)
685 shutdown_result = self.env.shutdown(test.operation)
686 if shutdown_result:
687 # That's all, folks!
688 self.run_queue.put(None)
689 return
690 else:
691 # Just pass (e.g., in the chroot).
692 test.update_state(status=TestState.PASSED)
693 self.state_instance.set_shared_data(
694 'tests_after_shutdown', None)
695 # Send event with no fields to indicate that there is no
696 # longer a pending shutdown.
697 self.event_client.post_event(Event(
698 Event.Type.PENDING_SHUTDOWN))
699 continue
Jon Salz258a40c2012-04-19 12:34:01 +0800700
Jon Salz1acc8742012-07-17 17:45:55 +0800701 self._run_test(test, test.iterations)
702
703 def _run_test(self, test, iterations_left=None):
704 invoc = TestInvocation(self, test, on_completion=self.run_next_test)
705 new_state = test.update_state(
706 status=TestState.ACTIVE, increment_count=1, error_msg='',
Jon Salzbd42ce12012-09-18 08:03:59 +0800707 invocation=invoc.uuid, iterations_left=iterations_left,
708 visible=(self.visible_test == test))
Jon Salz1acc8742012-07-17 17:45:55 +0800709 invoc.count = new_state.count
710
711 self.invocations[test] = invoc
712 if self.visible_test is None and test.has_ui:
713 self.set_visible_test(test)
714 self.check_connection_manager()
715 invoc.start()
Jon Salz5f2a0672012-05-22 17:14:06 +0800716
Jon Salz0697cbf2012-07-04 15:14:04 +0800717 def check_connection_manager(self):
718 exclusive_tests = [
719 test.path
720 for test in self.invocations
721 if test.is_exclusive(
722 factory.FactoryTest.EXCLUSIVE_OPTIONS.NETWORKING)]
723 if exclusive_tests:
724 # Make sure networking is disabled.
725 if self.network_enabled:
726 logging.info('Disabling network, as requested by %s',
727 exclusive_tests)
728 self.connection_manager.DisableNetworking()
729 self.network_enabled = False
730 else:
731 # Make sure networking is enabled.
732 if not self.network_enabled:
733 logging.info('Re-enabling network')
734 self.connection_manager.EnableNetworking()
735 self.network_enabled = True
Jon Salz5da61e62012-05-31 13:06:22 +0800736
cychiang21886742012-07-05 15:16:32 +0800737 def check_for_updates(self):
738 '''
739 Schedules an asynchronous check for updates if necessary.
740 '''
741 if not self.test_list.options.update_period_secs:
742 # Not enabled.
743 return
744
745 now = time.time()
746 if self.last_update_check and (
747 now - self.last_update_check <
748 self.test_list.options.update_period_secs):
749 # Not yet time for another check.
750 return
751
752 self.last_update_check = now
753
754 def handle_check_for_update(reached_shopfloor, md5sum, needs_update):
755 if reached_shopfloor:
756 new_update_md5sum = md5sum if needs_update else None
757 if system.SystemInfo.update_md5sum != new_update_md5sum:
758 logging.info('Received new update MD5SUM: %s', new_update_md5sum)
759 system.SystemInfo.update_md5sum = new_update_md5sum
760 self.run_queue.put(self.update_system_info)
761
762 updater.CheckForUpdateAsync(
763 handle_check_for_update,
764 self.test_list.options.shopfloor_timeout_secs)
765
Jon Salza6711d72012-07-18 14:33:03 +0800766 def cancel_pending_tests(self):
767 '''Cancels any tests in the run queue.'''
768 self.run_tests([])
769
Jon Salz0697cbf2012-07-04 15:14:04 +0800770 def run_tests(self, subtrees, untested_only=False):
771 '''
772 Runs tests under subtree.
Jon Salz258a40c2012-04-19 12:34:01 +0800773
Jon Salz0697cbf2012-07-04 15:14:04 +0800774 The tests are run in order unless one fails (then stops).
775 Backgroundable tests are run simultaneously; when a foreground test is
776 encountered, we wait for all active tests to finish before continuing.
Jon Salzb1b39092012-05-03 02:05:09 +0800777
Jon Salz0697cbf2012-07-04 15:14:04 +0800778 @param subtrees: Node or nodes containing tests to run (may either be
779 a single test or a list). Duplicates will be ignored.
780 '''
781 if type(subtrees) != list:
782 subtrees = [subtrees]
Jon Salz258a40c2012-04-19 12:34:01 +0800783
Jon Salz0697cbf2012-07-04 15:14:04 +0800784 # Nodes we've seen so far, to avoid duplicates.
785 seen = set()
Jon Salz94eb56f2012-06-12 18:01:12 +0800786
Jon Salz0697cbf2012-07-04 15:14:04 +0800787 self.tests_to_run = deque()
788 for subtree in subtrees:
789 for test in subtree.walk():
790 if test in seen:
791 continue
792 seen.add(test)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800793
Jon Salz0697cbf2012-07-04 15:14:04 +0800794 if not test.is_leaf():
795 continue
796 if (untested_only and
797 test.get_state().status != TestState.UNTESTED):
798 continue
799 self.tests_to_run.append(test)
800 self.run_next_test()
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800801
Jon Salz0697cbf2012-07-04 15:14:04 +0800802 def reap_completed_tests(self):
803 '''
804 Removes completed tests from the set of active tests.
805
806 Also updates the visible test if it was reaped.
807 '''
808 for t, v in dict(self.invocations).iteritems():
809 if v.is_completed():
Jon Salz1acc8742012-07-17 17:45:55 +0800810 new_state = t.update_state(**v.update_state_on_completion)
Jon Salz0697cbf2012-07-04 15:14:04 +0800811 del self.invocations[t]
812
Chun-Ta Lin54e17e42012-09-06 22:05:13 +0800813 # Stop on failure if flag is true.
814 if (self.test_list.options.stop_on_failure and
815 new_state.status == TestState.FAILED):
816 # Clean all the tests to cause goofy to stop.
817 self.tests_to_run = []
818 factory.console.info("Stop on failure triggered. Empty the queue.")
819
Jon Salz1acc8742012-07-17 17:45:55 +0800820 if new_state.iterations_left and new_state.status == TestState.PASSED:
821 # Play it again, Sam!
822 self._run_test(t)
823
Jon Salz0697cbf2012-07-04 15:14:04 +0800824 if (self.visible_test is None or
Jon Salz85a39882012-07-05 16:45:04 +0800825 self.visible_test not in self.invocations):
Jon Salz0697cbf2012-07-04 15:14:04 +0800826 self.set_visible_test(None)
827 # Make the first running test, if any, the visible test
828 for t in self.test_list.walk():
829 if t in self.invocations:
830 self.set_visible_test(t)
831 break
832
Jon Salz85a39882012-07-05 16:45:04 +0800833 def kill_active_tests(self, abort, root=None):
Jon Salz0697cbf2012-07-04 15:14:04 +0800834 '''
835 Kills and waits for all active tests.
836
Jon Salz85a39882012-07-05 16:45:04 +0800837 Args:
838 abort: True to change state of killed tests to FAILED, False for
Jon Salz0697cbf2012-07-04 15:14:04 +0800839 UNTESTED.
Jon Salz85a39882012-07-05 16:45:04 +0800840 root: If set, only kills tests with root as an ancestor.
Jon Salz0697cbf2012-07-04 15:14:04 +0800841 '''
842 self.reap_completed_tests()
843 for test, invoc in self.invocations.items():
Jon Salz85a39882012-07-05 16:45:04 +0800844 if root and not test.has_ancestor(root):
845 continue
846
Jon Salz0697cbf2012-07-04 15:14:04 +0800847 factory.console.info('Killing active test %s...' % test.path)
848 invoc.abort_and_join()
849 factory.console.info('Killed %s' % test.path)
Jon Salz1acc8742012-07-17 17:45:55 +0800850 test.update_state(**invoc.update_state_on_completion)
Jon Salz0697cbf2012-07-04 15:14:04 +0800851 del self.invocations[test]
Jon Salz1acc8742012-07-17 17:45:55 +0800852
Jon Salz0697cbf2012-07-04 15:14:04 +0800853 if not abort:
854 test.update_state(status=TestState.UNTESTED)
855 self.reap_completed_tests()
856
Jon Salz85a39882012-07-05 16:45:04 +0800857 def stop(self, root=None, fail=False):
858 self.kill_active_tests(fail, root)
859 # Remove any tests in the run queue under the root.
860 self.tests_to_run = deque([x for x in self.tests_to_run
861 if root and not x.has_ancestor(root)])
862 self.run_next_test()
Jon Salz0697cbf2012-07-04 15:14:04 +0800863
864 def abort_active_tests(self):
865 self.kill_active_tests(True)
866
867 def main(self):
868 try:
869 self.init()
870 self.event_log.Log('goofy_init',
871 success=True)
872 except:
873 if self.event_log:
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800874 try:
Jon Salz0697cbf2012-07-04 15:14:04 +0800875 self.event_log.Log('goofy_init',
876 success=False,
877 trace=traceback.format_exc())
878 except: # pylint: disable=W0702
879 pass
880 raise
881
882 self.run()
883
884 def update_system_info(self):
885 '''Updates system info.'''
886 system_info = system.SystemInfo()
887 self.state_instance.set_shared_data('system_info', system_info.__dict__)
888 self.event_client.post_event(Event(Event.Type.SYSTEM_INFO,
889 system_info=system_info.__dict__))
890 logging.info('System info: %r', system_info.__dict__)
891
Jon Salzeb42f0d2012-07-27 19:14:04 +0800892 def update_factory(self, auto_run_on_restart=False, post_update_hook=None):
893 '''Commences updating factory software.
894
895 Args:
896 auto_run_on_restart: Auto-run when the machine comes back up.
897 post_update_hook: Code to call after update but immediately before
898 restart.
899
900 Returns:
901 Never if the update was successful (we just reboot).
902 False if the update was unnecessary (no update available).
903 '''
Jon Salz0697cbf2012-07-04 15:14:04 +0800904 self.kill_active_tests(False)
Jon Salza6711d72012-07-18 14:33:03 +0800905 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +0800906
Jon Salz5c344f62012-07-13 14:31:16 +0800907 def pre_update_hook():
908 if auto_run_on_restart:
909 self.state_instance.set_shared_data('tests_after_shutdown',
910 FORCE_AUTO_RUN)
911 self.state_instance.close()
912
Jon Salzeb42f0d2012-07-27 19:14:04 +0800913 if updater.TryUpdate(pre_update_hook=pre_update_hook):
914 if post_update_hook:
915 post_update_hook()
916 self.env.shutdown('reboot')
Jon Salz0697cbf2012-07-04 15:14:04 +0800917
Jon Salzcef132a2012-08-30 04:58:08 +0800918 def handle_sigint(self, dummy_signum, dummy_frame):
Jon Salz77c151e2012-08-28 07:20:37 +0800919 logging.error('Received SIGINT')
920 self.run_queue.put(None)
921 raise KeyboardInterrupt()
922
Jon Salz0697cbf2012-07-04 15:14:04 +0800923 def init(self, args=None, env=None):
924 '''Initializes Goofy.
925
926 Args:
927 args: A list of command-line arguments. Uses sys.argv if
928 args is None.
929 env: An Environment instance to use (or None to choose
930 FakeChrootEnvironment or DUTEnvironment as appropriate).
931 '''
Jon Salz77c151e2012-08-28 07:20:37 +0800932 signal.signal(signal.SIGINT, self.handle_sigint)
933
Jon Salz0697cbf2012-07-04 15:14:04 +0800934 parser = OptionParser()
935 parser.add_option('-v', '--verbose', dest='verbose',
Jon Salz8fa8e832012-07-13 19:04:09 +0800936 action='store_true',
937 help='Enable debug logging')
Jon Salz0697cbf2012-07-04 15:14:04 +0800938 parser.add_option('--print_test_list', dest='print_test_list',
Jon Salz8fa8e832012-07-13 19:04:09 +0800939 metavar='FILE',
940 help='Read and print test list FILE, and exit')
Jon Salz0697cbf2012-07-04 15:14:04 +0800941 parser.add_option('--restart', dest='restart',
Jon Salz8fa8e832012-07-13 19:04:09 +0800942 action='store_true',
943 help='Clear all test state')
Jon Salz0697cbf2012-07-04 15:14:04 +0800944 parser.add_option('--ui', dest='ui', type='choice',
Jon Salz8fa8e832012-07-13 19:04:09 +0800945 choices=['none', 'gtk', 'chrome'],
946 default=('chrome' if utils.in_chroot() else 'gtk'),
947 help='UI to use')
Jon Salz0697cbf2012-07-04 15:14:04 +0800948 parser.add_option('--ui_scale_factor', dest='ui_scale_factor',
Jon Salz8fa8e832012-07-13 19:04:09 +0800949 type='int', default=1,
950 help=('Factor by which to scale UI '
951 '(Chrome UI only)'))
Jon Salz0697cbf2012-07-04 15:14:04 +0800952 parser.add_option('--test_list', dest='test_list',
Jon Salz8fa8e832012-07-13 19:04:09 +0800953 metavar='FILE',
954 help='Use FILE as test list')
Jon Salzc79a9982012-08-30 04:42:01 +0800955 parser.add_option('--dummy_shopfloor', action='store_true',
956 help='Use a dummy shopfloor server')
chungyiafe8f772012-08-15 19:36:29 +0800957 parser.add_option('--automation', dest='automation',
958 action='store_true',
959 help='Enable automation on running factory test')
Jon Salz0697cbf2012-07-04 15:14:04 +0800960 (self.options, self.args) = parser.parse_args(args)
961
Jon Salz46b89562012-07-05 11:49:22 +0800962 # Make sure factory directories exist.
963 factory.get_log_root()
964 factory.get_state_root()
965 factory.get_test_data_root()
966
Jon Salz0697cbf2012-07-04 15:14:04 +0800967 global _inited_logging # pylint: disable=W0603
968 if not _inited_logging:
969 factory.init_logging('goofy', verbose=self.options.verbose)
970 _inited_logging = True
Jon Salz8fa8e832012-07-13 19:04:09 +0800971
Jon Salzee85d522012-07-17 14:34:46 +0800972 event_log.IncrementBootSequence()
Jon Salz0697cbf2012-07-04 15:14:04 +0800973 self.event_log = EventLog('goofy')
974
975 if (not suppress_chroot_warning and
976 factory.in_chroot() and
977 self.options.ui == 'gtk' and
978 os.environ.get('DISPLAY') in [None, '', ':0', ':0.0']):
979 # That's not going to work! Tell the user how to run
980 # this way.
981 logging.warn(GOOFY_IN_CHROOT_WARNING)
982 time.sleep(1)
983
984 if env:
985 self.env = env
986 elif factory.in_chroot():
987 self.env = test_environment.FakeChrootEnvironment()
988 logging.warn(
989 'Using chroot environment: will not actually run autotests')
990 else:
991 self.env = test_environment.DUTEnvironment()
992 self.env.goofy = self
993
994 if self.options.restart:
995 state.clear_state()
996
997 if self.options.print_test_list:
Jon Salzeb42f0d2012-07-27 19:14:04 +0800998 print factory.read_test_list(
999 self.options.print_test_list).__repr__(recursive=True)
Jon Salz0697cbf2012-07-04 15:14:04 +08001000 return
1001
1002 if self.options.ui_scale_factor != 1 and utils.in_qemu():
1003 logging.warn(
1004 'In QEMU; ignoring ui_scale_factor argument')
1005 self.options.ui_scale_factor = 1
1006
1007 logging.info('Started')
1008
1009 self.start_state_server()
1010 self.state_instance.set_shared_data('hwid_cfg', get_hwid_cfg())
1011 self.state_instance.set_shared_data('ui_scale_factor',
1012 self.options.ui_scale_factor)
1013 self.last_shutdown_time = (
1014 self.state_instance.get_shared_data('shutdown_time', optional=True))
1015 self.state_instance.del_shared_data('shutdown_time', optional=True)
1016
1017 if not self.options.test_list:
1018 self.options.test_list = find_test_list()
1019 if not self.options.test_list:
1020 logging.error('No test list. Aborting.')
1021 sys.exit(1)
1022 logging.info('Using test list %s', self.options.test_list)
1023
1024 self.test_list = factory.read_test_list(
1025 self.options.test_list,
Jon Salzeb42f0d2012-07-27 19:14:04 +08001026 self.state_instance)
Jon Salz0697cbf2012-07-04 15:14:04 +08001027 if not self.state_instance.has_shared_data('ui_lang'):
1028 self.state_instance.set_shared_data('ui_lang',
1029 self.test_list.options.ui_lang)
1030 self.state_instance.set_shared_data(
1031 'test_list_options',
1032 self.test_list.options.__dict__)
1033 self.state_instance.test_list = self.test_list
1034
Jon Salz23926422012-09-01 03:38:13 +08001035 if self.options.dummy_shopfloor:
1036 os.environ[shopfloor.SHOPFLOOR_SERVER_ENV_VAR_NAME] = (
1037 'http://localhost:%d/' % shopfloor.DEFAULT_SERVER_PORT)
1038 self.dummy_shopfloor = Spawn(
1039 [os.path.join(factory.FACTORY_PATH, 'bin', 'shopfloor_server'),
1040 '--dummy'])
1041 elif self.test_list.options.shopfloor_server_url:
1042 shopfloor.set_server_url(self.test_list.options.shopfloor_server_url)
1043
Jon Salz8fa8e832012-07-13 19:04:09 +08001044 if self.test_list.options.time_sanitizer:
1045 self.time_sanitizer = time_sanitizer.TimeSanitizer(
1046 base_time=time_sanitizer.GetBaseTimeFromFile(
1047 # lsb-factory is written by the factory install shim during
1048 # installation, so it should have a good time obtained from
Jon Salz54882d02012-08-31 01:57:54 +08001049 # the mini-Omaha server. If it's not available, we'll use
1050 # /etc/lsb-factory (which will be much older, but reasonably
1051 # sane) and rely on a shopfloor sync to set a more accurate
1052 # time.
1053 '/usr/local/etc/lsb-factory',
1054 '/etc/lsb-release'))
Jon Salz8fa8e832012-07-13 19:04:09 +08001055 self.time_sanitizer.RunOnce()
1056
Jon Salz0697cbf2012-07-04 15:14:04 +08001057 self.init_states()
1058 self.start_event_server()
1059 self.connection_manager = self.env.create_connection_manager(
Tai-Hsu Lin371351a2012-08-27 14:17:14 +08001060 self.test_list.options.wlans,
1061 self.test_list.options.scan_wifi_period_secs)
Jon Salz0697cbf2012-07-04 15:14:04 +08001062 # Note that we create a log watcher even if
1063 # sync_event_log_period_secs isn't set (no background
1064 # syncing), since we may use it to flush event logs as well.
1065 self.log_watcher = EventLogWatcher(
1066 self.test_list.options.sync_event_log_period_secs,
Jon Salz16d10542012-07-23 12:18:45 +08001067 handle_event_logs_callback=self.handle_event_logs)
Jon Salz0697cbf2012-07-04 15:14:04 +08001068 if self.test_list.options.sync_event_log_period_secs:
1069 self.log_watcher.StartWatchThread()
1070
1071 self.update_system_info()
1072
Vic Yang4953fc12012-07-26 16:19:53 +08001073 assert ((self.test_list.options.min_charge_pct is None) ==
1074 (self.test_list.options.max_charge_pct is None))
1075 if (self.test_list.options.min_charge_pct and
1076 self.test_list.options.max_charge_pct):
1077 self.charge_manager = ChargeManager(self.test_list.options.min_charge_pct,
1078 self.test_list.options.max_charge_pct)
1079
Jon Salz0697cbf2012-07-04 15:14:04 +08001080 os.environ['CROS_FACTORY'] = '1'
1081 os.environ['CROS_DISABLE_SITE_SYSINFO'] = '1'
1082
1083 # Set CROS_UI since some behaviors in ui.py depend on the
1084 # particular UI in use. TODO(jsalz): Remove this (and all
1085 # places it is used) when the GTK UI is removed.
1086 os.environ['CROS_UI'] = self.options.ui
1087
1088 if self.options.ui == 'chrome':
1089 self.env.launch_chrome()
1090 logging.info('Waiting for a web socket connection')
1091 self.web_socket_manager.wait()
1092
1093 # Wait for the test widget size to be set; this is done in
1094 # an asynchronous RPC so there is a small chance that the
1095 # web socket might be opened first.
1096 for _ in range(100): # 10 s
1097 try:
1098 if self.state_instance.get_shared_data('test_widget_size'):
1099 break
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001100 except KeyError:
Jon Salz0697cbf2012-07-04 15:14:04 +08001101 pass # Retry
1102 time.sleep(0.1) # 100 ms
1103 else:
1104 logging.warn('Never received test_widget_size from UI')
1105 elif self.options.ui == 'gtk':
1106 self.start_ui()
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001107
Jon Salz0697cbf2012-07-04 15:14:04 +08001108 def state_change_callback(test, test_state):
1109 self.event_client.post_event(
1110 Event(Event.Type.STATE_CHANGE,
1111 path=test.path, state=test_state))
1112 self.test_list.state_change_callback = state_change_callback
Jon Salz73e0fd02012-04-04 11:46:38 +08001113
Jon Salza6711d72012-07-18 14:33:03 +08001114 for handler in self.on_ui_startup:
1115 handler()
1116
1117 self.prespawner = Prespawner()
1118 self.prespawner.start()
1119
Jon Salz0697cbf2012-07-04 15:14:04 +08001120 try:
1121 tests_after_shutdown = self.state_instance.get_shared_data(
1122 'tests_after_shutdown')
1123 except KeyError:
1124 tests_after_shutdown = None
Jon Salz57717ca2012-04-04 16:47:25 +08001125
Jon Salz5c344f62012-07-13 14:31:16 +08001126 force_auto_run = (tests_after_shutdown == FORCE_AUTO_RUN)
1127 if not force_auto_run and tests_after_shutdown is not None:
Jon Salz0697cbf2012-07-04 15:14:04 +08001128 logging.info('Resuming tests after shutdown: %s',
1129 tests_after_shutdown)
Jon Salz0697cbf2012-07-04 15:14:04 +08001130 self.tests_to_run.extend(
1131 self.test_list.lookup_path(t) for t in tests_after_shutdown)
1132 self.run_queue.put(self.run_next_test)
1133 else:
Jon Salz5c344f62012-07-13 14:31:16 +08001134 if force_auto_run or self.test_list.options.auto_run_on_start:
Jon Salz0697cbf2012-07-04 15:14:04 +08001135 self.run_queue.put(
1136 lambda: self.run_tests(self.test_list, untested_only=True))
Jon Salz5c344f62012-07-13 14:31:16 +08001137 self.state_instance.set_shared_data('tests_after_shutdown', None)
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001138
Jon Salz0697cbf2012-07-04 15:14:04 +08001139 def run(self):
1140 '''Runs Goofy.'''
1141 # Process events forever.
1142 while self.run_once(True):
1143 pass
Jon Salz73e0fd02012-04-04 11:46:38 +08001144
Jon Salz0697cbf2012-07-04 15:14:04 +08001145 def run_once(self, block=False):
1146 '''Runs all items pending in the event loop.
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001147
Jon Salz0697cbf2012-07-04 15:14:04 +08001148 Args:
1149 block: If true, block until at least one event is processed.
Jon Salz7c15e8b2012-06-19 17:10:37 +08001150
Jon Salz0697cbf2012-07-04 15:14:04 +08001151 Returns:
1152 True to keep going or False to shut down.
1153 '''
1154 events = utils.DrainQueue(self.run_queue)
cychiang21886742012-07-05 15:16:32 +08001155 while not events:
Jon Salz0697cbf2012-07-04 15:14:04 +08001156 # Nothing on the run queue.
1157 self._run_queue_idle()
1158 if block:
1159 # Block for at least one event...
cychiang21886742012-07-05 15:16:32 +08001160 try:
1161 events.append(self.run_queue.get(timeout=RUN_QUEUE_TIMEOUT_SECS))
1162 except Queue.Empty:
1163 # Keep going (calling _run_queue_idle() again at the top of
1164 # the loop)
1165 continue
Jon Salz0697cbf2012-07-04 15:14:04 +08001166 # ...and grab anything else that showed up at the same
1167 # time.
1168 events.extend(utils.DrainQueue(self.run_queue))
cychiang21886742012-07-05 15:16:32 +08001169 else:
1170 break
Jon Salz51528e12012-07-02 18:54:45 +08001171
Jon Salz0697cbf2012-07-04 15:14:04 +08001172 for event in events:
1173 if not event:
1174 # Shutdown request.
1175 self.run_queue.task_done()
1176 return False
Jon Salz51528e12012-07-02 18:54:45 +08001177
Jon Salz0697cbf2012-07-04 15:14:04 +08001178 try:
1179 event()
Jon Salz85a39882012-07-05 16:45:04 +08001180 except: # pylint: disable=W0702
1181 logging.exception('Error in event loop')
Jon Salz0697cbf2012-07-04 15:14:04 +08001182 self.record_exception(traceback.format_exception_only(
1183 *sys.exc_info()[:2]))
1184 # But keep going
1185 finally:
1186 self.run_queue.task_done()
1187 return True
Jon Salz0405ab52012-03-16 15:26:52 +08001188
Jon Salz54882d02012-08-31 01:57:54 +08001189 def _should_sync_time(self):
1190 '''Returns True if we should attempt syncing time with shopfloor.'''
1191 return (self.test_list.options.sync_time_period_secs and
1192 self.time_sanitizer and
1193 (not self.time_synced) and
1194 (not factory.in_chroot()))
1195
1196 def sync_time_with_shopfloor_server(self):
1197 '''Syncs time with shopfloor server, if not yet synced.
1198
1199 Returns:
1200 False if no time sanitizer is available, or True if this sync (or a
1201 previous sync) succeeded.
1202
1203 Raises:
1204 Exception if unable to contact the shopfloor server.
1205 '''
1206 if self._should_sync_time():
1207 self.time_sanitizer.SyncWithShopfloor()
1208 self.time_synced = True
1209 return self.time_synced
1210
Jon Salzb92c5112012-09-21 15:40:11 +08001211 def log_disk_space_stats(self):
1212 if not self.test_list.options.log_disk_space_period_secs:
1213 return
1214
1215 now = time.time()
1216 if (self.last_log_disk_space_time and
1217 now - self.last_log_disk_space_time <
1218 self.test_list.options.log_disk_space_period_secs):
1219 return
1220 self.last_log_disk_space_time = now
1221
1222 try:
1223 logging.info(disk_space.FormatSpaceUsedAll())
1224 except: # pylint: disable=W0702
1225 logging.exception('Unable to get disk space used')
1226
Jon Salz8fa8e832012-07-13 19:04:09 +08001227 def sync_time_in_background(self):
Jon Salzb22d1172012-08-06 10:38:57 +08001228 '''Writes out current time and tries to sync with shopfloor server.'''
1229 if not self.time_sanitizer:
1230 return
1231
1232 # Write out the current time.
1233 self.time_sanitizer.SaveTime()
1234
Jon Salz54882d02012-08-31 01:57:54 +08001235 if not self._should_sync_time():
Jon Salz8fa8e832012-07-13 19:04:09 +08001236 return
1237
1238 now = time.time()
1239 if self.last_sync_time and (
1240 now - self.last_sync_time <
1241 self.test_list.options.sync_time_period_secs):
1242 # Not yet time for another check.
1243 return
1244 self.last_sync_time = now
1245
1246 def target():
1247 try:
Jon Salz54882d02012-08-31 01:57:54 +08001248 self.sync_time_with_shopfloor_server()
Jon Salz8fa8e832012-07-13 19:04:09 +08001249 except: # pylint: disable=W0702
1250 # Oh well. Log an error (but no trace)
1251 logging.info(
1252 'Unable to get time from shopfloor server: %s',
1253 utils.FormatExceptionOnly())
1254
1255 thread = threading.Thread(target=target)
1256 thread.daemon = True
1257 thread.start()
1258
Jon Salz0697cbf2012-07-04 15:14:04 +08001259 def _run_queue_idle(self):
Vic Yang4953fc12012-07-26 16:19:53 +08001260 '''Invoked when the run queue has no events.
1261
1262 This method must not raise exception.
1263 '''
Jon Salzb22d1172012-08-06 10:38:57 +08001264 now = time.time()
1265 if (self.last_idle and
1266 now < (self.last_idle + RUN_QUEUE_TIMEOUT_SECS - 1)):
1267 # Don't run more often than once every (RUN_QUEUE_TIMEOUT_SECS -
1268 # 1) seconds.
1269 return
1270
1271 self.last_idle = now
1272
Jon Salz0697cbf2012-07-04 15:14:04 +08001273 self.check_connection_manager()
cychiang21886742012-07-05 15:16:32 +08001274 self.check_for_updates()
Jon Salz8fa8e832012-07-13 19:04:09 +08001275 self.sync_time_in_background()
Jon Salzb92c5112012-09-21 15:40:11 +08001276 self.log_disk_space_stats()
Vic Yang4953fc12012-07-26 16:19:53 +08001277 if self.charge_manager:
1278 self.charge_manager.AdjustChargeState()
Jon Salz57717ca2012-04-04 16:47:25 +08001279
Jon Salz16d10542012-07-23 12:18:45 +08001280 def handle_event_logs(self, log_name, chunk):
Jon Salz0697cbf2012-07-04 15:14:04 +08001281 '''Callback for event watcher.
Jon Salz258a40c2012-04-19 12:34:01 +08001282
Jon Salz0697cbf2012-07-04 15:14:04 +08001283 Attempts to upload the event logs to the shopfloor server.
1284 '''
1285 description = 'event logs (%s, %d bytes)' % (log_name, len(chunk))
1286 start_time = time.time()
Jon Salz0697cbf2012-07-04 15:14:04 +08001287 shopfloor_client = shopfloor.get_instance(
1288 detect=True,
1289 timeout=self.test_list.options.shopfloor_timeout_secs)
Jon Salzb10cf512012-08-09 17:29:21 +08001290 shopfloor_client.UploadEvent(log_name, Binary(chunk))
Jon Salz0697cbf2012-07-04 15:14:04 +08001291 logging.info(
1292 'Successfully synced %s in %.03f s',
1293 description, time.time() - start_time)
Jon Salz57717ca2012-04-04 16:47:25 +08001294
Jon Salz0697cbf2012-07-04 15:14:04 +08001295 def run_tests_with_status(self, statuses_to_run, starting_at=None,
1296 root=None):
1297 '''Runs all top-level tests with a particular status.
Jon Salz0405ab52012-03-16 15:26:52 +08001298
Jon Salz0697cbf2012-07-04 15:14:04 +08001299 All active tests, plus any tests to re-run, are reset.
Jon Salz57717ca2012-04-04 16:47:25 +08001300
Jon Salz0697cbf2012-07-04 15:14:04 +08001301 Args:
1302 starting_at: If provided, only auto-runs tests beginning with
1303 this test.
1304 '''
1305 root = root or self.test_list
Jon Salz57717ca2012-04-04 16:47:25 +08001306
Jon Salz0697cbf2012-07-04 15:14:04 +08001307 if starting_at:
1308 # Make sure they passed a test, not a string.
1309 assert isinstance(starting_at, factory.FactoryTest)
Jon Salz0405ab52012-03-16 15:26:52 +08001310
Jon Salz0697cbf2012-07-04 15:14:04 +08001311 tests_to_reset = []
1312 tests_to_run = []
Jon Salz0405ab52012-03-16 15:26:52 +08001313
Jon Salz0697cbf2012-07-04 15:14:04 +08001314 found_starting_at = False
Jon Salz0405ab52012-03-16 15:26:52 +08001315
Jon Salz0697cbf2012-07-04 15:14:04 +08001316 for test in root.get_top_level_tests():
1317 if starting_at:
1318 if test == starting_at:
1319 # We've found starting_at; do auto-run on all
1320 # subsequent tests.
1321 found_starting_at = True
1322 if not found_starting_at:
1323 # Don't start this guy yet
1324 continue
Jon Salz0405ab52012-03-16 15:26:52 +08001325
Jon Salz0697cbf2012-07-04 15:14:04 +08001326 status = test.get_state().status
1327 if status == TestState.ACTIVE or status in statuses_to_run:
1328 # Reset the test (later; we will need to abort
1329 # all active tests first).
1330 tests_to_reset.append(test)
1331 if status in statuses_to_run:
1332 tests_to_run.append(test)
Jon Salz0405ab52012-03-16 15:26:52 +08001333
Jon Salz0697cbf2012-07-04 15:14:04 +08001334 self.abort_active_tests()
Jon Salz258a40c2012-04-19 12:34:01 +08001335
Jon Salz0697cbf2012-07-04 15:14:04 +08001336 # Reset all statuses of the tests to run (in case any tests were active;
1337 # we want them to be run again).
1338 for test_to_reset in tests_to_reset:
1339 for test in test_to_reset.walk():
1340 test.update_state(status=TestState.UNTESTED)
Jon Salz57717ca2012-04-04 16:47:25 +08001341
Jon Salz0697cbf2012-07-04 15:14:04 +08001342 self.run_tests(tests_to_run, untested_only=True)
Jon Salz0405ab52012-03-16 15:26:52 +08001343
Jon Salz0697cbf2012-07-04 15:14:04 +08001344 def restart_tests(self, root=None):
1345 '''Restarts all tests.'''
1346 root = root or self.test_list
Jon Salz0405ab52012-03-16 15:26:52 +08001347
Jon Salz0697cbf2012-07-04 15:14:04 +08001348 self.abort_active_tests()
1349 for test in root.walk():
1350 test.update_state(status=TestState.UNTESTED)
1351 self.run_tests(root)
Hung-Te Lin96632362012-03-20 21:14:18 +08001352
Jon Salz0697cbf2012-07-04 15:14:04 +08001353 def auto_run(self, starting_at=None, root=None):
1354 '''"Auto-runs" tests that have not been run yet.
Hung-Te Lin96632362012-03-20 21:14:18 +08001355
Jon Salz0697cbf2012-07-04 15:14:04 +08001356 Args:
1357 starting_at: If provide, only auto-runs tests beginning with
1358 this test.
1359 '''
1360 root = root or self.test_list
1361 self.run_tests_with_status([TestState.UNTESTED, TestState.ACTIVE],
1362 starting_at=starting_at,
1363 root=root)
Jon Salz968e90b2012-03-18 16:12:43 +08001364
Jon Salz0697cbf2012-07-04 15:14:04 +08001365 def re_run_failed(self, root=None):
1366 '''Re-runs failed tests.'''
1367 root = root or self.test_list
1368 self.run_tests_with_status([TestState.FAILED], root=root)
Jon Salz57717ca2012-04-04 16:47:25 +08001369
Jon Salz0697cbf2012-07-04 15:14:04 +08001370 def show_review_information(self):
1371 '''Event handler for showing review information screen.
Jon Salz57717ca2012-04-04 16:47:25 +08001372
Jon Salz0697cbf2012-07-04 15:14:04 +08001373 The information screene is rendered by main UI program (ui.py), so in
1374 goofy we only need to kill all active tests, set them as untested, and
1375 clear remaining tests.
1376 '''
1377 self.kill_active_tests(False)
Jon Salza6711d72012-07-18 14:33:03 +08001378 self.cancel_pending_tests()
Jon Salz57717ca2012-04-04 16:47:25 +08001379
Jon Salz0697cbf2012-07-04 15:14:04 +08001380 def handle_switch_test(self, event):
1381 '''Switches to a particular test.
Jon Salz0405ab52012-03-16 15:26:52 +08001382
Jon Salz0697cbf2012-07-04 15:14:04 +08001383 @param event: The SWITCH_TEST event.
1384 '''
1385 test = self.test_list.lookup_path(event.path)
1386 if not test:
1387 logging.error('Unknown test %r', event.key)
1388 return
Jon Salz73e0fd02012-04-04 11:46:38 +08001389
Jon Salz0697cbf2012-07-04 15:14:04 +08001390 invoc = self.invocations.get(test)
1391 if invoc and test.backgroundable:
1392 # Already running: just bring to the front if it
1393 # has a UI.
1394 logging.info('Setting visible test to %s', test.path)
Jon Salz36fbbb52012-07-05 13:45:06 +08001395 self.set_visible_test(test)
Jon Salz0697cbf2012-07-04 15:14:04 +08001396 return
Jon Salz73e0fd02012-04-04 11:46:38 +08001397
Jon Salz0697cbf2012-07-04 15:14:04 +08001398 self.abort_active_tests()
1399 for t in test.walk():
1400 t.update_state(status=TestState.UNTESTED)
Jon Salz73e0fd02012-04-04 11:46:38 +08001401
Jon Salz0697cbf2012-07-04 15:14:04 +08001402 if self.test_list.options.auto_run_on_keypress:
1403 self.auto_run(starting_at=test)
1404 else:
1405 self.run_tests(test)
Jon Salz73e0fd02012-04-04 11:46:38 +08001406
Jon Salz0697cbf2012-07-04 15:14:04 +08001407 def wait(self):
1408 '''Waits for all pending invocations.
1409
1410 Useful for testing.
1411 '''
Jon Salz1acc8742012-07-17 17:45:55 +08001412 while self.invocations:
1413 for k, v in self.invocations.iteritems():
1414 logging.info('Waiting for %s to complete...', k)
1415 v.thread.join()
1416 self.reap_completed_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +08001417
1418 def check_exceptions(self):
1419 '''Raises an error if any exceptions have occurred in
1420 invocation threads.'''
1421 if self.exceptions:
1422 raise RuntimeError('Exception in invocation thread: %r' %
1423 self.exceptions)
1424
1425 def record_exception(self, msg):
1426 '''Records an exception in an invocation thread.
1427
1428 An exception with the given message will be rethrown when
1429 Goofy is destroyed.'''
1430 self.exceptions.append(msg)
Jon Salz73e0fd02012-04-04 11:46:38 +08001431
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001432
1433if __name__ == '__main__':
Jon Salz77c151e2012-08-28 07:20:37 +08001434 goofy = Goofy()
1435 try:
1436 goofy.main()
Jon Salz31373eb2012-09-21 16:19:49 +08001437 except:
1438 # Log the error before trying to shut down.
1439 logging.exception('Error in main loop')
1440 raise
Jon Salz77c151e2012-08-28 07:20:37 +08001441 finally:
1442 goofy.destroy()