blob: 853a53f7adee01cd1a8c6047195f5a7c3e72ac30 [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
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08008"""The main factory flow that runs the factory test and finalizes a device."""
Hung-Te Linf2f78f72012-02-08 19:27:11 +08009
Joel Kitchingb85ed7f2014-10-08 18:24:39 +080010from __future__ import print_function
11
Jon Salze12c2b32013-06-25 16:24:34 +080012import glob
Jon Salz0405ab52012-03-16 15:26:52 +080013import logging
14import os
Jon Salze12c2b32013-06-25 16:24:34 +080015import shutil
Jon Salz77c151e2012-08-28 07:20:37 +080016import signal
Jon Salz0405ab52012-03-16 15:26:52 +080017import sys
Jon Salzeff94182013-06-19 15:06:28 +080018import syslog
Jon Salz0405ab52012-03-16 15:26:52 +080019import threading
20import time
21import traceback
Jon Salz258a40c2012-04-19 12:34:01 +080022import uuid
Jon Salzb10cf512012-08-09 17:29:21 +080023from xmlrpclib import Binary
Hung-Te Linf2f78f72012-02-08 19:27:11 +080024from collections import deque
25from optparse import OptionParser
Hung-Te Linf2f78f72012-02-08 19:27:11 +080026
Jon Salz0697cbf2012-07-04 15:14:04 +080027import factory_common # pylint: disable=W0611
Hung-Te Lin91492a12014-11-25 18:56:30 +080028from cros.factory.test import event_log
jcliangcd688182012-08-20 21:01:26 +080029from cros.factory import system
Hung-Te Lin91492a12014-11-25 18:56:30 +080030from cros.factory.test.event_log import EventLog, FloatDigit
Hung-Te Lincc41d2a2014-10-29 13:35:20 +080031from cros.factory.goofy import connection_manager
Vic Yangd80ea752014-09-24 16:07:14 +080032from cros.factory.goofy import test_environment
33from cros.factory.goofy import time_sanitizer
34from cros.factory.goofy import updater
35from cros.factory.goofy.goofy_base import GoofyBase
36from cros.factory.goofy.goofy_rpc import GoofyRPC
37from cros.factory.goofy.invocation import TestArgEnv
38from cros.factory.goofy.invocation import TestInvocation
39from cros.factory.goofy.link_manager import PresenterLinkManager
Vic Yange2c76a82014-10-30 12:48:19 -070040from cros.factory.goofy import prespawner
Vic Yangd80ea752014-09-24 16:07:14 +080041from cros.factory.goofy.system_log_manager import SystemLogManager
Wei-Ning Huang38b75f02015-02-25 18:25:14 +080042from cros.factory.goofy.terminal_manager import TerminalManager
Vic Yangd80ea752014-09-24 16:07:14 +080043from cros.factory.goofy.web_socket_manager import WebSocketManager
Cheng-Yi Chiangd8186952013-04-04 23:41:14 +080044from cros.factory.system.board import Board, BoardException
jcliangcd688182012-08-20 21:01:26 +080045from cros.factory.system.charge_manager import ChargeManager
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +080046from cros.factory.system.core_dump_manager import CoreDumpManager
Jon Salzce6a7f82013-06-10 18:22:54 +080047from cros.factory.system.cpufreq_manager import CpufreqManager
Jon Salzb92c5112012-09-21 15:40:11 +080048from cros.factory.system import disk_space
jcliangcd688182012-08-20 21:01:26 +080049from cros.factory.test import factory
Jon Salz670ce062014-05-16 15:53:50 +080050from cros.factory.test import phase
jcliangcd688182012-08-20 21:01:26 +080051from cros.factory.test import state
Jon Salz51528e12012-07-02 18:54:45 +080052from cros.factory.test import shopfloor
Jon Salz83591782012-06-26 11:09:58 +080053from cros.factory.test import utils
Jon Salz128b0932013-07-03 16:55:26 +080054from cros.factory.test.test_lists import test_lists
Ricky Liang6fe218c2013-12-27 15:17:17 +080055from cros.factory.test.e2e_test.common import (
56 AutomationMode, AutomationModePrompt, ParseAutomationMode)
Jon Salz83591782012-06-26 11:09:58 +080057from cros.factory.test.event import Event
58from cros.factory.test.event import EventClient
59from cros.factory.test.event import EventServer
Hung-Te Lin91492a12014-11-25 18:56:30 +080060from cros.factory.test.event_log_watcher import EventLogWatcher
jcliangcd688182012-08-20 21:01:26 +080061from cros.factory.test.factory import TestState
Jon Salzd7550792013-07-12 05:49:27 +080062from cros.factory.test.utils import Enum
Dean Liao592e4d52013-01-10 20:06:39 +080063from cros.factory.tools.key_filter import KeyFilter
Jon Salz2af235d2013-06-24 14:47:21 +080064from cros.factory.utils import file_utils
Joel Kitchingb85ed7f2014-10-08 18:24:39 +080065from cros.factory.utils import net_utils
Jon Salz78c32392012-07-25 14:18:29 +080066from cros.factory.utils.process_utils import Spawn
Hung-Te Linf2f78f72012-02-08 19:27:11 +080067
68
Hung-Te Linf2f78f72012-02-08 19:27:11 +080069HWID_CFG_PATH = '/usr/local/share/chromeos-hwid/cfg'
Ricky Liang45c73e72015-01-15 15:00:30 +080070CACHES_DIR = os.path.join(factory.get_state_root(), 'caches')
Hung-Te Linf2f78f72012-02-08 19:27:11 +080071
Cheng-Yi Chiang39d32ad2013-07-23 15:02:38 +080072CLEANUP_LOGS_PAUSED = '/var/lib/cleanup_logs_paused'
73
Jon Salz5c344f62012-07-13 14:31:16 +080074# Value for tests_after_shutdown that forces auto-run (e.g., after
75# a factory update, when the available set of tests might change).
76FORCE_AUTO_RUN = 'force_auto_run'
77
Justin Chuang83813982013-05-13 01:26:32 +080078# Sync disks when battery level is higher than this value.
79# Otherwise, power loss during disk sync operation may incur even worse outcome.
80MIN_BATTERY_LEVEL_FOR_DISK_SYNC = 1.0
81
Ricky Liang45c73e72015-01-15 15:00:30 +080082MAX_CRASH_FILE_SIZE = 64 * 1024
Jon Salze12c2b32013-06-25 16:24:34 +080083
Jon Salzd7550792013-07-12 05:49:27 +080084Status = Enum(['UNINITIALIZED', 'INITIALIZING', 'RUNNING',
85 'TERMINATING', 'TERMINATED'])
86
Ricky Liang45c73e72015-01-15 15:00:30 +080087
Hung-Te Linf2f78f72012-02-08 19:27:11 +080088def get_hwid_cfg():
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +080089 """Returns the HWID config tag, or an empty string if none can be found."""
Jon Salz0697cbf2012-07-04 15:14:04 +080090 if 'CROS_HWID' in os.environ:
91 return os.environ['CROS_HWID']
92 if os.path.exists(HWID_CFG_PATH):
Ricky Liang45c73e72015-01-15 15:00:30 +080093 with open(HWID_CFG_PATH, 'r') as hwid_cfg_handle:
Jon Salz0697cbf2012-07-04 15:14:04 +080094 return hwid_cfg_handle.read().strip()
95 return ''
Hung-Te Linf2f78f72012-02-08 19:27:11 +080096
97
Jon Salz73e0fd02012-04-04 11:46:38 +080098_inited_logging = False
Hung-Te Linf2f78f72012-02-08 19:27:11 +080099
Ricky Liang45c73e72015-01-15 15:00:30 +0800100
Peter Ammon1e1ec572014-06-26 17:56:32 -0700101class Goofy(GoofyBase):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800102 """The main factory flow.
Jon Salz0697cbf2012-07-04 15:14:04 +0800103
104 Note that all methods in this class must be invoked from the main
105 (event) thread. Other threads, such as callbacks and TestInvocation
106 methods, should instead post events on the run queue.
107
108 TODO: Unit tests. (chrome-os-partner:7409)
109
110 Properties:
111 uuid: A unique UUID for this invocation of Goofy.
112 state_instance: An instance of FactoryState.
113 state_server: The FactoryState XML/RPC server.
114 state_server_thread: A thread running state_server.
115 event_server: The EventServer socket server.
116 event_server_thread: A thread running event_server.
117 event_client: A client to the event server.
118 connection_manager: The connection_manager object.
Cheng-Yi Chiang835f2682013-05-06 22:15:48 +0800119 system_log_manager: The SystemLogManager object.
120 core_dump_manager: The CoreDumpManager object.
Jon Salz0697cbf2012-07-04 15:14:04 +0800121 ui_process: The factory ui process object.
Jon Salz0697cbf2012-07-04 15:14:04 +0800122 invocations: A map from FactoryTest objects to the corresponding
123 TestInvocations objects representing active tests.
124 tests_to_run: A deque of tests that should be run when the current
125 test(s) complete.
126 options: Command-line options.
127 args: Command-line args.
128 test_list: The test list.
Jon Salz128b0932013-07-03 16:55:26 +0800129 test_lists: All new-style test lists.
Ricky Liang4bff3e32014-02-20 18:46:11 +0800130 run_id: The identifier for latest test run.
131 scheduled_run_tests: The list of tests scheduled for latest test run.
Jon Salz0697cbf2012-07-04 15:14:04 +0800132 event_handlers: Map of Event.Type to the method used to handle that
133 event. If the method has an 'event' argument, the event is passed
134 to the handler.
Jon Salz3c493bb2013-02-07 17:24:58 +0800135 last_log_disk_space_message: The last message we logged about disk space
136 (to avoid duplication).
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +0800137 last_kick_sync_time: The last time to kick system_log_manager to sync
138 because of core dump files (to avoid kicking too soon then abort the
139 sync.)
Jon Salz416f9cc2013-05-10 18:32:50 +0800140 hooks: A Hooks object containing hooks for various Goofy actions.
Jon Salzd7550792013-07-12 05:49:27 +0800141 status: The current Goofy status (a member of the Status enum).
Peter Ammon948b7172014-07-15 12:43:06 -0700142 link_manager: Instance of PresenterLinkManager for communicating
143 with GoofyPresenter
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800144 """
Ricky Liang45c73e72015-01-15 15:00:30 +0800145
Jon Salz0697cbf2012-07-04 15:14:04 +0800146 def __init__(self):
Peter Ammon1e1ec572014-06-26 17:56:32 -0700147 super(Goofy, self).__init__()
Jon Salz0697cbf2012-07-04 15:14:04 +0800148 self.uuid = str(uuid.uuid4())
149 self.state_instance = None
150 self.state_server = None
151 self.state_server_thread = None
Jon Salz16d10542012-07-23 12:18:45 +0800152 self.goofy_rpc = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800153 self.event_server = None
154 self.event_server_thread = None
155 self.event_client = None
156 self.connection_manager = None
Vic Yang4953fc12012-07-26 16:19:53 +0800157 self.charge_manager = None
Dean Liao88b93192014-10-23 19:37:41 +0800158 self._can_charge = True
Jon Salz8fa8e832012-07-13 19:04:09 +0800159 self.time_sanitizer = None
160 self.time_synced = False
Jon Salz0697cbf2012-07-04 15:14:04 +0800161 self.log_watcher = None
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +0800162 self.system_log_manager = None
Cheng-Yi Chiang835f2682013-05-06 22:15:48 +0800163 self.core_dump_manager = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800164 self.event_log = None
Vic Yange2c76a82014-10-30 12:48:19 -0700165 self.autotest_prespawner = None
166 self.pytest_prespawner = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800167 self.ui_process = None
Vic Yanga3cecf82014-12-26 00:44:21 -0800168 self._ui_initialized = False
Jon Salzc79a9982012-08-30 04:42:01 +0800169 self.dummy_shopfloor = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800170 self.invocations = {}
171 self.tests_to_run = deque()
172 self.visible_test = None
173 self.chrome = None
Jon Salz416f9cc2013-05-10 18:32:50 +0800174 self.hooks = None
Vic Yangd8990da2013-06-27 16:57:43 +0800175 self.cpu_usage_watcher = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800176
177 self.options = None
178 self.args = None
179 self.test_list = None
Jon Salz128b0932013-07-03 16:55:26 +0800180 self.test_lists = None
Ricky Liang4bff3e32014-02-20 18:46:11 +0800181 self.run_id = None
182 self.scheduled_run_tests = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800183 self.env = None
Jon Salzb22d1172012-08-06 10:38:57 +0800184 self.last_idle = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800185 self.last_shutdown_time = None
cychiang21886742012-07-05 15:16:32 +0800186 self.last_update_check = None
Cheng-Yi Chiang194d3c02015-03-16 14:37:15 +0800187 self._suppress_periodic_update_messages = False
Cheng-Yi Chiangf5b21012015-03-17 15:37:14 +0800188 self._suppress_event_log_error_messages = False
Jon Salz8fa8e832012-07-13 19:04:09 +0800189 self.last_sync_time = None
Jon Salzb92c5112012-09-21 15:40:11 +0800190 self.last_log_disk_space_time = None
Jon Salz3c493bb2013-02-07 17:24:58 +0800191 self.last_log_disk_space_message = None
Justin Chuang83813982013-05-13 01:26:32 +0800192 self.last_check_battery_time = None
193 self.last_check_battery_message = None
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +0800194 self.last_kick_sync_time = None
Vic Yang311ddb82012-09-26 12:08:28 +0800195 self.exclusive_items = set()
Jon Salz0f996602012-10-03 15:26:48 +0800196 self.event_log = None
Dean Liao592e4d52013-01-10 20:06:39 +0800197 self.key_filter = None
Jon Salzce6a7f82013-06-10 18:22:54 +0800198 self.cpufreq_manager = None
Jon Salzd7550792013-07-12 05:49:27 +0800199 self.status = Status.UNINITIALIZED
Ricky Liang36512a32014-07-25 11:47:04 +0800200 self.ready_for_ui_connection = False
Peter Ammon1e1ec572014-06-26 17:56:32 -0700201 self.link_manager = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800202
Jon Salz85a39882012-07-05 16:45:04 +0800203 def test_or_root(event, parent_or_group=True):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800204 """Returns the test affected by a particular event.
Jon Salz85a39882012-07-05 16:45:04 +0800205
206 Args:
207 event: The event containing an optional 'path' attribute.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800208 parent_or_group: If True, returns the top-level parent for a test (the
Jon Salz85a39882012-07-05 16:45:04 +0800209 root node of the tests that need to be run together if the given test
210 path is to be run).
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800211 """
Jon Salz0697cbf2012-07-04 15:14:04 +0800212 try:
213 path = event.path
214 except AttributeError:
215 path = None
216
217 if path:
Jon Salz85a39882012-07-05 16:45:04 +0800218 test = self.test_list.lookup_path(path)
219 if parent_or_group:
220 test = test.get_top_level_parent_or_group()
221 return test
Jon Salz0697cbf2012-07-04 15:14:04 +0800222 else:
223 return self.test_list
224
225 self.event_handlers = {
Ricky Liang45c73e72015-01-15 15:00:30 +0800226 Event.Type.SWITCH_TEST: self.handle_switch_test,
227 Event.Type.SHOW_NEXT_ACTIVE_TEST:
228 lambda event: self.show_next_active_test(),
229 Event.Type.RESTART_TESTS:
230 lambda event: self.restart_tests(root=test_or_root(event)),
231 Event.Type.AUTO_RUN:
232 lambda event: self.auto_run(root=test_or_root(event)),
233 Event.Type.RE_RUN_FAILED:
234 lambda event: self.re_run_failed(root=test_or_root(event)),
235 Event.Type.RUN_TESTS_WITH_STATUS:
236 lambda event: self.run_tests_with_status(
237 event.status,
238 root=test_or_root(event)),
239 Event.Type.REVIEW:
240 lambda event: self.show_review_information(),
241 Event.Type.UPDATE_SYSTEM_INFO:
242 lambda event: self.update_system_info(),
243 Event.Type.STOP:
244 lambda event: self.stop(root=test_or_root(event, False),
245 fail=getattr(event, 'fail', False),
246 reason=getattr(event, 'reason', None)),
247 Event.Type.SET_VISIBLE_TEST:
248 lambda event: self.set_visible_test(
249 self.test_list.lookup_path(event.path)),
250 Event.Type.CLEAR_STATE:
251 lambda event: self.clear_state(
252 self.test_list.lookup_path(event.path)),
Wei-Ning Huang38b75f02015-02-25 18:25:14 +0800253 Event.Type.KEY_FILTER_MODE: self.handle_key_filter_mode,
Jon Salz0697cbf2012-07-04 15:14:04 +0800254 }
255
Jon Salz0697cbf2012-07-04 15:14:04 +0800256 self.web_socket_manager = None
Wei-Ning Huang38b75f02015-02-25 18:25:14 +0800257 self.terminal_manager = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800258
259 def destroy(self):
Ricky Liang74237a02014-09-18 15:11:23 +0800260 """Performs any shutdown tasks. Overrides base class method."""
Jon Salzd7550792013-07-12 05:49:27 +0800261 self.status = Status.TERMINATING
Jon Salz0697cbf2012-07-04 15:14:04 +0800262 if self.chrome:
263 self.chrome.kill()
264 self.chrome = None
Jon Salzc79a9982012-08-30 04:42:01 +0800265 if self.dummy_shopfloor:
266 self.dummy_shopfloor.kill()
267 self.dummy_shopfloor = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800268 if self.ui_process:
269 utils.kill_process_tree(self.ui_process, 'ui')
270 self.ui_process = None
271 if self.web_socket_manager:
272 logging.info('Stopping web sockets')
273 self.web_socket_manager.close()
274 self.web_socket_manager = None
275 if self.state_server_thread:
276 logging.info('Stopping state server')
277 self.state_server.shutdown()
278 self.state_server_thread.join()
279 self.state_server.server_close()
280 self.state_server_thread = None
281 if self.state_instance:
282 self.state_instance.close()
283 if self.event_server_thread:
284 logging.info('Stopping event server')
285 self.event_server.shutdown() # pylint: disable=E1101
286 self.event_server_thread.join()
287 self.event_server.server_close()
288 self.event_server_thread = None
289 if self.log_watcher:
290 if self.log_watcher.IsThreadStarted():
291 self.log_watcher.StopWatchThread()
292 self.log_watcher = None
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +0800293 if self.system_log_manager:
294 if self.system_log_manager.IsThreadRunning():
Cheng-Yi Chianga0f6eff2014-01-09 18:27:22 +0800295 self.system_log_manager.Stop()
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +0800296 self.system_log_manager = None
Vic Yange2c76a82014-10-30 12:48:19 -0700297 if self.autotest_prespawner:
298 logging.info('Stopping autotest prespawner')
299 self.autotest_prespawner.stop()
300 self.autotest_prespawner = None
301 if self.pytest_prespawner:
302 logging.info('Stopping pytest prespawner')
303 self.pytest_prespawner.stop()
304 self.pytest_prespawner = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800305 if self.event_client:
306 logging.info('Closing event client')
307 self.event_client.close()
308 self.event_client = None
Jon Salzddf0d052013-06-18 12:52:44 +0800309 if self.cpufreq_manager:
310 self.cpufreq_manager.Stop()
Jon Salz0697cbf2012-07-04 15:14:04 +0800311 if self.event_log:
312 self.event_log.Close()
313 self.event_log = None
Dean Liao592e4d52013-01-10 20:06:39 +0800314 if self.key_filter:
315 self.key_filter.Stop()
Vic Yangd8990da2013-06-27 16:57:43 +0800316 if self.cpu_usage_watcher:
317 self.cpu_usage_watcher.terminate()
Peter Ammon1e1ec572014-06-26 17:56:32 -0700318 if self.link_manager:
319 self.link_manager.Stop()
320 self.link_manager = None
Dean Liao592e4d52013-01-10 20:06:39 +0800321
Peter Ammon1e1ec572014-06-26 17:56:32 -0700322 super(Goofy, self).destroy()
Jon Salz0697cbf2012-07-04 15:14:04 +0800323 logging.info('Done destroying Goofy')
Jon Salzd7550792013-07-12 05:49:27 +0800324 self.status = Status.TERMINATED
Jon Salz0697cbf2012-07-04 15:14:04 +0800325
326 def start_state_server(self):
Jon Salz2af235d2013-06-24 14:47:21 +0800327 # Before starting state server, remount stateful partitions with
328 # no commit flag. The default commit time (commit=600) makes corruption
329 # too likely.
Hung-Te Lind59dbfa2014-08-27 12:27:53 +0800330 utils.ResetCommitTime()
Jon Salz2af235d2013-06-24 14:47:21 +0800331
Jon Salz0697cbf2012-07-04 15:14:04 +0800332 self.state_instance, self.state_server = (
Ricky Liang45c73e72015-01-15 15:00:30 +0800333 state.create_server(bind_address='0.0.0.0'))
Jon Salz16d10542012-07-23 12:18:45 +0800334 self.goofy_rpc = GoofyRPC(self)
335 self.goofy_rpc.RegisterMethods(self.state_instance)
Jon Salz0697cbf2012-07-04 15:14:04 +0800336 logging.info('Starting state server')
337 self.state_server_thread = threading.Thread(
Ricky Liang45c73e72015-01-15 15:00:30 +0800338 target=self.state_server.serve_forever,
339 name='StateServer')
Jon Salz0697cbf2012-07-04 15:14:04 +0800340 self.state_server_thread.start()
341
342 def start_event_server(self):
343 self.event_server = EventServer()
344 logging.info('Starting factory event server')
345 self.event_server_thread = threading.Thread(
Ricky Liang45c73e72015-01-15 15:00:30 +0800346 target=self.event_server.serve_forever,
347 name='EventServer') # pylint: disable=E1101
Jon Salz0697cbf2012-07-04 15:14:04 +0800348 self.event_server_thread.start()
349
350 self.event_client = EventClient(
Ricky Liang45c73e72015-01-15 15:00:30 +0800351 callback=self.handle_event, event_loop=self.run_queue)
Jon Salz0697cbf2012-07-04 15:14:04 +0800352
353 self.web_socket_manager = WebSocketManager(self.uuid)
Ricky Liang45c73e72015-01-15 15:00:30 +0800354 self.state_server.add_handler('/event',
355 self.web_socket_manager.handle_web_socket)
Jon Salz0697cbf2012-07-04 15:14:04 +0800356
Wei-Ning Huang38b75f02015-02-25 18:25:14 +0800357 def start_terminal_server(self):
358 self.terminal_manager = TerminalManager()
359 self.state_server.add_handler('/pty',
360 self.terminal_manager.handle_web_socket)
361
Jon Salz0697cbf2012-07-04 15:14:04 +0800362 def start_ui(self):
363 ui_proc_args = [
Ricky Liang45c73e72015-01-15 15:00:30 +0800364 os.path.join(factory.FACTORY_PACKAGE_PATH, 'test', 'ui.py'),
365 self.options.test_list
366 ]
Jon Salz0697cbf2012-07-04 15:14:04 +0800367 if self.options.verbose:
368 ui_proc_args.append('-v')
369 logging.info('Starting ui %s', ui_proc_args)
Jon Salz78c32392012-07-25 14:18:29 +0800370 self.ui_process = Spawn(ui_proc_args)
Jon Salz0697cbf2012-07-04 15:14:04 +0800371 logging.info('Waiting for UI to come up...')
372 self.event_client.wait(
Ricky Liang45c73e72015-01-15 15:00:30 +0800373 lambda event: event.type == Event.Type.UI_READY)
Jon Salz0697cbf2012-07-04 15:14:04 +0800374 logging.info('UI has started')
375
376 def set_visible_test(self, test):
377 if self.visible_test == test:
378 return
Jon Salz2f2d42c2012-07-30 12:30:34 +0800379 if test and not test.has_ui:
380 return
Jon Salz0697cbf2012-07-04 15:14:04 +0800381
382 if test:
383 test.update_state(visible=True)
384 if self.visible_test:
385 self.visible_test.update_state(visible=False)
386 self.visible_test = test
387
Ricky Liang48e47f92014-02-26 19:31:51 +0800388 def log_startup_messages(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800389 """Logs the tail of var/log/messages and mosys and EC console logs."""
Jon Salzd4306c82012-11-30 15:16:36 +0800390 # TODO(jsalz): This is mostly a copy-and-paste of code in init_states,
391 # for factory-3004.B only. Consolidate and merge back to ToT.
392 if utils.in_chroot():
393 return
394
395 try:
Ricky Liang45c73e72015-01-15 15:00:30 +0800396 var_log_messages = utils.var_log_messages_before_reboot()
Jon Salzd4306c82012-11-30 15:16:36 +0800397 logging.info(
Ricky Liang45c73e72015-01-15 15:00:30 +0800398 'Tail of /var/log/messages before last reboot:\n'
399 '%s', ('\n'.join(
400 ' ' + x for x in var_log_messages)))
Jon Salzd4306c82012-11-30 15:16:36 +0800401 except: # pylint: disable=W0702
402 logging.exception('Unable to grok /var/log/messages')
403
404 try:
Ricky Liang117484a2014-04-14 11:14:41 +0800405 mosys_log = Spawn(
Jon Salzd4306c82012-11-30 15:16:36 +0800406 ['mosys', 'eventlog', 'list'],
407 read_stdout=True, log_stderr_on_error=True).stdout_data
408 logging.info('System eventlog from mosys:\n%s\n', mosys_log)
409 except: # pylint: disable=W0702
410 logging.exception('Unable to read mosys eventlog')
411
Dean Liao88b93192014-10-23 19:37:41 +0800412 self.log_ec_console()
413 self.log_ec_panic_info()
414
415 @staticmethod
416 def log_ec_console():
417 """Logs EC console log into logging.info.
418
419 It logs an error message in logging.exception if an exception is raised
420 when getting EC console log.
421 For unsupported device, it logs unsupport message in logging.info
422
423 Returns:
424 EC console log string.
425 """
Jon Salzd4306c82012-11-30 15:16:36 +0800426 try:
Vic Yang8341dde2013-01-29 16:48:52 +0800427 board = system.GetBoard()
428 ec_console_log = board.GetECConsoleLog()
Jon Salzd4306c82012-11-30 15:16:36 +0800429 logging.info('EC console log after reboot:\n%s\n', ec_console_log)
Dean Liao88b93192014-10-23 19:37:41 +0800430 return ec_console_log
431 except NotImplementedError:
432 logging.info('EC console log not supported')
Jon Salzd4306c82012-11-30 15:16:36 +0800433 except: # pylint: disable=W0702
434 logging.exception('Error retrieving EC console log')
435
Dean Liao88b93192014-10-23 19:37:41 +0800436 @staticmethod
437 def log_ec_panic_info():
438 """Logs EC panic info into logging.info.
439
440 It logs an error message in logging.exception if an exception is raised
441 when getting EC panic info.
442 For unsupported device, it logs unsupport message in logging.info
443
444 Returns:
445 EC panic info string.
446 """
Vic Yang079f9872013-07-01 11:32:00 +0800447 try:
448 board = system.GetBoard()
449 ec_panic_info = board.GetECPanicInfo()
450 logging.info('EC panic info after reboot:\n%s\n', ec_panic_info)
Dean Liao88b93192014-10-23 19:37:41 +0800451 return ec_panic_info
452 except NotImplementedError:
453 logging.info('EC panic info is not supported')
Vic Yang079f9872013-07-01 11:32:00 +0800454 except: # pylint: disable=W0702
455 logging.exception('Error retrieving EC panic info')
456
Ricky Liang48e47f92014-02-26 19:31:51 +0800457 def shutdown(self, operation):
458 """Starts shutdown procedure.
459
460 Args:
Vic (Chun-Ju) Yang05b0d952014-04-28 17:39:09 +0800461 operation: The shutdown operation (reboot, full_reboot, or halt).
Ricky Liang48e47f92014-02-26 19:31:51 +0800462 """
463 active_tests = []
464 for test in self.test_list.walk():
465 if not test.is_leaf():
466 continue
467
468 test_state = test.get_state()
469 if test_state.status == TestState.ACTIVE:
470 active_tests.append(test)
471
Ricky Liang48e47f92014-02-26 19:31:51 +0800472 if not (len(active_tests) == 1 and
473 isinstance(active_tests[0], factory.ShutdownStep)):
474 logging.error(
475 'Calling Goofy shutdown outside of the shutdown factory test')
476 return
477
478 logging.info('Start Goofy shutdown (%s)', operation)
479 # Save pending test list in the state server
480 self.state_instance.set_shared_data(
481 'tests_after_shutdown',
482 [t.path for t in self.tests_to_run])
483 # Save shutdown time
484 self.state_instance.set_shared_data('shutdown_time', time.time())
485
486 with self.env.lock:
487 self.event_log.Log('shutdown', operation=operation)
488 shutdown_result = self.env.shutdown(operation)
489 if shutdown_result:
490 # That's all, folks!
Peter Ammon1e1ec572014-06-26 17:56:32 -0700491 self.run_enqueue(None)
Ricky Liang48e47f92014-02-26 19:31:51 +0800492 else:
493 # Just pass (e.g., in the chroot).
494 self.state_instance.set_shared_data('tests_after_shutdown', None)
495 # Send event with no fields to indicate that there is no
496 # longer a pending shutdown.
497 self.event_client.post_event(Event(Event.Type.PENDING_SHUTDOWN))
498
499 def handle_shutdown_complete(self, test):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800500 """Handles the case where a shutdown was detected during a shutdown step.
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800501
Ricky Liang6fe218c2013-12-27 15:17:17 +0800502 Args:
503 test: The ShutdownStep.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800504 """
Jon Salz0697cbf2012-07-04 15:14:04 +0800505 test_state = test.update_state(increment_shutdown_count=1)
506 logging.info('Detected shutdown (%d of %d)',
Ricky Liang48e47f92014-02-26 19:31:51 +0800507 test_state.shutdown_count, test.iterations)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800508
Ricky Liang48e47f92014-02-26 19:31:51 +0800509 # Insert current shutdown test at the front of the list of tests to run
510 # after shutdown. This is to continue on post-shutdown verification in the
511 # shutdown step.
512 tests_after_shutdown = self.state_instance.get_shared_data(
513 'tests_after_shutdown', optional=True)
514 if not tests_after_shutdown:
515 self.state_instance.set_shared_data('tests_after_shutdown', [test.path])
516 elif isinstance(tests_after_shutdown, list):
517 self.state_instance.set_shared_data(
518 'tests_after_shutdown', [test.path] + tests_after_shutdown)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800519
Ricky Liang48e47f92014-02-26 19:31:51 +0800520 # Set 'post_shutdown' to inform shutdown test that a shutdown just occurred.
Ricky Liangb7eb8772014-09-15 18:05:22 +0800521 self.state_instance.set_shared_data(
522 state.POST_SHUTDOWN_TAG % test.path,
523 self.state_instance.get_test_state(test.path).invocation)
Jon Salz258a40c2012-04-19 12:34:01 +0800524
Jon Salz0697cbf2012-07-04 15:14:04 +0800525 def init_states(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800526 """Initializes all states on startup."""
Jon Salz0697cbf2012-07-04 15:14:04 +0800527 for test in self.test_list.get_all_tests():
528 # Make sure the state server knows about all the tests,
529 # defaulting to an untested state.
530 test.update_state(update_parent=False, visible=False)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800531
Jon Salz0697cbf2012-07-04 15:14:04 +0800532 var_log_messages = None
Vic Yanga9c32212012-08-16 20:07:54 +0800533 mosys_log = None
Vic Yange4c275d2012-08-28 01:50:20 +0800534 ec_console_log = None
Vic Yang079f9872013-07-01 11:32:00 +0800535 ec_panic_info = None
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800536
Jon Salz0697cbf2012-07-04 15:14:04 +0800537 # Any 'active' tests should be marked as failed now.
538 for test in self.test_list.walk():
Jon Salza6711d72012-07-18 14:33:03 +0800539 if not test.is_leaf():
540 # Don't bother with parents; they will be updated when their
541 # children are updated.
542 continue
543
Jon Salz0697cbf2012-07-04 15:14:04 +0800544 test_state = test.get_state()
545 if test_state.status != TestState.ACTIVE:
546 continue
547 if isinstance(test, factory.ShutdownStep):
548 # Shutdown while the test was active - that's good.
Ricky Liang48e47f92014-02-26 19:31:51 +0800549 self.handle_shutdown_complete(test)
Jon Salz0697cbf2012-07-04 15:14:04 +0800550 else:
551 # Unexpected shutdown. Grab /var/log/messages for context.
552 if var_log_messages is None:
553 try:
554 var_log_messages = (
Ricky Liang45c73e72015-01-15 15:00:30 +0800555 utils.var_log_messages_before_reboot())
Jon Salz0697cbf2012-07-04 15:14:04 +0800556 # Write it to the log, to make it easier to
557 # correlate with /var/log/messages.
558 logging.info(
Ricky Liang45c73e72015-01-15 15:00:30 +0800559 'Unexpected shutdown. '
560 'Tail of /var/log/messages before last reboot:\n'
561 '%s', ('\n'.join(
562 ' ' + x for x in var_log_messages)))
Jon Salz0697cbf2012-07-04 15:14:04 +0800563 except: # pylint: disable=W0702
564 logging.exception('Unable to grok /var/log/messages')
565 var_log_messages = []
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800566
Jon Salz008f4ea2012-08-28 05:39:45 +0800567 if mosys_log is None and not utils.in_chroot():
568 try:
Ricky Liang117484a2014-04-14 11:14:41 +0800569 mosys_log = Spawn(
Jon Salz008f4ea2012-08-28 05:39:45 +0800570 ['mosys', 'eventlog', 'list'],
571 read_stdout=True, log_stderr_on_error=True).stdout_data
572 # Write it to the log also.
573 logging.info('System eventlog from mosys:\n%s\n', mosys_log)
574 except: # pylint: disable=W0702
575 logging.exception('Unable to read mosys eventlog')
Vic Yanga9c32212012-08-16 20:07:54 +0800576
Vic Yange4c275d2012-08-28 01:50:20 +0800577 if ec_console_log is None:
Dean Liao88b93192014-10-23 19:37:41 +0800578 ec_console_log = self.log_ec_console()
Vic Yange4c275d2012-08-28 01:50:20 +0800579
Vic Yang079f9872013-07-01 11:32:00 +0800580 if ec_panic_info is None:
Dean Liao88b93192014-10-23 19:37:41 +0800581 ec_panic_info = self.log_ec_panic_info()
Vic Yang079f9872013-07-01 11:32:00 +0800582
Jon Salz0697cbf2012-07-04 15:14:04 +0800583 error_msg = 'Unexpected shutdown while test was running'
584 self.event_log.Log('end_test',
Ricky Liang45c73e72015-01-15 15:00:30 +0800585 path=test.path,
586 status=TestState.FAILED,
587 invocation=test.get_state().invocation,
588 error_msg=error_msg,
589 var_log_messages='\n'.join(var_log_messages),
590 mosys_log=mosys_log)
Jon Salz0697cbf2012-07-04 15:14:04 +0800591 test.update_state(
Ricky Liang45c73e72015-01-15 15:00:30 +0800592 status=TestState.FAILED,
593 error_msg=error_msg)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800594
Jon Salz50efe942012-07-26 11:54:10 +0800595 if not test.never_fails:
596 # For "never_fails" tests (such as "Start"), don't cancel
597 # pending tests, since reboot is expected.
598 factory.console.info('Unexpected shutdown while test %s '
599 'running; cancelling any pending tests',
600 test.path)
601 self.state_instance.set_shared_data('tests_after_shutdown', [])
Jon Salz69806bb2012-07-20 18:05:02 +0800602
Jon Salz008f4ea2012-08-28 05:39:45 +0800603 self.update_skipped_tests()
604
605 def update_skipped_tests(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800606 """Updates skipped states based on run_if."""
Jon Salz885dcac2013-07-23 16:39:50 +0800607 env = TestArgEnv()
Ricky Liang45c73e72015-01-15 15:00:30 +0800608
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800609 def _evaluate_skip_from_run_if(test):
610 """Returns the run_if evaluation of the test.
611
612 Args:
613 test: A FactoryTest object.
614
615 Returns:
616 The run_if evaluation result. Returns False if the test has no
617 run_if argument.
618 """
619 value = None
620 if test.run_if_expr:
621 try:
622 value = test.run_if_expr(env)
623 except: # pylint: disable=W0702
624 logging.exception('Unable to evaluate run_if expression for %s',
625 test.path)
626 # But keep going; we have no choice. This will end up
627 # always activating the test.
628 elif test.run_if_table_name:
629 try:
630 aux = shopfloor.get_selected_aux_data(test.run_if_table_name)
631 value = aux.get(test.run_if_col)
632 except ValueError:
633 # Not available; assume it shouldn't be skipped
634 pass
635
636 if value is None:
637 skip = False
638 else:
639 skip = (not value) ^ t.run_if_not
640 return skip
641
642 # Gets all run_if evaluation, and stores results in skip_map.
643 skip_map = dict()
Jon Salz008f4ea2012-08-28 05:39:45 +0800644 for t in self.test_list.walk():
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800645 skip_map[t.path] = _evaluate_skip_from_run_if(t)
Jon Salz885dcac2013-07-23 16:39:50 +0800646
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800647 # Propagates the skip value from root of tree and updates skip_map.
648 def _update_skip_map_from_node(test, skip_from_parent):
649 """Updates skip_map from a given node.
Jon Salz885dcac2013-07-23 16:39:50 +0800650
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800651 Given a FactoryTest node and the skip value from parent, updates the
652 skip value of current node in the skip_map if skip value from parent is
653 True. If this node has children, recursively propagate this value to all
654 its children, that is, all its subtests.
655 Note that this function only updates value in skip_map, not the actual
656 test_list tree.
Jon Salz008f4ea2012-08-28 05:39:45 +0800657
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800658 Args:
659 test: The given FactoryTest object. It is a node in the test_list tree.
660 skip_from_parent: The skip value which propagates from the parent of
661 input node.
662 """
663 skip_this_tree = skip_from_parent or skip_map[test.path]
664 if skip_this_tree:
665 logging.info('Skip from node %r', test.path)
666 skip_map[test.path] = True
667 if test.is_leaf():
668 return
669 # Propagates skip value to its subtests
670 for subtest in test.subtests:
671 _update_skip_map_from_node(subtest, skip_this_tree)
672
673 _update_skip_map_from_node(self.test_list, False)
674
675 # Updates the skip value from skip_map to test_list tree. Also, updates test
676 # status if needed.
677 for t in self.test_list.walk():
678 skip = skip_map[t.path]
679 test_state = t.get_state()
680 if ((not skip) and
681 (test_state.status == TestState.PASSED) and
682 (test_state.error_msg == TestState.SKIPPED_MSG)):
683 # It was marked as skipped before, but now we need to run it.
684 # Mark as untested.
685 t.update_state(skip=skip, status=TestState.UNTESTED, error_msg='')
686 else:
687 t.update_state(skip=skip)
Jon Salz008f4ea2012-08-28 05:39:45 +0800688
Jon Salz0697cbf2012-07-04 15:14:04 +0800689 def show_next_active_test(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800690 """Rotates to the next visible active test."""
Jon Salz0697cbf2012-07-04 15:14:04 +0800691 self.reap_completed_tests()
692 active_tests = [
Ricky Liang45c73e72015-01-15 15:00:30 +0800693 t for t in self.test_list.walk()
694 if t.is_leaf() and t.get_state().status == TestState.ACTIVE]
Jon Salz0697cbf2012-07-04 15:14:04 +0800695 if not active_tests:
696 return
Jon Salz4f6c7172012-06-11 20:45:36 +0800697
Jon Salz0697cbf2012-07-04 15:14:04 +0800698 try:
699 next_test = active_tests[
Ricky Liang45c73e72015-01-15 15:00:30 +0800700 (active_tests.index(self.visible_test) + 1) % len(active_tests)]
Jon Salz0697cbf2012-07-04 15:14:04 +0800701 except ValueError: # visible_test not present in active_tests
702 next_test = active_tests[0]
Jon Salz4f6c7172012-06-11 20:45:36 +0800703
Jon Salz0697cbf2012-07-04 15:14:04 +0800704 self.set_visible_test(next_test)
Jon Salz4f6c7172012-06-11 20:45:36 +0800705
Jon Salz0697cbf2012-07-04 15:14:04 +0800706 def handle_event(self, event):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800707 """Handles an event from the event server."""
Jon Salz0697cbf2012-07-04 15:14:04 +0800708 handler = self.event_handlers.get(event.type)
709 if handler:
710 handler(event)
711 else:
712 # We don't register handlers for all event types - just ignore
713 # this event.
714 logging.debug('Unbound event type %s', event.type)
Jon Salz4f6c7172012-06-11 20:45:36 +0800715
Vic Yangaabf9fd2013-04-09 18:56:13 +0800716 def check_critical_factory_note(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800717 """Returns True if the last factory note is critical."""
Vic Yangaabf9fd2013-04-09 18:56:13 +0800718 notes = self.state_instance.get_shared_data('factory_note', True)
719 return notes and notes[-1]['level'] == 'CRITICAL'
720
Jon Salz0697cbf2012-07-04 15:14:04 +0800721 def run_next_test(self):
henryhsu4cc6b022014-04-22 17:12:42 +0800722 """Runs the next eligible test (or tests) in self.tests_to_run.
723
724 We have three kinds of the next eligible test:
725 1. normal
726 2. backgroundable
727 3. force_background
728
729 And we have four situations of the ongoing invocations:
730 a. only a running normal test
731 b. all running tests are backgroundable
732 c. all running tests are force_background
733 d. all running tests are any combination of backgroundable and
734 force_background
735
736 When a test would like to be run, it must follow the rules:
737 [1] cannot run with [abd]
738 [2] cannot run with [a]
739 All the other combinations are allowed
740 """
Jon Salz0697cbf2012-07-04 15:14:04 +0800741 self.reap_completed_tests()
Vic Yangaabf9fd2013-04-09 18:56:13 +0800742 if self.tests_to_run and self.check_critical_factory_note():
743 self.tests_to_run.clear()
744 return
Jon Salz0697cbf2012-07-04 15:14:04 +0800745 while self.tests_to_run:
Ricky Liang6fe218c2013-12-27 15:17:17 +0800746 logging.debug('Tests to run: %s', [x.path for x in self.tests_to_run])
Jon Salz94eb56f2012-06-12 18:01:12 +0800747
Jon Salz0697cbf2012-07-04 15:14:04 +0800748 test = self.tests_to_run[0]
Jon Salz94eb56f2012-06-12 18:01:12 +0800749
Jon Salz0697cbf2012-07-04 15:14:04 +0800750 if test in self.invocations:
751 logging.info('Next test %s is already running', test.path)
752 self.tests_to_run.popleft()
753 return
Jon Salz94eb56f2012-06-12 18:01:12 +0800754
Jon Salza1412922012-07-23 16:04:17 +0800755 for requirement in test.require_run:
756 for i in requirement.test.walk():
757 if i.get_state().status == TestState.ACTIVE:
Jon Salz304a75d2012-07-06 11:14:15 +0800758 logging.info('Waiting for active test %s to complete '
Jon Salza1412922012-07-23 16:04:17 +0800759 'before running %s', i.path, test.path)
Jon Salz304a75d2012-07-06 11:14:15 +0800760 return
761
henryhsu4cc6b022014-04-22 17:12:42 +0800762 def is_normal_test(test):
763 return not (test.backgroundable or test.force_background)
764
765 # [1] cannot run with [abd].
766 if self.invocations and is_normal_test(test) and any(
767 [not x.force_background for x in self.invocations]):
768 logging.info('Waiting for non-force_background tests to '
769 'complete before running %s', test.path)
770 return
771
772 # [2] cannot run with [a].
773 if self.invocations and test.backgroundable and any(
774 [is_normal_test(x) for x in self.invocations]):
775 logging.info('Waiting for normal tests to '
776 'complete before running %s', test.path)
Jon Salz0697cbf2012-07-04 15:14:04 +0800777 return
Jon Salz94eb56f2012-06-12 18:01:12 +0800778
Jon Salz3e6f5202012-10-15 15:08:29 +0800779 if test.get_state().skip:
780 factory.console.info('Skipping test %s', test.path)
781 test.update_state(status=TestState.PASSED,
782 error_msg=TestState.SKIPPED_MSG)
783 self.tests_to_run.popleft()
784 continue
785
Jon Salz0697cbf2012-07-04 15:14:04 +0800786 self.tests_to_run.popleft()
Jon Salz94eb56f2012-06-12 18:01:12 +0800787
Jon Salz304a75d2012-07-06 11:14:15 +0800788 untested = set()
Jon Salza1412922012-07-23 16:04:17 +0800789 for requirement in test.require_run:
790 for i in requirement.test.walk():
791 if i == test:
Jon Salz304a75d2012-07-06 11:14:15 +0800792 # We've hit this test itself; stop checking
793 break
Jon Salza1412922012-07-23 16:04:17 +0800794 if ((i.get_state().status == TestState.UNTESTED) or
795 (requirement.passed and i.get_state().status !=
796 TestState.PASSED)):
Jon Salz304a75d2012-07-06 11:14:15 +0800797 # Found an untested test; move on to the next
798 # element in require_run.
Jon Salza1412922012-07-23 16:04:17 +0800799 untested.add(i)
Jon Salz304a75d2012-07-06 11:14:15 +0800800 break
801
802 if untested:
803 untested_paths = ', '.join(sorted([x.path for x in untested]))
804 if self.state_instance.get_shared_data('engineering_mode',
805 optional=True):
806 # In engineering mode, we'll let it go.
807 factory.console.warn('In engineering mode; running '
808 '%s even though required tests '
809 '[%s] have not completed',
810 test.path, untested_paths)
811 else:
812 # Not in engineering mode; mark it failed.
813 error_msg = ('Required tests [%s] have not been run yet'
814 % untested_paths)
815 factory.console.error('Not running %s: %s',
816 test.path, error_msg)
817 test.update_state(status=TestState.FAILED,
818 error_msg=error_msg)
819 continue
820
Ricky Liang48e47f92014-02-26 19:31:51 +0800821 if (isinstance(test, factory.ShutdownStep) and
Ricky Liangb7eb8772014-09-15 18:05:22 +0800822 self.state_instance.get_shared_data(
823 state.POST_SHUTDOWN_TAG % test.path, optional=True)):
Ricky Liang48e47f92014-02-26 19:31:51 +0800824 # Invoking post shutdown method of shutdown test. We should retain the
825 # iterations_left and retries_left of the original test state.
826 test_state = self.state_instance.get_test_state(test.path)
827 self._run_test(test, test_state.iterations_left,
828 test_state.retries_left)
829 else:
830 # Starts a new test run; reset iterations and retries.
831 self._run_test(test, test.iterations, test.retries)
Jon Salz1acc8742012-07-17 17:45:55 +0800832
Cheng-Yi Chiangce05c002013-04-04 02:13:17 +0800833 def _run_test(self, test, iterations_left=None, retries_left=None):
Vic Yanga3cecf82014-12-26 00:44:21 -0800834 if not self._ui_initialized and not test.is_no_host():
835 self.init_ui()
Vic Yang08505c72015-01-06 17:01:53 -0800836 invoc = TestInvocation(
837 self, test, on_completion=self.run_next_test,
838 on_test_failure=system.GetBoard().OnTestFailure)
Jon Salz1acc8742012-07-17 17:45:55 +0800839 new_state = test.update_state(
Ricky Liang48e47f92014-02-26 19:31:51 +0800840 status=TestState.ACTIVE, increment_count=1, error_msg='',
841 invocation=invoc.uuid, iterations_left=iterations_left,
842 retries_left=retries_left,
843 visible=(self.visible_test == test))
Jon Salz1acc8742012-07-17 17:45:55 +0800844 invoc.count = new_state.count
845
846 self.invocations[test] = invoc
847 if self.visible_test is None and test.has_ui:
848 self.set_visible_test(test)
Vic Yang311ddb82012-09-26 12:08:28 +0800849 self.check_exclusive()
Jon Salz1acc8742012-07-17 17:45:55 +0800850 invoc.start()
Jon Salz5f2a0672012-05-22 17:14:06 +0800851
Vic Yang311ddb82012-09-26 12:08:28 +0800852 def check_exclusive(self):
Jon Salzce6a7f82013-06-10 18:22:54 +0800853 # alias since this is really long
854 EXCL_OPT = factory.FactoryTest.EXCLUSIVE_OPTIONS
855
Vic Yang311ddb82012-09-26 12:08:28 +0800856 current_exclusive_items = set([
Jon Salzce6a7f82013-06-10 18:22:54 +0800857 item for item in EXCL_OPT
Vic Yang311ddb82012-09-26 12:08:28 +0800858 if any([test.is_exclusive(item) for test in self.invocations])])
859
860 new_exclusive_items = current_exclusive_items - self.exclusive_items
Jon Salzce6a7f82013-06-10 18:22:54 +0800861 if EXCL_OPT.NETWORKING in new_exclusive_items:
Vic Yang311ddb82012-09-26 12:08:28 +0800862 logging.info('Disabling network')
863 self.connection_manager.DisableNetworking()
Jon Salzce6a7f82013-06-10 18:22:54 +0800864 if EXCL_OPT.CHARGER in new_exclusive_items:
Vic Yang311ddb82012-09-26 12:08:28 +0800865 logging.info('Stop controlling charger')
866
867 new_non_exclusive_items = self.exclusive_items - current_exclusive_items
Jon Salzce6a7f82013-06-10 18:22:54 +0800868 if EXCL_OPT.NETWORKING in new_non_exclusive_items:
Vic Yang311ddb82012-09-26 12:08:28 +0800869 logging.info('Re-enabling network')
870 self.connection_manager.EnableNetworking()
Jon Salzce6a7f82013-06-10 18:22:54 +0800871 if EXCL_OPT.CHARGER in new_non_exclusive_items:
Vic Yang311ddb82012-09-26 12:08:28 +0800872 logging.info('Start controlling charger')
873
Jon Salzce6a7f82013-06-10 18:22:54 +0800874 if self.cpufreq_manager:
875 enabled = EXCL_OPT.CPUFREQ not in current_exclusive_items
876 try:
877 self.cpufreq_manager.SetEnabled(enabled)
878 except: # pylint: disable=W0702
879 logging.exception('Unable to %s cpufreq services',
880 'enable' if enabled else 'disable')
881
Ricky Liang0f9978e2015-01-30 08:19:17 +0000882 # Only adjust charge state if not excluded
883 if (EXCL_OPT.CHARGER not in current_exclusive_items and
884 not utils.in_chroot()):
885 if self.charge_manager:
Cheng-Yi Chiangd8186952013-04-04 23:41:14 +0800886 self.charge_manager.AdjustChargeState()
887 else:
Dean Liao88b93192014-10-23 19:37:41 +0800888 self.charge()
Vic Yang311ddb82012-09-26 12:08:28 +0800889
890 self.exclusive_items = current_exclusive_items
Jon Salz5da61e62012-05-31 13:06:22 +0800891
Dean Liao88b93192014-10-23 19:37:41 +0800892 def charge(self):
893 """Charges the board.
894
895 It won't try again if last time SetChargeState raised an exception.
896 """
897 if not self._can_charge:
898 return
899
900 try:
Ricky Liang9ac35e02015-01-30 16:01:32 +0800901 if self.charge_manager:
902 self.charge_manager.StartCharging()
903 else:
904 system.GetBoard().SetChargeState(Board.ChargeState.CHARGE)
Dean Liao88b93192014-10-23 19:37:41 +0800905 except NotImplementedError:
906 logging.info('Charging is not supported')
907 self._can_charge = False
908 except BoardException:
909 logging.exception('Unable to set charge state on this board')
910 self._can_charge = False
911
cychiang21886742012-07-05 15:16:32 +0800912 def check_for_updates(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800913 """Schedules an asynchronous check for updates if necessary."""
cychiang21886742012-07-05 15:16:32 +0800914 if not self.test_list.options.update_period_secs:
915 # Not enabled.
916 return
917
918 now = time.time()
919 if self.last_update_check and (
920 now - self.last_update_check <
921 self.test_list.options.update_period_secs):
922 # Not yet time for another check.
923 return
924
925 self.last_update_check = now
926
927 def handle_check_for_update(reached_shopfloor, md5sum, needs_update):
928 if reached_shopfloor:
929 new_update_md5sum = md5sum if needs_update else None
930 if system.SystemInfo.update_md5sum != new_update_md5sum:
931 logging.info('Received new update MD5SUM: %s', new_update_md5sum)
932 system.SystemInfo.update_md5sum = new_update_md5sum
Peter Ammon1e1ec572014-06-26 17:56:32 -0700933 self.run_enqueue(self.update_system_info)
Cheng-Yi Chiang194d3c02015-03-16 14:37:15 +0800934 else:
935 if not self._suppress_periodic_update_messages:
936 logging.warning('Suppress error messages for periodic update checking'
937 ' after the first one.')
938 self._suppress_periodic_update_messages = True
cychiang21886742012-07-05 15:16:32 +0800939
940 updater.CheckForUpdateAsync(
Ricky Liang45c73e72015-01-15 15:00:30 +0800941 handle_check_for_update,
Cheng-Yi Chiang194d3c02015-03-16 14:37:15 +0800942 self.test_list.options.shopfloor_timeout_secs,
943 self._suppress_periodic_update_messages)
cychiang21886742012-07-05 15:16:32 +0800944
Jon Salza6711d72012-07-18 14:33:03 +0800945 def cancel_pending_tests(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800946 """Cancels any tests in the run queue."""
Jon Salza6711d72012-07-18 14:33:03 +0800947 self.run_tests([])
948
Ricky Liang4bff3e32014-02-20 18:46:11 +0800949 def restore_active_run_state(self):
950 """Restores active run id and the list of scheduled tests."""
951 self.run_id = self.state_instance.get_shared_data('run_id', optional=True)
952 self.scheduled_run_tests = self.state_instance.get_shared_data(
953 'scheduled_run_tests', optional=True)
954
955 def set_active_run_state(self):
956 """Sets active run id and the list of scheduled tests."""
957 self.run_id = str(uuid.uuid4())
958 self.scheduled_run_tests = [test.path for test in self.tests_to_run]
959 self.state_instance.set_shared_data('run_id', self.run_id)
960 self.state_instance.set_shared_data('scheduled_run_tests',
961 self.scheduled_run_tests)
962
Jon Salz0697cbf2012-07-04 15:14:04 +0800963 def run_tests(self, subtrees, untested_only=False):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800964 """Runs tests under subtree.
Jon Salz258a40c2012-04-19 12:34:01 +0800965
Jon Salz0697cbf2012-07-04 15:14:04 +0800966 The tests are run in order unless one fails (then stops).
967 Backgroundable tests are run simultaneously; when a foreground test is
968 encountered, we wait for all active tests to finish before continuing.
Jon Salzb1b39092012-05-03 02:05:09 +0800969
Ricky Liang6fe218c2013-12-27 15:17:17 +0800970 Args:
971 subtrees: Node or nodes containing tests to run (may either be
972 a single test or a list). Duplicates will be ignored.
973 untested_only: True to run untested tests only.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800974 """
Vic Yang08505c72015-01-06 17:01:53 -0800975 system.GetBoard().OnTestStart()
976
Jon Salz0697cbf2012-07-04 15:14:04 +0800977 if type(subtrees) != list:
978 subtrees = [subtrees]
Jon Salz258a40c2012-04-19 12:34:01 +0800979
Jon Salz0697cbf2012-07-04 15:14:04 +0800980 # Nodes we've seen so far, to avoid duplicates.
981 seen = set()
Jon Salz94eb56f2012-06-12 18:01:12 +0800982
Jon Salz0697cbf2012-07-04 15:14:04 +0800983 self.tests_to_run = deque()
984 for subtree in subtrees:
985 for test in subtree.walk():
986 if test in seen:
987 continue
988 seen.add(test)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800989
Jon Salz0697cbf2012-07-04 15:14:04 +0800990 if not test.is_leaf():
991 continue
Ricky Liang45c73e72015-01-15 15:00:30 +0800992 if untested_only and test.get_state().status != TestState.UNTESTED:
Jon Salz0697cbf2012-07-04 15:14:04 +0800993 continue
994 self.tests_to_run.append(test)
Ricky Liang4bff3e32014-02-20 18:46:11 +0800995 if subtrees:
996 self.set_active_run_state()
Jon Salz0697cbf2012-07-04 15:14:04 +0800997 self.run_next_test()
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800998
Jon Salz0697cbf2012-07-04 15:14:04 +0800999 def reap_completed_tests(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001000 """Removes completed tests from the set of active tests.
Jon Salz0697cbf2012-07-04 15:14:04 +08001001
1002 Also updates the visible test if it was reaped.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001003 """
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +08001004 test_completed = False
Jon Salz0697cbf2012-07-04 15:14:04 +08001005 for t, v in dict(self.invocations).iteritems():
1006 if v.is_completed():
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +08001007 test_completed = True
Jon Salz1acc8742012-07-17 17:45:55 +08001008 new_state = t.update_state(**v.update_state_on_completion)
Jon Salz0697cbf2012-07-04 15:14:04 +08001009 del self.invocations[t]
1010
Chun-Ta Lin54e17e42012-09-06 22:05:13 +08001011 # Stop on failure if flag is true.
1012 if (self.test_list.options.stop_on_failure and
1013 new_state.status == TestState.FAILED):
1014 # Clean all the tests to cause goofy to stop.
1015 self.tests_to_run = []
Ricky Liang45c73e72015-01-15 15:00:30 +08001016 factory.console.info('Stop on failure triggered. Empty the queue.')
Chun-Ta Lin54e17e42012-09-06 22:05:13 +08001017
Jon Salz1acc8742012-07-17 17:45:55 +08001018 if new_state.iterations_left and new_state.status == TestState.PASSED:
1019 # Play it again, Sam!
1020 self._run_test(t)
Cheng-Yi Chiangce05c002013-04-04 02:13:17 +08001021 # new_state.retries_left is obtained after update.
1022 # For retries_left == 0, test can still be run for the last time.
1023 elif (new_state.retries_left >= 0 and
1024 new_state.status == TestState.FAILED):
1025 # Still have to retry, Sam!
1026 self._run_test(t)
Jon Salz1acc8742012-07-17 17:45:55 +08001027
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +08001028 if test_completed:
Vic Yangf01c59f2013-04-19 17:37:56 +08001029 self.log_watcher.KickWatchThread()
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +08001030
Jon Salz0697cbf2012-07-04 15:14:04 +08001031 if (self.visible_test is None or
Jon Salz85a39882012-07-05 16:45:04 +08001032 self.visible_test not in self.invocations):
Jon Salz0697cbf2012-07-04 15:14:04 +08001033 self.set_visible_test(None)
1034 # Make the first running test, if any, the visible test
1035 for t in self.test_list.walk():
1036 if t in self.invocations:
1037 self.set_visible_test(t)
1038 break
1039
Jon Salz6dc031d2013-06-19 13:06:23 +08001040 def kill_active_tests(self, abort, root=None, reason=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001041 """Kills and waits for all active tests.
Jon Salz0697cbf2012-07-04 15:14:04 +08001042
Jon Salz85a39882012-07-05 16:45:04 +08001043 Args:
1044 abort: True to change state of killed tests to FAILED, False for
Jon Salz0697cbf2012-07-04 15:14:04 +08001045 UNTESTED.
Jon Salz85a39882012-07-05 16:45:04 +08001046 root: If set, only kills tests with root as an ancestor.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001047 reason: If set, the abort reason.
1048 """
Jon Salz0697cbf2012-07-04 15:14:04 +08001049 self.reap_completed_tests()
1050 for test, invoc in self.invocations.items():
Jon Salz85a39882012-07-05 16:45:04 +08001051 if root and not test.has_ancestor(root):
1052 continue
1053
Ricky Liang45c73e72015-01-15 15:00:30 +08001054 factory.console.info('Killing active test %s...', test.path)
Jon Salz6dc031d2013-06-19 13:06:23 +08001055 invoc.abort_and_join(reason)
Ricky Liang45c73e72015-01-15 15:00:30 +08001056 factory.console.info('Killed %s', test.path)
Jon Salz1acc8742012-07-17 17:45:55 +08001057 test.update_state(**invoc.update_state_on_completion)
Jon Salz0697cbf2012-07-04 15:14:04 +08001058 del self.invocations[test]
Jon Salz1acc8742012-07-17 17:45:55 +08001059
Jon Salz0697cbf2012-07-04 15:14:04 +08001060 if not abort:
1061 test.update_state(status=TestState.UNTESTED)
1062 self.reap_completed_tests()
1063
Jon Salz6dc031d2013-06-19 13:06:23 +08001064 def stop(self, root=None, fail=False, reason=None):
1065 self.kill_active_tests(fail, root, reason)
Jon Salz85a39882012-07-05 16:45:04 +08001066 # Remove any tests in the run queue under the root.
1067 self.tests_to_run = deque([x for x in self.tests_to_run
1068 if root and not x.has_ancestor(root)])
1069 self.run_next_test()
Jon Salz0697cbf2012-07-04 15:14:04 +08001070
Jon Salz4712ac72013-02-07 17:12:05 +08001071 def clear_state(self, root=None):
Jon Salzd7550792013-07-12 05:49:27 +08001072 if root is None:
1073 root = self.test_list
Jon Salz6dc031d2013-06-19 13:06:23 +08001074 self.stop(root, reason='Clearing test state')
Jon Salz4712ac72013-02-07 17:12:05 +08001075 for f in root.walk():
1076 if f.is_leaf():
1077 f.update_state(status=TestState.UNTESTED)
1078
Jon Salz6dc031d2013-06-19 13:06:23 +08001079 def abort_active_tests(self, reason=None):
1080 self.kill_active_tests(True, reason=reason)
Jon Salz0697cbf2012-07-04 15:14:04 +08001081
1082 def main(self):
Jon Salzeff94182013-06-19 15:06:28 +08001083 syslog.openlog('goofy')
1084
Jon Salz0697cbf2012-07-04 15:14:04 +08001085 try:
Jon Salzd7550792013-07-12 05:49:27 +08001086 self.status = Status.INITIALIZING
Jon Salz0697cbf2012-07-04 15:14:04 +08001087 self.init()
1088 self.event_log.Log('goofy_init',
Ricky Liang45c73e72015-01-15 15:00:30 +08001089 success=True)
Jon Salz0697cbf2012-07-04 15:14:04 +08001090 except:
1091 if self.event_log:
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001092 try:
Jon Salz0697cbf2012-07-04 15:14:04 +08001093 self.event_log.Log('goofy_init',
Ricky Liang45c73e72015-01-15 15:00:30 +08001094 success=False,
1095 trace=traceback.format_exc())
Jon Salz0697cbf2012-07-04 15:14:04 +08001096 except: # pylint: disable=W0702
1097 pass
1098 raise
1099
Jon Salzd7550792013-07-12 05:49:27 +08001100 self.status = Status.RUNNING
Jon Salzeff94182013-06-19 15:06:28 +08001101 syslog.syslog('Goofy (factory test harness) starting')
Jon Salz0697cbf2012-07-04 15:14:04 +08001102 self.run()
1103
1104 def update_system_info(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001105 """Updates system info."""
Jon Salz0697cbf2012-07-04 15:14:04 +08001106 system_info = system.SystemInfo()
1107 self.state_instance.set_shared_data('system_info', system_info.__dict__)
1108 self.event_client.post_event(Event(Event.Type.SYSTEM_INFO,
Ricky Liang45c73e72015-01-15 15:00:30 +08001109 system_info=system_info.__dict__))
Jon Salz0697cbf2012-07-04 15:14:04 +08001110 logging.info('System info: %r', system_info.__dict__)
1111
Jon Salzeb42f0d2012-07-27 19:14:04 +08001112 def update_factory(self, auto_run_on_restart=False, post_update_hook=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001113 """Commences updating factory software.
Jon Salzeb42f0d2012-07-27 19:14:04 +08001114
1115 Args:
1116 auto_run_on_restart: Auto-run when the machine comes back up.
1117 post_update_hook: Code to call after update but immediately before
1118 restart.
1119
1120 Returns:
1121 Never if the update was successful (we just reboot).
1122 False if the update was unnecessary (no update available).
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001123 """
Jon Salz6dc031d2013-06-19 13:06:23 +08001124 self.kill_active_tests(False, reason='Factory software update')
Jon Salza6711d72012-07-18 14:33:03 +08001125 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +08001126
Jon Salz5c344f62012-07-13 14:31:16 +08001127 def pre_update_hook():
1128 if auto_run_on_restart:
1129 self.state_instance.set_shared_data('tests_after_shutdown',
1130 FORCE_AUTO_RUN)
1131 self.state_instance.close()
1132
Jon Salzeb42f0d2012-07-27 19:14:04 +08001133 if updater.TryUpdate(pre_update_hook=pre_update_hook):
1134 if post_update_hook:
1135 post_update_hook()
1136 self.env.shutdown('reboot')
Jon Salz0697cbf2012-07-04 15:14:04 +08001137
Ricky Liang8fecf412014-05-22 10:56:14 +08001138 def handle_sigint(self, dummy_signum, dummy_frame): # pylint: disable=W0613
Jon Salz77c151e2012-08-28 07:20:37 +08001139 logging.error('Received SIGINT')
Peter Ammon1e1ec572014-06-26 17:56:32 -07001140 self.run_enqueue(None)
Jon Salz77c151e2012-08-28 07:20:37 +08001141 raise KeyboardInterrupt()
1142
Ricky Liang8fecf412014-05-22 10:56:14 +08001143 def handle_sigterm(self, dummy_signum, dummy_frame): # pylint: disable=W0613
1144 logging.error('Received SIGTERM')
Hung-Te Lin94ca4742014-07-09 20:13:50 +08001145 self.env.terminate()
1146 self.run_queue.put(None)
Ricky Liang8fecf412014-05-22 10:56:14 +08001147 raise RuntimeError('Received SIGTERM')
1148
Jon Salze12c2b32013-06-25 16:24:34 +08001149 def find_kcrashes(self):
1150 """Finds kcrash files, logs them, and marks them as seen."""
1151 seen_crashes = set(
1152 self.state_instance.get_shared_data('seen_crashes', optional=True)
1153 or [])
1154
1155 for path in glob.glob('/var/spool/crash/*'):
1156 if not os.path.isfile(path):
1157 continue
1158 if path in seen_crashes:
1159 continue
1160 try:
1161 stat = os.stat(path)
1162 mtime = utils.TimeString(stat.st_mtime)
1163 logging.info(
1164 'Found new crash file %s (%d bytes at %s)',
1165 path, stat.st_size, mtime)
1166 extra_log_args = {}
1167
1168 try:
1169 _, ext = os.path.splitext(path)
1170 if ext in ['.kcrash', '.meta']:
1171 ext = ext.replace('.', '')
1172 with open(path) as f:
1173 data = f.read(MAX_CRASH_FILE_SIZE)
1174 tell = f.tell()
1175 logging.info(
1176 'Contents of %s%s:%s',
1177 path,
1178 ('' if tell == stat.st_size
1179 else '(truncated to %d bytes)' % MAX_CRASH_FILE_SIZE),
1180 ('\n' + data).replace('\n', '\n ' + ext + '> '))
1181 extra_log_args['data'] = data
1182
1183 # Copy to /var/factory/kcrash for posterity
1184 kcrash_dir = factory.get_factory_root('kcrash')
1185 utils.TryMakeDirs(kcrash_dir)
1186 shutil.copy(path, kcrash_dir)
1187 logging.info('Copied to %s',
1188 os.path.join(kcrash_dir, os.path.basename(path)))
1189 finally:
1190 # Even if something goes wrong with the above, still try to
1191 # log to event log
1192 self.event_log.Log('crash_file',
1193 path=path, size=stat.st_size, mtime=mtime,
1194 **extra_log_args)
1195 except: # pylint: disable=W0702
1196 logging.exception('Unable to handle crash files %s', path)
1197 seen_crashes.add(path)
1198
1199 self.state_instance.set_shared_data('seen_crashes', list(seen_crashes))
1200
Jon Salz128b0932013-07-03 16:55:26 +08001201 def GetTestList(self, test_list_id):
1202 """Returns the test list with the given ID.
1203
1204 Raises:
1205 TestListError: The test list ID is not valid.
1206 """
1207 try:
1208 return self.test_lists[test_list_id]
1209 except KeyError:
1210 raise test_lists.TestListError(
1211 '%r is not a valid test list ID (available IDs are [%s])' % (
1212 test_list_id, ', '.join(sorted(self.test_lists.keys()))))
1213
1214 def InitTestLists(self):
1215 """Reads in all test lists and sets the active test list."""
Ricky Liang27051552014-05-04 14:22:26 +08001216 self.test_lists = test_lists.BuildAllTestLists(
1217 force_generic=(self.options.automation_mode is not None))
Jon Salzd7550792013-07-12 05:49:27 +08001218 logging.info('Loaded test lists: [%s]',
1219 test_lists.DescribeTestLists(self.test_lists))
Jon Salz128b0932013-07-03 16:55:26 +08001220
1221 if not self.options.test_list:
1222 self.options.test_list = test_lists.GetActiveTestListId()
1223
1224 if os.sep in self.options.test_list:
1225 # It's a path pointing to an old-style test list; use it.
1226 self.test_list = factory.read_test_list(self.options.test_list)
1227 else:
1228 self.test_list = self.GetTestList(self.options.test_list)
1229
1230 logging.info('Active test list: %s', self.test_list.test_list_id)
1231
1232 if isinstance(self.test_list, test_lists.OldStyleTestList):
1233 # Actually load it in. (See OldStyleTestList for an explanation
1234 # of why this is necessary.)
1235 self.test_list = self.test_list.Load()
1236
1237 self.test_list.state_instance = self.state_instance
1238
Shuo-Peng Liao268b40b2013-07-01 15:58:59 +08001239 def init_hooks(self):
1240 """Initializes hooks.
1241
1242 Must run after self.test_list ready.
1243 """
Shuo-Peng Liao52b90da2013-06-30 17:00:06 +08001244 module, cls = self.test_list.options.hooks_class.rsplit('.', 1)
1245 self.hooks = getattr(__import__(module, fromlist=[cls]), cls)()
1246 assert isinstance(self.hooks, factory.Hooks), (
Ricky Liang45c73e72015-01-15 15:00:30 +08001247 'hooks should be of type Hooks but is %r' % type(self.hooks))
Shuo-Peng Liao52b90da2013-06-30 17:00:06 +08001248 self.hooks.test_list = self.test_list
Shuo-Peng Liao268b40b2013-07-01 15:58:59 +08001249 self.hooks.OnCreatedTestList()
Shuo-Peng Liao52b90da2013-06-30 17:00:06 +08001250
Vic Yanga3cecf82014-12-26 00:44:21 -08001251 def init_ui(self):
1252 """Initialize UI."""
1253 self._ui_initialized = True
1254 if self.options.ui == 'chrome':
Hung-Te Lin8f6a3782015-01-06 22:58:32 +08001255 if self.options.monolithic:
Hung-Te Lin7bd55312014-12-30 16:43:36 +08001256 self.env.launch_chrome()
1257 else:
1258 # The presenter is responsible for launching Chrome. Let's just
1259 # wait here.
1260 self.env.controller_ready_for_ui()
Vic Yanga3cecf82014-12-26 00:44:21 -08001261 logging.info('Waiting for a web socket connection')
1262 self.web_socket_manager.wait()
1263
1264 # Wait for the test widget size to be set; this is done in
1265 # an asynchronous RPC so there is a small chance that the
1266 # web socket might be opened first.
1267 for _ in range(100): # 10 s
1268 try:
1269 if self.state_instance.get_shared_data('test_widget_size'):
1270 break
1271 except KeyError:
1272 pass # Retry
1273 time.sleep(0.1) # 100 ms
1274 else:
1275 logging.warn('Never received test_widget_size from UI')
1276
Hung-Te Lin7bd55312014-12-30 16:43:36 +08001277 logging.info('Waiting for a web socket connection')
1278 self.web_socket_manager.wait()
1279
Jon Salz0697cbf2012-07-04 15:14:04 +08001280 def init(self, args=None, env=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001281 """Initializes Goofy.
Jon Salz0697cbf2012-07-04 15:14:04 +08001282
1283 Args:
1284 args: A list of command-line arguments. Uses sys.argv if
1285 args is None.
1286 env: An Environment instance to use (or None to choose
1287 FakeChrootEnvironment or DUTEnvironment as appropriate).
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001288 """
Jon Salz0697cbf2012-07-04 15:14:04 +08001289 parser = OptionParser()
1290 parser.add_option('-v', '--verbose', dest='verbose',
Jon Salz8fa8e832012-07-13 19:04:09 +08001291 action='store_true',
1292 help='Enable debug logging')
Jon Salz0697cbf2012-07-04 15:14:04 +08001293 parser.add_option('--print_test_list', dest='print_test_list',
Jon Salz8fa8e832012-07-13 19:04:09 +08001294 metavar='FILE',
1295 help='Read and print test list FILE, and exit')
Jon Salz0697cbf2012-07-04 15:14:04 +08001296 parser.add_option('--restart', dest='restart',
Jon Salz8fa8e832012-07-13 19:04:09 +08001297 action='store_true',
1298 help='Clear all test state')
Jon Salz0697cbf2012-07-04 15:14:04 +08001299 parser.add_option('--ui', dest='ui', type='choice',
Jon Salz7b5482e2014-08-04 17:48:41 +08001300 choices=['none', 'chrome'],
Jon Salz2f881df2013-02-01 17:00:35 +08001301 default='chrome',
Jon Salz8fa8e832012-07-13 19:04:09 +08001302 help='UI to use')
Jon Salz0697cbf2012-07-04 15:14:04 +08001303 parser.add_option('--ui_scale_factor', dest='ui_scale_factor',
Jon Salz8fa8e832012-07-13 19:04:09 +08001304 type='int', default=1,
1305 help=('Factor by which to scale UI '
1306 '(Chrome UI only)'))
Jon Salz0697cbf2012-07-04 15:14:04 +08001307 parser.add_option('--test_list', dest='test_list',
Jon Salz8fa8e832012-07-13 19:04:09 +08001308 metavar='FILE',
1309 help='Use FILE as test list')
Jon Salzc79a9982012-08-30 04:42:01 +08001310 parser.add_option('--dummy_shopfloor', action='store_true',
1311 help='Use a dummy shopfloor server')
Hung-Te Lincc41d2a2014-10-29 13:35:20 +08001312 parser.add_option('--dummy_connection_manager', action='store_true',
1313 help='Use a dummy connection manager')
Ricky Liang6fe218c2013-12-27 15:17:17 +08001314 parser.add_option('--automation-mode',
1315 choices=[m.lower() for m in AutomationMode],
Ricky Liang45c73e72015-01-15 15:00:30 +08001316 default='none', help='Factory test automation mode.')
Ricky Liang117484a2014-04-14 11:14:41 +08001317 parser.add_option('--no-auto-run-on-start', dest='auto_run_on_start',
1318 action='store_false', default=True,
1319 help=('do not automatically run the test list on goofy '
1320 'start; this is only valid when factory test '
1321 'automation is enabled'))
Chun-Ta Lina8dd3172014-11-26 16:15:13 +08001322 parser.add_option('--handshake_timeout', dest='handshake_timeout',
1323 type='float', default=0.3,
1324 help=('RPC timeout when doing handshake between device '
1325 'and presenter.'))
Vic Yang7d693c42014-09-14 09:52:39 +08001326 parser.add_option('--standalone', dest='standalone',
1327 action='store_true', default=False,
1328 help=('Assume the presenter is running on the same '
1329 'machines.'))
Hung-Te Lin8f6a3782015-01-06 22:58:32 +08001330 parser.add_option('--monolithic', dest='monolithic',
1331 action='store_true', default=False,
1332 help='Run in monolithic mode (without presenter)')
Jon Salz0697cbf2012-07-04 15:14:04 +08001333 (self.options, self.args) = parser.parse_args(args)
1334
Hung-Te Lina846f602014-07-04 20:32:22 +08001335 signal.signal(signal.SIGINT, self.handle_sigint)
1336 # TODO(hungte) SIGTERM does not work properly without Telemetry and should
1337 # be fixed.
Hung-Te Lina846f602014-07-04 20:32:22 +08001338
Jon Salz46b89562012-07-05 11:49:22 +08001339 # Make sure factory directories exist.
1340 factory.get_log_root()
1341 factory.get_state_root()
1342 factory.get_test_data_root()
1343
Jon Salz0697cbf2012-07-04 15:14:04 +08001344 global _inited_logging # pylint: disable=W0603
1345 if not _inited_logging:
1346 factory.init_logging('goofy', verbose=self.options.verbose)
1347 _inited_logging = True
Jon Salz8fa8e832012-07-13 19:04:09 +08001348
Jon Salz0f996602012-10-03 15:26:48 +08001349 if self.options.print_test_list:
Joel Kitchingb85ed7f2014-10-08 18:24:39 +08001350 print(factory.read_test_list(
1351 self.options.print_test_list).__repr__(recursive=True))
Jon Salz0f996602012-10-03 15:26:48 +08001352 sys.exit(0)
1353
Jon Salzee85d522012-07-17 14:34:46 +08001354 event_log.IncrementBootSequence()
Jon Salzd15bbcf2013-05-21 17:33:57 +08001355 # Don't defer logging the initial event, so we can make sure
1356 # that device_id, reimage_id, etc. are all set up.
1357 self.event_log = EventLog('goofy', defer=False)
Jon Salz0697cbf2012-07-04 15:14:04 +08001358
Jon Salz0697cbf2012-07-04 15:14:04 +08001359 if env:
1360 self.env = env
1361 elif factory.in_chroot():
1362 self.env = test_environment.FakeChrootEnvironment()
1363 logging.warn(
Ricky Liang45c73e72015-01-15 15:00:30 +08001364 'Using chroot environment: will not actually run autotests')
Hung-Te Lina846f602014-07-04 20:32:22 +08001365 elif self.options.ui == 'chrome':
Ricky Liang09d66d82014-09-25 11:20:54 +08001366 self.env = test_environment.DUTEnvironment()
Jon Salz0697cbf2012-07-04 15:14:04 +08001367 self.env.goofy = self
Vic Yanga4931152014-08-11 16:36:24 -07001368 # web_socket_manager will be initialized later
1369 # pylint: disable=W0108
1370 self.env.has_sockets = lambda: self.web_socket_manager.has_sockets()
Jon Salz0697cbf2012-07-04 15:14:04 +08001371
1372 if self.options.restart:
1373 state.clear_state()
1374
Jon Salz0697cbf2012-07-04 15:14:04 +08001375 if self.options.ui_scale_factor != 1 and utils.in_qemu():
1376 logging.warn(
Ricky Liang45c73e72015-01-15 15:00:30 +08001377 'In QEMU; ignoring ui_scale_factor argument')
Jon Salz0697cbf2012-07-04 15:14:04 +08001378 self.options.ui_scale_factor = 1
1379
1380 logging.info('Started')
1381
Hung-Te Lin8f6a3782015-01-06 22:58:32 +08001382 if not self.options.monolithic:
Hung-Te Lin7bd55312014-12-30 16:43:36 +08001383 self.link_manager = PresenterLinkManager(
1384 check_interval=1,
1385 handshake_timeout=self.options.handshake_timeout,
1386 standalone=self.options.standalone)
Peter Ammon1e1ec572014-06-26 17:56:32 -07001387
Jon Salz0697cbf2012-07-04 15:14:04 +08001388 self.start_state_server()
1389 self.state_instance.set_shared_data('hwid_cfg', get_hwid_cfg())
1390 self.state_instance.set_shared_data('ui_scale_factor',
Ricky Liang09216dc2013-02-22 17:26:45 +08001391 self.options.ui_scale_factor)
Jon Salz0697cbf2012-07-04 15:14:04 +08001392 self.last_shutdown_time = (
Ricky Liang45c73e72015-01-15 15:00:30 +08001393 self.state_instance.get_shared_data('shutdown_time', optional=True))
Jon Salz0697cbf2012-07-04 15:14:04 +08001394 self.state_instance.del_shared_data('shutdown_time', optional=True)
Jon Salzb19ea072013-02-07 16:35:00 +08001395 self.state_instance.del_shared_data('startup_error', optional=True)
Jon Salz0697cbf2012-07-04 15:14:04 +08001396
Ricky Liang6fe218c2013-12-27 15:17:17 +08001397 self.options.automation_mode = ParseAutomationMode(
1398 self.options.automation_mode)
1399 self.state_instance.set_shared_data('automation_mode',
1400 self.options.automation_mode)
1401 self.state_instance.set_shared_data(
1402 'automation_mode_prompt',
1403 AutomationModePrompt[self.options.automation_mode])
1404
Jon Salz128b0932013-07-03 16:55:26 +08001405 try:
1406 self.InitTestLists()
1407 except: # pylint: disable=W0702
1408 logging.exception('Unable to initialize test lists')
1409 self.state_instance.set_shared_data(
1410 'startup_error',
1411 'Unable to initialize test lists\n%s' % (
1412 traceback.format_exc()))
Jon Salzb19ea072013-02-07 16:35:00 +08001413 if self.options.ui == 'chrome':
1414 # Create an empty test list with default options so that the rest of
1415 # startup can proceed.
1416 self.test_list = factory.FactoryTestList(
1417 [], self.state_instance, factory.Options())
1418 else:
1419 # Bail with an error; no point in starting up.
1420 sys.exit('No valid test list; exiting.')
1421
Shuo-Peng Liao268b40b2013-07-01 15:58:59 +08001422 self.init_hooks()
1423
Jon Salz822838b2013-03-25 17:32:33 +08001424 if self.test_list.options.clear_state_on_start:
1425 self.state_instance.clear_test_state()
1426
Jon Salz670ce062014-05-16 15:53:50 +08001427 # If the phase is invalid, this will raise a ValueError.
1428 phase.SetPersistentPhase(self.test_list.options.phase)
1429
Dean Liao85ca86f2014-11-03 12:28:08 +08001430 # For netboot firmware, mainfw_type should be 'netboot'.
1431 if (system.SystemInfo().mainfw_type != 'nonchrome' and
1432 system.SystemInfo().firmware_version is None):
Ricky Liang45c73e72015-01-15 15:00:30 +08001433 self.state_instance.set_shared_data(
1434 'startup_error',
Vic Yang9bd4f772013-06-04 17:34:00 +08001435 'Netboot firmware detected\n'
1436 'Connect Ethernet and reboot to re-image.\n'
1437 u'侦测到网路开机固件\n'
1438 u'请连接乙太网并重启')
1439
Jon Salz0697cbf2012-07-04 15:14:04 +08001440 if not self.state_instance.has_shared_data('ui_lang'):
1441 self.state_instance.set_shared_data('ui_lang',
Ricky Liang45c73e72015-01-15 15:00:30 +08001442 self.test_list.options.ui_lang)
Jon Salz0697cbf2012-07-04 15:14:04 +08001443 self.state_instance.set_shared_data(
Ricky Liang45c73e72015-01-15 15:00:30 +08001444 'test_list_options',
1445 self.test_list.options.__dict__)
Jon Salz0697cbf2012-07-04 15:14:04 +08001446 self.state_instance.test_list = self.test_list
1447
Cheng-Yi Chiang39d32ad2013-07-23 15:02:38 +08001448 self.check_log_rotation()
Jon Salz83ef34b2012-11-01 19:46:35 +08001449
Jon Salz23926422012-09-01 03:38:13 +08001450 if self.options.dummy_shopfloor:
Ricky Liang45c73e72015-01-15 15:00:30 +08001451 os.environ[shopfloor.SHOPFLOOR_SERVER_ENV_VAR_NAME] = (
1452 'http://%s:%d/' %
Joel Kitchingb85ed7f2014-10-08 18:24:39 +08001453 (net_utils.LOCALHOST, shopfloor.DEFAULT_SERVER_PORT))
Jon Salz23926422012-09-01 03:38:13 +08001454 self.dummy_shopfloor = Spawn(
1455 [os.path.join(factory.FACTORY_PATH, 'bin', 'shopfloor_server'),
1456 '--dummy'])
1457 elif self.test_list.options.shopfloor_server_url:
1458 shopfloor.set_server_url(self.test_list.options.shopfloor_server_url)
Jon Salz2bf2f6b2013-03-28 18:49:26 +08001459 shopfloor.set_enabled(True)
Jon Salz23926422012-09-01 03:38:13 +08001460
Jon Salz0f996602012-10-03 15:26:48 +08001461 if self.test_list.options.time_sanitizer and not utils.in_chroot():
Jon Salz8fa8e832012-07-13 19:04:09 +08001462 self.time_sanitizer = time_sanitizer.TimeSanitizer(
Ricky Liang45c73e72015-01-15 15:00:30 +08001463 base_time=time_sanitizer.GetBaseTimeFromFile(
1464 # lsb-factory is written by the factory install shim during
1465 # installation, so it should have a good time obtained from
1466 # the mini-Omaha server. If it's not available, we'll use
1467 # /etc/lsb-factory (which will be much older, but reasonably
1468 # sane) and rely on a shopfloor sync to set a more accurate
1469 # time.
1470 '/usr/local/etc/lsb-factory',
1471 '/etc/lsb-release'))
Jon Salz8fa8e832012-07-13 19:04:09 +08001472 self.time_sanitizer.RunOnce()
1473
Vic Yangd8990da2013-06-27 16:57:43 +08001474 if self.test_list.options.check_cpu_usage_period_secs:
Ricky Liang45c73e72015-01-15 15:00:30 +08001475 self.cpu_usage_watcher = Spawn(
1476 ['py/tools/cpu_usage_monitor.py', '-p',
1477 str(self.test_list.options.check_cpu_usage_period_secs)],
Vic Yangd8990da2013-06-27 16:57:43 +08001478 cwd=factory.FACTORY_PATH)
1479
Jon Salz0697cbf2012-07-04 15:14:04 +08001480 self.init_states()
1481 self.start_event_server()
Wei-Ning Huang38b75f02015-02-25 18:25:14 +08001482 self.start_terminal_server()
Hung-Te Lincc41d2a2014-10-29 13:35:20 +08001483
1484 if self.options.dummy_connection_manager:
1485 # Override network manager creation to dummy implmenetation.
1486 logging.info('Using dummy network manager (--dummy_connection_manager).')
1487 self.connection_manager = connection_manager.DummyConnectionManager()
1488 else:
1489 self.connection_manager = self.env.create_connection_manager(
1490 self.test_list.options.wlans,
Mao Huang4340c632015-04-14 14:35:22 +08001491 self.test_list.options.scan_wifi_period_secs,
1492 self.test_list.options.override_blacklisted_network_devices)
Hung-Te Lincc41d2a2014-10-29 13:35:20 +08001493
Jon Salz0697cbf2012-07-04 15:14:04 +08001494 # Note that we create a log watcher even if
1495 # sync_event_log_period_secs isn't set (no background
1496 # syncing), since we may use it to flush event logs as well.
1497 self.log_watcher = EventLogWatcher(
Ricky Liang45c73e72015-01-15 15:00:30 +08001498 self.test_list.options.sync_event_log_period_secs,
1499 event_log_db_file=None,
1500 handle_event_logs_callback=self.handle_event_logs)
Jon Salz0697cbf2012-07-04 15:14:04 +08001501 if self.test_list.options.sync_event_log_period_secs:
1502 self.log_watcher.StartWatchThread()
1503
Cheng-Yi Chianga0f6eff2014-01-09 18:27:22 +08001504 # Creates a system log manager to scan logs periocially.
1505 # A scan includes clearing logs and optionally syncing logs if
1506 # enable_syng_log is True. We kick it to sync logs.
1507 self.system_log_manager = SystemLogManager(
Ricky Liang45c73e72015-01-15 15:00:30 +08001508 sync_log_paths=self.test_list.options.sync_log_paths,
1509 sync_log_period_secs=self.test_list.options.sync_log_period_secs,
1510 scan_log_period_secs=self.test_list.options.scan_log_period_secs,
1511 clear_log_paths=self.test_list.options.clear_log_paths,
1512 clear_log_excluded_paths=self.test_list.options.clear_log_excluded_paths)
Cheng-Yi Chianga0f6eff2014-01-09 18:27:22 +08001513 self.system_log_manager.Start()
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +08001514
Jon Salz0697cbf2012-07-04 15:14:04 +08001515 self.update_system_info()
1516
Vic Yang4953fc12012-07-26 16:19:53 +08001517 assert ((self.test_list.options.min_charge_pct is None) ==
1518 (self.test_list.options.max_charge_pct is None))
Vic Yange83d9a12013-04-19 20:00:20 +08001519 if utils.in_chroot():
1520 logging.info('In chroot, ignoring charge manager and charge state')
Ricky Liangc392a1c2014-06-20 18:24:59 +08001521 elif (self.test_list.options.enable_charge_manager and
1522 self.test_list.options.min_charge_pct is not None):
Vic Yang4953fc12012-07-26 16:19:53 +08001523 self.charge_manager = ChargeManager(self.test_list.options.min_charge_pct,
1524 self.test_list.options.max_charge_pct)
Jon Salzad7353b2012-10-15 16:22:46 +08001525 system.SystemStatus.charge_manager = self.charge_manager
Cheng-Yi Chiangd8186952013-04-04 23:41:14 +08001526 else:
1527 # Goofy should set charger state to charge if charge_manager is disabled.
Dean Liao88b93192014-10-23 19:37:41 +08001528 self.charge()
Vic Yang4953fc12012-07-26 16:19:53 +08001529
Vic Yang6cee2472014-10-22 17:18:52 -07001530 if CoreDumpManager.CoreDumpEnabled():
1531 self.core_dump_manager = CoreDumpManager(
1532 self.test_list.options.core_dump_watchlist)
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001533
Jon Salz0697cbf2012-07-04 15:14:04 +08001534 os.environ['CROS_FACTORY'] = '1'
1535 os.environ['CROS_DISABLE_SITE_SYSINFO'] = '1'
1536
Shuo-Peng Liao1ff502e2013-06-30 18:37:02 +08001537 if not utils.in_chroot() and self.test_list.options.use_cpufreq_manager:
Ricky Liangecddbd42014-07-24 11:32:10 +08001538 logging.info('Enabling CPU frequency manager')
Jon Salzddf0d052013-06-18 12:52:44 +08001539 self.cpufreq_manager = CpufreqManager(event_log=self.event_log)
Jon Salzce6a7f82013-06-10 18:22:54 +08001540
Justin Chuang31b02432013-06-27 15:16:51 +08001541 # Startup hooks may want to skip some tests.
1542 self.update_skipped_tests()
Jon Salz416f9cc2013-05-10 18:32:50 +08001543
Jon Salze12c2b32013-06-25 16:24:34 +08001544 self.find_kcrashes()
1545
Shuo-Peng Liao268b40b2013-07-01 15:58:59 +08001546 # Should not move earlier.
1547 self.hooks.OnStartup()
1548
Ricky Liang36512a32014-07-25 11:47:04 +08001549 # Only after this point the Goofy backend is ready for UI connection.
1550 self.ready_for_ui_connection = True
1551
Ricky Liang650f6bf2012-09-28 13:22:54 +08001552 # Create download path for autotest beforehand or autotests run at
1553 # the same time might fail due to race condition.
1554 if not factory.in_chroot():
1555 utils.TryMakeDirs(os.path.join('/usr/local/autotest', 'tests',
1556 'download'))
1557
Jon Salz0697cbf2012-07-04 15:14:04 +08001558 def state_change_callback(test, test_state):
1559 self.event_client.post_event(
Ricky Liang4bff3e32014-02-20 18:46:11 +08001560 Event(Event.Type.STATE_CHANGE, path=test.path, state=test_state))
Jon Salz0697cbf2012-07-04 15:14:04 +08001561 self.test_list.state_change_callback = state_change_callback
Jon Salz73e0fd02012-04-04 11:46:38 +08001562
Vic Yange2c76a82014-10-30 12:48:19 -07001563 self.autotest_prespawner = prespawner.AutotestPrespawner()
1564 self.autotest_prespawner.start()
1565
1566 self.pytest_prespawner = prespawner.PytestPrespawner()
1567 self.pytest_prespawner.start()
Jon Salza6711d72012-07-18 14:33:03 +08001568
Ricky Liang48e47f92014-02-26 19:31:51 +08001569 tests_after_shutdown = self.state_instance.get_shared_data(
1570 'tests_after_shutdown', optional=True)
Jon Salz57717ca2012-04-04 16:47:25 +08001571
Jon Salz5c344f62012-07-13 14:31:16 +08001572 force_auto_run = (tests_after_shutdown == FORCE_AUTO_RUN)
1573 if not force_auto_run and tests_after_shutdown is not None:
Ricky Liang48e47f92014-02-26 19:31:51 +08001574 logging.info('Resuming tests after shutdown: %s', tests_after_shutdown)
Jon Salz0697cbf2012-07-04 15:14:04 +08001575 self.tests_to_run.extend(
Ricky Liang4bff3e32014-02-20 18:46:11 +08001576 self.test_list.lookup_path(t) for t in tests_after_shutdown)
Peter Ammon1e1ec572014-06-26 17:56:32 -07001577 self.run_enqueue(self.run_next_test)
Jon Salz0697cbf2012-07-04 15:14:04 +08001578 else:
Jon Salz5c344f62012-07-13 14:31:16 +08001579 if force_auto_run or self.test_list.options.auto_run_on_start:
Ricky Liang117484a2014-04-14 11:14:41 +08001580 # If automation mode is enabled, allow suppress auto_run_on_start.
1581 if (self.options.automation_mode == 'NONE' or
1582 self.options.auto_run_on_start):
Peter Ammon1e1ec572014-06-26 17:56:32 -07001583 self.run_enqueue(
Ricky Liang117484a2014-04-14 11:14:41 +08001584 lambda: self.run_tests(self.test_list, untested_only=True))
Jon Salz5c344f62012-07-13 14:31:16 +08001585 self.state_instance.set_shared_data('tests_after_shutdown', None)
Ricky Liang4bff3e32014-02-20 18:46:11 +08001586 self.restore_active_run_state()
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001587
Vic Yang08505c72015-01-06 17:01:53 -08001588 system.GetBoard().OnTestStart()
1589
Dean Liao592e4d52013-01-10 20:06:39 +08001590 self.may_disable_cros_shortcut_keys()
1591
1592 def may_disable_cros_shortcut_keys(self):
1593 test_options = self.test_list.options
1594 if test_options.disable_cros_shortcut_keys:
1595 logging.info('Filter ChromeOS shortcut keys.')
1596 self.key_filter = KeyFilter(
1597 unmap_caps_lock=test_options.disable_caps_lock,
1598 caps_lock_keycode=test_options.caps_lock_keycode)
1599 self.key_filter.Start()
1600
Jon Salz0e6532d2012-10-25 16:30:11 +08001601 def _should_sync_time(self, foreground=False):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001602 """Returns True if we should attempt syncing time with shopfloor.
Jon Salz0e6532d2012-10-25 16:30:11 +08001603
1604 Args:
1605 foreground: If True, synchronizes even if background syncing
1606 is disabled (e.g., in explicit sync requests from the
1607 SyncShopfloor test).
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001608 """
Jon Salz0e6532d2012-10-25 16:30:11 +08001609 return ((foreground or
1610 self.test_list.options.sync_time_period_secs) and
Jon Salz54882d02012-08-31 01:57:54 +08001611 self.time_sanitizer and
1612 (not self.time_synced) and
1613 (not factory.in_chroot()))
1614
Jon Salz0e6532d2012-10-25 16:30:11 +08001615 def sync_time_with_shopfloor_server(self, foreground=False):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001616 """Syncs time with shopfloor server, if not yet synced.
Jon Salz54882d02012-08-31 01:57:54 +08001617
Jon Salz0e6532d2012-10-25 16:30:11 +08001618 Args:
1619 foreground: If True, synchronizes even if background syncing
1620 is disabled (e.g., in explicit sync requests from the
1621 SyncShopfloor test).
1622
Jon Salz54882d02012-08-31 01:57:54 +08001623 Returns:
1624 False if no time sanitizer is available, or True if this sync (or a
1625 previous sync) succeeded.
1626
1627 Raises:
1628 Exception if unable to contact the shopfloor server.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001629 """
Jon Salz0e6532d2012-10-25 16:30:11 +08001630 if self._should_sync_time(foreground):
Jon Salz54882d02012-08-31 01:57:54 +08001631 self.time_sanitizer.SyncWithShopfloor()
1632 self.time_synced = True
1633 return self.time_synced
1634
Jon Salzb92c5112012-09-21 15:40:11 +08001635 def log_disk_space_stats(self):
Jon Salz18e0e022013-06-11 17:13:39 +08001636 if (utils.in_chroot() or
1637 not self.test_list.options.log_disk_space_period_secs):
Jon Salzb92c5112012-09-21 15:40:11 +08001638 return
1639
1640 now = time.time()
1641 if (self.last_log_disk_space_time and
1642 now - self.last_log_disk_space_time <
1643 self.test_list.options.log_disk_space_period_secs):
1644 return
1645 self.last_log_disk_space_time = now
1646
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001647 # Upload event if stateful partition usage is above threshold.
1648 # Stateful partition is mounted on /usr/local, while
1649 # encrypted stateful partition is mounted on /var.
1650 # If there are too much logs in the factory process,
1651 # these two partitions might get full.
Jon Salzb92c5112012-09-21 15:40:11 +08001652 try:
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001653 vfs_infos = disk_space.GetAllVFSInfo()
1654 stateful_info, encrypted_info = None, None
1655 for vfs_info in vfs_infos.values():
1656 if '/usr/local' in vfs_info.mount_points:
1657 stateful_info = vfs_info
1658 if '/var' in vfs_info.mount_points:
1659 encrypted_info = vfs_info
1660
1661 stateful = disk_space.GetPartitionUsage(stateful_info)
1662 encrypted = disk_space.GetPartitionUsage(encrypted_info)
1663
Ricky Liang45c73e72015-01-15 15:00:30 +08001664 above_threshold = (
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001665 self.test_list.options.stateful_usage_threshold and
1666 max(stateful.bytes_used_pct,
1667 stateful.inodes_used_pct,
1668 encrypted.bytes_used_pct,
1669 encrypted.inodes_used_pct) >
Ricky Liang45c73e72015-01-15 15:00:30 +08001670 self.test_list.options.stateful_usage_threshold)
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001671
1672 if above_threshold:
1673 self.event_log.Log('stateful_partition_usage',
Ricky Liang45c73e72015-01-15 15:00:30 +08001674 partitions={
1675 'stateful': {
1676 'bytes_used_pct': FloatDigit(stateful.bytes_used_pct, 2),
1677 'inodes_used_pct': FloatDigit(stateful.inodes_used_pct, 2)},
1678 'encrypted_stateful': {
1679 'bytes_used_pct': FloatDigit(encrypted.bytes_used_pct, 2),
1680 'inodes_used_pct': FloatDigit(encrypted.inodes_used_pct, 2)}
1681 })
Cheng-Yi Chiang1b722322015-03-16 20:07:03 +08001682 self.log_watcher.KickWatchThread()
Cheng-Yi Chiang00798e72013-06-20 18:16:39 +08001683 if (not utils.in_chroot() and
1684 self.test_list.options.stateful_usage_above_threshold_action):
1685 Spawn(self.test_list.options.stateful_usage_above_threshold_action,
1686 call=True)
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001687
1688 message = disk_space.FormatSpaceUsedAll(vfs_infos)
Jon Salz3c493bb2013-02-07 17:24:58 +08001689 if message != self.last_log_disk_space_message:
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001690 if above_threshold:
1691 logging.warning(message)
1692 else:
1693 logging.info(message)
Jon Salz3c493bb2013-02-07 17:24:58 +08001694 self.last_log_disk_space_message = message
Jon Salzb92c5112012-09-21 15:40:11 +08001695 except: # pylint: disable=W0702
1696 logging.exception('Unable to get disk space used')
1697
Justin Chuang83813982013-05-13 01:26:32 +08001698 def check_battery(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001699 """Checks the current battery status.
Justin Chuang83813982013-05-13 01:26:32 +08001700
1701 Logs current battery charging level and status to log. If the battery level
1702 is lower below warning_low_battery_pct, send warning event to shopfloor.
1703 If the battery level is lower below critical_low_battery_pct, flush disks.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001704 """
Justin Chuang83813982013-05-13 01:26:32 +08001705 if not self.test_list.options.check_battery_period_secs:
1706 return
1707
1708 now = time.time()
1709 if (self.last_check_battery_time and
1710 now - self.last_check_battery_time <
1711 self.test_list.options.check_battery_period_secs):
1712 return
1713 self.last_check_battery_time = now
1714
1715 message = ''
1716 log_level = logging.INFO
1717 try:
1718 power = system.GetBoard().power
1719 if not power.CheckBatteryPresent():
1720 message = 'Battery is not present'
1721 else:
1722 ac_present = power.CheckACPresent()
1723 charge_pct = power.GetChargePct(get_float=True)
1724 message = ('Current battery level %.1f%%, AC charger is %s' %
1725 (charge_pct, 'connected' if ac_present else 'disconnected'))
1726
1727 if charge_pct > self.test_list.options.critical_low_battery_pct:
1728 critical_low_battery = False
1729 else:
1730 critical_low_battery = True
1731 # Only sync disks when battery level is still above minimum
1732 # value. This can be used for offline analysis when shopfloor cannot
1733 # be connected.
1734 if charge_pct > MIN_BATTERY_LEVEL_FOR_DISK_SYNC:
1735 logging.warning('disk syncing for critical low battery situation')
1736 os.system('sync; sync; sync')
1737 else:
1738 logging.warning('disk syncing is cancelled '
1739 'because battery level is lower than %.1f',
1740 MIN_BATTERY_LEVEL_FOR_DISK_SYNC)
1741
1742 # Notify shopfloor server
1743 if (critical_low_battery or
1744 (not ac_present and
1745 charge_pct <= self.test_list.options.warning_low_battery_pct)):
1746 log_level = logging.WARNING
1747
1748 self.event_log.Log('low_battery',
1749 battery_level=charge_pct,
1750 charger_connected=ac_present,
1751 critical=critical_low_battery)
1752 self.log_watcher.KickWatchThread()
Cheng-Yi Chianga0f6eff2014-01-09 18:27:22 +08001753 if self.test_list.options.enable_sync_log:
1754 self.system_log_manager.KickToSync()
Ricky Liang45c73e72015-01-15 15:00:30 +08001755 except: # pylint: disable=W0702
Justin Chuang83813982013-05-13 01:26:32 +08001756 logging.exception('Unable to check battery or notify shopfloor')
1757 finally:
1758 if message != self.last_check_battery_message:
1759 logging.log(log_level, message)
1760 self.last_check_battery_message = message
1761
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001762 def check_core_dump(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001763 """Checks if there is any core dumped file.
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001764
1765 Removes unwanted core dump files immediately.
1766 Syncs those files matching watch list to server with a delay between
1767 each sync. After the files have been synced to server, deletes the files.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001768 """
Vic Yang6cee2472014-10-22 17:18:52 -07001769 if not self.core_dump_manager:
1770 return
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001771 core_dump_files = self.core_dump_manager.ScanFiles()
1772 if core_dump_files:
1773 now = time.time()
1774 if (self.last_kick_sync_time and now - self.last_kick_sync_time <
1775 self.test_list.options.kick_sync_min_interval_secs):
1776 return
1777 self.last_kick_sync_time = now
1778
1779 # Sends event to server
1780 self.event_log.Log('core_dumped', files=core_dump_files)
1781 self.log_watcher.KickWatchThread()
1782
1783 # Syncs files to server
Cheng-Yi Chianga0f6eff2014-01-09 18:27:22 +08001784 if self.test_list.options.enable_sync_log:
1785 self.system_log_manager.KickToSync(
Cheng-Yi Chiangd3516a32013-07-17 15:30:47 +08001786 core_dump_files, self.core_dump_manager.ClearFiles)
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001787
Cheng-Yi Chiang39d32ad2013-07-23 15:02:38 +08001788 def check_log_rotation(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001789 """Checks log rotation file presence/absence according to test_list option.
Cheng-Yi Chiang39d32ad2013-07-23 15:02:38 +08001790
1791 Touch /var/lib/cleanup_logs_paused if test_list.options.disable_log_rotation
1792 is True, delete it otherwise. This must be done in idle loop because
1793 autotest client will touch /var/lib/cleanup_logs_paused each time it runs
1794 an autotest.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001795 """
Cheng-Yi Chiang39d32ad2013-07-23 15:02:38 +08001796 if utils.in_chroot():
1797 return
1798 try:
1799 if self.test_list.options.disable_log_rotation:
1800 open(CLEANUP_LOGS_PAUSED, 'w').close()
1801 else:
1802 file_utils.TryUnlink(CLEANUP_LOGS_PAUSED)
1803 except: # pylint: disable=W0702
1804 # Oh well. Logs an error (but no trace)
1805 logging.info(
1806 'Unable to %s %s: %s',
1807 'touch' if self.test_list.options.disable_log_rotation else 'delete',
1808 CLEANUP_LOGS_PAUSED, utils.FormatExceptionOnly())
1809
Jon Salz8fa8e832012-07-13 19:04:09 +08001810 def sync_time_in_background(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001811 """Writes out current time and tries to sync with shopfloor server."""
Jon Salzb22d1172012-08-06 10:38:57 +08001812 if not self.time_sanitizer:
1813 return
1814
1815 # Write out the current time.
1816 self.time_sanitizer.SaveTime()
1817
Jon Salz54882d02012-08-31 01:57:54 +08001818 if not self._should_sync_time():
Jon Salz8fa8e832012-07-13 19:04:09 +08001819 return
1820
1821 now = time.time()
1822 if self.last_sync_time and (
1823 now - self.last_sync_time <
1824 self.test_list.options.sync_time_period_secs):
1825 # Not yet time for another check.
1826 return
1827 self.last_sync_time = now
1828
1829 def target():
1830 try:
Jon Salz54882d02012-08-31 01:57:54 +08001831 self.sync_time_with_shopfloor_server()
Jon Salz8fa8e832012-07-13 19:04:09 +08001832 except: # pylint: disable=W0702
1833 # Oh well. Log an error (but no trace)
1834 logging.info(
Ricky Liang45c73e72015-01-15 15:00:30 +08001835 'Unable to get time from shopfloor server: %s',
1836 utils.FormatExceptionOnly())
Jon Salz8fa8e832012-07-13 19:04:09 +08001837
1838 thread = threading.Thread(target=target)
1839 thread.daemon = True
1840 thread.start()
1841
Peter Ammon1e1ec572014-06-26 17:56:32 -07001842 def perform_periodic_tasks(self):
1843 """Override of base method to perform periodic work.
Vic Yang4953fc12012-07-26 16:19:53 +08001844
Peter Ammon1e1ec572014-06-26 17:56:32 -07001845 This method must not raise exceptions.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001846 """
Peter Ammon1e1ec572014-06-26 17:56:32 -07001847 super(Goofy, self).perform_periodic_tasks()
Jon Salzb22d1172012-08-06 10:38:57 +08001848
Vic Yang311ddb82012-09-26 12:08:28 +08001849 self.check_exclusive()
cychiang21886742012-07-05 15:16:32 +08001850 self.check_for_updates()
Jon Salz8fa8e832012-07-13 19:04:09 +08001851 self.sync_time_in_background()
Jon Salzb92c5112012-09-21 15:40:11 +08001852 self.log_disk_space_stats()
Justin Chuang83813982013-05-13 01:26:32 +08001853 self.check_battery()
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001854 self.check_core_dump()
Cheng-Yi Chiang39d32ad2013-07-23 15:02:38 +08001855 self.check_log_rotation()
Jon Salz57717ca2012-04-04 16:47:25 +08001856
Cheng-Yi Chiangf5b21012015-03-17 15:37:14 +08001857 def handle_event_logs(self, chunks, periodic=False):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001858 """Callback for event watcher.
Jon Salz258a40c2012-04-19 12:34:01 +08001859
Jon Salz0697cbf2012-07-04 15:14:04 +08001860 Attempts to upload the event logs to the shopfloor server.
Vic Yang93027612013-05-06 02:42:49 +08001861
1862 Args:
Jon Salzd15bbcf2013-05-21 17:33:57 +08001863 chunks: A list of Chunk objects.
Cheng-Yi Chiangf5b21012015-03-17 15:37:14 +08001864 periodic: This event log handling is periodic. Error messages
1865 will only be shown for the first time.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001866 """
Vic Yang93027612013-05-06 02:42:49 +08001867 first_exception = None
1868 exception_count = 0
Cheng-Yi Chiangf5b21012015-03-17 15:37:14 +08001869 # Suppress error messages for periodic event syncing except for the
1870 # first time. If event syncing is not periodic, always show the error
1871 # messages.
1872 quiet = self._suppress_event_log_error_messages if periodic else False
Vic Yang93027612013-05-06 02:42:49 +08001873
Jon Salzd15bbcf2013-05-21 17:33:57 +08001874 for chunk in chunks:
Vic Yang93027612013-05-06 02:42:49 +08001875 try:
Jon Salzcddb6402013-05-23 12:56:42 +08001876 description = 'event logs (%s)' % str(chunk)
Vic Yang93027612013-05-06 02:42:49 +08001877 start_time = time.time()
1878 shopfloor_client = shopfloor.get_instance(
Ricky Liang45c73e72015-01-15 15:00:30 +08001879 detect=True,
Cheng-Yi Chiangf5b21012015-03-17 15:37:14 +08001880 timeout=self.test_list.options.shopfloor_timeout_secs,
1881 quiet=quiet)
Ricky Liang45c73e72015-01-15 15:00:30 +08001882 shopfloor_client.UploadEvent(chunk.log_name + '.' +
Jon Salzd15bbcf2013-05-21 17:33:57 +08001883 event_log.GetReimageId(),
1884 Binary(chunk.chunk))
Vic Yang93027612013-05-06 02:42:49 +08001885 logging.info(
Ricky Liang45c73e72015-01-15 15:00:30 +08001886 'Successfully synced %s in %.03f s',
1887 description, time.time() - start_time)
1888 except: # pylint: disable=W0702
Jon Salzd15bbcf2013-05-21 17:33:57 +08001889 first_exception = (first_exception or (chunk.log_name + ': ' +
Vic Yang93027612013-05-06 02:42:49 +08001890 utils.FormatExceptionOnly()))
1891 exception_count += 1
1892
1893 if exception_count:
1894 if exception_count == 1:
1895 msg = 'Log upload failed: %s' % first_exception
1896 else:
1897 msg = '%d log upload failed; first is: %s' % (
1898 exception_count, first_exception)
Cheng-Yi Chiangf5b21012015-03-17 15:37:14 +08001899 # For periodic event log syncing, only show the first error messages.
1900 if periodic:
1901 if not self._suppress_event_log_error_messages:
1902 self._suppress_event_log_error_messages = True
1903 logging.warning('Suppress periodic shopfloor error messages for '
1904 'event log syncing after the first one.')
1905 raise Exception(msg)
1906 # For event log syncing by request, show the error messages.
1907 else:
1908 raise Exception(msg)
Vic Yang93027612013-05-06 02:42:49 +08001909
Ricky Liang45c73e72015-01-15 15:00:30 +08001910 def run_tests_with_status(self, statuses_to_run, starting_at=None, root=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001911 """Runs all top-level tests with a particular status.
Jon Salz0405ab52012-03-16 15:26:52 +08001912
Jon Salz0697cbf2012-07-04 15:14:04 +08001913 All active tests, plus any tests to re-run, are reset.
Jon Salz57717ca2012-04-04 16:47:25 +08001914
Jon Salz0697cbf2012-07-04 15:14:04 +08001915 Args:
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001916 statuses_to_run: The particular status that caller wants to run.
Jon Salz0697cbf2012-07-04 15:14:04 +08001917 starting_at: If provided, only auto-runs tests beginning with
1918 this test.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001919 root: The root of tests to run. If not provided, it will be
1920 the root of all tests.
1921 """
Jon Salz0697cbf2012-07-04 15:14:04 +08001922 root = root or self.test_list
Jon Salz57717ca2012-04-04 16:47:25 +08001923
Jon Salz0697cbf2012-07-04 15:14:04 +08001924 if starting_at:
1925 # Make sure they passed a test, not a string.
1926 assert isinstance(starting_at, factory.FactoryTest)
Jon Salz0405ab52012-03-16 15:26:52 +08001927
Jon Salz0697cbf2012-07-04 15:14:04 +08001928 tests_to_reset = []
1929 tests_to_run = []
Jon Salz0405ab52012-03-16 15:26:52 +08001930
Jon Salz0697cbf2012-07-04 15:14:04 +08001931 found_starting_at = False
Jon Salz0405ab52012-03-16 15:26:52 +08001932
Jon Salz0697cbf2012-07-04 15:14:04 +08001933 for test in root.get_top_level_tests():
1934 if starting_at:
1935 if test == starting_at:
1936 # We've found starting_at; do auto-run on all
1937 # subsequent tests.
1938 found_starting_at = True
1939 if not found_starting_at:
1940 # Don't start this guy yet
1941 continue
Jon Salz0405ab52012-03-16 15:26:52 +08001942
Jon Salz0697cbf2012-07-04 15:14:04 +08001943 status = test.get_state().status
1944 if status == TestState.ACTIVE or status in statuses_to_run:
1945 # Reset the test (later; we will need to abort
1946 # all active tests first).
1947 tests_to_reset.append(test)
1948 if status in statuses_to_run:
1949 tests_to_run.append(test)
Jon Salz0405ab52012-03-16 15:26:52 +08001950
Jon Salz6dc031d2013-06-19 13:06:23 +08001951 self.abort_active_tests('Operator requested run/re-run of certain tests')
Jon Salz258a40c2012-04-19 12:34:01 +08001952
Jon Salz0697cbf2012-07-04 15:14:04 +08001953 # Reset all statuses of the tests to run (in case any tests were active;
1954 # we want them to be run again).
1955 for test_to_reset in tests_to_reset:
1956 for test in test_to_reset.walk():
1957 test.update_state(status=TestState.UNTESTED)
Jon Salz57717ca2012-04-04 16:47:25 +08001958
Jon Salz0697cbf2012-07-04 15:14:04 +08001959 self.run_tests(tests_to_run, untested_only=True)
Jon Salz0405ab52012-03-16 15:26:52 +08001960
Jon Salz0697cbf2012-07-04 15:14:04 +08001961 def restart_tests(self, root=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001962 """Restarts all tests."""
Jon Salz0697cbf2012-07-04 15:14:04 +08001963 root = root or self.test_list
Jon Salz0405ab52012-03-16 15:26:52 +08001964
Jon Salz6dc031d2013-06-19 13:06:23 +08001965 self.abort_active_tests('Operator requested restart of certain tests')
Jon Salz0697cbf2012-07-04 15:14:04 +08001966 for test in root.walk():
Ricky Liangfea4ac92014-08-21 11:55:59 +08001967 test.update_state(status=TestState.UNTESTED)
Jon Salz0697cbf2012-07-04 15:14:04 +08001968 self.run_tests(root)
Hung-Te Lin96632362012-03-20 21:14:18 +08001969
Jon Salz0697cbf2012-07-04 15:14:04 +08001970 def auto_run(self, starting_at=None, root=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001971 """"Auto-runs" tests that have not been run yet.
Hung-Te Lin96632362012-03-20 21:14:18 +08001972
Jon Salz0697cbf2012-07-04 15:14:04 +08001973 Args:
1974 starting_at: If provide, only auto-runs tests beginning with
1975 this test.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001976 root: If provided, the root of tests to run. If not provided, the root
1977 will be test_list (root of all tests).
1978 """
Jon Salz0697cbf2012-07-04 15:14:04 +08001979 root = root or self.test_list
1980 self.run_tests_with_status([TestState.UNTESTED, TestState.ACTIVE],
Ricky Liang45c73e72015-01-15 15:00:30 +08001981 starting_at=starting_at,
1982 root=root)
Jon Salz968e90b2012-03-18 16:12:43 +08001983
Jon Salz0697cbf2012-07-04 15:14:04 +08001984 def re_run_failed(self, root=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001985 """Re-runs failed tests."""
Jon Salz0697cbf2012-07-04 15:14:04 +08001986 root = root or self.test_list
1987 self.run_tests_with_status([TestState.FAILED], root=root)
Jon Salz57717ca2012-04-04 16:47:25 +08001988
Jon Salz0697cbf2012-07-04 15:14:04 +08001989 def show_review_information(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001990 """Event handler for showing review information screen.
Jon Salz57717ca2012-04-04 16:47:25 +08001991
Peter Ammon1e1ec572014-06-26 17:56:32 -07001992 The information screen is rendered by main UI program (ui.py), so in
Jon Salz0697cbf2012-07-04 15:14:04 +08001993 goofy we only need to kill all active tests, set them as untested, and
1994 clear remaining tests.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001995 """
Jon Salz0697cbf2012-07-04 15:14:04 +08001996 self.kill_active_tests(False)
Jon Salza6711d72012-07-18 14:33:03 +08001997 self.cancel_pending_tests()
Jon Salz57717ca2012-04-04 16:47:25 +08001998
Jon Salz0697cbf2012-07-04 15:14:04 +08001999 def handle_switch_test(self, event):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08002000 """Switches to a particular test.
Jon Salz0405ab52012-03-16 15:26:52 +08002001
Ricky Liang6fe218c2013-12-27 15:17:17 +08002002 Args:
2003 event: The SWITCH_TEST event.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08002004 """
Jon Salz0697cbf2012-07-04 15:14:04 +08002005 test = self.test_list.lookup_path(event.path)
2006 if not test:
2007 logging.error('Unknown test %r', event.key)
2008 return
Jon Salz73e0fd02012-04-04 11:46:38 +08002009
Jon Salz0697cbf2012-07-04 15:14:04 +08002010 invoc = self.invocations.get(test)
2011 if invoc and test.backgroundable:
2012 # Already running: just bring to the front if it
2013 # has a UI.
2014 logging.info('Setting visible test to %s', test.path)
Jon Salz36fbbb52012-07-05 13:45:06 +08002015 self.set_visible_test(test)
Jon Salz0697cbf2012-07-04 15:14:04 +08002016 return
Jon Salz73e0fd02012-04-04 11:46:38 +08002017
Jon Salz6dc031d2013-06-19 13:06:23 +08002018 self.abort_active_tests('Operator requested abort (switch_test)')
Jon Salz0697cbf2012-07-04 15:14:04 +08002019 for t in test.walk():
2020 t.update_state(status=TestState.UNTESTED)
Jon Salz73e0fd02012-04-04 11:46:38 +08002021
Jon Salz0697cbf2012-07-04 15:14:04 +08002022 if self.test_list.options.auto_run_on_keypress:
2023 self.auto_run(starting_at=test)
2024 else:
2025 self.run_tests(test)
Jon Salz73e0fd02012-04-04 11:46:38 +08002026
Wei-Ning Huang38b75f02015-02-25 18:25:14 +08002027 def handle_key_filter_mode(self, event):
2028 if self.key_filter:
2029 if getattr(event, 'enabled'):
2030 self.key_filter.Start()
2031 else:
2032 self.key_filter.Stop()
2033
Jon Salz0697cbf2012-07-04 15:14:04 +08002034 def wait(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08002035 """Waits for all pending invocations.
Jon Salz0697cbf2012-07-04 15:14:04 +08002036
2037 Useful for testing.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08002038 """
Jon Salz1acc8742012-07-17 17:45:55 +08002039 while self.invocations:
2040 for k, v in self.invocations.iteritems():
2041 logging.info('Waiting for %s to complete...', k)
2042 v.thread.join()
2043 self.reap_completed_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +08002044
Hung-Te Linf2f78f72012-02-08 19:27:11 +08002045if __name__ == '__main__':
Peter Ammona3d298c2014-09-23 10:11:02 -07002046 Goofy.run_main_and_exit()