blob: b96e5970198a9f98900e314087e01b534d38d2f5 [file] [log] [blame]
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001#!/usr/bin/python -u
Hung-Te Lin1990b742017-08-09 17:34:57 +08002# Copyright 2012 The Chromium OS Authors. All rights reserved.
Hung-Te Linf2f78f72012-02-08 19:27:11 +08003# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08006"""The main factory flow that runs the factory test and finalizes a device."""
Hung-Te Linf2f78f72012-02-08 19:27:11 +08007
Joel Kitchingb85ed7f2014-10-08 18:24:39 +08008from __future__ import print_function
9
Jon Salz0405ab52012-03-16 15:26:52 +080010import logging
Wei-Han Chenc17b4112016-11-22 14:56:51 +080011from optparse import OptionParser
Jon Salz0405ab52012-03-16 15:26:52 +080012import os
Jon Salz77c151e2012-08-28 07:20:37 +080013import signal
Jon Salz0405ab52012-03-16 15:26:52 +080014import sys
Jon Salz0405ab52012-03-16 15:26:52 +080015import threading
16import time
17import traceback
Jon Salz258a40c2012-04-19 12:34:01 +080018import uuid
Jon Salzb10cf512012-08-09 17:29:21 +080019from xmlrpclib import Binary
Hung-Te Linf2f78f72012-02-08 19:27:11 +080020
Peter Shihfdf17682017-05-26 11:38:39 +080021import factory_common # pylint: disable=unused-import
Hung-Te Linb6287242016-05-18 14:39:05 +080022from cros.factory.device import device_utils
Vic Yangd80ea752014-09-24 16:07:14 +080023from cros.factory.goofy.goofy_base import GoofyBase
24from cros.factory.goofy.goofy_rpc import GoofyRPC
Earl Ouacbe99c2017-02-21 16:04:19 +080025from cros.factory.goofy import goofy_server
Vic Yangd80ea752014-09-24 16:07:14 +080026from cros.factory.goofy.invocation import TestInvocation
Earl Oua3bca122016-10-21 16:00:30 +080027from cros.factory.goofy.plugins import plugin_controller
Vic Yange2c76a82014-10-30 12:48:19 -070028from cros.factory.goofy import prespawner
Earl Oua3bca122016-10-21 16:00:30 +080029from cros.factory.goofy import test_environment
Wei-Han Chenc17b4112016-11-22 14:56:51 +080030from cros.factory.goofy.test_list_iterator import TestListIterator
Earl Oua3bca122016-10-21 16:00:30 +080031from cros.factory.goofy import updater
Vic Yangd80ea752014-09-24 16:07:14 +080032from cros.factory.goofy.web_socket_manager import WebSocketManager
Wei-Han Chen109d76f2017-08-08 18:50:35 +080033from cros.factory.test import device_data
Hung-Te Linb6287242016-05-18 14:39:05 +080034from cros.factory.test.e2e_test.common import AutomationMode
35from cros.factory.test.e2e_test.common import AutomationModePrompt
36from cros.factory.test.e2e_test.common import ParseAutomationMode
Earl Ouacbe99c2017-02-21 16:04:19 +080037from cros.factory.test.env import goofy_proxy
Hung-Te Linb6287242016-05-18 14:39:05 +080038from cros.factory.test.env import paths
Jon Salz83591782012-06-26 11:09:58 +080039from cros.factory.test.event import Event
Shen-En Shihd7359cc2017-10-03 16:01:47 +080040from cros.factory.test.event import ThreadingEventClient
Jon Salz83591782012-06-26 11:09:58 +080041from cros.factory.test.event import EventServer
Hung-Te Linb6287242016-05-18 14:39:05 +080042from cros.factory.test import event_log
43from cros.factory.test.event_log import EventLog
Hung-Te Linb6287242016-05-18 14:39:05 +080044from cros.factory.test.event_log import GetBootSequence
Hung-Te Lin91492a12014-11-25 18:56:30 +080045from cros.factory.test.event_log_watcher import EventLogWatcher
Earl Oua3bca122016-10-21 16:00:30 +080046from cros.factory.test import factory
jcliangcd688182012-08-20 21:01:26 +080047from cros.factory.test.factory import TestState
Peter Shihce03c2e2017-03-21 17:36:10 +080048from cros.factory.test.i18n import html_translator
Peter Shihf65db932017-03-22 17:06:34 +080049from cros.factory.test.i18n import test_ui as i18n_test_ui
Peter Shih80e78b42017-03-10 17:00:56 +080050from cros.factory.test.i18n import translation
Hung-Te Lin3f096842016-01-13 17:37:06 +080051from cros.factory.test.rules import phase
Hung-Te Lind151bf32017-08-30 11:05:47 +080052from cros.factory.test import server_proxy
Hung-Te Linda8eb992017-09-28 03:27:12 +080053from cros.factory.test import session
Earl Oua3bca122016-10-21 16:00:30 +080054from cros.factory.test import state
Wei-Han Chen16cc5dd2017-04-27 17:38:53 +080055from cros.factory.test.test_lists import manager
Wei-Han Chen2ebb92d2016-01-12 14:51:41 +080056from cros.factory.test.test_lists import test_lists
Wei-Han Chen03113912017-09-29 15:58:25 +080057from cros.factory.test.test_lists import test_object
chuntseneb33f9d2017-05-12 13:38:17 +080058from cros.factory.testlog import testlog
Hung-Te Linb6287242016-05-18 14:39:05 +080059from cros.factory.tools.key_filter import KeyFilter
Wei-Han Chen78f35f62017-03-06 20:11:20 +080060from cros.factory.utils import config_utils
Hung-Te Linf707b242016-01-08 23:11:42 +080061from cros.factory.utils import debug_utils
Jon Salz2af235d2013-06-24 14:47:21 +080062from cros.factory.utils import file_utils
Hung-Te Lin8fc0d652017-09-21 13:05:44 +080063from cros.factory.utils import log_utils
Joel Kitchingb85ed7f2014-10-08 18:24:39 +080064from cros.factory.utils import net_utils
Hung-Te Lin4e6357c2016-01-08 14:32:00 +080065from cros.factory.utils import sys_utils
Hung-Te Linf707b242016-01-08 23:11:42 +080066from cros.factory.utils import type_utils
Hung-Te Linf2f78f72012-02-08 19:27:11 +080067
Earl Ou6de96c02017-05-19 18:51:28 +080068from cros.factory.external import syslog
69
Hung-Te Linf2f78f72012-02-08 19:27:11 +080070
Hung-Te Linf2f78f72012-02-08 19:27:11 +080071HWID_CFG_PATH = '/usr/local/share/chromeos-hwid/cfg'
Peter Shihb4e49352017-05-25 17:35:11 +080072CACHES_DIR = os.path.join(paths.DATA_STATE_DIR, 'caches')
Hung-Te Linf2f78f72012-02-08 19:27:11 +080073
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
Wei-Han Chenc17b4112016-11-22 14:56:51 +080078# Key to load the test list iterator after shutdown test
79TESTS_AFTER_SHUTDOWN = 'tests_after_shutdown'
80
Hung-Te Linf707b242016-01-08 23:11:42 +080081Status = type_utils.Enum(['UNINITIALIZED', 'INITIALIZING', 'RUNNING',
Wei-Han Chen2ebb92d2016-01-12 14:51:41 +080082 'TERMINATING', 'TERMINATED'])
Jon Salzd7550792013-07-12 05:49:27 +080083
Peter Ammon1e1ec572014-06-26 17:56:32 -070084class Goofy(GoofyBase):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +080085 """The main factory flow.
Jon Salz0697cbf2012-07-04 15:14:04 +080086
87 Note that all methods in this class must be invoked from the main
88 (event) thread. Other threads, such as callbacks and TestInvocation
89 methods, should instead post events on the run queue.
90
91 TODO: Unit tests. (chrome-os-partner:7409)
92
93 Properties:
94 uuid: A unique UUID for this invocation of Goofy.
95 state_instance: An instance of FactoryState.
96 state_server: The FactoryState XML/RPC server.
97 state_server_thread: A thread running state_server.
98 event_server: The EventServer socket server.
99 event_server_thread: A thread running event_server.
100 event_client: A client to the event server.
Earl Oua3bca122016-10-21 16:00:30 +0800101 plugin_controller: The PluginController object.
Jon Salz0697cbf2012-07-04 15:14:04 +0800102 invocations: A map from FactoryTest objects to the corresponding
103 TestInvocations objects representing active tests.
Jon Salz0697cbf2012-07-04 15:14:04 +0800104 options: Command-line options.
105 args: Command-line args.
106 test_list: The test list.
Jon Salz128b0932013-07-03 16:55:26 +0800107 test_lists: All new-style test lists.
Ricky Liang4bff3e32014-02-20 18:46:11 +0800108 run_id: The identifier for latest test run.
109 scheduled_run_tests: The list of tests scheduled for latest test run.
Jon Salz0697cbf2012-07-04 15:14:04 +0800110 event_handlers: Map of Event.Type to the method used to handle that
111 event. If the method has an 'event' argument, the event is passed
112 to the handler.
Jon Salz416f9cc2013-05-10 18:32:50 +0800113 hooks: A Hooks object containing hooks for various Goofy actions.
Jon Salzd7550792013-07-12 05:49:27 +0800114 status: The current Goofy status (a member of the Status enum).
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800115 """
Ricky Liang45c73e72015-01-15 15:00:30 +0800116
Jon Salz0697cbf2012-07-04 15:14:04 +0800117 def __init__(self):
Peter Ammon1e1ec572014-06-26 17:56:32 -0700118 super(Goofy, self).__init__()
Jon Salz0697cbf2012-07-04 15:14:04 +0800119 self.uuid = str(uuid.uuid4())
120 self.state_instance = None
Earl Ouacbe99c2017-02-21 16:04:19 +0800121 self.goofy_server = None
122 self.goofy_server_thread = None
Jon Salz16d10542012-07-23 12:18:45 +0800123 self.goofy_rpc = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800124 self.event_server = None
125 self.event_server_thread = None
126 self.event_client = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800127 self.log_watcher = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800128 self.event_log = None
Chun-Ta Lin53cbbd52016-06-08 21:42:19 +0800129 self.testlog = None
Earl Oua3bca122016-10-21 16:00:30 +0800130 self.plugin_controller = None
Vic Yange2c76a82014-10-30 12:48:19 -0700131 self.pytest_prespawner = None
Vic Yanga3cecf82014-12-26 00:44:21 -0800132 self._ui_initialized = False
Jon Salz0697cbf2012-07-04 15:14:04 +0800133 self.invocations = {}
Jon Salz0697cbf2012-07-04 15:14:04 +0800134 self.chrome = None
Jon Salz416f9cc2013-05-10 18:32:50 +0800135 self.hooks = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800136
137 self.options = None
138 self.args = None
139 self.test_list = None
Jon Salz128b0932013-07-03 16:55:26 +0800140 self.test_lists = None
Ricky Liang4bff3e32014-02-20 18:46:11 +0800141 self.run_id = None
142 self.scheduled_run_tests = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800143 self.env = None
Jon Salzb22d1172012-08-06 10:38:57 +0800144 self.last_idle = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800145 self.last_shutdown_time = None
cychiang21886742012-07-05 15:16:32 +0800146 self.last_update_check = None
Cheng-Yi Chiang194d3c02015-03-16 14:37:15 +0800147 self._suppress_periodic_update_messages = False
Cheng-Yi Chiangf5b21012015-03-17 15:37:14 +0800148 self._suppress_event_log_error_messages = False
Earl Ouab979142016-10-25 16:48:06 +0800149 self.exclusive_resources = set()
Dean Liao592e4d52013-01-10 20:06:39 +0800150 self.key_filter = None
Jon Salzd7550792013-07-12 05:49:27 +0800151 self.status = Status.UNINITIALIZED
Ricky Liang36512a32014-07-25 11:47:04 +0800152 self.ready_for_ui_connection = False
Hung-Te Linef7f2be2015-07-20 20:38:51 +0800153 self.is_restart_requested = False
Wei-Han Chenc17b4112016-11-22 14:56:51 +0800154 self.test_list_iterator = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800155
Wei-Han Chen16cc5dd2017-04-27 17:38:53 +0800156 self.test_list_manager = manager.Manager()
157
Peter Shih7cc81b12017-08-24 13:04:46 +0800158 self._default_test_ui_html = None
159
Hung-Te Lin6a72c642015-12-13 22:09:09 +0800160 # TODO(hungte) Support controlling remote DUT.
Hung-Te Linb6287242016-05-18 14:39:05 +0800161 self.dut = device_utils.CreateDUTInterface()
Hung-Te Lin6a72c642015-12-13 22:09:09 +0800162
Jon Salz85a39882012-07-05 16:45:04 +0800163 def test_or_root(event, parent_or_group=True):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800164 """Returns the test affected by a particular event.
Jon Salz85a39882012-07-05 16:45:04 +0800165
166 Args:
167 event: The event containing an optional 'path' attribute.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800168 parent_or_group: If True, returns the top-level parent for a test (the
Jon Salz85a39882012-07-05 16:45:04 +0800169 root node of the tests that need to be run together if the given test
170 path is to be run).
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800171 """
Jon Salz0697cbf2012-07-04 15:14:04 +0800172 try:
173 path = event.path
174 except AttributeError:
175 path = None
176
177 if path:
Wei-Han Chen3ae204c2017-04-28 19:36:55 +0800178 test = self.test_list.LookupPath(path)
Jon Salz85a39882012-07-05 16:45:04 +0800179 if parent_or_group:
Wei-Han Chen3ae204c2017-04-28 19:36:55 +0800180 test = test.GetTopLevelParentOrGroup()
Jon Salz85a39882012-07-05 16:45:04 +0800181 return test
Jon Salz0697cbf2012-07-04 15:14:04 +0800182 else:
Peter Shih999faf72017-07-07 11:32:42 +0800183 return self.test_list.ToFactoryTestList()
Jon Salz0697cbf2012-07-04 15:14:04 +0800184
185 self.event_handlers = {
Ricky Liang45c73e72015-01-15 15:00:30 +0800186 Event.Type.RESTART_TESTS:
187 lambda event: self.restart_tests(root=test_or_root(event)),
188 Event.Type.AUTO_RUN:
189 lambda event: self.auto_run(root=test_or_root(event)),
Ricky Liang45c73e72015-01-15 15:00:30 +0800190 Event.Type.RUN_TESTS_WITH_STATUS:
191 lambda event: self.run_tests_with_status(
192 event.status,
193 root=test_or_root(event)),
Ricky Liang45c73e72015-01-15 15:00:30 +0800194 Event.Type.UPDATE_SYSTEM_INFO:
195 lambda event: self.update_system_info(),
196 Event.Type.STOP:
197 lambda event: self.stop(root=test_or_root(event, False),
198 fail=getattr(event, 'fail', False),
199 reason=getattr(event, 'reason', None)),
Ricky Liang45c73e72015-01-15 15:00:30 +0800200 Event.Type.CLEAR_STATE:
201 lambda event: self.clear_state(
Wei-Han Chen3ae204c2017-04-28 19:36:55 +0800202 self.test_list.LookupPath(event.path)),
Wei-Ning Huang38b75f02015-02-25 18:25:14 +0800203 Event.Type.KEY_FILTER_MODE: self.handle_key_filter_mode,
Jon Salz0697cbf2012-07-04 15:14:04 +0800204 }
205
Jon Salz0697cbf2012-07-04 15:14:04 +0800206 self.web_socket_manager = None
207
208 def destroy(self):
Ricky Liang74237a02014-09-18 15:11:23 +0800209 """Performs any shutdown tasks. Overrides base class method."""
chuntsen9d675c62017-06-20 14:35:30 +0800210 # To avoid race condition when running shutdown test.
211 for test, invoc in self.invocations.iteritems():
212 logging.info('Waiting for %s to complete...', test)
213 invoc.thread.join(3) # Timeout in 3 seconds.
214
Jon Salzd7550792013-07-12 05:49:27 +0800215 self.status = Status.TERMINATING
Jon Salz0697cbf2012-07-04 15:14:04 +0800216 if self.chrome:
217 self.chrome.kill()
218 self.chrome = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800219 if self.web_socket_manager:
220 logging.info('Stopping web sockets')
221 self.web_socket_manager.close()
222 self.web_socket_manager = None
Earl Ouacbe99c2017-02-21 16:04:19 +0800223 if self.goofy_server_thread:
224 logging.info('Stopping goofy server')
225 self.goofy_server.shutdown()
226 self.goofy_server_thread.join()
227 self.goofy_server.server_close()
228 self.goofy_server_thread = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800229 if self.state_instance:
230 self.state_instance.close()
231 if self.event_server_thread:
232 logging.info('Stopping event server')
Peter Shihce9490e2017-05-11 14:32:12 +0800233 net_utils.ShutdownTCPServer(self.event_server)
Jon Salz0697cbf2012-07-04 15:14:04 +0800234 self.event_server_thread.join()
235 self.event_server.server_close()
236 self.event_server_thread = None
237 if self.log_watcher:
238 if self.log_watcher.IsThreadStarted():
239 self.log_watcher.StopWatchThread()
240 self.log_watcher = None
Vic Yange2c76a82014-10-30 12:48:19 -0700241 if self.pytest_prespawner:
242 logging.info('Stopping pytest prespawner')
243 self.pytest_prespawner.stop()
244 self.pytest_prespawner = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800245 if self.event_client:
246 logging.info('Closing event client')
247 self.event_client.close()
248 self.event_client = None
249 if self.event_log:
250 self.event_log.Close()
251 self.event_log = None
Chun-Ta Lin53cbbd52016-06-08 21:42:19 +0800252 if self.testlog:
253 self.testlog.Close()
254 self.testlog = None
Dean Liao592e4d52013-01-10 20:06:39 +0800255 if self.key_filter:
256 self.key_filter.Stop()
Earl Oua3bca122016-10-21 16:00:30 +0800257 if self.plugin_controller:
258 self.plugin_controller.StopAndDestroyAllPlugins()
259 self.plugin_controller = None
Dean Liao592e4d52013-01-10 20:06:39 +0800260
Peter Ammon1e1ec572014-06-26 17:56:32 -0700261 super(Goofy, self).destroy()
Jon Salz0697cbf2012-07-04 15:14:04 +0800262 logging.info('Done destroying Goofy')
Jon Salzd7550792013-07-12 05:49:27 +0800263 self.status = Status.TERMINATED
Jon Salz0697cbf2012-07-04 15:14:04 +0800264
Earl Ouacbe99c2017-02-21 16:04:19 +0800265 def start_goofy_server(self):
266 self.goofy_server = goofy_server.GoofyServer(
Shen-En Shihd5b96bf2017-08-09 17:47:21 +0800267 (goofy_proxy.DEFAULT_GOOFY_BIND, goofy_proxy.DEFAULT_GOOFY_PORT))
Earl Ouacbe99c2017-02-21 16:04:19 +0800268 logging.info('Starting goofy server')
269 self.goofy_server_thread = threading.Thread(
270 target=self.goofy_server.serve_forever,
271 name='GoofyServer')
272 self.goofy_server_thread.start()
273
Peter Shih7cc81b12017-08-24 13:04:46 +0800274 static_path = os.path.join(paths.FACTORY_PYTHON_PACKAGE_DIR, 'goofy/static')
Earl Ouacbe99c2017-02-21 16:04:19 +0800275 # Setup static file path
Peter Shih7cc81b12017-08-24 13:04:46 +0800276 self.goofy_server.RegisterPath('/', static_path)
Peter Shihce03c2e2017-03-21 17:36:10 +0800277 # index.html needs to be preprocessed.
Peter Shih7cc81b12017-08-24 13:04:46 +0800278 index_path = os.path.join(static_path, 'index.html')
Peter Shihce03c2e2017-03-21 17:36:10 +0800279 index_html = html_translator.TranslateHTML(file_utils.ReadFile(index_path))
280 self.goofy_server.RegisterData('/index.html', 'text/html', index_html)
Earl Ouacbe99c2017-02-21 16:04:19 +0800281
Peter Shih7cc81b12017-08-24 13:04:46 +0800282 default_test_ui_path = os.path.join(static_path,
283 'ui_templates/default_test_ui.html')
284 self._default_test_ui_html = html_translator.TranslateHTML(
285 file_utils.ReadFile(default_test_ui_path))
286
Earl Ouacbe99c2017-02-21 16:04:19 +0800287 def init_state_instance(self):
Jon Salz2af235d2013-06-24 14:47:21 +0800288 # Before starting state server, remount stateful partitions with
289 # no commit flag. The default commit time (commit=600) makes corruption
290 # too likely.
Hung-Te Lin1968d9c2016-01-08 22:55:46 +0800291 sys_utils.ResetCommitTime()
Earl Ouacbe99c2017-02-21 16:04:19 +0800292 self.state_instance = state.FactoryState()
293 self.goofy_server.AddRPCInstance(goofy_proxy.STATE_URL, self.state_instance)
Jon Salz2af235d2013-06-24 14:47:21 +0800294
Earl Ouacbe99c2017-02-21 16:04:19 +0800295 # Setup Goofy RPC.
296 # TODO(shunhsingou): separate goofy_rpc and state server instead of
297 # injecting goofy_rpc functions into state.
Jon Salz16d10542012-07-23 12:18:45 +0800298 self.goofy_rpc = GoofyRPC(self)
299 self.goofy_rpc.RegisterMethods(self.state_instance)
Jon Salz0697cbf2012-07-04 15:14:04 +0800300
Peter Shih80e78b42017-03-10 17:00:56 +0800301 def init_i18n(self):
302 js_data = 'var goofy_i18n_data = %s;' % translation.GetAllI18nDataJS()
Peter Shihce03c2e2017-03-21 17:36:10 +0800303 self.goofy_server.RegisterData('/js/goofy-translations.js',
304 'application/javascript', js_data)
Peter Shihf65db932017-03-22 17:06:34 +0800305 self.goofy_server.RegisterData('/css/i18n.css',
306 'text/css', i18n_test_ui.GetStyleSheet())
Peter Shih80e78b42017-03-10 17:00:56 +0800307
Jon Salz0697cbf2012-07-04 15:14:04 +0800308 def start_event_server(self):
309 self.event_server = EventServer()
310 logging.info('Starting factory event server')
311 self.event_server_thread = threading.Thread(
Ricky Liang45c73e72015-01-15 15:00:30 +0800312 target=self.event_server.serve_forever,
Peter Shihfdf17682017-05-26 11:38:39 +0800313 name='EventServer')
Jon Salz0697cbf2012-07-04 15:14:04 +0800314 self.event_server_thread.start()
315
Shen-En Shihd7359cc2017-10-03 16:01:47 +0800316 self.event_client = ThreadingEventClient(
Shen-En Shihba564cb2017-10-05 11:54:16 +0800317 callback=lambda event: self.run_queue.put(
318 lambda: self.handle_event(event)))
Jon Salz0697cbf2012-07-04 15:14:04 +0800319
320 self.web_socket_manager = WebSocketManager(self.uuid)
Earl Ouacbe99c2017-02-21 16:04:19 +0800321 self.goofy_server.AddHTTPGetHandler(
322 '/event', self.web_socket_manager.handle_web_socket)
Jon Salz0697cbf2012-07-04 15:14:04 +0800323
Ricky Liang48e47f92014-02-26 19:31:51 +0800324 def shutdown(self, operation):
325 """Starts shutdown procedure.
326
327 Args:
Vic (Chun-Ju) Yang05b0d952014-04-28 17:39:09 +0800328 operation: The shutdown operation (reboot, full_reboot, or halt).
Ricky Liang48e47f92014-02-26 19:31:51 +0800329 """
330 active_tests = []
Wei-Han Chen3ae204c2017-04-28 19:36:55 +0800331 for test in self.test_list.Walk():
332 if not test.IsLeaf():
Ricky Liang48e47f92014-02-26 19:31:51 +0800333 continue
334
Wei-Han Chen3ae204c2017-04-28 19:36:55 +0800335 test_state = test.GetState()
Ricky Liang48e47f92014-02-26 19:31:51 +0800336 if test_state.status == TestState.ACTIVE:
337 active_tests.append(test)
338
Ricky Liang48e47f92014-02-26 19:31:51 +0800339 if not (len(active_tests) == 1 and
Wei-Han Chen03113912017-09-29 15:58:25 +0800340 isinstance(active_tests[0], test_object.ShutdownStep)):
Ricky Liang48e47f92014-02-26 19:31:51 +0800341 logging.error(
342 'Calling Goofy shutdown outside of the shutdown factory test')
343 return
344
345 logging.info('Start Goofy shutdown (%s)', operation)
346 # Save pending test list in the state server
347 self.state_instance.set_shared_data(
Wei-Han Chenc17b4112016-11-22 14:56:51 +0800348 TESTS_AFTER_SHUTDOWN, self.test_list_iterator)
Ricky Liang48e47f92014-02-26 19:31:51 +0800349 # Save shutdown time
350 self.state_instance.set_shared_data('shutdown_time', time.time())
351
352 with self.env.lock:
353 self.event_log.Log('shutdown', operation=operation)
354 shutdown_result = self.env.shutdown(operation)
355 if shutdown_result:
356 # That's all, folks!
Peter Ammon1e1ec572014-06-26 17:56:32 -0700357 self.run_enqueue(None)
Ricky Liang48e47f92014-02-26 19:31:51 +0800358 else:
359 # Just pass (e.g., in the chroot).
Wei-Han Chenc17b4112016-11-22 14:56:51 +0800360 self.state_instance.set_shared_data(TESTS_AFTER_SHUTDOWN, None)
Ricky Liang48e47f92014-02-26 19:31:51 +0800361 # Send event with no fields to indicate that there is no
362 # longer a pending shutdown.
363 self.event_client.post_event(Event(Event.Type.PENDING_SHUTDOWN))
364
365 def handle_shutdown_complete(self, test):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800366 """Handles the case where a shutdown was detected during a shutdown step.
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800367
Ricky Liang6fe218c2013-12-27 15:17:17 +0800368 Args:
369 test: The ShutdownStep.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800370 """
Wei-Han Chen3ae204c2017-04-28 19:36:55 +0800371 test_state = test.UpdateState(increment_shutdown_count=1)
Jon Salz0697cbf2012-07-04 15:14:04 +0800372 logging.info('Detected shutdown (%d of %d)',
Ricky Liang48e47f92014-02-26 19:31:51 +0800373 test_state.shutdown_count, test.iterations)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800374
Ricky Liang48e47f92014-02-26 19:31:51 +0800375 tests_after_shutdown = self.state_instance.get_shared_data(
Wei-Han Chenc17b4112016-11-22 14:56:51 +0800376 TESTS_AFTER_SHUTDOWN, optional=True)
377
378 # Make this shutdown test the next test to run. This is to continue on
379 # post-shutdown verification in the shutdown step.
Ricky Liang48e47f92014-02-26 19:31:51 +0800380 if not tests_after_shutdown:
Wei-Han Chen29663c12017-06-27 10:28:54 +0800381 goofy_error = 'TESTS_AFTER_SHTUDOWN is not set'
Ricky Liang48e47f92014-02-26 19:31:51 +0800382 self.state_instance.set_shared_data(
Wei-Han Chenc17b4112016-11-22 14:56:51 +0800383 TESTS_AFTER_SHUTDOWN, TestListIterator(test))
384 else:
Wei-Han Chen29663c12017-06-27 10:28:54 +0800385 goofy_error = tests_after_shutdown.RestartLastTest()
Wei-Han Chenc17b4112016-11-22 14:56:51 +0800386 self.state_instance.set_shared_data(
387 TESTS_AFTER_SHUTDOWN, tests_after_shutdown)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800388
Ricky Liang48e47f92014-02-26 19:31:51 +0800389 # Set 'post_shutdown' to inform shutdown test that a shutdown just occurred.
Ricky Liangb7eb8772014-09-15 18:05:22 +0800390 self.state_instance.set_shared_data(
Wei-Han Chen29663c12017-06-27 10:28:54 +0800391 state.KEY_POST_SHUTDOWN % test.path,
392 {'invocation': self.state_instance.get_test_state(test.path).invocation,
393 'goofy_error': goofy_error})
Jon Salz258a40c2012-04-19 12:34:01 +0800394
Jon Salz0697cbf2012-07-04 15:14:04 +0800395 def init_states(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800396 """Initializes all states on startup."""
Wei-Han Chen3ae204c2017-04-28 19:36:55 +0800397 for test in self.test_list.GetAllTests():
Jon Salz0697cbf2012-07-04 15:14:04 +0800398 # Make sure the state server knows about all the tests,
399 # defaulting to an untested state.
Peter Shih6e578272017-09-12 17:41:43 +0800400 test.UpdateState(update_parent=False)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800401
Earl Ouf76e55c2017-03-07 11:48:34 +0800402 is_unexpected_shutdown = False
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800403
Jon Salz0697cbf2012-07-04 15:14:04 +0800404 # Any 'active' tests should be marked as failed now.
Wei-Han Chen3ae204c2017-04-28 19:36:55 +0800405 for test in self.test_list.Walk():
406 if not test.IsLeaf():
Jon Salza6711d72012-07-18 14:33:03 +0800407 # Don't bother with parents; they will be updated when their
408 # children are updated.
409 continue
410
Wei-Han Chen3ae204c2017-04-28 19:36:55 +0800411 test_state = test.GetState()
Jon Salz0697cbf2012-07-04 15:14:04 +0800412 if test_state.status != TestState.ACTIVE:
413 continue
Wei-Han Chen03113912017-09-29 15:58:25 +0800414 if isinstance(test, test_object.ShutdownStep):
Jon Salz0697cbf2012-07-04 15:14:04 +0800415 # Shutdown while the test was active - that's good.
Ricky Liang48e47f92014-02-26 19:31:51 +0800416 self.handle_shutdown_complete(test)
Jon Salz0697cbf2012-07-04 15:14:04 +0800417 else:
Earl Ouf76e55c2017-03-07 11:48:34 +0800418 is_unexpected_shutdown = True
Jon Salz0697cbf2012-07-04 15:14:04 +0800419 error_msg = 'Unexpected shutdown while test was running'
Chun-Ta Lin53cbbd52016-06-08 21:42:19 +0800420 # TODO(itspeter): Add testlog to collect expired session infos.
Jon Salz0697cbf2012-07-04 15:14:04 +0800421 self.event_log.Log('end_test',
Ricky Liang45c73e72015-01-15 15:00:30 +0800422 path=test.path,
423 status=TestState.FAILED,
Wei-Han Chen3ae204c2017-04-28 19:36:55 +0800424 invocation=test.GetState().invocation,
Earl Ouf76e55c2017-03-07 11:48:34 +0800425 error_msg=error_msg)
Wei-Han Chen3ae204c2017-04-28 19:36:55 +0800426 test.UpdateState(
Ricky Liang45c73e72015-01-15 15:00:30 +0800427 status=TestState.FAILED,
428 error_msg=error_msg)
Chun-Ta Lin87c2dac2015-05-02 01:35:01 -0700429 # Trigger the OnTestFailure callback.
Claire Changd1961a22015-08-05 16:15:55 +0800430 self.run_queue.put(lambda: self.test_fail(test))
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800431
Jon Salz50efe942012-07-26 11:54:10 +0800432 if not test.never_fails:
433 # For "never_fails" tests (such as "Start"), don't cancel
434 # pending tests, since reboot is expected.
435 factory.console.info('Unexpected shutdown while test %s '
436 'running; cancelling any pending tests',
437 test.path)
Wei-Han Chenc17b4112016-11-22 14:56:51 +0800438 # cancel pending tests by replace the iterator with an empty one
439 self.state_instance.set_shared_data(
440 TESTS_AFTER_SHUTDOWN,
441 TestListIterator(None))
Jon Salz008f4ea2012-08-28 05:39:45 +0800442
Earl Ouf76e55c2017-03-07 11:48:34 +0800443 if is_unexpected_shutdown:
444 logging.warning("Unexpected shutdown.")
Hung-Te Lin793d6572017-09-04 18:17:56 +0800445 self.hooks.OnUnexpectedReboot()
Earl Ouf76e55c2017-03-07 11:48:34 +0800446
Wei-Han Chen109d76f2017-08-08 18:50:35 +0800447 if self.test_list.options.read_device_data_from_vpd_on_init:
448 vpd_data = {}
449 for section in [device_data.NAME_RO, device_data.NAME_RW]:
450 try:
451 vpd_data[section] = self.dut.vpd.boot.GetPartition(section).GetAll()
452 except Exception:
453 logging.exception('Failed to read %s_VPD, ignored...',
454 section.upper())
455 # using None for key_map will use default key_map
456 device_data.UpdateDeviceDataFromVPD(None, vpd_data)
457
Wei-Han Chen212d2af2017-08-03 18:12:23 +0800458 # state_instance is initialized, we can mark skipped and waived tests now.
459 self.test_list.SetSkippedAndWaivedTests()
460
Jon Salz0697cbf2012-07-04 15:14:04 +0800461 def handle_event(self, event):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800462 """Handles an event from the event server."""
Jon Salz0697cbf2012-07-04 15:14:04 +0800463 handler = self.event_handlers.get(event.type)
464 if handler:
465 handler(event)
466 else:
467 # We don't register handlers for all event types - just ignore
468 # this event.
469 logging.debug('Unbound event type %s', event.type)
Jon Salz4f6c7172012-06-11 20:45:36 +0800470
Vic Yangaabf9fd2013-04-09 18:56:13 +0800471 def check_critical_factory_note(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800472 """Returns True if the last factory note is critical."""
Vic Yangaabf9fd2013-04-09 18:56:13 +0800473 notes = self.state_instance.get_shared_data('factory_note', True)
474 return notes and notes[-1]['level'] == 'CRITICAL'
475
Hung-Te Linef7f2be2015-07-20 20:38:51 +0800476 def schedule_restart(self):
477 """Schedules a restart event when any invocation is completed."""
478 self.is_restart_requested = True
479
480 def invocation_completion(self):
481 """Callback when an invocation is completed."""
482 if self.is_restart_requested:
483 logging.info('Restart by scheduled event.')
484 self.is_restart_requested = False
485 self.restart_tests()
486 else:
487 self.run_next_test()
488
Jon Salz0697cbf2012-07-04 15:14:04 +0800489 def run_next_test(self):
Wei-Han Chenc17b4112016-11-22 14:56:51 +0800490 """Runs the next eligible test.
henryhsu4cc6b022014-04-22 17:12:42 +0800491
Wei-Han Chenc17b4112016-11-22 14:56:51 +0800492 self.test_list_iterator (a TestListIterator object) will determine which
493 test should be run.
henryhsu4cc6b022014-04-22 17:12:42 +0800494 """
Jon Salz0697cbf2012-07-04 15:14:04 +0800495 self.reap_completed_tests()
Wei-Han Chenc17b4112016-11-22 14:56:51 +0800496
497 if self.invocations:
498 # there are tests still running, we cannot start new tests
Vic Yangaabf9fd2013-04-09 18:56:13 +0800499 return
Jon Salz94eb56f2012-06-12 18:01:12 +0800500
Wei-Han Chenc17b4112016-11-22 14:56:51 +0800501 if self.check_critical_factory_note():
502 logging.info('has critical factory note, stop running')
Wei-Han Chenbcac7252017-04-21 19:46:51 +0800503 self.test_list_iterator.Stop()
Wei-Han Chenc17b4112016-11-22 14:56:51 +0800504 return
Jon Salz94eb56f2012-06-12 18:01:12 +0800505
Wei-Han Chenc17b4112016-11-22 14:56:51 +0800506 while True:
507 try:
508 path = self.test_list_iterator.next()
Wei-Han Chen3ae204c2017-04-28 19:36:55 +0800509 test = self.test_list.LookupPath(path)
Wei-Han Chenc17b4112016-11-22 14:56:51 +0800510 except StopIteration:
511 logging.info('no next test, stop running')
Jon Salz0697cbf2012-07-04 15:14:04 +0800512 return
Jon Salz94eb56f2012-06-12 18:01:12 +0800513
Wei-Han Chenc17b4112016-11-22 14:56:51 +0800514 # check if we have run all required tests
Jon Salz304a75d2012-07-06 11:14:15 +0800515 untested = set()
Jon Salza1412922012-07-23 16:04:17 +0800516 for requirement in test.require_run:
Wei-Han Chen3ae204c2017-04-28 19:36:55 +0800517 for i in requirement.test.Walk():
Jon Salza1412922012-07-23 16:04:17 +0800518 if i == test:
Jon Salz304a75d2012-07-06 11:14:15 +0800519 # We've hit this test itself; stop checking
520 break
Wei-Han Chen3ae204c2017-04-28 19:36:55 +0800521 if ((i.GetState().status == TestState.UNTESTED) or
Wei-Han Chen3a160172017-07-11 17:31:28 +0800522 (requirement.passed and
523 i.GetState().status not in [TestState.SKIPPED,
524 TestState.PASSED])):
Jon Salz304a75d2012-07-06 11:14:15 +0800525 # Found an untested test; move on to the next
526 # element in require_run.
Jon Salza1412922012-07-23 16:04:17 +0800527 untested.add(i)
Jon Salz304a75d2012-07-06 11:14:15 +0800528 break
529
530 if untested:
531 untested_paths = ', '.join(sorted([x.path for x in untested]))
532 if self.state_instance.get_shared_data('engineering_mode',
533 optional=True):
534 # In engineering mode, we'll let it go.
535 factory.console.warn('In engineering mode; running '
536 '%s even though required tests '
537 '[%s] have not completed',
538 test.path, untested_paths)
539 else:
540 # Not in engineering mode; mark it failed.
541 error_msg = ('Required tests [%s] have not been run yet'
542 % untested_paths)
543 factory.console.error('Not running %s: %s',
544 test.path, error_msg)
Wei-Han Chen3ae204c2017-04-28 19:36:55 +0800545 test.UpdateState(status=TestState.FAILED,
546 error_msg=error_msg)
Jon Salz304a75d2012-07-06 11:14:15 +0800547 continue
548
Wei-Han Chenc17b4112016-11-22 14:56:51 +0800549 # okay, let's run the test
Wei-Han Chen03113912017-09-29 15:58:25 +0800550 if (isinstance(test, test_object.ShutdownStep) and
Ricky Liangb7eb8772014-09-15 18:05:22 +0800551 self.state_instance.get_shared_data(
Wei-Han Chen29663c12017-06-27 10:28:54 +0800552 state.KEY_POST_SHUTDOWN % test.path, optional=True)):
Ricky Liang48e47f92014-02-26 19:31:51 +0800553 # Invoking post shutdown method of shutdown test. We should retain the
554 # iterations_left and retries_left of the original test state.
555 test_state = self.state_instance.get_test_state(test.path)
556 self._run_test(test, test_state.iterations_left,
557 test_state.retries_left)
558 else:
559 # Starts a new test run; reset iterations and retries.
560 self._run_test(test, test.iterations, test.retries)
Wei-Han Chenc17b4112016-11-22 14:56:51 +0800561 return # to leave while
Jon Salz1acc8742012-07-17 17:45:55 +0800562
Peter Shih13d2ced2017-09-25 16:25:09 +0800563 def _run_test(self, test, iterations_left=None, retries_left=None,
564 set_layout=True):
Wei-Han Chenc17b4112016-11-22 14:56:51 +0800565 """Invokes the test.
566
567 The argument `test` should be either a leaf test (no subtests) or a parallel
568 test (all subtests should be run in parallel).
569 """
Wei-Han Chen3ae204c2017-04-28 19:36:55 +0800570 if not self._ui_initialized and not test.IsNoHost():
Vic Yanga3cecf82014-12-26 00:44:21 -0800571 self.init_ui()
Jon Salz1acc8742012-07-17 17:45:55 +0800572
Peter Shih13d2ced2017-09-25 16:25:09 +0800573 if set_layout:
574 self.event_client.post_event(
575 Event(
576 Event.Type.SET_TEST_UI_LAYOUT,
577 layout_type=test.layout_type,
578 layout_options=test.layout_options))
579
Wei-Han Chen3ae204c2017-04-28 19:36:55 +0800580 if test.IsLeaf():
Wei-Han Chenc17b4112016-11-22 14:56:51 +0800581 invoc = TestInvocation(
582 self, test, on_completion=self.invocation_completion,
583 on_test_failure=lambda: self.test_fail(test))
Wei-Han Chen3ae204c2017-04-28 19:36:55 +0800584 new_state = test.UpdateState(
Wei-Han Chenc17b4112016-11-22 14:56:51 +0800585 status=TestState.ACTIVE, increment_count=1, error_msg='',
586 invocation=invoc.uuid, iterations_left=iterations_left,
Peter Shihf5c048d2017-09-01 17:57:51 +0800587 retries_left=retries_left)
Wei-Han Chenc17b4112016-11-22 14:56:51 +0800588 invoc.count = new_state.count
589 self.invocations[test] = invoc
Peter Shihb2ecd552017-08-24 17:48:58 +0800590 # Send a INIT_TEST_UI event here, so the test UI are initialized in
591 # order, and the tab order would be same as test list order when there
592 # are parallel tests with UI.
593 self.event_client.post_event(
594 Event(
595 Event.Type.INIT_TEST_UI,
596 html=self._default_test_ui_html,
597 test=test.path,
598 invocation=invoc.uuid))
Wei-Han Chenc17b4112016-11-22 14:56:51 +0800599 self.check_plugins()
600 invoc.start()
Wei-Han Chendc3e3ba2017-07-05 16:49:09 +0800601 elif test.parallel:
Wei-Han Chenc17b4112016-11-22 14:56:51 +0800602 for subtest in test.subtests:
603 # TODO(stimim): what if the subtests *must* be run in parallel?
604 # for example, stressapptest and countdown test.
605
606 # Make sure we don't need to skip it:
Wei-Han Chenbcac7252017-04-21 19:46:51 +0800607 if not self.test_list_iterator.CheckSkip(subtest):
Peter Shih13d2ced2017-09-25 16:25:09 +0800608 self._run_test(subtest, subtest.iterations, subtest.retries,
609 set_layout=False)
Wei-Han Chendc3e3ba2017-07-05 16:49:09 +0800610 else:
611 # This should never happen, there must be something wrong.
612 # However, we can't raise an exception, otherwise goofy will be closed
613 logging.critical(
614 'Goofy should not get a non-leaf test that is not parallel: %r',
615 test)
616 factory.console.critical(
617 'Goofy should not get a non-leaf test that is not parallel: %r',
618 test)
Jon Salz5f2a0672012-05-22 17:14:06 +0800619
Earl Oua3bca122016-10-21 16:00:30 +0800620 def check_plugins(self):
621 """Check plugins to be paused or resumed."""
622 exclusive_resources = set()
623 for test in self.invocations:
624 exclusive_resources = exclusive_resources.union(
Wei-Han Chen3ae204c2017-04-28 19:36:55 +0800625 test.GetExclusiveResources())
Earl Oua3bca122016-10-21 16:00:30 +0800626 self.plugin_controller.PauseAndResumePluginByResource(exclusive_resources)
627
cychiang21886742012-07-05 15:16:32 +0800628 def check_for_updates(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800629 """Schedules an asynchronous check for updates if necessary."""
cychiang21886742012-07-05 15:16:32 +0800630 if not self.test_list.options.update_period_secs:
631 # Not enabled.
632 return
633
634 now = time.time()
635 if self.last_update_check and (
636 now - self.last_update_check <
637 self.test_list.options.update_period_secs):
638 # Not yet time for another check.
639 return
640
641 self.last_update_check = now
642
You-Cheng Syud4a24bf2017-08-21 17:56:48 +0800643 def handle_check_for_update(
Hung-Te Lind151bf32017-08-30 11:05:47 +0800644 reached_server, toolkit_version, needs_update):
645 if reached_server:
You-Cheng Syud4a24bf2017-08-21 17:56:48 +0800646 new_update_toolkit_version = toolkit_version if needs_update else None
647 if self.dut.info.update_toolkit_version != new_update_toolkit_version:
648 logging.info('Received new update TOOLKIT_VERSION: %s',
649 new_update_toolkit_version)
650 self.dut.info.Overrides('update_toolkit_version',
651 new_update_toolkit_version)
Peter Ammon1e1ec572014-06-26 17:56:32 -0700652 self.run_enqueue(self.update_system_info)
You-Cheng Syud4a24bf2017-08-21 17:56:48 +0800653 elif not self._suppress_periodic_update_messages:
654 logging.warning('Suppress error messages for periodic update checking '
655 'after the first one.')
656 self._suppress_periodic_update_messages = True
cychiang21886742012-07-05 15:16:32 +0800657
658 updater.CheckForUpdateAsync(
Hung-Te Lind151bf32017-08-30 11:05:47 +0800659 handle_check_for_update, None, self._suppress_periodic_update_messages)
cychiang21886742012-07-05 15:16:32 +0800660
Jon Salza6711d72012-07-18 14:33:03 +0800661 def cancel_pending_tests(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800662 """Cancels any tests in the run queue."""
Wei-Han Chenc17b4112016-11-22 14:56:51 +0800663 self.run_tests(None)
Jon Salza6711d72012-07-18 14:33:03 +0800664
Ricky Liang4bff3e32014-02-20 18:46:11 +0800665 def restore_active_run_state(self):
666 """Restores active run id and the list of scheduled tests."""
667 self.run_id = self.state_instance.get_shared_data('run_id', optional=True)
668 self.scheduled_run_tests = self.state_instance.get_shared_data(
669 'scheduled_run_tests', optional=True)
670
671 def set_active_run_state(self):
672 """Sets active run id and the list of scheduled tests."""
673 self.run_id = str(uuid.uuid4())
Wei-Han Chenc17b4112016-11-22 14:56:51 +0800674 # try our best to predict which tests will be run.
Wei-Han Chenbcac7252017-04-21 19:46:51 +0800675 self.scheduled_run_tests = self.test_list_iterator.GetPendingTests()
Ricky Liang4bff3e32014-02-20 18:46:11 +0800676 self.state_instance.set_shared_data('run_id', self.run_id)
677 self.state_instance.set_shared_data('scheduled_run_tests',
678 self.scheduled_run_tests)
679
Wei-Han Chenc17b4112016-11-22 14:56:51 +0800680 def run_tests(self, subtree, status_filter=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800681 """Runs tests under subtree.
Jon Salz258a40c2012-04-19 12:34:01 +0800682
Wei-Han Chenc17b4112016-11-22 14:56:51 +0800683 Run tests under a given subtree.
Jon Salzb1b39092012-05-03 02:05:09 +0800684
Ricky Liang6fe218c2013-12-27 15:17:17 +0800685 Args:
Wei-Han Chenc17b4112016-11-22 14:56:51 +0800686 subtree: root of subtree to run or None to run nothing.
Chih-Yu Huang85dc63c2015-08-12 15:21:28 +0800687 status_filter: List of available test states. Only run the tests which
688 states are in the list. Set to None if all test states are available.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800689 """
Hung-Te Lin793d6572017-09-04 18:17:56 +0800690 self.hooks.OnTestStart()
Wei-Han Chenc17b4112016-11-22 14:56:51 +0800691 self.test_list_iterator = TestListIterator(
692 subtree, status_filter, self.test_list)
693 if subtree is not None:
Ricky Liang4bff3e32014-02-20 18:46:11 +0800694 self.set_active_run_state()
Jon Salz0697cbf2012-07-04 15:14:04 +0800695 self.run_next_test()
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800696
Jon Salz0697cbf2012-07-04 15:14:04 +0800697 def reap_completed_tests(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800698 """Removes completed tests from the set of active tests.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800699 """
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +0800700 test_completed = False
Jon Salz0697cbf2012-07-04 15:14:04 +0800701 for t, v in dict(self.invocations).iteritems():
702 if v.is_completed():
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +0800703 test_completed = True
Wei-Han Chen3ae204c2017-04-28 19:36:55 +0800704 new_state = t.UpdateState(**v.update_state_on_completion)
Jon Salz0697cbf2012-07-04 15:14:04 +0800705 del self.invocations[t]
706
Johny Lin62ed2a32015-05-13 11:57:12 +0800707 # Stop on failure if flag is true and there is no retry chances.
Chun-Ta Lin54e17e42012-09-06 22:05:13 +0800708 if (self.test_list.options.stop_on_failure and
Johny Lin62ed2a32015-05-13 11:57:12 +0800709 new_state.retries_left < 0 and
Chun-Ta Lin54e17e42012-09-06 22:05:13 +0800710 new_state.status == TestState.FAILED):
711 # Clean all the tests to cause goofy to stop.
Ricky Liang45c73e72015-01-15 15:00:30 +0800712 factory.console.info('Stop on failure triggered. Empty the queue.')
Wei-Han Chenc17b4112016-11-22 14:56:51 +0800713 self.cancel_pending_tests()
Chun-Ta Lin54e17e42012-09-06 22:05:13 +0800714
Jon Salz1acc8742012-07-17 17:45:55 +0800715 if new_state.iterations_left and new_state.status == TestState.PASSED:
716 # Play it again, Sam!
717 self._run_test(t)
Cheng-Yi Chiangce05c002013-04-04 02:13:17 +0800718 # new_state.retries_left is obtained after update.
719 # For retries_left == 0, test can still be run for the last time.
720 elif (new_state.retries_left >= 0 and
721 new_state.status == TestState.FAILED):
722 # Still have to retry, Sam!
723 self._run_test(t)
Jon Salz1acc8742012-07-17 17:45:55 +0800724
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +0800725 if test_completed:
Vic Yangf01c59f2013-04-19 17:37:56 +0800726 self.log_watcher.KickWatchThread()
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +0800727
Jon Salz6dc031d2013-06-19 13:06:23 +0800728 def kill_active_tests(self, abort, root=None, reason=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800729 """Kills and waits for all active tests.
Jon Salz0697cbf2012-07-04 15:14:04 +0800730
Jon Salz85a39882012-07-05 16:45:04 +0800731 Args:
732 abort: True to change state of killed tests to FAILED, False for
Jon Salz0697cbf2012-07-04 15:14:04 +0800733 UNTESTED.
Jon Salz85a39882012-07-05 16:45:04 +0800734 root: If set, only kills tests with root as an ancestor.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800735 reason: If set, the abort reason.
736 """
Jon Salz0697cbf2012-07-04 15:14:04 +0800737 self.reap_completed_tests()
Wei-Han Chenc17b4112016-11-22 14:56:51 +0800738 # since we remove objects while iterating, make a copy
739 for test, invoc in dict(self.invocations).iteritems():
Wei-Han Chen3ae204c2017-04-28 19:36:55 +0800740 if root and not test.HasAncestor(root):
Jon Salz85a39882012-07-05 16:45:04 +0800741 continue
742
Ricky Liang45c73e72015-01-15 15:00:30 +0800743 factory.console.info('Killing active test %s...', test.path)
Jon Salz6dc031d2013-06-19 13:06:23 +0800744 invoc.abort_and_join(reason)
Ricky Liang45c73e72015-01-15 15:00:30 +0800745 factory.console.info('Killed %s', test.path)
Wei-Han Chen3ae204c2017-04-28 19:36:55 +0800746 test.UpdateState(**invoc.update_state_on_completion)
Jon Salz0697cbf2012-07-04 15:14:04 +0800747 del self.invocations[test]
Jon Salz1acc8742012-07-17 17:45:55 +0800748
Jon Salz0697cbf2012-07-04 15:14:04 +0800749 if not abort:
Wei-Han Chen3ae204c2017-04-28 19:36:55 +0800750 test.UpdateState(status=TestState.UNTESTED)
Jon Salz0697cbf2012-07-04 15:14:04 +0800751 self.reap_completed_tests()
752
Jon Salz6dc031d2013-06-19 13:06:23 +0800753 def stop(self, root=None, fail=False, reason=None):
754 self.kill_active_tests(fail, root, reason)
Wei-Han Chenc17b4112016-11-22 14:56:51 +0800755
Wei-Han Chenbcac7252017-04-21 19:46:51 +0800756 self.test_list_iterator.Stop(root)
Jon Salz85a39882012-07-05 16:45:04 +0800757 self.run_next_test()
Jon Salz0697cbf2012-07-04 15:14:04 +0800758
Jon Salz4712ac72013-02-07 17:12:05 +0800759 def clear_state(self, root=None):
Jon Salzd7550792013-07-12 05:49:27 +0800760 if root is None:
761 root = self.test_list
Jon Salz6dc031d2013-06-19 13:06:23 +0800762 self.stop(root, reason='Clearing test state')
Wei-Han Chen3ae204c2017-04-28 19:36:55 +0800763 for f in root.Walk():
764 if f.IsLeaf():
765 f.UpdateState(status=TestState.UNTESTED)
Jon Salz4712ac72013-02-07 17:12:05 +0800766
Jon Salz6dc031d2013-06-19 13:06:23 +0800767 def abort_active_tests(self, reason=None):
768 self.kill_active_tests(True, reason=reason)
Jon Salz0697cbf2012-07-04 15:14:04 +0800769
770 def main(self):
Jon Salzeff94182013-06-19 15:06:28 +0800771 syslog.openlog('goofy')
772
Jon Salz0697cbf2012-07-04 15:14:04 +0800773 try:
Jon Salzd7550792013-07-12 05:49:27 +0800774 self.status = Status.INITIALIZING
Jon Salz0697cbf2012-07-04 15:14:04 +0800775 self.init()
776 self.event_log.Log('goofy_init',
Ricky Liang45c73e72015-01-15 15:00:30 +0800777 success=True)
Chun-Ta Lin53cbbd52016-06-08 21:42:19 +0800778 testlog.Log(
Joel Kitching9eb203a2016-04-21 15:36:30 +0800779 testlog.StationInit({
Hung-Te Linda8eb992017-09-28 03:27:12 +0800780 'stationDeviceId': session.GetDeviceID(),
781 'stationInstallationId': session.GetInstallationID(),
782 'count': session.GetInitCount(),
Joel Kitching9eb203a2016-04-21 15:36:30 +0800783 'success': True}))
Hung-Te Linc8174b52017-06-02 11:11:45 +0800784 except Exception:
Joel Kitching9eb203a2016-04-21 15:36:30 +0800785 try:
786 if self.event_log:
Jon Salz0697cbf2012-07-04 15:14:04 +0800787 self.event_log.Log('goofy_init',
Ricky Liang45c73e72015-01-15 15:00:30 +0800788 success=False,
789 trace=traceback.format_exc())
Chun-Ta Lin53cbbd52016-06-08 21:42:19 +0800790 if self.testlog:
791 testlog.Log(
Joel Kitching9eb203a2016-04-21 15:36:30 +0800792 testlog.StationInit({
Hung-Te Linda8eb992017-09-28 03:27:12 +0800793 'stationDeviceId': session.GetDeviceID(),
794 'stationInstallationId': session.GetInstallationID(),
795 'count': session.GetInitCount(),
Joel Kitching9eb203a2016-04-21 15:36:30 +0800796 'success': False,
797 'failureMessage': traceback.format_exc()}))
Hung-Te Linc8174b52017-06-02 11:11:45 +0800798 except Exception:
Joel Kitching9eb203a2016-04-21 15:36:30 +0800799 pass
Jon Salz0697cbf2012-07-04 15:14:04 +0800800 raise
801
Jon Salzd7550792013-07-12 05:49:27 +0800802 self.status = Status.RUNNING
Jon Salzeff94182013-06-19 15:06:28 +0800803 syslog.syslog('Goofy (factory test harness) starting')
Chun-Ta Lin5d12b592015-06-30 00:54:23 -0700804 syslog.syslog('Boot sequence = %d' % GetBootSequence())
Hung-Te Linda8eb992017-09-28 03:27:12 +0800805 syslog.syslog('Goofy init count = %d' % session.GetInitCount())
Jon Salz0697cbf2012-07-04 15:14:04 +0800806 self.run()
807
808 def update_system_info(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800809 """Updates system info."""
Shen-En Shihce8ffe02017-08-01 18:58:09 +0800810 logging.info('Received a notify to update system info.')
811 self.dut.info.Invalidate()
812
813 # Propagate this notify to goofy components
814 try:
815 status_monitor = plugin_controller.GetPluginRPCProxy(
816 'status_monitor.status_monitor')
817 status_monitor.UpdateDeviceInfo()
818 except Exception:
819 logging.debug('Failed to update status monitor plugin.')
Jon Salz0697cbf2012-07-04 15:14:04 +0800820
Jon Salzeb42f0d2012-07-27 19:14:04 +0800821 def update_factory(self, auto_run_on_restart=False, post_update_hook=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800822 """Commences updating factory software.
Jon Salzeb42f0d2012-07-27 19:14:04 +0800823
824 Args:
825 auto_run_on_restart: Auto-run when the machine comes back up.
826 post_update_hook: Code to call after update but immediately before
827 restart.
828
829 Returns:
830 Never if the update was successful (we just reboot).
831 False if the update was unnecessary (no update available).
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800832 """
Jon Salz6dc031d2013-06-19 13:06:23 +0800833 self.kill_active_tests(False, reason='Factory software update')
Jon Salza6711d72012-07-18 14:33:03 +0800834 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +0800835
Jon Salz5c344f62012-07-13 14:31:16 +0800836 def pre_update_hook():
837 if auto_run_on_restart:
Wei-Han Chenc17b4112016-11-22 14:56:51 +0800838 self.state_instance.set_shared_data(TESTS_AFTER_SHUTDOWN,
Jon Salz5c344f62012-07-13 14:31:16 +0800839 FORCE_AUTO_RUN)
840 self.state_instance.close()
841
Jon Salzeb42f0d2012-07-27 19:14:04 +0800842 if updater.TryUpdate(pre_update_hook=pre_update_hook):
843 if post_update_hook:
844 post_update_hook()
845 self.env.shutdown('reboot')
Jon Salz0697cbf2012-07-04 15:14:04 +0800846
chuntsen9d675c62017-06-20 14:35:30 +0800847 def handle_signal(self, signum, unused_frame):
848 names = [signame for signame in dir(signal) if signame.startswith('SIG') and
849 getattr(signal, signame) == signum]
850 signal_name = ', '.join(names) if names else 'UNKNOWN'
851 logging.error('Received signal %s(%d)', signal_name, signum)
Peter Ammon1e1ec572014-06-26 17:56:32 -0700852 self.run_enqueue(None)
Jon Salz77c151e2012-08-28 07:20:37 +0800853 raise KeyboardInterrupt()
854
Jon Salz128b0932013-07-03 16:55:26 +0800855 def GetTestList(self, test_list_id):
856 """Returns the test list with the given ID.
857
858 Raises:
859 TestListError: The test list ID is not valid.
860 """
861 try:
862 return self.test_lists[test_list_id]
863 except KeyError:
864 raise test_lists.TestListError(
Wei-Han Chendbc0fa22017-09-28 10:29:53 +0800865 '%r is not a valid test list ID (available IDs are %r)' % (
866 test_list_id, sorted(self.test_lists.keys())))
Jon Salz128b0932013-07-03 16:55:26 +0800867
Chih-Yu Huang1725d622017-03-24 16:08:35 +0800868 def _RecordStartError(self, error_message):
869 """Appends the startup error message into the shared data."""
870 KEY = 'startup_error'
871 data = self.state_instance.get_shared_data(KEY, optional=True)
872 new_data = '%s\n\n%s' % (data, error_message) if data else error_message
873 self.state_instance.set_shared_data(KEY, new_data)
874
Jon Salz128b0932013-07-03 16:55:26 +0800875 def InitTestLists(self):
Joel Kitching50a63ea2016-02-22 13:15:09 +0800876 """Reads in all test lists and sets the active test list.
877
878 Returns:
879 True if the active test list could be set, False if failed.
880 """
881 startup_errors = []
Wei-Han Chen16cc5dd2017-04-27 17:38:53 +0800882
883 self.test_lists, failed_files = self.test_list_manager.BuildAllTestLists()
884
Wei-Han Chendbc0fa22017-09-28 10:29:53 +0800885 logging.info('Loaded test lists: %r', sorted(self.test_lists.keys()))
Jon Salz128b0932013-07-03 16:55:26 +0800886
Joel Kitching50a63ea2016-02-22 13:15:09 +0800887 # Check for any syntax errors in test list files.
888 if failed_files:
889 logging.info('Failed test list files: [%s]',
890 ' '.join(failed_files.keys()))
891 for f, exc_info in failed_files.iteritems():
892 logging.error('Error in test list file: %s', f,
893 exc_info=exc_info)
894
895 # Limit the stack trace to the very last entry.
896 exc_type, exc_value, exc_traceback = exc_info
897 while exc_traceback and exc_traceback.tb_next:
898 exc_traceback = exc_traceback.tb_next
899
900 exc_string = ''.join(
901 traceback.format_exception(
902 exc_type, exc_value, exc_traceback)).rstrip()
903 startup_errors.append('Error in test list file (%s):\n%s'
904 % (f, exc_string))
905
Jon Salz128b0932013-07-03 16:55:26 +0800906 if not self.options.test_list:
Hung-Te Linab78fc42017-09-22 00:21:57 +0800907 self.options.test_list = self.test_list_manager.GetActiveTestListId()
Jon Salz128b0932013-07-03 16:55:26 +0800908
Joel Kitching50a63ea2016-02-22 13:15:09 +0800909 # Check for a non-existent test list ID.
910 try:
Wei-Han Chen84fee7c2016-08-26 21:56:25 +0800911 self.test_list = self.GetTestList(self.options.test_list)
Joel Kitching50a63ea2016-02-22 13:15:09 +0800912 logging.info('Active test list: %s', self.test_list.test_list_id)
913 except test_lists.TestListError as e:
914 logging.exception('Invalid active test list: %s',
915 self.options.test_list)
916 startup_errors.append(e.message)
Jon Salz128b0932013-07-03 16:55:26 +0800917
Joel Kitching50a63ea2016-02-22 13:15:09 +0800918 # We may have failed loading the active test list.
919 if self.test_list:
Joel Kitching50a63ea2016-02-22 13:15:09 +0800920 self.test_list.state_instance = self.state_instance
Jon Salz128b0932013-07-03 16:55:26 +0800921
Joel Kitching50a63ea2016-02-22 13:15:09 +0800922 # Show all startup errors.
923 if startup_errors:
Chih-Yu Huang1725d622017-03-24 16:08:35 +0800924 self._RecordStartError('\n\n'.join(startup_errors))
Joel Kitching50a63ea2016-02-22 13:15:09 +0800925
926 # Only return False if failed to load the active test list.
927 return bool(self.test_list)
Jon Salz128b0932013-07-03 16:55:26 +0800928
Shuo-Peng Liao268b40b2013-07-01 15:58:59 +0800929 def init_hooks(self):
930 """Initializes hooks.
931
932 Must run after self.test_list ready.
933 """
Shuo-Peng Liao52b90da2013-06-30 17:00:06 +0800934 module, cls = self.test_list.options.hooks_class.rsplit('.', 1)
935 self.hooks = getattr(__import__(module, fromlist=[cls]), cls)()
936 assert isinstance(self.hooks, factory.Hooks), (
Ricky Liang45c73e72015-01-15 15:00:30 +0800937 'hooks should be of type Hooks but is %r' % type(self.hooks))
Shuo-Peng Liao52b90da2013-06-30 17:00:06 +0800938 self.hooks.test_list = self.test_list
Shuo-Peng Liao268b40b2013-07-01 15:58:59 +0800939 self.hooks.OnCreatedTestList()
Shuo-Peng Liao52b90da2013-06-30 17:00:06 +0800940
Vic Yanga3cecf82014-12-26 00:44:21 -0800941 def init_ui(self):
942 """Initialize UI."""
Shen-En Shih65619f42017-10-02 16:52:10 +0800943 logging.info('Waiting for a web socket connection')
944 self.web_socket_manager.wait()
Vic Yanga3cecf82014-12-26 00:44:21 -0800945 self._ui_initialized = True
Vic Yanga3cecf82014-12-26 00:44:21 -0800946
Hung-Te Lin9d81ac72017-09-21 12:58:01 +0800947 @staticmethod
948 def GetCommandLineArgsParser():
949 """Returns a parser for Goofy command line arguments."""
Jon Salz0697cbf2012-07-04 15:14:04 +0800950 parser = OptionParser()
951 parser.add_option('-v', '--verbose', dest='verbose',
Jon Salz8fa8e832012-07-13 19:04:09 +0800952 action='store_true',
953 help='Enable debug logging')
Jon Salz0697cbf2012-07-04 15:14:04 +0800954 parser.add_option('--print_test_list', dest='print_test_list',
Wei-Han Chen84fee7c2016-08-26 21:56:25 +0800955 metavar='TEST_LIST_ID',
956 help='Print the content of TEST_LIST_ID and exit')
Jon Salz0697cbf2012-07-04 15:14:04 +0800957 parser.add_option('--restart', dest='restart',
Jon Salz8fa8e832012-07-13 19:04:09 +0800958 action='store_true',
959 help='Clear all test state')
Jon Salz0697cbf2012-07-04 15:14:04 +0800960 parser.add_option('--test_list', dest='test_list',
Wei-Han Chen84fee7c2016-08-26 21:56:25 +0800961 metavar='TEST_LIST_ID',
962 help='Use test list whose id is TEST_LIST_ID')
Ricky Liang6fe218c2013-12-27 15:17:17 +0800963 parser.add_option('--automation-mode',
964 choices=[m.lower() for m in AutomationMode],
Ricky Liang45c73e72015-01-15 15:00:30 +0800965 default='none', help='Factory test automation mode.')
Ricky Liang117484a2014-04-14 11:14:41 +0800966 parser.add_option('--no-auto-run-on-start', dest='auto_run_on_start',
967 action='store_false', default=True,
968 help=('do not automatically run the test list on goofy '
969 'start; this is only valid when factory test '
970 'automation is enabled'))
Hung-Te Lin9d81ac72017-09-21 12:58:01 +0800971 return parser
972
973 def init(self, args=None, env=None):
974 """Initializes Goofy.
975
976 Args:
Shen-En Shihe05cbbc2017-10-02 16:47:30 +0800977 args: A list of command-line arguments. Uses sys.argv if args is None.
978 env: An Environment instance to use (or None to use DUTEnvironment).
Hung-Te Lin9d81ac72017-09-21 12:58:01 +0800979 """
980 (self.options, self.args) = self.GetCommandLineArgsParser().parse_args(args)
Jon Salz0697cbf2012-07-04 15:14:04 +0800981
Joel Kitching261e0422017-03-30 16:52:01 -0700982 signal.signal(signal.SIGINT, self.handle_signal)
983 signal.signal(signal.SIGTERM, self.handle_signal)
Hung-Te Lina846f602014-07-04 20:32:22 +0800984 # TODO(hungte) SIGTERM does not work properly without Telemetry and should
985 # be fixed.
Hung-Te Lina846f602014-07-04 20:32:22 +0800986
Jon Salz46b89562012-07-05 11:49:22 +0800987 # Make sure factory directories exist.
Peter Shihb4e49352017-05-25 17:35:11 +0800988 for path in [
989 paths.DATA_LOG_DIR, paths.DATA_STATE_DIR, paths.DATA_TESTS_DIR]:
990 file_utils.TryMakeDirs(path)
Jon Salz46b89562012-07-05 11:49:22 +0800991
Wei-Han Chen78f35f62017-03-06 20:11:20 +0800992 try:
993 goofy_default_options = config_utils.LoadConfig(validate_schema=False)
994 for key, value in goofy_default_options.iteritems():
995 if getattr(self.options, key, None) is None:
996 logging.info('self.options.%s = %r', key, value)
997 setattr(self.options, key, value)
998 except Exception:
999 logging.exception('failed to load goofy overriding options')
1000
Jon Salz0f996602012-10-03 15:26:48 +08001001 if self.options.print_test_list:
Wei-Han Chen16cc5dd2017-04-27 17:38:53 +08001002 all_test_lists, unused_errors = self.test_list_manager.BuildAllTestLists()
1003 test_list = (
1004 all_test_lists[self.options.print_test_list].ToFactoryTestList())
Wei-Han Chen84fee7c2016-08-26 21:56:25 +08001005 print(test_list.__repr__(recursive=True))
Jon Salz0f996602012-10-03 15:26:48 +08001006 sys.exit(0)
1007
Jon Salzee85d522012-07-17 14:34:46 +08001008 event_log.IncrementBootSequence()
Hung-Te Linda8eb992017-09-28 03:27:12 +08001009 session.IncrementInitCount()
Chun-Ta Lin53cbbd52016-06-08 21:42:19 +08001010
Jon Salzd15bbcf2013-05-21 17:33:57 +08001011 # Don't defer logging the initial event, so we can make sure
1012 # that device_id, reimage_id, etc. are all set up.
1013 self.event_log = EventLog('goofy', defer=False)
Chun-Ta Lin53cbbd52016-06-08 21:42:19 +08001014 self.testlog = testlog.Testlog(
Peter Shihb4e49352017-05-25 17:35:11 +08001015 log_root=paths.DATA_LOG_DIR, uuid=self.uuid,
Hung-Te Linda8eb992017-09-28 03:27:12 +08001016 stationDeviceId=session.GetDeviceID(),
1017 stationInstallationId=session.GetInstallationID())
Jon Salz0697cbf2012-07-04 15:14:04 +08001018
Jon Salz0697cbf2012-07-04 15:14:04 +08001019 if env:
1020 self.env = env
Shen-En Shihe05cbbc2017-10-02 16:47:30 +08001021 else:
Ricky Liang09d66d82014-09-25 11:20:54 +08001022 self.env = test_environment.DUTEnvironment()
Jon Salz0697cbf2012-07-04 15:14:04 +08001023 self.env.goofy = self
1024
1025 if self.options.restart:
1026 state.clear_state()
1027
Jon Salz0697cbf2012-07-04 15:14:04 +08001028 logging.info('Started')
1029
Earl Ouacbe99c2017-02-21 16:04:19 +08001030 self.start_goofy_server()
1031 self.init_state_instance()
Peter Shih80e78b42017-03-10 17:00:56 +08001032 self.init_i18n()
Jon Salz0697cbf2012-07-04 15:14:04 +08001033 self.last_shutdown_time = (
Ricky Liang45c73e72015-01-15 15:00:30 +08001034 self.state_instance.get_shared_data('shutdown_time', optional=True))
Jon Salz0697cbf2012-07-04 15:14:04 +08001035 self.state_instance.del_shared_data('shutdown_time', optional=True)
Jon Salzb19ea072013-02-07 16:35:00 +08001036 self.state_instance.del_shared_data('startup_error', optional=True)
Jon Salz0697cbf2012-07-04 15:14:04 +08001037
Ricky Liang6fe218c2013-12-27 15:17:17 +08001038 self.options.automation_mode = ParseAutomationMode(
1039 self.options.automation_mode)
1040 self.state_instance.set_shared_data('automation_mode',
1041 self.options.automation_mode)
1042 self.state_instance.set_shared_data(
1043 'automation_mode_prompt',
1044 AutomationModePrompt[self.options.automation_mode])
1045
Joel Kitching50a63ea2016-02-22 13:15:09 +08001046 success = False
Jon Salz128b0932013-07-03 16:55:26 +08001047 try:
Joel Kitching50a63ea2016-02-22 13:15:09 +08001048 success = self.InitTestLists()
Hung-Te Linc8174b52017-06-02 11:11:45 +08001049 except Exception:
Shen-En Shih44107d12017-10-02 11:31:12 +08001050 logging.exception('Unable to initialize test lists')
1051 self._RecordStartError(
1052 'Unable to initialize test lists\n%s' % traceback.format_exc())
Joel Kitching50a63ea2016-02-22 13:15:09 +08001053
1054 if not success:
Shen-En Shih65619f42017-10-02 16:52:10 +08001055 # Create an empty test list with default options so that the rest of
1056 # startup can proceed.
1057 # A message box will pop up in UI for the error details.
Wei-Han Chen03113912017-09-29 15:58:25 +08001058 self.test_list = manager.LegacyTestList(test_object.FactoryTestList(
Shen-En Shih65619f42017-10-02 16:52:10 +08001059 [], self.state_instance, factory.Options()))
Jon Salzb19ea072013-02-07 16:35:00 +08001060
Shuo-Peng Liao268b40b2013-07-01 15:58:59 +08001061 self.init_hooks()
1062
Jon Salz822838b2013-03-25 17:32:33 +08001063 if self.test_list.options.clear_state_on_start:
1064 self.state_instance.clear_test_state()
1065
Jon Salz670ce062014-05-16 15:53:50 +08001066 # If the phase is invalid, this will raise a ValueError.
1067 phase.SetPersistentPhase(self.test_list.options.phase)
1068
Peter Shih3b0bb9f2017-03-21 16:23:32 +08001069 if not self.state_instance.has_shared_data('ui_locale'):
Hung-Te Lin134403c2017-08-23 17:30:17 +08001070 ui_locale = self.test_list.options.ui_locale
Peter Shih3b0bb9f2017-03-21 16:23:32 +08001071 self.state_instance.set_shared_data('ui_locale', ui_locale)
Jon Salz0697cbf2012-07-04 15:14:04 +08001072 self.state_instance.set_shared_data(
Ricky Liang45c73e72015-01-15 15:00:30 +08001073 'test_list_options',
Peter Shih90425db2017-08-02 15:53:48 +08001074 self.test_list.options.ToDict())
Jon Salz0697cbf2012-07-04 15:14:04 +08001075 self.state_instance.test_list = self.test_list
1076
1077 self.init_states()
1078 self.start_event_server()
Hung-Te Lincc41d2a2014-10-29 13:35:20 +08001079
Earl Oua3bca122016-10-21 16:00:30 +08001080 # Load and run Goofy plugins.
1081 self.plugin_controller = plugin_controller.PluginController(
1082 self.test_list.options.plugin_config_name, self)
1083 self.plugin_controller.StartAllPlugins()
1084
Chih-Yu Huang97103ae2017-03-20 18:22:54 +08001085 # TODO(akahuang): Move this part into a pytest.
1086 # Prepare DUT link after the plugins start running, because the link might
1087 # need the network connection.
1088 if success:
1089 try:
1090 if self.test_list.options.dut_options:
1091 logging.info('dut_options set by %s: %r', self.test_list.test_list_id,
1092 self.test_list.options.dut_options)
1093 device_utils.PrepareDUTLink(**self.test_list.options.dut_options)
1094 except Exception:
1095 logging.exception('Unable to prepare DUT link.')
Chih-Yu Huang1725d622017-03-24 16:08:35 +08001096 self._RecordStartError(
Chih-Yu Huang97103ae2017-03-20 18:22:54 +08001097 'Unable to prepare DUT link.\n%s' % traceback.format_exc())
1098
Jon Salz0697cbf2012-07-04 15:14:04 +08001099 # Note that we create a log watcher even if
1100 # sync_event_log_period_secs isn't set (no background
1101 # syncing), since we may use it to flush event logs as well.
1102 self.log_watcher = EventLogWatcher(
Ricky Liang45c73e72015-01-15 15:00:30 +08001103 self.test_list.options.sync_event_log_period_secs,
1104 event_log_db_file=None,
1105 handle_event_logs_callback=self.handle_event_logs)
Jon Salz0697cbf2012-07-04 15:14:04 +08001106 if self.test_list.options.sync_event_log_period_secs:
1107 self.log_watcher.StartWatchThread()
1108
Shen-En Shihf4ad32f2017-07-31 15:56:39 +08001109 self.event_client.post_event(
1110 Event(Event.Type.UPDATE_SYSTEM_INFO))
Jon Salz0697cbf2012-07-04 15:14:04 +08001111
1112 os.environ['CROS_FACTORY'] = '1'
1113 os.environ['CROS_DISABLE_SITE_SYSINFO'] = '1'
1114
Shuo-Peng Liao268b40b2013-07-01 15:58:59 +08001115 # Should not move earlier.
1116 self.hooks.OnStartup()
1117
Ricky Liang36512a32014-07-25 11:47:04 +08001118 # Only after this point the Goofy backend is ready for UI connection.
1119 self.ready_for_ui_connection = True
1120
Jon Salz0697cbf2012-07-04 15:14:04 +08001121 def state_change_callback(test, test_state):
1122 self.event_client.post_event(
Peter Shihd46c5fd2017-09-22 15:28:42 +08001123 Event(
1124 Event.Type.STATE_CHANGE,
1125 path=test.path,
1126 state=test_state.ToStruct()))
Jon Salz0697cbf2012-07-04 15:14:04 +08001127 self.test_list.state_change_callback = state_change_callback
Jon Salz73e0fd02012-04-04 11:46:38 +08001128
Vic Yange2c76a82014-10-30 12:48:19 -07001129 self.pytest_prespawner = prespawner.PytestPrespawner()
1130 self.pytest_prespawner.start()
Jon Salza6711d72012-07-18 14:33:03 +08001131
Ricky Liang48e47f92014-02-26 19:31:51 +08001132 tests_after_shutdown = self.state_instance.get_shared_data(
Wei-Han Chenc17b4112016-11-22 14:56:51 +08001133 TESTS_AFTER_SHUTDOWN, optional=True)
Jon Salz5c344f62012-07-13 14:31:16 +08001134 force_auto_run = (tests_after_shutdown == FORCE_AUTO_RUN)
Wei-Han Chenc17b4112016-11-22 14:56:51 +08001135
Jon Salz5c344f62012-07-13 14:31:16 +08001136 if not force_auto_run and tests_after_shutdown is not None:
Wei-Han Chenc17b4112016-11-22 14:56:51 +08001137 logging.info('Resuming tests after shutdown: %r', tests_after_shutdown)
1138 self.test_list_iterator = tests_after_shutdown
Wei-Han Chenbcac7252017-04-21 19:46:51 +08001139 self.test_list_iterator.SetTestList(self.test_list)
Peter Ammon1e1ec572014-06-26 17:56:32 -07001140 self.run_enqueue(self.run_next_test)
Wei-Han Chenc17b4112016-11-22 14:56:51 +08001141 elif force_auto_run or self.test_list.options.auto_run_on_start:
1142 # If automation mode is enabled, allow suppress auto_run_on_start.
1143 if (self.options.automation_mode == 'NONE' or
1144 self.options.auto_run_on_start):
1145 status_filter = [TestState.UNTESTED]
1146 if self.test_list.options.retry_failed_on_start:
1147 status_filter.append(TestState.FAILED)
1148 self.run_enqueue(lambda: self.run_tests(self.test_list, status_filter))
1149 self.state_instance.set_shared_data(TESTS_AFTER_SHUTDOWN, None)
Ricky Liang4bff3e32014-02-20 18:46:11 +08001150 self.restore_active_run_state()
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001151
Hung-Te Lin793d6572017-09-04 18:17:56 +08001152 self.hooks.OnTestStart()
Vic Yang08505c72015-01-06 17:01:53 -08001153
Dean Liao592e4d52013-01-10 20:06:39 +08001154 self.may_disable_cros_shortcut_keys()
1155
1156 def may_disable_cros_shortcut_keys(self):
1157 test_options = self.test_list.options
1158 if test_options.disable_cros_shortcut_keys:
1159 logging.info('Filter ChromeOS shortcut keys.')
1160 self.key_filter = KeyFilter(
1161 unmap_caps_lock=test_options.disable_caps_lock,
1162 caps_lock_keycode=test_options.caps_lock_keycode)
1163 self.key_filter.Start()
1164
Peter Ammon1e1ec572014-06-26 17:56:32 -07001165 def perform_periodic_tasks(self):
1166 """Override of base method to perform periodic work.
Vic Yang4953fc12012-07-26 16:19:53 +08001167
Peter Ammon1e1ec572014-06-26 17:56:32 -07001168 This method must not raise exceptions.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001169 """
Peter Ammon1e1ec572014-06-26 17:56:32 -07001170 super(Goofy, self).perform_periodic_tasks()
Jon Salzb22d1172012-08-06 10:38:57 +08001171
Earl Oua3bca122016-10-21 16:00:30 +08001172 self.check_plugins()
cychiang21886742012-07-05 15:16:32 +08001173 self.check_for_updates()
Jon Salz57717ca2012-04-04 16:47:25 +08001174
Cheng-Yi Chiangf5b21012015-03-17 15:37:14 +08001175 def handle_event_logs(self, chunks, periodic=False):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001176 """Callback for event watcher.
Jon Salz258a40c2012-04-19 12:34:01 +08001177
Hung-Te Lind151bf32017-08-30 11:05:47 +08001178 Attempts to upload the event logs to the factory server.
Vic Yang93027612013-05-06 02:42:49 +08001179
1180 Args:
Jon Salzd15bbcf2013-05-21 17:33:57 +08001181 chunks: A list of Chunk objects.
Cheng-Yi Chiangf5b21012015-03-17 15:37:14 +08001182 periodic: This event log handling is periodic. Error messages
1183 will only be shown for the first time.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001184 """
Vic Yang93027612013-05-06 02:42:49 +08001185 first_exception = None
1186 exception_count = 0
Cheng-Yi Chiangf5b21012015-03-17 15:37:14 +08001187 # Suppress error messages for periodic event syncing except for the
1188 # first time. If event syncing is not periodic, always show the error
1189 # messages.
1190 quiet = self._suppress_event_log_error_messages if periodic else False
Vic Yang93027612013-05-06 02:42:49 +08001191
Jon Salzd15bbcf2013-05-21 17:33:57 +08001192 for chunk in chunks:
Vic Yang93027612013-05-06 02:42:49 +08001193 try:
Jon Salzcddb6402013-05-23 12:56:42 +08001194 description = 'event logs (%s)' % str(chunk)
Vic Yang93027612013-05-06 02:42:49 +08001195 start_time = time.time()
Hung-Te Lind151bf32017-08-30 11:05:47 +08001196 proxy = server_proxy.GetServerProxy(quiet=quiet)
1197 proxy.UploadEvent(
1198 chunk.log_name + '.' + event_log.GetReimageId(),
1199 Binary(chunk.chunk))
Vic Yang93027612013-05-06 02:42:49 +08001200 logging.info(
Ricky Liang45c73e72015-01-15 15:00:30 +08001201 'Successfully synced %s in %.03f s',
1202 description, time.time() - start_time)
Hung-Te Linc8174b52017-06-02 11:11:45 +08001203 except Exception:
Hung-Te Linf707b242016-01-08 23:11:42 +08001204 first_exception = (first_exception or
1205 (chunk.log_name + ': ' +
1206 debug_utils.FormatExceptionOnly()))
Vic Yang93027612013-05-06 02:42:49 +08001207 exception_count += 1
1208
1209 if exception_count:
1210 if exception_count == 1:
1211 msg = 'Log upload failed: %s' % first_exception
1212 else:
1213 msg = '%d log upload failed; first is: %s' % (
1214 exception_count, first_exception)
Cheng-Yi Chiangf5b21012015-03-17 15:37:14 +08001215 # For periodic event log syncing, only show the first error messages.
1216 if periodic:
1217 if not self._suppress_event_log_error_messages:
1218 self._suppress_event_log_error_messages = True
Hung-Te Lind151bf32017-08-30 11:05:47 +08001219 logging.warning('Suppress periodic factory server error messages for '
Cheng-Yi Chiangf5b21012015-03-17 15:37:14 +08001220 'event log syncing after the first one.')
1221 raise Exception(msg)
1222 # For event log syncing by request, show the error messages.
1223 else:
1224 raise Exception(msg)
Vic Yang93027612013-05-06 02:42:49 +08001225
Wei-Han Chenc17b4112016-11-22 14:56:51 +08001226 def run_tests_with_status(self, statuses_to_run, root=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001227 """Runs all top-level tests with a particular status.
Jon Salz0405ab52012-03-16 15:26:52 +08001228
Jon Salz0697cbf2012-07-04 15:14:04 +08001229 All active tests, plus any tests to re-run, are reset.
Jon Salz57717ca2012-04-04 16:47:25 +08001230
Jon Salz0697cbf2012-07-04 15:14:04 +08001231 Args:
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001232 statuses_to_run: The particular status that caller wants to run.
Jon Salz0697cbf2012-07-04 15:14:04 +08001233 starting_at: If provided, only auto-runs tests beginning with
1234 this test.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001235 root: The root of tests to run. If not provided, it will be
1236 the root of all tests.
1237 """
Jon Salz0697cbf2012-07-04 15:14:04 +08001238 root = root or self.test_list
Jon Salz6dc031d2013-06-19 13:06:23 +08001239 self.abort_active_tests('Operator requested run/re-run of certain tests')
Wei-Han Chenc17b4112016-11-22 14:56:51 +08001240 self.run_tests(root, status_filter=statuses_to_run)
Jon Salz0405ab52012-03-16 15:26:52 +08001241
Jon Salz0697cbf2012-07-04 15:14:04 +08001242 def restart_tests(self, root=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001243 """Restarts all tests."""
Jon Salz0697cbf2012-07-04 15:14:04 +08001244 root = root or self.test_list
Jon Salz0405ab52012-03-16 15:26:52 +08001245
Jon Salz6dc031d2013-06-19 13:06:23 +08001246 self.abort_active_tests('Operator requested restart of certain tests')
Wei-Han Chen3ae204c2017-04-28 19:36:55 +08001247 for test in root.Walk():
1248 test.UpdateState(status=TestState.UNTESTED)
Jon Salz0697cbf2012-07-04 15:14:04 +08001249 self.run_tests(root)
Hung-Te Lin96632362012-03-20 21:14:18 +08001250
Wei-Han Chenc17b4112016-11-22 14:56:51 +08001251 def auto_run(self, root=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001252 """"Auto-runs" tests that have not been run yet.
Hung-Te Lin96632362012-03-20 21:14:18 +08001253
Jon Salz0697cbf2012-07-04 15:14:04 +08001254 Args:
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001255 root: If provided, the root of tests to run. If not provided, the root
1256 will be test_list (root of all tests).
1257 """
Jon Salz0697cbf2012-07-04 15:14:04 +08001258 root = root or self.test_list
1259 self.run_tests_with_status([TestState.UNTESTED, TestState.ACTIVE],
Ricky Liang45c73e72015-01-15 15:00:30 +08001260 root=root)
Jon Salz968e90b2012-03-18 16:12:43 +08001261
Wei-Ning Huang38b75f02015-02-25 18:25:14 +08001262 def handle_key_filter_mode(self, event):
1263 if self.key_filter:
1264 if getattr(event, 'enabled'):
1265 self.key_filter.Start()
1266 else:
1267 self.key_filter.Stop()
1268
Jon Salz0697cbf2012-07-04 15:14:04 +08001269 def wait(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001270 """Waits for all pending invocations.
Jon Salz0697cbf2012-07-04 15:14:04 +08001271
1272 Useful for testing.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001273 """
Jon Salz1acc8742012-07-17 17:45:55 +08001274 while self.invocations:
1275 for k, v in self.invocations.iteritems():
1276 logging.info('Waiting for %s to complete...', k)
1277 v.thread.join()
1278 self.reap_completed_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +08001279
Claire Changd1961a22015-08-05 16:15:55 +08001280 def test_fail(self, test):
Hung-Te Lin793d6572017-09-04 18:17:56 +08001281 self.hooks.OnTestFailure(test)
Claire Changd1961a22015-08-05 16:15:55 +08001282
Wei-Han Chenced08ef2016-11-08 09:40:02 +08001283
Hung-Te Lin9d81ac72017-09-21 12:58:01 +08001284def main():
1285 # Logging should be solved first.
1286 (options, unused_args) = Goofy.GetCommandLineArgsParser().parse_args()
Hung-Te Lin8fc0d652017-09-21 13:05:44 +08001287 log_utils.InitLogging(verbose=options.verbose)
Hung-Te Lin9d81ac72017-09-21 12:58:01 +08001288
Peter Ammona3d298c2014-09-23 10:11:02 -07001289 Goofy.run_main_and_exit()
Hung-Te Lin9d81ac72017-09-21 12:58:01 +08001290
1291
1292if __name__ == '__main__':
1293 main()