blob: ad32d81bd35fb6a8bb0ae2793134cad0c220b7b4 [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
Jon Salz8fa8e832012-07-13 19:04:09 +0800188 self.last_sync_time = None
Jon Salzb92c5112012-09-21 15:40:11 +0800189 self.last_log_disk_space_time = None
Jon Salz3c493bb2013-02-07 17:24:58 +0800190 self.last_log_disk_space_message = None
Justin Chuang83813982013-05-13 01:26:32 +0800191 self.last_check_battery_time = None
192 self.last_check_battery_message = None
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +0800193 self.last_kick_sync_time = None
Vic Yang311ddb82012-09-26 12:08:28 +0800194 self.exclusive_items = set()
Jon Salz0f996602012-10-03 15:26:48 +0800195 self.event_log = None
Dean Liao592e4d52013-01-10 20:06:39 +0800196 self.key_filter = None
Jon Salzce6a7f82013-06-10 18:22:54 +0800197 self.cpufreq_manager = None
Jon Salzd7550792013-07-12 05:49:27 +0800198 self.status = Status.UNINITIALIZED
Ricky Liang36512a32014-07-25 11:47:04 +0800199 self.ready_for_ui_connection = False
Peter Ammon1e1ec572014-06-26 17:56:32 -0700200 self.link_manager = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800201
Jon Salz85a39882012-07-05 16:45:04 +0800202 def test_or_root(event, parent_or_group=True):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800203 """Returns the test affected by a particular event.
Jon Salz85a39882012-07-05 16:45:04 +0800204
205 Args:
206 event: The event containing an optional 'path' attribute.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800207 parent_or_group: If True, returns the top-level parent for a test (the
Jon Salz85a39882012-07-05 16:45:04 +0800208 root node of the tests that need to be run together if the given test
209 path is to be run).
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800210 """
Jon Salz0697cbf2012-07-04 15:14:04 +0800211 try:
212 path = event.path
213 except AttributeError:
214 path = None
215
216 if path:
Jon Salz85a39882012-07-05 16:45:04 +0800217 test = self.test_list.lookup_path(path)
218 if parent_or_group:
219 test = test.get_top_level_parent_or_group()
220 return test
Jon Salz0697cbf2012-07-04 15:14:04 +0800221 else:
222 return self.test_list
223
224 self.event_handlers = {
Ricky Liang45c73e72015-01-15 15:00:30 +0800225 Event.Type.SWITCH_TEST: self.handle_switch_test,
226 Event.Type.SHOW_NEXT_ACTIVE_TEST:
227 lambda event: self.show_next_active_test(),
228 Event.Type.RESTART_TESTS:
229 lambda event: self.restart_tests(root=test_or_root(event)),
230 Event.Type.AUTO_RUN:
231 lambda event: self.auto_run(root=test_or_root(event)),
232 Event.Type.RE_RUN_FAILED:
233 lambda event: self.re_run_failed(root=test_or_root(event)),
234 Event.Type.RUN_TESTS_WITH_STATUS:
235 lambda event: self.run_tests_with_status(
236 event.status,
237 root=test_or_root(event)),
238 Event.Type.REVIEW:
239 lambda event: self.show_review_information(),
240 Event.Type.UPDATE_SYSTEM_INFO:
241 lambda event: self.update_system_info(),
242 Event.Type.STOP:
243 lambda event: self.stop(root=test_or_root(event, False),
244 fail=getattr(event, 'fail', False),
245 reason=getattr(event, 'reason', None)),
246 Event.Type.SET_VISIBLE_TEST:
247 lambda event: self.set_visible_test(
248 self.test_list.lookup_path(event.path)),
249 Event.Type.CLEAR_STATE:
250 lambda event: self.clear_state(
251 self.test_list.lookup_path(event.path)),
Wei-Ning Huang38b75f02015-02-25 18:25:14 +0800252 Event.Type.KEY_FILTER_MODE: self.handle_key_filter_mode,
Jon Salz0697cbf2012-07-04 15:14:04 +0800253 }
254
Jon Salz0697cbf2012-07-04 15:14:04 +0800255 self.web_socket_manager = None
Wei-Ning Huang38b75f02015-02-25 18:25:14 +0800256 self.terminal_manager = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800257
258 def destroy(self):
Ricky Liang74237a02014-09-18 15:11:23 +0800259 """Performs any shutdown tasks. Overrides base class method."""
Jon Salzd7550792013-07-12 05:49:27 +0800260 self.status = Status.TERMINATING
Jon Salz0697cbf2012-07-04 15:14:04 +0800261 if self.chrome:
262 self.chrome.kill()
263 self.chrome = None
Jon Salzc79a9982012-08-30 04:42:01 +0800264 if self.dummy_shopfloor:
265 self.dummy_shopfloor.kill()
266 self.dummy_shopfloor = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800267 if self.ui_process:
268 utils.kill_process_tree(self.ui_process, 'ui')
269 self.ui_process = None
270 if self.web_socket_manager:
271 logging.info('Stopping web sockets')
272 self.web_socket_manager.close()
273 self.web_socket_manager = None
274 if self.state_server_thread:
275 logging.info('Stopping state server')
276 self.state_server.shutdown()
277 self.state_server_thread.join()
278 self.state_server.server_close()
279 self.state_server_thread = None
280 if self.state_instance:
281 self.state_instance.close()
282 if self.event_server_thread:
283 logging.info('Stopping event server')
284 self.event_server.shutdown() # pylint: disable=E1101
285 self.event_server_thread.join()
286 self.event_server.server_close()
287 self.event_server_thread = None
288 if self.log_watcher:
289 if self.log_watcher.IsThreadStarted():
290 self.log_watcher.StopWatchThread()
291 self.log_watcher = None
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +0800292 if self.system_log_manager:
293 if self.system_log_manager.IsThreadRunning():
Cheng-Yi Chianga0f6eff2014-01-09 18:27:22 +0800294 self.system_log_manager.Stop()
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +0800295 self.system_log_manager = None
Vic Yange2c76a82014-10-30 12:48:19 -0700296 if self.autotest_prespawner:
297 logging.info('Stopping autotest prespawner')
298 self.autotest_prespawner.stop()
299 self.autotest_prespawner = None
300 if self.pytest_prespawner:
301 logging.info('Stopping pytest prespawner')
302 self.pytest_prespawner.stop()
303 self.pytest_prespawner = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800304 if self.event_client:
305 logging.info('Closing event client')
306 self.event_client.close()
307 self.event_client = None
Jon Salzddf0d052013-06-18 12:52:44 +0800308 if self.cpufreq_manager:
309 self.cpufreq_manager.Stop()
Jon Salz0697cbf2012-07-04 15:14:04 +0800310 if self.event_log:
311 self.event_log.Close()
312 self.event_log = None
Dean Liao592e4d52013-01-10 20:06:39 +0800313 if self.key_filter:
314 self.key_filter.Stop()
Vic Yangd8990da2013-06-27 16:57:43 +0800315 if self.cpu_usage_watcher:
316 self.cpu_usage_watcher.terminate()
Peter Ammon1e1ec572014-06-26 17:56:32 -0700317 if self.link_manager:
318 self.link_manager.Stop()
319 self.link_manager = None
Dean Liao592e4d52013-01-10 20:06:39 +0800320
Peter Ammon1e1ec572014-06-26 17:56:32 -0700321 super(Goofy, self).destroy()
Jon Salz0697cbf2012-07-04 15:14:04 +0800322 logging.info('Done destroying Goofy')
Jon Salzd7550792013-07-12 05:49:27 +0800323 self.status = Status.TERMINATED
Jon Salz0697cbf2012-07-04 15:14:04 +0800324
325 def start_state_server(self):
Jon Salz2af235d2013-06-24 14:47:21 +0800326 # Before starting state server, remount stateful partitions with
327 # no commit flag. The default commit time (commit=600) makes corruption
328 # too likely.
Hung-Te Lind59dbfa2014-08-27 12:27:53 +0800329 utils.ResetCommitTime()
Jon Salz2af235d2013-06-24 14:47:21 +0800330
Jon Salz0697cbf2012-07-04 15:14:04 +0800331 self.state_instance, self.state_server = (
Ricky Liang45c73e72015-01-15 15:00:30 +0800332 state.create_server(bind_address='0.0.0.0'))
Jon Salz16d10542012-07-23 12:18:45 +0800333 self.goofy_rpc = GoofyRPC(self)
334 self.goofy_rpc.RegisterMethods(self.state_instance)
Jon Salz0697cbf2012-07-04 15:14:04 +0800335 logging.info('Starting state server')
336 self.state_server_thread = threading.Thread(
Ricky Liang45c73e72015-01-15 15:00:30 +0800337 target=self.state_server.serve_forever,
338 name='StateServer')
Jon Salz0697cbf2012-07-04 15:14:04 +0800339 self.state_server_thread.start()
340
341 def start_event_server(self):
342 self.event_server = EventServer()
343 logging.info('Starting factory event server')
344 self.event_server_thread = threading.Thread(
Ricky Liang45c73e72015-01-15 15:00:30 +0800345 target=self.event_server.serve_forever,
346 name='EventServer') # pylint: disable=E1101
Jon Salz0697cbf2012-07-04 15:14:04 +0800347 self.event_server_thread.start()
348
349 self.event_client = EventClient(
Ricky Liang45c73e72015-01-15 15:00:30 +0800350 callback=self.handle_event, event_loop=self.run_queue)
Jon Salz0697cbf2012-07-04 15:14:04 +0800351
352 self.web_socket_manager = WebSocketManager(self.uuid)
Ricky Liang45c73e72015-01-15 15:00:30 +0800353 self.state_server.add_handler('/event',
354 self.web_socket_manager.handle_web_socket)
Jon Salz0697cbf2012-07-04 15:14:04 +0800355
Wei-Ning Huang38b75f02015-02-25 18:25:14 +0800356 def start_terminal_server(self):
357 self.terminal_manager = TerminalManager()
358 self.state_server.add_handler('/pty',
359 self.terminal_manager.handle_web_socket)
360
Jon Salz0697cbf2012-07-04 15:14:04 +0800361 def start_ui(self):
362 ui_proc_args = [
Ricky Liang45c73e72015-01-15 15:00:30 +0800363 os.path.join(factory.FACTORY_PACKAGE_PATH, 'test', 'ui.py'),
364 self.options.test_list
365 ]
Jon Salz0697cbf2012-07-04 15:14:04 +0800366 if self.options.verbose:
367 ui_proc_args.append('-v')
368 logging.info('Starting ui %s', ui_proc_args)
Jon Salz78c32392012-07-25 14:18:29 +0800369 self.ui_process = Spawn(ui_proc_args)
Jon Salz0697cbf2012-07-04 15:14:04 +0800370 logging.info('Waiting for UI to come up...')
371 self.event_client.wait(
Ricky Liang45c73e72015-01-15 15:00:30 +0800372 lambda event: event.type == Event.Type.UI_READY)
Jon Salz0697cbf2012-07-04 15:14:04 +0800373 logging.info('UI has started')
374
375 def set_visible_test(self, test):
376 if self.visible_test == test:
377 return
Jon Salz2f2d42c2012-07-30 12:30:34 +0800378 if test and not test.has_ui:
379 return
Jon Salz0697cbf2012-07-04 15:14:04 +0800380
381 if test:
382 test.update_state(visible=True)
383 if self.visible_test:
384 self.visible_test.update_state(visible=False)
385 self.visible_test = test
386
Ricky Liang48e47f92014-02-26 19:31:51 +0800387 def log_startup_messages(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800388 """Logs the tail of var/log/messages and mosys and EC console logs."""
Jon Salzd4306c82012-11-30 15:16:36 +0800389 # TODO(jsalz): This is mostly a copy-and-paste of code in init_states,
390 # for factory-3004.B only. Consolidate and merge back to ToT.
391 if utils.in_chroot():
392 return
393
394 try:
Ricky Liang45c73e72015-01-15 15:00:30 +0800395 var_log_messages = utils.var_log_messages_before_reboot()
Jon Salzd4306c82012-11-30 15:16:36 +0800396 logging.info(
Ricky Liang45c73e72015-01-15 15:00:30 +0800397 'Tail of /var/log/messages before last reboot:\n'
398 '%s', ('\n'.join(
399 ' ' + x for x in var_log_messages)))
Jon Salzd4306c82012-11-30 15:16:36 +0800400 except: # pylint: disable=W0702
401 logging.exception('Unable to grok /var/log/messages')
402
403 try:
Ricky Liang117484a2014-04-14 11:14:41 +0800404 mosys_log = Spawn(
Jon Salzd4306c82012-11-30 15:16:36 +0800405 ['mosys', 'eventlog', 'list'],
406 read_stdout=True, log_stderr_on_error=True).stdout_data
407 logging.info('System eventlog from mosys:\n%s\n', mosys_log)
408 except: # pylint: disable=W0702
409 logging.exception('Unable to read mosys eventlog')
410
Dean Liao88b93192014-10-23 19:37:41 +0800411 self.log_ec_console()
412 self.log_ec_panic_info()
413
414 @staticmethod
415 def log_ec_console():
416 """Logs EC console log into logging.info.
417
418 It logs an error message in logging.exception if an exception is raised
419 when getting EC console log.
420 For unsupported device, it logs unsupport message in logging.info
421
422 Returns:
423 EC console log string.
424 """
Jon Salzd4306c82012-11-30 15:16:36 +0800425 try:
Vic Yang8341dde2013-01-29 16:48:52 +0800426 board = system.GetBoard()
427 ec_console_log = board.GetECConsoleLog()
Jon Salzd4306c82012-11-30 15:16:36 +0800428 logging.info('EC console log after reboot:\n%s\n', ec_console_log)
Dean Liao88b93192014-10-23 19:37:41 +0800429 return ec_console_log
430 except NotImplementedError:
431 logging.info('EC console log not supported')
Jon Salzd4306c82012-11-30 15:16:36 +0800432 except: # pylint: disable=W0702
433 logging.exception('Error retrieving EC console log')
434
Dean Liao88b93192014-10-23 19:37:41 +0800435 @staticmethod
436 def log_ec_panic_info():
437 """Logs EC panic info into logging.info.
438
439 It logs an error message in logging.exception if an exception is raised
440 when getting EC panic info.
441 For unsupported device, it logs unsupport message in logging.info
442
443 Returns:
444 EC panic info string.
445 """
Vic Yang079f9872013-07-01 11:32:00 +0800446 try:
447 board = system.GetBoard()
448 ec_panic_info = board.GetECPanicInfo()
449 logging.info('EC panic info after reboot:\n%s\n', ec_panic_info)
Dean Liao88b93192014-10-23 19:37:41 +0800450 return ec_panic_info
451 except NotImplementedError:
452 logging.info('EC panic info is not supported')
Vic Yang079f9872013-07-01 11:32:00 +0800453 except: # pylint: disable=W0702
454 logging.exception('Error retrieving EC panic info')
455
Ricky Liang48e47f92014-02-26 19:31:51 +0800456 def shutdown(self, operation):
457 """Starts shutdown procedure.
458
459 Args:
Vic (Chun-Ju) Yang05b0d952014-04-28 17:39:09 +0800460 operation: The shutdown operation (reboot, full_reboot, or halt).
Ricky Liang48e47f92014-02-26 19:31:51 +0800461 """
462 active_tests = []
463 for test in self.test_list.walk():
464 if not test.is_leaf():
465 continue
466
467 test_state = test.get_state()
468 if test_state.status == TestState.ACTIVE:
469 active_tests.append(test)
470
Ricky Liang48e47f92014-02-26 19:31:51 +0800471 if not (len(active_tests) == 1 and
472 isinstance(active_tests[0], factory.ShutdownStep)):
473 logging.error(
474 'Calling Goofy shutdown outside of the shutdown factory test')
475 return
476
477 logging.info('Start Goofy shutdown (%s)', operation)
478 # Save pending test list in the state server
479 self.state_instance.set_shared_data(
480 'tests_after_shutdown',
481 [t.path for t in self.tests_to_run])
482 # Save shutdown time
483 self.state_instance.set_shared_data('shutdown_time', time.time())
484
485 with self.env.lock:
486 self.event_log.Log('shutdown', operation=operation)
487 shutdown_result = self.env.shutdown(operation)
488 if shutdown_result:
489 # That's all, folks!
Peter Ammon1e1ec572014-06-26 17:56:32 -0700490 self.run_enqueue(None)
Ricky Liang48e47f92014-02-26 19:31:51 +0800491 else:
492 # Just pass (e.g., in the chroot).
493 self.state_instance.set_shared_data('tests_after_shutdown', None)
494 # Send event with no fields to indicate that there is no
495 # longer a pending shutdown.
496 self.event_client.post_event(Event(Event.Type.PENDING_SHUTDOWN))
497
498 def handle_shutdown_complete(self, test):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800499 """Handles the case where a shutdown was detected during a shutdown step.
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800500
Ricky Liang6fe218c2013-12-27 15:17:17 +0800501 Args:
502 test: The ShutdownStep.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800503 """
Jon Salz0697cbf2012-07-04 15:14:04 +0800504 test_state = test.update_state(increment_shutdown_count=1)
505 logging.info('Detected shutdown (%d of %d)',
Ricky Liang48e47f92014-02-26 19:31:51 +0800506 test_state.shutdown_count, test.iterations)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800507
Ricky Liang48e47f92014-02-26 19:31:51 +0800508 # Insert current shutdown test at the front of the list of tests to run
509 # after shutdown. This is to continue on post-shutdown verification in the
510 # shutdown step.
511 tests_after_shutdown = self.state_instance.get_shared_data(
512 'tests_after_shutdown', optional=True)
513 if not tests_after_shutdown:
514 self.state_instance.set_shared_data('tests_after_shutdown', [test.path])
515 elif isinstance(tests_after_shutdown, list):
516 self.state_instance.set_shared_data(
517 'tests_after_shutdown', [test.path] + tests_after_shutdown)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800518
Ricky Liang48e47f92014-02-26 19:31:51 +0800519 # Set 'post_shutdown' to inform shutdown test that a shutdown just occurred.
Ricky Liangb7eb8772014-09-15 18:05:22 +0800520 self.state_instance.set_shared_data(
521 state.POST_SHUTDOWN_TAG % test.path,
522 self.state_instance.get_test_state(test.path).invocation)
Jon Salz258a40c2012-04-19 12:34:01 +0800523
Jon Salz0697cbf2012-07-04 15:14:04 +0800524 def init_states(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800525 """Initializes all states on startup."""
Jon Salz0697cbf2012-07-04 15:14:04 +0800526 for test in self.test_list.get_all_tests():
527 # Make sure the state server knows about all the tests,
528 # defaulting to an untested state.
529 test.update_state(update_parent=False, visible=False)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800530
Jon Salz0697cbf2012-07-04 15:14:04 +0800531 var_log_messages = None
Vic Yanga9c32212012-08-16 20:07:54 +0800532 mosys_log = None
Vic Yange4c275d2012-08-28 01:50:20 +0800533 ec_console_log = None
Vic Yang079f9872013-07-01 11:32:00 +0800534 ec_panic_info = None
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800535
Jon Salz0697cbf2012-07-04 15:14:04 +0800536 # Any 'active' tests should be marked as failed now.
537 for test in self.test_list.walk():
Jon Salza6711d72012-07-18 14:33:03 +0800538 if not test.is_leaf():
539 # Don't bother with parents; they will be updated when their
540 # children are updated.
541 continue
542
Jon Salz0697cbf2012-07-04 15:14:04 +0800543 test_state = test.get_state()
544 if test_state.status != TestState.ACTIVE:
545 continue
546 if isinstance(test, factory.ShutdownStep):
547 # Shutdown while the test was active - that's good.
Ricky Liang48e47f92014-02-26 19:31:51 +0800548 self.handle_shutdown_complete(test)
Jon Salz0697cbf2012-07-04 15:14:04 +0800549 else:
550 # Unexpected shutdown. Grab /var/log/messages for context.
551 if var_log_messages is None:
552 try:
553 var_log_messages = (
Ricky Liang45c73e72015-01-15 15:00:30 +0800554 utils.var_log_messages_before_reboot())
Jon Salz0697cbf2012-07-04 15:14:04 +0800555 # Write it to the log, to make it easier to
556 # correlate with /var/log/messages.
557 logging.info(
Ricky Liang45c73e72015-01-15 15:00:30 +0800558 'Unexpected shutdown. '
559 'Tail of /var/log/messages before last reboot:\n'
560 '%s', ('\n'.join(
561 ' ' + x for x in var_log_messages)))
Jon Salz0697cbf2012-07-04 15:14:04 +0800562 except: # pylint: disable=W0702
563 logging.exception('Unable to grok /var/log/messages')
564 var_log_messages = []
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800565
Jon Salz008f4ea2012-08-28 05:39:45 +0800566 if mosys_log is None and not utils.in_chroot():
567 try:
Ricky Liang117484a2014-04-14 11:14:41 +0800568 mosys_log = Spawn(
Jon Salz008f4ea2012-08-28 05:39:45 +0800569 ['mosys', 'eventlog', 'list'],
570 read_stdout=True, log_stderr_on_error=True).stdout_data
571 # Write it to the log also.
572 logging.info('System eventlog from mosys:\n%s\n', mosys_log)
573 except: # pylint: disable=W0702
574 logging.exception('Unable to read mosys eventlog')
Vic Yanga9c32212012-08-16 20:07:54 +0800575
Vic Yange4c275d2012-08-28 01:50:20 +0800576 if ec_console_log is None:
Dean Liao88b93192014-10-23 19:37:41 +0800577 ec_console_log = self.log_ec_console()
Vic Yange4c275d2012-08-28 01:50:20 +0800578
Vic Yang079f9872013-07-01 11:32:00 +0800579 if ec_panic_info is None:
Dean Liao88b93192014-10-23 19:37:41 +0800580 ec_panic_info = self.log_ec_panic_info()
Vic Yang079f9872013-07-01 11:32:00 +0800581
Jon Salz0697cbf2012-07-04 15:14:04 +0800582 error_msg = 'Unexpected shutdown while test was running'
583 self.event_log.Log('end_test',
Ricky Liang45c73e72015-01-15 15:00:30 +0800584 path=test.path,
585 status=TestState.FAILED,
586 invocation=test.get_state().invocation,
587 error_msg=error_msg,
588 var_log_messages='\n'.join(var_log_messages),
589 mosys_log=mosys_log)
Jon Salz0697cbf2012-07-04 15:14:04 +0800590 test.update_state(
Ricky Liang45c73e72015-01-15 15:00:30 +0800591 status=TestState.FAILED,
592 error_msg=error_msg)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800593
Jon Salz50efe942012-07-26 11:54:10 +0800594 if not test.never_fails:
595 # For "never_fails" tests (such as "Start"), don't cancel
596 # pending tests, since reboot is expected.
597 factory.console.info('Unexpected shutdown while test %s '
598 'running; cancelling any pending tests',
599 test.path)
600 self.state_instance.set_shared_data('tests_after_shutdown', [])
Jon Salz69806bb2012-07-20 18:05:02 +0800601
Jon Salz008f4ea2012-08-28 05:39:45 +0800602 self.update_skipped_tests()
603
604 def update_skipped_tests(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800605 """Updates skipped states based on run_if."""
Jon Salz885dcac2013-07-23 16:39:50 +0800606 env = TestArgEnv()
Ricky Liang45c73e72015-01-15 15:00:30 +0800607
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800608 def _evaluate_skip_from_run_if(test):
609 """Returns the run_if evaluation of the test.
610
611 Args:
612 test: A FactoryTest object.
613
614 Returns:
615 The run_if evaluation result. Returns False if the test has no
616 run_if argument.
617 """
618 value = None
619 if test.run_if_expr:
620 try:
621 value = test.run_if_expr(env)
622 except: # pylint: disable=W0702
623 logging.exception('Unable to evaluate run_if expression for %s',
624 test.path)
625 # But keep going; we have no choice. This will end up
626 # always activating the test.
627 elif test.run_if_table_name:
628 try:
629 aux = shopfloor.get_selected_aux_data(test.run_if_table_name)
630 value = aux.get(test.run_if_col)
631 except ValueError:
632 # Not available; assume it shouldn't be skipped
633 pass
634
635 if value is None:
636 skip = False
637 else:
638 skip = (not value) ^ t.run_if_not
639 return skip
640
641 # Gets all run_if evaluation, and stores results in skip_map.
642 skip_map = dict()
Jon Salz008f4ea2012-08-28 05:39:45 +0800643 for t in self.test_list.walk():
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800644 skip_map[t.path] = _evaluate_skip_from_run_if(t)
Jon Salz885dcac2013-07-23 16:39:50 +0800645
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800646 # Propagates the skip value from root of tree and updates skip_map.
647 def _update_skip_map_from_node(test, skip_from_parent):
648 """Updates skip_map from a given node.
Jon Salz885dcac2013-07-23 16:39:50 +0800649
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800650 Given a FactoryTest node and the skip value from parent, updates the
651 skip value of current node in the skip_map if skip value from parent is
652 True. If this node has children, recursively propagate this value to all
653 its children, that is, all its subtests.
654 Note that this function only updates value in skip_map, not the actual
655 test_list tree.
Jon Salz008f4ea2012-08-28 05:39:45 +0800656
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800657 Args:
658 test: The given FactoryTest object. It is a node in the test_list tree.
659 skip_from_parent: The skip value which propagates from the parent of
660 input node.
661 """
662 skip_this_tree = skip_from_parent or skip_map[test.path]
663 if skip_this_tree:
664 logging.info('Skip from node %r', test.path)
665 skip_map[test.path] = True
666 if test.is_leaf():
667 return
668 # Propagates skip value to its subtests
669 for subtest in test.subtests:
670 _update_skip_map_from_node(subtest, skip_this_tree)
671
672 _update_skip_map_from_node(self.test_list, False)
673
674 # Updates the skip value from skip_map to test_list tree. Also, updates test
675 # status if needed.
676 for t in self.test_list.walk():
677 skip = skip_map[t.path]
678 test_state = t.get_state()
679 if ((not skip) and
680 (test_state.status == TestState.PASSED) and
681 (test_state.error_msg == TestState.SKIPPED_MSG)):
682 # It was marked as skipped before, but now we need to run it.
683 # Mark as untested.
684 t.update_state(skip=skip, status=TestState.UNTESTED, error_msg='')
685 else:
686 t.update_state(skip=skip)
Jon Salz008f4ea2012-08-28 05:39:45 +0800687
Jon Salz0697cbf2012-07-04 15:14:04 +0800688 def show_next_active_test(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800689 """Rotates to the next visible active test."""
Jon Salz0697cbf2012-07-04 15:14:04 +0800690 self.reap_completed_tests()
691 active_tests = [
Ricky Liang45c73e72015-01-15 15:00:30 +0800692 t for t in self.test_list.walk()
693 if t.is_leaf() and t.get_state().status == TestState.ACTIVE]
Jon Salz0697cbf2012-07-04 15:14:04 +0800694 if not active_tests:
695 return
Jon Salz4f6c7172012-06-11 20:45:36 +0800696
Jon Salz0697cbf2012-07-04 15:14:04 +0800697 try:
698 next_test = active_tests[
Ricky Liang45c73e72015-01-15 15:00:30 +0800699 (active_tests.index(self.visible_test) + 1) % len(active_tests)]
Jon Salz0697cbf2012-07-04 15:14:04 +0800700 except ValueError: # visible_test not present in active_tests
701 next_test = active_tests[0]
Jon Salz4f6c7172012-06-11 20:45:36 +0800702
Jon Salz0697cbf2012-07-04 15:14:04 +0800703 self.set_visible_test(next_test)
Jon Salz4f6c7172012-06-11 20:45:36 +0800704
Jon Salz0697cbf2012-07-04 15:14:04 +0800705 def handle_event(self, event):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800706 """Handles an event from the event server."""
Jon Salz0697cbf2012-07-04 15:14:04 +0800707 handler = self.event_handlers.get(event.type)
708 if handler:
709 handler(event)
710 else:
711 # We don't register handlers for all event types - just ignore
712 # this event.
713 logging.debug('Unbound event type %s', event.type)
Jon Salz4f6c7172012-06-11 20:45:36 +0800714
Vic Yangaabf9fd2013-04-09 18:56:13 +0800715 def check_critical_factory_note(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800716 """Returns True if the last factory note is critical."""
Vic Yangaabf9fd2013-04-09 18:56:13 +0800717 notes = self.state_instance.get_shared_data('factory_note', True)
718 return notes and notes[-1]['level'] == 'CRITICAL'
719
Jon Salz0697cbf2012-07-04 15:14:04 +0800720 def run_next_test(self):
henryhsu4cc6b022014-04-22 17:12:42 +0800721 """Runs the next eligible test (or tests) in self.tests_to_run.
722
723 We have three kinds of the next eligible test:
724 1. normal
725 2. backgroundable
726 3. force_background
727
728 And we have four situations of the ongoing invocations:
729 a. only a running normal test
730 b. all running tests are backgroundable
731 c. all running tests are force_background
732 d. all running tests are any combination of backgroundable and
733 force_background
734
735 When a test would like to be run, it must follow the rules:
736 [1] cannot run with [abd]
737 [2] cannot run with [a]
738 All the other combinations are allowed
739 """
Jon Salz0697cbf2012-07-04 15:14:04 +0800740 self.reap_completed_tests()
Vic Yangaabf9fd2013-04-09 18:56:13 +0800741 if self.tests_to_run and self.check_critical_factory_note():
742 self.tests_to_run.clear()
743 return
Jon Salz0697cbf2012-07-04 15:14:04 +0800744 while self.tests_to_run:
Ricky Liang6fe218c2013-12-27 15:17:17 +0800745 logging.debug('Tests to run: %s', [x.path for x in self.tests_to_run])
Jon Salz94eb56f2012-06-12 18:01:12 +0800746
Jon Salz0697cbf2012-07-04 15:14:04 +0800747 test = self.tests_to_run[0]
Jon Salz94eb56f2012-06-12 18:01:12 +0800748
Jon Salz0697cbf2012-07-04 15:14:04 +0800749 if test in self.invocations:
750 logging.info('Next test %s is already running', test.path)
751 self.tests_to_run.popleft()
752 return
Jon Salz94eb56f2012-06-12 18:01:12 +0800753
Jon Salza1412922012-07-23 16:04:17 +0800754 for requirement in test.require_run:
755 for i in requirement.test.walk():
756 if i.get_state().status == TestState.ACTIVE:
Jon Salz304a75d2012-07-06 11:14:15 +0800757 logging.info('Waiting for active test %s to complete '
Jon Salza1412922012-07-23 16:04:17 +0800758 'before running %s', i.path, test.path)
Jon Salz304a75d2012-07-06 11:14:15 +0800759 return
760
henryhsu4cc6b022014-04-22 17:12:42 +0800761 def is_normal_test(test):
762 return not (test.backgroundable or test.force_background)
763
764 # [1] cannot run with [abd].
765 if self.invocations and is_normal_test(test) and any(
766 [not x.force_background for x in self.invocations]):
767 logging.info('Waiting for non-force_background tests to '
768 'complete before running %s', test.path)
769 return
770
771 # [2] cannot run with [a].
772 if self.invocations and test.backgroundable and any(
773 [is_normal_test(x) for x in self.invocations]):
774 logging.info('Waiting for normal tests to '
775 'complete before running %s', test.path)
Jon Salz0697cbf2012-07-04 15:14:04 +0800776 return
Jon Salz94eb56f2012-06-12 18:01:12 +0800777
Jon Salz3e6f5202012-10-15 15:08:29 +0800778 if test.get_state().skip:
779 factory.console.info('Skipping test %s', test.path)
780 test.update_state(status=TestState.PASSED,
781 error_msg=TestState.SKIPPED_MSG)
782 self.tests_to_run.popleft()
783 continue
784
Jon Salz0697cbf2012-07-04 15:14:04 +0800785 self.tests_to_run.popleft()
Jon Salz94eb56f2012-06-12 18:01:12 +0800786
Jon Salz304a75d2012-07-06 11:14:15 +0800787 untested = set()
Jon Salza1412922012-07-23 16:04:17 +0800788 for requirement in test.require_run:
789 for i in requirement.test.walk():
790 if i == test:
Jon Salz304a75d2012-07-06 11:14:15 +0800791 # We've hit this test itself; stop checking
792 break
Jon Salza1412922012-07-23 16:04:17 +0800793 if ((i.get_state().status == TestState.UNTESTED) or
794 (requirement.passed and i.get_state().status !=
795 TestState.PASSED)):
Jon Salz304a75d2012-07-06 11:14:15 +0800796 # Found an untested test; move on to the next
797 # element in require_run.
Jon Salza1412922012-07-23 16:04:17 +0800798 untested.add(i)
Jon Salz304a75d2012-07-06 11:14:15 +0800799 break
800
801 if untested:
802 untested_paths = ', '.join(sorted([x.path for x in untested]))
803 if self.state_instance.get_shared_data('engineering_mode',
804 optional=True):
805 # In engineering mode, we'll let it go.
806 factory.console.warn('In engineering mode; running '
807 '%s even though required tests '
808 '[%s] have not completed',
809 test.path, untested_paths)
810 else:
811 # Not in engineering mode; mark it failed.
812 error_msg = ('Required tests [%s] have not been run yet'
813 % untested_paths)
814 factory.console.error('Not running %s: %s',
815 test.path, error_msg)
816 test.update_state(status=TestState.FAILED,
817 error_msg=error_msg)
818 continue
819
Ricky Liang48e47f92014-02-26 19:31:51 +0800820 if (isinstance(test, factory.ShutdownStep) and
Ricky Liangb7eb8772014-09-15 18:05:22 +0800821 self.state_instance.get_shared_data(
822 state.POST_SHUTDOWN_TAG % test.path, optional=True)):
Ricky Liang48e47f92014-02-26 19:31:51 +0800823 # Invoking post shutdown method of shutdown test. We should retain the
824 # iterations_left and retries_left of the original test state.
825 test_state = self.state_instance.get_test_state(test.path)
826 self._run_test(test, test_state.iterations_left,
827 test_state.retries_left)
828 else:
829 # Starts a new test run; reset iterations and retries.
830 self._run_test(test, test.iterations, test.retries)
Jon Salz1acc8742012-07-17 17:45:55 +0800831
Cheng-Yi Chiangce05c002013-04-04 02:13:17 +0800832 def _run_test(self, test, iterations_left=None, retries_left=None):
Vic Yanga3cecf82014-12-26 00:44:21 -0800833 if not self._ui_initialized and not test.is_no_host():
834 self.init_ui()
Vic Yang08505c72015-01-06 17:01:53 -0800835 invoc = TestInvocation(
836 self, test, on_completion=self.run_next_test,
837 on_test_failure=system.GetBoard().OnTestFailure)
Jon Salz1acc8742012-07-17 17:45:55 +0800838 new_state = test.update_state(
Ricky Liang48e47f92014-02-26 19:31:51 +0800839 status=TestState.ACTIVE, increment_count=1, error_msg='',
840 invocation=invoc.uuid, iterations_left=iterations_left,
841 retries_left=retries_left,
842 visible=(self.visible_test == test))
Jon Salz1acc8742012-07-17 17:45:55 +0800843 invoc.count = new_state.count
844
845 self.invocations[test] = invoc
846 if self.visible_test is None and test.has_ui:
847 self.set_visible_test(test)
Vic Yang311ddb82012-09-26 12:08:28 +0800848 self.check_exclusive()
Jon Salz1acc8742012-07-17 17:45:55 +0800849 invoc.start()
Jon Salz5f2a0672012-05-22 17:14:06 +0800850
Vic Yang311ddb82012-09-26 12:08:28 +0800851 def check_exclusive(self):
Jon Salzce6a7f82013-06-10 18:22:54 +0800852 # alias since this is really long
853 EXCL_OPT = factory.FactoryTest.EXCLUSIVE_OPTIONS
854
Vic Yang311ddb82012-09-26 12:08:28 +0800855 current_exclusive_items = set([
Jon Salzce6a7f82013-06-10 18:22:54 +0800856 item for item in EXCL_OPT
Vic Yang311ddb82012-09-26 12:08:28 +0800857 if any([test.is_exclusive(item) for test in self.invocations])])
858
859 new_exclusive_items = current_exclusive_items - self.exclusive_items
Jon Salzce6a7f82013-06-10 18:22:54 +0800860 if EXCL_OPT.NETWORKING in new_exclusive_items:
Vic Yang311ddb82012-09-26 12:08:28 +0800861 logging.info('Disabling network')
862 self.connection_manager.DisableNetworking()
Jon Salzce6a7f82013-06-10 18:22:54 +0800863 if EXCL_OPT.CHARGER in new_exclusive_items:
Vic Yang311ddb82012-09-26 12:08:28 +0800864 logging.info('Stop controlling charger')
865
866 new_non_exclusive_items = self.exclusive_items - current_exclusive_items
Jon Salzce6a7f82013-06-10 18:22:54 +0800867 if EXCL_OPT.NETWORKING in new_non_exclusive_items:
Vic Yang311ddb82012-09-26 12:08:28 +0800868 logging.info('Re-enabling network')
869 self.connection_manager.EnableNetworking()
Jon Salzce6a7f82013-06-10 18:22:54 +0800870 if EXCL_OPT.CHARGER in new_non_exclusive_items:
Vic Yang311ddb82012-09-26 12:08:28 +0800871 logging.info('Start controlling charger')
872
Jon Salzce6a7f82013-06-10 18:22:54 +0800873 if self.cpufreq_manager:
874 enabled = EXCL_OPT.CPUFREQ not in current_exclusive_items
875 try:
876 self.cpufreq_manager.SetEnabled(enabled)
877 except: # pylint: disable=W0702
878 logging.exception('Unable to %s cpufreq services',
879 'enable' if enabled else 'disable')
880
Ricky Liang0f9978e2015-01-30 08:19:17 +0000881 # Only adjust charge state if not excluded
882 if (EXCL_OPT.CHARGER not in current_exclusive_items and
883 not utils.in_chroot()):
884 if self.charge_manager:
Cheng-Yi Chiangd8186952013-04-04 23:41:14 +0800885 self.charge_manager.AdjustChargeState()
886 else:
Dean Liao88b93192014-10-23 19:37:41 +0800887 self.charge()
Vic Yang311ddb82012-09-26 12:08:28 +0800888
889 self.exclusive_items = current_exclusive_items
Jon Salz5da61e62012-05-31 13:06:22 +0800890
Dean Liao88b93192014-10-23 19:37:41 +0800891 def charge(self):
892 """Charges the board.
893
894 It won't try again if last time SetChargeState raised an exception.
895 """
896 if not self._can_charge:
897 return
898
899 try:
Ricky Liang9ac35e02015-01-30 16:01:32 +0800900 if self.charge_manager:
901 self.charge_manager.StartCharging()
902 else:
903 system.GetBoard().SetChargeState(Board.ChargeState.CHARGE)
Dean Liao88b93192014-10-23 19:37:41 +0800904 except NotImplementedError:
905 logging.info('Charging is not supported')
906 self._can_charge = False
907 except BoardException:
908 logging.exception('Unable to set charge state on this board')
909 self._can_charge = False
910
cychiang21886742012-07-05 15:16:32 +0800911 def check_for_updates(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800912 """Schedules an asynchronous check for updates if necessary."""
cychiang21886742012-07-05 15:16:32 +0800913 if not self.test_list.options.update_period_secs:
914 # Not enabled.
915 return
916
917 now = time.time()
918 if self.last_update_check and (
919 now - self.last_update_check <
920 self.test_list.options.update_period_secs):
921 # Not yet time for another check.
922 return
923
924 self.last_update_check = now
925
926 def handle_check_for_update(reached_shopfloor, md5sum, needs_update):
927 if reached_shopfloor:
928 new_update_md5sum = md5sum if needs_update else None
929 if system.SystemInfo.update_md5sum != new_update_md5sum:
930 logging.info('Received new update MD5SUM: %s', new_update_md5sum)
931 system.SystemInfo.update_md5sum = new_update_md5sum
Peter Ammon1e1ec572014-06-26 17:56:32 -0700932 self.run_enqueue(self.update_system_info)
Cheng-Yi Chiang194d3c02015-03-16 14:37:15 +0800933 else:
934 if not self._suppress_periodic_update_messages:
935 logging.warning('Suppress error messages for periodic update checking'
936 ' after the first one.')
937 self._suppress_periodic_update_messages = True
cychiang21886742012-07-05 15:16:32 +0800938
939 updater.CheckForUpdateAsync(
Ricky Liang45c73e72015-01-15 15:00:30 +0800940 handle_check_for_update,
Cheng-Yi Chiang194d3c02015-03-16 14:37:15 +0800941 self.test_list.options.shopfloor_timeout_secs,
942 self._suppress_periodic_update_messages)
cychiang21886742012-07-05 15:16:32 +0800943
Jon Salza6711d72012-07-18 14:33:03 +0800944 def cancel_pending_tests(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800945 """Cancels any tests in the run queue."""
Jon Salza6711d72012-07-18 14:33:03 +0800946 self.run_tests([])
947
Ricky Liang4bff3e32014-02-20 18:46:11 +0800948 def restore_active_run_state(self):
949 """Restores active run id and the list of scheduled tests."""
950 self.run_id = self.state_instance.get_shared_data('run_id', optional=True)
951 self.scheduled_run_tests = self.state_instance.get_shared_data(
952 'scheduled_run_tests', optional=True)
953
954 def set_active_run_state(self):
955 """Sets active run id and the list of scheduled tests."""
956 self.run_id = str(uuid.uuid4())
957 self.scheduled_run_tests = [test.path for test in self.tests_to_run]
958 self.state_instance.set_shared_data('run_id', self.run_id)
959 self.state_instance.set_shared_data('scheduled_run_tests',
960 self.scheduled_run_tests)
961
Jon Salz0697cbf2012-07-04 15:14:04 +0800962 def run_tests(self, subtrees, untested_only=False):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800963 """Runs tests under subtree.
Jon Salz258a40c2012-04-19 12:34:01 +0800964
Jon Salz0697cbf2012-07-04 15:14:04 +0800965 The tests are run in order unless one fails (then stops).
966 Backgroundable tests are run simultaneously; when a foreground test is
967 encountered, we wait for all active tests to finish before continuing.
Jon Salzb1b39092012-05-03 02:05:09 +0800968
Ricky Liang6fe218c2013-12-27 15:17:17 +0800969 Args:
970 subtrees: Node or nodes containing tests to run (may either be
971 a single test or a list). Duplicates will be ignored.
972 untested_only: True to run untested tests only.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800973 """
Vic Yang08505c72015-01-06 17:01:53 -0800974 system.GetBoard().OnTestStart()
975
Jon Salz0697cbf2012-07-04 15:14:04 +0800976 if type(subtrees) != list:
977 subtrees = [subtrees]
Jon Salz258a40c2012-04-19 12:34:01 +0800978
Jon Salz0697cbf2012-07-04 15:14:04 +0800979 # Nodes we've seen so far, to avoid duplicates.
980 seen = set()
Jon Salz94eb56f2012-06-12 18:01:12 +0800981
Jon Salz0697cbf2012-07-04 15:14:04 +0800982 self.tests_to_run = deque()
983 for subtree in subtrees:
984 for test in subtree.walk():
985 if test in seen:
986 continue
987 seen.add(test)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800988
Jon Salz0697cbf2012-07-04 15:14:04 +0800989 if not test.is_leaf():
990 continue
Ricky Liang45c73e72015-01-15 15:00:30 +0800991 if untested_only and test.get_state().status != TestState.UNTESTED:
Jon Salz0697cbf2012-07-04 15:14:04 +0800992 continue
993 self.tests_to_run.append(test)
Ricky Liang4bff3e32014-02-20 18:46:11 +0800994 if subtrees:
995 self.set_active_run_state()
Jon Salz0697cbf2012-07-04 15:14:04 +0800996 self.run_next_test()
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800997
Jon Salz0697cbf2012-07-04 15:14:04 +0800998 def reap_completed_tests(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800999 """Removes completed tests from the set of active tests.
Jon Salz0697cbf2012-07-04 15:14:04 +08001000
1001 Also updates the visible test if it was reaped.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001002 """
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +08001003 test_completed = False
Jon Salz0697cbf2012-07-04 15:14:04 +08001004 for t, v in dict(self.invocations).iteritems():
1005 if v.is_completed():
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +08001006 test_completed = True
Jon Salz1acc8742012-07-17 17:45:55 +08001007 new_state = t.update_state(**v.update_state_on_completion)
Jon Salz0697cbf2012-07-04 15:14:04 +08001008 del self.invocations[t]
1009
Chun-Ta Lin54e17e42012-09-06 22:05:13 +08001010 # Stop on failure if flag is true.
1011 if (self.test_list.options.stop_on_failure and
1012 new_state.status == TestState.FAILED):
1013 # Clean all the tests to cause goofy to stop.
1014 self.tests_to_run = []
Ricky Liang45c73e72015-01-15 15:00:30 +08001015 factory.console.info('Stop on failure triggered. Empty the queue.')
Chun-Ta Lin54e17e42012-09-06 22:05:13 +08001016
Jon Salz1acc8742012-07-17 17:45:55 +08001017 if new_state.iterations_left and new_state.status == TestState.PASSED:
1018 # Play it again, Sam!
1019 self._run_test(t)
Cheng-Yi Chiangce05c002013-04-04 02:13:17 +08001020 # new_state.retries_left is obtained after update.
1021 # For retries_left == 0, test can still be run for the last time.
1022 elif (new_state.retries_left >= 0 and
1023 new_state.status == TestState.FAILED):
1024 # Still have to retry, Sam!
1025 self._run_test(t)
Jon Salz1acc8742012-07-17 17:45:55 +08001026
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +08001027 if test_completed:
Vic Yangf01c59f2013-04-19 17:37:56 +08001028 self.log_watcher.KickWatchThread()
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +08001029
Jon Salz0697cbf2012-07-04 15:14:04 +08001030 if (self.visible_test is None or
Jon Salz85a39882012-07-05 16:45:04 +08001031 self.visible_test not in self.invocations):
Jon Salz0697cbf2012-07-04 15:14:04 +08001032 self.set_visible_test(None)
1033 # Make the first running test, if any, the visible test
1034 for t in self.test_list.walk():
1035 if t in self.invocations:
1036 self.set_visible_test(t)
1037 break
1038
Jon Salz6dc031d2013-06-19 13:06:23 +08001039 def kill_active_tests(self, abort, root=None, reason=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001040 """Kills and waits for all active tests.
Jon Salz0697cbf2012-07-04 15:14:04 +08001041
Jon Salz85a39882012-07-05 16:45:04 +08001042 Args:
1043 abort: True to change state of killed tests to FAILED, False for
Jon Salz0697cbf2012-07-04 15:14:04 +08001044 UNTESTED.
Jon Salz85a39882012-07-05 16:45:04 +08001045 root: If set, only kills tests with root as an ancestor.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001046 reason: If set, the abort reason.
1047 """
Jon Salz0697cbf2012-07-04 15:14:04 +08001048 self.reap_completed_tests()
1049 for test, invoc in self.invocations.items():
Jon Salz85a39882012-07-05 16:45:04 +08001050 if root and not test.has_ancestor(root):
1051 continue
1052
Ricky Liang45c73e72015-01-15 15:00:30 +08001053 factory.console.info('Killing active test %s...', test.path)
Jon Salz6dc031d2013-06-19 13:06:23 +08001054 invoc.abort_and_join(reason)
Ricky Liang45c73e72015-01-15 15:00:30 +08001055 factory.console.info('Killed %s', test.path)
Jon Salz1acc8742012-07-17 17:45:55 +08001056 test.update_state(**invoc.update_state_on_completion)
Jon Salz0697cbf2012-07-04 15:14:04 +08001057 del self.invocations[test]
Jon Salz1acc8742012-07-17 17:45:55 +08001058
Jon Salz0697cbf2012-07-04 15:14:04 +08001059 if not abort:
1060 test.update_state(status=TestState.UNTESTED)
1061 self.reap_completed_tests()
1062
Jon Salz6dc031d2013-06-19 13:06:23 +08001063 def stop(self, root=None, fail=False, reason=None):
1064 self.kill_active_tests(fail, root, reason)
Jon Salz85a39882012-07-05 16:45:04 +08001065 # Remove any tests in the run queue under the root.
1066 self.tests_to_run = deque([x for x in self.tests_to_run
1067 if root and not x.has_ancestor(root)])
1068 self.run_next_test()
Jon Salz0697cbf2012-07-04 15:14:04 +08001069
Jon Salz4712ac72013-02-07 17:12:05 +08001070 def clear_state(self, root=None):
Jon Salzd7550792013-07-12 05:49:27 +08001071 if root is None:
1072 root = self.test_list
Jon Salz6dc031d2013-06-19 13:06:23 +08001073 self.stop(root, reason='Clearing test state')
Jon Salz4712ac72013-02-07 17:12:05 +08001074 for f in root.walk():
1075 if f.is_leaf():
1076 f.update_state(status=TestState.UNTESTED)
1077
Jon Salz6dc031d2013-06-19 13:06:23 +08001078 def abort_active_tests(self, reason=None):
1079 self.kill_active_tests(True, reason=reason)
Jon Salz0697cbf2012-07-04 15:14:04 +08001080
1081 def main(self):
Jon Salzeff94182013-06-19 15:06:28 +08001082 syslog.openlog('goofy')
1083
Jon Salz0697cbf2012-07-04 15:14:04 +08001084 try:
Jon Salzd7550792013-07-12 05:49:27 +08001085 self.status = Status.INITIALIZING
Jon Salz0697cbf2012-07-04 15:14:04 +08001086 self.init()
1087 self.event_log.Log('goofy_init',
Ricky Liang45c73e72015-01-15 15:00:30 +08001088 success=True)
Jon Salz0697cbf2012-07-04 15:14:04 +08001089 except:
1090 if self.event_log:
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001091 try:
Jon Salz0697cbf2012-07-04 15:14:04 +08001092 self.event_log.Log('goofy_init',
Ricky Liang45c73e72015-01-15 15:00:30 +08001093 success=False,
1094 trace=traceback.format_exc())
Jon Salz0697cbf2012-07-04 15:14:04 +08001095 except: # pylint: disable=W0702
1096 pass
1097 raise
1098
Jon Salzd7550792013-07-12 05:49:27 +08001099 self.status = Status.RUNNING
Jon Salzeff94182013-06-19 15:06:28 +08001100 syslog.syslog('Goofy (factory test harness) starting')
Jon Salz0697cbf2012-07-04 15:14:04 +08001101 self.run()
1102
1103 def update_system_info(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001104 """Updates system info."""
Jon Salz0697cbf2012-07-04 15:14:04 +08001105 system_info = system.SystemInfo()
1106 self.state_instance.set_shared_data('system_info', system_info.__dict__)
1107 self.event_client.post_event(Event(Event.Type.SYSTEM_INFO,
Ricky Liang45c73e72015-01-15 15:00:30 +08001108 system_info=system_info.__dict__))
Jon Salz0697cbf2012-07-04 15:14:04 +08001109 logging.info('System info: %r', system_info.__dict__)
1110
Jon Salzeb42f0d2012-07-27 19:14:04 +08001111 def update_factory(self, auto_run_on_restart=False, post_update_hook=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001112 """Commences updating factory software.
Jon Salzeb42f0d2012-07-27 19:14:04 +08001113
1114 Args:
1115 auto_run_on_restart: Auto-run when the machine comes back up.
1116 post_update_hook: Code to call after update but immediately before
1117 restart.
1118
1119 Returns:
1120 Never if the update was successful (we just reboot).
1121 False if the update was unnecessary (no update available).
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001122 """
Jon Salz6dc031d2013-06-19 13:06:23 +08001123 self.kill_active_tests(False, reason='Factory software update')
Jon Salza6711d72012-07-18 14:33:03 +08001124 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +08001125
Jon Salz5c344f62012-07-13 14:31:16 +08001126 def pre_update_hook():
1127 if auto_run_on_restart:
1128 self.state_instance.set_shared_data('tests_after_shutdown',
1129 FORCE_AUTO_RUN)
1130 self.state_instance.close()
1131
Jon Salzeb42f0d2012-07-27 19:14:04 +08001132 if updater.TryUpdate(pre_update_hook=pre_update_hook):
1133 if post_update_hook:
1134 post_update_hook()
1135 self.env.shutdown('reboot')
Jon Salz0697cbf2012-07-04 15:14:04 +08001136
Ricky Liang8fecf412014-05-22 10:56:14 +08001137 def handle_sigint(self, dummy_signum, dummy_frame): # pylint: disable=W0613
Jon Salz77c151e2012-08-28 07:20:37 +08001138 logging.error('Received SIGINT')
Peter Ammon1e1ec572014-06-26 17:56:32 -07001139 self.run_enqueue(None)
Jon Salz77c151e2012-08-28 07:20:37 +08001140 raise KeyboardInterrupt()
1141
Ricky Liang8fecf412014-05-22 10:56:14 +08001142 def handle_sigterm(self, dummy_signum, dummy_frame): # pylint: disable=W0613
1143 logging.error('Received SIGTERM')
Hung-Te Lin94ca4742014-07-09 20:13:50 +08001144 self.env.terminate()
1145 self.run_queue.put(None)
Ricky Liang8fecf412014-05-22 10:56:14 +08001146 raise RuntimeError('Received SIGTERM')
1147
Jon Salze12c2b32013-06-25 16:24:34 +08001148 def find_kcrashes(self):
1149 """Finds kcrash files, logs them, and marks them as seen."""
1150 seen_crashes = set(
1151 self.state_instance.get_shared_data('seen_crashes', optional=True)
1152 or [])
1153
1154 for path in glob.glob('/var/spool/crash/*'):
1155 if not os.path.isfile(path):
1156 continue
1157 if path in seen_crashes:
1158 continue
1159 try:
1160 stat = os.stat(path)
1161 mtime = utils.TimeString(stat.st_mtime)
1162 logging.info(
1163 'Found new crash file %s (%d bytes at %s)',
1164 path, stat.st_size, mtime)
1165 extra_log_args = {}
1166
1167 try:
1168 _, ext = os.path.splitext(path)
1169 if ext in ['.kcrash', '.meta']:
1170 ext = ext.replace('.', '')
1171 with open(path) as f:
1172 data = f.read(MAX_CRASH_FILE_SIZE)
1173 tell = f.tell()
1174 logging.info(
1175 'Contents of %s%s:%s',
1176 path,
1177 ('' if tell == stat.st_size
1178 else '(truncated to %d bytes)' % MAX_CRASH_FILE_SIZE),
1179 ('\n' + data).replace('\n', '\n ' + ext + '> '))
1180 extra_log_args['data'] = data
1181
1182 # Copy to /var/factory/kcrash for posterity
1183 kcrash_dir = factory.get_factory_root('kcrash')
1184 utils.TryMakeDirs(kcrash_dir)
1185 shutil.copy(path, kcrash_dir)
1186 logging.info('Copied to %s',
1187 os.path.join(kcrash_dir, os.path.basename(path)))
1188 finally:
1189 # Even if something goes wrong with the above, still try to
1190 # log to event log
1191 self.event_log.Log('crash_file',
1192 path=path, size=stat.st_size, mtime=mtime,
1193 **extra_log_args)
1194 except: # pylint: disable=W0702
1195 logging.exception('Unable to handle crash files %s', path)
1196 seen_crashes.add(path)
1197
1198 self.state_instance.set_shared_data('seen_crashes', list(seen_crashes))
1199
Jon Salz128b0932013-07-03 16:55:26 +08001200 def GetTestList(self, test_list_id):
1201 """Returns the test list with the given ID.
1202
1203 Raises:
1204 TestListError: The test list ID is not valid.
1205 """
1206 try:
1207 return self.test_lists[test_list_id]
1208 except KeyError:
1209 raise test_lists.TestListError(
1210 '%r is not a valid test list ID (available IDs are [%s])' % (
1211 test_list_id, ', '.join(sorted(self.test_lists.keys()))))
1212
1213 def InitTestLists(self):
1214 """Reads in all test lists and sets the active test list."""
Ricky Liang27051552014-05-04 14:22:26 +08001215 self.test_lists = test_lists.BuildAllTestLists(
1216 force_generic=(self.options.automation_mode is not None))
Jon Salzd7550792013-07-12 05:49:27 +08001217 logging.info('Loaded test lists: [%s]',
1218 test_lists.DescribeTestLists(self.test_lists))
Jon Salz128b0932013-07-03 16:55:26 +08001219
1220 if not self.options.test_list:
1221 self.options.test_list = test_lists.GetActiveTestListId()
1222
1223 if os.sep in self.options.test_list:
1224 # It's a path pointing to an old-style test list; use it.
1225 self.test_list = factory.read_test_list(self.options.test_list)
1226 else:
1227 self.test_list = self.GetTestList(self.options.test_list)
1228
1229 logging.info('Active test list: %s', self.test_list.test_list_id)
1230
1231 if isinstance(self.test_list, test_lists.OldStyleTestList):
1232 # Actually load it in. (See OldStyleTestList for an explanation
1233 # of why this is necessary.)
1234 self.test_list = self.test_list.Load()
1235
1236 self.test_list.state_instance = self.state_instance
1237
Shuo-Peng Liao268b40b2013-07-01 15:58:59 +08001238 def init_hooks(self):
1239 """Initializes hooks.
1240
1241 Must run after self.test_list ready.
1242 """
Shuo-Peng Liao52b90da2013-06-30 17:00:06 +08001243 module, cls = self.test_list.options.hooks_class.rsplit('.', 1)
1244 self.hooks = getattr(__import__(module, fromlist=[cls]), cls)()
1245 assert isinstance(self.hooks, factory.Hooks), (
Ricky Liang45c73e72015-01-15 15:00:30 +08001246 'hooks should be of type Hooks but is %r' % type(self.hooks))
Shuo-Peng Liao52b90da2013-06-30 17:00:06 +08001247 self.hooks.test_list = self.test_list
Shuo-Peng Liao268b40b2013-07-01 15:58:59 +08001248 self.hooks.OnCreatedTestList()
Shuo-Peng Liao52b90da2013-06-30 17:00:06 +08001249
Vic Yanga3cecf82014-12-26 00:44:21 -08001250 def init_ui(self):
1251 """Initialize UI."""
1252 self._ui_initialized = True
1253 if self.options.ui == 'chrome':
Hung-Te Lin8f6a3782015-01-06 22:58:32 +08001254 if self.options.monolithic:
Hung-Te Lin7bd55312014-12-30 16:43:36 +08001255 self.env.launch_chrome()
1256 else:
1257 # The presenter is responsible for launching Chrome. Let's just
1258 # wait here.
1259 self.env.controller_ready_for_ui()
Vic Yanga3cecf82014-12-26 00:44:21 -08001260 logging.info('Waiting for a web socket connection')
1261 self.web_socket_manager.wait()
1262
1263 # Wait for the test widget size to be set; this is done in
1264 # an asynchronous RPC so there is a small chance that the
1265 # web socket might be opened first.
1266 for _ in range(100): # 10 s
1267 try:
1268 if self.state_instance.get_shared_data('test_widget_size'):
1269 break
1270 except KeyError:
1271 pass # Retry
1272 time.sleep(0.1) # 100 ms
1273 else:
1274 logging.warn('Never received test_widget_size from UI')
1275
Hung-Te Lin7bd55312014-12-30 16:43:36 +08001276 logging.info('Waiting for a web socket connection')
1277 self.web_socket_manager.wait()
1278
Jon Salz0697cbf2012-07-04 15:14:04 +08001279 def init(self, args=None, env=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001280 """Initializes Goofy.
Jon Salz0697cbf2012-07-04 15:14:04 +08001281
1282 Args:
1283 args: A list of command-line arguments. Uses sys.argv if
1284 args is None.
1285 env: An Environment instance to use (or None to choose
1286 FakeChrootEnvironment or DUTEnvironment as appropriate).
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001287 """
Jon Salz0697cbf2012-07-04 15:14:04 +08001288 parser = OptionParser()
1289 parser.add_option('-v', '--verbose', dest='verbose',
Jon Salz8fa8e832012-07-13 19:04:09 +08001290 action='store_true',
1291 help='Enable debug logging')
Jon Salz0697cbf2012-07-04 15:14:04 +08001292 parser.add_option('--print_test_list', dest='print_test_list',
Jon Salz8fa8e832012-07-13 19:04:09 +08001293 metavar='FILE',
1294 help='Read and print test list FILE, and exit')
Jon Salz0697cbf2012-07-04 15:14:04 +08001295 parser.add_option('--restart', dest='restart',
Jon Salz8fa8e832012-07-13 19:04:09 +08001296 action='store_true',
1297 help='Clear all test state')
Jon Salz0697cbf2012-07-04 15:14:04 +08001298 parser.add_option('--ui', dest='ui', type='choice',
Jon Salz7b5482e2014-08-04 17:48:41 +08001299 choices=['none', 'chrome'],
Jon Salz2f881df2013-02-01 17:00:35 +08001300 default='chrome',
Jon Salz8fa8e832012-07-13 19:04:09 +08001301 help='UI to use')
Jon Salz0697cbf2012-07-04 15:14:04 +08001302 parser.add_option('--ui_scale_factor', dest='ui_scale_factor',
Jon Salz8fa8e832012-07-13 19:04:09 +08001303 type='int', default=1,
1304 help=('Factor by which to scale UI '
1305 '(Chrome UI only)'))
Jon Salz0697cbf2012-07-04 15:14:04 +08001306 parser.add_option('--test_list', dest='test_list',
Jon Salz8fa8e832012-07-13 19:04:09 +08001307 metavar='FILE',
1308 help='Use FILE as test list')
Jon Salzc79a9982012-08-30 04:42:01 +08001309 parser.add_option('--dummy_shopfloor', action='store_true',
1310 help='Use a dummy shopfloor server')
Hung-Te Lincc41d2a2014-10-29 13:35:20 +08001311 parser.add_option('--dummy_connection_manager', action='store_true',
1312 help='Use a dummy connection manager')
Ricky Liang6fe218c2013-12-27 15:17:17 +08001313 parser.add_option('--automation-mode',
1314 choices=[m.lower() for m in AutomationMode],
Ricky Liang45c73e72015-01-15 15:00:30 +08001315 default='none', help='Factory test automation mode.')
Ricky Liang117484a2014-04-14 11:14:41 +08001316 parser.add_option('--no-auto-run-on-start', dest='auto_run_on_start',
1317 action='store_false', default=True,
1318 help=('do not automatically run the test list on goofy '
1319 'start; this is only valid when factory test '
1320 'automation is enabled'))
Chun-Ta Lina8dd3172014-11-26 16:15:13 +08001321 parser.add_option('--handshake_timeout', dest='handshake_timeout',
1322 type='float', default=0.3,
1323 help=('RPC timeout when doing handshake between device '
1324 'and presenter.'))
Vic Yang7d693c42014-09-14 09:52:39 +08001325 parser.add_option('--standalone', dest='standalone',
1326 action='store_true', default=False,
1327 help=('Assume the presenter is running on the same '
1328 'machines.'))
Hung-Te Lin8f6a3782015-01-06 22:58:32 +08001329 parser.add_option('--monolithic', dest='monolithic',
1330 action='store_true', default=False,
1331 help='Run in monolithic mode (without presenter)')
Jon Salz0697cbf2012-07-04 15:14:04 +08001332 (self.options, self.args) = parser.parse_args(args)
1333
Hung-Te Lina846f602014-07-04 20:32:22 +08001334 signal.signal(signal.SIGINT, self.handle_sigint)
1335 # TODO(hungte) SIGTERM does not work properly without Telemetry and should
1336 # be fixed.
Hung-Te Lina846f602014-07-04 20:32:22 +08001337
Jon Salz46b89562012-07-05 11:49:22 +08001338 # Make sure factory directories exist.
1339 factory.get_log_root()
1340 factory.get_state_root()
1341 factory.get_test_data_root()
1342
Jon Salz0697cbf2012-07-04 15:14:04 +08001343 global _inited_logging # pylint: disable=W0603
1344 if not _inited_logging:
1345 factory.init_logging('goofy', verbose=self.options.verbose)
1346 _inited_logging = True
Jon Salz8fa8e832012-07-13 19:04:09 +08001347
Jon Salz0f996602012-10-03 15:26:48 +08001348 if self.options.print_test_list:
Joel Kitchingb85ed7f2014-10-08 18:24:39 +08001349 print(factory.read_test_list(
1350 self.options.print_test_list).__repr__(recursive=True))
Jon Salz0f996602012-10-03 15:26:48 +08001351 sys.exit(0)
1352
Jon Salzee85d522012-07-17 14:34:46 +08001353 event_log.IncrementBootSequence()
Jon Salzd15bbcf2013-05-21 17:33:57 +08001354 # Don't defer logging the initial event, so we can make sure
1355 # that device_id, reimage_id, etc. are all set up.
1356 self.event_log = EventLog('goofy', defer=False)
Jon Salz0697cbf2012-07-04 15:14:04 +08001357
Jon Salz0697cbf2012-07-04 15:14:04 +08001358 if env:
1359 self.env = env
1360 elif factory.in_chroot():
1361 self.env = test_environment.FakeChrootEnvironment()
1362 logging.warn(
Ricky Liang45c73e72015-01-15 15:00:30 +08001363 'Using chroot environment: will not actually run autotests')
Hung-Te Lina846f602014-07-04 20:32:22 +08001364 elif self.options.ui == 'chrome':
Ricky Liang09d66d82014-09-25 11:20:54 +08001365 self.env = test_environment.DUTEnvironment()
Jon Salz0697cbf2012-07-04 15:14:04 +08001366 self.env.goofy = self
Vic Yanga4931152014-08-11 16:36:24 -07001367 # web_socket_manager will be initialized later
1368 # pylint: disable=W0108
1369 self.env.has_sockets = lambda: self.web_socket_manager.has_sockets()
Jon Salz0697cbf2012-07-04 15:14:04 +08001370
1371 if self.options.restart:
1372 state.clear_state()
1373
Jon Salz0697cbf2012-07-04 15:14:04 +08001374 if self.options.ui_scale_factor != 1 and utils.in_qemu():
1375 logging.warn(
Ricky Liang45c73e72015-01-15 15:00:30 +08001376 'In QEMU; ignoring ui_scale_factor argument')
Jon Salz0697cbf2012-07-04 15:14:04 +08001377 self.options.ui_scale_factor = 1
1378
1379 logging.info('Started')
1380
Hung-Te Lin8f6a3782015-01-06 22:58:32 +08001381 if not self.options.monolithic:
Hung-Te Lin7bd55312014-12-30 16:43:36 +08001382 self.link_manager = PresenterLinkManager(
1383 check_interval=1,
1384 handshake_timeout=self.options.handshake_timeout,
1385 standalone=self.options.standalone)
Peter Ammon1e1ec572014-06-26 17:56:32 -07001386
Jon Salz0697cbf2012-07-04 15:14:04 +08001387 self.start_state_server()
1388 self.state_instance.set_shared_data('hwid_cfg', get_hwid_cfg())
1389 self.state_instance.set_shared_data('ui_scale_factor',
Ricky Liang09216dc2013-02-22 17:26:45 +08001390 self.options.ui_scale_factor)
Jon Salz0697cbf2012-07-04 15:14:04 +08001391 self.last_shutdown_time = (
Ricky Liang45c73e72015-01-15 15:00:30 +08001392 self.state_instance.get_shared_data('shutdown_time', optional=True))
Jon Salz0697cbf2012-07-04 15:14:04 +08001393 self.state_instance.del_shared_data('shutdown_time', optional=True)
Jon Salzb19ea072013-02-07 16:35:00 +08001394 self.state_instance.del_shared_data('startup_error', optional=True)
Jon Salz0697cbf2012-07-04 15:14:04 +08001395
Ricky Liang6fe218c2013-12-27 15:17:17 +08001396 self.options.automation_mode = ParseAutomationMode(
1397 self.options.automation_mode)
1398 self.state_instance.set_shared_data('automation_mode',
1399 self.options.automation_mode)
1400 self.state_instance.set_shared_data(
1401 'automation_mode_prompt',
1402 AutomationModePrompt[self.options.automation_mode])
1403
Jon Salz128b0932013-07-03 16:55:26 +08001404 try:
1405 self.InitTestLists()
1406 except: # pylint: disable=W0702
1407 logging.exception('Unable to initialize test lists')
1408 self.state_instance.set_shared_data(
1409 'startup_error',
1410 'Unable to initialize test lists\n%s' % (
1411 traceback.format_exc()))
Jon Salzb19ea072013-02-07 16:35:00 +08001412 if self.options.ui == 'chrome':
1413 # Create an empty test list with default options so that the rest of
1414 # startup can proceed.
1415 self.test_list = factory.FactoryTestList(
1416 [], self.state_instance, factory.Options())
1417 else:
1418 # Bail with an error; no point in starting up.
1419 sys.exit('No valid test list; exiting.')
1420
Shuo-Peng Liao268b40b2013-07-01 15:58:59 +08001421 self.init_hooks()
1422
Jon Salz822838b2013-03-25 17:32:33 +08001423 if self.test_list.options.clear_state_on_start:
1424 self.state_instance.clear_test_state()
1425
Jon Salz670ce062014-05-16 15:53:50 +08001426 # If the phase is invalid, this will raise a ValueError.
1427 phase.SetPersistentPhase(self.test_list.options.phase)
1428
Dean Liao85ca86f2014-11-03 12:28:08 +08001429 # For netboot firmware, mainfw_type should be 'netboot'.
1430 if (system.SystemInfo().mainfw_type != 'nonchrome' and
1431 system.SystemInfo().firmware_version is None):
Ricky Liang45c73e72015-01-15 15:00:30 +08001432 self.state_instance.set_shared_data(
1433 'startup_error',
Vic Yang9bd4f772013-06-04 17:34:00 +08001434 'Netboot firmware detected\n'
1435 'Connect Ethernet and reboot to re-image.\n'
1436 u'侦测到网路开机固件\n'
1437 u'请连接乙太网并重启')
1438
Jon Salz0697cbf2012-07-04 15:14:04 +08001439 if not self.state_instance.has_shared_data('ui_lang'):
1440 self.state_instance.set_shared_data('ui_lang',
Ricky Liang45c73e72015-01-15 15:00:30 +08001441 self.test_list.options.ui_lang)
Jon Salz0697cbf2012-07-04 15:14:04 +08001442 self.state_instance.set_shared_data(
Ricky Liang45c73e72015-01-15 15:00:30 +08001443 'test_list_options',
1444 self.test_list.options.__dict__)
Jon Salz0697cbf2012-07-04 15:14:04 +08001445 self.state_instance.test_list = self.test_list
1446
Cheng-Yi Chiang39d32ad2013-07-23 15:02:38 +08001447 self.check_log_rotation()
Jon Salz83ef34b2012-11-01 19:46:35 +08001448
Jon Salz23926422012-09-01 03:38:13 +08001449 if self.options.dummy_shopfloor:
Ricky Liang45c73e72015-01-15 15:00:30 +08001450 os.environ[shopfloor.SHOPFLOOR_SERVER_ENV_VAR_NAME] = (
1451 'http://%s:%d/' %
Joel Kitchingb85ed7f2014-10-08 18:24:39 +08001452 (net_utils.LOCALHOST, shopfloor.DEFAULT_SERVER_PORT))
Jon Salz23926422012-09-01 03:38:13 +08001453 self.dummy_shopfloor = Spawn(
1454 [os.path.join(factory.FACTORY_PATH, 'bin', 'shopfloor_server'),
1455 '--dummy'])
1456 elif self.test_list.options.shopfloor_server_url:
1457 shopfloor.set_server_url(self.test_list.options.shopfloor_server_url)
Jon Salz2bf2f6b2013-03-28 18:49:26 +08001458 shopfloor.set_enabled(True)
Jon Salz23926422012-09-01 03:38:13 +08001459
Jon Salz0f996602012-10-03 15:26:48 +08001460 if self.test_list.options.time_sanitizer and not utils.in_chroot():
Jon Salz8fa8e832012-07-13 19:04:09 +08001461 self.time_sanitizer = time_sanitizer.TimeSanitizer(
Ricky Liang45c73e72015-01-15 15:00:30 +08001462 base_time=time_sanitizer.GetBaseTimeFromFile(
1463 # lsb-factory is written by the factory install shim during
1464 # installation, so it should have a good time obtained from
1465 # the mini-Omaha server. If it's not available, we'll use
1466 # /etc/lsb-factory (which will be much older, but reasonably
1467 # sane) and rely on a shopfloor sync to set a more accurate
1468 # time.
1469 '/usr/local/etc/lsb-factory',
1470 '/etc/lsb-release'))
Jon Salz8fa8e832012-07-13 19:04:09 +08001471 self.time_sanitizer.RunOnce()
1472
Vic Yangd8990da2013-06-27 16:57:43 +08001473 if self.test_list.options.check_cpu_usage_period_secs:
Ricky Liang45c73e72015-01-15 15:00:30 +08001474 self.cpu_usage_watcher = Spawn(
1475 ['py/tools/cpu_usage_monitor.py', '-p',
1476 str(self.test_list.options.check_cpu_usage_period_secs)],
Vic Yangd8990da2013-06-27 16:57:43 +08001477 cwd=factory.FACTORY_PATH)
1478
Jon Salz0697cbf2012-07-04 15:14:04 +08001479 self.init_states()
1480 self.start_event_server()
Wei-Ning Huang38b75f02015-02-25 18:25:14 +08001481 self.start_terminal_server()
Hung-Te Lincc41d2a2014-10-29 13:35:20 +08001482
1483 if self.options.dummy_connection_manager:
1484 # Override network manager creation to dummy implmenetation.
1485 logging.info('Using dummy network manager (--dummy_connection_manager).')
1486 self.connection_manager = connection_manager.DummyConnectionManager()
1487 else:
1488 self.connection_manager = self.env.create_connection_manager(
1489 self.test_list.options.wlans,
1490 self.test_list.options.scan_wifi_period_secs)
1491
Jon Salz0697cbf2012-07-04 15:14:04 +08001492 # Note that we create a log watcher even if
1493 # sync_event_log_period_secs isn't set (no background
1494 # syncing), since we may use it to flush event logs as well.
1495 self.log_watcher = EventLogWatcher(
Ricky Liang45c73e72015-01-15 15:00:30 +08001496 self.test_list.options.sync_event_log_period_secs,
1497 event_log_db_file=None,
1498 handle_event_logs_callback=self.handle_event_logs)
Jon Salz0697cbf2012-07-04 15:14:04 +08001499 if self.test_list.options.sync_event_log_period_secs:
1500 self.log_watcher.StartWatchThread()
1501
Cheng-Yi Chianga0f6eff2014-01-09 18:27:22 +08001502 # Creates a system log manager to scan logs periocially.
1503 # A scan includes clearing logs and optionally syncing logs if
1504 # enable_syng_log is True. We kick it to sync logs.
1505 self.system_log_manager = SystemLogManager(
Ricky Liang45c73e72015-01-15 15:00:30 +08001506 sync_log_paths=self.test_list.options.sync_log_paths,
1507 sync_log_period_secs=self.test_list.options.sync_log_period_secs,
1508 scan_log_period_secs=self.test_list.options.scan_log_period_secs,
1509 clear_log_paths=self.test_list.options.clear_log_paths,
1510 clear_log_excluded_paths=self.test_list.options.clear_log_excluded_paths)
Cheng-Yi Chianga0f6eff2014-01-09 18:27:22 +08001511 self.system_log_manager.Start()
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +08001512
Jon Salz0697cbf2012-07-04 15:14:04 +08001513 self.update_system_info()
1514
Vic Yang4953fc12012-07-26 16:19:53 +08001515 assert ((self.test_list.options.min_charge_pct is None) ==
1516 (self.test_list.options.max_charge_pct is None))
Vic Yange83d9a12013-04-19 20:00:20 +08001517 if utils.in_chroot():
1518 logging.info('In chroot, ignoring charge manager and charge state')
Ricky Liangc392a1c2014-06-20 18:24:59 +08001519 elif (self.test_list.options.enable_charge_manager and
1520 self.test_list.options.min_charge_pct is not None):
Vic Yang4953fc12012-07-26 16:19:53 +08001521 self.charge_manager = ChargeManager(self.test_list.options.min_charge_pct,
1522 self.test_list.options.max_charge_pct)
Jon Salzad7353b2012-10-15 16:22:46 +08001523 system.SystemStatus.charge_manager = self.charge_manager
Cheng-Yi Chiangd8186952013-04-04 23:41:14 +08001524 else:
1525 # Goofy should set charger state to charge if charge_manager is disabled.
Dean Liao88b93192014-10-23 19:37:41 +08001526 self.charge()
Vic Yang4953fc12012-07-26 16:19:53 +08001527
Vic Yang6cee2472014-10-22 17:18:52 -07001528 if CoreDumpManager.CoreDumpEnabled():
1529 self.core_dump_manager = CoreDumpManager(
1530 self.test_list.options.core_dump_watchlist)
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001531
Jon Salz0697cbf2012-07-04 15:14:04 +08001532 os.environ['CROS_FACTORY'] = '1'
1533 os.environ['CROS_DISABLE_SITE_SYSINFO'] = '1'
1534
Shuo-Peng Liao1ff502e2013-06-30 18:37:02 +08001535 if not utils.in_chroot() and self.test_list.options.use_cpufreq_manager:
Ricky Liangecddbd42014-07-24 11:32:10 +08001536 logging.info('Enabling CPU frequency manager')
Jon Salzddf0d052013-06-18 12:52:44 +08001537 self.cpufreq_manager = CpufreqManager(event_log=self.event_log)
Jon Salzce6a7f82013-06-10 18:22:54 +08001538
Justin Chuang31b02432013-06-27 15:16:51 +08001539 # Startup hooks may want to skip some tests.
1540 self.update_skipped_tests()
Jon Salz416f9cc2013-05-10 18:32:50 +08001541
Jon Salze12c2b32013-06-25 16:24:34 +08001542 self.find_kcrashes()
1543
Shuo-Peng Liao268b40b2013-07-01 15:58:59 +08001544 # Should not move earlier.
1545 self.hooks.OnStartup()
1546
Ricky Liang36512a32014-07-25 11:47:04 +08001547 # Only after this point the Goofy backend is ready for UI connection.
1548 self.ready_for_ui_connection = True
1549
Ricky Liang650f6bf2012-09-28 13:22:54 +08001550 # Create download path for autotest beforehand or autotests run at
1551 # the same time might fail due to race condition.
1552 if not factory.in_chroot():
1553 utils.TryMakeDirs(os.path.join('/usr/local/autotest', 'tests',
1554 'download'))
1555
Jon Salz0697cbf2012-07-04 15:14:04 +08001556 def state_change_callback(test, test_state):
1557 self.event_client.post_event(
Ricky Liang4bff3e32014-02-20 18:46:11 +08001558 Event(Event.Type.STATE_CHANGE, path=test.path, state=test_state))
Jon Salz0697cbf2012-07-04 15:14:04 +08001559 self.test_list.state_change_callback = state_change_callback
Jon Salz73e0fd02012-04-04 11:46:38 +08001560
Vic Yange2c76a82014-10-30 12:48:19 -07001561 self.autotest_prespawner = prespawner.AutotestPrespawner()
1562 self.autotest_prespawner.start()
1563
1564 self.pytest_prespawner = prespawner.PytestPrespawner()
1565 self.pytest_prespawner.start()
Jon Salza6711d72012-07-18 14:33:03 +08001566
Ricky Liang48e47f92014-02-26 19:31:51 +08001567 tests_after_shutdown = self.state_instance.get_shared_data(
1568 'tests_after_shutdown', optional=True)
Jon Salz57717ca2012-04-04 16:47:25 +08001569
Jon Salz5c344f62012-07-13 14:31:16 +08001570 force_auto_run = (tests_after_shutdown == FORCE_AUTO_RUN)
1571 if not force_auto_run and tests_after_shutdown is not None:
Ricky Liang48e47f92014-02-26 19:31:51 +08001572 logging.info('Resuming tests after shutdown: %s', tests_after_shutdown)
Jon Salz0697cbf2012-07-04 15:14:04 +08001573 self.tests_to_run.extend(
Ricky Liang4bff3e32014-02-20 18:46:11 +08001574 self.test_list.lookup_path(t) for t in tests_after_shutdown)
Peter Ammon1e1ec572014-06-26 17:56:32 -07001575 self.run_enqueue(self.run_next_test)
Jon Salz0697cbf2012-07-04 15:14:04 +08001576 else:
Jon Salz5c344f62012-07-13 14:31:16 +08001577 if force_auto_run or self.test_list.options.auto_run_on_start:
Ricky Liang117484a2014-04-14 11:14:41 +08001578 # If automation mode is enabled, allow suppress auto_run_on_start.
1579 if (self.options.automation_mode == 'NONE' or
1580 self.options.auto_run_on_start):
Peter Ammon1e1ec572014-06-26 17:56:32 -07001581 self.run_enqueue(
Ricky Liang117484a2014-04-14 11:14:41 +08001582 lambda: self.run_tests(self.test_list, untested_only=True))
Jon Salz5c344f62012-07-13 14:31:16 +08001583 self.state_instance.set_shared_data('tests_after_shutdown', None)
Ricky Liang4bff3e32014-02-20 18:46:11 +08001584 self.restore_active_run_state()
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001585
Vic Yang08505c72015-01-06 17:01:53 -08001586 system.GetBoard().OnTestStart()
1587
Dean Liao592e4d52013-01-10 20:06:39 +08001588 self.may_disable_cros_shortcut_keys()
1589
1590 def may_disable_cros_shortcut_keys(self):
1591 test_options = self.test_list.options
1592 if test_options.disable_cros_shortcut_keys:
1593 logging.info('Filter ChromeOS shortcut keys.')
1594 self.key_filter = KeyFilter(
1595 unmap_caps_lock=test_options.disable_caps_lock,
1596 caps_lock_keycode=test_options.caps_lock_keycode)
1597 self.key_filter.Start()
1598
Jon Salz0e6532d2012-10-25 16:30:11 +08001599 def _should_sync_time(self, foreground=False):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001600 """Returns True if we should attempt syncing time with shopfloor.
Jon Salz0e6532d2012-10-25 16:30:11 +08001601
1602 Args:
1603 foreground: If True, synchronizes even if background syncing
1604 is disabled (e.g., in explicit sync requests from the
1605 SyncShopfloor test).
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001606 """
Jon Salz0e6532d2012-10-25 16:30:11 +08001607 return ((foreground or
1608 self.test_list.options.sync_time_period_secs) and
Jon Salz54882d02012-08-31 01:57:54 +08001609 self.time_sanitizer and
1610 (not self.time_synced) and
1611 (not factory.in_chroot()))
1612
Jon Salz0e6532d2012-10-25 16:30:11 +08001613 def sync_time_with_shopfloor_server(self, foreground=False):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001614 """Syncs time with shopfloor server, if not yet synced.
Jon Salz54882d02012-08-31 01:57:54 +08001615
Jon Salz0e6532d2012-10-25 16:30:11 +08001616 Args:
1617 foreground: If True, synchronizes even if background syncing
1618 is disabled (e.g., in explicit sync requests from the
1619 SyncShopfloor test).
1620
Jon Salz54882d02012-08-31 01:57:54 +08001621 Returns:
1622 False if no time sanitizer is available, or True if this sync (or a
1623 previous sync) succeeded.
1624
1625 Raises:
1626 Exception if unable to contact the shopfloor server.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001627 """
Jon Salz0e6532d2012-10-25 16:30:11 +08001628 if self._should_sync_time(foreground):
Jon Salz54882d02012-08-31 01:57:54 +08001629 self.time_sanitizer.SyncWithShopfloor()
1630 self.time_synced = True
1631 return self.time_synced
1632
Jon Salzb92c5112012-09-21 15:40:11 +08001633 def log_disk_space_stats(self):
Jon Salz18e0e022013-06-11 17:13:39 +08001634 if (utils.in_chroot() or
1635 not self.test_list.options.log_disk_space_period_secs):
Jon Salzb92c5112012-09-21 15:40:11 +08001636 return
1637
1638 now = time.time()
1639 if (self.last_log_disk_space_time and
1640 now - self.last_log_disk_space_time <
1641 self.test_list.options.log_disk_space_period_secs):
1642 return
1643 self.last_log_disk_space_time = now
1644
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001645 # Upload event if stateful partition usage is above threshold.
1646 # Stateful partition is mounted on /usr/local, while
1647 # encrypted stateful partition is mounted on /var.
1648 # If there are too much logs in the factory process,
1649 # these two partitions might get full.
Jon Salzb92c5112012-09-21 15:40:11 +08001650 try:
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001651 vfs_infos = disk_space.GetAllVFSInfo()
1652 stateful_info, encrypted_info = None, None
1653 for vfs_info in vfs_infos.values():
1654 if '/usr/local' in vfs_info.mount_points:
1655 stateful_info = vfs_info
1656 if '/var' in vfs_info.mount_points:
1657 encrypted_info = vfs_info
1658
1659 stateful = disk_space.GetPartitionUsage(stateful_info)
1660 encrypted = disk_space.GetPartitionUsage(encrypted_info)
1661
Ricky Liang45c73e72015-01-15 15:00:30 +08001662 above_threshold = (
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001663 self.test_list.options.stateful_usage_threshold and
1664 max(stateful.bytes_used_pct,
1665 stateful.inodes_used_pct,
1666 encrypted.bytes_used_pct,
1667 encrypted.inodes_used_pct) >
Ricky Liang45c73e72015-01-15 15:00:30 +08001668 self.test_list.options.stateful_usage_threshold)
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001669
1670 if above_threshold:
1671 self.event_log.Log('stateful_partition_usage',
Ricky Liang45c73e72015-01-15 15:00:30 +08001672 partitions={
1673 'stateful': {
1674 'bytes_used_pct': FloatDigit(stateful.bytes_used_pct, 2),
1675 'inodes_used_pct': FloatDigit(stateful.inodes_used_pct, 2)},
1676 'encrypted_stateful': {
1677 'bytes_used_pct': FloatDigit(encrypted.bytes_used_pct, 2),
1678 'inodes_used_pct': FloatDigit(encrypted.inodes_used_pct, 2)}
1679 })
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001680 self.log_watcher.ScanEventLogs()
Cheng-Yi Chiang00798e72013-06-20 18:16:39 +08001681 if (not utils.in_chroot() and
1682 self.test_list.options.stateful_usage_above_threshold_action):
1683 Spawn(self.test_list.options.stateful_usage_above_threshold_action,
1684 call=True)
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001685
1686 message = disk_space.FormatSpaceUsedAll(vfs_infos)
Jon Salz3c493bb2013-02-07 17:24:58 +08001687 if message != self.last_log_disk_space_message:
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001688 if above_threshold:
1689 logging.warning(message)
1690 else:
1691 logging.info(message)
Jon Salz3c493bb2013-02-07 17:24:58 +08001692 self.last_log_disk_space_message = message
Jon Salzb92c5112012-09-21 15:40:11 +08001693 except: # pylint: disable=W0702
1694 logging.exception('Unable to get disk space used')
1695
Justin Chuang83813982013-05-13 01:26:32 +08001696 def check_battery(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001697 """Checks the current battery status.
Justin Chuang83813982013-05-13 01:26:32 +08001698
1699 Logs current battery charging level and status to log. If the battery level
1700 is lower below warning_low_battery_pct, send warning event to shopfloor.
1701 If the battery level is lower below critical_low_battery_pct, flush disks.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001702 """
Justin Chuang83813982013-05-13 01:26:32 +08001703 if not self.test_list.options.check_battery_period_secs:
1704 return
1705
1706 now = time.time()
1707 if (self.last_check_battery_time and
1708 now - self.last_check_battery_time <
1709 self.test_list.options.check_battery_period_secs):
1710 return
1711 self.last_check_battery_time = now
1712
1713 message = ''
1714 log_level = logging.INFO
1715 try:
1716 power = system.GetBoard().power
1717 if not power.CheckBatteryPresent():
1718 message = 'Battery is not present'
1719 else:
1720 ac_present = power.CheckACPresent()
1721 charge_pct = power.GetChargePct(get_float=True)
1722 message = ('Current battery level %.1f%%, AC charger is %s' %
1723 (charge_pct, 'connected' if ac_present else 'disconnected'))
1724
1725 if charge_pct > self.test_list.options.critical_low_battery_pct:
1726 critical_low_battery = False
1727 else:
1728 critical_low_battery = True
1729 # Only sync disks when battery level is still above minimum
1730 # value. This can be used for offline analysis when shopfloor cannot
1731 # be connected.
1732 if charge_pct > MIN_BATTERY_LEVEL_FOR_DISK_SYNC:
1733 logging.warning('disk syncing for critical low battery situation')
1734 os.system('sync; sync; sync')
1735 else:
1736 logging.warning('disk syncing is cancelled '
1737 'because battery level is lower than %.1f',
1738 MIN_BATTERY_LEVEL_FOR_DISK_SYNC)
1739
1740 # Notify shopfloor server
1741 if (critical_low_battery or
1742 (not ac_present and
1743 charge_pct <= self.test_list.options.warning_low_battery_pct)):
1744 log_level = logging.WARNING
1745
1746 self.event_log.Log('low_battery',
1747 battery_level=charge_pct,
1748 charger_connected=ac_present,
1749 critical=critical_low_battery)
1750 self.log_watcher.KickWatchThread()
Cheng-Yi Chianga0f6eff2014-01-09 18:27:22 +08001751 if self.test_list.options.enable_sync_log:
1752 self.system_log_manager.KickToSync()
Ricky Liang45c73e72015-01-15 15:00:30 +08001753 except: # pylint: disable=W0702
Justin Chuang83813982013-05-13 01:26:32 +08001754 logging.exception('Unable to check battery or notify shopfloor')
1755 finally:
1756 if message != self.last_check_battery_message:
1757 logging.log(log_level, message)
1758 self.last_check_battery_message = message
1759
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001760 def check_core_dump(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001761 """Checks if there is any core dumped file.
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001762
1763 Removes unwanted core dump files immediately.
1764 Syncs those files matching watch list to server with a delay between
1765 each sync. After the files have been synced to server, deletes the files.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001766 """
Vic Yang6cee2472014-10-22 17:18:52 -07001767 if not self.core_dump_manager:
1768 return
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001769 core_dump_files = self.core_dump_manager.ScanFiles()
1770 if core_dump_files:
1771 now = time.time()
1772 if (self.last_kick_sync_time and now - self.last_kick_sync_time <
1773 self.test_list.options.kick_sync_min_interval_secs):
1774 return
1775 self.last_kick_sync_time = now
1776
1777 # Sends event to server
1778 self.event_log.Log('core_dumped', files=core_dump_files)
1779 self.log_watcher.KickWatchThread()
1780
1781 # Syncs files to server
Cheng-Yi Chianga0f6eff2014-01-09 18:27:22 +08001782 if self.test_list.options.enable_sync_log:
1783 self.system_log_manager.KickToSync(
Cheng-Yi Chiangd3516a32013-07-17 15:30:47 +08001784 core_dump_files, self.core_dump_manager.ClearFiles)
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001785
Cheng-Yi Chiang39d32ad2013-07-23 15:02:38 +08001786 def check_log_rotation(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001787 """Checks log rotation file presence/absence according to test_list option.
Cheng-Yi Chiang39d32ad2013-07-23 15:02:38 +08001788
1789 Touch /var/lib/cleanup_logs_paused if test_list.options.disable_log_rotation
1790 is True, delete it otherwise. This must be done in idle loop because
1791 autotest client will touch /var/lib/cleanup_logs_paused each time it runs
1792 an autotest.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001793 """
Cheng-Yi Chiang39d32ad2013-07-23 15:02:38 +08001794 if utils.in_chroot():
1795 return
1796 try:
1797 if self.test_list.options.disable_log_rotation:
1798 open(CLEANUP_LOGS_PAUSED, 'w').close()
1799 else:
1800 file_utils.TryUnlink(CLEANUP_LOGS_PAUSED)
1801 except: # pylint: disable=W0702
1802 # Oh well. Logs an error (but no trace)
1803 logging.info(
1804 'Unable to %s %s: %s',
1805 'touch' if self.test_list.options.disable_log_rotation else 'delete',
1806 CLEANUP_LOGS_PAUSED, utils.FormatExceptionOnly())
1807
Jon Salz8fa8e832012-07-13 19:04:09 +08001808 def sync_time_in_background(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001809 """Writes out current time and tries to sync with shopfloor server."""
Jon Salzb22d1172012-08-06 10:38:57 +08001810 if not self.time_sanitizer:
1811 return
1812
1813 # Write out the current time.
1814 self.time_sanitizer.SaveTime()
1815
Jon Salz54882d02012-08-31 01:57:54 +08001816 if not self._should_sync_time():
Jon Salz8fa8e832012-07-13 19:04:09 +08001817 return
1818
1819 now = time.time()
1820 if self.last_sync_time and (
1821 now - self.last_sync_time <
1822 self.test_list.options.sync_time_period_secs):
1823 # Not yet time for another check.
1824 return
1825 self.last_sync_time = now
1826
1827 def target():
1828 try:
Jon Salz54882d02012-08-31 01:57:54 +08001829 self.sync_time_with_shopfloor_server()
Jon Salz8fa8e832012-07-13 19:04:09 +08001830 except: # pylint: disable=W0702
1831 # Oh well. Log an error (but no trace)
1832 logging.info(
Ricky Liang45c73e72015-01-15 15:00:30 +08001833 'Unable to get time from shopfloor server: %s',
1834 utils.FormatExceptionOnly())
Jon Salz8fa8e832012-07-13 19:04:09 +08001835
1836 thread = threading.Thread(target=target)
1837 thread.daemon = True
1838 thread.start()
1839
Peter Ammon1e1ec572014-06-26 17:56:32 -07001840 def perform_periodic_tasks(self):
1841 """Override of base method to perform periodic work.
Vic Yang4953fc12012-07-26 16:19:53 +08001842
Peter Ammon1e1ec572014-06-26 17:56:32 -07001843 This method must not raise exceptions.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001844 """
Peter Ammon1e1ec572014-06-26 17:56:32 -07001845 super(Goofy, self).perform_periodic_tasks()
Jon Salzb22d1172012-08-06 10:38:57 +08001846
Vic Yang311ddb82012-09-26 12:08:28 +08001847 self.check_exclusive()
cychiang21886742012-07-05 15:16:32 +08001848 self.check_for_updates()
Jon Salz8fa8e832012-07-13 19:04:09 +08001849 self.sync_time_in_background()
Jon Salzb92c5112012-09-21 15:40:11 +08001850 self.log_disk_space_stats()
Justin Chuang83813982013-05-13 01:26:32 +08001851 self.check_battery()
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001852 self.check_core_dump()
Cheng-Yi Chiang39d32ad2013-07-23 15:02:38 +08001853 self.check_log_rotation()
Jon Salz57717ca2012-04-04 16:47:25 +08001854
Jon Salzd15bbcf2013-05-21 17:33:57 +08001855 def handle_event_logs(self, chunks):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001856 """Callback for event watcher.
Jon Salz258a40c2012-04-19 12:34:01 +08001857
Jon Salz0697cbf2012-07-04 15:14:04 +08001858 Attempts to upload the event logs to the shopfloor server.
Vic Yang93027612013-05-06 02:42:49 +08001859
1860 Args:
Jon Salzd15bbcf2013-05-21 17:33:57 +08001861 chunks: A list of Chunk objects.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001862 """
Vic Yang93027612013-05-06 02:42:49 +08001863 first_exception = None
1864 exception_count = 0
1865
Jon Salzd15bbcf2013-05-21 17:33:57 +08001866 for chunk in chunks:
Vic Yang93027612013-05-06 02:42:49 +08001867 try:
Jon Salzcddb6402013-05-23 12:56:42 +08001868 description = 'event logs (%s)' % str(chunk)
Vic Yang93027612013-05-06 02:42:49 +08001869 start_time = time.time()
1870 shopfloor_client = shopfloor.get_instance(
Ricky Liang45c73e72015-01-15 15:00:30 +08001871 detect=True,
1872 timeout=self.test_list.options.shopfloor_timeout_secs)
1873 shopfloor_client.UploadEvent(chunk.log_name + '.' +
Jon Salzd15bbcf2013-05-21 17:33:57 +08001874 event_log.GetReimageId(),
1875 Binary(chunk.chunk))
Vic Yang93027612013-05-06 02:42:49 +08001876 logging.info(
Ricky Liang45c73e72015-01-15 15:00:30 +08001877 'Successfully synced %s in %.03f s',
1878 description, time.time() - start_time)
1879 except: # pylint: disable=W0702
Jon Salzd15bbcf2013-05-21 17:33:57 +08001880 first_exception = (first_exception or (chunk.log_name + ': ' +
Vic Yang93027612013-05-06 02:42:49 +08001881 utils.FormatExceptionOnly()))
1882 exception_count += 1
1883
1884 if exception_count:
1885 if exception_count == 1:
1886 msg = 'Log upload failed: %s' % first_exception
1887 else:
1888 msg = '%d log upload failed; first is: %s' % (
1889 exception_count, first_exception)
1890 raise Exception(msg)
1891
Ricky Liang45c73e72015-01-15 15:00:30 +08001892 def run_tests_with_status(self, statuses_to_run, starting_at=None, root=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001893 """Runs all top-level tests with a particular status.
Jon Salz0405ab52012-03-16 15:26:52 +08001894
Jon Salz0697cbf2012-07-04 15:14:04 +08001895 All active tests, plus any tests to re-run, are reset.
Jon Salz57717ca2012-04-04 16:47:25 +08001896
Jon Salz0697cbf2012-07-04 15:14:04 +08001897 Args:
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001898 statuses_to_run: The particular status that caller wants to run.
Jon Salz0697cbf2012-07-04 15:14:04 +08001899 starting_at: If provided, only auto-runs tests beginning with
1900 this test.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001901 root: The root of tests to run. If not provided, it will be
1902 the root of all tests.
1903 """
Jon Salz0697cbf2012-07-04 15:14:04 +08001904 root = root or self.test_list
Jon Salz57717ca2012-04-04 16:47:25 +08001905
Jon Salz0697cbf2012-07-04 15:14:04 +08001906 if starting_at:
1907 # Make sure they passed a test, not a string.
1908 assert isinstance(starting_at, factory.FactoryTest)
Jon Salz0405ab52012-03-16 15:26:52 +08001909
Jon Salz0697cbf2012-07-04 15:14:04 +08001910 tests_to_reset = []
1911 tests_to_run = []
Jon Salz0405ab52012-03-16 15:26:52 +08001912
Jon Salz0697cbf2012-07-04 15:14:04 +08001913 found_starting_at = False
Jon Salz0405ab52012-03-16 15:26:52 +08001914
Jon Salz0697cbf2012-07-04 15:14:04 +08001915 for test in root.get_top_level_tests():
1916 if starting_at:
1917 if test == starting_at:
1918 # We've found starting_at; do auto-run on all
1919 # subsequent tests.
1920 found_starting_at = True
1921 if not found_starting_at:
1922 # Don't start this guy yet
1923 continue
Jon Salz0405ab52012-03-16 15:26:52 +08001924
Jon Salz0697cbf2012-07-04 15:14:04 +08001925 status = test.get_state().status
1926 if status == TestState.ACTIVE or status in statuses_to_run:
1927 # Reset the test (later; we will need to abort
1928 # all active tests first).
1929 tests_to_reset.append(test)
1930 if status in statuses_to_run:
1931 tests_to_run.append(test)
Jon Salz0405ab52012-03-16 15:26:52 +08001932
Jon Salz6dc031d2013-06-19 13:06:23 +08001933 self.abort_active_tests('Operator requested run/re-run of certain tests')
Jon Salz258a40c2012-04-19 12:34:01 +08001934
Jon Salz0697cbf2012-07-04 15:14:04 +08001935 # Reset all statuses of the tests to run (in case any tests were active;
1936 # we want them to be run again).
1937 for test_to_reset in tests_to_reset:
1938 for test in test_to_reset.walk():
1939 test.update_state(status=TestState.UNTESTED)
Jon Salz57717ca2012-04-04 16:47:25 +08001940
Jon Salz0697cbf2012-07-04 15:14:04 +08001941 self.run_tests(tests_to_run, untested_only=True)
Jon Salz0405ab52012-03-16 15:26:52 +08001942
Jon Salz0697cbf2012-07-04 15:14:04 +08001943 def restart_tests(self, root=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001944 """Restarts all tests."""
Jon Salz0697cbf2012-07-04 15:14:04 +08001945 root = root or self.test_list
Jon Salz0405ab52012-03-16 15:26:52 +08001946
Jon Salz6dc031d2013-06-19 13:06:23 +08001947 self.abort_active_tests('Operator requested restart of certain tests')
Jon Salz0697cbf2012-07-04 15:14:04 +08001948 for test in root.walk():
Ricky Liangfea4ac92014-08-21 11:55:59 +08001949 test.update_state(status=TestState.UNTESTED)
Jon Salz0697cbf2012-07-04 15:14:04 +08001950 self.run_tests(root)
Hung-Te Lin96632362012-03-20 21:14:18 +08001951
Jon Salz0697cbf2012-07-04 15:14:04 +08001952 def auto_run(self, starting_at=None, root=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001953 """"Auto-runs" tests that have not been run yet.
Hung-Te Lin96632362012-03-20 21:14:18 +08001954
Jon Salz0697cbf2012-07-04 15:14:04 +08001955 Args:
1956 starting_at: If provide, only auto-runs tests beginning with
1957 this test.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001958 root: If provided, the root of tests to run. If not provided, the root
1959 will be test_list (root of all tests).
1960 """
Jon Salz0697cbf2012-07-04 15:14:04 +08001961 root = root or self.test_list
1962 self.run_tests_with_status([TestState.UNTESTED, TestState.ACTIVE],
Ricky Liang45c73e72015-01-15 15:00:30 +08001963 starting_at=starting_at,
1964 root=root)
Jon Salz968e90b2012-03-18 16:12:43 +08001965
Jon Salz0697cbf2012-07-04 15:14:04 +08001966 def re_run_failed(self, root=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001967 """Re-runs failed tests."""
Jon Salz0697cbf2012-07-04 15:14:04 +08001968 root = root or self.test_list
1969 self.run_tests_with_status([TestState.FAILED], root=root)
Jon Salz57717ca2012-04-04 16:47:25 +08001970
Jon Salz0697cbf2012-07-04 15:14:04 +08001971 def show_review_information(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001972 """Event handler for showing review information screen.
Jon Salz57717ca2012-04-04 16:47:25 +08001973
Peter Ammon1e1ec572014-06-26 17:56:32 -07001974 The information screen is rendered by main UI program (ui.py), so in
Jon Salz0697cbf2012-07-04 15:14:04 +08001975 goofy we only need to kill all active tests, set them as untested, and
1976 clear remaining tests.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001977 """
Jon Salz0697cbf2012-07-04 15:14:04 +08001978 self.kill_active_tests(False)
Jon Salza6711d72012-07-18 14:33:03 +08001979 self.cancel_pending_tests()
Jon Salz57717ca2012-04-04 16:47:25 +08001980
Jon Salz0697cbf2012-07-04 15:14:04 +08001981 def handle_switch_test(self, event):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001982 """Switches to a particular test.
Jon Salz0405ab52012-03-16 15:26:52 +08001983
Ricky Liang6fe218c2013-12-27 15:17:17 +08001984 Args:
1985 event: The SWITCH_TEST event.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001986 """
Jon Salz0697cbf2012-07-04 15:14:04 +08001987 test = self.test_list.lookup_path(event.path)
1988 if not test:
1989 logging.error('Unknown test %r', event.key)
1990 return
Jon Salz73e0fd02012-04-04 11:46:38 +08001991
Jon Salz0697cbf2012-07-04 15:14:04 +08001992 invoc = self.invocations.get(test)
1993 if invoc and test.backgroundable:
1994 # Already running: just bring to the front if it
1995 # has a UI.
1996 logging.info('Setting visible test to %s', test.path)
Jon Salz36fbbb52012-07-05 13:45:06 +08001997 self.set_visible_test(test)
Jon Salz0697cbf2012-07-04 15:14:04 +08001998 return
Jon Salz73e0fd02012-04-04 11:46:38 +08001999
Jon Salz6dc031d2013-06-19 13:06:23 +08002000 self.abort_active_tests('Operator requested abort (switch_test)')
Jon Salz0697cbf2012-07-04 15:14:04 +08002001 for t in test.walk():
2002 t.update_state(status=TestState.UNTESTED)
Jon Salz73e0fd02012-04-04 11:46:38 +08002003
Jon Salz0697cbf2012-07-04 15:14:04 +08002004 if self.test_list.options.auto_run_on_keypress:
2005 self.auto_run(starting_at=test)
2006 else:
2007 self.run_tests(test)
Jon Salz73e0fd02012-04-04 11:46:38 +08002008
Wei-Ning Huang38b75f02015-02-25 18:25:14 +08002009 def handle_key_filter_mode(self, event):
2010 if self.key_filter:
2011 if getattr(event, 'enabled'):
2012 self.key_filter.Start()
2013 else:
2014 self.key_filter.Stop()
2015
Jon Salz0697cbf2012-07-04 15:14:04 +08002016 def wait(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08002017 """Waits for all pending invocations.
Jon Salz0697cbf2012-07-04 15:14:04 +08002018
2019 Useful for testing.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08002020 """
Jon Salz1acc8742012-07-17 17:45:55 +08002021 while self.invocations:
2022 for k, v in self.invocations.iteritems():
2023 logging.info('Waiting for %s to complete...', k)
2024 v.thread.join()
2025 self.reap_completed_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +08002026
Hung-Te Linf2f78f72012-02-08 19:27:11 +08002027if __name__ == '__main__':
Peter Ammona3d298c2014-09-23 10:11:02 -07002028 Goofy.run_main_and_exit()