blob: 4fe1589a18dc65c51c1932380d5381ec3af9168e [file] [log] [blame]
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001#!/usr/bin/python -u
Hung-Te Linf2f78f72012-02-08 19:27:11 +08002# -*- coding: utf-8 -*-
3#
Jon Salz37eccbd2012-05-25 16:06:52 +08004# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
Hung-Te Linf2f78f72012-02-08 19:27:11 +08005# Use of this source code is governed by a BSD-style license that can be
6# found in the LICENSE file.
7
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08008"""The main factory flow that runs the factory test and finalizes a device."""
Hung-Te Linf2f78f72012-02-08 19:27:11 +08009
Joel Kitchingb85ed7f2014-10-08 18:24:39 +080010from __future__ import print_function
11
Jon Salze12c2b32013-06-25 16:24:34 +080012import glob
Jon Salz0405ab52012-03-16 15:26:52 +080013import logging
14import os
Jon Salze12c2b32013-06-25 16:24:34 +080015import shutil
Jon Salz77c151e2012-08-28 07:20:37 +080016import signal
Jon Salz0405ab52012-03-16 15:26:52 +080017import sys
Jon Salzeff94182013-06-19 15:06:28 +080018import syslog
Jon Salz0405ab52012-03-16 15:26:52 +080019import threading
20import time
21import traceback
Jon Salz258a40c2012-04-19 12:34:01 +080022import uuid
Jon Salzb10cf512012-08-09 17:29:21 +080023from xmlrpclib import Binary
Hung-Te Linf2f78f72012-02-08 19:27:11 +080024from collections import deque
25from optparse import OptionParser
Hung-Te Linf2f78f72012-02-08 19:27:11 +080026
Jon Salz0697cbf2012-07-04 15:14:04 +080027import factory_common # pylint: disable=W0611
Hung-Te Lin91492a12014-11-25 18:56:30 +080028from cros.factory.test import event_log
jcliangcd688182012-08-20 21:01:26 +080029from cros.factory import system
Hung-Te Lin91492a12014-11-25 18:56:30 +080030from cros.factory.test.event_log import EventLog, FloatDigit
Hung-Te Lincc41d2a2014-10-29 13:35:20 +080031from cros.factory.goofy import connection_manager
Vic Yangd80ea752014-09-24 16:07:14 +080032from cros.factory.goofy import test_environment
33from cros.factory.goofy import time_sanitizer
34from cros.factory.goofy import updater
35from cros.factory.goofy.goofy_base import GoofyBase
36from cros.factory.goofy.goofy_rpc import GoofyRPC
37from cros.factory.goofy.invocation import TestArgEnv
38from cros.factory.goofy.invocation import TestInvocation
39from cros.factory.goofy.link_manager import PresenterLinkManager
Vic Yange2c76a82014-10-30 12:48:19 -070040from cros.factory.goofy import prespawner
Vic Yangd80ea752014-09-24 16:07:14 +080041from cros.factory.goofy.system_log_manager import SystemLogManager
Wei-Ning Huang38b75f02015-02-25 18:25:14 +080042from cros.factory.goofy.terminal_manager import TerminalManager
Vic Yangd80ea752014-09-24 16:07:14 +080043from cros.factory.goofy.web_socket_manager import WebSocketManager
Cheng-Yi Chiangd8186952013-04-04 23:41:14 +080044from cros.factory.system.board import Board, BoardException
jcliangcd688182012-08-20 21:01:26 +080045from cros.factory.system.charge_manager import ChargeManager
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +080046from cros.factory.system.core_dump_manager import CoreDumpManager
Jon Salzce6a7f82013-06-10 18:22:54 +080047from cros.factory.system.cpufreq_manager import CpufreqManager
Jon Salzb92c5112012-09-21 15:40:11 +080048from cros.factory.system import disk_space
jcliangcd688182012-08-20 21:01:26 +080049from cros.factory.test import factory
Jon Salz670ce062014-05-16 15:53:50 +080050from cros.factory.test import phase
jcliangcd688182012-08-20 21:01:26 +080051from cros.factory.test import state
Jon Salz51528e12012-07-02 18:54:45 +080052from cros.factory.test import shopfloor
Jon Salz83591782012-06-26 11:09:58 +080053from cros.factory.test import utils
Jon Salz128b0932013-07-03 16:55:26 +080054from cros.factory.test.test_lists import test_lists
Ricky Liang6fe218c2013-12-27 15:17:17 +080055from cros.factory.test.e2e_test.common import (
56 AutomationMode, AutomationModePrompt, ParseAutomationMode)
Jon Salz83591782012-06-26 11:09:58 +080057from cros.factory.test.event import Event
58from cros.factory.test.event import EventClient
59from cros.factory.test.event import EventServer
Hung-Te Lin91492a12014-11-25 18:56:30 +080060from cros.factory.test.event_log_watcher import EventLogWatcher
jcliangcd688182012-08-20 21:01:26 +080061from cros.factory.test.factory import TestState
Jon Salzd7550792013-07-12 05:49:27 +080062from cros.factory.test.utils import Enum
Dean Liao592e4d52013-01-10 20:06:39 +080063from cros.factory.tools.key_filter import KeyFilter
Jon Salz2af235d2013-06-24 14:47:21 +080064from cros.factory.utils import file_utils
Joel Kitchingb85ed7f2014-10-08 18:24:39 +080065from cros.factory.utils import net_utils
Jon Salz78c32392012-07-25 14:18:29 +080066from cros.factory.utils.process_utils import Spawn
Hung-Te Linf2f78f72012-02-08 19:27:11 +080067
68
Hung-Te Linf2f78f72012-02-08 19:27:11 +080069HWID_CFG_PATH = '/usr/local/share/chromeos-hwid/cfg'
Ricky Liang45c73e72015-01-15 15:00:30 +080070CACHES_DIR = os.path.join(factory.get_state_root(), 'caches')
Hung-Te Linf2f78f72012-02-08 19:27:11 +080071
Cheng-Yi Chiang39d32ad2013-07-23 15:02:38 +080072CLEANUP_LOGS_PAUSED = '/var/lib/cleanup_logs_paused'
73
Jon Salz5c344f62012-07-13 14:31:16 +080074# Value for tests_after_shutdown that forces auto-run (e.g., after
75# a factory update, when the available set of tests might change).
76FORCE_AUTO_RUN = 'force_auto_run'
77
Justin Chuang83813982013-05-13 01:26:32 +080078# Sync disks when battery level is higher than this value.
79# Otherwise, power loss during disk sync operation may incur even worse outcome.
80MIN_BATTERY_LEVEL_FOR_DISK_SYNC = 1.0
81
Ricky Liang45c73e72015-01-15 15:00:30 +080082MAX_CRASH_FILE_SIZE = 64 * 1024
Jon Salze12c2b32013-06-25 16:24:34 +080083
Jon Salzd7550792013-07-12 05:49:27 +080084Status = Enum(['UNINITIALIZED', 'INITIALIZING', 'RUNNING',
85 'TERMINATING', 'TERMINATED'])
86
Ricky Liang45c73e72015-01-15 15:00:30 +080087
Hung-Te Linf2f78f72012-02-08 19:27:11 +080088def get_hwid_cfg():
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +080089 """Returns the HWID config tag, or an empty string if none can be found."""
Jon Salz0697cbf2012-07-04 15:14:04 +080090 if 'CROS_HWID' in os.environ:
91 return os.environ['CROS_HWID']
92 if os.path.exists(HWID_CFG_PATH):
Ricky Liang45c73e72015-01-15 15:00:30 +080093 with open(HWID_CFG_PATH, 'r') as hwid_cfg_handle:
Jon Salz0697cbf2012-07-04 15:14:04 +080094 return hwid_cfg_handle.read().strip()
95 return ''
Hung-Te Linf2f78f72012-02-08 19:27:11 +080096
97
Jon Salz73e0fd02012-04-04 11:46:38 +080098_inited_logging = False
Hung-Te Linf2f78f72012-02-08 19:27:11 +080099
Ricky Liang45c73e72015-01-15 15:00:30 +0800100
Peter Ammon1e1ec572014-06-26 17:56:32 -0700101class Goofy(GoofyBase):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800102 """The main factory flow.
Jon Salz0697cbf2012-07-04 15:14:04 +0800103
104 Note that all methods in this class must be invoked from the main
105 (event) thread. Other threads, such as callbacks and TestInvocation
106 methods, should instead post events on the run queue.
107
108 TODO: Unit tests. (chrome-os-partner:7409)
109
110 Properties:
111 uuid: A unique UUID for this invocation of Goofy.
112 state_instance: An instance of FactoryState.
113 state_server: The FactoryState XML/RPC server.
114 state_server_thread: A thread running state_server.
115 event_server: The EventServer socket server.
116 event_server_thread: A thread running event_server.
117 event_client: A client to the event server.
118 connection_manager: The connection_manager object.
Cheng-Yi Chiang835f2682013-05-06 22:15:48 +0800119 system_log_manager: The SystemLogManager object.
120 core_dump_manager: The CoreDumpManager object.
Jon Salz0697cbf2012-07-04 15:14:04 +0800121 ui_process: The factory ui process object.
Jon Salz0697cbf2012-07-04 15:14:04 +0800122 invocations: A map from FactoryTest objects to the corresponding
123 TestInvocations objects representing active tests.
124 tests_to_run: A deque of tests that should be run when the current
125 test(s) complete.
126 options: Command-line options.
127 args: Command-line args.
128 test_list: The test list.
Jon Salz128b0932013-07-03 16:55:26 +0800129 test_lists: All new-style test lists.
Ricky Liang4bff3e32014-02-20 18:46:11 +0800130 run_id: The identifier for latest test run.
131 scheduled_run_tests: The list of tests scheduled for latest test run.
Jon Salz0697cbf2012-07-04 15:14:04 +0800132 event_handlers: Map of Event.Type to the method used to handle that
133 event. If the method has an 'event' argument, the event is passed
134 to the handler.
Jon Salz3c493bb2013-02-07 17:24:58 +0800135 last_log_disk_space_message: The last message we logged about disk space
136 (to avoid duplication).
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +0800137 last_kick_sync_time: The last time to kick system_log_manager to sync
138 because of core dump files (to avoid kicking too soon then abort the
139 sync.)
Jon Salz416f9cc2013-05-10 18:32:50 +0800140 hooks: A Hooks object containing hooks for various Goofy actions.
Jon Salzd7550792013-07-12 05:49:27 +0800141 status: The current Goofy status (a member of the Status enum).
Peter Ammon948b7172014-07-15 12:43:06 -0700142 link_manager: Instance of PresenterLinkManager for communicating
143 with GoofyPresenter
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800144 """
Ricky Liang45c73e72015-01-15 15:00:30 +0800145
Jon Salz0697cbf2012-07-04 15:14:04 +0800146 def __init__(self):
Peter Ammon1e1ec572014-06-26 17:56:32 -0700147 super(Goofy, self).__init__()
Jon Salz0697cbf2012-07-04 15:14:04 +0800148 self.uuid = str(uuid.uuid4())
149 self.state_instance = None
150 self.state_server = None
151 self.state_server_thread = None
Jon Salz16d10542012-07-23 12:18:45 +0800152 self.goofy_rpc = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800153 self.event_server = None
154 self.event_server_thread = None
155 self.event_client = None
156 self.connection_manager = None
Vic Yang4953fc12012-07-26 16:19:53 +0800157 self.charge_manager = None
Dean Liao88b93192014-10-23 19:37:41 +0800158 self._can_charge = True
Jon Salz8fa8e832012-07-13 19:04:09 +0800159 self.time_sanitizer = None
160 self.time_synced = False
Jon Salz0697cbf2012-07-04 15:14:04 +0800161 self.log_watcher = None
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +0800162 self.system_log_manager = None
Cheng-Yi Chiang835f2682013-05-06 22:15:48 +0800163 self.core_dump_manager = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800164 self.event_log = None
Vic Yange2c76a82014-10-30 12:48:19 -0700165 self.autotest_prespawner = None
166 self.pytest_prespawner = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800167 self.ui_process = None
Vic Yanga3cecf82014-12-26 00:44:21 -0800168 self._ui_initialized = False
Jon Salzc79a9982012-08-30 04:42:01 +0800169 self.dummy_shopfloor = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800170 self.invocations = {}
171 self.tests_to_run = deque()
172 self.visible_test = None
173 self.chrome = None
Jon Salz416f9cc2013-05-10 18:32:50 +0800174 self.hooks = None
Vic Yangd8990da2013-06-27 16:57:43 +0800175 self.cpu_usage_watcher = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800176
177 self.options = None
178 self.args = None
179 self.test_list = None
Jon Salz128b0932013-07-03 16:55:26 +0800180 self.test_lists = None
Ricky Liang4bff3e32014-02-20 18:46:11 +0800181 self.run_id = None
182 self.scheduled_run_tests = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800183 self.env = None
Jon Salzb22d1172012-08-06 10:38:57 +0800184 self.last_idle = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800185 self.last_shutdown_time = None
cychiang21886742012-07-05 15:16:32 +0800186 self.last_update_check = None
Cheng-Yi Chiang194d3c02015-03-16 14:37:15 +0800187 self._suppress_periodic_update_messages = False
Cheng-Yi Chiangf5b21012015-03-17 15:37:14 +0800188 self._suppress_event_log_error_messages = False
Jon Salz8fa8e832012-07-13 19:04:09 +0800189 self.last_sync_time = None
Jon Salzb92c5112012-09-21 15:40:11 +0800190 self.last_log_disk_space_time = None
Jon Salz3c493bb2013-02-07 17:24:58 +0800191 self.last_log_disk_space_message = None
Justin Chuang83813982013-05-13 01:26:32 +0800192 self.last_check_battery_time = None
193 self.last_check_battery_message = None
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +0800194 self.last_kick_sync_time = None
Vic Yang311ddb82012-09-26 12:08:28 +0800195 self.exclusive_items = set()
Jon Salz0f996602012-10-03 15:26:48 +0800196 self.event_log = None
Dean Liao592e4d52013-01-10 20:06:39 +0800197 self.key_filter = None
Jon Salzce6a7f82013-06-10 18:22:54 +0800198 self.cpufreq_manager = None
Jon Salzd7550792013-07-12 05:49:27 +0800199 self.status = Status.UNINITIALIZED
Ricky Liang36512a32014-07-25 11:47:04 +0800200 self.ready_for_ui_connection = False
Peter Ammon1e1ec572014-06-26 17:56:32 -0700201 self.link_manager = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800202
Jon Salz85a39882012-07-05 16:45:04 +0800203 def test_or_root(event, parent_or_group=True):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800204 """Returns the test affected by a particular event.
Jon Salz85a39882012-07-05 16:45:04 +0800205
206 Args:
207 event: The event containing an optional 'path' attribute.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800208 parent_or_group: If True, returns the top-level parent for a test (the
Jon Salz85a39882012-07-05 16:45:04 +0800209 root node of the tests that need to be run together if the given test
210 path is to be run).
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800211 """
Jon Salz0697cbf2012-07-04 15:14:04 +0800212 try:
213 path = event.path
214 except AttributeError:
215 path = None
216
217 if path:
Jon Salz85a39882012-07-05 16:45:04 +0800218 test = self.test_list.lookup_path(path)
219 if parent_or_group:
220 test = test.get_top_level_parent_or_group()
221 return test
Jon Salz0697cbf2012-07-04 15:14:04 +0800222 else:
223 return self.test_list
224
225 self.event_handlers = {
Ricky Liang45c73e72015-01-15 15:00:30 +0800226 Event.Type.SWITCH_TEST: self.handle_switch_test,
227 Event.Type.SHOW_NEXT_ACTIVE_TEST:
228 lambda event: self.show_next_active_test(),
229 Event.Type.RESTART_TESTS:
230 lambda event: self.restart_tests(root=test_or_root(event)),
231 Event.Type.AUTO_RUN:
232 lambda event: self.auto_run(root=test_or_root(event)),
233 Event.Type.RE_RUN_FAILED:
234 lambda event: self.re_run_failed(root=test_or_root(event)),
235 Event.Type.RUN_TESTS_WITH_STATUS:
236 lambda event: self.run_tests_with_status(
237 event.status,
238 root=test_or_root(event)),
239 Event.Type.REVIEW:
240 lambda event: self.show_review_information(),
241 Event.Type.UPDATE_SYSTEM_INFO:
242 lambda event: self.update_system_info(),
243 Event.Type.STOP:
244 lambda event: self.stop(root=test_or_root(event, False),
245 fail=getattr(event, 'fail', False),
246 reason=getattr(event, 'reason', None)),
247 Event.Type.SET_VISIBLE_TEST:
248 lambda event: self.set_visible_test(
249 self.test_list.lookup_path(event.path)),
250 Event.Type.CLEAR_STATE:
251 lambda event: self.clear_state(
252 self.test_list.lookup_path(event.path)),
Wei-Ning Huang38b75f02015-02-25 18:25:14 +0800253 Event.Type.KEY_FILTER_MODE: self.handle_key_filter_mode,
Jon Salz0697cbf2012-07-04 15:14:04 +0800254 }
255
Jon Salz0697cbf2012-07-04 15:14:04 +0800256 self.web_socket_manager = None
Wei-Ning Huang38b75f02015-02-25 18:25:14 +0800257 self.terminal_manager = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800258
259 def destroy(self):
Ricky Liang74237a02014-09-18 15:11:23 +0800260 """Performs any shutdown tasks. Overrides base class method."""
Jon Salzd7550792013-07-12 05:49:27 +0800261 self.status = Status.TERMINATING
Jon Salz0697cbf2012-07-04 15:14:04 +0800262 if self.chrome:
263 self.chrome.kill()
264 self.chrome = None
Jon Salzc79a9982012-08-30 04:42:01 +0800265 if self.dummy_shopfloor:
266 self.dummy_shopfloor.kill()
267 self.dummy_shopfloor = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800268 if self.ui_process:
269 utils.kill_process_tree(self.ui_process, 'ui')
270 self.ui_process = None
271 if self.web_socket_manager:
272 logging.info('Stopping web sockets')
273 self.web_socket_manager.close()
274 self.web_socket_manager = None
275 if self.state_server_thread:
276 logging.info('Stopping state server')
277 self.state_server.shutdown()
278 self.state_server_thread.join()
279 self.state_server.server_close()
280 self.state_server_thread = None
281 if self.state_instance:
282 self.state_instance.close()
283 if self.event_server_thread:
284 logging.info('Stopping event server')
285 self.event_server.shutdown() # pylint: disable=E1101
286 self.event_server_thread.join()
287 self.event_server.server_close()
288 self.event_server_thread = None
289 if self.log_watcher:
290 if self.log_watcher.IsThreadStarted():
291 self.log_watcher.StopWatchThread()
292 self.log_watcher = None
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +0800293 if self.system_log_manager:
294 if self.system_log_manager.IsThreadRunning():
Cheng-Yi Chianga0f6eff2014-01-09 18:27:22 +0800295 self.system_log_manager.Stop()
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +0800296 self.system_log_manager = None
Vic Yange2c76a82014-10-30 12:48:19 -0700297 if self.autotest_prespawner:
298 logging.info('Stopping autotest prespawner')
299 self.autotest_prespawner.stop()
300 self.autotest_prespawner = None
301 if self.pytest_prespawner:
302 logging.info('Stopping pytest prespawner')
303 self.pytest_prespawner.stop()
304 self.pytest_prespawner = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800305 if self.event_client:
306 logging.info('Closing event client')
307 self.event_client.close()
308 self.event_client = None
Jon Salzddf0d052013-06-18 12:52:44 +0800309 if self.cpufreq_manager:
310 self.cpufreq_manager.Stop()
Jon Salz0697cbf2012-07-04 15:14:04 +0800311 if self.event_log:
312 self.event_log.Close()
313 self.event_log = None
Dean Liao592e4d52013-01-10 20:06:39 +0800314 if self.key_filter:
315 self.key_filter.Stop()
Vic Yangd8990da2013-06-27 16:57:43 +0800316 if self.cpu_usage_watcher:
317 self.cpu_usage_watcher.terminate()
Peter Ammon1e1ec572014-06-26 17:56:32 -0700318 if self.link_manager:
319 self.link_manager.Stop()
320 self.link_manager = None
Dean Liao592e4d52013-01-10 20:06:39 +0800321
Peter Ammon1e1ec572014-06-26 17:56:32 -0700322 super(Goofy, self).destroy()
Jon Salz0697cbf2012-07-04 15:14:04 +0800323 logging.info('Done destroying Goofy')
Jon Salzd7550792013-07-12 05:49:27 +0800324 self.status = Status.TERMINATED
Jon Salz0697cbf2012-07-04 15:14:04 +0800325
326 def start_state_server(self):
Jon Salz2af235d2013-06-24 14:47:21 +0800327 # Before starting state server, remount stateful partitions with
328 # no commit flag. The default commit time (commit=600) makes corruption
329 # too likely.
Hung-Te Lind59dbfa2014-08-27 12:27:53 +0800330 utils.ResetCommitTime()
Jon Salz2af235d2013-06-24 14:47:21 +0800331
Jon Salz0697cbf2012-07-04 15:14:04 +0800332 self.state_instance, self.state_server = (
Ricky Liang45c73e72015-01-15 15:00:30 +0800333 state.create_server(bind_address='0.0.0.0'))
Jon Salz16d10542012-07-23 12:18:45 +0800334 self.goofy_rpc = GoofyRPC(self)
335 self.goofy_rpc.RegisterMethods(self.state_instance)
Jon Salz0697cbf2012-07-04 15:14:04 +0800336 logging.info('Starting state server')
337 self.state_server_thread = threading.Thread(
Ricky Liang45c73e72015-01-15 15:00:30 +0800338 target=self.state_server.serve_forever,
339 name='StateServer')
Jon Salz0697cbf2012-07-04 15:14:04 +0800340 self.state_server_thread.start()
341
342 def start_event_server(self):
343 self.event_server = EventServer()
344 logging.info('Starting factory event server')
345 self.event_server_thread = threading.Thread(
Ricky Liang45c73e72015-01-15 15:00:30 +0800346 target=self.event_server.serve_forever,
347 name='EventServer') # pylint: disable=E1101
Jon Salz0697cbf2012-07-04 15:14:04 +0800348 self.event_server_thread.start()
349
350 self.event_client = EventClient(
Ricky Liang45c73e72015-01-15 15:00:30 +0800351 callback=self.handle_event, event_loop=self.run_queue)
Jon Salz0697cbf2012-07-04 15:14:04 +0800352
353 self.web_socket_manager = WebSocketManager(self.uuid)
Ricky Liang45c73e72015-01-15 15:00:30 +0800354 self.state_server.add_handler('/event',
355 self.web_socket_manager.handle_web_socket)
Jon Salz0697cbf2012-07-04 15:14:04 +0800356
Wei-Ning Huang38b75f02015-02-25 18:25:14 +0800357 def start_terminal_server(self):
358 self.terminal_manager = TerminalManager()
359 self.state_server.add_handler('/pty',
360 self.terminal_manager.handle_web_socket)
361
Jon Salz0697cbf2012-07-04 15:14:04 +0800362 def start_ui(self):
363 ui_proc_args = [
Ricky Liang45c73e72015-01-15 15:00:30 +0800364 os.path.join(factory.FACTORY_PACKAGE_PATH, 'test', 'ui.py'),
365 self.options.test_list
366 ]
Jon Salz0697cbf2012-07-04 15:14:04 +0800367 if self.options.verbose:
368 ui_proc_args.append('-v')
369 logging.info('Starting ui %s', ui_proc_args)
Jon Salz78c32392012-07-25 14:18:29 +0800370 self.ui_process = Spawn(ui_proc_args)
Jon Salz0697cbf2012-07-04 15:14:04 +0800371 logging.info('Waiting for UI to come up...')
372 self.event_client.wait(
Ricky Liang45c73e72015-01-15 15:00:30 +0800373 lambda event: event.type == Event.Type.UI_READY)
Jon Salz0697cbf2012-07-04 15:14:04 +0800374 logging.info('UI has started')
375
376 def set_visible_test(self, test):
377 if self.visible_test == test:
378 return
Jon Salz2f2d42c2012-07-30 12:30:34 +0800379 if test and not test.has_ui:
380 return
Jon Salz0697cbf2012-07-04 15:14:04 +0800381
382 if test:
383 test.update_state(visible=True)
384 if self.visible_test:
385 self.visible_test.update_state(visible=False)
386 self.visible_test = test
387
Ricky Liang48e47f92014-02-26 19:31:51 +0800388 def log_startup_messages(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800389 """Logs the tail of var/log/messages and mosys and EC console logs."""
Jon Salzd4306c82012-11-30 15:16:36 +0800390 # TODO(jsalz): This is mostly a copy-and-paste of code in init_states,
391 # for factory-3004.B only. Consolidate and merge back to ToT.
392 if utils.in_chroot():
393 return
394
395 try:
Ricky Liang45c73e72015-01-15 15:00:30 +0800396 var_log_messages = utils.var_log_messages_before_reboot()
Jon Salzd4306c82012-11-30 15:16:36 +0800397 logging.info(
Ricky Liang45c73e72015-01-15 15:00:30 +0800398 'Tail of /var/log/messages before last reboot:\n'
399 '%s', ('\n'.join(
400 ' ' + x for x in var_log_messages)))
Jon Salzd4306c82012-11-30 15:16:36 +0800401 except: # pylint: disable=W0702
402 logging.exception('Unable to grok /var/log/messages')
403
404 try:
Ricky Liang117484a2014-04-14 11:14:41 +0800405 mosys_log = Spawn(
Jon Salzd4306c82012-11-30 15:16:36 +0800406 ['mosys', 'eventlog', 'list'],
407 read_stdout=True, log_stderr_on_error=True).stdout_data
408 logging.info('System eventlog from mosys:\n%s\n', mosys_log)
409 except: # pylint: disable=W0702
410 logging.exception('Unable to read mosys eventlog')
411
Dean Liao88b93192014-10-23 19:37:41 +0800412 self.log_ec_console()
413 self.log_ec_panic_info()
414
415 @staticmethod
416 def log_ec_console():
417 """Logs EC console log into logging.info.
418
419 It logs an error message in logging.exception if an exception is raised
420 when getting EC console log.
421 For unsupported device, it logs unsupport message in logging.info
422
423 Returns:
424 EC console log string.
425 """
Jon Salzd4306c82012-11-30 15:16:36 +0800426 try:
Vic Yang8341dde2013-01-29 16:48:52 +0800427 board = system.GetBoard()
428 ec_console_log = board.GetECConsoleLog()
Jon Salzd4306c82012-11-30 15:16:36 +0800429 logging.info('EC console log after reboot:\n%s\n', ec_console_log)
Dean Liao88b93192014-10-23 19:37:41 +0800430 return ec_console_log
431 except NotImplementedError:
432 logging.info('EC console log not supported')
Jon Salzd4306c82012-11-30 15:16:36 +0800433 except: # pylint: disable=W0702
434 logging.exception('Error retrieving EC console log')
435
Dean Liao88b93192014-10-23 19:37:41 +0800436 @staticmethod
437 def log_ec_panic_info():
438 """Logs EC panic info into logging.info.
439
440 It logs an error message in logging.exception if an exception is raised
441 when getting EC panic info.
442 For unsupported device, it logs unsupport message in logging.info
443
444 Returns:
445 EC panic info string.
446 """
Vic Yang079f9872013-07-01 11:32:00 +0800447 try:
448 board = system.GetBoard()
449 ec_panic_info = board.GetECPanicInfo()
450 logging.info('EC panic info after reboot:\n%s\n', ec_panic_info)
Dean Liao88b93192014-10-23 19:37:41 +0800451 return ec_panic_info
452 except NotImplementedError:
453 logging.info('EC panic info is not supported')
Vic Yang079f9872013-07-01 11:32:00 +0800454 except: # pylint: disable=W0702
455 logging.exception('Error retrieving EC panic info')
456
Ricky Liang48e47f92014-02-26 19:31:51 +0800457 def shutdown(self, operation):
458 """Starts shutdown procedure.
459
460 Args:
Vic (Chun-Ju) Yang05b0d952014-04-28 17:39:09 +0800461 operation: The shutdown operation (reboot, full_reboot, or halt).
Ricky Liang48e47f92014-02-26 19:31:51 +0800462 """
463 active_tests = []
464 for test in self.test_list.walk():
465 if not test.is_leaf():
466 continue
467
468 test_state = test.get_state()
469 if test_state.status == TestState.ACTIVE:
470 active_tests.append(test)
471
Ricky Liang48e47f92014-02-26 19:31:51 +0800472 if not (len(active_tests) == 1 and
473 isinstance(active_tests[0], factory.ShutdownStep)):
474 logging.error(
475 'Calling Goofy shutdown outside of the shutdown factory test')
476 return
477
478 logging.info('Start Goofy shutdown (%s)', operation)
479 # Save pending test list in the state server
480 self.state_instance.set_shared_data(
481 'tests_after_shutdown',
482 [t.path for t in self.tests_to_run])
483 # Save shutdown time
484 self.state_instance.set_shared_data('shutdown_time', time.time())
485
486 with self.env.lock:
487 self.event_log.Log('shutdown', operation=operation)
488 shutdown_result = self.env.shutdown(operation)
489 if shutdown_result:
490 # That's all, folks!
Peter Ammon1e1ec572014-06-26 17:56:32 -0700491 self.run_enqueue(None)
Ricky Liang48e47f92014-02-26 19:31:51 +0800492 else:
493 # Just pass (e.g., in the chroot).
494 self.state_instance.set_shared_data('tests_after_shutdown', None)
495 # Send event with no fields to indicate that there is no
496 # longer a pending shutdown.
497 self.event_client.post_event(Event(Event.Type.PENDING_SHUTDOWN))
498
499 def handle_shutdown_complete(self, test):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800500 """Handles the case where a shutdown was detected during a shutdown step.
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800501
Ricky Liang6fe218c2013-12-27 15:17:17 +0800502 Args:
503 test: The ShutdownStep.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800504 """
Jon Salz0697cbf2012-07-04 15:14:04 +0800505 test_state = test.update_state(increment_shutdown_count=1)
506 logging.info('Detected shutdown (%d of %d)',
Ricky Liang48e47f92014-02-26 19:31:51 +0800507 test_state.shutdown_count, test.iterations)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800508
Ricky Liang48e47f92014-02-26 19:31:51 +0800509 # Insert current shutdown test at the front of the list of tests to run
510 # after shutdown. This is to continue on post-shutdown verification in the
511 # shutdown step.
512 tests_after_shutdown = self.state_instance.get_shared_data(
513 'tests_after_shutdown', optional=True)
514 if not tests_after_shutdown:
515 self.state_instance.set_shared_data('tests_after_shutdown', [test.path])
516 elif isinstance(tests_after_shutdown, list):
517 self.state_instance.set_shared_data(
518 'tests_after_shutdown', [test.path] + tests_after_shutdown)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800519
Ricky Liang48e47f92014-02-26 19:31:51 +0800520 # Set 'post_shutdown' to inform shutdown test that a shutdown just occurred.
Ricky Liangb7eb8772014-09-15 18:05:22 +0800521 self.state_instance.set_shared_data(
522 state.POST_SHUTDOWN_TAG % test.path,
523 self.state_instance.get_test_state(test.path).invocation)
Jon Salz258a40c2012-04-19 12:34:01 +0800524
Jon Salz0697cbf2012-07-04 15:14:04 +0800525 def init_states(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800526 """Initializes all states on startup."""
Jon Salz0697cbf2012-07-04 15:14:04 +0800527 for test in self.test_list.get_all_tests():
528 # Make sure the state server knows about all the tests,
529 # defaulting to an untested state.
530 test.update_state(update_parent=False, visible=False)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800531
Jon Salz0697cbf2012-07-04 15:14:04 +0800532 var_log_messages = None
Vic Yanga9c32212012-08-16 20:07:54 +0800533 mosys_log = None
Vic Yange4c275d2012-08-28 01:50:20 +0800534 ec_console_log = None
Vic Yang079f9872013-07-01 11:32:00 +0800535 ec_panic_info = None
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800536
Jon Salz0697cbf2012-07-04 15:14:04 +0800537 # Any 'active' tests should be marked as failed now.
538 for test in self.test_list.walk():
Jon Salza6711d72012-07-18 14:33:03 +0800539 if not test.is_leaf():
540 # Don't bother with parents; they will be updated when their
541 # children are updated.
542 continue
543
Jon Salz0697cbf2012-07-04 15:14:04 +0800544 test_state = test.get_state()
545 if test_state.status != TestState.ACTIVE:
546 continue
547 if isinstance(test, factory.ShutdownStep):
548 # Shutdown while the test was active - that's good.
Ricky Liang48e47f92014-02-26 19:31:51 +0800549 self.handle_shutdown_complete(test)
Jon Salz0697cbf2012-07-04 15:14:04 +0800550 else:
551 # Unexpected shutdown. Grab /var/log/messages for context.
552 if var_log_messages is None:
553 try:
554 var_log_messages = (
Ricky Liang45c73e72015-01-15 15:00:30 +0800555 utils.var_log_messages_before_reboot())
Jon Salz0697cbf2012-07-04 15:14:04 +0800556 # Write it to the log, to make it easier to
557 # correlate with /var/log/messages.
558 logging.info(
Ricky Liang45c73e72015-01-15 15:00:30 +0800559 'Unexpected shutdown. '
560 'Tail of /var/log/messages before last reboot:\n'
561 '%s', ('\n'.join(
562 ' ' + x for x in var_log_messages)))
Jon Salz0697cbf2012-07-04 15:14:04 +0800563 except: # pylint: disable=W0702
564 logging.exception('Unable to grok /var/log/messages')
565 var_log_messages = []
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800566
Jon Salz008f4ea2012-08-28 05:39:45 +0800567 if mosys_log is None and not utils.in_chroot():
568 try:
Ricky Liang117484a2014-04-14 11:14:41 +0800569 mosys_log = Spawn(
Jon Salz008f4ea2012-08-28 05:39:45 +0800570 ['mosys', 'eventlog', 'list'],
571 read_stdout=True, log_stderr_on_error=True).stdout_data
572 # Write it to the log also.
573 logging.info('System eventlog from mosys:\n%s\n', mosys_log)
574 except: # pylint: disable=W0702
575 logging.exception('Unable to read mosys eventlog')
Vic Yanga9c32212012-08-16 20:07:54 +0800576
Vic Yange4c275d2012-08-28 01:50:20 +0800577 if ec_console_log is None:
Dean Liao88b93192014-10-23 19:37:41 +0800578 ec_console_log = self.log_ec_console()
Vic Yange4c275d2012-08-28 01:50:20 +0800579
Vic Yang079f9872013-07-01 11:32:00 +0800580 if ec_panic_info is None:
Dean Liao88b93192014-10-23 19:37:41 +0800581 ec_panic_info = self.log_ec_panic_info()
Vic Yang079f9872013-07-01 11:32:00 +0800582
Jon Salz0697cbf2012-07-04 15:14:04 +0800583 error_msg = 'Unexpected shutdown while test was running'
584 self.event_log.Log('end_test',
Ricky Liang45c73e72015-01-15 15:00:30 +0800585 path=test.path,
586 status=TestState.FAILED,
587 invocation=test.get_state().invocation,
588 error_msg=error_msg,
589 var_log_messages='\n'.join(var_log_messages),
590 mosys_log=mosys_log)
Jon Salz0697cbf2012-07-04 15:14:04 +0800591 test.update_state(
Ricky Liang45c73e72015-01-15 15:00:30 +0800592 status=TestState.FAILED,
593 error_msg=error_msg)
Chun-Ta Lin87c2dac2015-05-02 01:35:01 -0700594 # Trigger the OnTestFailure callback.
595 self.run_queue.put(system.GetBoard().OnTestFailure)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800596
Jon Salz50efe942012-07-26 11:54:10 +0800597 if not test.never_fails:
598 # For "never_fails" tests (such as "Start"), don't cancel
599 # pending tests, since reboot is expected.
600 factory.console.info('Unexpected shutdown while test %s '
601 'running; cancelling any pending tests',
602 test.path)
603 self.state_instance.set_shared_data('tests_after_shutdown', [])
Jon Salz69806bb2012-07-20 18:05:02 +0800604
Jon Salz008f4ea2012-08-28 05:39:45 +0800605 self.update_skipped_tests()
606
607 def update_skipped_tests(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800608 """Updates skipped states based on run_if."""
Jon Salz885dcac2013-07-23 16:39:50 +0800609 env = TestArgEnv()
Ricky Liang45c73e72015-01-15 15:00:30 +0800610
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800611 def _evaluate_skip_from_run_if(test):
612 """Returns the run_if evaluation of the test.
613
614 Args:
615 test: A FactoryTest object.
616
617 Returns:
618 The run_if evaluation result. Returns False if the test has no
619 run_if argument.
620 """
621 value = None
622 if test.run_if_expr:
623 try:
624 value = test.run_if_expr(env)
625 except: # pylint: disable=W0702
626 logging.exception('Unable to evaluate run_if expression for %s',
627 test.path)
628 # But keep going; we have no choice. This will end up
629 # always activating the test.
630 elif test.run_if_table_name:
631 try:
632 aux = shopfloor.get_selected_aux_data(test.run_if_table_name)
633 value = aux.get(test.run_if_col)
634 except ValueError:
635 # Not available; assume it shouldn't be skipped
636 pass
637
638 if value is None:
639 skip = False
640 else:
641 skip = (not value) ^ t.run_if_not
642 return skip
643
644 # Gets all run_if evaluation, and stores results in skip_map.
645 skip_map = dict()
Jon Salz008f4ea2012-08-28 05:39:45 +0800646 for t in self.test_list.walk():
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800647 skip_map[t.path] = _evaluate_skip_from_run_if(t)
Jon Salz885dcac2013-07-23 16:39:50 +0800648
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800649 # Propagates the skip value from root of tree and updates skip_map.
650 def _update_skip_map_from_node(test, skip_from_parent):
651 """Updates skip_map from a given node.
Jon Salz885dcac2013-07-23 16:39:50 +0800652
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800653 Given a FactoryTest node and the skip value from parent, updates the
654 skip value of current node in the skip_map if skip value from parent is
655 True. If this node has children, recursively propagate this value to all
656 its children, that is, all its subtests.
657 Note that this function only updates value in skip_map, not the actual
658 test_list tree.
Jon Salz008f4ea2012-08-28 05:39:45 +0800659
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800660 Args:
661 test: The given FactoryTest object. It is a node in the test_list tree.
662 skip_from_parent: The skip value which propagates from the parent of
663 input node.
664 """
665 skip_this_tree = skip_from_parent or skip_map[test.path]
666 if skip_this_tree:
667 logging.info('Skip from node %r', test.path)
668 skip_map[test.path] = True
669 if test.is_leaf():
670 return
671 # Propagates skip value to its subtests
672 for subtest in test.subtests:
673 _update_skip_map_from_node(subtest, skip_this_tree)
674
675 _update_skip_map_from_node(self.test_list, False)
676
677 # Updates the skip value from skip_map to test_list tree. Also, updates test
678 # status if needed.
679 for t in self.test_list.walk():
680 skip = skip_map[t.path]
681 test_state = t.get_state()
682 if ((not skip) and
683 (test_state.status == TestState.PASSED) and
684 (test_state.error_msg == TestState.SKIPPED_MSG)):
685 # It was marked as skipped before, but now we need to run it.
686 # Mark as untested.
687 t.update_state(skip=skip, status=TestState.UNTESTED, error_msg='')
688 else:
689 t.update_state(skip=skip)
Jon Salz008f4ea2012-08-28 05:39:45 +0800690
Jon Salz0697cbf2012-07-04 15:14:04 +0800691 def show_next_active_test(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800692 """Rotates to the next visible active test."""
Jon Salz0697cbf2012-07-04 15:14:04 +0800693 self.reap_completed_tests()
694 active_tests = [
Ricky Liang45c73e72015-01-15 15:00:30 +0800695 t for t in self.test_list.walk()
696 if t.is_leaf() and t.get_state().status == TestState.ACTIVE]
Jon Salz0697cbf2012-07-04 15:14:04 +0800697 if not active_tests:
698 return
Jon Salz4f6c7172012-06-11 20:45:36 +0800699
Jon Salz0697cbf2012-07-04 15:14:04 +0800700 try:
701 next_test = active_tests[
Ricky Liang45c73e72015-01-15 15:00:30 +0800702 (active_tests.index(self.visible_test) + 1) % len(active_tests)]
Jon Salz0697cbf2012-07-04 15:14:04 +0800703 except ValueError: # visible_test not present in active_tests
704 next_test = active_tests[0]
Jon Salz4f6c7172012-06-11 20:45:36 +0800705
Jon Salz0697cbf2012-07-04 15:14:04 +0800706 self.set_visible_test(next_test)
Jon Salz4f6c7172012-06-11 20:45:36 +0800707
Jon Salz0697cbf2012-07-04 15:14:04 +0800708 def handle_event(self, event):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800709 """Handles an event from the event server."""
Jon Salz0697cbf2012-07-04 15:14:04 +0800710 handler = self.event_handlers.get(event.type)
711 if handler:
712 handler(event)
713 else:
714 # We don't register handlers for all event types - just ignore
715 # this event.
716 logging.debug('Unbound event type %s', event.type)
Jon Salz4f6c7172012-06-11 20:45:36 +0800717
Vic Yangaabf9fd2013-04-09 18:56:13 +0800718 def check_critical_factory_note(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800719 """Returns True if the last factory note is critical."""
Vic Yangaabf9fd2013-04-09 18:56:13 +0800720 notes = self.state_instance.get_shared_data('factory_note', True)
721 return notes and notes[-1]['level'] == 'CRITICAL'
722
Jon Salz0697cbf2012-07-04 15:14:04 +0800723 def run_next_test(self):
henryhsu4cc6b022014-04-22 17:12:42 +0800724 """Runs the next eligible test (or tests) in self.tests_to_run.
725
726 We have three kinds of the next eligible test:
727 1. normal
728 2. backgroundable
729 3. force_background
730
731 And we have four situations of the ongoing invocations:
732 a. only a running normal test
733 b. all running tests are backgroundable
734 c. all running tests are force_background
735 d. all running tests are any combination of backgroundable and
736 force_background
737
738 When a test would like to be run, it must follow the rules:
739 [1] cannot run with [abd]
740 [2] cannot run with [a]
741 All the other combinations are allowed
742 """
Jon Salz0697cbf2012-07-04 15:14:04 +0800743 self.reap_completed_tests()
Vic Yangaabf9fd2013-04-09 18:56:13 +0800744 if self.tests_to_run and self.check_critical_factory_note():
745 self.tests_to_run.clear()
746 return
Jon Salz0697cbf2012-07-04 15:14:04 +0800747 while self.tests_to_run:
Ricky Liang6fe218c2013-12-27 15:17:17 +0800748 logging.debug('Tests to run: %s', [x.path for x in self.tests_to_run])
Jon Salz94eb56f2012-06-12 18:01:12 +0800749
Jon Salz0697cbf2012-07-04 15:14:04 +0800750 test = self.tests_to_run[0]
Jon Salz94eb56f2012-06-12 18:01:12 +0800751
Jon Salz0697cbf2012-07-04 15:14:04 +0800752 if test in self.invocations:
753 logging.info('Next test %s is already running', test.path)
754 self.tests_to_run.popleft()
755 return
Jon Salz94eb56f2012-06-12 18:01:12 +0800756
Jon Salza1412922012-07-23 16:04:17 +0800757 for requirement in test.require_run:
758 for i in requirement.test.walk():
759 if i.get_state().status == TestState.ACTIVE:
Jon Salz304a75d2012-07-06 11:14:15 +0800760 logging.info('Waiting for active test %s to complete '
Jon Salza1412922012-07-23 16:04:17 +0800761 'before running %s', i.path, test.path)
Jon Salz304a75d2012-07-06 11:14:15 +0800762 return
763
henryhsu4cc6b022014-04-22 17:12:42 +0800764 def is_normal_test(test):
765 return not (test.backgroundable or test.force_background)
766
767 # [1] cannot run with [abd].
768 if self.invocations and is_normal_test(test) and any(
769 [not x.force_background for x in self.invocations]):
770 logging.info('Waiting for non-force_background tests to '
771 'complete before running %s', test.path)
772 return
773
774 # [2] cannot run with [a].
775 if self.invocations and test.backgroundable and any(
776 [is_normal_test(x) for x in self.invocations]):
777 logging.info('Waiting for normal tests to '
778 'complete before running %s', test.path)
Jon Salz0697cbf2012-07-04 15:14:04 +0800779 return
Jon Salz94eb56f2012-06-12 18:01:12 +0800780
Jon Salz3e6f5202012-10-15 15:08:29 +0800781 if test.get_state().skip:
782 factory.console.info('Skipping test %s', test.path)
783 test.update_state(status=TestState.PASSED,
784 error_msg=TestState.SKIPPED_MSG)
785 self.tests_to_run.popleft()
786 continue
787
Jon Salz0697cbf2012-07-04 15:14:04 +0800788 self.tests_to_run.popleft()
Jon Salz94eb56f2012-06-12 18:01:12 +0800789
Jon Salz304a75d2012-07-06 11:14:15 +0800790 untested = set()
Jon Salza1412922012-07-23 16:04:17 +0800791 for requirement in test.require_run:
792 for i in requirement.test.walk():
793 if i == test:
Jon Salz304a75d2012-07-06 11:14:15 +0800794 # We've hit this test itself; stop checking
795 break
Jon Salza1412922012-07-23 16:04:17 +0800796 if ((i.get_state().status == TestState.UNTESTED) or
797 (requirement.passed and i.get_state().status !=
798 TestState.PASSED)):
Jon Salz304a75d2012-07-06 11:14:15 +0800799 # Found an untested test; move on to the next
800 # element in require_run.
Jon Salza1412922012-07-23 16:04:17 +0800801 untested.add(i)
Jon Salz304a75d2012-07-06 11:14:15 +0800802 break
803
804 if untested:
805 untested_paths = ', '.join(sorted([x.path for x in untested]))
806 if self.state_instance.get_shared_data('engineering_mode',
807 optional=True):
808 # In engineering mode, we'll let it go.
809 factory.console.warn('In engineering mode; running '
810 '%s even though required tests '
811 '[%s] have not completed',
812 test.path, untested_paths)
813 else:
814 # Not in engineering mode; mark it failed.
815 error_msg = ('Required tests [%s] have not been run yet'
816 % untested_paths)
817 factory.console.error('Not running %s: %s',
818 test.path, error_msg)
819 test.update_state(status=TestState.FAILED,
820 error_msg=error_msg)
821 continue
822
Ricky Liang48e47f92014-02-26 19:31:51 +0800823 if (isinstance(test, factory.ShutdownStep) and
Ricky Liangb7eb8772014-09-15 18:05:22 +0800824 self.state_instance.get_shared_data(
825 state.POST_SHUTDOWN_TAG % test.path, optional=True)):
Ricky Liang48e47f92014-02-26 19:31:51 +0800826 # Invoking post shutdown method of shutdown test. We should retain the
827 # iterations_left and retries_left of the original test state.
828 test_state = self.state_instance.get_test_state(test.path)
829 self._run_test(test, test_state.iterations_left,
830 test_state.retries_left)
831 else:
832 # Starts a new test run; reset iterations and retries.
833 self._run_test(test, test.iterations, test.retries)
Jon Salz1acc8742012-07-17 17:45:55 +0800834
Cheng-Yi Chiangce05c002013-04-04 02:13:17 +0800835 def _run_test(self, test, iterations_left=None, retries_left=None):
Vic Yanga3cecf82014-12-26 00:44:21 -0800836 if not self._ui_initialized and not test.is_no_host():
837 self.init_ui()
Vic Yang08505c72015-01-06 17:01:53 -0800838 invoc = TestInvocation(
839 self, test, on_completion=self.run_next_test,
840 on_test_failure=system.GetBoard().OnTestFailure)
Jon Salz1acc8742012-07-17 17:45:55 +0800841 new_state = test.update_state(
Ricky Liang48e47f92014-02-26 19:31:51 +0800842 status=TestState.ACTIVE, increment_count=1, error_msg='',
843 invocation=invoc.uuid, iterations_left=iterations_left,
844 retries_left=retries_left,
845 visible=(self.visible_test == test))
Jon Salz1acc8742012-07-17 17:45:55 +0800846 invoc.count = new_state.count
847
848 self.invocations[test] = invoc
849 if self.visible_test is None and test.has_ui:
850 self.set_visible_test(test)
Vic Yang311ddb82012-09-26 12:08:28 +0800851 self.check_exclusive()
Jon Salz1acc8742012-07-17 17:45:55 +0800852 invoc.start()
Jon Salz5f2a0672012-05-22 17:14:06 +0800853
Vic Yang311ddb82012-09-26 12:08:28 +0800854 def check_exclusive(self):
Jon Salzce6a7f82013-06-10 18:22:54 +0800855 # alias since this is really long
856 EXCL_OPT = factory.FactoryTest.EXCLUSIVE_OPTIONS
857
Vic Yang311ddb82012-09-26 12:08:28 +0800858 current_exclusive_items = set([
Jon Salzce6a7f82013-06-10 18:22:54 +0800859 item for item in EXCL_OPT
Vic Yang311ddb82012-09-26 12:08:28 +0800860 if any([test.is_exclusive(item) for test in self.invocations])])
861
862 new_exclusive_items = current_exclusive_items - self.exclusive_items
Jon Salzce6a7f82013-06-10 18:22:54 +0800863 if EXCL_OPT.NETWORKING in new_exclusive_items:
Vic Yang311ddb82012-09-26 12:08:28 +0800864 logging.info('Disabling network')
865 self.connection_manager.DisableNetworking()
Jon Salzce6a7f82013-06-10 18:22:54 +0800866 if EXCL_OPT.CHARGER in new_exclusive_items:
Vic Yang311ddb82012-09-26 12:08:28 +0800867 logging.info('Stop controlling charger')
868
869 new_non_exclusive_items = self.exclusive_items - current_exclusive_items
Jon Salzce6a7f82013-06-10 18:22:54 +0800870 if EXCL_OPT.NETWORKING in new_non_exclusive_items:
Vic Yang311ddb82012-09-26 12:08:28 +0800871 logging.info('Re-enabling network')
872 self.connection_manager.EnableNetworking()
Jon Salzce6a7f82013-06-10 18:22:54 +0800873 if EXCL_OPT.CHARGER in new_non_exclusive_items:
Vic Yang311ddb82012-09-26 12:08:28 +0800874 logging.info('Start controlling charger')
875
Jon Salzce6a7f82013-06-10 18:22:54 +0800876 if self.cpufreq_manager:
877 enabled = EXCL_OPT.CPUFREQ not in current_exclusive_items
878 try:
879 self.cpufreq_manager.SetEnabled(enabled)
880 except: # pylint: disable=W0702
881 logging.exception('Unable to %s cpufreq services',
882 'enable' if enabled else 'disable')
883
Ricky Liang0f9978e2015-01-30 08:19:17 +0000884 # Only adjust charge state if not excluded
885 if (EXCL_OPT.CHARGER not in current_exclusive_items and
886 not utils.in_chroot()):
887 if self.charge_manager:
Cheng-Yi Chiangd8186952013-04-04 23:41:14 +0800888 self.charge_manager.AdjustChargeState()
889 else:
Dean Liao88b93192014-10-23 19:37:41 +0800890 self.charge()
Vic Yang311ddb82012-09-26 12:08:28 +0800891
892 self.exclusive_items = current_exclusive_items
Jon Salz5da61e62012-05-31 13:06:22 +0800893
Dean Liao88b93192014-10-23 19:37:41 +0800894 def charge(self):
895 """Charges the board.
896
897 It won't try again if last time SetChargeState raised an exception.
898 """
899 if not self._can_charge:
900 return
901
902 try:
Ricky Liang9ac35e02015-01-30 16:01:32 +0800903 if self.charge_manager:
904 self.charge_manager.StartCharging()
905 else:
906 system.GetBoard().SetChargeState(Board.ChargeState.CHARGE)
Dean Liao88b93192014-10-23 19:37:41 +0800907 except NotImplementedError:
908 logging.info('Charging is not supported')
909 self._can_charge = False
910 except BoardException:
911 logging.exception('Unable to set charge state on this board')
912 self._can_charge = False
913
cychiang21886742012-07-05 15:16:32 +0800914 def check_for_updates(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800915 """Schedules an asynchronous check for updates if necessary."""
cychiang21886742012-07-05 15:16:32 +0800916 if not self.test_list.options.update_period_secs:
917 # Not enabled.
918 return
919
920 now = time.time()
921 if self.last_update_check and (
922 now - self.last_update_check <
923 self.test_list.options.update_period_secs):
924 # Not yet time for another check.
925 return
926
927 self.last_update_check = now
928
929 def handle_check_for_update(reached_shopfloor, md5sum, needs_update):
930 if reached_shopfloor:
931 new_update_md5sum = md5sum if needs_update else None
932 if system.SystemInfo.update_md5sum != new_update_md5sum:
933 logging.info('Received new update MD5SUM: %s', new_update_md5sum)
934 system.SystemInfo.update_md5sum = new_update_md5sum
Peter Ammon1e1ec572014-06-26 17:56:32 -0700935 self.run_enqueue(self.update_system_info)
Cheng-Yi Chiang194d3c02015-03-16 14:37:15 +0800936 else:
937 if not self._suppress_periodic_update_messages:
938 logging.warning('Suppress error messages for periodic update checking'
939 ' after the first one.')
940 self._suppress_periodic_update_messages = True
cychiang21886742012-07-05 15:16:32 +0800941
942 updater.CheckForUpdateAsync(
Ricky Liang45c73e72015-01-15 15:00:30 +0800943 handle_check_for_update,
Cheng-Yi Chiang194d3c02015-03-16 14:37:15 +0800944 self.test_list.options.shopfloor_timeout_secs,
945 self._suppress_periodic_update_messages)
cychiang21886742012-07-05 15:16:32 +0800946
Jon Salza6711d72012-07-18 14:33:03 +0800947 def cancel_pending_tests(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800948 """Cancels any tests in the run queue."""
Jon Salza6711d72012-07-18 14:33:03 +0800949 self.run_tests([])
950
Ricky Liang4bff3e32014-02-20 18:46:11 +0800951 def restore_active_run_state(self):
952 """Restores active run id and the list of scheduled tests."""
953 self.run_id = self.state_instance.get_shared_data('run_id', optional=True)
954 self.scheduled_run_tests = self.state_instance.get_shared_data(
955 'scheduled_run_tests', optional=True)
956
957 def set_active_run_state(self):
958 """Sets active run id and the list of scheduled tests."""
959 self.run_id = str(uuid.uuid4())
960 self.scheduled_run_tests = [test.path for test in self.tests_to_run]
961 self.state_instance.set_shared_data('run_id', self.run_id)
962 self.state_instance.set_shared_data('scheduled_run_tests',
963 self.scheduled_run_tests)
964
Jon Salz0697cbf2012-07-04 15:14:04 +0800965 def run_tests(self, subtrees, untested_only=False):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800966 """Runs tests under subtree.
Jon Salz258a40c2012-04-19 12:34:01 +0800967
Jon Salz0697cbf2012-07-04 15:14:04 +0800968 The tests are run in order unless one fails (then stops).
969 Backgroundable tests are run simultaneously; when a foreground test is
970 encountered, we wait for all active tests to finish before continuing.
Jon Salzb1b39092012-05-03 02:05:09 +0800971
Ricky Liang6fe218c2013-12-27 15:17:17 +0800972 Args:
973 subtrees: Node or nodes containing tests to run (may either be
974 a single test or a list). Duplicates will be ignored.
975 untested_only: True to run untested tests only.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800976 """
Vic Yang08505c72015-01-06 17:01:53 -0800977 system.GetBoard().OnTestStart()
978
Jon Salz0697cbf2012-07-04 15:14:04 +0800979 if type(subtrees) != list:
980 subtrees = [subtrees]
Jon Salz258a40c2012-04-19 12:34:01 +0800981
Jon Salz0697cbf2012-07-04 15:14:04 +0800982 # Nodes we've seen so far, to avoid duplicates.
983 seen = set()
Jon Salz94eb56f2012-06-12 18:01:12 +0800984
Jon Salz0697cbf2012-07-04 15:14:04 +0800985 self.tests_to_run = deque()
986 for subtree in subtrees:
987 for test in subtree.walk():
988 if test in seen:
989 continue
990 seen.add(test)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800991
Jon Salz0697cbf2012-07-04 15:14:04 +0800992 if not test.is_leaf():
993 continue
Ricky Liang45c73e72015-01-15 15:00:30 +0800994 if untested_only and test.get_state().status != TestState.UNTESTED:
Jon Salz0697cbf2012-07-04 15:14:04 +0800995 continue
996 self.tests_to_run.append(test)
Ricky Liang4bff3e32014-02-20 18:46:11 +0800997 if subtrees:
998 self.set_active_run_state()
Jon Salz0697cbf2012-07-04 15:14:04 +0800999 self.run_next_test()
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001000
Jon Salz0697cbf2012-07-04 15:14:04 +08001001 def reap_completed_tests(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001002 """Removes completed tests from the set of active tests.
Jon Salz0697cbf2012-07-04 15:14:04 +08001003
1004 Also updates the visible test if it was reaped.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001005 """
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +08001006 test_completed = False
Jon Salz0697cbf2012-07-04 15:14:04 +08001007 for t, v in dict(self.invocations).iteritems():
1008 if v.is_completed():
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +08001009 test_completed = True
Jon Salz1acc8742012-07-17 17:45:55 +08001010 new_state = t.update_state(**v.update_state_on_completion)
Jon Salz0697cbf2012-07-04 15:14:04 +08001011 del self.invocations[t]
1012
Johny Lin62ed2a32015-05-13 11:57:12 +08001013 # Stop on failure if flag is true and there is no retry chances.
Chun-Ta Lin54e17e42012-09-06 22:05:13 +08001014 if (self.test_list.options.stop_on_failure and
Johny Lin62ed2a32015-05-13 11:57:12 +08001015 new_state.retries_left < 0 and
Chun-Ta Lin54e17e42012-09-06 22:05:13 +08001016 new_state.status == TestState.FAILED):
1017 # Clean all the tests to cause goofy to stop.
1018 self.tests_to_run = []
Ricky Liang45c73e72015-01-15 15:00:30 +08001019 factory.console.info('Stop on failure triggered. Empty the queue.')
Chun-Ta Lin54e17e42012-09-06 22:05:13 +08001020
Jon Salz1acc8742012-07-17 17:45:55 +08001021 if new_state.iterations_left and new_state.status == TestState.PASSED:
1022 # Play it again, Sam!
1023 self._run_test(t)
Cheng-Yi Chiangce05c002013-04-04 02:13:17 +08001024 # new_state.retries_left is obtained after update.
1025 # For retries_left == 0, test can still be run for the last time.
1026 elif (new_state.retries_left >= 0 and
1027 new_state.status == TestState.FAILED):
1028 # Still have to retry, Sam!
1029 self._run_test(t)
Jon Salz1acc8742012-07-17 17:45:55 +08001030
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +08001031 if test_completed:
Vic Yangf01c59f2013-04-19 17:37:56 +08001032 self.log_watcher.KickWatchThread()
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +08001033
Jon Salz0697cbf2012-07-04 15:14:04 +08001034 if (self.visible_test is None or
Jon Salz85a39882012-07-05 16:45:04 +08001035 self.visible_test not in self.invocations):
Jon Salz0697cbf2012-07-04 15:14:04 +08001036 self.set_visible_test(None)
1037 # Make the first running test, if any, the visible test
1038 for t in self.test_list.walk():
1039 if t in self.invocations:
1040 self.set_visible_test(t)
1041 break
1042
Jon Salz6dc031d2013-06-19 13:06:23 +08001043 def kill_active_tests(self, abort, root=None, reason=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001044 """Kills and waits for all active tests.
Jon Salz0697cbf2012-07-04 15:14:04 +08001045
Jon Salz85a39882012-07-05 16:45:04 +08001046 Args:
1047 abort: True to change state of killed tests to FAILED, False for
Jon Salz0697cbf2012-07-04 15:14:04 +08001048 UNTESTED.
Jon Salz85a39882012-07-05 16:45:04 +08001049 root: If set, only kills tests with root as an ancestor.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001050 reason: If set, the abort reason.
1051 """
Jon Salz0697cbf2012-07-04 15:14:04 +08001052 self.reap_completed_tests()
1053 for test, invoc in self.invocations.items():
Jon Salz85a39882012-07-05 16:45:04 +08001054 if root and not test.has_ancestor(root):
1055 continue
1056
Ricky Liang45c73e72015-01-15 15:00:30 +08001057 factory.console.info('Killing active test %s...', test.path)
Jon Salz6dc031d2013-06-19 13:06:23 +08001058 invoc.abort_and_join(reason)
Ricky Liang45c73e72015-01-15 15:00:30 +08001059 factory.console.info('Killed %s', test.path)
Jon Salz1acc8742012-07-17 17:45:55 +08001060 test.update_state(**invoc.update_state_on_completion)
Jon Salz0697cbf2012-07-04 15:14:04 +08001061 del self.invocations[test]
Jon Salz1acc8742012-07-17 17:45:55 +08001062
Jon Salz0697cbf2012-07-04 15:14:04 +08001063 if not abort:
1064 test.update_state(status=TestState.UNTESTED)
1065 self.reap_completed_tests()
1066
Jon Salz6dc031d2013-06-19 13:06:23 +08001067 def stop(self, root=None, fail=False, reason=None):
1068 self.kill_active_tests(fail, root, reason)
Jon Salz85a39882012-07-05 16:45:04 +08001069 # Remove any tests in the run queue under the root.
1070 self.tests_to_run = deque([x for x in self.tests_to_run
1071 if root and not x.has_ancestor(root)])
1072 self.run_next_test()
Jon Salz0697cbf2012-07-04 15:14:04 +08001073
Jon Salz4712ac72013-02-07 17:12:05 +08001074 def clear_state(self, root=None):
Jon Salzd7550792013-07-12 05:49:27 +08001075 if root is None:
1076 root = self.test_list
Jon Salz6dc031d2013-06-19 13:06:23 +08001077 self.stop(root, reason='Clearing test state')
Jon Salz4712ac72013-02-07 17:12:05 +08001078 for f in root.walk():
1079 if f.is_leaf():
1080 f.update_state(status=TestState.UNTESTED)
1081
Jon Salz6dc031d2013-06-19 13:06:23 +08001082 def abort_active_tests(self, reason=None):
1083 self.kill_active_tests(True, reason=reason)
Jon Salz0697cbf2012-07-04 15:14:04 +08001084
1085 def main(self):
Jon Salzeff94182013-06-19 15:06:28 +08001086 syslog.openlog('goofy')
1087
Jon Salz0697cbf2012-07-04 15:14:04 +08001088 try:
Jon Salzd7550792013-07-12 05:49:27 +08001089 self.status = Status.INITIALIZING
Jon Salz0697cbf2012-07-04 15:14:04 +08001090 self.init()
1091 self.event_log.Log('goofy_init',
Ricky Liang45c73e72015-01-15 15:00:30 +08001092 success=True)
Jon Salz0697cbf2012-07-04 15:14:04 +08001093 except:
1094 if self.event_log:
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001095 try:
Jon Salz0697cbf2012-07-04 15:14:04 +08001096 self.event_log.Log('goofy_init',
Ricky Liang45c73e72015-01-15 15:00:30 +08001097 success=False,
1098 trace=traceback.format_exc())
Jon Salz0697cbf2012-07-04 15:14:04 +08001099 except: # pylint: disable=W0702
1100 pass
1101 raise
1102
Jon Salzd7550792013-07-12 05:49:27 +08001103 self.status = Status.RUNNING
Jon Salzeff94182013-06-19 15:06:28 +08001104 syslog.syslog('Goofy (factory test harness) starting')
Jon Salz0697cbf2012-07-04 15:14:04 +08001105 self.run()
1106
1107 def update_system_info(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001108 """Updates system info."""
Jon Salz0697cbf2012-07-04 15:14:04 +08001109 system_info = system.SystemInfo()
1110 self.state_instance.set_shared_data('system_info', system_info.__dict__)
1111 self.event_client.post_event(Event(Event.Type.SYSTEM_INFO,
Ricky Liang45c73e72015-01-15 15:00:30 +08001112 system_info=system_info.__dict__))
Jon Salz0697cbf2012-07-04 15:14:04 +08001113 logging.info('System info: %r', system_info.__dict__)
1114
Jon Salzeb42f0d2012-07-27 19:14:04 +08001115 def update_factory(self, auto_run_on_restart=False, post_update_hook=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001116 """Commences updating factory software.
Jon Salzeb42f0d2012-07-27 19:14:04 +08001117
1118 Args:
1119 auto_run_on_restart: Auto-run when the machine comes back up.
1120 post_update_hook: Code to call after update but immediately before
1121 restart.
1122
1123 Returns:
1124 Never if the update was successful (we just reboot).
1125 False if the update was unnecessary (no update available).
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001126 """
Jon Salz6dc031d2013-06-19 13:06:23 +08001127 self.kill_active_tests(False, reason='Factory software update')
Jon Salza6711d72012-07-18 14:33:03 +08001128 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +08001129
Jon Salz5c344f62012-07-13 14:31:16 +08001130 def pre_update_hook():
1131 if auto_run_on_restart:
1132 self.state_instance.set_shared_data('tests_after_shutdown',
1133 FORCE_AUTO_RUN)
1134 self.state_instance.close()
1135
Jon Salzeb42f0d2012-07-27 19:14:04 +08001136 if updater.TryUpdate(pre_update_hook=pre_update_hook):
1137 if post_update_hook:
1138 post_update_hook()
1139 self.env.shutdown('reboot')
Jon Salz0697cbf2012-07-04 15:14:04 +08001140
Ricky Liang8fecf412014-05-22 10:56:14 +08001141 def handle_sigint(self, dummy_signum, dummy_frame): # pylint: disable=W0613
Jon Salz77c151e2012-08-28 07:20:37 +08001142 logging.error('Received SIGINT')
Peter Ammon1e1ec572014-06-26 17:56:32 -07001143 self.run_enqueue(None)
Jon Salz77c151e2012-08-28 07:20:37 +08001144 raise KeyboardInterrupt()
1145
Ricky Liang8fecf412014-05-22 10:56:14 +08001146 def handle_sigterm(self, dummy_signum, dummy_frame): # pylint: disable=W0613
1147 logging.error('Received SIGTERM')
Hung-Te Lin94ca4742014-07-09 20:13:50 +08001148 self.env.terminate()
1149 self.run_queue.put(None)
Ricky Liang8fecf412014-05-22 10:56:14 +08001150 raise RuntimeError('Received SIGTERM')
1151
Jon Salze12c2b32013-06-25 16:24:34 +08001152 def find_kcrashes(self):
1153 """Finds kcrash files, logs them, and marks them as seen."""
1154 seen_crashes = set(
1155 self.state_instance.get_shared_data('seen_crashes', optional=True)
1156 or [])
1157
1158 for path in glob.glob('/var/spool/crash/*'):
1159 if not os.path.isfile(path):
1160 continue
1161 if path in seen_crashes:
1162 continue
1163 try:
1164 stat = os.stat(path)
1165 mtime = utils.TimeString(stat.st_mtime)
1166 logging.info(
1167 'Found new crash file %s (%d bytes at %s)',
1168 path, stat.st_size, mtime)
1169 extra_log_args = {}
1170
1171 try:
1172 _, ext = os.path.splitext(path)
1173 if ext in ['.kcrash', '.meta']:
1174 ext = ext.replace('.', '')
1175 with open(path) as f:
1176 data = f.read(MAX_CRASH_FILE_SIZE)
1177 tell = f.tell()
1178 logging.info(
1179 'Contents of %s%s:%s',
1180 path,
1181 ('' if tell == stat.st_size
1182 else '(truncated to %d bytes)' % MAX_CRASH_FILE_SIZE),
1183 ('\n' + data).replace('\n', '\n ' + ext + '> '))
1184 extra_log_args['data'] = data
1185
1186 # Copy to /var/factory/kcrash for posterity
1187 kcrash_dir = factory.get_factory_root('kcrash')
1188 utils.TryMakeDirs(kcrash_dir)
1189 shutil.copy(path, kcrash_dir)
1190 logging.info('Copied to %s',
1191 os.path.join(kcrash_dir, os.path.basename(path)))
1192 finally:
1193 # Even if something goes wrong with the above, still try to
1194 # log to event log
1195 self.event_log.Log('crash_file',
1196 path=path, size=stat.st_size, mtime=mtime,
1197 **extra_log_args)
1198 except: # pylint: disable=W0702
1199 logging.exception('Unable to handle crash files %s', path)
1200 seen_crashes.add(path)
1201
1202 self.state_instance.set_shared_data('seen_crashes', list(seen_crashes))
1203
Jon Salz128b0932013-07-03 16:55:26 +08001204 def GetTestList(self, test_list_id):
1205 """Returns the test list with the given ID.
1206
1207 Raises:
1208 TestListError: The test list ID is not valid.
1209 """
1210 try:
1211 return self.test_lists[test_list_id]
1212 except KeyError:
1213 raise test_lists.TestListError(
1214 '%r is not a valid test list ID (available IDs are [%s])' % (
1215 test_list_id, ', '.join(sorted(self.test_lists.keys()))))
1216
1217 def InitTestLists(self):
1218 """Reads in all test lists and sets the active test list."""
Ricky Liang27051552014-05-04 14:22:26 +08001219 self.test_lists = test_lists.BuildAllTestLists(
1220 force_generic=(self.options.automation_mode is not None))
Jon Salzd7550792013-07-12 05:49:27 +08001221 logging.info('Loaded test lists: [%s]',
1222 test_lists.DescribeTestLists(self.test_lists))
Jon Salz128b0932013-07-03 16:55:26 +08001223
1224 if not self.options.test_list:
1225 self.options.test_list = test_lists.GetActiveTestListId()
1226
1227 if os.sep in self.options.test_list:
1228 # It's a path pointing to an old-style test list; use it.
1229 self.test_list = factory.read_test_list(self.options.test_list)
1230 else:
1231 self.test_list = self.GetTestList(self.options.test_list)
1232
1233 logging.info('Active test list: %s', self.test_list.test_list_id)
1234
1235 if isinstance(self.test_list, test_lists.OldStyleTestList):
1236 # Actually load it in. (See OldStyleTestList for an explanation
1237 # of why this is necessary.)
1238 self.test_list = self.test_list.Load()
1239
1240 self.test_list.state_instance = self.state_instance
1241
Shuo-Peng Liao268b40b2013-07-01 15:58:59 +08001242 def init_hooks(self):
1243 """Initializes hooks.
1244
1245 Must run after self.test_list ready.
1246 """
Shuo-Peng Liao52b90da2013-06-30 17:00:06 +08001247 module, cls = self.test_list.options.hooks_class.rsplit('.', 1)
1248 self.hooks = getattr(__import__(module, fromlist=[cls]), cls)()
1249 assert isinstance(self.hooks, factory.Hooks), (
Ricky Liang45c73e72015-01-15 15:00:30 +08001250 'hooks should be of type Hooks but is %r' % type(self.hooks))
Shuo-Peng Liao52b90da2013-06-30 17:00:06 +08001251 self.hooks.test_list = self.test_list
Shuo-Peng Liao268b40b2013-07-01 15:58:59 +08001252 self.hooks.OnCreatedTestList()
Shuo-Peng Liao52b90da2013-06-30 17:00:06 +08001253
Vic Yanga3cecf82014-12-26 00:44:21 -08001254 def init_ui(self):
1255 """Initialize UI."""
1256 self._ui_initialized = True
1257 if self.options.ui == 'chrome':
Hung-Te Lin8f6a3782015-01-06 22:58:32 +08001258 if self.options.monolithic:
Hung-Te Lin7bd55312014-12-30 16:43:36 +08001259 self.env.launch_chrome()
1260 else:
1261 # The presenter is responsible for launching Chrome. Let's just
1262 # wait here.
1263 self.env.controller_ready_for_ui()
Vic Yanga3cecf82014-12-26 00:44:21 -08001264 logging.info('Waiting for a web socket connection')
1265 self.web_socket_manager.wait()
1266
1267 # Wait for the test widget size to be set; this is done in
1268 # an asynchronous RPC so there is a small chance that the
1269 # web socket might be opened first.
1270 for _ in range(100): # 10 s
1271 try:
1272 if self.state_instance.get_shared_data('test_widget_size'):
1273 break
1274 except KeyError:
1275 pass # Retry
1276 time.sleep(0.1) # 100 ms
1277 else:
1278 logging.warn('Never received test_widget_size from UI')
1279
Hung-Te Lin7bd55312014-12-30 16:43:36 +08001280 logging.info('Waiting for a web socket connection')
1281 self.web_socket_manager.wait()
1282
Jon Salz0697cbf2012-07-04 15:14:04 +08001283 def init(self, args=None, env=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001284 """Initializes Goofy.
Jon Salz0697cbf2012-07-04 15:14:04 +08001285
1286 Args:
1287 args: A list of command-line arguments. Uses sys.argv if
1288 args is None.
1289 env: An Environment instance to use (or None to choose
1290 FakeChrootEnvironment or DUTEnvironment as appropriate).
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001291 """
Jon Salz0697cbf2012-07-04 15:14:04 +08001292 parser = OptionParser()
1293 parser.add_option('-v', '--verbose', dest='verbose',
Jon Salz8fa8e832012-07-13 19:04:09 +08001294 action='store_true',
1295 help='Enable debug logging')
Jon Salz0697cbf2012-07-04 15:14:04 +08001296 parser.add_option('--print_test_list', dest='print_test_list',
Jon Salz8fa8e832012-07-13 19:04:09 +08001297 metavar='FILE',
1298 help='Read and print test list FILE, and exit')
Jon Salz0697cbf2012-07-04 15:14:04 +08001299 parser.add_option('--restart', dest='restart',
Jon Salz8fa8e832012-07-13 19:04:09 +08001300 action='store_true',
1301 help='Clear all test state')
Jon Salz0697cbf2012-07-04 15:14:04 +08001302 parser.add_option('--ui', dest='ui', type='choice',
Jon Salz7b5482e2014-08-04 17:48:41 +08001303 choices=['none', 'chrome'],
Jon Salz2f881df2013-02-01 17:00:35 +08001304 default='chrome',
Jon Salz8fa8e832012-07-13 19:04:09 +08001305 help='UI to use')
Jon Salz0697cbf2012-07-04 15:14:04 +08001306 parser.add_option('--ui_scale_factor', dest='ui_scale_factor',
Jon Salz8fa8e832012-07-13 19:04:09 +08001307 type='int', default=1,
1308 help=('Factor by which to scale UI '
1309 '(Chrome UI only)'))
Jon Salz0697cbf2012-07-04 15:14:04 +08001310 parser.add_option('--test_list', dest='test_list',
Jon Salz8fa8e832012-07-13 19:04:09 +08001311 metavar='FILE',
1312 help='Use FILE as test list')
Jon Salzc79a9982012-08-30 04:42:01 +08001313 parser.add_option('--dummy_shopfloor', action='store_true',
1314 help='Use a dummy shopfloor server')
Hung-Te Lincc41d2a2014-10-29 13:35:20 +08001315 parser.add_option('--dummy_connection_manager', action='store_true',
1316 help='Use a dummy connection manager')
Ricky Liang6fe218c2013-12-27 15:17:17 +08001317 parser.add_option('--automation-mode',
1318 choices=[m.lower() for m in AutomationMode],
Ricky Liang45c73e72015-01-15 15:00:30 +08001319 default='none', help='Factory test automation mode.')
Ricky Liang117484a2014-04-14 11:14:41 +08001320 parser.add_option('--no-auto-run-on-start', dest='auto_run_on_start',
1321 action='store_false', default=True,
1322 help=('do not automatically run the test list on goofy '
1323 'start; this is only valid when factory test '
1324 'automation is enabled'))
Chun-Ta Lina8dd3172014-11-26 16:15:13 +08001325 parser.add_option('--handshake_timeout', dest='handshake_timeout',
1326 type='float', default=0.3,
1327 help=('RPC timeout when doing handshake between device '
1328 'and presenter.'))
Vic Yang7d693c42014-09-14 09:52:39 +08001329 parser.add_option('--standalone', dest='standalone',
1330 action='store_true', default=False,
1331 help=('Assume the presenter is running on the same '
1332 'machines.'))
Hung-Te Lin8f6a3782015-01-06 22:58:32 +08001333 parser.add_option('--monolithic', dest='monolithic',
1334 action='store_true', default=False,
1335 help='Run in monolithic mode (without presenter)')
Jon Salz0697cbf2012-07-04 15:14:04 +08001336 (self.options, self.args) = parser.parse_args(args)
1337
Hung-Te Lina846f602014-07-04 20:32:22 +08001338 signal.signal(signal.SIGINT, self.handle_sigint)
1339 # TODO(hungte) SIGTERM does not work properly without Telemetry and should
1340 # be fixed.
Hung-Te Lina846f602014-07-04 20:32:22 +08001341
Jon Salz46b89562012-07-05 11:49:22 +08001342 # Make sure factory directories exist.
1343 factory.get_log_root()
1344 factory.get_state_root()
1345 factory.get_test_data_root()
1346
Jon Salz0697cbf2012-07-04 15:14:04 +08001347 global _inited_logging # pylint: disable=W0603
1348 if not _inited_logging:
1349 factory.init_logging('goofy', verbose=self.options.verbose)
1350 _inited_logging = True
Jon Salz8fa8e832012-07-13 19:04:09 +08001351
Jon Salz0f996602012-10-03 15:26:48 +08001352 if self.options.print_test_list:
Joel Kitchingb85ed7f2014-10-08 18:24:39 +08001353 print(factory.read_test_list(
1354 self.options.print_test_list).__repr__(recursive=True))
Jon Salz0f996602012-10-03 15:26:48 +08001355 sys.exit(0)
1356
Jon Salzee85d522012-07-17 14:34:46 +08001357 event_log.IncrementBootSequence()
Jon Salzd15bbcf2013-05-21 17:33:57 +08001358 # Don't defer logging the initial event, so we can make sure
1359 # that device_id, reimage_id, etc. are all set up.
1360 self.event_log = EventLog('goofy', defer=False)
Jon Salz0697cbf2012-07-04 15:14:04 +08001361
Jon Salz0697cbf2012-07-04 15:14:04 +08001362 if env:
1363 self.env = env
1364 elif factory.in_chroot():
1365 self.env = test_environment.FakeChrootEnvironment()
1366 logging.warn(
Ricky Liang45c73e72015-01-15 15:00:30 +08001367 'Using chroot environment: will not actually run autotests')
Hung-Te Lina846f602014-07-04 20:32:22 +08001368 elif self.options.ui == 'chrome':
Ricky Liang09d66d82014-09-25 11:20:54 +08001369 self.env = test_environment.DUTEnvironment()
Jon Salz0697cbf2012-07-04 15:14:04 +08001370 self.env.goofy = self
Vic Yanga4931152014-08-11 16:36:24 -07001371 # web_socket_manager will be initialized later
1372 # pylint: disable=W0108
1373 self.env.has_sockets = lambda: self.web_socket_manager.has_sockets()
Jon Salz0697cbf2012-07-04 15:14:04 +08001374
1375 if self.options.restart:
1376 state.clear_state()
1377
Jon Salz0697cbf2012-07-04 15:14:04 +08001378 if self.options.ui_scale_factor != 1 and utils.in_qemu():
1379 logging.warn(
Ricky Liang45c73e72015-01-15 15:00:30 +08001380 'In QEMU; ignoring ui_scale_factor argument')
Jon Salz0697cbf2012-07-04 15:14:04 +08001381 self.options.ui_scale_factor = 1
1382
1383 logging.info('Started')
1384
Hung-Te Lin8f6a3782015-01-06 22:58:32 +08001385 if not self.options.monolithic:
Hung-Te Lin7bd55312014-12-30 16:43:36 +08001386 self.link_manager = PresenterLinkManager(
1387 check_interval=1,
1388 handshake_timeout=self.options.handshake_timeout,
1389 standalone=self.options.standalone)
Peter Ammon1e1ec572014-06-26 17:56:32 -07001390
Jon Salz0697cbf2012-07-04 15:14:04 +08001391 self.start_state_server()
1392 self.state_instance.set_shared_data('hwid_cfg', get_hwid_cfg())
1393 self.state_instance.set_shared_data('ui_scale_factor',
Ricky Liang09216dc2013-02-22 17:26:45 +08001394 self.options.ui_scale_factor)
Jon Salz0697cbf2012-07-04 15:14:04 +08001395 self.last_shutdown_time = (
Ricky Liang45c73e72015-01-15 15:00:30 +08001396 self.state_instance.get_shared_data('shutdown_time', optional=True))
Jon Salz0697cbf2012-07-04 15:14:04 +08001397 self.state_instance.del_shared_data('shutdown_time', optional=True)
Jon Salzb19ea072013-02-07 16:35:00 +08001398 self.state_instance.del_shared_data('startup_error', optional=True)
Jon Salz0697cbf2012-07-04 15:14:04 +08001399
Ricky Liang6fe218c2013-12-27 15:17:17 +08001400 self.options.automation_mode = ParseAutomationMode(
1401 self.options.automation_mode)
1402 self.state_instance.set_shared_data('automation_mode',
1403 self.options.automation_mode)
1404 self.state_instance.set_shared_data(
1405 'automation_mode_prompt',
1406 AutomationModePrompt[self.options.automation_mode])
1407
Jon Salz128b0932013-07-03 16:55:26 +08001408 try:
1409 self.InitTestLists()
1410 except: # pylint: disable=W0702
1411 logging.exception('Unable to initialize test lists')
1412 self.state_instance.set_shared_data(
1413 'startup_error',
1414 'Unable to initialize test lists\n%s' % (
1415 traceback.format_exc()))
Jon Salzb19ea072013-02-07 16:35:00 +08001416 if self.options.ui == 'chrome':
1417 # Create an empty test list with default options so that the rest of
1418 # startup can proceed.
1419 self.test_list = factory.FactoryTestList(
1420 [], self.state_instance, factory.Options())
1421 else:
1422 # Bail with an error; no point in starting up.
1423 sys.exit('No valid test list; exiting.')
1424
Shuo-Peng Liao268b40b2013-07-01 15:58:59 +08001425 self.init_hooks()
1426
Jon Salz822838b2013-03-25 17:32:33 +08001427 if self.test_list.options.clear_state_on_start:
1428 self.state_instance.clear_test_state()
1429
Jon Salz670ce062014-05-16 15:53:50 +08001430 # If the phase is invalid, this will raise a ValueError.
1431 phase.SetPersistentPhase(self.test_list.options.phase)
1432
Dean Liao85ca86f2014-11-03 12:28:08 +08001433 # For netboot firmware, mainfw_type should be 'netboot'.
1434 if (system.SystemInfo().mainfw_type != 'nonchrome' and
1435 system.SystemInfo().firmware_version is None):
Ricky Liang45c73e72015-01-15 15:00:30 +08001436 self.state_instance.set_shared_data(
1437 'startup_error',
Vic Yang9bd4f772013-06-04 17:34:00 +08001438 'Netboot firmware detected\n'
1439 'Connect Ethernet and reboot to re-image.\n'
1440 u'侦测到网路开机固件\n'
1441 u'请连接乙太网并重启')
1442
Jon Salz0697cbf2012-07-04 15:14:04 +08001443 if not self.state_instance.has_shared_data('ui_lang'):
1444 self.state_instance.set_shared_data('ui_lang',
Ricky Liang45c73e72015-01-15 15:00:30 +08001445 self.test_list.options.ui_lang)
Jon Salz0697cbf2012-07-04 15:14:04 +08001446 self.state_instance.set_shared_data(
Ricky Liang45c73e72015-01-15 15:00:30 +08001447 'test_list_options',
1448 self.test_list.options.__dict__)
Jon Salz0697cbf2012-07-04 15:14:04 +08001449 self.state_instance.test_list = self.test_list
1450
Cheng-Yi Chiang39d32ad2013-07-23 15:02:38 +08001451 self.check_log_rotation()
Jon Salz83ef34b2012-11-01 19:46:35 +08001452
Jon Salz23926422012-09-01 03:38:13 +08001453 if self.options.dummy_shopfloor:
Ricky Liang45c73e72015-01-15 15:00:30 +08001454 os.environ[shopfloor.SHOPFLOOR_SERVER_ENV_VAR_NAME] = (
1455 'http://%s:%d/' %
Joel Kitchingb85ed7f2014-10-08 18:24:39 +08001456 (net_utils.LOCALHOST, shopfloor.DEFAULT_SERVER_PORT))
Jon Salz23926422012-09-01 03:38:13 +08001457 self.dummy_shopfloor = Spawn(
1458 [os.path.join(factory.FACTORY_PATH, 'bin', 'shopfloor_server'),
1459 '--dummy'])
1460 elif self.test_list.options.shopfloor_server_url:
1461 shopfloor.set_server_url(self.test_list.options.shopfloor_server_url)
Jon Salz2bf2f6b2013-03-28 18:49:26 +08001462 shopfloor.set_enabled(True)
Jon Salz23926422012-09-01 03:38:13 +08001463
Jon Salz0f996602012-10-03 15:26:48 +08001464 if self.test_list.options.time_sanitizer and not utils.in_chroot():
Jon Salz8fa8e832012-07-13 19:04:09 +08001465 self.time_sanitizer = time_sanitizer.TimeSanitizer(
Ricky Liang45c73e72015-01-15 15:00:30 +08001466 base_time=time_sanitizer.GetBaseTimeFromFile(
1467 # lsb-factory is written by the factory install shim during
1468 # installation, so it should have a good time obtained from
1469 # the mini-Omaha server. If it's not available, we'll use
1470 # /etc/lsb-factory (which will be much older, but reasonably
1471 # sane) and rely on a shopfloor sync to set a more accurate
1472 # time.
1473 '/usr/local/etc/lsb-factory',
1474 '/etc/lsb-release'))
Jon Salz8fa8e832012-07-13 19:04:09 +08001475 self.time_sanitizer.RunOnce()
1476
Vic Yangd8990da2013-06-27 16:57:43 +08001477 if self.test_list.options.check_cpu_usage_period_secs:
Ricky Liang45c73e72015-01-15 15:00:30 +08001478 self.cpu_usage_watcher = Spawn(
1479 ['py/tools/cpu_usage_monitor.py', '-p',
1480 str(self.test_list.options.check_cpu_usage_period_secs)],
Vic Yangd8990da2013-06-27 16:57:43 +08001481 cwd=factory.FACTORY_PATH)
1482
Jon Salz0697cbf2012-07-04 15:14:04 +08001483 self.init_states()
1484 self.start_event_server()
Wei-Ning Huang38b75f02015-02-25 18:25:14 +08001485 self.start_terminal_server()
Hung-Te Lincc41d2a2014-10-29 13:35:20 +08001486
1487 if self.options.dummy_connection_manager:
1488 # Override network manager creation to dummy implmenetation.
1489 logging.info('Using dummy network manager (--dummy_connection_manager).')
1490 self.connection_manager = connection_manager.DummyConnectionManager()
1491 else:
1492 self.connection_manager = self.env.create_connection_manager(
1493 self.test_list.options.wlans,
Mao Huang4340c632015-04-14 14:35:22 +08001494 self.test_list.options.scan_wifi_period_secs,
1495 self.test_list.options.override_blacklisted_network_devices)
Hung-Te Lincc41d2a2014-10-29 13:35:20 +08001496
Jon Salz0697cbf2012-07-04 15:14:04 +08001497 # Note that we create a log watcher even if
1498 # sync_event_log_period_secs isn't set (no background
1499 # syncing), since we may use it to flush event logs as well.
1500 self.log_watcher = EventLogWatcher(
Ricky Liang45c73e72015-01-15 15:00:30 +08001501 self.test_list.options.sync_event_log_period_secs,
1502 event_log_db_file=None,
1503 handle_event_logs_callback=self.handle_event_logs)
Jon Salz0697cbf2012-07-04 15:14:04 +08001504 if self.test_list.options.sync_event_log_period_secs:
1505 self.log_watcher.StartWatchThread()
1506
Cheng-Yi Chianga0f6eff2014-01-09 18:27:22 +08001507 # Creates a system log manager to scan logs periocially.
1508 # A scan includes clearing logs and optionally syncing logs if
1509 # enable_syng_log is True. We kick it to sync logs.
1510 self.system_log_manager = SystemLogManager(
Ricky Liang45c73e72015-01-15 15:00:30 +08001511 sync_log_paths=self.test_list.options.sync_log_paths,
1512 sync_log_period_secs=self.test_list.options.sync_log_period_secs,
1513 scan_log_period_secs=self.test_list.options.scan_log_period_secs,
1514 clear_log_paths=self.test_list.options.clear_log_paths,
1515 clear_log_excluded_paths=self.test_list.options.clear_log_excluded_paths)
Cheng-Yi Chianga0f6eff2014-01-09 18:27:22 +08001516 self.system_log_manager.Start()
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +08001517
Jon Salz0697cbf2012-07-04 15:14:04 +08001518 self.update_system_info()
1519
Vic Yang4953fc12012-07-26 16:19:53 +08001520 assert ((self.test_list.options.min_charge_pct is None) ==
1521 (self.test_list.options.max_charge_pct is None))
Vic Yange83d9a12013-04-19 20:00:20 +08001522 if utils.in_chroot():
1523 logging.info('In chroot, ignoring charge manager and charge state')
Ricky Liangc392a1c2014-06-20 18:24:59 +08001524 elif (self.test_list.options.enable_charge_manager and
1525 self.test_list.options.min_charge_pct is not None):
Vic Yang4953fc12012-07-26 16:19:53 +08001526 self.charge_manager = ChargeManager(self.test_list.options.min_charge_pct,
1527 self.test_list.options.max_charge_pct)
Jon Salzad7353b2012-10-15 16:22:46 +08001528 system.SystemStatus.charge_manager = self.charge_manager
Cheng-Yi Chiangd8186952013-04-04 23:41:14 +08001529 else:
1530 # Goofy should set charger state to charge if charge_manager is disabled.
Dean Liao88b93192014-10-23 19:37:41 +08001531 self.charge()
Vic Yang4953fc12012-07-26 16:19:53 +08001532
Vic Yang6cee2472014-10-22 17:18:52 -07001533 if CoreDumpManager.CoreDumpEnabled():
1534 self.core_dump_manager = CoreDumpManager(
1535 self.test_list.options.core_dump_watchlist)
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001536
Jon Salz0697cbf2012-07-04 15:14:04 +08001537 os.environ['CROS_FACTORY'] = '1'
1538 os.environ['CROS_DISABLE_SITE_SYSINFO'] = '1'
1539
Shuo-Peng Liao1ff502e2013-06-30 18:37:02 +08001540 if not utils.in_chroot() and self.test_list.options.use_cpufreq_manager:
Ricky Liangecddbd42014-07-24 11:32:10 +08001541 logging.info('Enabling CPU frequency manager')
Jon Salzddf0d052013-06-18 12:52:44 +08001542 self.cpufreq_manager = CpufreqManager(event_log=self.event_log)
Jon Salzce6a7f82013-06-10 18:22:54 +08001543
Justin Chuang31b02432013-06-27 15:16:51 +08001544 # Startup hooks may want to skip some tests.
1545 self.update_skipped_tests()
Jon Salz416f9cc2013-05-10 18:32:50 +08001546
Jon Salze12c2b32013-06-25 16:24:34 +08001547 self.find_kcrashes()
1548
Shuo-Peng Liao268b40b2013-07-01 15:58:59 +08001549 # Should not move earlier.
1550 self.hooks.OnStartup()
1551
Ricky Liang36512a32014-07-25 11:47:04 +08001552 # Only after this point the Goofy backend is ready for UI connection.
1553 self.ready_for_ui_connection = True
1554
Ricky Liang650f6bf2012-09-28 13:22:54 +08001555 # Create download path for autotest beforehand or autotests run at
1556 # the same time might fail due to race condition.
1557 if not factory.in_chroot():
1558 utils.TryMakeDirs(os.path.join('/usr/local/autotest', 'tests',
1559 'download'))
1560
Jon Salz0697cbf2012-07-04 15:14:04 +08001561 def state_change_callback(test, test_state):
1562 self.event_client.post_event(
Ricky Liang4bff3e32014-02-20 18:46:11 +08001563 Event(Event.Type.STATE_CHANGE, path=test.path, state=test_state))
Jon Salz0697cbf2012-07-04 15:14:04 +08001564 self.test_list.state_change_callback = state_change_callback
Jon Salz73e0fd02012-04-04 11:46:38 +08001565
Vic Yange2c76a82014-10-30 12:48:19 -07001566 self.autotest_prespawner = prespawner.AutotestPrespawner()
1567 self.autotest_prespawner.start()
1568
1569 self.pytest_prespawner = prespawner.PytestPrespawner()
1570 self.pytest_prespawner.start()
Jon Salza6711d72012-07-18 14:33:03 +08001571
Ricky Liang48e47f92014-02-26 19:31:51 +08001572 tests_after_shutdown = self.state_instance.get_shared_data(
1573 'tests_after_shutdown', optional=True)
Jon Salz57717ca2012-04-04 16:47:25 +08001574
Jon Salz5c344f62012-07-13 14:31:16 +08001575 force_auto_run = (tests_after_shutdown == FORCE_AUTO_RUN)
1576 if not force_auto_run and tests_after_shutdown is not None:
Ricky Liang48e47f92014-02-26 19:31:51 +08001577 logging.info('Resuming tests after shutdown: %s', tests_after_shutdown)
Jon Salz0697cbf2012-07-04 15:14:04 +08001578 self.tests_to_run.extend(
Ricky Liang4bff3e32014-02-20 18:46:11 +08001579 self.test_list.lookup_path(t) for t in tests_after_shutdown)
Peter Ammon1e1ec572014-06-26 17:56:32 -07001580 self.run_enqueue(self.run_next_test)
Jon Salz0697cbf2012-07-04 15:14:04 +08001581 else:
Jon Salz5c344f62012-07-13 14:31:16 +08001582 if force_auto_run or self.test_list.options.auto_run_on_start:
Ricky Liang117484a2014-04-14 11:14:41 +08001583 # If automation mode is enabled, allow suppress auto_run_on_start.
1584 if (self.options.automation_mode == 'NONE' or
1585 self.options.auto_run_on_start):
Peter Ammon1e1ec572014-06-26 17:56:32 -07001586 self.run_enqueue(
Ricky Liang117484a2014-04-14 11:14:41 +08001587 lambda: self.run_tests(self.test_list, untested_only=True))
Jon Salz5c344f62012-07-13 14:31:16 +08001588 self.state_instance.set_shared_data('tests_after_shutdown', None)
Ricky Liang4bff3e32014-02-20 18:46:11 +08001589 self.restore_active_run_state()
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001590
Vic Yang08505c72015-01-06 17:01:53 -08001591 system.GetBoard().OnTestStart()
1592
Dean Liao592e4d52013-01-10 20:06:39 +08001593 self.may_disable_cros_shortcut_keys()
1594
1595 def may_disable_cros_shortcut_keys(self):
1596 test_options = self.test_list.options
1597 if test_options.disable_cros_shortcut_keys:
1598 logging.info('Filter ChromeOS shortcut keys.')
1599 self.key_filter = KeyFilter(
1600 unmap_caps_lock=test_options.disable_caps_lock,
1601 caps_lock_keycode=test_options.caps_lock_keycode)
1602 self.key_filter.Start()
1603
Jon Salz0e6532d2012-10-25 16:30:11 +08001604 def _should_sync_time(self, foreground=False):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001605 """Returns True if we should attempt syncing time with shopfloor.
Jon Salz0e6532d2012-10-25 16:30:11 +08001606
1607 Args:
1608 foreground: If True, synchronizes even if background syncing
1609 is disabled (e.g., in explicit sync requests from the
1610 SyncShopfloor test).
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001611 """
Jon Salz0e6532d2012-10-25 16:30:11 +08001612 return ((foreground or
1613 self.test_list.options.sync_time_period_secs) and
Jon Salz54882d02012-08-31 01:57:54 +08001614 self.time_sanitizer and
1615 (not self.time_synced) and
1616 (not factory.in_chroot()))
1617
Jon Salz0e6532d2012-10-25 16:30:11 +08001618 def sync_time_with_shopfloor_server(self, foreground=False):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001619 """Syncs time with shopfloor server, if not yet synced.
Jon Salz54882d02012-08-31 01:57:54 +08001620
Jon Salz0e6532d2012-10-25 16:30:11 +08001621 Args:
1622 foreground: If True, synchronizes even if background syncing
1623 is disabled (e.g., in explicit sync requests from the
1624 SyncShopfloor test).
1625
Jon Salz54882d02012-08-31 01:57:54 +08001626 Returns:
1627 False if no time sanitizer is available, or True if this sync (or a
1628 previous sync) succeeded.
1629
1630 Raises:
1631 Exception if unable to contact the shopfloor server.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001632 """
Jon Salz0e6532d2012-10-25 16:30:11 +08001633 if self._should_sync_time(foreground):
Jon Salz54882d02012-08-31 01:57:54 +08001634 self.time_sanitizer.SyncWithShopfloor()
1635 self.time_synced = True
1636 return self.time_synced
1637
Jon Salzb92c5112012-09-21 15:40:11 +08001638 def log_disk_space_stats(self):
Jon Salz18e0e022013-06-11 17:13:39 +08001639 if (utils.in_chroot() or
1640 not self.test_list.options.log_disk_space_period_secs):
Jon Salzb92c5112012-09-21 15:40:11 +08001641 return
1642
1643 now = time.time()
1644 if (self.last_log_disk_space_time and
1645 now - self.last_log_disk_space_time <
1646 self.test_list.options.log_disk_space_period_secs):
1647 return
1648 self.last_log_disk_space_time = now
1649
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001650 # Upload event if stateful partition usage is above threshold.
1651 # Stateful partition is mounted on /usr/local, while
1652 # encrypted stateful partition is mounted on /var.
1653 # If there are too much logs in the factory process,
1654 # these two partitions might get full.
Jon Salzb92c5112012-09-21 15:40:11 +08001655 try:
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001656 vfs_infos = disk_space.GetAllVFSInfo()
1657 stateful_info, encrypted_info = None, None
1658 for vfs_info in vfs_infos.values():
1659 if '/usr/local' in vfs_info.mount_points:
1660 stateful_info = vfs_info
1661 if '/var' in vfs_info.mount_points:
1662 encrypted_info = vfs_info
1663
1664 stateful = disk_space.GetPartitionUsage(stateful_info)
1665 encrypted = disk_space.GetPartitionUsage(encrypted_info)
1666
Ricky Liang45c73e72015-01-15 15:00:30 +08001667 above_threshold = (
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001668 self.test_list.options.stateful_usage_threshold and
1669 max(stateful.bytes_used_pct,
1670 stateful.inodes_used_pct,
1671 encrypted.bytes_used_pct,
1672 encrypted.inodes_used_pct) >
Ricky Liang45c73e72015-01-15 15:00:30 +08001673 self.test_list.options.stateful_usage_threshold)
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001674
1675 if above_threshold:
1676 self.event_log.Log('stateful_partition_usage',
Ricky Liang45c73e72015-01-15 15:00:30 +08001677 partitions={
1678 'stateful': {
1679 'bytes_used_pct': FloatDigit(stateful.bytes_used_pct, 2),
1680 'inodes_used_pct': FloatDigit(stateful.inodes_used_pct, 2)},
1681 'encrypted_stateful': {
1682 'bytes_used_pct': FloatDigit(encrypted.bytes_used_pct, 2),
1683 'inodes_used_pct': FloatDigit(encrypted.inodes_used_pct, 2)}
1684 })
Cheng-Yi Chiang1b722322015-03-16 20:07:03 +08001685 self.log_watcher.KickWatchThread()
Cheng-Yi Chiang00798e72013-06-20 18:16:39 +08001686 if (not utils.in_chroot() and
1687 self.test_list.options.stateful_usage_above_threshold_action):
1688 Spawn(self.test_list.options.stateful_usage_above_threshold_action,
1689 call=True)
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001690
1691 message = disk_space.FormatSpaceUsedAll(vfs_infos)
Jon Salz3c493bb2013-02-07 17:24:58 +08001692 if message != self.last_log_disk_space_message:
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001693 if above_threshold:
1694 logging.warning(message)
1695 else:
1696 logging.info(message)
Jon Salz3c493bb2013-02-07 17:24:58 +08001697 self.last_log_disk_space_message = message
Jon Salzb92c5112012-09-21 15:40:11 +08001698 except: # pylint: disable=W0702
1699 logging.exception('Unable to get disk space used')
1700
Justin Chuang83813982013-05-13 01:26:32 +08001701 def check_battery(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001702 """Checks the current battery status.
Justin Chuang83813982013-05-13 01:26:32 +08001703
1704 Logs current battery charging level and status to log. If the battery level
1705 is lower below warning_low_battery_pct, send warning event to shopfloor.
1706 If the battery level is lower below critical_low_battery_pct, flush disks.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001707 """
Justin Chuang83813982013-05-13 01:26:32 +08001708 if not self.test_list.options.check_battery_period_secs:
1709 return
1710
1711 now = time.time()
1712 if (self.last_check_battery_time and
1713 now - self.last_check_battery_time <
1714 self.test_list.options.check_battery_period_secs):
1715 return
1716 self.last_check_battery_time = now
1717
1718 message = ''
1719 log_level = logging.INFO
1720 try:
1721 power = system.GetBoard().power
1722 if not power.CheckBatteryPresent():
1723 message = 'Battery is not present'
1724 else:
1725 ac_present = power.CheckACPresent()
1726 charge_pct = power.GetChargePct(get_float=True)
1727 message = ('Current battery level %.1f%%, AC charger is %s' %
1728 (charge_pct, 'connected' if ac_present else 'disconnected'))
1729
1730 if charge_pct > self.test_list.options.critical_low_battery_pct:
1731 critical_low_battery = False
1732 else:
1733 critical_low_battery = True
1734 # Only sync disks when battery level is still above minimum
1735 # value. This can be used for offline analysis when shopfloor cannot
1736 # be connected.
1737 if charge_pct > MIN_BATTERY_LEVEL_FOR_DISK_SYNC:
1738 logging.warning('disk syncing for critical low battery situation')
1739 os.system('sync; sync; sync')
1740 else:
1741 logging.warning('disk syncing is cancelled '
1742 'because battery level is lower than %.1f',
1743 MIN_BATTERY_LEVEL_FOR_DISK_SYNC)
1744
1745 # Notify shopfloor server
1746 if (critical_low_battery or
1747 (not ac_present and
1748 charge_pct <= self.test_list.options.warning_low_battery_pct)):
1749 log_level = logging.WARNING
1750
1751 self.event_log.Log('low_battery',
1752 battery_level=charge_pct,
1753 charger_connected=ac_present,
1754 critical=critical_low_battery)
1755 self.log_watcher.KickWatchThread()
Cheng-Yi Chianga0f6eff2014-01-09 18:27:22 +08001756 if self.test_list.options.enable_sync_log:
1757 self.system_log_manager.KickToSync()
Ricky Liang45c73e72015-01-15 15:00:30 +08001758 except: # pylint: disable=W0702
Justin Chuang83813982013-05-13 01:26:32 +08001759 logging.exception('Unable to check battery or notify shopfloor')
1760 finally:
1761 if message != self.last_check_battery_message:
1762 logging.log(log_level, message)
1763 self.last_check_battery_message = message
1764
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001765 def check_core_dump(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001766 """Checks if there is any core dumped file.
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001767
1768 Removes unwanted core dump files immediately.
1769 Syncs those files matching watch list to server with a delay between
1770 each sync. After the files have been synced to server, deletes the files.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001771 """
Vic Yang6cee2472014-10-22 17:18:52 -07001772 if not self.core_dump_manager:
1773 return
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001774 core_dump_files = self.core_dump_manager.ScanFiles()
1775 if core_dump_files:
1776 now = time.time()
1777 if (self.last_kick_sync_time and now - self.last_kick_sync_time <
1778 self.test_list.options.kick_sync_min_interval_secs):
1779 return
1780 self.last_kick_sync_time = now
1781
1782 # Sends event to server
1783 self.event_log.Log('core_dumped', files=core_dump_files)
1784 self.log_watcher.KickWatchThread()
1785
1786 # Syncs files to server
Cheng-Yi Chianga0f6eff2014-01-09 18:27:22 +08001787 if self.test_list.options.enable_sync_log:
1788 self.system_log_manager.KickToSync(
Cheng-Yi Chiangd3516a32013-07-17 15:30:47 +08001789 core_dump_files, self.core_dump_manager.ClearFiles)
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001790
Cheng-Yi Chiang39d32ad2013-07-23 15:02:38 +08001791 def check_log_rotation(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001792 """Checks log rotation file presence/absence according to test_list option.
Cheng-Yi Chiang39d32ad2013-07-23 15:02:38 +08001793
1794 Touch /var/lib/cleanup_logs_paused if test_list.options.disable_log_rotation
1795 is True, delete it otherwise. This must be done in idle loop because
1796 autotest client will touch /var/lib/cleanup_logs_paused each time it runs
1797 an autotest.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001798 """
Cheng-Yi Chiang39d32ad2013-07-23 15:02:38 +08001799 if utils.in_chroot():
1800 return
1801 try:
1802 if self.test_list.options.disable_log_rotation:
1803 open(CLEANUP_LOGS_PAUSED, 'w').close()
1804 else:
1805 file_utils.TryUnlink(CLEANUP_LOGS_PAUSED)
1806 except: # pylint: disable=W0702
1807 # Oh well. Logs an error (but no trace)
1808 logging.info(
1809 'Unable to %s %s: %s',
1810 'touch' if self.test_list.options.disable_log_rotation else 'delete',
1811 CLEANUP_LOGS_PAUSED, utils.FormatExceptionOnly())
1812
Jon Salz8fa8e832012-07-13 19:04:09 +08001813 def sync_time_in_background(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001814 """Writes out current time and tries to sync with shopfloor server."""
Jon Salzb22d1172012-08-06 10:38:57 +08001815 if not self.time_sanitizer:
1816 return
1817
1818 # Write out the current time.
1819 self.time_sanitizer.SaveTime()
1820
Jon Salz54882d02012-08-31 01:57:54 +08001821 if not self._should_sync_time():
Jon Salz8fa8e832012-07-13 19:04:09 +08001822 return
1823
1824 now = time.time()
1825 if self.last_sync_time and (
1826 now - self.last_sync_time <
1827 self.test_list.options.sync_time_period_secs):
1828 # Not yet time for another check.
1829 return
1830 self.last_sync_time = now
1831
1832 def target():
1833 try:
Jon Salz54882d02012-08-31 01:57:54 +08001834 self.sync_time_with_shopfloor_server()
Jon Salz8fa8e832012-07-13 19:04:09 +08001835 except: # pylint: disable=W0702
1836 # Oh well. Log an error (but no trace)
1837 logging.info(
Ricky Liang45c73e72015-01-15 15:00:30 +08001838 'Unable to get time from shopfloor server: %s',
1839 utils.FormatExceptionOnly())
Jon Salz8fa8e832012-07-13 19:04:09 +08001840
1841 thread = threading.Thread(target=target)
1842 thread.daemon = True
1843 thread.start()
1844
Peter Ammon1e1ec572014-06-26 17:56:32 -07001845 def perform_periodic_tasks(self):
1846 """Override of base method to perform periodic work.
Vic Yang4953fc12012-07-26 16:19:53 +08001847
Peter Ammon1e1ec572014-06-26 17:56:32 -07001848 This method must not raise exceptions.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001849 """
Peter Ammon1e1ec572014-06-26 17:56:32 -07001850 super(Goofy, self).perform_periodic_tasks()
Jon Salzb22d1172012-08-06 10:38:57 +08001851
Vic Yang311ddb82012-09-26 12:08:28 +08001852 self.check_exclusive()
cychiang21886742012-07-05 15:16:32 +08001853 self.check_for_updates()
Jon Salz8fa8e832012-07-13 19:04:09 +08001854 self.sync_time_in_background()
Jon Salzb92c5112012-09-21 15:40:11 +08001855 self.log_disk_space_stats()
Justin Chuang83813982013-05-13 01:26:32 +08001856 self.check_battery()
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001857 self.check_core_dump()
Cheng-Yi Chiang39d32ad2013-07-23 15:02:38 +08001858 self.check_log_rotation()
Jon Salz57717ca2012-04-04 16:47:25 +08001859
Cheng-Yi Chiangf5b21012015-03-17 15:37:14 +08001860 def handle_event_logs(self, chunks, periodic=False):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001861 """Callback for event watcher.
Jon Salz258a40c2012-04-19 12:34:01 +08001862
Jon Salz0697cbf2012-07-04 15:14:04 +08001863 Attempts to upload the event logs to the shopfloor server.
Vic Yang93027612013-05-06 02:42:49 +08001864
1865 Args:
Jon Salzd15bbcf2013-05-21 17:33:57 +08001866 chunks: A list of Chunk objects.
Cheng-Yi Chiangf5b21012015-03-17 15:37:14 +08001867 periodic: This event log handling is periodic. Error messages
1868 will only be shown for the first time.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001869 """
Vic Yang93027612013-05-06 02:42:49 +08001870 first_exception = None
1871 exception_count = 0
Cheng-Yi Chiangf5b21012015-03-17 15:37:14 +08001872 # Suppress error messages for periodic event syncing except for the
1873 # first time. If event syncing is not periodic, always show the error
1874 # messages.
1875 quiet = self._suppress_event_log_error_messages if periodic else False
Vic Yang93027612013-05-06 02:42:49 +08001876
Jon Salzd15bbcf2013-05-21 17:33:57 +08001877 for chunk in chunks:
Vic Yang93027612013-05-06 02:42:49 +08001878 try:
Jon Salzcddb6402013-05-23 12:56:42 +08001879 description = 'event logs (%s)' % str(chunk)
Vic Yang93027612013-05-06 02:42:49 +08001880 start_time = time.time()
1881 shopfloor_client = shopfloor.get_instance(
Ricky Liang45c73e72015-01-15 15:00:30 +08001882 detect=True,
Cheng-Yi Chiangf5b21012015-03-17 15:37:14 +08001883 timeout=self.test_list.options.shopfloor_timeout_secs,
1884 quiet=quiet)
Ricky Liang45c73e72015-01-15 15:00:30 +08001885 shopfloor_client.UploadEvent(chunk.log_name + '.' +
Jon Salzd15bbcf2013-05-21 17:33:57 +08001886 event_log.GetReimageId(),
1887 Binary(chunk.chunk))
Vic Yang93027612013-05-06 02:42:49 +08001888 logging.info(
Ricky Liang45c73e72015-01-15 15:00:30 +08001889 'Successfully synced %s in %.03f s',
1890 description, time.time() - start_time)
1891 except: # pylint: disable=W0702
Jon Salzd15bbcf2013-05-21 17:33:57 +08001892 first_exception = (first_exception or (chunk.log_name + ': ' +
Vic Yang93027612013-05-06 02:42:49 +08001893 utils.FormatExceptionOnly()))
1894 exception_count += 1
1895
1896 if exception_count:
1897 if exception_count == 1:
1898 msg = 'Log upload failed: %s' % first_exception
1899 else:
1900 msg = '%d log upload failed; first is: %s' % (
1901 exception_count, first_exception)
Cheng-Yi Chiangf5b21012015-03-17 15:37:14 +08001902 # For periodic event log syncing, only show the first error messages.
1903 if periodic:
1904 if not self._suppress_event_log_error_messages:
1905 self._suppress_event_log_error_messages = True
1906 logging.warning('Suppress periodic shopfloor error messages for '
1907 'event log syncing after the first one.')
1908 raise Exception(msg)
1909 # For event log syncing by request, show the error messages.
1910 else:
1911 raise Exception(msg)
Vic Yang93027612013-05-06 02:42:49 +08001912
Ricky Liang45c73e72015-01-15 15:00:30 +08001913 def run_tests_with_status(self, statuses_to_run, starting_at=None, root=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001914 """Runs all top-level tests with a particular status.
Jon Salz0405ab52012-03-16 15:26:52 +08001915
Jon Salz0697cbf2012-07-04 15:14:04 +08001916 All active tests, plus any tests to re-run, are reset.
Jon Salz57717ca2012-04-04 16:47:25 +08001917
Jon Salz0697cbf2012-07-04 15:14:04 +08001918 Args:
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001919 statuses_to_run: The particular status that caller wants to run.
Jon Salz0697cbf2012-07-04 15:14:04 +08001920 starting_at: If provided, only auto-runs tests beginning with
1921 this test.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001922 root: The root of tests to run. If not provided, it will be
1923 the root of all tests.
1924 """
Jon Salz0697cbf2012-07-04 15:14:04 +08001925 root = root or self.test_list
Jon Salz57717ca2012-04-04 16:47:25 +08001926
Jon Salz0697cbf2012-07-04 15:14:04 +08001927 if starting_at:
1928 # Make sure they passed a test, not a string.
1929 assert isinstance(starting_at, factory.FactoryTest)
Jon Salz0405ab52012-03-16 15:26:52 +08001930
Jon Salz0697cbf2012-07-04 15:14:04 +08001931 tests_to_reset = []
1932 tests_to_run = []
Jon Salz0405ab52012-03-16 15:26:52 +08001933
Jon Salz0697cbf2012-07-04 15:14:04 +08001934 found_starting_at = False
Jon Salz0405ab52012-03-16 15:26:52 +08001935
Jon Salz0697cbf2012-07-04 15:14:04 +08001936 for test in root.get_top_level_tests():
1937 if starting_at:
1938 if test == starting_at:
1939 # We've found starting_at; do auto-run on all
1940 # subsequent tests.
1941 found_starting_at = True
1942 if not found_starting_at:
1943 # Don't start this guy yet
1944 continue
Jon Salz0405ab52012-03-16 15:26:52 +08001945
Jon Salz0697cbf2012-07-04 15:14:04 +08001946 status = test.get_state().status
1947 if status == TestState.ACTIVE or status in statuses_to_run:
1948 # Reset the test (later; we will need to abort
1949 # all active tests first).
1950 tests_to_reset.append(test)
1951 if status in statuses_to_run:
1952 tests_to_run.append(test)
Jon Salz0405ab52012-03-16 15:26:52 +08001953
Jon Salz6dc031d2013-06-19 13:06:23 +08001954 self.abort_active_tests('Operator requested run/re-run of certain tests')
Jon Salz258a40c2012-04-19 12:34:01 +08001955
Jon Salz0697cbf2012-07-04 15:14:04 +08001956 # Reset all statuses of the tests to run (in case any tests were active;
1957 # we want them to be run again).
1958 for test_to_reset in tests_to_reset:
1959 for test in test_to_reset.walk():
1960 test.update_state(status=TestState.UNTESTED)
Jon Salz57717ca2012-04-04 16:47:25 +08001961
Jon Salz0697cbf2012-07-04 15:14:04 +08001962 self.run_tests(tests_to_run, untested_only=True)
Jon Salz0405ab52012-03-16 15:26:52 +08001963
Jon Salz0697cbf2012-07-04 15:14:04 +08001964 def restart_tests(self, root=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001965 """Restarts all tests."""
Jon Salz0697cbf2012-07-04 15:14:04 +08001966 root = root or self.test_list
Jon Salz0405ab52012-03-16 15:26:52 +08001967
Jon Salz6dc031d2013-06-19 13:06:23 +08001968 self.abort_active_tests('Operator requested restart of certain tests')
Jon Salz0697cbf2012-07-04 15:14:04 +08001969 for test in root.walk():
Ricky Liangfea4ac92014-08-21 11:55:59 +08001970 test.update_state(status=TestState.UNTESTED)
Jon Salz0697cbf2012-07-04 15:14:04 +08001971 self.run_tests(root)
Hung-Te Lin96632362012-03-20 21:14:18 +08001972
Jon Salz0697cbf2012-07-04 15:14:04 +08001973 def auto_run(self, starting_at=None, root=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001974 """"Auto-runs" tests that have not been run yet.
Hung-Te Lin96632362012-03-20 21:14:18 +08001975
Jon Salz0697cbf2012-07-04 15:14:04 +08001976 Args:
1977 starting_at: If provide, only auto-runs tests beginning with
1978 this test.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001979 root: If provided, the root of tests to run. If not provided, the root
1980 will be test_list (root of all tests).
1981 """
Jon Salz0697cbf2012-07-04 15:14:04 +08001982 root = root or self.test_list
1983 self.run_tests_with_status([TestState.UNTESTED, TestState.ACTIVE],
Ricky Liang45c73e72015-01-15 15:00:30 +08001984 starting_at=starting_at,
1985 root=root)
Jon Salz968e90b2012-03-18 16:12:43 +08001986
Jon Salz0697cbf2012-07-04 15:14:04 +08001987 def re_run_failed(self, root=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001988 """Re-runs failed tests."""
Jon Salz0697cbf2012-07-04 15:14:04 +08001989 root = root or self.test_list
1990 self.run_tests_with_status([TestState.FAILED], root=root)
Jon Salz57717ca2012-04-04 16:47:25 +08001991
Jon Salz0697cbf2012-07-04 15:14:04 +08001992 def show_review_information(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001993 """Event handler for showing review information screen.
Jon Salz57717ca2012-04-04 16:47:25 +08001994
Peter Ammon1e1ec572014-06-26 17:56:32 -07001995 The information screen is rendered by main UI program (ui.py), so in
Jon Salz0697cbf2012-07-04 15:14:04 +08001996 goofy we only need to kill all active tests, set them as untested, and
1997 clear remaining tests.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001998 """
Jon Salz0697cbf2012-07-04 15:14:04 +08001999 self.kill_active_tests(False)
Jon Salza6711d72012-07-18 14:33:03 +08002000 self.cancel_pending_tests()
Jon Salz57717ca2012-04-04 16:47:25 +08002001
Jon Salz0697cbf2012-07-04 15:14:04 +08002002 def handle_switch_test(self, event):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08002003 """Switches to a particular test.
Jon Salz0405ab52012-03-16 15:26:52 +08002004
Ricky Liang6fe218c2013-12-27 15:17:17 +08002005 Args:
2006 event: The SWITCH_TEST event.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08002007 """
Jon Salz0697cbf2012-07-04 15:14:04 +08002008 test = self.test_list.lookup_path(event.path)
2009 if not test:
2010 logging.error('Unknown test %r', event.key)
2011 return
Jon Salz73e0fd02012-04-04 11:46:38 +08002012
Jon Salz0697cbf2012-07-04 15:14:04 +08002013 invoc = self.invocations.get(test)
2014 if invoc and test.backgroundable:
2015 # Already running: just bring to the front if it
2016 # has a UI.
2017 logging.info('Setting visible test to %s', test.path)
Jon Salz36fbbb52012-07-05 13:45:06 +08002018 self.set_visible_test(test)
Jon Salz0697cbf2012-07-04 15:14:04 +08002019 return
Jon Salz73e0fd02012-04-04 11:46:38 +08002020
Jon Salz6dc031d2013-06-19 13:06:23 +08002021 self.abort_active_tests('Operator requested abort (switch_test)')
Jon Salz0697cbf2012-07-04 15:14:04 +08002022 for t in test.walk():
2023 t.update_state(status=TestState.UNTESTED)
Jon Salz73e0fd02012-04-04 11:46:38 +08002024
Jon Salz0697cbf2012-07-04 15:14:04 +08002025 if self.test_list.options.auto_run_on_keypress:
2026 self.auto_run(starting_at=test)
2027 else:
2028 self.run_tests(test)
Jon Salz73e0fd02012-04-04 11:46:38 +08002029
Wei-Ning Huang38b75f02015-02-25 18:25:14 +08002030 def handle_key_filter_mode(self, event):
2031 if self.key_filter:
2032 if getattr(event, 'enabled'):
2033 self.key_filter.Start()
2034 else:
2035 self.key_filter.Stop()
2036
Jon Salz0697cbf2012-07-04 15:14:04 +08002037 def wait(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08002038 """Waits for all pending invocations.
Jon Salz0697cbf2012-07-04 15:14:04 +08002039
2040 Useful for testing.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08002041 """
Jon Salz1acc8742012-07-17 17:45:55 +08002042 while self.invocations:
2043 for k, v in self.invocations.iteritems():
2044 logging.info('Waiting for %s to complete...', k)
2045 v.thread.join()
2046 self.reap_completed_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +08002047
Hung-Te Linf2f78f72012-02-08 19:27:11 +08002048if __name__ == '__main__':
Peter Ammona3d298c2014-09-23 10:11:02 -07002049 Goofy.run_main_and_exit()