blob: c2c81abcc73bc30e64f655cc7d4a13b3e2260d2c [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 Salze12c2b32013-06-25 16:24:34 +080012import glob
Jon Salz0405ab52012-03-16 15:26:52 +080013import logging
14import os
Jon Salz73e0fd02012-04-04 11:46:38 +080015import Queue
Jon Salze12c2b32013-06-25 16:24:34 +080016import shutil
Jon Salz77c151e2012-08-28 07:20:37 +080017import signal
Jon Salz0405ab52012-03-16 15:26:52 +080018import sys
Jon Salzeff94182013-06-19 15:06:28 +080019import syslog
Jon Salz0405ab52012-03-16 15:26:52 +080020import threading
21import time
22import traceback
Jon Salz258a40c2012-04-19 12:34:01 +080023import uuid
Jon Salzb10cf512012-08-09 17:29:21 +080024from xmlrpclib import Binary
Hung-Te Linf2f78f72012-02-08 19:27:11 +080025from collections import deque
26from optparse import OptionParser
Hung-Te Linf2f78f72012-02-08 19:27:11 +080027
Jon Salz0697cbf2012-07-04 15:14:04 +080028import factory_common # pylint: disable=W0611
jcliangcd688182012-08-20 21:01:26 +080029from cros.factory import event_log
30from cros.factory import system
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +080031from cros.factory.event_log import EventLog, FloatDigit
Tom Wai-Hong Tamd33723e2013-04-10 21:14:37 +080032from cros.factory.event_log_watcher import EventLogWatcher
jcliangcd688182012-08-20 21:01:26 +080033from cros.factory.goofy import test_environment
34from cros.factory.goofy import time_sanitizer
Jon Salz83591782012-06-26 11:09:58 +080035from cros.factory.goofy import updater
jcliangcd688182012-08-20 21:01:26 +080036from cros.factory.goofy.goofy_rpc import GoofyRPC
Jon Salz885dcac2013-07-23 16:39:50 +080037from cros.factory.goofy.invocation import TestArgEnv
jcliangcd688182012-08-20 21:01:26 +080038from cros.factory.goofy.invocation import TestInvocation
39from cros.factory.goofy.prespawner import Prespawner
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +080040from cros.factory.goofy.system_log_manager import SystemLogManager
jcliangcd688182012-08-20 21:01:26 +080041from cros.factory.goofy.web_socket_manager import WebSocketManager
Cheng-Yi Chiangd8186952013-04-04 23:41:14 +080042from cros.factory.system.board import Board, BoardException
jcliangcd688182012-08-20 21:01:26 +080043from cros.factory.system.charge_manager import ChargeManager
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +080044from cros.factory.system.core_dump_manager import CoreDumpManager
Jon Salzce6a7f82013-06-10 18:22:54 +080045from cros.factory.system.cpufreq_manager import CpufreqManager
Jon Salzb92c5112012-09-21 15:40:11 +080046from cros.factory.system import disk_space
jcliangcd688182012-08-20 21:01:26 +080047from cros.factory.test import factory
48from cros.factory.test import state
Jon Salz51528e12012-07-02 18:54:45 +080049from cros.factory.test import shopfloor
Jon Salz83591782012-06-26 11:09:58 +080050from cros.factory.test import utils
Jon Salz128b0932013-07-03 16:55:26 +080051from cros.factory.test.test_lists import test_lists
Jon Salz83591782012-06-26 11:09:58 +080052from cros.factory.test.event import Event
53from cros.factory.test.event import EventClient
54from cros.factory.test.event import EventServer
jcliangcd688182012-08-20 21:01:26 +080055from cros.factory.test.factory import TestState
Jon Salzd7550792013-07-12 05:49:27 +080056from cros.factory.test.utils import Enum
Dean Liao592e4d52013-01-10 20:06:39 +080057from cros.factory.tools.key_filter import KeyFilter
Jon Salz2af235d2013-06-24 14:47:21 +080058from cros.factory.utils import file_utils
Jon Salz78c32392012-07-25 14:18:29 +080059from cros.factory.utils.process_utils import Spawn
Hung-Te Linf2f78f72012-02-08 19:27:11 +080060
61
Hung-Te Linf2f78f72012-02-08 19:27:11 +080062HWID_CFG_PATH = '/usr/local/share/chromeos-hwid/cfg'
Chun-ta Lin279e7e92013-02-19 17:40:39 +080063CACHES_DIR = os.path.join(factory.get_state_root(), "caches")
Hung-Te Linf2f78f72012-02-08 19:27:11 +080064
Jon Salz8796e362012-05-24 11:39:09 +080065# File that suppresses reboot if present (e.g., for development).
66NO_REBOOT_FILE = '/var/log/factory.noreboot'
67
Jon Salz5c344f62012-07-13 14:31:16 +080068# Value for tests_after_shutdown that forces auto-run (e.g., after
69# a factory update, when the available set of tests might change).
70FORCE_AUTO_RUN = 'force_auto_run'
71
cychiang21886742012-07-05 15:16:32 +080072RUN_QUEUE_TIMEOUT_SECS = 10
73
Justin Chuang83813982013-05-13 01:26:32 +080074# Sync disks when battery level is higher than this value.
75# Otherwise, power loss during disk sync operation may incur even worse outcome.
76MIN_BATTERY_LEVEL_FOR_DISK_SYNC = 1.0
77
Jon Salze12c2b32013-06-25 16:24:34 +080078MAX_CRASH_FILE_SIZE = 64*1024
79
Jon Salz758e6cc2012-04-03 15:47:07 +080080GOOFY_IN_CHROOT_WARNING = '\n' + ('*' * 70) + '''
81You are running Goofy inside the chroot. Autotests are not supported.
82
83To use Goofy in the chroot, first install an Xvnc server:
84
Jon Salz0697cbf2012-07-04 15:14:04 +080085 sudo apt-get install tightvncserver
Jon Salz758e6cc2012-04-03 15:47:07 +080086
87...and then start a VNC X server outside the chroot:
88
Jon Salz0697cbf2012-07-04 15:14:04 +080089 vncserver :10 &
90 vncviewer :10
Jon Salz758e6cc2012-04-03 15:47:07 +080091
92...and run Goofy as follows:
93
Jon Salz0697cbf2012-07-04 15:14:04 +080094 env --unset=XAUTHORITY DISPLAY=localhost:10 python goofy.py
Jon Salz758e6cc2012-04-03 15:47:07 +080095''' + ('*' * 70)
Jon Salz73e0fd02012-04-04 11:46:38 +080096suppress_chroot_warning = False
Hung-Te Linf2f78f72012-02-08 19:27:11 +080097
Jon Salzd7550792013-07-12 05:49:27 +080098Status = Enum(['UNINITIALIZED', 'INITIALIZING', 'RUNNING',
99 'TERMINATING', 'TERMINATED'])
100
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800101def get_hwid_cfg():
Jon Salz0697cbf2012-07-04 15:14:04 +0800102 '''
103 Returns the HWID config tag, or an empty string if none can be found.
104 '''
105 if 'CROS_HWID' in os.environ:
106 return os.environ['CROS_HWID']
107 if os.path.exists(HWID_CFG_PATH):
108 with open(HWID_CFG_PATH, 'rt') as hwid_cfg_handle:
109 return hwid_cfg_handle.read().strip()
110 return ''
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800111
112
Jon Salz73e0fd02012-04-04 11:46:38 +0800113_inited_logging = False
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800114
115class Goofy(object):
Jon Salz0697cbf2012-07-04 15:14:04 +0800116 '''
117 The main factory flow.
118
119 Note that all methods in this class must be invoked from the main
120 (event) thread. Other threads, such as callbacks and TestInvocation
121 methods, should instead post events on the run queue.
122
123 TODO: Unit tests. (chrome-os-partner:7409)
124
125 Properties:
126 uuid: A unique UUID for this invocation of Goofy.
127 state_instance: An instance of FactoryState.
128 state_server: The FactoryState XML/RPC server.
129 state_server_thread: A thread running state_server.
130 event_server: The EventServer socket server.
131 event_server_thread: A thread running event_server.
132 event_client: A client to the event server.
133 connection_manager: The connection_manager object.
Cheng-Yi Chiang835f2682013-05-06 22:15:48 +0800134 system_log_manager: The SystemLogManager object.
135 core_dump_manager: The CoreDumpManager object.
Jon Salz0697cbf2012-07-04 15:14:04 +0800136 ui_process: The factory ui process object.
137 run_queue: A queue of callbacks to invoke from the main thread.
138 invocations: A map from FactoryTest objects to the corresponding
139 TestInvocations objects representing active tests.
140 tests_to_run: A deque of tests that should be run when the current
141 test(s) complete.
142 options: Command-line options.
143 args: Command-line args.
144 test_list: The test list.
Jon Salz128b0932013-07-03 16:55:26 +0800145 test_lists: All new-style test lists.
Jon Salz0697cbf2012-07-04 15:14:04 +0800146 event_handlers: Map of Event.Type to the method used to handle that
147 event. If the method has an 'event' argument, the event is passed
148 to the handler.
149 exceptions: Exceptions encountered in invocation threads.
Jon Salz3c493bb2013-02-07 17:24:58 +0800150 last_log_disk_space_message: The last message we logged about disk space
151 (to avoid duplication).
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +0800152 last_kick_sync_time: The last time to kick system_log_manager to sync
153 because of core dump files (to avoid kicking too soon then abort the
154 sync.)
Jon Salz416f9cc2013-05-10 18:32:50 +0800155 hooks: A Hooks object containing hooks for various Goofy actions.
Jon Salzd7550792013-07-12 05:49:27 +0800156 status: The current Goofy status (a member of the Status enum).
Jon Salz0697cbf2012-07-04 15:14:04 +0800157 '''
158 def __init__(self):
159 self.uuid = str(uuid.uuid4())
160 self.state_instance = None
161 self.state_server = None
162 self.state_server_thread = None
Jon Salz16d10542012-07-23 12:18:45 +0800163 self.goofy_rpc = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800164 self.event_server = None
165 self.event_server_thread = None
166 self.event_client = None
167 self.connection_manager = None
Vic Yang4953fc12012-07-26 16:19:53 +0800168 self.charge_manager = None
Jon Salz8fa8e832012-07-13 19:04:09 +0800169 self.time_sanitizer = None
170 self.time_synced = False
Jon Salz0697cbf2012-07-04 15:14:04 +0800171 self.log_watcher = None
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +0800172 self.system_log_manager = None
Cheng-Yi Chiang835f2682013-05-06 22:15:48 +0800173 self.core_dump_manager = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800174 self.event_log = None
175 self.prespawner = None
176 self.ui_process = None
Jon Salzc79a9982012-08-30 04:42:01 +0800177 self.dummy_shopfloor = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800178 self.run_queue = Queue.Queue()
179 self.invocations = {}
180 self.tests_to_run = deque()
181 self.visible_test = None
182 self.chrome = None
Jon Salz416f9cc2013-05-10 18:32:50 +0800183 self.hooks = None
Vic Yangd8990da2013-06-27 16:57:43 +0800184 self.cpu_usage_watcher = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800185
186 self.options = None
187 self.args = None
188 self.test_list = None
Jon Salz128b0932013-07-03 16:55:26 +0800189 self.test_lists = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800190 self.on_ui_startup = []
191 self.env = None
Jon Salzb22d1172012-08-06 10:38:57 +0800192 self.last_idle = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800193 self.last_shutdown_time = None
cychiang21886742012-07-05 15:16:32 +0800194 self.last_update_check = None
Jon Salz8fa8e832012-07-13 19:04:09 +0800195 self.last_sync_time = None
Jon Salzb92c5112012-09-21 15:40:11 +0800196 self.last_log_disk_space_time = None
Jon Salz3c493bb2013-02-07 17:24:58 +0800197 self.last_log_disk_space_message = None
Justin Chuang83813982013-05-13 01:26:32 +0800198 self.last_check_battery_time = None
199 self.last_check_battery_message = None
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +0800200 self.last_kick_sync_time = None
Vic Yang311ddb82012-09-26 12:08:28 +0800201 self.exclusive_items = set()
Jon Salz0f996602012-10-03 15:26:48 +0800202 self.event_log = None
Dean Liao592e4d52013-01-10 20:06:39 +0800203 self.key_filter = None
Jon Salzce6a7f82013-06-10 18:22:54 +0800204 self.cpufreq_manager = None
Jon Salzd7550792013-07-12 05:49:27 +0800205 self.status = Status.UNINITIALIZED
Jon Salz0697cbf2012-07-04 15:14:04 +0800206
Jon Salz85a39882012-07-05 16:45:04 +0800207 def test_or_root(event, parent_or_group=True):
208 '''Returns the test affected by a particular event.
209
210 Args:
211 event: The event containing an optional 'path' attribute.
212 parent_on_group: If True, returns the top-level parent for a test (the
213 root node of the tests that need to be run together if the given test
214 path is to be run).
215 '''
Jon Salz0697cbf2012-07-04 15:14:04 +0800216 try:
217 path = event.path
218 except AttributeError:
219 path = None
220
221 if path:
Jon Salz85a39882012-07-05 16:45:04 +0800222 test = self.test_list.lookup_path(path)
223 if parent_or_group:
224 test = test.get_top_level_parent_or_group()
225 return test
Jon Salz0697cbf2012-07-04 15:14:04 +0800226 else:
227 return self.test_list
228
229 self.event_handlers = {
230 Event.Type.SWITCH_TEST: self.handle_switch_test,
231 Event.Type.SHOW_NEXT_ACTIVE_TEST:
232 lambda event: self.show_next_active_test(),
233 Event.Type.RESTART_TESTS:
234 lambda event: self.restart_tests(root=test_or_root(event)),
235 Event.Type.AUTO_RUN:
236 lambda event: self.auto_run(root=test_or_root(event)),
237 Event.Type.RE_RUN_FAILED:
238 lambda event: self.re_run_failed(root=test_or_root(event)),
239 Event.Type.RUN_TESTS_WITH_STATUS:
240 lambda event: self.run_tests_with_status(
241 event.status,
242 root=test_or_root(event)),
243 Event.Type.REVIEW:
244 lambda event: self.show_review_information(),
245 Event.Type.UPDATE_SYSTEM_INFO:
246 lambda event: self.update_system_info(),
Jon Salz0697cbf2012-07-04 15:14:04 +0800247 Event.Type.STOP:
Jon Salz85a39882012-07-05 16:45:04 +0800248 lambda event: self.stop(root=test_or_root(event, False),
Jon Salz6dc031d2013-06-19 13:06:23 +0800249 fail=getattr(event, 'fail', False),
250 reason=getattr(event, 'reason', None)),
Jon Salz36fbbb52012-07-05 13:45:06 +0800251 Event.Type.SET_VISIBLE_TEST:
252 lambda event: self.set_visible_test(
253 self.test_list.lookup_path(event.path)),
Jon Salz4712ac72013-02-07 17:12:05 +0800254 Event.Type.CLEAR_STATE:
255 lambda event: self.clear_state(self.test_list.lookup_path(event.path)),
Jon Salz0697cbf2012-07-04 15:14:04 +0800256 }
257
258 self.exceptions = []
259 self.web_socket_manager = None
260
261 def destroy(self):
Jon Salzd7550792013-07-12 05:49:27 +0800262 self.status = Status.TERMINATING
Jon Salz0697cbf2012-07-04 15:14:04 +0800263 if self.chrome:
264 self.chrome.kill()
265 self.chrome = None
Jon Salzc79a9982012-08-30 04:42:01 +0800266 if self.dummy_shopfloor:
267 self.dummy_shopfloor.kill()
268 self.dummy_shopfloor = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800269 if self.ui_process:
270 utils.kill_process_tree(self.ui_process, 'ui')
271 self.ui_process = None
272 if self.web_socket_manager:
273 logging.info('Stopping web sockets')
274 self.web_socket_manager.close()
275 self.web_socket_manager = None
276 if self.state_server_thread:
277 logging.info('Stopping state server')
278 self.state_server.shutdown()
279 self.state_server_thread.join()
280 self.state_server.server_close()
281 self.state_server_thread = None
282 if self.state_instance:
283 self.state_instance.close()
284 if self.event_server_thread:
285 logging.info('Stopping event server')
286 self.event_server.shutdown() # pylint: disable=E1101
287 self.event_server_thread.join()
288 self.event_server.server_close()
289 self.event_server_thread = None
290 if self.log_watcher:
291 if self.log_watcher.IsThreadStarted():
292 self.log_watcher.StopWatchThread()
293 self.log_watcher = None
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +0800294 if self.system_log_manager:
295 if self.system_log_manager.IsThreadRunning():
296 self.system_log_manager.StopSyncThread()
297 self.system_log_manager = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800298 if self.prespawner:
299 logging.info('Stopping prespawner')
300 self.prespawner.stop()
301 self.prespawner = None
302 if self.event_client:
303 logging.info('Closing event client')
304 self.event_client.close()
305 self.event_client = None
Jon Salzddf0d052013-06-18 12:52:44 +0800306 if self.cpufreq_manager:
307 self.cpufreq_manager.Stop()
Jon Salz0697cbf2012-07-04 15:14:04 +0800308 if self.event_log:
309 self.event_log.Close()
310 self.event_log = None
Dean Liao592e4d52013-01-10 20:06:39 +0800311 if self.key_filter:
312 self.key_filter.Stop()
Vic Yangd8990da2013-06-27 16:57:43 +0800313 if self.cpu_usage_watcher:
314 self.cpu_usage_watcher.terminate()
Dean Liao592e4d52013-01-10 20:06:39 +0800315
Jon Salz0697cbf2012-07-04 15:14:04 +0800316 self.check_exceptions()
317 logging.info('Done destroying Goofy')
Jon Salzd7550792013-07-12 05:49:27 +0800318 self.status = Status.TERMINATED
Jon Salz0697cbf2012-07-04 15:14:04 +0800319
320 def start_state_server(self):
Jon Salz2af235d2013-06-24 14:47:21 +0800321 # Before starting state server, remount stateful partitions with
322 # no commit flag. The default commit time (commit=600) makes corruption
323 # too likely.
324 file_utils.ResetCommitTime()
325
Jon Salz0697cbf2012-07-04 15:14:04 +0800326 self.state_instance, self.state_server = (
327 state.create_server(bind_address='0.0.0.0'))
Jon Salz16d10542012-07-23 12:18:45 +0800328 self.goofy_rpc = GoofyRPC(self)
329 self.goofy_rpc.RegisterMethods(self.state_instance)
Jon Salz0697cbf2012-07-04 15:14:04 +0800330 logging.info('Starting state server')
331 self.state_server_thread = threading.Thread(
332 target=self.state_server.serve_forever,
333 name='StateServer')
334 self.state_server_thread.start()
335
336 def start_event_server(self):
337 self.event_server = EventServer()
338 logging.info('Starting factory event server')
339 self.event_server_thread = threading.Thread(
340 target=self.event_server.serve_forever,
341 name='EventServer') # pylint: disable=E1101
342 self.event_server_thread.start()
343
344 self.event_client = EventClient(
345 callback=self.handle_event, event_loop=self.run_queue)
346
347 self.web_socket_manager = WebSocketManager(self.uuid)
348 self.state_server.add_handler("/event",
349 self.web_socket_manager.handle_web_socket)
350
351 def start_ui(self):
352 ui_proc_args = [
353 os.path.join(factory.FACTORY_PACKAGE_PATH, 'test', 'ui.py'),
354 self.options.test_list]
355 if self.options.verbose:
356 ui_proc_args.append('-v')
357 logging.info('Starting ui %s', ui_proc_args)
Jon Salz78c32392012-07-25 14:18:29 +0800358 self.ui_process = Spawn(ui_proc_args)
Jon Salz0697cbf2012-07-04 15:14:04 +0800359 logging.info('Waiting for UI to come up...')
360 self.event_client.wait(
361 lambda event: event.type == Event.Type.UI_READY)
362 logging.info('UI has started')
363
364 def set_visible_test(self, test):
365 if self.visible_test == test:
366 return
Jon Salz2f2d42c2012-07-30 12:30:34 +0800367 if test and not test.has_ui:
368 return
Jon Salz0697cbf2012-07-04 15:14:04 +0800369
370 if test:
371 test.update_state(visible=True)
372 if self.visible_test:
373 self.visible_test.update_state(visible=False)
374 self.visible_test = test
375
Jon Salzd4306c82012-11-30 15:16:36 +0800376 def _log_startup_messages(self):
377 '''Logs the tail of var/log/messages and mosys and EC console logs.'''
378 # TODO(jsalz): This is mostly a copy-and-paste of code in init_states,
379 # for factory-3004.B only. Consolidate and merge back to ToT.
380 if utils.in_chroot():
381 return
382
383 try:
384 var_log_messages = (
385 utils.var_log_messages_before_reboot())
386 logging.info(
387 'Tail of /var/log/messages before last reboot:\n'
388 '%s', ('\n'.join(
389 ' ' + x for x in var_log_messages)))
390 except: # pylint: disable=W0702
391 logging.exception('Unable to grok /var/log/messages')
392
393 try:
394 mosys_log = utils.Spawn(
395 ['mosys', 'eventlog', 'list'],
396 read_stdout=True, log_stderr_on_error=True).stdout_data
397 logging.info('System eventlog from mosys:\n%s\n', mosys_log)
398 except: # pylint: disable=W0702
399 logging.exception('Unable to read mosys eventlog')
400
401 try:
Vic Yang8341dde2013-01-29 16:48:52 +0800402 board = system.GetBoard()
403 ec_console_log = board.GetECConsoleLog()
Jon Salzd4306c82012-11-30 15:16:36 +0800404 logging.info('EC console log after reboot:\n%s\n', ec_console_log)
405 except: # pylint: disable=W0702
406 logging.exception('Error retrieving EC console log')
407
Vic Yang079f9872013-07-01 11:32:00 +0800408 try:
409 board = system.GetBoard()
410 ec_panic_info = board.GetECPanicInfo()
411 logging.info('EC panic info after reboot:\n%s\n', ec_panic_info)
412 except: # pylint: disable=W0702
413 logging.exception('Error retrieving EC panic info')
414
Jon Salz0697cbf2012-07-04 15:14:04 +0800415 def handle_shutdown_complete(self, test, test_state):
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800416 '''
Jon Salz0697cbf2012-07-04 15:14:04 +0800417 Handles the case where a shutdown was detected during a shutdown step.
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800418
Jon Salz0697cbf2012-07-04 15:14:04 +0800419 @param test: The ShutdownStep.
420 @param test_state: The test state.
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800421 '''
Jon Salz0697cbf2012-07-04 15:14:04 +0800422 test_state = test.update_state(increment_shutdown_count=1)
423 logging.info('Detected shutdown (%d of %d)',
424 test_state.shutdown_count, test.iterations)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800425
Jon Salz0697cbf2012-07-04 15:14:04 +0800426 def log_and_update_state(status, error_msg, **kw):
427 self.event_log.Log('rebooted',
428 status=status, error_msg=error_msg, **kw)
Jon Salzd4306c82012-11-30 15:16:36 +0800429 logging.info('Rebooted: status=%s, %s', status,
430 (('error_msg=%s' % error_msg) if error_msg else None))
Jon Salz0697cbf2012-07-04 15:14:04 +0800431 test.update_state(status=status, error_msg=error_msg)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800432
Jon Salz0697cbf2012-07-04 15:14:04 +0800433 if not self.last_shutdown_time:
434 log_and_update_state(status=TestState.FAILED,
435 error_msg='Unable to read shutdown_time')
436 return
Jon Salz258a40c2012-04-19 12:34:01 +0800437
Jon Salz0697cbf2012-07-04 15:14:04 +0800438 now = time.time()
439 logging.info('%.03f s passed since reboot',
440 now - self.last_shutdown_time)
Jon Salz258a40c2012-04-19 12:34:01 +0800441
Jon Salz0697cbf2012-07-04 15:14:04 +0800442 if self.last_shutdown_time > now:
443 test.update_state(status=TestState.FAILED,
444 error_msg='Time moved backward during reboot')
445 elif (isinstance(test, factory.RebootStep) and
446 self.test_list.options.max_reboot_time_secs and
447 (now - self.last_shutdown_time >
448 self.test_list.options.max_reboot_time_secs)):
449 # A reboot took too long; fail. (We don't check this for
450 # HaltSteps, because the machine could be halted for a
451 # very long time, and even unplugged with battery backup,
452 # thus hosing the clock.)
453 log_and_update_state(
454 status=TestState.FAILED,
455 error_msg=('More than %d s elapsed during reboot '
456 '(%.03f s, from %s to %s)' % (
457 self.test_list.options.max_reboot_time_secs,
458 now - self.last_shutdown_time,
459 utils.TimeString(self.last_shutdown_time),
460 utils.TimeString(now))),
461 duration=(now-self.last_shutdown_time))
Jon Salzd4306c82012-11-30 15:16:36 +0800462 self._log_startup_messages()
Jon Salz0697cbf2012-07-04 15:14:04 +0800463 elif test_state.shutdown_count == test.iterations:
464 # Good!
465 log_and_update_state(status=TestState.PASSED,
466 duration=(now - self.last_shutdown_time),
467 error_msg='')
468 elif test_state.shutdown_count > test.iterations:
469 # Shut down too many times
470 log_and_update_state(status=TestState.FAILED,
471 error_msg='Too many shutdowns')
Jon Salzd4306c82012-11-30 15:16:36 +0800472 self._log_startup_messages()
Jon Salz0697cbf2012-07-04 15:14:04 +0800473 elif utils.are_shift_keys_depressed():
474 logging.info('Shift keys are depressed; cancelling restarts')
475 # Abort shutdown
476 log_and_update_state(
477 status=TestState.FAILED,
478 error_msg='Shutdown aborted with double shift keys')
Jon Salza6711d72012-07-18 14:33:03 +0800479 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +0800480 else:
481 def handler():
482 if self._prompt_cancel_shutdown(
483 test, test_state.shutdown_count + 1):
Jon Salza6711d72012-07-18 14:33:03 +0800484 factory.console.info('Shutdown aborted by operator')
Jon Salz0697cbf2012-07-04 15:14:04 +0800485 log_and_update_state(
486 status=TestState.FAILED,
487 error_msg='Shutdown aborted by operator')
Jon Salza6711d72012-07-18 14:33:03 +0800488 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +0800489 return
Jon Salz0405ab52012-03-16 15:26:52 +0800490
Jon Salz0697cbf2012-07-04 15:14:04 +0800491 # Time to shutdown again
492 log_and_update_state(
493 status=TestState.ACTIVE,
494 error_msg='',
495 iteration=test_state.shutdown_count)
Jon Salz73e0fd02012-04-04 11:46:38 +0800496
Jon Salz0697cbf2012-07-04 15:14:04 +0800497 self.event_log.Log('shutdown', operation='reboot')
498 self.state_instance.set_shared_data('shutdown_time',
499 time.time())
500 self.env.shutdown('reboot')
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800501
Jon Salz0697cbf2012-07-04 15:14:04 +0800502 self.on_ui_startup.append(handler)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800503
Jon Salz0697cbf2012-07-04 15:14:04 +0800504 def _prompt_cancel_shutdown(self, test, iteration):
505 if self.options.ui != 'chrome':
506 return False
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800507
Jon Salz0697cbf2012-07-04 15:14:04 +0800508 pending_shutdown_data = {
509 'delay_secs': test.delay_secs,
510 'time': time.time() + test.delay_secs,
511 'operation': test.operation,
512 'iteration': iteration,
513 'iterations': test.iterations,
514 }
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800515
Jon Salz0697cbf2012-07-04 15:14:04 +0800516 # Create a new (threaded) event client since we
517 # don't want to use the event loop for this.
518 with EventClient() as event_client:
519 event_client.post_event(Event(Event.Type.PENDING_SHUTDOWN,
520 **pending_shutdown_data))
521 aborted = event_client.wait(
522 lambda event: event.type == Event.Type.CANCEL_SHUTDOWN,
523 timeout=test.delay_secs) is not None
524 if aborted:
525 event_client.post_event(Event(Event.Type.PENDING_SHUTDOWN))
526 return aborted
Jon Salz258a40c2012-04-19 12:34:01 +0800527
Jon Salz0697cbf2012-07-04 15:14:04 +0800528 def init_states(self):
529 '''
530 Initializes all states on startup.
531 '''
532 for test in self.test_list.get_all_tests():
533 # Make sure the state server knows about all the tests,
534 # defaulting to an untested state.
535 test.update_state(update_parent=False, visible=False)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800536
Jon Salz0697cbf2012-07-04 15:14:04 +0800537 var_log_messages = None
Vic Yanga9c32212012-08-16 20:07:54 +0800538 mosys_log = None
Vic Yange4c275d2012-08-28 01:50:20 +0800539 ec_console_log = None
Vic Yang079f9872013-07-01 11:32:00 +0800540 ec_panic_info = None
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800541
Jon Salz0697cbf2012-07-04 15:14:04 +0800542 # Any 'active' tests should be marked as failed now.
543 for test in self.test_list.walk():
Jon Salza6711d72012-07-18 14:33:03 +0800544 if not test.is_leaf():
545 # Don't bother with parents; they will be updated when their
546 # children are updated.
547 continue
548
Jon Salz0697cbf2012-07-04 15:14:04 +0800549 test_state = test.get_state()
550 if test_state.status != TestState.ACTIVE:
551 continue
552 if isinstance(test, factory.ShutdownStep):
553 # Shutdown while the test was active - that's good.
554 self.handle_shutdown_complete(test, test_state)
555 else:
556 # Unexpected shutdown. Grab /var/log/messages for context.
557 if var_log_messages is None:
558 try:
559 var_log_messages = (
560 utils.var_log_messages_before_reboot())
561 # Write it to the log, to make it easier to
562 # correlate with /var/log/messages.
563 logging.info(
564 'Unexpected shutdown. '
565 'Tail of /var/log/messages before last reboot:\n'
566 '%s', ('\n'.join(
567 ' ' + x for x in var_log_messages)))
568 except: # pylint: disable=W0702
569 logging.exception('Unable to grok /var/log/messages')
570 var_log_messages = []
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800571
Jon Salz008f4ea2012-08-28 05:39:45 +0800572 if mosys_log is None and not utils.in_chroot():
573 try:
574 mosys_log = utils.Spawn(
575 ['mosys', 'eventlog', 'list'],
576 read_stdout=True, log_stderr_on_error=True).stdout_data
577 # Write it to the log also.
578 logging.info('System eventlog from mosys:\n%s\n', mosys_log)
579 except: # pylint: disable=W0702
580 logging.exception('Unable to read mosys eventlog')
Vic Yanga9c32212012-08-16 20:07:54 +0800581
Vic Yange4c275d2012-08-28 01:50:20 +0800582 if ec_console_log is None:
583 try:
Vic Yang8341dde2013-01-29 16:48:52 +0800584 board = system.GetBoard()
585 ec_console_log = board.GetECConsoleLog()
Vic Yange4c275d2012-08-28 01:50:20 +0800586 logging.info('EC console log after reboot:\n%s\n', ec_console_log)
Jon Salzfe1f6652012-09-07 05:40:14 +0800587 except: # pylint: disable=W0702
Vic Yange4c275d2012-08-28 01:50:20 +0800588 logging.exception('Error retrieving EC console log')
589
Vic Yang079f9872013-07-01 11:32:00 +0800590 if ec_panic_info is None:
591 try:
592 board = system.GetBoard()
593 ec_panic_info = board.GetECPanicInfo()
594 logging.info('EC panic info after reboot:\n%s\n', ec_panic_info)
595 except: # pylint: disable=W0702
596 logging.exception('Error retrieving EC panic info')
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 '''
Jon Salz885dcac2013-07-23 16:39:50 +0800624 env = TestArgEnv()
Jon Salz008f4ea2012-08-28 05:39:45 +0800625 for t in self.test_list.walk():
Jon Salz885dcac2013-07-23 16:39:50 +0800626 if t.is_leaf() and (t.run_if_table_name or t.run_if_expr):
627 value = None
628
629 if t.run_if_expr:
630 try:
631 value = t.run_if_expr(env)
632 except: # pylint: disable=W0702
633 logging.exception('Unable to evaluate run_if expression for %s',
634 t.path)
635 # But keep going; we have no choice. This will end up
636 # always activating the test.
637 else:
638 try:
639 aux = shopfloor.get_selected_aux_data(t.run_if_table_name)
640 value = aux.get(t.run_if_col)
641 except ValueError:
642 # Not available; assume it shouldn't be skipped
643 pass
644
645 if value is None:
646 skip = False
647 else:
648 skip = (not value) ^ t.run_if_not
Jon Salz008f4ea2012-08-28 05:39:45 +0800649
650 test_state = t.get_state()
651 if ((not skip) and
652 (test_state.status == TestState.PASSED) and
653 (test_state.error_msg == TestState.SKIPPED_MSG)):
654 # It was marked as skipped before, but now we need to run it.
655 # Mark as untested.
656 t.update_state(skip=skip, status=TestState.UNTESTED, error_msg='')
657 else:
658 t.update_state(skip=skip)
659
Jon Salz0697cbf2012-07-04 15:14:04 +0800660 def show_next_active_test(self):
661 '''
662 Rotates to the next visible active test.
663 '''
664 self.reap_completed_tests()
665 active_tests = [
666 t for t in self.test_list.walk()
667 if t.is_leaf() and t.get_state().status == TestState.ACTIVE]
668 if not active_tests:
669 return
Jon Salz4f6c7172012-06-11 20:45:36 +0800670
Jon Salz0697cbf2012-07-04 15:14:04 +0800671 try:
672 next_test = active_tests[
673 (active_tests.index(self.visible_test) + 1) % len(active_tests)]
674 except ValueError: # visible_test not present in active_tests
675 next_test = active_tests[0]
Jon Salz4f6c7172012-06-11 20:45:36 +0800676
Jon Salz0697cbf2012-07-04 15:14:04 +0800677 self.set_visible_test(next_test)
Jon Salz4f6c7172012-06-11 20:45:36 +0800678
Jon Salz0697cbf2012-07-04 15:14:04 +0800679 def handle_event(self, event):
680 '''
681 Handles an event from the event server.
682 '''
683 handler = self.event_handlers.get(event.type)
684 if handler:
685 handler(event)
686 else:
687 # We don't register handlers for all event types - just ignore
688 # this event.
689 logging.debug('Unbound event type %s', event.type)
Jon Salz4f6c7172012-06-11 20:45:36 +0800690
Vic Yangaabf9fd2013-04-09 18:56:13 +0800691 def check_critical_factory_note(self):
692 '''
693 Returns True if the last factory note is critical.
694 '''
695 notes = self.state_instance.get_shared_data('factory_note', True)
696 return notes and notes[-1]['level'] == 'CRITICAL'
697
Jon Salz0697cbf2012-07-04 15:14:04 +0800698 def run_next_test(self):
699 '''
700 Runs the next eligible test (or tests) in self.tests_to_run.
701 '''
702 self.reap_completed_tests()
Vic Yangaabf9fd2013-04-09 18:56:13 +0800703 if self.tests_to_run and self.check_critical_factory_note():
704 self.tests_to_run.clear()
705 return
Jon Salz0697cbf2012-07-04 15:14:04 +0800706 while self.tests_to_run:
707 logging.debug('Tests to run: %s',
708 [x.path for x in self.tests_to_run])
Jon Salz94eb56f2012-06-12 18:01:12 +0800709
Jon Salz0697cbf2012-07-04 15:14:04 +0800710 test = self.tests_to_run[0]
Jon Salz94eb56f2012-06-12 18:01:12 +0800711
Jon Salz0697cbf2012-07-04 15:14:04 +0800712 if test in self.invocations:
713 logging.info('Next test %s is already running', test.path)
714 self.tests_to_run.popleft()
715 return
Jon Salz94eb56f2012-06-12 18:01:12 +0800716
Jon Salza1412922012-07-23 16:04:17 +0800717 for requirement in test.require_run:
718 for i in requirement.test.walk():
719 if i.get_state().status == TestState.ACTIVE:
Jon Salz304a75d2012-07-06 11:14:15 +0800720 logging.info('Waiting for active test %s to complete '
Jon Salza1412922012-07-23 16:04:17 +0800721 'before running %s', i.path, test.path)
Jon Salz304a75d2012-07-06 11:14:15 +0800722 return
723
Jon Salz0697cbf2012-07-04 15:14:04 +0800724 if self.invocations and not (test.backgroundable and all(
725 [x.backgroundable for x in self.invocations])):
726 logging.debug('Waiting for non-backgroundable tests to '
727 'complete before running %s', test.path)
728 return
Jon Salz94eb56f2012-06-12 18:01:12 +0800729
Jon Salz3e6f5202012-10-15 15:08:29 +0800730 if test.get_state().skip:
731 factory.console.info('Skipping test %s', test.path)
732 test.update_state(status=TestState.PASSED,
733 error_msg=TestState.SKIPPED_MSG)
734 self.tests_to_run.popleft()
735 continue
736
Jon Salz0697cbf2012-07-04 15:14:04 +0800737 self.tests_to_run.popleft()
Jon Salz94eb56f2012-06-12 18:01:12 +0800738
Jon Salz304a75d2012-07-06 11:14:15 +0800739 untested = set()
Jon Salza1412922012-07-23 16:04:17 +0800740 for requirement in test.require_run:
741 for i in requirement.test.walk():
742 if i == test:
Jon Salz304a75d2012-07-06 11:14:15 +0800743 # We've hit this test itself; stop checking
744 break
Jon Salza1412922012-07-23 16:04:17 +0800745 if ((i.get_state().status == TestState.UNTESTED) or
746 (requirement.passed and i.get_state().status !=
747 TestState.PASSED)):
Jon Salz304a75d2012-07-06 11:14:15 +0800748 # Found an untested test; move on to the next
749 # element in require_run.
Jon Salza1412922012-07-23 16:04:17 +0800750 untested.add(i)
Jon Salz304a75d2012-07-06 11:14:15 +0800751 break
752
753 if untested:
754 untested_paths = ', '.join(sorted([x.path for x in untested]))
755 if self.state_instance.get_shared_data('engineering_mode',
756 optional=True):
757 # In engineering mode, we'll let it go.
758 factory.console.warn('In engineering mode; running '
759 '%s even though required tests '
760 '[%s] have not completed',
761 test.path, untested_paths)
762 else:
763 # Not in engineering mode; mark it failed.
764 error_msg = ('Required tests [%s] have not been run yet'
765 % untested_paths)
766 factory.console.error('Not running %s: %s',
767 test.path, error_msg)
768 test.update_state(status=TestState.FAILED,
769 error_msg=error_msg)
770 continue
771
Jon Salz0697cbf2012-07-04 15:14:04 +0800772 if isinstance(test, factory.ShutdownStep):
773 if os.path.exists(NO_REBOOT_FILE):
774 test.update_state(
775 status=TestState.FAILED, increment_count=1,
776 error_msg=('Skipped shutdown since %s is present' %
Jon Salz304a75d2012-07-06 11:14:15 +0800777 NO_REBOOT_FILE))
Jon Salz0697cbf2012-07-04 15:14:04 +0800778 continue
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800779
Jon Salz0697cbf2012-07-04 15:14:04 +0800780 test.update_state(status=TestState.ACTIVE, increment_count=1,
781 error_msg='', shutdown_count=0)
782 if self._prompt_cancel_shutdown(test, 1):
783 self.event_log.Log('reboot_cancelled')
784 test.update_state(
785 status=TestState.FAILED, increment_count=1,
786 error_msg='Shutdown aborted by operator',
787 shutdown_count=0)
chungyiafe8f772012-08-15 19:36:29 +0800788 continue
Jon Salz2f757d42012-06-27 17:06:42 +0800789
Jon Salz0697cbf2012-07-04 15:14:04 +0800790 # Save pending test list in the state server
Jon Salzdbf398f2012-06-14 17:30:01 +0800791 self.state_instance.set_shared_data(
Jon Salz0697cbf2012-07-04 15:14:04 +0800792 'tests_after_shutdown',
793 [t.path for t in self.tests_to_run])
794 # Save shutdown time
795 self.state_instance.set_shared_data('shutdown_time',
796 time.time())
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800797
Jon Salz0697cbf2012-07-04 15:14:04 +0800798 with self.env.lock:
799 self.event_log.Log('shutdown', operation=test.operation)
800 shutdown_result = self.env.shutdown(test.operation)
801 if shutdown_result:
802 # That's all, folks!
803 self.run_queue.put(None)
804 return
805 else:
806 # Just pass (e.g., in the chroot).
807 test.update_state(status=TestState.PASSED)
808 self.state_instance.set_shared_data(
809 'tests_after_shutdown', None)
810 # Send event with no fields to indicate that there is no
811 # longer a pending shutdown.
812 self.event_client.post_event(Event(
813 Event.Type.PENDING_SHUTDOWN))
814 continue
Jon Salz258a40c2012-04-19 12:34:01 +0800815
Cheng-Yi Chiangce05c002013-04-04 02:13:17 +0800816 self._run_test(test, test.iterations, test.retries)
Jon Salz1acc8742012-07-17 17:45:55 +0800817
Cheng-Yi Chiangce05c002013-04-04 02:13:17 +0800818 def _run_test(self, test, iterations_left=None, retries_left=None):
Jon Salz1acc8742012-07-17 17:45:55 +0800819 invoc = TestInvocation(self, test, on_completion=self.run_next_test)
820 new_state = test.update_state(
821 status=TestState.ACTIVE, increment_count=1, error_msg='',
Jon Salzbd42ce12012-09-18 08:03:59 +0800822 invocation=invoc.uuid, iterations_left=iterations_left,
Cheng-Yi Chiangce05c002013-04-04 02:13:17 +0800823 retries_left=retries_left,
Jon Salzbd42ce12012-09-18 08:03:59 +0800824 visible=(self.visible_test == test))
Jon Salz1acc8742012-07-17 17:45:55 +0800825 invoc.count = new_state.count
826
827 self.invocations[test] = invoc
828 if self.visible_test is None and test.has_ui:
829 self.set_visible_test(test)
Vic Yang311ddb82012-09-26 12:08:28 +0800830 self.check_exclusive()
Jon Salz1acc8742012-07-17 17:45:55 +0800831 invoc.start()
Jon Salz5f2a0672012-05-22 17:14:06 +0800832
Vic Yang311ddb82012-09-26 12:08:28 +0800833 def check_exclusive(self):
Jon Salzce6a7f82013-06-10 18:22:54 +0800834 # alias since this is really long
835 EXCL_OPT = factory.FactoryTest.EXCLUSIVE_OPTIONS
836
Vic Yang311ddb82012-09-26 12:08:28 +0800837 current_exclusive_items = set([
Jon Salzce6a7f82013-06-10 18:22:54 +0800838 item for item in EXCL_OPT
Vic Yang311ddb82012-09-26 12:08:28 +0800839 if any([test.is_exclusive(item) for test in self.invocations])])
840
841 new_exclusive_items = current_exclusive_items - self.exclusive_items
Jon Salzce6a7f82013-06-10 18:22:54 +0800842 if EXCL_OPT.NETWORKING in new_exclusive_items:
Vic Yang311ddb82012-09-26 12:08:28 +0800843 logging.info('Disabling network')
844 self.connection_manager.DisableNetworking()
Jon Salzce6a7f82013-06-10 18:22:54 +0800845 if EXCL_OPT.CHARGER in new_exclusive_items:
Vic Yang311ddb82012-09-26 12:08:28 +0800846 logging.info('Stop controlling charger')
847
848 new_non_exclusive_items = self.exclusive_items - current_exclusive_items
Jon Salzce6a7f82013-06-10 18:22:54 +0800849 if EXCL_OPT.NETWORKING in new_non_exclusive_items:
Vic Yang311ddb82012-09-26 12:08:28 +0800850 logging.info('Re-enabling network')
851 self.connection_manager.EnableNetworking()
Jon Salzce6a7f82013-06-10 18:22:54 +0800852 if EXCL_OPT.CHARGER in new_non_exclusive_items:
Vic Yang311ddb82012-09-26 12:08:28 +0800853 logging.info('Start controlling charger')
854
Jon Salzce6a7f82013-06-10 18:22:54 +0800855 if self.cpufreq_manager:
856 enabled = EXCL_OPT.CPUFREQ not in current_exclusive_items
857 try:
858 self.cpufreq_manager.SetEnabled(enabled)
859 except: # pylint: disable=W0702
860 logging.exception('Unable to %s cpufreq services',
861 'enable' if enabled else 'disable')
862
Vic Yang311ddb82012-09-26 12:08:28 +0800863 # Only adjust charge state if not excluded
Jon Salzce6a7f82013-06-10 18:22:54 +0800864 if (EXCL_OPT.CHARGER not in current_exclusive_items and
865 not utils.in_chroot()):
Cheng-Yi Chiangd8186952013-04-04 23:41:14 +0800866 if self.charge_manager:
867 self.charge_manager.AdjustChargeState()
868 else:
869 try:
870 system.GetBoard().SetChargeState(Board.ChargeState.CHARGE)
871 except BoardException:
872 logging.exception('Unable to set charge state on this board')
Vic Yang311ddb82012-09-26 12:08:28 +0800873
874 self.exclusive_items = current_exclusive_items
Jon Salz5da61e62012-05-31 13:06:22 +0800875
cychiang21886742012-07-05 15:16:32 +0800876 def check_for_updates(self):
877 '''
878 Schedules an asynchronous check for updates if necessary.
879 '''
880 if not self.test_list.options.update_period_secs:
881 # Not enabled.
882 return
883
884 now = time.time()
885 if self.last_update_check and (
886 now - self.last_update_check <
887 self.test_list.options.update_period_secs):
888 # Not yet time for another check.
889 return
890
891 self.last_update_check = now
892
893 def handle_check_for_update(reached_shopfloor, md5sum, needs_update):
894 if reached_shopfloor:
895 new_update_md5sum = md5sum if needs_update else None
896 if system.SystemInfo.update_md5sum != new_update_md5sum:
897 logging.info('Received new update MD5SUM: %s', new_update_md5sum)
898 system.SystemInfo.update_md5sum = new_update_md5sum
899 self.run_queue.put(self.update_system_info)
900
901 updater.CheckForUpdateAsync(
902 handle_check_for_update,
903 self.test_list.options.shopfloor_timeout_secs)
904
Jon Salza6711d72012-07-18 14:33:03 +0800905 def cancel_pending_tests(self):
906 '''Cancels any tests in the run queue.'''
907 self.run_tests([])
908
Jon Salz0697cbf2012-07-04 15:14:04 +0800909 def run_tests(self, subtrees, untested_only=False):
910 '''
911 Runs tests under subtree.
Jon Salz258a40c2012-04-19 12:34:01 +0800912
Jon Salz0697cbf2012-07-04 15:14:04 +0800913 The tests are run in order unless one fails (then stops).
914 Backgroundable tests are run simultaneously; when a foreground test is
915 encountered, we wait for all active tests to finish before continuing.
Jon Salzb1b39092012-05-03 02:05:09 +0800916
Jon Salz0697cbf2012-07-04 15:14:04 +0800917 @param subtrees: Node or nodes containing tests to run (may either be
918 a single test or a list). Duplicates will be ignored.
919 '''
920 if type(subtrees) != list:
921 subtrees = [subtrees]
Jon Salz258a40c2012-04-19 12:34:01 +0800922
Jon Salz0697cbf2012-07-04 15:14:04 +0800923 # Nodes we've seen so far, to avoid duplicates.
924 seen = set()
Jon Salz94eb56f2012-06-12 18:01:12 +0800925
Jon Salz0697cbf2012-07-04 15:14:04 +0800926 self.tests_to_run = deque()
927 for subtree in subtrees:
928 for test in subtree.walk():
929 if test in seen:
930 continue
931 seen.add(test)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800932
Jon Salz0697cbf2012-07-04 15:14:04 +0800933 if not test.is_leaf():
934 continue
935 if (untested_only and
936 test.get_state().status != TestState.UNTESTED):
937 continue
938 self.tests_to_run.append(test)
939 self.run_next_test()
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800940
Jon Salz0697cbf2012-07-04 15:14:04 +0800941 def reap_completed_tests(self):
942 '''
943 Removes completed tests from the set of active tests.
944
945 Also updates the visible test if it was reaped.
946 '''
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +0800947 test_completed = False
Jon Salz0697cbf2012-07-04 15:14:04 +0800948 for t, v in dict(self.invocations).iteritems():
949 if v.is_completed():
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +0800950 test_completed = True
Jon Salz1acc8742012-07-17 17:45:55 +0800951 new_state = t.update_state(**v.update_state_on_completion)
Jon Salz0697cbf2012-07-04 15:14:04 +0800952 del self.invocations[t]
953
Chun-Ta Lin54e17e42012-09-06 22:05:13 +0800954 # Stop on failure if flag is true.
955 if (self.test_list.options.stop_on_failure and
956 new_state.status == TestState.FAILED):
957 # Clean all the tests to cause goofy to stop.
958 self.tests_to_run = []
959 factory.console.info("Stop on failure triggered. Empty the queue.")
960
Jon Salz1acc8742012-07-17 17:45:55 +0800961 if new_state.iterations_left and new_state.status == TestState.PASSED:
962 # Play it again, Sam!
963 self._run_test(t)
Cheng-Yi Chiangce05c002013-04-04 02:13:17 +0800964 # new_state.retries_left is obtained after update.
965 # For retries_left == 0, test can still be run for the last time.
966 elif (new_state.retries_left >= 0 and
967 new_state.status == TestState.FAILED):
968 # Still have to retry, Sam!
969 self._run_test(t)
Jon Salz1acc8742012-07-17 17:45:55 +0800970
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +0800971 if test_completed:
Vic Yangf01c59f2013-04-19 17:37:56 +0800972 self.log_watcher.KickWatchThread()
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +0800973
Jon Salz0697cbf2012-07-04 15:14:04 +0800974 if (self.visible_test is None or
Jon Salz85a39882012-07-05 16:45:04 +0800975 self.visible_test not in self.invocations):
Jon Salz0697cbf2012-07-04 15:14:04 +0800976 self.set_visible_test(None)
977 # Make the first running test, if any, the visible test
978 for t in self.test_list.walk():
979 if t in self.invocations:
980 self.set_visible_test(t)
981 break
982
Jon Salz6dc031d2013-06-19 13:06:23 +0800983 def kill_active_tests(self, abort, root=None, reason=None):
Jon Salz0697cbf2012-07-04 15:14:04 +0800984 '''
985 Kills and waits for all active tests.
986
Jon Salz85a39882012-07-05 16:45:04 +0800987 Args:
988 abort: True to change state of killed tests to FAILED, False for
Jon Salz0697cbf2012-07-04 15:14:04 +0800989 UNTESTED.
Jon Salz85a39882012-07-05 16:45:04 +0800990 root: If set, only kills tests with root as an ancestor.
Jon Salz0697cbf2012-07-04 15:14:04 +0800991 '''
992 self.reap_completed_tests()
993 for test, invoc in self.invocations.items():
Jon Salz85a39882012-07-05 16:45:04 +0800994 if root and not test.has_ancestor(root):
995 continue
996
Jon Salz0697cbf2012-07-04 15:14:04 +0800997 factory.console.info('Killing active test %s...' % test.path)
Jon Salz6dc031d2013-06-19 13:06:23 +0800998 invoc.abort_and_join(reason)
Jon Salz0697cbf2012-07-04 15:14:04 +0800999 factory.console.info('Killed %s' % test.path)
Jon Salz1acc8742012-07-17 17:45:55 +08001000 test.update_state(**invoc.update_state_on_completion)
Jon Salz0697cbf2012-07-04 15:14:04 +08001001 del self.invocations[test]
Jon Salz1acc8742012-07-17 17:45:55 +08001002
Jon Salz0697cbf2012-07-04 15:14:04 +08001003 if not abort:
1004 test.update_state(status=TestState.UNTESTED)
1005 self.reap_completed_tests()
1006
Jon Salz6dc031d2013-06-19 13:06:23 +08001007 def stop(self, root=None, fail=False, reason=None):
1008 self.kill_active_tests(fail, root, reason)
Jon Salz85a39882012-07-05 16:45:04 +08001009 # Remove any tests in the run queue under the root.
1010 self.tests_to_run = deque([x for x in self.tests_to_run
1011 if root and not x.has_ancestor(root)])
1012 self.run_next_test()
Jon Salz0697cbf2012-07-04 15:14:04 +08001013
Jon Salz4712ac72013-02-07 17:12:05 +08001014 def clear_state(self, root=None):
Jon Salzd7550792013-07-12 05:49:27 +08001015 if root is None:
1016 root = self.test_list
Jon Salz6dc031d2013-06-19 13:06:23 +08001017 self.stop(root, reason='Clearing test state')
Jon Salz4712ac72013-02-07 17:12:05 +08001018 for f in root.walk():
1019 if f.is_leaf():
1020 f.update_state(status=TestState.UNTESTED)
1021
Jon Salz6dc031d2013-06-19 13:06:23 +08001022 def abort_active_tests(self, reason=None):
1023 self.kill_active_tests(True, reason=reason)
Jon Salz0697cbf2012-07-04 15:14:04 +08001024
1025 def main(self):
Jon Salzeff94182013-06-19 15:06:28 +08001026 syslog.openlog('goofy')
1027
Jon Salz0697cbf2012-07-04 15:14:04 +08001028 try:
Jon Salzd7550792013-07-12 05:49:27 +08001029 self.status = Status.INITIALIZING
Jon Salz0697cbf2012-07-04 15:14:04 +08001030 self.init()
1031 self.event_log.Log('goofy_init',
1032 success=True)
1033 except:
1034 if self.event_log:
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001035 try:
Jon Salz0697cbf2012-07-04 15:14:04 +08001036 self.event_log.Log('goofy_init',
1037 success=False,
1038 trace=traceback.format_exc())
1039 except: # pylint: disable=W0702
1040 pass
1041 raise
1042
Jon Salzd7550792013-07-12 05:49:27 +08001043 self.status = Status.RUNNING
Jon Salzeff94182013-06-19 15:06:28 +08001044 syslog.syslog('Goofy (factory test harness) starting')
Jon Salz0697cbf2012-07-04 15:14:04 +08001045 self.run()
1046
1047 def update_system_info(self):
1048 '''Updates system info.'''
1049 system_info = system.SystemInfo()
1050 self.state_instance.set_shared_data('system_info', system_info.__dict__)
1051 self.event_client.post_event(Event(Event.Type.SYSTEM_INFO,
1052 system_info=system_info.__dict__))
1053 logging.info('System info: %r', system_info.__dict__)
1054
Jon Salzeb42f0d2012-07-27 19:14:04 +08001055 def update_factory(self, auto_run_on_restart=False, post_update_hook=None):
1056 '''Commences updating factory software.
1057
1058 Args:
1059 auto_run_on_restart: Auto-run when the machine comes back up.
1060 post_update_hook: Code to call after update but immediately before
1061 restart.
1062
1063 Returns:
1064 Never if the update was successful (we just reboot).
1065 False if the update was unnecessary (no update available).
1066 '''
Jon Salz6dc031d2013-06-19 13:06:23 +08001067 self.kill_active_tests(False, reason='Factory software update')
Jon Salza6711d72012-07-18 14:33:03 +08001068 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +08001069
Jon Salz5c344f62012-07-13 14:31:16 +08001070 def pre_update_hook():
1071 if auto_run_on_restart:
1072 self.state_instance.set_shared_data('tests_after_shutdown',
1073 FORCE_AUTO_RUN)
1074 self.state_instance.close()
1075
Jon Salzeb42f0d2012-07-27 19:14:04 +08001076 if updater.TryUpdate(pre_update_hook=pre_update_hook):
1077 if post_update_hook:
1078 post_update_hook()
1079 self.env.shutdown('reboot')
Jon Salz0697cbf2012-07-04 15:14:04 +08001080
Jon Salzcef132a2012-08-30 04:58:08 +08001081 def handle_sigint(self, dummy_signum, dummy_frame):
Jon Salz77c151e2012-08-28 07:20:37 +08001082 logging.error('Received SIGINT')
1083 self.run_queue.put(None)
1084 raise KeyboardInterrupt()
1085
Jon Salze12c2b32013-06-25 16:24:34 +08001086 def find_kcrashes(self):
1087 """Finds kcrash files, logs them, and marks them as seen."""
1088 seen_crashes = set(
1089 self.state_instance.get_shared_data('seen_crashes', optional=True)
1090 or [])
1091
1092 for path in glob.glob('/var/spool/crash/*'):
1093 if not os.path.isfile(path):
1094 continue
1095 if path in seen_crashes:
1096 continue
1097 try:
1098 stat = os.stat(path)
1099 mtime = utils.TimeString(stat.st_mtime)
1100 logging.info(
1101 'Found new crash file %s (%d bytes at %s)',
1102 path, stat.st_size, mtime)
1103 extra_log_args = {}
1104
1105 try:
1106 _, ext = os.path.splitext(path)
1107 if ext in ['.kcrash', '.meta']:
1108 ext = ext.replace('.', '')
1109 with open(path) as f:
1110 data = f.read(MAX_CRASH_FILE_SIZE)
1111 tell = f.tell()
1112 logging.info(
1113 'Contents of %s%s:%s',
1114 path,
1115 ('' if tell == stat.st_size
1116 else '(truncated to %d bytes)' % MAX_CRASH_FILE_SIZE),
1117 ('\n' + data).replace('\n', '\n ' + ext + '> '))
1118 extra_log_args['data'] = data
1119
1120 # Copy to /var/factory/kcrash for posterity
1121 kcrash_dir = factory.get_factory_root('kcrash')
1122 utils.TryMakeDirs(kcrash_dir)
1123 shutil.copy(path, kcrash_dir)
1124 logging.info('Copied to %s',
1125 os.path.join(kcrash_dir, os.path.basename(path)))
1126 finally:
1127 # Even if something goes wrong with the above, still try to
1128 # log to event log
1129 self.event_log.Log('crash_file',
1130 path=path, size=stat.st_size, mtime=mtime,
1131 **extra_log_args)
1132 except: # pylint: disable=W0702
1133 logging.exception('Unable to handle crash files %s', path)
1134 seen_crashes.add(path)
1135
1136 self.state_instance.set_shared_data('seen_crashes', list(seen_crashes))
1137
Jon Salz128b0932013-07-03 16:55:26 +08001138 def GetTestList(self, test_list_id):
1139 """Returns the test list with the given ID.
1140
1141 Raises:
1142 TestListError: The test list ID is not valid.
1143 """
1144 try:
1145 return self.test_lists[test_list_id]
1146 except KeyError:
1147 raise test_lists.TestListError(
1148 '%r is not a valid test list ID (available IDs are [%s])' % (
1149 test_list_id, ', '.join(sorted(self.test_lists.keys()))))
1150
1151 def InitTestLists(self):
1152 """Reads in all test lists and sets the active test list."""
1153 self.test_lists = test_lists.BuildAllTestLists()
Jon Salzd7550792013-07-12 05:49:27 +08001154 logging.info('Loaded test lists: [%s]',
1155 test_lists.DescribeTestLists(self.test_lists))
Jon Salz128b0932013-07-03 16:55:26 +08001156
1157 if not self.options.test_list:
1158 self.options.test_list = test_lists.GetActiveTestListId()
1159
1160 if os.sep in self.options.test_list:
1161 # It's a path pointing to an old-style test list; use it.
1162 self.test_list = factory.read_test_list(self.options.test_list)
1163 else:
1164 self.test_list = self.GetTestList(self.options.test_list)
1165
1166 logging.info('Active test list: %s', self.test_list.test_list_id)
1167
1168 if isinstance(self.test_list, test_lists.OldStyleTestList):
1169 # Actually load it in. (See OldStyleTestList for an explanation
1170 # of why this is necessary.)
1171 self.test_list = self.test_list.Load()
1172
1173 self.test_list.state_instance = self.state_instance
1174
Jon Salz0697cbf2012-07-04 15:14:04 +08001175 def init(self, args=None, env=None):
1176 '''Initializes Goofy.
1177
1178 Args:
1179 args: A list of command-line arguments. Uses sys.argv if
1180 args is None.
1181 env: An Environment instance to use (or None to choose
1182 FakeChrootEnvironment or DUTEnvironment as appropriate).
1183 '''
Jon Salz77c151e2012-08-28 07:20:37 +08001184 signal.signal(signal.SIGINT, self.handle_sigint)
1185
Jon Salz0697cbf2012-07-04 15:14:04 +08001186 parser = OptionParser()
1187 parser.add_option('-v', '--verbose', dest='verbose',
Jon Salz8fa8e832012-07-13 19:04:09 +08001188 action='store_true',
1189 help='Enable debug logging')
Jon Salz0697cbf2012-07-04 15:14:04 +08001190 parser.add_option('--print_test_list', dest='print_test_list',
Jon Salz8fa8e832012-07-13 19:04:09 +08001191 metavar='FILE',
1192 help='Read and print test list FILE, and exit')
Jon Salz0697cbf2012-07-04 15:14:04 +08001193 parser.add_option('--restart', dest='restart',
Jon Salz8fa8e832012-07-13 19:04:09 +08001194 action='store_true',
1195 help='Clear all test state')
Jon Salz0697cbf2012-07-04 15:14:04 +08001196 parser.add_option('--ui', dest='ui', type='choice',
Jon Salz8fa8e832012-07-13 19:04:09 +08001197 choices=['none', 'gtk', 'chrome'],
Jon Salz2f881df2013-02-01 17:00:35 +08001198 default='chrome',
Jon Salz8fa8e832012-07-13 19:04:09 +08001199 help='UI to use')
Jon Salz0697cbf2012-07-04 15:14:04 +08001200 parser.add_option('--ui_scale_factor', dest='ui_scale_factor',
Jon Salz8fa8e832012-07-13 19:04:09 +08001201 type='int', default=1,
1202 help=('Factor by which to scale UI '
1203 '(Chrome UI only)'))
Jon Salz0697cbf2012-07-04 15:14:04 +08001204 parser.add_option('--test_list', dest='test_list',
Jon Salz8fa8e832012-07-13 19:04:09 +08001205 metavar='FILE',
1206 help='Use FILE as test list')
Jon Salzc79a9982012-08-30 04:42:01 +08001207 parser.add_option('--dummy_shopfloor', action='store_true',
1208 help='Use a dummy shopfloor server')
chungyiafe8f772012-08-15 19:36:29 +08001209 parser.add_option('--automation', dest='automation',
1210 action='store_true',
1211 help='Enable automation on running factory test')
Ricky Liang09216dc2013-02-22 17:26:45 +08001212 parser.add_option('--one_pixel_less', dest='one_pixel_less',
1213 action='store_true',
1214 help=('Start Chrome one pixel less than the full screen.'
1215 'Needed by Exynos platform to run GTK.'))
Jon Salz0697cbf2012-07-04 15:14:04 +08001216 (self.options, self.args) = parser.parse_args(args)
1217
Jon Salz46b89562012-07-05 11:49:22 +08001218 # Make sure factory directories exist.
1219 factory.get_log_root()
1220 factory.get_state_root()
1221 factory.get_test_data_root()
1222
Jon Salz0697cbf2012-07-04 15:14:04 +08001223 global _inited_logging # pylint: disable=W0603
1224 if not _inited_logging:
1225 factory.init_logging('goofy', verbose=self.options.verbose)
1226 _inited_logging = True
Jon Salz8fa8e832012-07-13 19:04:09 +08001227
Jon Salz0f996602012-10-03 15:26:48 +08001228 if self.options.print_test_list:
1229 print factory.read_test_list(
1230 self.options.print_test_list).__repr__(recursive=True)
1231 sys.exit(0)
1232
Jon Salzee85d522012-07-17 14:34:46 +08001233 event_log.IncrementBootSequence()
Jon Salzd15bbcf2013-05-21 17:33:57 +08001234 # Don't defer logging the initial event, so we can make sure
1235 # that device_id, reimage_id, etc. are all set up.
1236 self.event_log = EventLog('goofy', defer=False)
Jon Salz0697cbf2012-07-04 15:14:04 +08001237
1238 if (not suppress_chroot_warning and
1239 factory.in_chroot() and
1240 self.options.ui == 'gtk' and
1241 os.environ.get('DISPLAY') in [None, '', ':0', ':0.0']):
1242 # That's not going to work! Tell the user how to run
1243 # this way.
1244 logging.warn(GOOFY_IN_CHROOT_WARNING)
1245 time.sleep(1)
1246
1247 if env:
1248 self.env = env
1249 elif factory.in_chroot():
1250 self.env = test_environment.FakeChrootEnvironment()
1251 logging.warn(
1252 'Using chroot environment: will not actually run autotests')
1253 else:
1254 self.env = test_environment.DUTEnvironment()
1255 self.env.goofy = self
1256
1257 if self.options.restart:
1258 state.clear_state()
1259
Jon Salz0697cbf2012-07-04 15:14:04 +08001260 if self.options.ui_scale_factor != 1 and utils.in_qemu():
1261 logging.warn(
1262 'In QEMU; ignoring ui_scale_factor argument')
1263 self.options.ui_scale_factor = 1
1264
1265 logging.info('Started')
1266
1267 self.start_state_server()
1268 self.state_instance.set_shared_data('hwid_cfg', get_hwid_cfg())
1269 self.state_instance.set_shared_data('ui_scale_factor',
Ricky Liang09216dc2013-02-22 17:26:45 +08001270 self.options.ui_scale_factor)
1271 self.state_instance.set_shared_data('one_pixel_less',
1272 self.options.one_pixel_less)
Jon Salz0697cbf2012-07-04 15:14:04 +08001273 self.last_shutdown_time = (
1274 self.state_instance.get_shared_data('shutdown_time', optional=True))
1275 self.state_instance.del_shared_data('shutdown_time', optional=True)
Jon Salzb19ea072013-02-07 16:35:00 +08001276 self.state_instance.del_shared_data('startup_error', optional=True)
Jon Salz0697cbf2012-07-04 15:14:04 +08001277
Jon Salz128b0932013-07-03 16:55:26 +08001278 try:
1279 self.InitTestLists()
1280 except: # pylint: disable=W0702
1281 logging.exception('Unable to initialize test lists')
1282 self.state_instance.set_shared_data(
1283 'startup_error',
1284 'Unable to initialize test lists\n%s' % (
1285 traceback.format_exc()))
Jon Salzb19ea072013-02-07 16:35:00 +08001286 if self.options.ui == 'chrome':
1287 # Create an empty test list with default options so that the rest of
1288 # startup can proceed.
1289 self.test_list = factory.FactoryTestList(
1290 [], self.state_instance, factory.Options())
1291 else:
1292 # Bail with an error; no point in starting up.
1293 sys.exit('No valid test list; exiting.')
1294
Jon Salz822838b2013-03-25 17:32:33 +08001295 if self.test_list.options.clear_state_on_start:
1296 self.state_instance.clear_test_state()
1297
Vic Yang3e1cf5d2013-06-05 18:50:24 +08001298 if system.SystemInfo().firmware_version is None and not utils.in_chroot():
Vic Yang9bd4f772013-06-04 17:34:00 +08001299 self.state_instance.set_shared_data('startup_error',
1300 'Netboot firmware detected\n'
1301 'Connect Ethernet and reboot to re-image.\n'
1302 u'侦测到网路开机固件\n'
1303 u'请连接乙太网并重启')
1304
Jon Salz0697cbf2012-07-04 15:14:04 +08001305 if not self.state_instance.has_shared_data('ui_lang'):
1306 self.state_instance.set_shared_data('ui_lang',
1307 self.test_list.options.ui_lang)
1308 self.state_instance.set_shared_data(
1309 'test_list_options',
1310 self.test_list.options.__dict__)
1311 self.state_instance.test_list = self.test_list
1312
Cheng-Yi Chiangeb398df2013-07-19 14:30:45 +08001313 if not utils.in_chroot():
1314 cleanup_logs_paused_path = '/var/lib/cleanup_logs_paused'
1315 if self.test_list.options.disable_log_rotation:
1316 open(cleanup_logs_paused_path, 'w').close()
1317 else:
1318 file_utils.TryUnlink(cleanup_logs_paused_path)
Jon Salz83ef34b2012-11-01 19:46:35 +08001319
Jon Salz23926422012-09-01 03:38:13 +08001320 if self.options.dummy_shopfloor:
1321 os.environ[shopfloor.SHOPFLOOR_SERVER_ENV_VAR_NAME] = (
1322 'http://localhost:%d/' % shopfloor.DEFAULT_SERVER_PORT)
1323 self.dummy_shopfloor = Spawn(
1324 [os.path.join(factory.FACTORY_PATH, 'bin', 'shopfloor_server'),
1325 '--dummy'])
1326 elif self.test_list.options.shopfloor_server_url:
1327 shopfloor.set_server_url(self.test_list.options.shopfloor_server_url)
Jon Salz2bf2f6b2013-03-28 18:49:26 +08001328 shopfloor.set_enabled(True)
Jon Salz23926422012-09-01 03:38:13 +08001329
Jon Salz0f996602012-10-03 15:26:48 +08001330 if self.test_list.options.time_sanitizer and not utils.in_chroot():
Jon Salz8fa8e832012-07-13 19:04:09 +08001331 self.time_sanitizer = time_sanitizer.TimeSanitizer(
1332 base_time=time_sanitizer.GetBaseTimeFromFile(
1333 # lsb-factory is written by the factory install shim during
1334 # installation, so it should have a good time obtained from
Jon Salz54882d02012-08-31 01:57:54 +08001335 # the mini-Omaha server. If it's not available, we'll use
1336 # /etc/lsb-factory (which will be much older, but reasonably
1337 # sane) and rely on a shopfloor sync to set a more accurate
1338 # time.
1339 '/usr/local/etc/lsb-factory',
1340 '/etc/lsb-release'))
Jon Salz8fa8e832012-07-13 19:04:09 +08001341 self.time_sanitizer.RunOnce()
1342
Vic Yangd8990da2013-06-27 16:57:43 +08001343 if self.test_list.options.check_cpu_usage_period_secs:
1344 self.cpu_usage_watcher = Spawn(['py/tools/cpu_usage_monitor.py',
1345 '-p', str(self.test_list.options.check_cpu_usage_period_secs)],
1346 cwd=factory.FACTORY_PATH)
1347
Jon Salz0697cbf2012-07-04 15:14:04 +08001348 self.init_states()
1349 self.start_event_server()
1350 self.connection_manager = self.env.create_connection_manager(
Tai-Hsu Lin371351a2012-08-27 14:17:14 +08001351 self.test_list.options.wlans,
1352 self.test_list.options.scan_wifi_period_secs)
Jon Salz0697cbf2012-07-04 15:14:04 +08001353 # Note that we create a log watcher even if
1354 # sync_event_log_period_secs isn't set (no background
1355 # syncing), since we may use it to flush event logs as well.
1356 self.log_watcher = EventLogWatcher(
1357 self.test_list.options.sync_event_log_period_secs,
Jon Salzd15bbcf2013-05-21 17:33:57 +08001358 event_log_db_file=None,
Jon Salz16d10542012-07-23 12:18:45 +08001359 handle_event_logs_callback=self.handle_event_logs)
Jon Salz0697cbf2012-07-04 15:14:04 +08001360 if self.test_list.options.sync_event_log_period_secs:
1361 self.log_watcher.StartWatchThread()
1362
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +08001363 # Note that we create a system log manager even if
1364 # sync_log_period_secs isn't set (no background
1365 # syncing), since we may kick it to sync logs in its
1366 # thread.
Cheng-Yi Chiangd3516a32013-07-17 15:30:47 +08001367 if self.test_list.options.enable_sync_log:
1368 self.system_log_manager = SystemLogManager(
1369 sync_log_paths=self.test_list.options.sync_log_paths,
1370 sync_period_sec=self.test_list.options.sync_log_period_secs,
1371 clear_log_paths=self.test_list.options.clear_log_paths)
1372 self.system_log_manager.StartSyncThread()
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +08001373
Jon Salz0697cbf2012-07-04 15:14:04 +08001374 self.update_system_info()
1375
Vic Yang4953fc12012-07-26 16:19:53 +08001376 assert ((self.test_list.options.min_charge_pct is None) ==
1377 (self.test_list.options.max_charge_pct is None))
Vic Yange83d9a12013-04-19 20:00:20 +08001378 if utils.in_chroot():
1379 logging.info('In chroot, ignoring charge manager and charge state')
1380 elif self.test_list.options.min_charge_pct is not None:
Vic Yang4953fc12012-07-26 16:19:53 +08001381 self.charge_manager = ChargeManager(self.test_list.options.min_charge_pct,
1382 self.test_list.options.max_charge_pct)
Jon Salzad7353b2012-10-15 16:22:46 +08001383 system.SystemStatus.charge_manager = self.charge_manager
Cheng-Yi Chiangd8186952013-04-04 23:41:14 +08001384 else:
1385 # Goofy should set charger state to charge if charge_manager is disabled.
1386 try:
1387 system.GetBoard().SetChargeState(Board.ChargeState.CHARGE)
1388 except BoardException:
1389 logging.exception('Unable to set charge state on this board')
Vic Yang4953fc12012-07-26 16:19:53 +08001390
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001391 self.core_dump_manager = CoreDumpManager(
1392 self.test_list.options.core_dump_watchlist)
1393
Jon Salz0697cbf2012-07-04 15:14:04 +08001394 os.environ['CROS_FACTORY'] = '1'
1395 os.environ['CROS_DISABLE_SITE_SYSINFO'] = '1'
1396
1397 # Set CROS_UI since some behaviors in ui.py depend on the
1398 # particular UI in use. TODO(jsalz): Remove this (and all
1399 # places it is used) when the GTK UI is removed.
1400 os.environ['CROS_UI'] = self.options.ui
1401
Jon Salz416f9cc2013-05-10 18:32:50 +08001402 # Initialize hooks.
1403 module, cls = self.test_list.options.hooks_class.rsplit('.', 1)
1404 self.hooks = getattr(__import__(module, fromlist=[cls]), cls)()
1405 assert isinstance(self.hooks, factory.Hooks), (
1406 "hooks should be of type Hooks but is %r" % type(self.hooks))
1407 self.hooks.test_list = self.test_list
1408
Jon Salzce6a7f82013-06-10 18:22:54 +08001409 if not utils.in_chroot():
Jon Salzddf0d052013-06-18 12:52:44 +08001410 self.cpufreq_manager = CpufreqManager(event_log=self.event_log)
Jon Salzce6a7f82013-06-10 18:22:54 +08001411
Jon Salz416f9cc2013-05-10 18:32:50 +08001412 # Call startup hook.
1413 self.hooks.OnStartup()
Justin Chuang31b02432013-06-27 15:16:51 +08001414 # Startup hooks may want to skip some tests.
1415 self.update_skipped_tests()
Jon Salz416f9cc2013-05-10 18:32:50 +08001416
Jon Salze12c2b32013-06-25 16:24:34 +08001417 self.find_kcrashes()
1418
Jon Salz0697cbf2012-07-04 15:14:04 +08001419 if self.options.ui == 'chrome':
1420 self.env.launch_chrome()
1421 logging.info('Waiting for a web socket connection')
Cheng-Yi Chiangfd8ed392013-03-08 21:37:31 +08001422 self.web_socket_manager.wait()
Jon Salz0697cbf2012-07-04 15:14:04 +08001423
1424 # Wait for the test widget size to be set; this is done in
1425 # an asynchronous RPC so there is a small chance that the
1426 # web socket might be opened first.
1427 for _ in range(100): # 10 s
1428 try:
1429 if self.state_instance.get_shared_data('test_widget_size'):
1430 break
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001431 except KeyError:
Jon Salz0697cbf2012-07-04 15:14:04 +08001432 pass # Retry
1433 time.sleep(0.1) # 100 ms
1434 else:
1435 logging.warn('Never received test_widget_size from UI')
Jon Salz45297282013-05-18 14:31:47 +08001436
1437 # Send Chrome a Tab to get focus to the factory UI
1438 # (http://crosbug.com/p/19444). TODO(jsalz): remove this hack
1439 # and figure out the right way to get the focus to Chrome.
1440 if not utils.in_chroot():
1441 Spawn(
1442 [os.path.join(factory.FACTORY_PATH, 'bin', 'send_key'), 'Tab'],
1443 check_call=True, log=True)
Jon Salz0697cbf2012-07-04 15:14:04 +08001444 elif self.options.ui == 'gtk':
1445 self.start_ui()
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001446
Ricky Liang650f6bf2012-09-28 13:22:54 +08001447 # Create download path for autotest beforehand or autotests run at
1448 # the same time might fail due to race condition.
1449 if not factory.in_chroot():
1450 utils.TryMakeDirs(os.path.join('/usr/local/autotest', 'tests',
1451 'download'))
1452
Jon Salz0697cbf2012-07-04 15:14:04 +08001453 def state_change_callback(test, test_state):
1454 self.event_client.post_event(
1455 Event(Event.Type.STATE_CHANGE,
1456 path=test.path, state=test_state))
1457 self.test_list.state_change_callback = state_change_callback
Jon Salz73e0fd02012-04-04 11:46:38 +08001458
Jon Salza6711d72012-07-18 14:33:03 +08001459 for handler in self.on_ui_startup:
1460 handler()
1461
1462 self.prespawner = Prespawner()
1463 self.prespawner.start()
1464
Jon Salz0697cbf2012-07-04 15:14:04 +08001465 try:
1466 tests_after_shutdown = self.state_instance.get_shared_data(
1467 'tests_after_shutdown')
1468 except KeyError:
1469 tests_after_shutdown = None
Jon Salz57717ca2012-04-04 16:47:25 +08001470
Jon Salz5c344f62012-07-13 14:31:16 +08001471 force_auto_run = (tests_after_shutdown == FORCE_AUTO_RUN)
1472 if not force_auto_run and tests_after_shutdown is not None:
Jon Salz0697cbf2012-07-04 15:14:04 +08001473 logging.info('Resuming tests after shutdown: %s',
1474 tests_after_shutdown)
Jon Salz0697cbf2012-07-04 15:14:04 +08001475 self.tests_to_run.extend(
1476 self.test_list.lookup_path(t) for t in tests_after_shutdown)
1477 self.run_queue.put(self.run_next_test)
1478 else:
Jon Salz5c344f62012-07-13 14:31:16 +08001479 if force_auto_run or self.test_list.options.auto_run_on_start:
Jon Salz0697cbf2012-07-04 15:14:04 +08001480 self.run_queue.put(
1481 lambda: self.run_tests(self.test_list, untested_only=True))
Jon Salz5c344f62012-07-13 14:31:16 +08001482 self.state_instance.set_shared_data('tests_after_shutdown', None)
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001483
Dean Liao592e4d52013-01-10 20:06:39 +08001484 self.may_disable_cros_shortcut_keys()
1485
1486 def may_disable_cros_shortcut_keys(self):
1487 test_options = self.test_list.options
1488 if test_options.disable_cros_shortcut_keys:
1489 logging.info('Filter ChromeOS shortcut keys.')
1490 self.key_filter = KeyFilter(
1491 unmap_caps_lock=test_options.disable_caps_lock,
1492 caps_lock_keycode=test_options.caps_lock_keycode)
1493 self.key_filter.Start()
1494
Jon Salz0697cbf2012-07-04 15:14:04 +08001495 def run(self):
1496 '''Runs Goofy.'''
1497 # Process events forever.
1498 while self.run_once(True):
1499 pass
Jon Salz73e0fd02012-04-04 11:46:38 +08001500
Jon Salz0697cbf2012-07-04 15:14:04 +08001501 def run_once(self, block=False):
1502 '''Runs all items pending in the event loop.
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001503
Jon Salz0697cbf2012-07-04 15:14:04 +08001504 Args:
1505 block: If true, block until at least one event is processed.
Jon Salz7c15e8b2012-06-19 17:10:37 +08001506
Jon Salz0697cbf2012-07-04 15:14:04 +08001507 Returns:
1508 True to keep going or False to shut down.
1509 '''
1510 events = utils.DrainQueue(self.run_queue)
cychiang21886742012-07-05 15:16:32 +08001511 while not events:
Jon Salz0697cbf2012-07-04 15:14:04 +08001512 # Nothing on the run queue.
1513 self._run_queue_idle()
1514 if block:
1515 # Block for at least one event...
cychiang21886742012-07-05 15:16:32 +08001516 try:
1517 events.append(self.run_queue.get(timeout=RUN_QUEUE_TIMEOUT_SECS))
1518 except Queue.Empty:
1519 # Keep going (calling _run_queue_idle() again at the top of
1520 # the loop)
1521 continue
Jon Salz0697cbf2012-07-04 15:14:04 +08001522 # ...and grab anything else that showed up at the same
1523 # time.
1524 events.extend(utils.DrainQueue(self.run_queue))
cychiang21886742012-07-05 15:16:32 +08001525 else:
1526 break
Jon Salz51528e12012-07-02 18:54:45 +08001527
Jon Salz0697cbf2012-07-04 15:14:04 +08001528 for event in events:
1529 if not event:
1530 # Shutdown request.
1531 self.run_queue.task_done()
1532 return False
Jon Salz51528e12012-07-02 18:54:45 +08001533
Jon Salz0697cbf2012-07-04 15:14:04 +08001534 try:
1535 event()
Jon Salz85a39882012-07-05 16:45:04 +08001536 except: # pylint: disable=W0702
1537 logging.exception('Error in event loop')
Jon Salz0697cbf2012-07-04 15:14:04 +08001538 self.record_exception(traceback.format_exception_only(
1539 *sys.exc_info()[:2]))
1540 # But keep going
1541 finally:
1542 self.run_queue.task_done()
1543 return True
Jon Salz0405ab52012-03-16 15:26:52 +08001544
Jon Salz0e6532d2012-10-25 16:30:11 +08001545 def _should_sync_time(self, foreground=False):
1546 '''Returns True if we should attempt syncing time with shopfloor.
1547
1548 Args:
1549 foreground: If True, synchronizes even if background syncing
1550 is disabled (e.g., in explicit sync requests from the
1551 SyncShopfloor test).
1552 '''
1553 return ((foreground or
1554 self.test_list.options.sync_time_period_secs) and
Jon Salz54882d02012-08-31 01:57:54 +08001555 self.time_sanitizer and
1556 (not self.time_synced) and
1557 (not factory.in_chroot()))
1558
Jon Salz0e6532d2012-10-25 16:30:11 +08001559 def sync_time_with_shopfloor_server(self, foreground=False):
Jon Salz54882d02012-08-31 01:57:54 +08001560 '''Syncs time with shopfloor server, if not yet synced.
1561
Jon Salz0e6532d2012-10-25 16:30:11 +08001562 Args:
1563 foreground: If True, synchronizes even if background syncing
1564 is disabled (e.g., in explicit sync requests from the
1565 SyncShopfloor test).
1566
Jon Salz54882d02012-08-31 01:57:54 +08001567 Returns:
1568 False if no time sanitizer is available, or True if this sync (or a
1569 previous sync) succeeded.
1570
1571 Raises:
1572 Exception if unable to contact the shopfloor server.
1573 '''
Jon Salz0e6532d2012-10-25 16:30:11 +08001574 if self._should_sync_time(foreground):
Jon Salz54882d02012-08-31 01:57:54 +08001575 self.time_sanitizer.SyncWithShopfloor()
1576 self.time_synced = True
1577 return self.time_synced
1578
Jon Salzb92c5112012-09-21 15:40:11 +08001579 def log_disk_space_stats(self):
Jon Salz18e0e022013-06-11 17:13:39 +08001580 if (utils.in_chroot() or
1581 not self.test_list.options.log_disk_space_period_secs):
Jon Salzb92c5112012-09-21 15:40:11 +08001582 return
1583
1584 now = time.time()
1585 if (self.last_log_disk_space_time and
1586 now - self.last_log_disk_space_time <
1587 self.test_list.options.log_disk_space_period_secs):
1588 return
1589 self.last_log_disk_space_time = now
1590
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001591 # Upload event if stateful partition usage is above threshold.
1592 # Stateful partition is mounted on /usr/local, while
1593 # encrypted stateful partition is mounted on /var.
1594 # If there are too much logs in the factory process,
1595 # these two partitions might get full.
Jon Salzb92c5112012-09-21 15:40:11 +08001596 try:
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001597 vfs_infos = disk_space.GetAllVFSInfo()
1598 stateful_info, encrypted_info = None, None
1599 for vfs_info in vfs_infos.values():
1600 if '/usr/local' in vfs_info.mount_points:
1601 stateful_info = vfs_info
1602 if '/var' in vfs_info.mount_points:
1603 encrypted_info = vfs_info
1604
1605 stateful = disk_space.GetPartitionUsage(stateful_info)
1606 encrypted = disk_space.GetPartitionUsage(encrypted_info)
1607
1608 above_threshold = (
1609 self.test_list.options.stateful_usage_threshold and
1610 max(stateful.bytes_used_pct,
1611 stateful.inodes_used_pct,
1612 encrypted.bytes_used_pct,
1613 encrypted.inodes_used_pct) >
1614 self.test_list.options.stateful_usage_threshold)
1615
1616 if above_threshold:
1617 self.event_log.Log('stateful_partition_usage',
1618 partitions={
1619 'stateful': {
1620 'bytes_used_pct': FloatDigit(stateful.bytes_used_pct, 2),
1621 'inodes_used_pct': FloatDigit(stateful.inodes_used_pct, 2)},
1622 'encrypted_stateful': {
1623 'bytes_used_pct': FloatDigit(encrypted.bytes_used_pct, 2),
1624 'inodes_used_pct': FloatDigit(encrypted.inodes_used_pct, 2)}
1625 })
1626 self.log_watcher.ScanEventLogs()
Cheng-Yi Chiang00798e72013-06-20 18:16:39 +08001627 if (not utils.in_chroot() and
1628 self.test_list.options.stateful_usage_above_threshold_action):
1629 Spawn(self.test_list.options.stateful_usage_above_threshold_action,
1630 call=True)
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001631
1632 message = disk_space.FormatSpaceUsedAll(vfs_infos)
Jon Salz3c493bb2013-02-07 17:24:58 +08001633 if message != self.last_log_disk_space_message:
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001634 if above_threshold:
1635 logging.warning(message)
1636 else:
1637 logging.info(message)
Jon Salz3c493bb2013-02-07 17:24:58 +08001638 self.last_log_disk_space_message = message
Jon Salzb92c5112012-09-21 15:40:11 +08001639 except: # pylint: disable=W0702
1640 logging.exception('Unable to get disk space used')
1641
Justin Chuang83813982013-05-13 01:26:32 +08001642 def check_battery(self):
1643 '''Checks the current battery status.
1644
1645 Logs current battery charging level and status to log. If the battery level
1646 is lower below warning_low_battery_pct, send warning event to shopfloor.
1647 If the battery level is lower below critical_low_battery_pct, flush disks.
1648 '''
1649 if not self.test_list.options.check_battery_period_secs:
1650 return
1651
1652 now = time.time()
1653 if (self.last_check_battery_time and
1654 now - self.last_check_battery_time <
1655 self.test_list.options.check_battery_period_secs):
1656 return
1657 self.last_check_battery_time = now
1658
1659 message = ''
1660 log_level = logging.INFO
1661 try:
1662 power = system.GetBoard().power
1663 if not power.CheckBatteryPresent():
1664 message = 'Battery is not present'
1665 else:
1666 ac_present = power.CheckACPresent()
1667 charge_pct = power.GetChargePct(get_float=True)
1668 message = ('Current battery level %.1f%%, AC charger is %s' %
1669 (charge_pct, 'connected' if ac_present else 'disconnected'))
1670
1671 if charge_pct > self.test_list.options.critical_low_battery_pct:
1672 critical_low_battery = False
1673 else:
1674 critical_low_battery = True
1675 # Only sync disks when battery level is still above minimum
1676 # value. This can be used for offline analysis when shopfloor cannot
1677 # be connected.
1678 if charge_pct > MIN_BATTERY_LEVEL_FOR_DISK_SYNC:
1679 logging.warning('disk syncing for critical low battery situation')
1680 os.system('sync; sync; sync')
1681 else:
1682 logging.warning('disk syncing is cancelled '
1683 'because battery level is lower than %.1f',
1684 MIN_BATTERY_LEVEL_FOR_DISK_SYNC)
1685
1686 # Notify shopfloor server
1687 if (critical_low_battery or
1688 (not ac_present and
1689 charge_pct <= self.test_list.options.warning_low_battery_pct)):
1690 log_level = logging.WARNING
1691
1692 self.event_log.Log('low_battery',
1693 battery_level=charge_pct,
1694 charger_connected=ac_present,
1695 critical=critical_low_battery)
1696 self.log_watcher.KickWatchThread()
Cheng-Yi Chiangd3516a32013-07-17 15:30:47 +08001697 if self.system_log_manager:
1698 self.system_log_manager.KickSyncThread()
Justin Chuang83813982013-05-13 01:26:32 +08001699 except: # pylint: disable=W0702
1700 logging.exception('Unable to check battery or notify shopfloor')
1701 finally:
1702 if message != self.last_check_battery_message:
1703 logging.log(log_level, message)
1704 self.last_check_battery_message = message
1705
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001706 def check_core_dump(self):
1707 '''Checks if there is any core dumped file.
1708
1709 Removes unwanted core dump files immediately.
1710 Syncs those files matching watch list to server with a delay between
1711 each sync. After the files have been synced to server, deletes the files.
1712 '''
1713 core_dump_files = self.core_dump_manager.ScanFiles()
1714 if core_dump_files:
1715 now = time.time()
1716 if (self.last_kick_sync_time and now - self.last_kick_sync_time <
1717 self.test_list.options.kick_sync_min_interval_secs):
1718 return
1719 self.last_kick_sync_time = now
1720
1721 # Sends event to server
1722 self.event_log.Log('core_dumped', files=core_dump_files)
1723 self.log_watcher.KickWatchThread()
1724
1725 # Syncs files to server
Cheng-Yi Chiangd3516a32013-07-17 15:30:47 +08001726 if self.system_log_manager:
1727 self.system_log_manager.KickSyncThread(
1728 core_dump_files, self.core_dump_manager.ClearFiles)
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001729
Jon Salz8fa8e832012-07-13 19:04:09 +08001730 def sync_time_in_background(self):
Jon Salzb22d1172012-08-06 10:38:57 +08001731 '''Writes out current time and tries to sync with shopfloor server.'''
1732 if not self.time_sanitizer:
1733 return
1734
1735 # Write out the current time.
1736 self.time_sanitizer.SaveTime()
1737
Jon Salz54882d02012-08-31 01:57:54 +08001738 if not self._should_sync_time():
Jon Salz8fa8e832012-07-13 19:04:09 +08001739 return
1740
1741 now = time.time()
1742 if self.last_sync_time and (
1743 now - self.last_sync_time <
1744 self.test_list.options.sync_time_period_secs):
1745 # Not yet time for another check.
1746 return
1747 self.last_sync_time = now
1748
1749 def target():
1750 try:
Jon Salz54882d02012-08-31 01:57:54 +08001751 self.sync_time_with_shopfloor_server()
Jon Salz8fa8e832012-07-13 19:04:09 +08001752 except: # pylint: disable=W0702
1753 # Oh well. Log an error (but no trace)
1754 logging.info(
1755 'Unable to get time from shopfloor server: %s',
1756 utils.FormatExceptionOnly())
1757
1758 thread = threading.Thread(target=target)
1759 thread.daemon = True
1760 thread.start()
1761
Jon Salz0697cbf2012-07-04 15:14:04 +08001762 def _run_queue_idle(self):
Vic Yang4953fc12012-07-26 16:19:53 +08001763 '''Invoked when the run queue has no events.
1764
1765 This method must not raise exception.
1766 '''
Jon Salzb22d1172012-08-06 10:38:57 +08001767 now = time.time()
1768 if (self.last_idle and
1769 now < (self.last_idle + RUN_QUEUE_TIMEOUT_SECS - 1)):
1770 # Don't run more often than once every (RUN_QUEUE_TIMEOUT_SECS -
1771 # 1) seconds.
1772 return
1773
1774 self.last_idle = now
1775
Vic Yang311ddb82012-09-26 12:08:28 +08001776 self.check_exclusive()
cychiang21886742012-07-05 15:16:32 +08001777 self.check_for_updates()
Jon Salz8fa8e832012-07-13 19:04:09 +08001778 self.sync_time_in_background()
Jon Salzb92c5112012-09-21 15:40:11 +08001779 self.log_disk_space_stats()
Justin Chuang83813982013-05-13 01:26:32 +08001780 self.check_battery()
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001781 self.check_core_dump()
Jon Salz57717ca2012-04-04 16:47:25 +08001782
Jon Salzd15bbcf2013-05-21 17:33:57 +08001783 def handle_event_logs(self, chunks):
Jon Salz0697cbf2012-07-04 15:14:04 +08001784 '''Callback for event watcher.
Jon Salz258a40c2012-04-19 12:34:01 +08001785
Jon Salz0697cbf2012-07-04 15:14:04 +08001786 Attempts to upload the event logs to the shopfloor server.
Vic Yang93027612013-05-06 02:42:49 +08001787
1788 Args:
Jon Salzd15bbcf2013-05-21 17:33:57 +08001789 chunks: A list of Chunk objects.
Jon Salz0697cbf2012-07-04 15:14:04 +08001790 '''
Vic Yang93027612013-05-06 02:42:49 +08001791 first_exception = None
1792 exception_count = 0
1793
Jon Salzd15bbcf2013-05-21 17:33:57 +08001794 for chunk in chunks:
Vic Yang93027612013-05-06 02:42:49 +08001795 try:
Jon Salzcddb6402013-05-23 12:56:42 +08001796 description = 'event logs (%s)' % str(chunk)
Vic Yang93027612013-05-06 02:42:49 +08001797 start_time = time.time()
1798 shopfloor_client = shopfloor.get_instance(
1799 detect=True,
1800 timeout=self.test_list.options.shopfloor_timeout_secs)
Jon Salzd15bbcf2013-05-21 17:33:57 +08001801 shopfloor_client.UploadEvent(chunk.log_name + "." +
1802 event_log.GetReimageId(),
1803 Binary(chunk.chunk))
Vic Yang93027612013-05-06 02:42:49 +08001804 logging.info(
1805 'Successfully synced %s in %.03f s',
1806 description, time.time() - start_time)
1807 except: # pylint: disable=W0702
Jon Salzd15bbcf2013-05-21 17:33:57 +08001808 first_exception = (first_exception or (chunk.log_name + ': ' +
Vic Yang93027612013-05-06 02:42:49 +08001809 utils.FormatExceptionOnly()))
1810 exception_count += 1
1811
1812 if exception_count:
1813 if exception_count == 1:
1814 msg = 'Log upload failed: %s' % first_exception
1815 else:
1816 msg = '%d log upload failed; first is: %s' % (
1817 exception_count, first_exception)
1818 raise Exception(msg)
1819
Jon Salz57717ca2012-04-04 16:47:25 +08001820
Jon Salz0697cbf2012-07-04 15:14:04 +08001821 def run_tests_with_status(self, statuses_to_run, starting_at=None,
1822 root=None):
1823 '''Runs all top-level tests with a particular status.
Jon Salz0405ab52012-03-16 15:26:52 +08001824
Jon Salz0697cbf2012-07-04 15:14:04 +08001825 All active tests, plus any tests to re-run, are reset.
Jon Salz57717ca2012-04-04 16:47:25 +08001826
Jon Salz0697cbf2012-07-04 15:14:04 +08001827 Args:
1828 starting_at: If provided, only auto-runs tests beginning with
1829 this test.
1830 '''
1831 root = root or self.test_list
Jon Salz57717ca2012-04-04 16:47:25 +08001832
Jon Salz0697cbf2012-07-04 15:14:04 +08001833 if starting_at:
1834 # Make sure they passed a test, not a string.
1835 assert isinstance(starting_at, factory.FactoryTest)
Jon Salz0405ab52012-03-16 15:26:52 +08001836
Jon Salz0697cbf2012-07-04 15:14:04 +08001837 tests_to_reset = []
1838 tests_to_run = []
Jon Salz0405ab52012-03-16 15:26:52 +08001839
Jon Salz0697cbf2012-07-04 15:14:04 +08001840 found_starting_at = False
Jon Salz0405ab52012-03-16 15:26:52 +08001841
Jon Salz0697cbf2012-07-04 15:14:04 +08001842 for test in root.get_top_level_tests():
1843 if starting_at:
1844 if test == starting_at:
1845 # We've found starting_at; do auto-run on all
1846 # subsequent tests.
1847 found_starting_at = True
1848 if not found_starting_at:
1849 # Don't start this guy yet
1850 continue
Jon Salz0405ab52012-03-16 15:26:52 +08001851
Jon Salz0697cbf2012-07-04 15:14:04 +08001852 status = test.get_state().status
1853 if status == TestState.ACTIVE or status in statuses_to_run:
1854 # Reset the test (later; we will need to abort
1855 # all active tests first).
1856 tests_to_reset.append(test)
1857 if status in statuses_to_run:
1858 tests_to_run.append(test)
Jon Salz0405ab52012-03-16 15:26:52 +08001859
Jon Salz6dc031d2013-06-19 13:06:23 +08001860 self.abort_active_tests('Operator requested run/re-run of certain tests')
Jon Salz258a40c2012-04-19 12:34:01 +08001861
Jon Salz0697cbf2012-07-04 15:14:04 +08001862 # Reset all statuses of the tests to run (in case any tests were active;
1863 # we want them to be run again).
1864 for test_to_reset in tests_to_reset:
1865 for test in test_to_reset.walk():
1866 test.update_state(status=TestState.UNTESTED)
Jon Salz57717ca2012-04-04 16:47:25 +08001867
Jon Salz0697cbf2012-07-04 15:14:04 +08001868 self.run_tests(tests_to_run, untested_only=True)
Jon Salz0405ab52012-03-16 15:26:52 +08001869
Jon Salz0697cbf2012-07-04 15:14:04 +08001870 def restart_tests(self, root=None):
1871 '''Restarts all tests.'''
1872 root = root or self.test_list
Jon Salz0405ab52012-03-16 15:26:52 +08001873
Jon Salz6dc031d2013-06-19 13:06:23 +08001874 self.abort_active_tests('Operator requested restart of certain tests')
Jon Salz0697cbf2012-07-04 15:14:04 +08001875 for test in root.walk():
1876 test.update_state(status=TestState.UNTESTED)
1877 self.run_tests(root)
Hung-Te Lin96632362012-03-20 21:14:18 +08001878
Jon Salz0697cbf2012-07-04 15:14:04 +08001879 def auto_run(self, starting_at=None, root=None):
1880 '''"Auto-runs" tests that have not been run yet.
Hung-Te Lin96632362012-03-20 21:14:18 +08001881
Jon Salz0697cbf2012-07-04 15:14:04 +08001882 Args:
1883 starting_at: If provide, only auto-runs tests beginning with
1884 this test.
1885 '''
1886 root = root or self.test_list
1887 self.run_tests_with_status([TestState.UNTESTED, TestState.ACTIVE],
1888 starting_at=starting_at,
1889 root=root)
Jon Salz968e90b2012-03-18 16:12:43 +08001890
Jon Salz0697cbf2012-07-04 15:14:04 +08001891 def re_run_failed(self, root=None):
1892 '''Re-runs failed tests.'''
1893 root = root or self.test_list
1894 self.run_tests_with_status([TestState.FAILED], root=root)
Jon Salz57717ca2012-04-04 16:47:25 +08001895
Jon Salz0697cbf2012-07-04 15:14:04 +08001896 def show_review_information(self):
1897 '''Event handler for showing review information screen.
Jon Salz57717ca2012-04-04 16:47:25 +08001898
Jon Salz0697cbf2012-07-04 15:14:04 +08001899 The information screene is rendered by main UI program (ui.py), so in
1900 goofy we only need to kill all active tests, set them as untested, and
1901 clear remaining tests.
1902 '''
1903 self.kill_active_tests(False)
Jon Salza6711d72012-07-18 14:33:03 +08001904 self.cancel_pending_tests()
Jon Salz57717ca2012-04-04 16:47:25 +08001905
Jon Salz0697cbf2012-07-04 15:14:04 +08001906 def handle_switch_test(self, event):
1907 '''Switches to a particular test.
Jon Salz0405ab52012-03-16 15:26:52 +08001908
Jon Salz0697cbf2012-07-04 15:14:04 +08001909 @param event: The SWITCH_TEST event.
1910 '''
1911 test = self.test_list.lookup_path(event.path)
1912 if not test:
1913 logging.error('Unknown test %r', event.key)
1914 return
Jon Salz73e0fd02012-04-04 11:46:38 +08001915
Jon Salz0697cbf2012-07-04 15:14:04 +08001916 invoc = self.invocations.get(test)
1917 if invoc and test.backgroundable:
1918 # Already running: just bring to the front if it
1919 # has a UI.
1920 logging.info('Setting visible test to %s', test.path)
Jon Salz36fbbb52012-07-05 13:45:06 +08001921 self.set_visible_test(test)
Jon Salz0697cbf2012-07-04 15:14:04 +08001922 return
Jon Salz73e0fd02012-04-04 11:46:38 +08001923
Jon Salz6dc031d2013-06-19 13:06:23 +08001924 self.abort_active_tests('Operator requested abort (switch_test)')
Jon Salz0697cbf2012-07-04 15:14:04 +08001925 for t in test.walk():
1926 t.update_state(status=TestState.UNTESTED)
Jon Salz73e0fd02012-04-04 11:46:38 +08001927
Jon Salz0697cbf2012-07-04 15:14:04 +08001928 if self.test_list.options.auto_run_on_keypress:
1929 self.auto_run(starting_at=test)
1930 else:
1931 self.run_tests(test)
Jon Salz73e0fd02012-04-04 11:46:38 +08001932
Jon Salz0697cbf2012-07-04 15:14:04 +08001933 def wait(self):
1934 '''Waits for all pending invocations.
1935
1936 Useful for testing.
1937 '''
Jon Salz1acc8742012-07-17 17:45:55 +08001938 while self.invocations:
1939 for k, v in self.invocations.iteritems():
1940 logging.info('Waiting for %s to complete...', k)
1941 v.thread.join()
1942 self.reap_completed_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +08001943
1944 def check_exceptions(self):
1945 '''Raises an error if any exceptions have occurred in
1946 invocation threads.'''
1947 if self.exceptions:
1948 raise RuntimeError('Exception in invocation thread: %r' %
1949 self.exceptions)
1950
1951 def record_exception(self, msg):
1952 '''Records an exception in an invocation thread.
1953
1954 An exception with the given message will be rethrown when
1955 Goofy is destroyed.'''
1956 self.exceptions.append(msg)
Jon Salz73e0fd02012-04-04 11:46:38 +08001957
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001958
1959if __name__ == '__main__':
Jon Salz77c151e2012-08-28 07:20:37 +08001960 goofy = Goofy()
1961 try:
1962 goofy.main()
Jon Salz0f996602012-10-03 15:26:48 +08001963 except SystemExit:
1964 # Propagate SystemExit without logging.
1965 raise
Jon Salz31373eb2012-09-21 16:19:49 +08001966 except:
Jon Salz0f996602012-10-03 15:26:48 +08001967 # Log the error before trying to shut down (unless it's a graceful
1968 # exit).
Jon Salz31373eb2012-09-21 16:19:49 +08001969 logging.exception('Error in main loop')
1970 raise
Jon Salz77c151e2012-08-28 07:20:37 +08001971 finally:
1972 goofy.destroy()