blob: b8c1b79014dc89d777bb8f4e37321b8fd9d21846 [file] [log] [blame]
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001#!/usr/bin/python -u
2#
3# -*- coding: utf-8 -*-
4#
Jon Salz37eccbd2012-05-25 16:06:52 +08005# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
Hung-Te Linf2f78f72012-02-08 19:27:11 +08006# Use of this source code is governed by a BSD-style license that can be
7# found in the LICENSE file.
8
9'''
10The main factory flow that runs the factory test and finalizes a device.
11'''
12
Jon Salz73e0fd02012-04-04 11:46:38 +080013import array
14import fcntl
15import glob
Jon Salz0405ab52012-03-16 15:26:52 +080016import logging
17import os
Jon Salz258a40c2012-04-19 12:34:01 +080018import cPickle as pickle
Jon Salz0405ab52012-03-16 15:26:52 +080019import pipes
Jon Salz73e0fd02012-04-04 11:46:38 +080020import Queue
Jon Salz0405ab52012-03-16 15:26:52 +080021import re
22import signal
23import subprocess
24import sys
25import tempfile
26import threading
27import time
28import traceback
Jon Salz258a40c2012-04-19 12:34:01 +080029import unittest
30import uuid
Hung-Te Linf2f78f72012-02-08 19:27:11 +080031from collections import deque
32from optparse import OptionParser
Jon Salz258a40c2012-04-19 12:34:01 +080033from StringIO import StringIO
Hung-Te Linf2f78f72012-02-08 19:27:11 +080034
35import factory_common
Jon Salz8375c2e2012-04-04 15:22:24 +080036from autotest_lib.client.bin.prespawner import Prespawner
Hung-Te Linf2f78f72012-02-08 19:27:11 +080037from autotest_lib.client.cros import factory
38from autotest_lib.client.cros.factory import state
39from autotest_lib.client.cros.factory import TestState
Jon Salz37eccbd2012-05-25 16:06:52 +080040from autotest_lib.client.cros.factory import updater
Jon Salz258a40c2012-04-19 12:34:01 +080041from autotest_lib.client.cros.factory import utils
Hung-Te Linf2f78f72012-02-08 19:27:11 +080042from autotest_lib.client.cros.factory.event import Event
43from autotest_lib.client.cros.factory.event import EventClient
44from autotest_lib.client.cros.factory.event import EventServer
Jon Salzeb8d25f2012-05-22 15:17:32 +080045from autotest_lib.client.cros.factory.event_log import EventLog
Jon Salz258a40c2012-04-19 12:34:01 +080046from autotest_lib.client.cros.factory.invocation import TestInvocation
Jon Salz5f2a0672012-05-22 17:14:06 +080047from autotest_lib.client.cros.factory import test_environment
Jon Salz258a40c2012-04-19 12:34:01 +080048from autotest_lib.client.cros.factory.web_socket_manager import WebSocketManager
Hung-Te Linf2f78f72012-02-08 19:27:11 +080049
50
Hung-Te Linf2f78f72012-02-08 19:27:11 +080051DEFAULT_TEST_LIST_PATH = os.path.join(
Jon Salz258a40c2012-04-19 12:34:01 +080052 factory.CLIENT_PATH , 'site_tests', 'suite_Factory', 'test_list')
Hung-Te Linf2f78f72012-02-08 19:27:11 +080053HWID_CFG_PATH = '/usr/local/share/chromeos-hwid/cfg'
54
Jon Salz8796e362012-05-24 11:39:09 +080055# File that suppresses reboot if present (e.g., for development).
56NO_REBOOT_FILE = '/var/log/factory.noreboot'
57
Jon Salz758e6cc2012-04-03 15:47:07 +080058GOOFY_IN_CHROOT_WARNING = '\n' + ('*' * 70) + '''
59You are running Goofy inside the chroot. Autotests are not supported.
60
61To use Goofy in the chroot, first install an Xvnc server:
62
63 sudo apt-get install tightvncserver
64
65...and then start a VNC X server outside the chroot:
66
67 vncserver :10 &
68 vncviewer :10
69
70...and run Goofy as follows:
71
72 env --unset=XAUTHORITY DISPLAY=localhost:10 python goofy.py
73''' + ('*' * 70)
Jon Salz73e0fd02012-04-04 11:46:38 +080074suppress_chroot_warning = False
Hung-Te Linf2f78f72012-02-08 19:27:11 +080075
76def get_hwid_cfg():
77 '''
78 Returns the HWID config tag, or an empty string if none can be found.
79 '''
80 if 'CROS_HWID' in os.environ:
81 return os.environ['CROS_HWID']
82 if os.path.exists(HWID_CFG_PATH):
83 with open(HWID_CFG_PATH, 'rt') as hwid_cfg_handle:
84 return hwid_cfg_handle.read().strip()
85 return ''
86
87
88def find_test_list():
89 '''
90 Returns the path to the active test list, based on the HWID config tag.
91 '''
92 hwid_cfg = get_hwid_cfg()
93
94 # Try in order: test_list, test_list.$hwid_cfg, test_list.all
95 if hwid_cfg:
96 test_list = '%s_%s' % (DEFAULT_TEST_LIST_PATH, hwid_cfg)
97 if os.path.exists(test_list):
98 logging.info('Using special test list: %s', test_list)
99 return test_list
100 logging.info('WARNING: no specific test list for config: %s', hwid_cfg)
101
102 test_list = DEFAULT_TEST_LIST_PATH
103 if os.path.exists(test_list):
104 return test_list
105
106 test_list = ('%s.all' % DEFAULT_TEST_LIST_PATH)
107 if os.path.exists(test_list):
108 logging.info('Using default test list: ' + test_list)
109 return test_list
110 logging.info('ERROR: Cannot find any test list.')
111
Jon Salz73e0fd02012-04-04 11:46:38 +0800112
Jon Salz73e0fd02012-04-04 11:46:38 +0800113_inited_logging = False
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800114
115class Goofy(object):
116 '''
117 The main factory flow.
118
119 Note that all methods in this class must be invoked from the main
120 (event) thread. Other threads, such as callbacks and TestInvocation
121 methods, should instead post events on the run queue.
122
123 TODO: Unit tests. (chrome-os-partner:7409)
124
125 Properties:
Jon Salz258a40c2012-04-19 12:34:01 +0800126 uuid: A unique UUID for this invocation of Goofy.
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800127 state_instance: An instance of FactoryState.
128 state_server: The FactoryState XML/RPC server.
129 state_server_thread: A thread running state_server.
130 event_server: The EventServer socket server.
131 event_server_thread: A thread running event_server.
132 event_client: A client to the event server.
Hung-Te Lin6bb48552012-02-09 14:37:43 +0800133 ui_process: The factory ui process object.
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800134 run_queue: A queue of callbacks to invoke from the main thread.
135 invocations: A map from FactoryTest objects to the corresponding
136 TestInvocations objects representing active tests.
137 tests_to_run: A deque of tests that should be run when the current
138 test(s) complete.
139 options: Command-line options.
140 args: Command-line args.
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800141 test_list: The test list.
Jon Salz0405ab52012-03-16 15:26:52 +0800142 event_handlers: Map of Event.Type to the method used to handle that
143 event. If the method has an 'event' argument, the event is passed
144 to the handler.
Jon Salz73e0fd02012-04-04 11:46:38 +0800145 exceptions: Exceptions encountered in invocation threads.
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800146 '''
147 def __init__(self):
Jon Salz258a40c2012-04-19 12:34:01 +0800148 self.uuid = str(uuid.uuid4())
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800149 self.state_instance = None
150 self.state_server = None
151 self.state_server_thread = None
152 self.event_server = None
153 self.event_server_thread = None
154 self.event_client = None
Jon Salzeb8d25f2012-05-22 15:17:32 +0800155 self.event_log = None
Jon Salz8375c2e2012-04-04 15:22:24 +0800156 self.prespawner = None
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800157 self.ui_process = None
Jon Salz73e0fd02012-04-04 11:46:38 +0800158 self.run_queue = Queue.Queue()
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800159 self.invocations = {}
160 self.tests_to_run = deque()
161 self.visible_test = None
Jon Salz258a40c2012-04-19 12:34:01 +0800162 self.chrome = None
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800163
164 self.options = None
165 self.args = None
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800166 self.test_list = None
167
Jon Salz258a40c2012-04-19 12:34:01 +0800168 def test_or_root(event):
169 '''Returns the top-level parent for a test (the root node of the
170 tests that need to be run together if the given test path is to
171 be run).'''
172 try:
173 path = event.path
Jon Salzd2ed6cb2012-05-02 09:35:14 +0800174 except AttributeError:
Jon Salz258a40c2012-04-19 12:34:01 +0800175 path = None
176
177 if path:
Jon Salzf617b282012-05-24 14:14:04 +0800178 return (self.test_list.lookup_path(path).
179 get_top_level_parent_or_group())
Jon Salz258a40c2012-04-19 12:34:01 +0800180 else:
181 return self.test_list
182
Jon Salz0405ab52012-03-16 15:26:52 +0800183 self.event_handlers = {
184 Event.Type.SWITCH_TEST: self.handle_switch_test,
Jon Salz968e90b2012-03-18 16:12:43 +0800185 Event.Type.SHOW_NEXT_ACTIVE_TEST:
186 lambda event: self.show_next_active_test(),
187 Event.Type.RESTART_TESTS:
Jon Salz258a40c2012-04-19 12:34:01 +0800188 lambda event: self.restart_tests(root=test_or_root(event)),
Jon Salz968e90b2012-03-18 16:12:43 +0800189 Event.Type.AUTO_RUN:
Jon Salz258a40c2012-04-19 12:34:01 +0800190 lambda event: self.auto_run(root=test_or_root(event)),
Jon Salz968e90b2012-03-18 16:12:43 +0800191 Event.Type.RE_RUN_FAILED:
Jon Salz258a40c2012-04-19 12:34:01 +0800192 lambda event: self.re_run_failed(root=test_or_root(event)),
Jon Salz968e90b2012-03-18 16:12:43 +0800193 Event.Type.REVIEW:
194 lambda event: self.show_review_information(),
Jon Salz5f2a0672012-05-22 17:14:06 +0800195 Event.Type.UPDATE_SYSTEM_INFO:
196 lambda event: self.update_system_info(),
Jon Salz37eccbd2012-05-25 16:06:52 +0800197 Event.Type.UPDATE_FACTORY:
198 lambda event: self.update_factory(),
Jon Salzf00cdc82012-05-28 18:56:17 +0800199 Event.Type.STOP:
200 lambda event: self.stop(),
Jon Salz0405ab52012-03-16 15:26:52 +0800201 }
202
Jon Salz73e0fd02012-04-04 11:46:38 +0800203 self.exceptions = []
Jon Salz258a40c2012-04-19 12:34:01 +0800204 self.web_socket_manager = None
Jon Salz73e0fd02012-04-04 11:46:38 +0800205
206 def destroy(self):
Jon Salz258a40c2012-04-19 12:34:01 +0800207 if self.chrome:
208 self.chrome.kill()
209 self.chrome = None
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800210 if self.ui_process:
Jon Salz258a40c2012-04-19 12:34:01 +0800211 utils.kill_process_tree(self.ui_process, 'ui')
Jon Salz73e0fd02012-04-04 11:46:38 +0800212 self.ui_process = None
Jon Salz258a40c2012-04-19 12:34:01 +0800213 if self.web_socket_manager:
214 logging.info('Stopping web sockets')
215 self.web_socket_manager.close()
216 self.web_socket_manager = None
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800217 if self.state_server_thread:
218 logging.info('Stopping state server')
219 self.state_server.shutdown()
220 self.state_server_thread.join()
Jon Salz73e0fd02012-04-04 11:46:38 +0800221 self.state_server.server_close()
222 self.state_server_thread = None
Jon Salz66f65e62012-05-24 17:40:26 +0800223 if self.state_instance:
224 self.state_instance.close()
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800225 if self.event_server_thread:
226 logging.info('Stopping event server')
227 self.event_server.shutdown() # pylint: disable=E1101
228 self.event_server_thread.join()
Jon Salz73e0fd02012-04-04 11:46:38 +0800229 self.event_server.server_close()
230 self.event_server_thread = None
Jon Salz8375c2e2012-04-04 15:22:24 +0800231 if self.prespawner:
232 logging.info('Stopping prespawner')
233 self.prespawner.stop()
234 self.prespawner = None
235 if self.event_client:
Jon Salz258a40c2012-04-19 12:34:01 +0800236 logging.info('Closing event client')
Jon Salz8375c2e2012-04-04 15:22:24 +0800237 self.event_client.close()
Jon Salz258a40c2012-04-19 12:34:01 +0800238 self.event_client = None
Jon Salzeb8d25f2012-05-22 15:17:32 +0800239 if self.event_log:
240 self.event_log.Close()
241 self.event_log = None
Jon Salz73e0fd02012-04-04 11:46:38 +0800242 self.check_exceptions()
Jon Salz258a40c2012-04-19 12:34:01 +0800243 logging.info('Done destroying Goofy')
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800244
245 def start_state_server(self):
Jon Salz258a40c2012-04-19 12:34:01 +0800246 self.state_instance, self.state_server = (
247 state.create_server(bind_address='0.0.0.0'))
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800248 logging.info('Starting state server')
249 self.state_server_thread = threading.Thread(
Jon Salz8375c2e2012-04-04 15:22:24 +0800250 target=self.state_server.serve_forever,
251 name='StateServer')
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800252 self.state_server_thread.start()
253
254 def start_event_server(self):
255 self.event_server = EventServer()
256 logging.info('Starting factory event server')
257 self.event_server_thread = threading.Thread(
Jon Salz8375c2e2012-04-04 15:22:24 +0800258 target=self.event_server.serve_forever,
259 name='EventServer') # pylint: disable=E1101
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800260 self.event_server_thread.start()
261
262 self.event_client = EventClient(
263 callback=self.handle_event, event_loop=self.run_queue)
264
Jon Salz258a40c2012-04-19 12:34:01 +0800265 self.web_socket_manager = WebSocketManager(self.uuid)
266 self.state_server.add_handler("/event",
267 self.web_socket_manager.handle_web_socket)
268
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800269 def start_ui(self):
Jon Salz258a40c2012-04-19 12:34:01 +0800270 ui_proc_args = [os.path.join(factory.CROS_FACTORY_LIB_PATH, 'ui'),
271 self.options.test_list]
Jon Salz14bcbb02012-03-17 15:11:50 +0800272 if self.options.verbose:
273 ui_proc_args.append('-v')
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800274 logging.info('Starting ui %s', ui_proc_args)
275 self.ui_process = subprocess.Popen(ui_proc_args)
276 logging.info('Waiting for UI to come up...')
277 self.event_client.wait(
278 lambda event: event.type == Event.Type.UI_READY)
279 logging.info('UI has started')
280
281 def set_visible_test(self, test):
282 if self.visible_test == test:
283 return
284
285 if test:
286 test.update_state(visible=True)
287 if self.visible_test:
288 self.visible_test.update_state(visible=False)
289 self.visible_test = test
290
Jon Salz74ad3262012-03-16 14:40:55 +0800291 def handle_shutdown_complete(self, test, state):
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800292 '''
Jon Salz74ad3262012-03-16 14:40:55 +0800293 Handles the case where a shutdown was detected during a shutdown step.
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800294
Jon Salz74ad3262012-03-16 14:40:55 +0800295 @param test: The ShutdownStep.
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800296 @param state: The test state.
297 '''
Jon Salz74ad3262012-03-16 14:40:55 +0800298 state = test.update_state(increment_shutdown_count=1)
299 logging.info('Detected shutdown (%d of %d)',
300 state.shutdown_count, test.iterations)
301 if state.shutdown_count == test.iterations:
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800302 # Good!
303 test.update_state(status=TestState.PASSED, error_msg='')
Jon Salz74ad3262012-03-16 14:40:55 +0800304 elif state.shutdown_count > test.iterations:
Jon Salz73e0fd02012-04-04 11:46:38 +0800305 # Shut down too many times
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800306 test.update_state(status=TestState.FAILED,
Jon Salz74ad3262012-03-16 14:40:55 +0800307 error_msg='Too many shutdowns')
Jon Salz258a40c2012-04-19 12:34:01 +0800308 elif utils.are_shift_keys_depressed():
Jon Salz73e0fd02012-04-04 11:46:38 +0800309 logging.info('Shift keys are depressed; cancelling restarts')
310 # Abort shutdown
311 test.update_state(
312 status=TestState.FAILED,
313 error_msg='Shutdown aborted with double shift keys')
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800314 else:
Jon Salz74ad3262012-03-16 14:40:55 +0800315 # Need to shutdown again
Jon Salzb9038572012-05-24 10:34:51 +0800316 self.event_log.Log('shutdown', operation='reboot')
Jon Salz73e0fd02012-04-04 11:46:38 +0800317 self.env.shutdown('reboot')
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800318
319 def init_states(self):
320 '''
321 Initializes all states on startup.
322 '''
323 for test in self.test_list.get_all_tests():
324 # Make sure the state server knows about all the tests,
325 # defaulting to an untested state.
326 test.update_state(update_parent=False, visible=False)
327
328 # Any 'active' tests should be marked as failed now.
329 for test in self.test_list.walk():
330 state = test.get_state()
Hung-Te Lin96632362012-03-20 21:14:18 +0800331 if state.status != TestState.ACTIVE:
332 continue
333 if isinstance(test, factory.ShutdownStep):
334 # Shutdown while the test was active - that's good.
335 self.handle_shutdown_complete(test, state)
336 else:
337 test.update_state(status=TestState.FAILED,
338 error_msg='Unknown (shutdown?)')
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800339
340 def show_next_active_test(self):
341 '''
342 Rotates to the next visible active test.
343 '''
344 self.reap_completed_tests()
345 active_tests = [
346 t for t in self.test_list.walk()
347 if t.is_leaf() and t.get_state().status == TestState.ACTIVE]
348 if not active_tests:
349 return
350
351 try:
352 next_test = active_tests[
353 (active_tests.index(self.visible_test) + 1) % len(active_tests)]
354 except ValueError: # visible_test not present in active_tests
355 next_test = active_tests[0]
356
357 self.set_visible_test(next_test)
358
359 def handle_event(self, event):
360 '''
361 Handles an event from the event server.
362 '''
Jon Salz0405ab52012-03-16 15:26:52 +0800363 handler = self.event_handlers.get(event.type)
364 if handler:
Jon Salz968e90b2012-03-18 16:12:43 +0800365 handler(event)
Jon Salz0405ab52012-03-16 15:26:52 +0800366 else:
Jon Salz968e90b2012-03-18 16:12:43 +0800367 # We don't register handlers for all event types - just ignore
368 # this event.
369 logging.debug('Unbound event type %s', event.type)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800370
371 def run_next_test(self):
372 '''
373 Runs the next eligible test (or tests) in self.tests_to_run.
374 '''
375 self.reap_completed_tests()
376 while self.tests_to_run:
377 logging.debug('Tests to run: %s',
378 [x.path for x in self.tests_to_run])
379
380 test = self.tests_to_run[0]
381
382 if test in self.invocations:
383 logging.info('Next test %s is already running', test.path)
384 self.tests_to_run.popleft()
385 return
386
387 if self.invocations and not (test.backgroundable and all(
388 [x.backgroundable for x in self.invocations])):
389 logging.debug('Waiting for non-backgroundable tests to '
390 'complete before running %s', test.path)
391 return
392
393 self.tests_to_run.popleft()
394
Jon Salz74ad3262012-03-16 14:40:55 +0800395 if isinstance(test, factory.ShutdownStep):
Jon Salz8796e362012-05-24 11:39:09 +0800396 if os.path.exists(NO_REBOOT_FILE):
397 test.update_state(
398 status=TestState.FAILED, increment_count=1,
399 error_msg=('Skipped shutdown since %s is present' %
400 NO_REBOOT_FILE))
401 continue
402
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800403 test.update_state(status=TestState.ACTIVE, increment_count=1,
Jon Salz74ad3262012-03-16 14:40:55 +0800404 error_msg='', shutdown_count=0)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800405 # Save pending test list in the state server
406 self.state_instance.set_shared_data(
Jon Salz74ad3262012-03-16 14:40:55 +0800407 'tests_after_shutdown',
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800408 [t.path for t in self.tests_to_run])
Jon Salz74ad3262012-03-16 14:40:55 +0800409
Jon Salz73e0fd02012-04-04 11:46:38 +0800410 with self.env.lock:
Jon Salzb9038572012-05-24 10:34:51 +0800411 self.event_log.Log('shutdown', operation=test.operation)
Jon Salz73e0fd02012-04-04 11:46:38 +0800412 shutdown_result = self.env.shutdown(test.operation)
413 if shutdown_result:
414 # That's all, folks!
415 self.run_queue.put(None)
416 return
417 else:
418 # Just pass (e.g., in the chroot).
419 test.update_state(status=TestState.PASSED)
420 self.state_instance.set_shared_data(
421 'tests_after_shutdown', None)
422 continue
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800423
424 invoc = TestInvocation(self, test, on_completion=self.run_next_test)
425 self.invocations[test] = invoc
426 if self.visible_test is None and test.has_ui:
427 self.set_visible_test(test)
428 invoc.start()
429
Jon Salz0405ab52012-03-16 15:26:52 +0800430 def run_tests(self, subtrees, untested_only=False):
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800431 '''
Jon Salz0405ab52012-03-16 15:26:52 +0800432 Runs tests under subtree.
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800433
434 The tests are run in order unless one fails (then stops).
435 Backgroundable tests are run simultaneously; when a foreground test is
436 encountered, we wait for all active tests to finish before continuing.
Jon Salz0405ab52012-03-16 15:26:52 +0800437
438 @param subtrees: Node or nodes containing tests to run (may either be
439 a single test or a list). Duplicates will be ignored.
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800440 '''
Jon Salz0405ab52012-03-16 15:26:52 +0800441 if type(subtrees) != list:
442 subtrees = [subtrees]
443
444 # Nodes we've seen so far, to avoid duplicates.
445 seen = set()
446
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800447 self.tests_to_run = deque()
Jon Salz0405ab52012-03-16 15:26:52 +0800448 for subtree in subtrees:
449 for test in subtree.walk():
450 if test in seen:
451 continue
452 seen.add(test)
453
454 if not test.is_leaf():
455 continue
456 if (untested_only and
457 test.get_state().status != TestState.UNTESTED):
458 continue
459 self.tests_to_run.append(test)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800460 self.run_next_test()
461
462 def reap_completed_tests(self):
463 '''
464 Removes completed tests from the set of active tests.
465
466 Also updates the visible test if it was reaped.
467 '''
468 for t, v in dict(self.invocations).iteritems():
469 if v.is_completed():
470 del self.invocations[t]
471
472 if (self.visible_test is None or
473 self.visible_test not in self.invocations):
474 self.set_visible_test(None)
475 # Make the first running test, if any, the visible test
476 for t in self.test_list.walk():
477 if t in self.invocations:
478 self.set_visible_test(t)
479 break
480
Hung-Te Lin96632362012-03-20 21:14:18 +0800481 def kill_active_tests(self, abort):
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800482 '''
483 Kills and waits for all active tests.
Hung-Te Lin96632362012-03-20 21:14:18 +0800484
485 @param abort: True to change state of killed tests to FAILED, False for
486 UNTESTED.
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800487 '''
488 self.reap_completed_tests()
489 for test, invoc in self.invocations.items():
490 factory.console.info('Killing active test %s...' % test.path)
491 invoc.abort_and_join()
492 factory.console.info('Killed %s' % test.path)
493 del self.invocations[test]
Hung-Te Lin96632362012-03-20 21:14:18 +0800494 if not abort:
495 test.update_state(status=TestState.UNTESTED)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800496 self.reap_completed_tests()
497
Jon Salzf00cdc82012-05-28 18:56:17 +0800498 def stop(self):
499 self.kill_active_tests(False)
500 self.run_tests([])
501
Hung-Te Lin96632362012-03-20 21:14:18 +0800502 def abort_active_tests(self):
503 self.kill_active_tests(True)
504
Jon Salz73e0fd02012-04-04 11:46:38 +0800505 def main(self):
Jon Salzeb8d25f2012-05-22 15:17:32 +0800506 try:
507 self.init()
Jon Salzb9038572012-05-24 10:34:51 +0800508 self.event_log.Log('goofy_init',
509 success=True)
Jon Salzeb8d25f2012-05-22 15:17:32 +0800510 except:
511 if self.event_log:
512 try:
Jon Salzb9038572012-05-24 10:34:51 +0800513 self.event_log.Log('goofy_init',
514 success=False,
515 trace=traceback.format_exc())
Jon Salzeb8d25f2012-05-22 15:17:32 +0800516 except:
517 pass
518 raise
519
Jon Salz73e0fd02012-04-04 11:46:38 +0800520 self.run()
521
Jon Salz5f2a0672012-05-22 17:14:06 +0800522 def update_system_info(self):
523 '''Updates system info.'''
524 system_info = test_environment.SystemInfo(self.env, self.state_instance)
525 self.state_instance.set_shared_data('system_info', system_info.__dict__)
526 self.event_client.post_event(Event(Event.Type.SYSTEM_INFO,
527 system_info=system_info.__dict__))
528 logging.info('System info: %r', system_info.__dict__)
529
Jon Salz37eccbd2012-05-25 16:06:52 +0800530 def update_factory(self):
531 self.kill_active_tests(False)
532 self.run_tests([])
533
534 try:
535 if updater.TryUpdate(pre_update_hook=self.state_instance.close):
536 self.env.shutdown('reboot')
537 except:
538 factory.console.exception('Unable to update')
539
Jon Salz73e0fd02012-04-04 11:46:38 +0800540 def init(self, args=None, env=None):
541 '''Initializes Goofy.
Jon Salz74ad3262012-03-16 14:40:55 +0800542
543 Args:
Jon Salz73e0fd02012-04-04 11:46:38 +0800544 args: A list of command-line arguments. Uses sys.argv if
545 args is None.
546 env: An Environment instance to use (or None to choose
Jon Salz258a40c2012-04-19 12:34:01 +0800547 FakeChrootEnvironment or DUTEnvironment as appropriate).
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800548 '''
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800549 parser = OptionParser()
550 parser.add_option('-v', '--verbose', dest='verbose',
551 action='store_true',
552 help='Enable debug logging')
553 parser.add_option('--print_test_list', dest='print_test_list',
554 metavar='FILE',
555 help='Read and print test list FILE, and exit')
Jon Salz758e6cc2012-04-03 15:47:07 +0800556 parser.add_option('--restart', dest='restart',
557 action='store_true',
558 help='Clear all test state')
Jon Salz258a40c2012-04-19 12:34:01 +0800559 parser.add_option('--ui', dest='ui', type='choice',
560 choices=['none', 'gtk', 'chrome'],
561 default='gtk',
562 help='UI to use')
Jon Salz63585ea2012-05-21 15:03:32 +0800563 parser.add_option('--ui_scale_factor', dest='ui_scale_factor',
564 type='int', default=1,
565 help=('Factor by which to scale UI '
566 '(Chrome UI only)'))
Jon Salz73e0fd02012-04-04 11:46:38 +0800567 parser.add_option('--test_list', dest='test_list',
568 metavar='FILE',
569 help='Use FILE as test list')
570 (self.options, self.args) = parser.parse_args(args)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800571
Jon Salz73e0fd02012-04-04 11:46:38 +0800572 global _inited_logging
573 if not _inited_logging:
574 factory.init_logging('goofy', verbose=self.options.verbose)
575 _inited_logging = True
Jon Salzeb8d25f2012-05-22 15:17:32 +0800576 self.event_log = EventLog('goofy')
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800577
Jon Salz73e0fd02012-04-04 11:46:38 +0800578 if (not suppress_chroot_warning and
579 factory.in_chroot() and
Jon Salz258a40c2012-04-19 12:34:01 +0800580 self.options.ui == 'gtk' and
Jon Salz758e6cc2012-04-03 15:47:07 +0800581 os.environ.get('DISPLAY') in [None, '', ':0', ':0.0']):
582 # That's not going to work! Tell the user how to run
583 # this way.
584 logging.warn(GOOFY_IN_CHROOT_WARNING)
585 time.sleep(1)
586
Jon Salz73e0fd02012-04-04 11:46:38 +0800587 if env:
588 self.env = env
589 elif factory.in_chroot():
Jon Salz5f2a0672012-05-22 17:14:06 +0800590 self.env = test_environment.FakeChrootEnvironment()
Jon Salz73e0fd02012-04-04 11:46:38 +0800591 logging.warn(
592 'Using chroot environment: will not actually run autotests')
593 else:
Jon Salz5f2a0672012-05-22 17:14:06 +0800594 self.env = test_environment.DUTEnvironment()
Jon Salz323dd3d2012-04-09 18:40:43 +0800595 self.env.goofy = self
Jon Salz73e0fd02012-04-04 11:46:38 +0800596
Jon Salz758e6cc2012-04-03 15:47:07 +0800597 if self.options.restart:
598 state.clear_state()
599
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800600 if self.options.print_test_list:
601 print (factory.read_test_list(self.options.print_test_list).
602 __repr__(recursive=True))
603 return
604
605 logging.info('Started')
606
607 self.start_state_server()
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800608 self.state_instance.set_shared_data('hwid_cfg', get_hwid_cfg())
Jon Salz63585ea2012-05-21 15:03:32 +0800609 self.state_instance.set_shared_data('ui_scale_factor',
610 self.options.ui_scale_factor)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800611
Jon Salz73e0fd02012-04-04 11:46:38 +0800612 self.options.test_list = (self.options.test_list or find_test_list())
613 self.test_list = factory.read_test_list(self.options.test_list,
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800614 self.state_instance)
Jon Salz06fbeff2012-05-21 17:06:05 +0800615 if not self.state_instance.has_shared_data('ui_lang'):
616 self.state_instance.set_shared_data('ui_lang',
617 self.test_list.options.ui_lang)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800618 logging.info('TEST_LIST:\n%s', self.test_list.__repr__(recursive=True))
Jon Salz258a40c2012-04-19 12:34:01 +0800619 self.state_instance.test_list = self.test_list
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800620
621 self.init_states()
622 self.start_event_server()
Jon Salz258a40c2012-04-19 12:34:01 +0800623
Jon Salz5f2a0672012-05-22 17:14:06 +0800624 self.update_system_info()
625
Jon Salz5da61e62012-05-31 13:06:22 +0800626 os.environ['CROS_FACTORY'] = '1'
627
Jon Salzb1b39092012-05-03 02:05:09 +0800628 # Set CROS_UI since some behaviors in ui.py depend on the
629 # particular UI in use. TODO(jsalz): Remove this (and all
630 # places it is used) when the GTK UI is removed.
631 os.environ['CROS_UI'] = self.options.ui
Jon Salz258a40c2012-04-19 12:34:01 +0800632
Jon Salzb1b39092012-05-03 02:05:09 +0800633 if self.options.ui == 'chrome':
Jon Salz258a40c2012-04-19 12:34:01 +0800634 self.env.launch_chrome()
635 logging.info('Waiting for a web socket connection')
636 self.web_socket_manager.wait()
Jon Salzb1b39092012-05-03 02:05:09 +0800637
638 # Wait for the test widget size to be set; this is done in
639 # an asynchronous RPC so there is a small chance that the
640 # web socket might be opened first.
641 for i in range(100): # 10 s
Jon Salz63585ea2012-05-21 15:03:32 +0800642 try:
643 if self.state_instance.get_shared_data('test_widget_size'):
644 break
645 except KeyError:
646 pass # Retry
Jon Salzb1b39092012-05-03 02:05:09 +0800647 time.sleep(0.1) # 100 ms
648 else:
649 logging.warn('Never received test_widget_size from UI')
Jon Salz258a40c2012-04-19 12:34:01 +0800650 elif self.options.ui == 'gtk':
Jon Salz73e0fd02012-04-04 11:46:38 +0800651 self.start_ui()
Jon Salz258a40c2012-04-19 12:34:01 +0800652
Jon Salz8375c2e2012-04-04 15:22:24 +0800653 self.prespawner = Prespawner()
Jon Salz323dd3d2012-04-09 18:40:43 +0800654 self.prespawner.start()
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800655
656 def state_change_callback(test, state):
657 self.event_client.post_event(
658 Event(Event.Type.STATE_CHANGE,
659 path=test.path, state=state))
660 self.test_list.state_change_callback = state_change_callback
661
662 try:
Jon Salz758e6cc2012-04-03 15:47:07 +0800663 tests_after_shutdown = self.state_instance.get_shared_data(
664 'tests_after_shutdown')
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800665 except KeyError:
Jon Salz758e6cc2012-04-03 15:47:07 +0800666 tests_after_shutdown = None
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800667
Jon Salz758e6cc2012-04-03 15:47:07 +0800668 if tests_after_shutdown is not None:
669 logging.info('Resuming tests after shutdown: %s',
670 tests_after_shutdown)
671 self.state_instance.set_shared_data('tests_after_shutdown', None)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800672 self.tests_to_run.extend(
Jon Salz758e6cc2012-04-03 15:47:07 +0800673 self.test_list.lookup_path(t) for t in tests_after_shutdown)
Jon Salz73e0fd02012-04-04 11:46:38 +0800674 self.run_queue.put(self.run_next_test)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800675 else:
Jon Salz57717ca2012-04-04 16:47:25 +0800676 if self.test_list.options.auto_run_on_start:
677 self.run_queue.put(
678 lambda: self.run_tests(self.test_list, untested_only=True))
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800679
Jon Salz73e0fd02012-04-04 11:46:38 +0800680 def run(self):
681 '''Runs Goofy.'''
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800682 # Process events forever.
Jon Salz57717ca2012-04-04 16:47:25 +0800683 while self.run_once(True):
Jon Salz73e0fd02012-04-04 11:46:38 +0800684 pass
685
Jon Salz57717ca2012-04-04 16:47:25 +0800686 def run_once(self, block=False):
Jon Salz73e0fd02012-04-04 11:46:38 +0800687 '''Runs all items pending in the event loop.
688
Jon Salz57717ca2012-04-04 16:47:25 +0800689 Args:
690 block: If true, block until at least one event is processed.
691
Jon Salz73e0fd02012-04-04 11:46:38 +0800692 Returns:
693 True to keep going or False to shut down.
694 '''
Jon Salz57717ca2012-04-04 16:47:25 +0800695 events = []
696 if block:
697 # Get at least one event
698 events.append(self.run_queue.get())
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800699 while True:
Jon Salz73e0fd02012-04-04 11:46:38 +0800700 try:
701 events.append(self.run_queue.get_nowait())
702 except Queue.Empty:
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800703 break
704
Jon Salz73e0fd02012-04-04 11:46:38 +0800705 for event in events:
706 if not event:
707 # Shutdown request.
708 self.run_queue.task_done()
709 return False
710
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800711 try:
712 event()
713 except Exception as e: # pylint: disable=W0703
714 logging.error('Error in event loop: %s', e)
715 traceback.print_exc(sys.stderr)
Jon Salz8375c2e2012-04-04 15:22:24 +0800716 self.record_exception(traceback.format_exception_only(
717 *sys.exc_info()[:2]))
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800718 # But keep going
719 finally:
720 self.run_queue.task_done()
Jon Salz73e0fd02012-04-04 11:46:38 +0800721 return True
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800722
Jon Salz258a40c2012-04-19 12:34:01 +0800723 def run_tests_with_status(self, statuses_to_run, starting_at=None,
724 root=None):
Jon Salz0405ab52012-03-16 15:26:52 +0800725 '''Runs all top-level tests with a particular status.
726
727 All active tests, plus any tests to re-run, are reset.
Jon Salz57717ca2012-04-04 16:47:25 +0800728
729 Args:
730 starting_at: If provided, only auto-runs tests beginning with
731 this test.
Jon Salz0405ab52012-03-16 15:26:52 +0800732 '''
Jon Salz258a40c2012-04-19 12:34:01 +0800733 root = root or self.test_list
734
Jon Salz57717ca2012-04-04 16:47:25 +0800735 if starting_at:
736 # Make sure they passed a test, not a string.
737 assert isinstance(starting_at, factory.FactoryTest)
738
Jon Salz0405ab52012-03-16 15:26:52 +0800739 tests_to_reset = []
740 tests_to_run = []
741
Jon Salz57717ca2012-04-04 16:47:25 +0800742 found_starting_at = False
743
Jon Salz258a40c2012-04-19 12:34:01 +0800744 for test in root.get_top_level_tests():
Jon Salz57717ca2012-04-04 16:47:25 +0800745 if starting_at:
746 if test == starting_at:
747 # We've found starting_at; do auto-run on all
748 # subsequent tests.
749 found_starting_at = True
750 if not found_starting_at:
751 # Don't start this guy yet
752 continue
753
Jon Salz0405ab52012-03-16 15:26:52 +0800754 status = test.get_state().status
755 if status == TestState.ACTIVE or status in statuses_to_run:
756 # Reset the test (later; we will need to abort
757 # all active tests first).
758 tests_to_reset.append(test)
759 if status in statuses_to_run:
760 tests_to_run.append(test)
761
762 self.abort_active_tests()
763
764 # Reset all statuses of the tests to run (in case any tests were active;
765 # we want them to be run again).
766 for test_to_reset in tests_to_reset:
767 for test in test_to_reset.walk():
768 test.update_state(status=TestState.UNTESTED)
769
770 self.run_tests(tests_to_run, untested_only=True)
771
Jon Salz258a40c2012-04-19 12:34:01 +0800772 def restart_tests(self, root=None):
Jon Salz0405ab52012-03-16 15:26:52 +0800773 '''Restarts all tests.'''
Jon Salz258a40c2012-04-19 12:34:01 +0800774 root = root or self.test_list
Jon Salz0405ab52012-03-16 15:26:52 +0800775
Jon Salz258a40c2012-04-19 12:34:01 +0800776 self.abort_active_tests()
777 for test in root.walk():
778 test.update_state(status=TestState.UNTESTED)
779 self.run_tests(root)
780
781 def auto_run(self, starting_at=None, root=None):
Jon Salz57717ca2012-04-04 16:47:25 +0800782 '''"Auto-runs" tests that have not been run yet.
783
784 Args:
785 starting_at: If provide, only auto-runs tests beginning with
786 this test.
787 '''
Jon Salz258a40c2012-04-19 12:34:01 +0800788 root = root or self.test_list
Jon Salz57717ca2012-04-04 16:47:25 +0800789 self.run_tests_with_status([TestState.UNTESTED, TestState.ACTIVE],
Jon Salz258a40c2012-04-19 12:34:01 +0800790 starting_at=starting_at,
791 root=root)
Jon Salz0405ab52012-03-16 15:26:52 +0800792
Jon Salz258a40c2012-04-19 12:34:01 +0800793 def re_run_failed(self, root=None):
Jon Salz0405ab52012-03-16 15:26:52 +0800794 '''Re-runs failed tests.'''
Jon Salz258a40c2012-04-19 12:34:01 +0800795 root = root or self.test_list
796 self.run_tests_with_status([TestState.FAILED], root=root)
Jon Salz0405ab52012-03-16 15:26:52 +0800797
Jon Salz968e90b2012-03-18 16:12:43 +0800798 def show_review_information(self):
Hung-Te Lin96632362012-03-20 21:14:18 +0800799 '''Event handler for showing review information screen.
800
801 The information screene is rendered by main UI program (ui.py), so in
802 goofy we only need to kill all active tests, set them as untested, and
803 clear remaining tests.
804 '''
805 self.kill_active_tests(False)
806 self.run_tests([])
807
Jon Salz0405ab52012-03-16 15:26:52 +0800808 def handle_switch_test(self, event):
Jon Salz968e90b2012-03-18 16:12:43 +0800809 '''Switches to a particular test.
810
811 @param event: The SWITCH_TEST event.
812 '''
Jon Salz0405ab52012-03-16 15:26:52 +0800813 test = self.test_list.lookup_path(event.path)
Jon Salz57717ca2012-04-04 16:47:25 +0800814 if not test:
Jon Salz968e90b2012-03-18 16:12:43 +0800815 logging.error('Unknown test %r', event.key)
Jon Salz57717ca2012-04-04 16:47:25 +0800816 return
817
818 invoc = self.invocations.get(test)
819 if invoc and test.backgroundable:
820 # Already running: just bring to the front if it
821 # has a UI.
822 logging.info('Setting visible test to %s', test.path)
823 self.event_client.post_event(
824 Event(Event.Type.SET_VISIBLE_TEST, path=test.path))
825 return
826
827 self.abort_active_tests()
828 for t in test.walk():
829 t.update_state(status=TestState.UNTESTED)
830
831 if self.test_list.options.auto_run_on_keypress:
832 self.auto_run(starting_at=test)
833 else:
834 self.run_tests(test)
Jon Salz0405ab52012-03-16 15:26:52 +0800835
Jon Salz73e0fd02012-04-04 11:46:38 +0800836 def wait(self):
837 '''Waits for all pending invocations.
838
839 Useful for testing.
840 '''
841 for k, v in self.invocations.iteritems():
842 logging.info('Waiting for %s to complete...', k)
843 v.thread.join()
844
845 def check_exceptions(self):
846 '''Raises an error if any exceptions have occurred in
847 invocation threads.'''
848 if self.exceptions:
849 raise RuntimeError('Exception in invocation thread: %r' %
850 self.exceptions)
851
852 def record_exception(self, msg):
853 '''Records an exception in an invocation thread.
854
855 An exception with the given message will be rethrown when
856 Goofy is destroyed.'''
857 self.exceptions.append(msg)
858
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800859
860if __name__ == '__main__':
861 Goofy().main()