blob: 04024f4ca4d35f91e92116ba33ade0d0e42e7056 [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
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +080028from cros.factory.event_log import EventLog, FloatDigit
Tom Wai-Hong Tamd33723e2013-04-10 21:14:37 +080029from cros.factory.event_log_watcher import EventLogWatcher
jcliangcd688182012-08-20 21:01:26 +080030from cros.factory.goofy import test_environment
31from cros.factory.goofy import time_sanitizer
Jon Salz83591782012-06-26 11:09:58 +080032from cros.factory.goofy import updater
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
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +080036from cros.factory.goofy.system_log_manager import SystemLogManager
jcliangcd688182012-08-20 21:01:26 +080037from cros.factory.goofy.web_socket_manager import WebSocketManager
Cheng-Yi Chiangd8186952013-04-04 23:41:14 +080038from cros.factory.system.board import Board, BoardException
jcliangcd688182012-08-20 21:01:26 +080039from cros.factory.system.charge_manager import ChargeManager
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +080040from cros.factory.system.core_dump_manager import CoreDumpManager
Jon Salzb92c5112012-09-21 15:40:11 +080041from cros.factory.system import disk_space
jcliangcd688182012-08-20 21:01:26 +080042from cros.factory.test import factory
43from cros.factory.test import state
Jon Salz51528e12012-07-02 18:54:45 +080044from cros.factory.test import shopfloor
Jon Salz83591782012-06-26 11:09:58 +080045from cros.factory.test import utils
46from cros.factory.test.event import Event
47from cros.factory.test.event import EventClient
48from cros.factory.test.event import EventServer
jcliangcd688182012-08-20 21:01:26 +080049from cros.factory.test.factory import TestState
Dean Liao592e4d52013-01-10 20:06:39 +080050from cros.factory.tools.key_filter import KeyFilter
Jon Salz78c32392012-07-25 14:18:29 +080051from cros.factory.utils.process_utils import Spawn
Hung-Te Linf2f78f72012-02-08 19:27:11 +080052
53
Jon Salz2f757d42012-06-27 17:06:42 +080054CUSTOM_DIR = os.path.join(factory.FACTORY_PATH, 'custom')
Hung-Te Linf2f78f72012-02-08 19:27:11 +080055HWID_CFG_PATH = '/usr/local/share/chromeos-hwid/cfg'
Chun-ta Lin279e7e92013-02-19 17:40:39 +080056CACHES_DIR = os.path.join(factory.get_state_root(), "caches")
Hung-Te Linf2f78f72012-02-08 19:27:11 +080057
Jon Salz8796e362012-05-24 11:39:09 +080058# File that suppresses reboot if present (e.g., for development).
59NO_REBOOT_FILE = '/var/log/factory.noreboot'
60
Jon Salz5c344f62012-07-13 14:31:16 +080061# Value for tests_after_shutdown that forces auto-run (e.g., after
62# a factory update, when the available set of tests might change).
63FORCE_AUTO_RUN = 'force_auto_run'
64
cychiang21886742012-07-05 15:16:32 +080065RUN_QUEUE_TIMEOUT_SECS = 10
66
Justin Chuang83813982013-05-13 01:26:32 +080067# Sync disks when battery level is higher than this value.
68# Otherwise, power loss during disk sync operation may incur even worse outcome.
69MIN_BATTERY_LEVEL_FOR_DISK_SYNC = 1.0
70
Jon Salz758e6cc2012-04-03 15:47:07 +080071GOOFY_IN_CHROOT_WARNING = '\n' + ('*' * 70) + '''
72You are running Goofy inside the chroot. Autotests are not supported.
73
74To use Goofy in the chroot, first install an Xvnc server:
75
Jon Salz0697cbf2012-07-04 15:14:04 +080076 sudo apt-get install tightvncserver
Jon Salz758e6cc2012-04-03 15:47:07 +080077
78...and then start a VNC X server outside the chroot:
79
Jon Salz0697cbf2012-07-04 15:14:04 +080080 vncserver :10 &
81 vncviewer :10
Jon Salz758e6cc2012-04-03 15:47:07 +080082
83...and run Goofy as follows:
84
Jon Salz0697cbf2012-07-04 15:14:04 +080085 env --unset=XAUTHORITY DISPLAY=localhost:10 python goofy.py
Jon Salz758e6cc2012-04-03 15:47:07 +080086''' + ('*' * 70)
Jon Salz73e0fd02012-04-04 11:46:38 +080087suppress_chroot_warning = False
Hung-Te Linf2f78f72012-02-08 19:27:11 +080088
89def get_hwid_cfg():
Jon Salz0697cbf2012-07-04 15:14:04 +080090 '''
91 Returns the HWID config tag, or an empty string if none can be found.
92 '''
93 if 'CROS_HWID' in os.environ:
94 return os.environ['CROS_HWID']
95 if os.path.exists(HWID_CFG_PATH):
96 with open(HWID_CFG_PATH, 'rt') as hwid_cfg_handle:
97 return hwid_cfg_handle.read().strip()
98 return ''
Hung-Te Linf2f78f72012-02-08 19:27:11 +080099
100
101def find_test_list():
Jon Salz0697cbf2012-07-04 15:14:04 +0800102 '''
103 Returns the path to the active test list, based on the HWID config tag.
Jon Salzfb615892013-02-01 18:04:35 +0800104
105 The algorithm is:
106
107 - Try $FACTORY/test_lists/active (the symlink reflecting the option chosen
108 in the UI).
109 - For each of $FACTORY/custom, $FACTORY/test_lists (and
110 autotest/site_tests/suite_Factory for backward compatibility):
111 - Try test_list_${hwid_cfg} (if hwid_cfg is set)
112 - Try test_list
113 - Try test_list.generic
Jon Salz0697cbf2012-07-04 15:14:04 +0800114 '''
Jon Salzfb615892013-02-01 18:04:35 +0800115 # If the 'active' symlink is present, that trumps everything else.
116 if os.path.lexists(factory.ACTIVE_TEST_LIST_SYMLINK):
117 return os.path.realpath(factory.ACTIVE_TEST_LIST_SYMLINK)
118
Jon Salz0697cbf2012-07-04 15:14:04 +0800119 hwid_cfg = get_hwid_cfg()
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800120
Jon Salzfb615892013-02-01 18:04:35 +0800121 search_dirs = [CUSTOM_DIR, factory.TEST_LISTS_PATH]
Jon Salz4be56b02012-12-22 07:30:46 +0800122 if not utils.in_chroot():
123 # Also look in suite_Factory. For backward compatibility only;
124 # new boards should just put the test list in the "test_lists"
125 # directory.
126 search_dirs.insert(0, os.path.join(
127 os.path.dirname(factory.FACTORY_PATH),
128 'autotest', 'site_tests', 'suite_Factory'))
Jon Salz2f757d42012-06-27 17:06:42 +0800129
Jon Salzfb615892013-02-01 18:04:35 +0800130
131 search_files = []
Jon Salz0697cbf2012-07-04 15:14:04 +0800132 if hwid_cfg:
Jon Salzfb615892013-02-01 18:04:35 +0800133 search_files += [hwid_cfg]
134 search_files += ['test_list', 'test_list.generic']
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800135
Jon Salz0697cbf2012-07-04 15:14:04 +0800136 for d in search_dirs:
137 for f in search_files:
138 test_list = os.path.join(d, f)
139 if os.path.exists(test_list):
140 return test_list
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800141
Jon Salz0697cbf2012-07-04 15:14:04 +0800142 logging.warn('Cannot find test lists named any of %s in any of %s',
143 search_files, search_dirs)
144 return None
Jon Salz73e0fd02012-04-04 11:46:38 +0800145
Jon Salzfb615892013-02-01 18:04:35 +0800146
Jon Salz73e0fd02012-04-04 11:46:38 +0800147_inited_logging = False
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800148
149class Goofy(object):
Jon Salz0697cbf2012-07-04 15:14:04 +0800150 '''
151 The main factory flow.
152
153 Note that all methods in this class must be invoked from the main
154 (event) thread. Other threads, such as callbacks and TestInvocation
155 methods, should instead post events on the run queue.
156
157 TODO: Unit tests. (chrome-os-partner:7409)
158
159 Properties:
160 uuid: A unique UUID for this invocation of Goofy.
161 state_instance: An instance of FactoryState.
162 state_server: The FactoryState XML/RPC server.
163 state_server_thread: A thread running state_server.
164 event_server: The EventServer socket server.
165 event_server_thread: A thread running event_server.
166 event_client: A client to the event server.
167 connection_manager: The connection_manager object.
Cheng-Yi Chiang835f2682013-05-06 22:15:48 +0800168 system_log_manager: The SystemLogManager object.
169 core_dump_manager: The CoreDumpManager object.
Jon Salz0697cbf2012-07-04 15:14:04 +0800170 ui_process: The factory ui process object.
171 run_queue: A queue of callbacks to invoke from the main thread.
172 invocations: A map from FactoryTest objects to the corresponding
173 TestInvocations objects representing active tests.
174 tests_to_run: A deque of tests that should be run when the current
175 test(s) complete.
176 options: Command-line options.
177 args: Command-line args.
178 test_list: The test list.
179 event_handlers: Map of Event.Type to the method used to handle that
180 event. If the method has an 'event' argument, the event is passed
181 to the handler.
182 exceptions: Exceptions encountered in invocation threads.
Jon Salz3c493bb2013-02-07 17:24:58 +0800183 last_log_disk_space_message: The last message we logged about disk space
184 (to avoid duplication).
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +0800185 last_kick_sync_time: The last time to kick system_log_manager to sync
186 because of core dump files (to avoid kicking too soon then abort the
187 sync.)
Jon Salz416f9cc2013-05-10 18:32:50 +0800188 hooks: A Hooks object containing hooks for various Goofy actions.
Jon Salz0697cbf2012-07-04 15:14:04 +0800189 '''
190 def __init__(self):
191 self.uuid = str(uuid.uuid4())
192 self.state_instance = None
193 self.state_server = None
194 self.state_server_thread = None
Jon Salz16d10542012-07-23 12:18:45 +0800195 self.goofy_rpc = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800196 self.event_server = None
197 self.event_server_thread = None
198 self.event_client = None
199 self.connection_manager = None
Vic Yang4953fc12012-07-26 16:19:53 +0800200 self.charge_manager = None
Jon Salz8fa8e832012-07-13 19:04:09 +0800201 self.time_sanitizer = None
202 self.time_synced = False
Jon Salz0697cbf2012-07-04 15:14:04 +0800203 self.log_watcher = None
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +0800204 self.system_log_manager = None
Cheng-Yi Chiang835f2682013-05-06 22:15:48 +0800205 self.core_dump_manager = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800206 self.event_log = None
207 self.prespawner = None
208 self.ui_process = None
Jon Salzc79a9982012-08-30 04:42:01 +0800209 self.dummy_shopfloor = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800210 self.run_queue = Queue.Queue()
211 self.invocations = {}
212 self.tests_to_run = deque()
213 self.visible_test = None
214 self.chrome = None
Jon Salz416f9cc2013-05-10 18:32:50 +0800215 self.hooks = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800216
217 self.options = None
218 self.args = None
219 self.test_list = None
220 self.on_ui_startup = []
221 self.env = None
Jon Salzb22d1172012-08-06 10:38:57 +0800222 self.last_idle = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800223 self.last_shutdown_time = None
cychiang21886742012-07-05 15:16:32 +0800224 self.last_update_check = None
Jon Salz8fa8e832012-07-13 19:04:09 +0800225 self.last_sync_time = None
Jon Salzb92c5112012-09-21 15:40:11 +0800226 self.last_log_disk_space_time = None
Jon Salz3c493bb2013-02-07 17:24:58 +0800227 self.last_log_disk_space_message = None
Justin Chuang83813982013-05-13 01:26:32 +0800228 self.last_check_battery_time = None
229 self.last_check_battery_message = None
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +0800230 self.last_kick_sync_time = None
Vic Yang311ddb82012-09-26 12:08:28 +0800231 self.exclusive_items = set()
Jon Salz0f996602012-10-03 15:26:48 +0800232 self.event_log = None
Dean Liao592e4d52013-01-10 20:06:39 +0800233 self.key_filter = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800234
Jon Salz85a39882012-07-05 16:45:04 +0800235 def test_or_root(event, parent_or_group=True):
236 '''Returns the test affected by a particular event.
237
238 Args:
239 event: The event containing an optional 'path' attribute.
240 parent_on_group: If True, returns the top-level parent for a test (the
241 root node of the tests that need to be run together if the given test
242 path is to be run).
243 '''
Jon Salz0697cbf2012-07-04 15:14:04 +0800244 try:
245 path = event.path
246 except AttributeError:
247 path = None
248
249 if path:
Jon Salz85a39882012-07-05 16:45:04 +0800250 test = self.test_list.lookup_path(path)
251 if parent_or_group:
252 test = test.get_top_level_parent_or_group()
253 return test
Jon Salz0697cbf2012-07-04 15:14:04 +0800254 else:
255 return self.test_list
256
257 self.event_handlers = {
258 Event.Type.SWITCH_TEST: self.handle_switch_test,
259 Event.Type.SHOW_NEXT_ACTIVE_TEST:
260 lambda event: self.show_next_active_test(),
261 Event.Type.RESTART_TESTS:
262 lambda event: self.restart_tests(root=test_or_root(event)),
263 Event.Type.AUTO_RUN:
264 lambda event: self.auto_run(root=test_or_root(event)),
265 Event.Type.RE_RUN_FAILED:
266 lambda event: self.re_run_failed(root=test_or_root(event)),
267 Event.Type.RUN_TESTS_WITH_STATUS:
268 lambda event: self.run_tests_with_status(
269 event.status,
270 root=test_or_root(event)),
271 Event.Type.REVIEW:
272 lambda event: self.show_review_information(),
273 Event.Type.UPDATE_SYSTEM_INFO:
274 lambda event: self.update_system_info(),
Jon Salz0697cbf2012-07-04 15:14:04 +0800275 Event.Type.STOP:
Jon Salz85a39882012-07-05 16:45:04 +0800276 lambda event: self.stop(root=test_or_root(event, False),
277 fail=getattr(event, 'fail', False)),
Jon Salz36fbbb52012-07-05 13:45:06 +0800278 Event.Type.SET_VISIBLE_TEST:
279 lambda event: self.set_visible_test(
280 self.test_list.lookup_path(event.path)),
Jon Salz4712ac72013-02-07 17:12:05 +0800281 Event.Type.CLEAR_STATE:
282 lambda event: self.clear_state(self.test_list.lookup_path(event.path)),
Jon Salz0697cbf2012-07-04 15:14:04 +0800283 }
284
285 self.exceptions = []
286 self.web_socket_manager = None
287
288 def destroy(self):
289 if self.chrome:
290 self.chrome.kill()
291 self.chrome = None
Jon Salzc79a9982012-08-30 04:42:01 +0800292 if self.dummy_shopfloor:
293 self.dummy_shopfloor.kill()
294 self.dummy_shopfloor = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800295 if self.ui_process:
296 utils.kill_process_tree(self.ui_process, 'ui')
297 self.ui_process = None
298 if self.web_socket_manager:
299 logging.info('Stopping web sockets')
300 self.web_socket_manager.close()
301 self.web_socket_manager = None
302 if self.state_server_thread:
303 logging.info('Stopping state server')
304 self.state_server.shutdown()
305 self.state_server_thread.join()
306 self.state_server.server_close()
307 self.state_server_thread = None
308 if self.state_instance:
309 self.state_instance.close()
310 if self.event_server_thread:
311 logging.info('Stopping event server')
312 self.event_server.shutdown() # pylint: disable=E1101
313 self.event_server_thread.join()
314 self.event_server.server_close()
315 self.event_server_thread = None
316 if self.log_watcher:
317 if self.log_watcher.IsThreadStarted():
318 self.log_watcher.StopWatchThread()
319 self.log_watcher = None
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +0800320 if self.system_log_manager:
321 if self.system_log_manager.IsThreadRunning():
322 self.system_log_manager.StopSyncThread()
323 self.system_log_manager = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800324 if self.prespawner:
325 logging.info('Stopping prespawner')
326 self.prespawner.stop()
327 self.prespawner = None
328 if self.event_client:
329 logging.info('Closing event client')
330 self.event_client.close()
331 self.event_client = None
332 if self.event_log:
333 self.event_log.Close()
334 self.event_log = None
Dean Liao592e4d52013-01-10 20:06:39 +0800335 if self.key_filter:
336 self.key_filter.Stop()
337
Jon Salz0697cbf2012-07-04 15:14:04 +0800338 self.check_exceptions()
339 logging.info('Done destroying Goofy')
340
341 def start_state_server(self):
342 self.state_instance, self.state_server = (
343 state.create_server(bind_address='0.0.0.0'))
Jon Salz16d10542012-07-23 12:18:45 +0800344 self.goofy_rpc = GoofyRPC(self)
345 self.goofy_rpc.RegisterMethods(self.state_instance)
Jon Salz0697cbf2012-07-04 15:14:04 +0800346 logging.info('Starting state server')
347 self.state_server_thread = threading.Thread(
348 target=self.state_server.serve_forever,
349 name='StateServer')
350 self.state_server_thread.start()
351
352 def start_event_server(self):
353 self.event_server = EventServer()
354 logging.info('Starting factory event server')
355 self.event_server_thread = threading.Thread(
356 target=self.event_server.serve_forever,
357 name='EventServer') # pylint: disable=E1101
358 self.event_server_thread.start()
359
360 self.event_client = EventClient(
361 callback=self.handle_event, event_loop=self.run_queue)
362
363 self.web_socket_manager = WebSocketManager(self.uuid)
364 self.state_server.add_handler("/event",
365 self.web_socket_manager.handle_web_socket)
366
367 def start_ui(self):
368 ui_proc_args = [
369 os.path.join(factory.FACTORY_PACKAGE_PATH, 'test', 'ui.py'),
370 self.options.test_list]
371 if self.options.verbose:
372 ui_proc_args.append('-v')
373 logging.info('Starting ui %s', ui_proc_args)
Jon Salz78c32392012-07-25 14:18:29 +0800374 self.ui_process = Spawn(ui_proc_args)
Jon Salz0697cbf2012-07-04 15:14:04 +0800375 logging.info('Waiting for UI to come up...')
376 self.event_client.wait(
377 lambda event: event.type == Event.Type.UI_READY)
378 logging.info('UI has started')
379
380 def set_visible_test(self, test):
381 if self.visible_test == test:
382 return
Jon Salz2f2d42c2012-07-30 12:30:34 +0800383 if test and not test.has_ui:
384 return
Jon Salz0697cbf2012-07-04 15:14:04 +0800385
386 if test:
387 test.update_state(visible=True)
388 if self.visible_test:
389 self.visible_test.update_state(visible=False)
390 self.visible_test = test
391
Jon Salzd4306c82012-11-30 15:16:36 +0800392 def _log_startup_messages(self):
393 '''Logs the tail of var/log/messages and mosys and EC console logs.'''
394 # TODO(jsalz): This is mostly a copy-and-paste of code in init_states,
395 # for factory-3004.B only. Consolidate and merge back to ToT.
396 if utils.in_chroot():
397 return
398
399 try:
400 var_log_messages = (
401 utils.var_log_messages_before_reboot())
402 logging.info(
403 'Tail of /var/log/messages before last reboot:\n'
404 '%s', ('\n'.join(
405 ' ' + x for x in var_log_messages)))
406 except: # pylint: disable=W0702
407 logging.exception('Unable to grok /var/log/messages')
408
409 try:
410 mosys_log = utils.Spawn(
411 ['mosys', 'eventlog', 'list'],
412 read_stdout=True, log_stderr_on_error=True).stdout_data
413 logging.info('System eventlog from mosys:\n%s\n', mosys_log)
414 except: # pylint: disable=W0702
415 logging.exception('Unable to read mosys eventlog')
416
417 try:
Vic Yang8341dde2013-01-29 16:48:52 +0800418 board = system.GetBoard()
419 ec_console_log = board.GetECConsoleLog()
Jon Salzd4306c82012-11-30 15:16:36 +0800420 logging.info('EC console log after reboot:\n%s\n', ec_console_log)
421 except: # pylint: disable=W0702
422 logging.exception('Error retrieving EC console log')
423
Jon Salz0697cbf2012-07-04 15:14:04 +0800424 def handle_shutdown_complete(self, test, test_state):
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800425 '''
Jon Salz0697cbf2012-07-04 15:14:04 +0800426 Handles the case where a shutdown was detected during a shutdown step.
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800427
Jon Salz0697cbf2012-07-04 15:14:04 +0800428 @param test: The ShutdownStep.
429 @param test_state: The test state.
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800430 '''
Jon Salz0697cbf2012-07-04 15:14:04 +0800431 test_state = test.update_state(increment_shutdown_count=1)
432 logging.info('Detected shutdown (%d of %d)',
433 test_state.shutdown_count, test.iterations)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800434
Jon Salz0697cbf2012-07-04 15:14:04 +0800435 def log_and_update_state(status, error_msg, **kw):
436 self.event_log.Log('rebooted',
437 status=status, error_msg=error_msg, **kw)
Jon Salzd4306c82012-11-30 15:16:36 +0800438 logging.info('Rebooted: status=%s, %s', status,
439 (('error_msg=%s' % error_msg) if error_msg else None))
Jon Salz0697cbf2012-07-04 15:14:04 +0800440 test.update_state(status=status, error_msg=error_msg)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800441
Jon Salz0697cbf2012-07-04 15:14:04 +0800442 if not self.last_shutdown_time:
443 log_and_update_state(status=TestState.FAILED,
444 error_msg='Unable to read shutdown_time')
445 return
Jon Salz258a40c2012-04-19 12:34:01 +0800446
Jon Salz0697cbf2012-07-04 15:14:04 +0800447 now = time.time()
448 logging.info('%.03f s passed since reboot',
449 now - self.last_shutdown_time)
Jon Salz258a40c2012-04-19 12:34:01 +0800450
Jon Salz0697cbf2012-07-04 15:14:04 +0800451 if self.last_shutdown_time > now:
452 test.update_state(status=TestState.FAILED,
453 error_msg='Time moved backward during reboot')
454 elif (isinstance(test, factory.RebootStep) and
455 self.test_list.options.max_reboot_time_secs and
456 (now - self.last_shutdown_time >
457 self.test_list.options.max_reboot_time_secs)):
458 # A reboot took too long; fail. (We don't check this for
459 # HaltSteps, because the machine could be halted for a
460 # very long time, and even unplugged with battery backup,
461 # thus hosing the clock.)
462 log_and_update_state(
463 status=TestState.FAILED,
464 error_msg=('More than %d s elapsed during reboot '
465 '(%.03f s, from %s to %s)' % (
466 self.test_list.options.max_reboot_time_secs,
467 now - self.last_shutdown_time,
468 utils.TimeString(self.last_shutdown_time),
469 utils.TimeString(now))),
470 duration=(now-self.last_shutdown_time))
Jon Salzd4306c82012-11-30 15:16:36 +0800471 self._log_startup_messages()
Jon Salz0697cbf2012-07-04 15:14:04 +0800472 elif test_state.shutdown_count == test.iterations:
473 # Good!
474 log_and_update_state(status=TestState.PASSED,
475 duration=(now - self.last_shutdown_time),
476 error_msg='')
477 elif test_state.shutdown_count > test.iterations:
478 # Shut down too many times
479 log_and_update_state(status=TestState.FAILED,
480 error_msg='Too many shutdowns')
Jon Salzd4306c82012-11-30 15:16:36 +0800481 self._log_startup_messages()
Jon Salz0697cbf2012-07-04 15:14:04 +0800482 elif utils.are_shift_keys_depressed():
483 logging.info('Shift keys are depressed; cancelling restarts')
484 # Abort shutdown
485 log_and_update_state(
486 status=TestState.FAILED,
487 error_msg='Shutdown aborted with double shift keys')
Jon Salza6711d72012-07-18 14:33:03 +0800488 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +0800489 else:
490 def handler():
491 if self._prompt_cancel_shutdown(
492 test, test_state.shutdown_count + 1):
Jon Salza6711d72012-07-18 14:33:03 +0800493 factory.console.info('Shutdown aborted by operator')
Jon Salz0697cbf2012-07-04 15:14:04 +0800494 log_and_update_state(
495 status=TestState.FAILED,
496 error_msg='Shutdown aborted by operator')
Jon Salza6711d72012-07-18 14:33:03 +0800497 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +0800498 return
Jon Salz0405ab52012-03-16 15:26:52 +0800499
Jon Salz0697cbf2012-07-04 15:14:04 +0800500 # Time to shutdown again
501 log_and_update_state(
502 status=TestState.ACTIVE,
503 error_msg='',
504 iteration=test_state.shutdown_count)
Jon Salz73e0fd02012-04-04 11:46:38 +0800505
Jon Salz0697cbf2012-07-04 15:14:04 +0800506 self.event_log.Log('shutdown', operation='reboot')
507 self.state_instance.set_shared_data('shutdown_time',
508 time.time())
509 self.env.shutdown('reboot')
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800510
Jon Salz0697cbf2012-07-04 15:14:04 +0800511 self.on_ui_startup.append(handler)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800512
Jon Salz0697cbf2012-07-04 15:14:04 +0800513 def _prompt_cancel_shutdown(self, test, iteration):
514 if self.options.ui != 'chrome':
515 return False
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800516
Jon Salz0697cbf2012-07-04 15:14:04 +0800517 pending_shutdown_data = {
518 'delay_secs': test.delay_secs,
519 'time': time.time() + test.delay_secs,
520 'operation': test.operation,
521 'iteration': iteration,
522 'iterations': test.iterations,
523 }
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800524
Jon Salz0697cbf2012-07-04 15:14:04 +0800525 # Create a new (threaded) event client since we
526 # don't want to use the event loop for this.
527 with EventClient() as event_client:
528 event_client.post_event(Event(Event.Type.PENDING_SHUTDOWN,
529 **pending_shutdown_data))
530 aborted = event_client.wait(
531 lambda event: event.type == Event.Type.CANCEL_SHUTDOWN,
532 timeout=test.delay_secs) is not None
533 if aborted:
534 event_client.post_event(Event(Event.Type.PENDING_SHUTDOWN))
535 return aborted
Jon Salz258a40c2012-04-19 12:34:01 +0800536
Jon Salz0697cbf2012-07-04 15:14:04 +0800537 def init_states(self):
538 '''
539 Initializes all states on startup.
540 '''
541 for test in self.test_list.get_all_tests():
542 # Make sure the state server knows about all the tests,
543 # defaulting to an untested state.
544 test.update_state(update_parent=False, visible=False)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800545
Jon Salz0697cbf2012-07-04 15:14:04 +0800546 var_log_messages = None
Vic Yanga9c32212012-08-16 20:07:54 +0800547 mosys_log = None
Vic Yange4c275d2012-08-28 01:50:20 +0800548 ec_console_log = None
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800549
Jon Salz0697cbf2012-07-04 15:14:04 +0800550 # Any 'active' tests should be marked as failed now.
551 for test in self.test_list.walk():
Jon Salza6711d72012-07-18 14:33:03 +0800552 if not test.is_leaf():
553 # Don't bother with parents; they will be updated when their
554 # children are updated.
555 continue
556
Jon Salz0697cbf2012-07-04 15:14:04 +0800557 test_state = test.get_state()
558 if test_state.status != TestState.ACTIVE:
559 continue
560 if isinstance(test, factory.ShutdownStep):
561 # Shutdown while the test was active - that's good.
562 self.handle_shutdown_complete(test, test_state)
563 else:
564 # Unexpected shutdown. Grab /var/log/messages for context.
565 if var_log_messages is None:
566 try:
567 var_log_messages = (
568 utils.var_log_messages_before_reboot())
569 # Write it to the log, to make it easier to
570 # correlate with /var/log/messages.
571 logging.info(
572 'Unexpected shutdown. '
573 'Tail of /var/log/messages before last reboot:\n'
574 '%s', ('\n'.join(
575 ' ' + x for x in var_log_messages)))
576 except: # pylint: disable=W0702
577 logging.exception('Unable to grok /var/log/messages')
578 var_log_messages = []
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800579
Jon Salz008f4ea2012-08-28 05:39:45 +0800580 if mosys_log is None and not utils.in_chroot():
581 try:
582 mosys_log = utils.Spawn(
583 ['mosys', 'eventlog', 'list'],
584 read_stdout=True, log_stderr_on_error=True).stdout_data
585 # Write it to the log also.
586 logging.info('System eventlog from mosys:\n%s\n', mosys_log)
587 except: # pylint: disable=W0702
588 logging.exception('Unable to read mosys eventlog')
Vic Yanga9c32212012-08-16 20:07:54 +0800589
Vic Yange4c275d2012-08-28 01:50:20 +0800590 if ec_console_log is None:
591 try:
Vic Yang8341dde2013-01-29 16:48:52 +0800592 board = system.GetBoard()
593 ec_console_log = board.GetECConsoleLog()
Vic Yange4c275d2012-08-28 01:50:20 +0800594 logging.info('EC console log after reboot:\n%s\n', ec_console_log)
Jon Salzfe1f6652012-09-07 05:40:14 +0800595 except: # pylint: disable=W0702
Vic Yange4c275d2012-08-28 01:50:20 +0800596 logging.exception('Error retrieving EC console log')
597
Jon Salz0697cbf2012-07-04 15:14:04 +0800598 error_msg = 'Unexpected shutdown while test was running'
599 self.event_log.Log('end_test',
600 path=test.path,
601 status=TestState.FAILED,
602 invocation=test.get_state().invocation,
603 error_msg=error_msg,
Vic Yanga9c32212012-08-16 20:07:54 +0800604 var_log_messages='\n'.join(var_log_messages),
605 mosys_log=mosys_log)
Jon Salz0697cbf2012-07-04 15:14:04 +0800606 test.update_state(
607 status=TestState.FAILED,
608 error_msg=error_msg)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800609
Jon Salz50efe942012-07-26 11:54:10 +0800610 if not test.never_fails:
611 # For "never_fails" tests (such as "Start"), don't cancel
612 # pending tests, since reboot is expected.
613 factory.console.info('Unexpected shutdown while test %s '
614 'running; cancelling any pending tests',
615 test.path)
616 self.state_instance.set_shared_data('tests_after_shutdown', [])
Jon Salz69806bb2012-07-20 18:05:02 +0800617
Jon Salz008f4ea2012-08-28 05:39:45 +0800618 self.update_skipped_tests()
619
620 def update_skipped_tests(self):
621 '''
622 Updates skipped states based on run_if.
623 '''
624 for t in self.test_list.walk():
625 if t.is_leaf() and t.run_if_table_name:
626 skip = False
627 try:
628 aux = shopfloor.get_selected_aux_data(t.run_if_table_name)
629 value = aux.get(t.run_if_col)
630 if value is not None:
631 skip = (not value) ^ t.run_if_not
632 except ValueError:
633 # Not available; assume it shouldn't be skipped
634 pass
635
636 test_state = t.get_state()
637 if ((not skip) and
638 (test_state.status == TestState.PASSED) and
639 (test_state.error_msg == TestState.SKIPPED_MSG)):
640 # It was marked as skipped before, but now we need to run it.
641 # Mark as untested.
642 t.update_state(skip=skip, status=TestState.UNTESTED, error_msg='')
643 else:
644 t.update_state(skip=skip)
645
Jon Salz0697cbf2012-07-04 15:14:04 +0800646 def show_next_active_test(self):
647 '''
648 Rotates to the next visible active test.
649 '''
650 self.reap_completed_tests()
651 active_tests = [
652 t for t in self.test_list.walk()
653 if t.is_leaf() and t.get_state().status == TestState.ACTIVE]
654 if not active_tests:
655 return
Jon Salz4f6c7172012-06-11 20:45:36 +0800656
Jon Salz0697cbf2012-07-04 15:14:04 +0800657 try:
658 next_test = active_tests[
659 (active_tests.index(self.visible_test) + 1) % len(active_tests)]
660 except ValueError: # visible_test not present in active_tests
661 next_test = active_tests[0]
Jon Salz4f6c7172012-06-11 20:45:36 +0800662
Jon Salz0697cbf2012-07-04 15:14:04 +0800663 self.set_visible_test(next_test)
Jon Salz4f6c7172012-06-11 20:45:36 +0800664
Jon Salz0697cbf2012-07-04 15:14:04 +0800665 def handle_event(self, event):
666 '''
667 Handles an event from the event server.
668 '''
669 handler = self.event_handlers.get(event.type)
670 if handler:
671 handler(event)
672 else:
673 # We don't register handlers for all event types - just ignore
674 # this event.
675 logging.debug('Unbound event type %s', event.type)
Jon Salz4f6c7172012-06-11 20:45:36 +0800676
Vic Yangaabf9fd2013-04-09 18:56:13 +0800677 def check_critical_factory_note(self):
678 '''
679 Returns True if the last factory note is critical.
680 '''
681 notes = self.state_instance.get_shared_data('factory_note', True)
682 return notes and notes[-1]['level'] == 'CRITICAL'
683
Jon Salz0697cbf2012-07-04 15:14:04 +0800684 def run_next_test(self):
685 '''
686 Runs the next eligible test (or tests) in self.tests_to_run.
687 '''
688 self.reap_completed_tests()
Vic Yangaabf9fd2013-04-09 18:56:13 +0800689 if self.tests_to_run and self.check_critical_factory_note():
690 self.tests_to_run.clear()
691 return
Jon Salz0697cbf2012-07-04 15:14:04 +0800692 while self.tests_to_run:
693 logging.debug('Tests to run: %s',
694 [x.path for x in self.tests_to_run])
Jon Salz94eb56f2012-06-12 18:01:12 +0800695
Jon Salz0697cbf2012-07-04 15:14:04 +0800696 test = self.tests_to_run[0]
Jon Salz94eb56f2012-06-12 18:01:12 +0800697
Jon Salz0697cbf2012-07-04 15:14:04 +0800698 if test in self.invocations:
699 logging.info('Next test %s is already running', test.path)
700 self.tests_to_run.popleft()
701 return
Jon Salz94eb56f2012-06-12 18:01:12 +0800702
Jon Salza1412922012-07-23 16:04:17 +0800703 for requirement in test.require_run:
704 for i in requirement.test.walk():
705 if i.get_state().status == TestState.ACTIVE:
Jon Salz304a75d2012-07-06 11:14:15 +0800706 logging.info('Waiting for active test %s to complete '
Jon Salza1412922012-07-23 16:04:17 +0800707 'before running %s', i.path, test.path)
Jon Salz304a75d2012-07-06 11:14:15 +0800708 return
709
Jon Salz0697cbf2012-07-04 15:14:04 +0800710 if self.invocations and not (test.backgroundable and all(
711 [x.backgroundable for x in self.invocations])):
712 logging.debug('Waiting for non-backgroundable tests to '
713 'complete before running %s', test.path)
714 return
Jon Salz94eb56f2012-06-12 18:01:12 +0800715
Jon Salz3e6f5202012-10-15 15:08:29 +0800716 if test.get_state().skip:
717 factory.console.info('Skipping test %s', test.path)
718 test.update_state(status=TestState.PASSED,
719 error_msg=TestState.SKIPPED_MSG)
720 self.tests_to_run.popleft()
721 continue
722
Jon Salz0697cbf2012-07-04 15:14:04 +0800723 self.tests_to_run.popleft()
Jon Salz94eb56f2012-06-12 18:01:12 +0800724
Jon Salz304a75d2012-07-06 11:14:15 +0800725 untested = set()
Jon Salza1412922012-07-23 16:04:17 +0800726 for requirement in test.require_run:
727 for i in requirement.test.walk():
728 if i == test:
Jon Salz304a75d2012-07-06 11:14:15 +0800729 # We've hit this test itself; stop checking
730 break
Jon Salza1412922012-07-23 16:04:17 +0800731 if ((i.get_state().status == TestState.UNTESTED) or
732 (requirement.passed and i.get_state().status !=
733 TestState.PASSED)):
Jon Salz304a75d2012-07-06 11:14:15 +0800734 # Found an untested test; move on to the next
735 # element in require_run.
Jon Salza1412922012-07-23 16:04:17 +0800736 untested.add(i)
Jon Salz304a75d2012-07-06 11:14:15 +0800737 break
738
739 if untested:
740 untested_paths = ', '.join(sorted([x.path for x in untested]))
741 if self.state_instance.get_shared_data('engineering_mode',
742 optional=True):
743 # In engineering mode, we'll let it go.
744 factory.console.warn('In engineering mode; running '
745 '%s even though required tests '
746 '[%s] have not completed',
747 test.path, untested_paths)
748 else:
749 # Not in engineering mode; mark it failed.
750 error_msg = ('Required tests [%s] have not been run yet'
751 % untested_paths)
752 factory.console.error('Not running %s: %s',
753 test.path, error_msg)
754 test.update_state(status=TestState.FAILED,
755 error_msg=error_msg)
756 continue
757
Jon Salz0697cbf2012-07-04 15:14:04 +0800758 if isinstance(test, factory.ShutdownStep):
759 if os.path.exists(NO_REBOOT_FILE):
760 test.update_state(
761 status=TestState.FAILED, increment_count=1,
762 error_msg=('Skipped shutdown since %s is present' %
Jon Salz304a75d2012-07-06 11:14:15 +0800763 NO_REBOOT_FILE))
Jon Salz0697cbf2012-07-04 15:14:04 +0800764 continue
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800765
Jon Salz0697cbf2012-07-04 15:14:04 +0800766 test.update_state(status=TestState.ACTIVE, increment_count=1,
767 error_msg='', shutdown_count=0)
768 if self._prompt_cancel_shutdown(test, 1):
769 self.event_log.Log('reboot_cancelled')
770 test.update_state(
771 status=TestState.FAILED, increment_count=1,
772 error_msg='Shutdown aborted by operator',
773 shutdown_count=0)
chungyiafe8f772012-08-15 19:36:29 +0800774 continue
Jon Salz2f757d42012-06-27 17:06:42 +0800775
Jon Salz0697cbf2012-07-04 15:14:04 +0800776 # Save pending test list in the state server
Jon Salzdbf398f2012-06-14 17:30:01 +0800777 self.state_instance.set_shared_data(
Jon Salz0697cbf2012-07-04 15:14:04 +0800778 'tests_after_shutdown',
779 [t.path for t in self.tests_to_run])
780 # Save shutdown time
781 self.state_instance.set_shared_data('shutdown_time',
782 time.time())
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800783
Jon Salz0697cbf2012-07-04 15:14:04 +0800784 with self.env.lock:
785 self.event_log.Log('shutdown', operation=test.operation)
786 shutdown_result = self.env.shutdown(test.operation)
787 if shutdown_result:
788 # That's all, folks!
789 self.run_queue.put(None)
790 return
791 else:
792 # Just pass (e.g., in the chroot).
793 test.update_state(status=TestState.PASSED)
794 self.state_instance.set_shared_data(
795 'tests_after_shutdown', None)
796 # Send event with no fields to indicate that there is no
797 # longer a pending shutdown.
798 self.event_client.post_event(Event(
799 Event.Type.PENDING_SHUTDOWN))
800 continue
Jon Salz258a40c2012-04-19 12:34:01 +0800801
Cheng-Yi Chiangce05c002013-04-04 02:13:17 +0800802 self._run_test(test, test.iterations, test.retries)
Jon Salz1acc8742012-07-17 17:45:55 +0800803
Cheng-Yi Chiangce05c002013-04-04 02:13:17 +0800804 def _run_test(self, test, iterations_left=None, retries_left=None):
Jon Salz1acc8742012-07-17 17:45:55 +0800805 invoc = TestInvocation(self, test, on_completion=self.run_next_test)
806 new_state = test.update_state(
807 status=TestState.ACTIVE, increment_count=1, error_msg='',
Jon Salzbd42ce12012-09-18 08:03:59 +0800808 invocation=invoc.uuid, iterations_left=iterations_left,
Cheng-Yi Chiangce05c002013-04-04 02:13:17 +0800809 retries_left=retries_left,
Jon Salzbd42ce12012-09-18 08:03:59 +0800810 visible=(self.visible_test == test))
Jon Salz1acc8742012-07-17 17:45:55 +0800811 invoc.count = new_state.count
812
813 self.invocations[test] = invoc
814 if self.visible_test is None and test.has_ui:
815 self.set_visible_test(test)
Vic Yang311ddb82012-09-26 12:08:28 +0800816 self.check_exclusive()
Jon Salz1acc8742012-07-17 17:45:55 +0800817 invoc.start()
Jon Salz5f2a0672012-05-22 17:14:06 +0800818
Vic Yang311ddb82012-09-26 12:08:28 +0800819 def check_exclusive(self):
820 current_exclusive_items = set([
821 item
822 for item in factory.FactoryTest.EXCLUSIVE_OPTIONS
823 if any([test.is_exclusive(item) for test in self.invocations])])
824
825 new_exclusive_items = current_exclusive_items - self.exclusive_items
826 if factory.FactoryTest.EXCLUSIVE_OPTIONS.NETWORKING in new_exclusive_items:
827 logging.info('Disabling network')
828 self.connection_manager.DisableNetworking()
829 if factory.FactoryTest.EXCLUSIVE_OPTIONS.CHARGER in new_exclusive_items:
830 logging.info('Stop controlling charger')
831
832 new_non_exclusive_items = self.exclusive_items - current_exclusive_items
833 if (factory.FactoryTest.EXCLUSIVE_OPTIONS.NETWORKING in
834 new_non_exclusive_items):
835 logging.info('Re-enabling network')
836 self.connection_manager.EnableNetworking()
837 if factory.FactoryTest.EXCLUSIVE_OPTIONS.CHARGER in new_non_exclusive_items:
838 logging.info('Start controlling charger')
839
840 # Only adjust charge state if not excluded
Cheng-Yi Chiangd8186952013-04-04 23:41:14 +0800841 if (factory.FactoryTest.EXCLUSIVE_OPTIONS.CHARGER not in
Vic Yange83d9a12013-04-19 20:00:20 +0800842 current_exclusive_items and not utils.in_chroot()):
Cheng-Yi Chiangd8186952013-04-04 23:41:14 +0800843 if self.charge_manager:
844 self.charge_manager.AdjustChargeState()
845 else:
846 try:
847 system.GetBoard().SetChargeState(Board.ChargeState.CHARGE)
848 except BoardException:
849 logging.exception('Unable to set charge state on this board')
Vic Yang311ddb82012-09-26 12:08:28 +0800850
851 self.exclusive_items = current_exclusive_items
Jon Salz5da61e62012-05-31 13:06:22 +0800852
cychiang21886742012-07-05 15:16:32 +0800853 def check_for_updates(self):
854 '''
855 Schedules an asynchronous check for updates if necessary.
856 '''
857 if not self.test_list.options.update_period_secs:
858 # Not enabled.
859 return
860
861 now = time.time()
862 if self.last_update_check and (
863 now - self.last_update_check <
864 self.test_list.options.update_period_secs):
865 # Not yet time for another check.
866 return
867
868 self.last_update_check = now
869
870 def handle_check_for_update(reached_shopfloor, md5sum, needs_update):
871 if reached_shopfloor:
872 new_update_md5sum = md5sum if needs_update else None
873 if system.SystemInfo.update_md5sum != new_update_md5sum:
874 logging.info('Received new update MD5SUM: %s', new_update_md5sum)
875 system.SystemInfo.update_md5sum = new_update_md5sum
876 self.run_queue.put(self.update_system_info)
877
878 updater.CheckForUpdateAsync(
879 handle_check_for_update,
880 self.test_list.options.shopfloor_timeout_secs)
881
Jon Salza6711d72012-07-18 14:33:03 +0800882 def cancel_pending_tests(self):
883 '''Cancels any tests in the run queue.'''
884 self.run_tests([])
885
Jon Salz0697cbf2012-07-04 15:14:04 +0800886 def run_tests(self, subtrees, untested_only=False):
887 '''
888 Runs tests under subtree.
Jon Salz258a40c2012-04-19 12:34:01 +0800889
Jon Salz0697cbf2012-07-04 15:14:04 +0800890 The tests are run in order unless one fails (then stops).
891 Backgroundable tests are run simultaneously; when a foreground test is
892 encountered, we wait for all active tests to finish before continuing.
Jon Salzb1b39092012-05-03 02:05:09 +0800893
Jon Salz0697cbf2012-07-04 15:14:04 +0800894 @param subtrees: Node or nodes containing tests to run (may either be
895 a single test or a list). Duplicates will be ignored.
896 '''
897 if type(subtrees) != list:
898 subtrees = [subtrees]
Jon Salz258a40c2012-04-19 12:34:01 +0800899
Jon Salz0697cbf2012-07-04 15:14:04 +0800900 # Nodes we've seen so far, to avoid duplicates.
901 seen = set()
Jon Salz94eb56f2012-06-12 18:01:12 +0800902
Jon Salz0697cbf2012-07-04 15:14:04 +0800903 self.tests_to_run = deque()
904 for subtree in subtrees:
905 for test in subtree.walk():
906 if test in seen:
907 continue
908 seen.add(test)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800909
Jon Salz0697cbf2012-07-04 15:14:04 +0800910 if not test.is_leaf():
911 continue
912 if (untested_only and
913 test.get_state().status != TestState.UNTESTED):
914 continue
915 self.tests_to_run.append(test)
916 self.run_next_test()
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800917
Jon Salz0697cbf2012-07-04 15:14:04 +0800918 def reap_completed_tests(self):
919 '''
920 Removes completed tests from the set of active tests.
921
922 Also updates the visible test if it was reaped.
923 '''
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +0800924 test_completed = False
Jon Salz0697cbf2012-07-04 15:14:04 +0800925 for t, v in dict(self.invocations).iteritems():
926 if v.is_completed():
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +0800927 test_completed = True
Jon Salz1acc8742012-07-17 17:45:55 +0800928 new_state = t.update_state(**v.update_state_on_completion)
Jon Salz0697cbf2012-07-04 15:14:04 +0800929 del self.invocations[t]
930
Chun-Ta Lin54e17e42012-09-06 22:05:13 +0800931 # Stop on failure if flag is true.
932 if (self.test_list.options.stop_on_failure and
933 new_state.status == TestState.FAILED):
934 # Clean all the tests to cause goofy to stop.
935 self.tests_to_run = []
936 factory.console.info("Stop on failure triggered. Empty the queue.")
937
Jon Salz1acc8742012-07-17 17:45:55 +0800938 if new_state.iterations_left and new_state.status == TestState.PASSED:
939 # Play it again, Sam!
940 self._run_test(t)
Cheng-Yi Chiangce05c002013-04-04 02:13:17 +0800941 # new_state.retries_left is obtained after update.
942 # For retries_left == 0, test can still be run for the last time.
943 elif (new_state.retries_left >= 0 and
944 new_state.status == TestState.FAILED):
945 # Still have to retry, Sam!
946 self._run_test(t)
Jon Salz1acc8742012-07-17 17:45:55 +0800947
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +0800948 if test_completed:
Vic Yangf01c59f2013-04-19 17:37:56 +0800949 self.log_watcher.KickWatchThread()
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +0800950
Jon Salz0697cbf2012-07-04 15:14:04 +0800951 if (self.visible_test is None or
Jon Salz85a39882012-07-05 16:45:04 +0800952 self.visible_test not in self.invocations):
Jon Salz0697cbf2012-07-04 15:14:04 +0800953 self.set_visible_test(None)
954 # Make the first running test, if any, the visible test
955 for t in self.test_list.walk():
956 if t in self.invocations:
957 self.set_visible_test(t)
958 break
959
Jon Salz85a39882012-07-05 16:45:04 +0800960 def kill_active_tests(self, abort, root=None):
Jon Salz0697cbf2012-07-04 15:14:04 +0800961 '''
962 Kills and waits for all active tests.
963
Jon Salz85a39882012-07-05 16:45:04 +0800964 Args:
965 abort: True to change state of killed tests to FAILED, False for
Jon Salz0697cbf2012-07-04 15:14:04 +0800966 UNTESTED.
Jon Salz85a39882012-07-05 16:45:04 +0800967 root: If set, only kills tests with root as an ancestor.
Jon Salz0697cbf2012-07-04 15:14:04 +0800968 '''
969 self.reap_completed_tests()
970 for test, invoc in self.invocations.items():
Jon Salz85a39882012-07-05 16:45:04 +0800971 if root and not test.has_ancestor(root):
972 continue
973
Jon Salz0697cbf2012-07-04 15:14:04 +0800974 factory.console.info('Killing active test %s...' % test.path)
975 invoc.abort_and_join()
976 factory.console.info('Killed %s' % test.path)
Jon Salz1acc8742012-07-17 17:45:55 +0800977 test.update_state(**invoc.update_state_on_completion)
Jon Salz0697cbf2012-07-04 15:14:04 +0800978 del self.invocations[test]
Jon Salz1acc8742012-07-17 17:45:55 +0800979
Jon Salz0697cbf2012-07-04 15:14:04 +0800980 if not abort:
981 test.update_state(status=TestState.UNTESTED)
982 self.reap_completed_tests()
983
Jon Salz85a39882012-07-05 16:45:04 +0800984 def stop(self, root=None, fail=False):
985 self.kill_active_tests(fail, root)
986 # Remove any tests in the run queue under the root.
987 self.tests_to_run = deque([x for x in self.tests_to_run
988 if root and not x.has_ancestor(root)])
989 self.run_next_test()
Jon Salz0697cbf2012-07-04 15:14:04 +0800990
Jon Salz4712ac72013-02-07 17:12:05 +0800991 def clear_state(self, root=None):
992 self.stop(root)
993 for f in root.walk():
994 if f.is_leaf():
995 f.update_state(status=TestState.UNTESTED)
996
Jon Salz0697cbf2012-07-04 15:14:04 +0800997 def abort_active_tests(self):
998 self.kill_active_tests(True)
999
1000 def main(self):
1001 try:
1002 self.init()
1003 self.event_log.Log('goofy_init',
1004 success=True)
1005 except:
1006 if self.event_log:
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001007 try:
Jon Salz0697cbf2012-07-04 15:14:04 +08001008 self.event_log.Log('goofy_init',
1009 success=False,
1010 trace=traceback.format_exc())
1011 except: # pylint: disable=W0702
1012 pass
1013 raise
1014
1015 self.run()
1016
1017 def update_system_info(self):
1018 '''Updates system info.'''
1019 system_info = system.SystemInfo()
1020 self.state_instance.set_shared_data('system_info', system_info.__dict__)
1021 self.event_client.post_event(Event(Event.Type.SYSTEM_INFO,
1022 system_info=system_info.__dict__))
1023 logging.info('System info: %r', system_info.__dict__)
1024
Jon Salzeb42f0d2012-07-27 19:14:04 +08001025 def update_factory(self, auto_run_on_restart=False, post_update_hook=None):
1026 '''Commences updating factory software.
1027
1028 Args:
1029 auto_run_on_restart: Auto-run when the machine comes back up.
1030 post_update_hook: Code to call after update but immediately before
1031 restart.
1032
1033 Returns:
1034 Never if the update was successful (we just reboot).
1035 False if the update was unnecessary (no update available).
1036 '''
Jon Salz0697cbf2012-07-04 15:14:04 +08001037 self.kill_active_tests(False)
Jon Salza6711d72012-07-18 14:33:03 +08001038 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +08001039
Jon Salz5c344f62012-07-13 14:31:16 +08001040 def pre_update_hook():
1041 if auto_run_on_restart:
1042 self.state_instance.set_shared_data('tests_after_shutdown',
1043 FORCE_AUTO_RUN)
1044 self.state_instance.close()
1045
Jon Salzeb42f0d2012-07-27 19:14:04 +08001046 if updater.TryUpdate(pre_update_hook=pre_update_hook):
1047 if post_update_hook:
1048 post_update_hook()
1049 self.env.shutdown('reboot')
Jon Salz0697cbf2012-07-04 15:14:04 +08001050
Jon Salzcef132a2012-08-30 04:58:08 +08001051 def handle_sigint(self, dummy_signum, dummy_frame):
Jon Salz77c151e2012-08-28 07:20:37 +08001052 logging.error('Received SIGINT')
1053 self.run_queue.put(None)
1054 raise KeyboardInterrupt()
1055
Jon Salz0697cbf2012-07-04 15:14:04 +08001056 def init(self, args=None, env=None):
1057 '''Initializes Goofy.
1058
1059 Args:
1060 args: A list of command-line arguments. Uses sys.argv if
1061 args is None.
1062 env: An Environment instance to use (or None to choose
1063 FakeChrootEnvironment or DUTEnvironment as appropriate).
1064 '''
Jon Salz77c151e2012-08-28 07:20:37 +08001065 signal.signal(signal.SIGINT, self.handle_sigint)
1066
Jon Salz0697cbf2012-07-04 15:14:04 +08001067 parser = OptionParser()
1068 parser.add_option('-v', '--verbose', dest='verbose',
Jon Salz8fa8e832012-07-13 19:04:09 +08001069 action='store_true',
1070 help='Enable debug logging')
Jon Salz0697cbf2012-07-04 15:14:04 +08001071 parser.add_option('--print_test_list', dest='print_test_list',
Jon Salz8fa8e832012-07-13 19:04:09 +08001072 metavar='FILE',
1073 help='Read and print test list FILE, and exit')
Jon Salz0697cbf2012-07-04 15:14:04 +08001074 parser.add_option('--restart', dest='restart',
Jon Salz8fa8e832012-07-13 19:04:09 +08001075 action='store_true',
1076 help='Clear all test state')
Jon Salz0697cbf2012-07-04 15:14:04 +08001077 parser.add_option('--ui', dest='ui', type='choice',
Jon Salz8fa8e832012-07-13 19:04:09 +08001078 choices=['none', 'gtk', 'chrome'],
Jon Salz2f881df2013-02-01 17:00:35 +08001079 default='chrome',
Jon Salz8fa8e832012-07-13 19:04:09 +08001080 help='UI to use')
Jon Salz0697cbf2012-07-04 15:14:04 +08001081 parser.add_option('--ui_scale_factor', dest='ui_scale_factor',
Jon Salz8fa8e832012-07-13 19:04:09 +08001082 type='int', default=1,
1083 help=('Factor by which to scale UI '
1084 '(Chrome UI only)'))
Jon Salz0697cbf2012-07-04 15:14:04 +08001085 parser.add_option('--test_list', dest='test_list',
Jon Salz8fa8e832012-07-13 19:04:09 +08001086 metavar='FILE',
1087 help='Use FILE as test list')
Jon Salzc79a9982012-08-30 04:42:01 +08001088 parser.add_option('--dummy_shopfloor', action='store_true',
1089 help='Use a dummy shopfloor server')
chungyiafe8f772012-08-15 19:36:29 +08001090 parser.add_option('--automation', dest='automation',
1091 action='store_true',
1092 help='Enable automation on running factory test')
Ricky Liang09216dc2013-02-22 17:26:45 +08001093 parser.add_option('--one_pixel_less', dest='one_pixel_less',
1094 action='store_true',
1095 help=('Start Chrome one pixel less than the full screen.'
1096 'Needed by Exynos platform to run GTK.'))
Jon Salz0697cbf2012-07-04 15:14:04 +08001097 (self.options, self.args) = parser.parse_args(args)
1098
Jon Salz46b89562012-07-05 11:49:22 +08001099 # Make sure factory directories exist.
1100 factory.get_log_root()
1101 factory.get_state_root()
1102 factory.get_test_data_root()
1103
Jon Salz0697cbf2012-07-04 15:14:04 +08001104 global _inited_logging # pylint: disable=W0603
1105 if not _inited_logging:
1106 factory.init_logging('goofy', verbose=self.options.verbose)
1107 _inited_logging = True
Jon Salz8fa8e832012-07-13 19:04:09 +08001108
Jon Salz0f996602012-10-03 15:26:48 +08001109 if self.options.print_test_list:
1110 print factory.read_test_list(
1111 self.options.print_test_list).__repr__(recursive=True)
1112 sys.exit(0)
1113
Jon Salzee85d522012-07-17 14:34:46 +08001114 event_log.IncrementBootSequence()
Jon Salz0697cbf2012-07-04 15:14:04 +08001115 self.event_log = EventLog('goofy')
1116
1117 if (not suppress_chroot_warning and
1118 factory.in_chroot() and
1119 self.options.ui == 'gtk' and
1120 os.environ.get('DISPLAY') in [None, '', ':0', ':0.0']):
1121 # That's not going to work! Tell the user how to run
1122 # this way.
1123 logging.warn(GOOFY_IN_CHROOT_WARNING)
1124 time.sleep(1)
1125
1126 if env:
1127 self.env = env
1128 elif factory.in_chroot():
1129 self.env = test_environment.FakeChrootEnvironment()
1130 logging.warn(
1131 'Using chroot environment: will not actually run autotests')
1132 else:
1133 self.env = test_environment.DUTEnvironment()
1134 self.env.goofy = self
1135
1136 if self.options.restart:
1137 state.clear_state()
1138
Jon Salz0697cbf2012-07-04 15:14:04 +08001139 if self.options.ui_scale_factor != 1 and utils.in_qemu():
1140 logging.warn(
1141 'In QEMU; ignoring ui_scale_factor argument')
1142 self.options.ui_scale_factor = 1
1143
1144 logging.info('Started')
1145
1146 self.start_state_server()
1147 self.state_instance.set_shared_data('hwid_cfg', get_hwid_cfg())
1148 self.state_instance.set_shared_data('ui_scale_factor',
Ricky Liang09216dc2013-02-22 17:26:45 +08001149 self.options.ui_scale_factor)
1150 self.state_instance.set_shared_data('one_pixel_less',
1151 self.options.one_pixel_less)
Jon Salz0697cbf2012-07-04 15:14:04 +08001152 self.last_shutdown_time = (
1153 self.state_instance.get_shared_data('shutdown_time', optional=True))
1154 self.state_instance.del_shared_data('shutdown_time', optional=True)
1155
Jon Salzb19ea072013-02-07 16:35:00 +08001156 self.state_instance.del_shared_data('startup_error', optional=True)
Jon Salz0697cbf2012-07-04 15:14:04 +08001157 if not self.options.test_list:
1158 self.options.test_list = find_test_list()
Jon Salzb19ea072013-02-07 16:35:00 +08001159 if self.options.test_list:
Jon Salz0697cbf2012-07-04 15:14:04 +08001160 logging.info('Using test list %s', self.options.test_list)
Jon Salzb19ea072013-02-07 16:35:00 +08001161 try:
1162 self.test_list = factory.read_test_list(
1163 self.options.test_list,
1164 self.state_instance)
1165 except: # pylint: disable=W0702
1166 logging.exception('Unable to read test list %r', self.options.test_list)
1167 self.state_instance.set_shared_data('startup_error',
1168 'Unable to read test list %s\n%s' % (
1169 self.options.test_list,
1170 traceback.format_exc()))
1171 else:
1172 logging.error('No test list found.')
1173 self.state_instance.set_shared_data('startup_error',
1174 'No test list found.')
Jon Salz0697cbf2012-07-04 15:14:04 +08001175
Jon Salzb19ea072013-02-07 16:35:00 +08001176 if not self.test_list:
1177 if self.options.ui == 'chrome':
1178 # Create an empty test list with default options so that the rest of
1179 # startup can proceed.
1180 self.test_list = factory.FactoryTestList(
1181 [], self.state_instance, factory.Options())
1182 else:
1183 # Bail with an error; no point in starting up.
1184 sys.exit('No valid test list; exiting.')
1185
Jon Salz822838b2013-03-25 17:32:33 +08001186 if self.test_list.options.clear_state_on_start:
1187 self.state_instance.clear_test_state()
1188
Jon Salz0697cbf2012-07-04 15:14:04 +08001189 if not self.state_instance.has_shared_data('ui_lang'):
1190 self.state_instance.set_shared_data('ui_lang',
1191 self.test_list.options.ui_lang)
1192 self.state_instance.set_shared_data(
1193 'test_list_options',
1194 self.test_list.options.__dict__)
1195 self.state_instance.test_list = self.test_list
1196
Jon Salz83ef34b2012-11-01 19:46:35 +08001197 if not utils.in_chroot() and self.test_list.options.disable_log_rotation:
1198 open('/var/lib/cleanup_logs_paused', 'w').close()
1199
Jon Salz23926422012-09-01 03:38:13 +08001200 if self.options.dummy_shopfloor:
1201 os.environ[shopfloor.SHOPFLOOR_SERVER_ENV_VAR_NAME] = (
1202 'http://localhost:%d/' % shopfloor.DEFAULT_SERVER_PORT)
1203 self.dummy_shopfloor = Spawn(
1204 [os.path.join(factory.FACTORY_PATH, 'bin', 'shopfloor_server'),
1205 '--dummy'])
1206 elif self.test_list.options.shopfloor_server_url:
1207 shopfloor.set_server_url(self.test_list.options.shopfloor_server_url)
Jon Salz2bf2f6b2013-03-28 18:49:26 +08001208 shopfloor.set_enabled(True)
Jon Salz23926422012-09-01 03:38:13 +08001209
Jon Salz0f996602012-10-03 15:26:48 +08001210 if self.test_list.options.time_sanitizer and not utils.in_chroot():
Jon Salz8fa8e832012-07-13 19:04:09 +08001211 self.time_sanitizer = time_sanitizer.TimeSanitizer(
1212 base_time=time_sanitizer.GetBaseTimeFromFile(
1213 # lsb-factory is written by the factory install shim during
1214 # installation, so it should have a good time obtained from
Jon Salz54882d02012-08-31 01:57:54 +08001215 # the mini-Omaha server. If it's not available, we'll use
1216 # /etc/lsb-factory (which will be much older, but reasonably
1217 # sane) and rely on a shopfloor sync to set a more accurate
1218 # time.
1219 '/usr/local/etc/lsb-factory',
1220 '/etc/lsb-release'))
Jon Salz8fa8e832012-07-13 19:04:09 +08001221 self.time_sanitizer.RunOnce()
1222
Jon Salz0697cbf2012-07-04 15:14:04 +08001223 self.init_states()
1224 self.start_event_server()
1225 self.connection_manager = self.env.create_connection_manager(
Tai-Hsu Lin371351a2012-08-27 14:17:14 +08001226 self.test_list.options.wlans,
1227 self.test_list.options.scan_wifi_period_secs)
Jon Salz0697cbf2012-07-04 15:14:04 +08001228 # Note that we create a log watcher even if
1229 # sync_event_log_period_secs isn't set (no background
1230 # syncing), since we may use it to flush event logs as well.
1231 self.log_watcher = EventLogWatcher(
1232 self.test_list.options.sync_event_log_period_secs,
Jon Salz16d10542012-07-23 12:18:45 +08001233 handle_event_logs_callback=self.handle_event_logs)
Jon Salz0697cbf2012-07-04 15:14:04 +08001234 if self.test_list.options.sync_event_log_period_secs:
1235 self.log_watcher.StartWatchThread()
1236
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +08001237 # Note that we create a system log manager even if
1238 # sync_log_period_secs isn't set (no background
1239 # syncing), since we may kick it to sync logs in its
1240 # thread.
1241 self.system_log_manager = SystemLogManager(
Cheng-Yi Chiang835f2682013-05-06 22:15:48 +08001242 sync_log_paths=self.test_list.options.sync_log_paths,
1243 sync_period_sec=self.test_list.options.sync_log_period_secs,
1244 clear_log_paths=self.test_list.options.clear_log_paths)
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +08001245 self.system_log_manager.StartSyncThread()
1246
Jon Salz0697cbf2012-07-04 15:14:04 +08001247 self.update_system_info()
1248
Vic Yang4953fc12012-07-26 16:19:53 +08001249 assert ((self.test_list.options.min_charge_pct is None) ==
1250 (self.test_list.options.max_charge_pct is None))
Vic Yange83d9a12013-04-19 20:00:20 +08001251 if utils.in_chroot():
1252 logging.info('In chroot, ignoring charge manager and charge state')
1253 elif self.test_list.options.min_charge_pct is not None:
Vic Yang4953fc12012-07-26 16:19:53 +08001254 self.charge_manager = ChargeManager(self.test_list.options.min_charge_pct,
1255 self.test_list.options.max_charge_pct)
Jon Salzad7353b2012-10-15 16:22:46 +08001256 system.SystemStatus.charge_manager = self.charge_manager
Cheng-Yi Chiangd8186952013-04-04 23:41:14 +08001257 else:
1258 # Goofy should set charger state to charge if charge_manager is disabled.
1259 try:
1260 system.GetBoard().SetChargeState(Board.ChargeState.CHARGE)
1261 except BoardException:
1262 logging.exception('Unable to set charge state on this board')
Vic Yang4953fc12012-07-26 16:19:53 +08001263
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001264 self.core_dump_manager = CoreDumpManager(
1265 self.test_list.options.core_dump_watchlist)
1266
Jon Salz0697cbf2012-07-04 15:14:04 +08001267 os.environ['CROS_FACTORY'] = '1'
1268 os.environ['CROS_DISABLE_SITE_SYSINFO'] = '1'
1269
1270 # Set CROS_UI since some behaviors in ui.py depend on the
1271 # particular UI in use. TODO(jsalz): Remove this (and all
1272 # places it is used) when the GTK UI is removed.
1273 os.environ['CROS_UI'] = self.options.ui
1274
Jon Salz416f9cc2013-05-10 18:32:50 +08001275 # Initialize hooks.
1276 module, cls = self.test_list.options.hooks_class.rsplit('.', 1)
1277 self.hooks = getattr(__import__(module, fromlist=[cls]), cls)()
1278 assert isinstance(self.hooks, factory.Hooks), (
1279 "hooks should be of type Hooks but is %r" % type(self.hooks))
1280 self.hooks.test_list = self.test_list
1281
1282 # Call startup hook.
1283 self.hooks.OnStartup()
1284
Jon Salz0697cbf2012-07-04 15:14:04 +08001285 if self.options.ui == 'chrome':
1286 self.env.launch_chrome()
1287 logging.info('Waiting for a web socket connection')
Cheng-Yi Chiangfd8ed392013-03-08 21:37:31 +08001288 self.web_socket_manager.wait()
Jon Salz0697cbf2012-07-04 15:14:04 +08001289
1290 # Wait for the test widget size to be set; this is done in
1291 # an asynchronous RPC so there is a small chance that the
1292 # web socket might be opened first.
1293 for _ in range(100): # 10 s
1294 try:
1295 if self.state_instance.get_shared_data('test_widget_size'):
1296 break
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001297 except KeyError:
Jon Salz0697cbf2012-07-04 15:14:04 +08001298 pass # Retry
1299 time.sleep(0.1) # 100 ms
1300 else:
1301 logging.warn('Never received test_widget_size from UI')
1302 elif self.options.ui == 'gtk':
1303 self.start_ui()
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001304
Ricky Liang650f6bf2012-09-28 13:22:54 +08001305 # Create download path for autotest beforehand or autotests run at
1306 # the same time might fail due to race condition.
1307 if not factory.in_chroot():
1308 utils.TryMakeDirs(os.path.join('/usr/local/autotest', 'tests',
1309 'download'))
1310
Jon Salz0697cbf2012-07-04 15:14:04 +08001311 def state_change_callback(test, test_state):
1312 self.event_client.post_event(
1313 Event(Event.Type.STATE_CHANGE,
1314 path=test.path, state=test_state))
1315 self.test_list.state_change_callback = state_change_callback
Jon Salz73e0fd02012-04-04 11:46:38 +08001316
Jon Salza6711d72012-07-18 14:33:03 +08001317 for handler in self.on_ui_startup:
1318 handler()
1319
1320 self.prespawner = Prespawner()
1321 self.prespawner.start()
1322
Jon Salz0697cbf2012-07-04 15:14:04 +08001323 try:
1324 tests_after_shutdown = self.state_instance.get_shared_data(
1325 'tests_after_shutdown')
1326 except KeyError:
1327 tests_after_shutdown = None
Jon Salz57717ca2012-04-04 16:47:25 +08001328
Jon Salz5c344f62012-07-13 14:31:16 +08001329 force_auto_run = (tests_after_shutdown == FORCE_AUTO_RUN)
1330 if not force_auto_run and tests_after_shutdown is not None:
Jon Salz0697cbf2012-07-04 15:14:04 +08001331 logging.info('Resuming tests after shutdown: %s',
1332 tests_after_shutdown)
Jon Salz0697cbf2012-07-04 15:14:04 +08001333 self.tests_to_run.extend(
1334 self.test_list.lookup_path(t) for t in tests_after_shutdown)
1335 self.run_queue.put(self.run_next_test)
1336 else:
Jon Salz5c344f62012-07-13 14:31:16 +08001337 if force_auto_run or self.test_list.options.auto_run_on_start:
Jon Salz0697cbf2012-07-04 15:14:04 +08001338 self.run_queue.put(
1339 lambda: self.run_tests(self.test_list, untested_only=True))
Jon Salz5c344f62012-07-13 14:31:16 +08001340 self.state_instance.set_shared_data('tests_after_shutdown', None)
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001341
Dean Liao592e4d52013-01-10 20:06:39 +08001342 self.may_disable_cros_shortcut_keys()
1343
1344 def may_disable_cros_shortcut_keys(self):
1345 test_options = self.test_list.options
1346 if test_options.disable_cros_shortcut_keys:
1347 logging.info('Filter ChromeOS shortcut keys.')
1348 self.key_filter = KeyFilter(
1349 unmap_caps_lock=test_options.disable_caps_lock,
1350 caps_lock_keycode=test_options.caps_lock_keycode)
1351 self.key_filter.Start()
1352
Jon Salz0697cbf2012-07-04 15:14:04 +08001353 def run(self):
1354 '''Runs Goofy.'''
1355 # Process events forever.
1356 while self.run_once(True):
1357 pass
Jon Salz73e0fd02012-04-04 11:46:38 +08001358
Jon Salz0697cbf2012-07-04 15:14:04 +08001359 def run_once(self, block=False):
1360 '''Runs all items pending in the event loop.
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001361
Jon Salz0697cbf2012-07-04 15:14:04 +08001362 Args:
1363 block: If true, block until at least one event is processed.
Jon Salz7c15e8b2012-06-19 17:10:37 +08001364
Jon Salz0697cbf2012-07-04 15:14:04 +08001365 Returns:
1366 True to keep going or False to shut down.
1367 '''
1368 events = utils.DrainQueue(self.run_queue)
cychiang21886742012-07-05 15:16:32 +08001369 while not events:
Jon Salz0697cbf2012-07-04 15:14:04 +08001370 # Nothing on the run queue.
1371 self._run_queue_idle()
1372 if block:
1373 # Block for at least one event...
cychiang21886742012-07-05 15:16:32 +08001374 try:
1375 events.append(self.run_queue.get(timeout=RUN_QUEUE_TIMEOUT_SECS))
1376 except Queue.Empty:
1377 # Keep going (calling _run_queue_idle() again at the top of
1378 # the loop)
1379 continue
Jon Salz0697cbf2012-07-04 15:14:04 +08001380 # ...and grab anything else that showed up at the same
1381 # time.
1382 events.extend(utils.DrainQueue(self.run_queue))
cychiang21886742012-07-05 15:16:32 +08001383 else:
1384 break
Jon Salz51528e12012-07-02 18:54:45 +08001385
Jon Salz0697cbf2012-07-04 15:14:04 +08001386 for event in events:
1387 if not event:
1388 # Shutdown request.
1389 self.run_queue.task_done()
1390 return False
Jon Salz51528e12012-07-02 18:54:45 +08001391
Jon Salz0697cbf2012-07-04 15:14:04 +08001392 try:
1393 event()
Jon Salz85a39882012-07-05 16:45:04 +08001394 except: # pylint: disable=W0702
1395 logging.exception('Error in event loop')
Jon Salz0697cbf2012-07-04 15:14:04 +08001396 self.record_exception(traceback.format_exception_only(
1397 *sys.exc_info()[:2]))
1398 # But keep going
1399 finally:
1400 self.run_queue.task_done()
1401 return True
Jon Salz0405ab52012-03-16 15:26:52 +08001402
Jon Salz0e6532d2012-10-25 16:30:11 +08001403 def _should_sync_time(self, foreground=False):
1404 '''Returns True if we should attempt syncing time with shopfloor.
1405
1406 Args:
1407 foreground: If True, synchronizes even if background syncing
1408 is disabled (e.g., in explicit sync requests from the
1409 SyncShopfloor test).
1410 '''
1411 return ((foreground or
1412 self.test_list.options.sync_time_period_secs) and
Jon Salz54882d02012-08-31 01:57:54 +08001413 self.time_sanitizer and
1414 (not self.time_synced) and
1415 (not factory.in_chroot()))
1416
Jon Salz0e6532d2012-10-25 16:30:11 +08001417 def sync_time_with_shopfloor_server(self, foreground=False):
Jon Salz54882d02012-08-31 01:57:54 +08001418 '''Syncs time with shopfloor server, if not yet synced.
1419
Jon Salz0e6532d2012-10-25 16:30:11 +08001420 Args:
1421 foreground: If True, synchronizes even if background syncing
1422 is disabled (e.g., in explicit sync requests from the
1423 SyncShopfloor test).
1424
Jon Salz54882d02012-08-31 01:57:54 +08001425 Returns:
1426 False if no time sanitizer is available, or True if this sync (or a
1427 previous sync) succeeded.
1428
1429 Raises:
1430 Exception if unable to contact the shopfloor server.
1431 '''
Jon Salz0e6532d2012-10-25 16:30:11 +08001432 if self._should_sync_time(foreground):
Jon Salz54882d02012-08-31 01:57:54 +08001433 self.time_sanitizer.SyncWithShopfloor()
1434 self.time_synced = True
1435 return self.time_synced
1436
Jon Salzb92c5112012-09-21 15:40:11 +08001437 def log_disk_space_stats(self):
1438 if not self.test_list.options.log_disk_space_period_secs:
1439 return
1440
1441 now = time.time()
1442 if (self.last_log_disk_space_time and
1443 now - self.last_log_disk_space_time <
1444 self.test_list.options.log_disk_space_period_secs):
1445 return
1446 self.last_log_disk_space_time = now
1447
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001448 # Upload event if stateful partition usage is above threshold.
1449 # Stateful partition is mounted on /usr/local, while
1450 # encrypted stateful partition is mounted on /var.
1451 # If there are too much logs in the factory process,
1452 # these two partitions might get full.
Jon Salzb92c5112012-09-21 15:40:11 +08001453 try:
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001454 vfs_infos = disk_space.GetAllVFSInfo()
1455 stateful_info, encrypted_info = None, None
1456 for vfs_info in vfs_infos.values():
1457 if '/usr/local' in vfs_info.mount_points:
1458 stateful_info = vfs_info
1459 if '/var' in vfs_info.mount_points:
1460 encrypted_info = vfs_info
1461
1462 stateful = disk_space.GetPartitionUsage(stateful_info)
1463 encrypted = disk_space.GetPartitionUsage(encrypted_info)
1464
1465 above_threshold = (
1466 self.test_list.options.stateful_usage_threshold and
1467 max(stateful.bytes_used_pct,
1468 stateful.inodes_used_pct,
1469 encrypted.bytes_used_pct,
1470 encrypted.inodes_used_pct) >
1471 self.test_list.options.stateful_usage_threshold)
1472
1473 if above_threshold:
1474 self.event_log.Log('stateful_partition_usage',
1475 partitions={
1476 'stateful': {
1477 'bytes_used_pct': FloatDigit(stateful.bytes_used_pct, 2),
1478 'inodes_used_pct': FloatDigit(stateful.inodes_used_pct, 2)},
1479 'encrypted_stateful': {
1480 'bytes_used_pct': FloatDigit(encrypted.bytes_used_pct, 2),
1481 'inodes_used_pct': FloatDigit(encrypted.inodes_used_pct, 2)}
1482 })
1483 self.log_watcher.ScanEventLogs()
1484
1485 message = disk_space.FormatSpaceUsedAll(vfs_infos)
Jon Salz3c493bb2013-02-07 17:24:58 +08001486 if message != self.last_log_disk_space_message:
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001487 if above_threshold:
1488 logging.warning(message)
1489 else:
1490 logging.info(message)
Jon Salz3c493bb2013-02-07 17:24:58 +08001491 self.last_log_disk_space_message = message
Jon Salzb92c5112012-09-21 15:40:11 +08001492 except: # pylint: disable=W0702
1493 logging.exception('Unable to get disk space used')
1494
Justin Chuang83813982013-05-13 01:26:32 +08001495 def check_battery(self):
1496 '''Checks the current battery status.
1497
1498 Logs current battery charging level and status to log. If the battery level
1499 is lower below warning_low_battery_pct, send warning event to shopfloor.
1500 If the battery level is lower below critical_low_battery_pct, flush disks.
1501 '''
1502 if not self.test_list.options.check_battery_period_secs:
1503 return
1504
1505 now = time.time()
1506 if (self.last_check_battery_time and
1507 now - self.last_check_battery_time <
1508 self.test_list.options.check_battery_period_secs):
1509 return
1510 self.last_check_battery_time = now
1511
1512 message = ''
1513 log_level = logging.INFO
1514 try:
1515 power = system.GetBoard().power
1516 if not power.CheckBatteryPresent():
1517 message = 'Battery is not present'
1518 else:
1519 ac_present = power.CheckACPresent()
1520 charge_pct = power.GetChargePct(get_float=True)
1521 message = ('Current battery level %.1f%%, AC charger is %s' %
1522 (charge_pct, 'connected' if ac_present else 'disconnected'))
1523
1524 if charge_pct > self.test_list.options.critical_low_battery_pct:
1525 critical_low_battery = False
1526 else:
1527 critical_low_battery = True
1528 # Only sync disks when battery level is still above minimum
1529 # value. This can be used for offline analysis when shopfloor cannot
1530 # be connected.
1531 if charge_pct > MIN_BATTERY_LEVEL_FOR_DISK_SYNC:
1532 logging.warning('disk syncing for critical low battery situation')
1533 os.system('sync; sync; sync')
1534 else:
1535 logging.warning('disk syncing is cancelled '
1536 'because battery level is lower than %.1f',
1537 MIN_BATTERY_LEVEL_FOR_DISK_SYNC)
1538
1539 # Notify shopfloor server
1540 if (critical_low_battery or
1541 (not ac_present and
1542 charge_pct <= self.test_list.options.warning_low_battery_pct)):
1543 log_level = logging.WARNING
1544
1545 self.event_log.Log('low_battery',
1546 battery_level=charge_pct,
1547 charger_connected=ac_present,
1548 critical=critical_low_battery)
1549 self.log_watcher.KickWatchThread()
1550 self.system_log_manager.KickSyncThread()
1551 except: # pylint: disable=W0702
1552 logging.exception('Unable to check battery or notify shopfloor')
1553 finally:
1554 if message != self.last_check_battery_message:
1555 logging.log(log_level, message)
1556 self.last_check_battery_message = message
1557
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001558 def check_core_dump(self):
1559 '''Checks if there is any core dumped file.
1560
1561 Removes unwanted core dump files immediately.
1562 Syncs those files matching watch list to server with a delay between
1563 each sync. After the files have been synced to server, deletes the files.
1564 '''
1565 core_dump_files = self.core_dump_manager.ScanFiles()
1566 if core_dump_files:
1567 now = time.time()
1568 if (self.last_kick_sync_time and now - self.last_kick_sync_time <
1569 self.test_list.options.kick_sync_min_interval_secs):
1570 return
1571 self.last_kick_sync_time = now
1572
1573 # Sends event to server
1574 self.event_log.Log('core_dumped', files=core_dump_files)
1575 self.log_watcher.KickWatchThread()
1576
1577 # Syncs files to server
1578 self.system_log_manager.KickSyncThread(
1579 core_dump_files, self.core_dump_manager.ClearFiles)
1580
Jon Salz8fa8e832012-07-13 19:04:09 +08001581 def sync_time_in_background(self):
Jon Salzb22d1172012-08-06 10:38:57 +08001582 '''Writes out current time and tries to sync with shopfloor server.'''
1583 if not self.time_sanitizer:
1584 return
1585
1586 # Write out the current time.
1587 self.time_sanitizer.SaveTime()
1588
Jon Salz54882d02012-08-31 01:57:54 +08001589 if not self._should_sync_time():
Jon Salz8fa8e832012-07-13 19:04:09 +08001590 return
1591
1592 now = time.time()
1593 if self.last_sync_time and (
1594 now - self.last_sync_time <
1595 self.test_list.options.sync_time_period_secs):
1596 # Not yet time for another check.
1597 return
1598 self.last_sync_time = now
1599
1600 def target():
1601 try:
Jon Salz54882d02012-08-31 01:57:54 +08001602 self.sync_time_with_shopfloor_server()
Jon Salz8fa8e832012-07-13 19:04:09 +08001603 except: # pylint: disable=W0702
1604 # Oh well. Log an error (but no trace)
1605 logging.info(
1606 'Unable to get time from shopfloor server: %s',
1607 utils.FormatExceptionOnly())
1608
1609 thread = threading.Thread(target=target)
1610 thread.daemon = True
1611 thread.start()
1612
Jon Salz0697cbf2012-07-04 15:14:04 +08001613 def _run_queue_idle(self):
Vic Yang4953fc12012-07-26 16:19:53 +08001614 '''Invoked when the run queue has no events.
1615
1616 This method must not raise exception.
1617 '''
Jon Salzb22d1172012-08-06 10:38:57 +08001618 now = time.time()
1619 if (self.last_idle and
1620 now < (self.last_idle + RUN_QUEUE_TIMEOUT_SECS - 1)):
1621 # Don't run more often than once every (RUN_QUEUE_TIMEOUT_SECS -
1622 # 1) seconds.
1623 return
1624
1625 self.last_idle = now
1626
Vic Yang311ddb82012-09-26 12:08:28 +08001627 self.check_exclusive()
cychiang21886742012-07-05 15:16:32 +08001628 self.check_for_updates()
Jon Salz8fa8e832012-07-13 19:04:09 +08001629 self.sync_time_in_background()
Jon Salzb92c5112012-09-21 15:40:11 +08001630 self.log_disk_space_stats()
Justin Chuang83813982013-05-13 01:26:32 +08001631 self.check_battery()
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001632 self.check_core_dump()
Jon Salz57717ca2012-04-04 16:47:25 +08001633
Vic Yang93027612013-05-06 02:42:49 +08001634 def handle_event_logs(self, chunk_info):
Jon Salz0697cbf2012-07-04 15:14:04 +08001635 '''Callback for event watcher.
Jon Salz258a40c2012-04-19 12:34:01 +08001636
Jon Salz0697cbf2012-07-04 15:14:04 +08001637 Attempts to upload the event logs to the shopfloor server.
Vic Yang93027612013-05-06 02:42:49 +08001638
1639 Args:
1640 chunk_info: A list of tuple (log_name, chunk)
Jon Salz0697cbf2012-07-04 15:14:04 +08001641 '''
Vic Yang93027612013-05-06 02:42:49 +08001642 first_exception = None
1643 exception_count = 0
1644
1645 for log_name, chunk in chunk_info:
1646 try:
1647 description = 'event logs (%s, %d bytes)' % (log_name, len(chunk))
1648 start_time = time.time()
1649 shopfloor_client = shopfloor.get_instance(
1650 detect=True,
1651 timeout=self.test_list.options.shopfloor_timeout_secs)
1652 shopfloor_client.UploadEvent(log_name, Binary(chunk))
1653 logging.info(
1654 'Successfully synced %s in %.03f s',
1655 description, time.time() - start_time)
1656 except: # pylint: disable=W0702
1657 first_exception = (first_exception or (log_name + ': ' +
1658 utils.FormatExceptionOnly()))
1659 exception_count += 1
1660
1661 if exception_count:
1662 if exception_count == 1:
1663 msg = 'Log upload failed: %s' % first_exception
1664 else:
1665 msg = '%d log upload failed; first is: %s' % (
1666 exception_count, first_exception)
1667 raise Exception(msg)
1668
Jon Salz57717ca2012-04-04 16:47:25 +08001669
Jon Salz0697cbf2012-07-04 15:14:04 +08001670 def run_tests_with_status(self, statuses_to_run, starting_at=None,
1671 root=None):
1672 '''Runs all top-level tests with a particular status.
Jon Salz0405ab52012-03-16 15:26:52 +08001673
Jon Salz0697cbf2012-07-04 15:14:04 +08001674 All active tests, plus any tests to re-run, are reset.
Jon Salz57717ca2012-04-04 16:47:25 +08001675
Jon Salz0697cbf2012-07-04 15:14:04 +08001676 Args:
1677 starting_at: If provided, only auto-runs tests beginning with
1678 this test.
1679 '''
1680 root = root or self.test_list
Jon Salz57717ca2012-04-04 16:47:25 +08001681
Jon Salz0697cbf2012-07-04 15:14:04 +08001682 if starting_at:
1683 # Make sure they passed a test, not a string.
1684 assert isinstance(starting_at, factory.FactoryTest)
Jon Salz0405ab52012-03-16 15:26:52 +08001685
Jon Salz0697cbf2012-07-04 15:14:04 +08001686 tests_to_reset = []
1687 tests_to_run = []
Jon Salz0405ab52012-03-16 15:26:52 +08001688
Jon Salz0697cbf2012-07-04 15:14:04 +08001689 found_starting_at = False
Jon Salz0405ab52012-03-16 15:26:52 +08001690
Jon Salz0697cbf2012-07-04 15:14:04 +08001691 for test in root.get_top_level_tests():
1692 if starting_at:
1693 if test == starting_at:
1694 # We've found starting_at; do auto-run on all
1695 # subsequent tests.
1696 found_starting_at = True
1697 if not found_starting_at:
1698 # Don't start this guy yet
1699 continue
Jon Salz0405ab52012-03-16 15:26:52 +08001700
Jon Salz0697cbf2012-07-04 15:14:04 +08001701 status = test.get_state().status
1702 if status == TestState.ACTIVE or status in statuses_to_run:
1703 # Reset the test (later; we will need to abort
1704 # all active tests first).
1705 tests_to_reset.append(test)
1706 if status in statuses_to_run:
1707 tests_to_run.append(test)
Jon Salz0405ab52012-03-16 15:26:52 +08001708
Jon Salz0697cbf2012-07-04 15:14:04 +08001709 self.abort_active_tests()
Jon Salz258a40c2012-04-19 12:34:01 +08001710
Jon Salz0697cbf2012-07-04 15:14:04 +08001711 # Reset all statuses of the tests to run (in case any tests were active;
1712 # we want them to be run again).
1713 for test_to_reset in tests_to_reset:
1714 for test in test_to_reset.walk():
1715 test.update_state(status=TestState.UNTESTED)
Jon Salz57717ca2012-04-04 16:47:25 +08001716
Jon Salz0697cbf2012-07-04 15:14:04 +08001717 self.run_tests(tests_to_run, untested_only=True)
Jon Salz0405ab52012-03-16 15:26:52 +08001718
Jon Salz0697cbf2012-07-04 15:14:04 +08001719 def restart_tests(self, root=None):
1720 '''Restarts all tests.'''
1721 root = root or self.test_list
Jon Salz0405ab52012-03-16 15:26:52 +08001722
Jon Salz0697cbf2012-07-04 15:14:04 +08001723 self.abort_active_tests()
1724 for test in root.walk():
1725 test.update_state(status=TestState.UNTESTED)
1726 self.run_tests(root)
Hung-Te Lin96632362012-03-20 21:14:18 +08001727
Jon Salz0697cbf2012-07-04 15:14:04 +08001728 def auto_run(self, starting_at=None, root=None):
1729 '''"Auto-runs" tests that have not been run yet.
Hung-Te Lin96632362012-03-20 21:14:18 +08001730
Jon Salz0697cbf2012-07-04 15:14:04 +08001731 Args:
1732 starting_at: If provide, only auto-runs tests beginning with
1733 this test.
1734 '''
1735 root = root or self.test_list
1736 self.run_tests_with_status([TestState.UNTESTED, TestState.ACTIVE],
1737 starting_at=starting_at,
1738 root=root)
Jon Salz968e90b2012-03-18 16:12:43 +08001739
Jon Salz0697cbf2012-07-04 15:14:04 +08001740 def re_run_failed(self, root=None):
1741 '''Re-runs failed tests.'''
1742 root = root or self.test_list
1743 self.run_tests_with_status([TestState.FAILED], root=root)
Jon Salz57717ca2012-04-04 16:47:25 +08001744
Jon Salz0697cbf2012-07-04 15:14:04 +08001745 def show_review_information(self):
1746 '''Event handler for showing review information screen.
Jon Salz57717ca2012-04-04 16:47:25 +08001747
Jon Salz0697cbf2012-07-04 15:14:04 +08001748 The information screene is rendered by main UI program (ui.py), so in
1749 goofy we only need to kill all active tests, set them as untested, and
1750 clear remaining tests.
1751 '''
1752 self.kill_active_tests(False)
Jon Salza6711d72012-07-18 14:33:03 +08001753 self.cancel_pending_tests()
Jon Salz57717ca2012-04-04 16:47:25 +08001754
Jon Salz0697cbf2012-07-04 15:14:04 +08001755 def handle_switch_test(self, event):
1756 '''Switches to a particular test.
Jon Salz0405ab52012-03-16 15:26:52 +08001757
Jon Salz0697cbf2012-07-04 15:14:04 +08001758 @param event: The SWITCH_TEST event.
1759 '''
1760 test = self.test_list.lookup_path(event.path)
1761 if not test:
1762 logging.error('Unknown test %r', event.key)
1763 return
Jon Salz73e0fd02012-04-04 11:46:38 +08001764
Jon Salz0697cbf2012-07-04 15:14:04 +08001765 invoc = self.invocations.get(test)
1766 if invoc and test.backgroundable:
1767 # Already running: just bring to the front if it
1768 # has a UI.
1769 logging.info('Setting visible test to %s', test.path)
Jon Salz36fbbb52012-07-05 13:45:06 +08001770 self.set_visible_test(test)
Jon Salz0697cbf2012-07-04 15:14:04 +08001771 return
Jon Salz73e0fd02012-04-04 11:46:38 +08001772
Jon Salz0697cbf2012-07-04 15:14:04 +08001773 self.abort_active_tests()
1774 for t in test.walk():
1775 t.update_state(status=TestState.UNTESTED)
Jon Salz73e0fd02012-04-04 11:46:38 +08001776
Jon Salz0697cbf2012-07-04 15:14:04 +08001777 if self.test_list.options.auto_run_on_keypress:
1778 self.auto_run(starting_at=test)
1779 else:
1780 self.run_tests(test)
Jon Salz73e0fd02012-04-04 11:46:38 +08001781
Jon Salz0697cbf2012-07-04 15:14:04 +08001782 def wait(self):
1783 '''Waits for all pending invocations.
1784
1785 Useful for testing.
1786 '''
Jon Salz1acc8742012-07-17 17:45:55 +08001787 while self.invocations:
1788 for k, v in self.invocations.iteritems():
1789 logging.info('Waiting for %s to complete...', k)
1790 v.thread.join()
1791 self.reap_completed_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +08001792
1793 def check_exceptions(self):
1794 '''Raises an error if any exceptions have occurred in
1795 invocation threads.'''
1796 if self.exceptions:
1797 raise RuntimeError('Exception in invocation thread: %r' %
1798 self.exceptions)
1799
1800 def record_exception(self, msg):
1801 '''Records an exception in an invocation thread.
1802
1803 An exception with the given message will be rethrown when
1804 Goofy is destroyed.'''
1805 self.exceptions.append(msg)
Jon Salz73e0fd02012-04-04 11:46:38 +08001806
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001807
1808if __name__ == '__main__':
Jon Salz77c151e2012-08-28 07:20:37 +08001809 goofy = Goofy()
1810 try:
1811 goofy.main()
Jon Salz0f996602012-10-03 15:26:48 +08001812 except SystemExit:
1813 # Propagate SystemExit without logging.
1814 raise
Jon Salz31373eb2012-09-21 16:19:49 +08001815 except:
Jon Salz0f996602012-10-03 15:26:48 +08001816 # Log the error before trying to shut down (unless it's a graceful
1817 # exit).
Jon Salz31373eb2012-09-21 16:19:49 +08001818 logging.exception('Error in main loop')
1819 raise
Jon Salz77c151e2012-08-28 07:20:37 +08001820 finally:
1821 goofy.destroy()