blob: c25de950ebf34e7e474133a9f99b16c1dadfd776 [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 Linb6287242016-05-18 14:39:05 +080028from cros.factory.device import device_utils
Vic Yangd80ea752014-09-24 16:07:14 +080029from cros.factory.goofy.goofy_base import GoofyBase
30from cros.factory.goofy.goofy_rpc import GoofyRPC
31from cros.factory.goofy.invocation import TestArgEnv
32from cros.factory.goofy.invocation import TestInvocation
33from cros.factory.goofy.link_manager import PresenterLinkManager
Earl Oua3bca122016-10-21 16:00:30 +080034from cros.factory.goofy.plugins import plugin_controller
Vic Yange2c76a82014-10-30 12:48:19 -070035from cros.factory.goofy import prespawner
Wei-Ning Huang38b75f02015-02-25 18:25:14 +080036from cros.factory.goofy.terminal_manager import TerminalManager
Earl Oua3bca122016-10-21 16:00:30 +080037from cros.factory.goofy import test_environment
Earl Oua3bca122016-10-21 16:00:30 +080038from cros.factory.goofy import updater
Vic Yangd80ea752014-09-24 16:07:14 +080039from cros.factory.goofy.web_socket_manager import WebSocketManager
Hung-Te Linb6287242016-05-18 14:39:05 +080040from cros.factory.test.e2e_test.common import AutomationMode
41from cros.factory.test.e2e_test.common import AutomationModePrompt
42from cros.factory.test.e2e_test.common import ParseAutomationMode
43from cros.factory.test.env import paths
Jon Salz83591782012-06-26 11:09:58 +080044from cros.factory.test.event import Event
45from cros.factory.test.event import EventClient
46from cros.factory.test.event import EventServer
Hung-Te Linb6287242016-05-18 14:39:05 +080047from cros.factory.test import event_log
48from cros.factory.test.event_log import EventLog
Hung-Te Linb6287242016-05-18 14:39:05 +080049from cros.factory.test.event_log import GetBootSequence
Hung-Te Lin91492a12014-11-25 18:56:30 +080050from cros.factory.test.event_log_watcher import EventLogWatcher
Earl Oua3bca122016-10-21 16:00:30 +080051from cros.factory.test import factory
jcliangcd688182012-08-20 21:01:26 +080052from cros.factory.test.factory import TestState
Hung-Te Lin3f096842016-01-13 17:37:06 +080053from cros.factory.test.rules import phase
Earl Oua3bca122016-10-21 16:00:30 +080054from cros.factory.test import shopfloor
55from cros.factory.test import state
Wei-Han Chen2ebb92d2016-01-12 14:51:41 +080056from cros.factory.test.test_lists import test_lists
Earl Oua3bca122016-10-21 16:00:30 +080057from cros.factory.test import testlog
58from cros.factory.test import testlog_goofy
Hung-Te Linb6287242016-05-18 14:39:05 +080059from cros.factory.tools.key_filter import KeyFilter
Hung-Te Linf707b242016-01-08 23:11:42 +080060from cros.factory.utils import debug_utils
Jon Salz2af235d2013-06-24 14:47:21 +080061from cros.factory.utils import file_utils
Joel Kitchingb85ed7f2014-10-08 18:24:39 +080062from cros.factory.utils import net_utils
Hung-Te Lin4e6357c2016-01-08 14:32:00 +080063from cros.factory.utils import process_utils
64from cros.factory.utils import sys_utils
65from cros.factory.utils import time_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
68
Hung-Te Linf2f78f72012-02-08 19:27:11 +080069HWID_CFG_PATH = '/usr/local/share/chromeos-hwid/cfg'
Joel Kitching625ff0f2016-05-16 14:59:40 -070070CACHES_DIR = os.path.join(paths.GetStateRoot(), '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
Ricky Liang45c73e72015-01-15 15:00:30 +080079MAX_CRASH_FILE_SIZE = 64 * 1024
Jon Salze12c2b32013-06-25 16:24:34 +080080
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
Ricky Liang45c73e72015-01-15 15:00:30 +080084
Hung-Te Linf2f78f72012-02-08 19:27:11 +080085def get_hwid_cfg():
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +080086 """Returns the HWID config tag, or an empty string if none can be found."""
Jon Salz0697cbf2012-07-04 15:14:04 +080087 if 'CROS_HWID' in os.environ:
88 return os.environ['CROS_HWID']
89 if os.path.exists(HWID_CFG_PATH):
Ricky Liang45c73e72015-01-15 15:00:30 +080090 with open(HWID_CFG_PATH, 'r') as hwid_cfg_handle:
Jon Salz0697cbf2012-07-04 15:14:04 +080091 return hwid_cfg_handle.read().strip()
92 return ''
Hung-Te Linf2f78f72012-02-08 19:27:11 +080093
94
Jon Salz73e0fd02012-04-04 11:46:38 +080095_inited_logging = False
Hung-Te Linf2f78f72012-02-08 19:27:11 +080096
Ricky Liang45c73e72015-01-15 15:00:30 +080097
Peter Ammon1e1ec572014-06-26 17:56:32 -070098class Goofy(GoofyBase):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +080099 """The main factory flow.
Jon Salz0697cbf2012-07-04 15:14:04 +0800100
101 Note that all methods in this class must be invoked from the main
102 (event) thread. Other threads, such as callbacks and TestInvocation
103 methods, should instead post events on the run queue.
104
105 TODO: Unit tests. (chrome-os-partner:7409)
106
107 Properties:
108 uuid: A unique UUID for this invocation of Goofy.
109 state_instance: An instance of FactoryState.
110 state_server: The FactoryState XML/RPC server.
111 state_server_thread: A thread running state_server.
112 event_server: The EventServer socket server.
113 event_server_thread: A thread running event_server.
114 event_client: A client to the event server.
Earl Oua3bca122016-10-21 16:00:30 +0800115 plugin_controller: The PluginController object.
Jon Salz0697cbf2012-07-04 15:14:04 +0800116 ui_process: The factory ui process object.
Jon Salz0697cbf2012-07-04 15:14:04 +0800117 invocations: A map from FactoryTest objects to the corresponding
118 TestInvocations objects representing active tests.
119 tests_to_run: A deque of tests that should be run when the current
120 test(s) complete.
121 options: Command-line options.
122 args: Command-line args.
123 test_list: The test list.
Jon Salz128b0932013-07-03 16:55:26 +0800124 test_lists: All new-style test lists.
Ricky Liang4bff3e32014-02-20 18:46:11 +0800125 run_id: The identifier for latest test run.
126 scheduled_run_tests: The list of tests scheduled for latest test run.
Jon Salz0697cbf2012-07-04 15:14:04 +0800127 event_handlers: Map of Event.Type to the method used to handle that
128 event. If the method has an 'event' argument, the event is passed
129 to the handler.
Jon Salz416f9cc2013-05-10 18:32:50 +0800130 hooks: A Hooks object containing hooks for various Goofy actions.
Jon Salzd7550792013-07-12 05:49:27 +0800131 status: The current Goofy status (a member of the Status enum).
Peter Ammon948b7172014-07-15 12:43:06 -0700132 link_manager: Instance of PresenterLinkManager for communicating
133 with GoofyPresenter
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800134 """
Ricky Liang45c73e72015-01-15 15:00:30 +0800135
Jon Salz0697cbf2012-07-04 15:14:04 +0800136 def __init__(self):
Peter Ammon1e1ec572014-06-26 17:56:32 -0700137 super(Goofy, self).__init__()
Jon Salz0697cbf2012-07-04 15:14:04 +0800138 self.uuid = str(uuid.uuid4())
139 self.state_instance = None
140 self.state_server = None
141 self.state_server_thread = None
Jon Salz16d10542012-07-23 12:18:45 +0800142 self.goofy_rpc = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800143 self.event_server = None
144 self.event_server_thread = None
145 self.event_client = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800146 self.log_watcher = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800147 self.event_log = None
Chun-Ta Lin53cbbd52016-06-08 21:42:19 +0800148 self.testlog = None
Vic Yange2c76a82014-10-30 12:48:19 -0700149 self.autotest_prespawner = None
Earl Oua3bca122016-10-21 16:00:30 +0800150 self.plugin_controller = None
Vic Yange2c76a82014-10-30 12:48:19 -0700151 self.pytest_prespawner = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800152 self.ui_process = None
Vic Yanga3cecf82014-12-26 00:44:21 -0800153 self._ui_initialized = False
Jon Salzc79a9982012-08-30 04:42:01 +0800154 self.dummy_shopfloor = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800155 self.invocations = {}
156 self.tests_to_run = deque()
157 self.visible_test = None
158 self.chrome = None
Jon Salz416f9cc2013-05-10 18:32:50 +0800159 self.hooks = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800160
161 self.options = None
162 self.args = None
163 self.test_list = None
Jon Salz128b0932013-07-03 16:55:26 +0800164 self.test_lists = None
Ricky Liang4bff3e32014-02-20 18:46:11 +0800165 self.run_id = None
166 self.scheduled_run_tests = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800167 self.env = None
Jon Salzb22d1172012-08-06 10:38:57 +0800168 self.last_idle = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800169 self.last_shutdown_time = None
cychiang21886742012-07-05 15:16:32 +0800170 self.last_update_check = None
Cheng-Yi Chiang194d3c02015-03-16 14:37:15 +0800171 self._suppress_periodic_update_messages = False
Cheng-Yi Chiangf5b21012015-03-17 15:37:14 +0800172 self._suppress_event_log_error_messages = False
Earl Ouab979142016-10-25 16:48:06 +0800173 self.exclusive_resources = set()
Dean Liao592e4d52013-01-10 20:06:39 +0800174 self.key_filter = None
Jon Salzd7550792013-07-12 05:49:27 +0800175 self.status = Status.UNINITIALIZED
Ricky Liang36512a32014-07-25 11:47:04 +0800176 self.ready_for_ui_connection = False
Peter Ammon1e1ec572014-06-26 17:56:32 -0700177 self.link_manager = None
Hung-Te Linef7f2be2015-07-20 20:38:51 +0800178 self.is_restart_requested = False
Jon Salz0697cbf2012-07-04 15:14:04 +0800179
Hung-Te Lin6a72c642015-12-13 22:09:09 +0800180 # TODO(hungte) Support controlling remote DUT.
Hung-Te Linb6287242016-05-18 14:39:05 +0800181 self.dut = device_utils.CreateDUTInterface()
Hung-Te Lin6a72c642015-12-13 22:09:09 +0800182
Jon Salz85a39882012-07-05 16:45:04 +0800183 def test_or_root(event, parent_or_group=True):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800184 """Returns the test affected by a particular event.
Jon Salz85a39882012-07-05 16:45:04 +0800185
186 Args:
187 event: The event containing an optional 'path' attribute.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800188 parent_or_group: If True, returns the top-level parent for a test (the
Jon Salz85a39882012-07-05 16:45:04 +0800189 root node of the tests that need to be run together if the given test
190 path is to be run).
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800191 """
Jon Salz0697cbf2012-07-04 15:14:04 +0800192 try:
193 path = event.path
194 except AttributeError:
195 path = None
196
197 if path:
Jon Salz85a39882012-07-05 16:45:04 +0800198 test = self.test_list.lookup_path(path)
199 if parent_or_group:
200 test = test.get_top_level_parent_or_group()
201 return test
Jon Salz0697cbf2012-07-04 15:14:04 +0800202 else:
203 return self.test_list
204
205 self.event_handlers = {
Ricky Liang45c73e72015-01-15 15:00:30 +0800206 Event.Type.SWITCH_TEST: self.handle_switch_test,
Ricky Liang45c73e72015-01-15 15:00:30 +0800207 Event.Type.RESTART_TESTS:
208 lambda event: self.restart_tests(root=test_or_root(event)),
209 Event.Type.AUTO_RUN:
210 lambda event: self.auto_run(root=test_or_root(event)),
Ricky Liang45c73e72015-01-15 15:00:30 +0800211 Event.Type.RUN_TESTS_WITH_STATUS:
212 lambda event: self.run_tests_with_status(
213 event.status,
214 root=test_or_root(event)),
Ricky Liang45c73e72015-01-15 15:00:30 +0800215 Event.Type.UPDATE_SYSTEM_INFO:
216 lambda event: self.update_system_info(),
217 Event.Type.STOP:
218 lambda event: self.stop(root=test_or_root(event, False),
219 fail=getattr(event, 'fail', False),
220 reason=getattr(event, 'reason', None)),
221 Event.Type.SET_VISIBLE_TEST:
222 lambda event: self.set_visible_test(
223 self.test_list.lookup_path(event.path)),
224 Event.Type.CLEAR_STATE:
225 lambda event: self.clear_state(
226 self.test_list.lookup_path(event.path)),
Wei-Ning Huang38b75f02015-02-25 18:25:14 +0800227 Event.Type.KEY_FILTER_MODE: self.handle_key_filter_mode,
Jon Salz0697cbf2012-07-04 15:14:04 +0800228 }
229
Jon Salz0697cbf2012-07-04 15:14:04 +0800230 self.web_socket_manager = None
Wei-Ning Huang38b75f02015-02-25 18:25:14 +0800231 self.terminal_manager = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800232
233 def destroy(self):
Ricky Liang74237a02014-09-18 15:11:23 +0800234 """Performs any shutdown tasks. Overrides base class method."""
Jon Salzd7550792013-07-12 05:49:27 +0800235 self.status = Status.TERMINATING
Jon Salz0697cbf2012-07-04 15:14:04 +0800236 if self.chrome:
237 self.chrome.kill()
238 self.chrome = None
Jon Salzc79a9982012-08-30 04:42:01 +0800239 if self.dummy_shopfloor:
240 self.dummy_shopfloor.kill()
241 self.dummy_shopfloor = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800242 if self.ui_process:
Hung-Te Lin4e6357c2016-01-08 14:32:00 +0800243 process_utils.KillProcessTree(self.ui_process, 'ui')
Jon Salz0697cbf2012-07-04 15:14:04 +0800244 self.ui_process = None
245 if self.web_socket_manager:
246 logging.info('Stopping web sockets')
247 self.web_socket_manager.close()
248 self.web_socket_manager = None
249 if self.state_server_thread:
250 logging.info('Stopping state server')
251 self.state_server.shutdown()
252 self.state_server_thread.join()
253 self.state_server.server_close()
254 self.state_server_thread = None
255 if self.state_instance:
256 self.state_instance.close()
257 if self.event_server_thread:
258 logging.info('Stopping event server')
259 self.event_server.shutdown() # pylint: disable=E1101
260 self.event_server_thread.join()
261 self.event_server.server_close()
262 self.event_server_thread = None
263 if self.log_watcher:
264 if self.log_watcher.IsThreadStarted():
265 self.log_watcher.StopWatchThread()
266 self.log_watcher = None
Vic Yange2c76a82014-10-30 12:48:19 -0700267 if self.autotest_prespawner:
268 logging.info('Stopping autotest prespawner')
269 self.autotest_prespawner.stop()
270 self.autotest_prespawner = None
271 if self.pytest_prespawner:
272 logging.info('Stopping pytest prespawner')
273 self.pytest_prespawner.stop()
274 self.pytest_prespawner = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800275 if self.event_client:
276 logging.info('Closing event client')
277 self.event_client.close()
278 self.event_client = None
279 if self.event_log:
280 self.event_log.Close()
281 self.event_log = None
Chun-Ta Lin53cbbd52016-06-08 21:42:19 +0800282 if self.testlog:
283 self.testlog.Close()
284 self.testlog = None
Dean Liao592e4d52013-01-10 20:06:39 +0800285 if self.key_filter:
286 self.key_filter.Stop()
Peter Ammon1e1ec572014-06-26 17:56:32 -0700287 if self.link_manager:
288 self.link_manager.Stop()
289 self.link_manager = None
Earl Oua3bca122016-10-21 16:00:30 +0800290 if self.plugin_controller:
291 self.plugin_controller.StopAndDestroyAllPlugins()
292 self.plugin_controller = None
Dean Liao592e4d52013-01-10 20:06:39 +0800293
Peter Ammon1e1ec572014-06-26 17:56:32 -0700294 super(Goofy, self).destroy()
Jon Salz0697cbf2012-07-04 15:14:04 +0800295 logging.info('Done destroying Goofy')
Jon Salzd7550792013-07-12 05:49:27 +0800296 self.status = Status.TERMINATED
Jon Salz0697cbf2012-07-04 15:14:04 +0800297
298 def start_state_server(self):
Jon Salz2af235d2013-06-24 14:47:21 +0800299 # Before starting state server, remount stateful partitions with
300 # no commit flag. The default commit time (commit=600) makes corruption
301 # too likely.
Hung-Te Lin1968d9c2016-01-08 22:55:46 +0800302 sys_utils.ResetCommitTime()
Jon Salz2af235d2013-06-24 14:47:21 +0800303
Jon Salz0697cbf2012-07-04 15:14:04 +0800304 self.state_instance, self.state_server = (
Ricky Liang45c73e72015-01-15 15:00:30 +0800305 state.create_server(bind_address='0.0.0.0'))
Jon Salz16d10542012-07-23 12:18:45 +0800306 self.goofy_rpc = GoofyRPC(self)
307 self.goofy_rpc.RegisterMethods(self.state_instance)
Jon Salz0697cbf2012-07-04 15:14:04 +0800308 logging.info('Starting state server')
309 self.state_server_thread = threading.Thread(
Ricky Liang45c73e72015-01-15 15:00:30 +0800310 target=self.state_server.serve_forever,
311 name='StateServer')
Jon Salz0697cbf2012-07-04 15:14:04 +0800312 self.state_server_thread.start()
313
314 def start_event_server(self):
315 self.event_server = EventServer()
316 logging.info('Starting factory event server')
317 self.event_server_thread = threading.Thread(
Ricky Liang45c73e72015-01-15 15:00:30 +0800318 target=self.event_server.serve_forever,
319 name='EventServer') # pylint: disable=E1101
Jon Salz0697cbf2012-07-04 15:14:04 +0800320 self.event_server_thread.start()
321
322 self.event_client = EventClient(
Ricky Liang45c73e72015-01-15 15:00:30 +0800323 callback=self.handle_event, event_loop=self.run_queue)
Jon Salz0697cbf2012-07-04 15:14:04 +0800324
325 self.web_socket_manager = WebSocketManager(self.uuid)
Ricky Liang45c73e72015-01-15 15:00:30 +0800326 self.state_server.add_handler('/event',
327 self.web_socket_manager.handle_web_socket)
Jon Salz0697cbf2012-07-04 15:14:04 +0800328
Wei-Ning Huang38b75f02015-02-25 18:25:14 +0800329 def start_terminal_server(self):
330 self.terminal_manager = TerminalManager()
331 self.state_server.add_handler('/pty',
332 self.terminal_manager.handle_web_socket)
333
Jon Salz0697cbf2012-07-04 15:14:04 +0800334 def start_ui(self):
335 ui_proc_args = [
Wei-Han Chen2ebb92d2016-01-12 14:51:41 +0800336 os.path.join(paths.FACTORY_PACKAGE_PATH, 'test', 'ui.py'),
Ricky Liang45c73e72015-01-15 15:00:30 +0800337 self.options.test_list
338 ]
Jon Salz0697cbf2012-07-04 15:14:04 +0800339 if self.options.verbose:
340 ui_proc_args.append('-v')
341 logging.info('Starting ui %s', ui_proc_args)
Hung-Te Lin4e6357c2016-01-08 14:32:00 +0800342 self.ui_process = process_utils.Spawn(ui_proc_args)
Jon Salz0697cbf2012-07-04 15:14:04 +0800343 logging.info('Waiting for UI to come up...')
344 self.event_client.wait(
Ricky Liang45c73e72015-01-15 15:00:30 +0800345 lambda event: event.type == Event.Type.UI_READY)
Jon Salz0697cbf2012-07-04 15:14:04 +0800346 logging.info('UI has started')
347
348 def set_visible_test(self, test):
349 if self.visible_test == test:
350 return
Jon Salz2f2d42c2012-07-30 12:30:34 +0800351 if test and not test.has_ui:
352 return
Jon Salz0697cbf2012-07-04 15:14:04 +0800353
354 if test:
355 test.update_state(visible=True)
356 if self.visible_test:
357 self.visible_test.update_state(visible=False)
358 self.visible_test = test
359
Ricky Liang48e47f92014-02-26 19:31:51 +0800360 def log_startup_messages(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800361 """Logs the tail of var/log/messages and mosys and EC console logs."""
Jon Salzd4306c82012-11-30 15:16:36 +0800362 # TODO(jsalz): This is mostly a copy-and-paste of code in init_states,
363 # for factory-3004.B only. Consolidate and merge back to ToT.
Hung-Te Linf5f2d7f2016-01-08 17:12:46 +0800364 if sys_utils.InChroot():
Jon Salzd4306c82012-11-30 15:16:36 +0800365 return
366
367 try:
Hung-Te Lin1a4e30c2016-01-08 23:25:10 +0800368 var_log_messages = sys_utils.GetVarLogMessagesBeforeReboot()
Jon Salzd4306c82012-11-30 15:16:36 +0800369 logging.info(
Ricky Liang45c73e72015-01-15 15:00:30 +0800370 'Tail of /var/log/messages before last reboot:\n'
371 '%s', ('\n'.join(
372 ' ' + x for x in var_log_messages)))
Jon Salzd4306c82012-11-30 15:16:36 +0800373 except: # pylint: disable=W0702
374 logging.exception('Unable to grok /var/log/messages')
375
376 try:
Hung-Te Lin4e6357c2016-01-08 14:32:00 +0800377 mosys_log = process_utils.Spawn(
Jon Salzd4306c82012-11-30 15:16:36 +0800378 ['mosys', 'eventlog', 'list'],
379 read_stdout=True, log_stderr_on_error=True).stdout_data
380 logging.info('System eventlog from mosys:\n%s\n', mosys_log)
381 except: # pylint: disable=W0702
382 logging.exception('Unable to read mosys eventlog')
383
Dean Liao88b93192014-10-23 19:37:41 +0800384 self.log_ec_console()
385 self.log_ec_panic_info()
386
387 @staticmethod
388 def log_ec_console():
389 """Logs EC console log into logging.info.
390
391 It logs an error message in logging.exception if an exception is raised
392 when getting EC console log.
393 For unsupported device, it logs unsupport message in logging.info
394
395 Returns:
396 EC console log string.
397 """
Jon Salzd4306c82012-11-30 15:16:36 +0800398 try:
Hung-Te Linb6287242016-05-18 14:39:05 +0800399 ec_console_log = device_utils.CreateDUTInterface().ec.GetECConsoleLog()
Jon Salzd4306c82012-11-30 15:16:36 +0800400 logging.info('EC console log after reboot:\n%s\n', ec_console_log)
Dean Liao88b93192014-10-23 19:37:41 +0800401 return ec_console_log
402 except NotImplementedError:
403 logging.info('EC console log not supported')
Jon Salzd4306c82012-11-30 15:16:36 +0800404 except: # pylint: disable=W0702
405 logging.exception('Error retrieving EC console log')
406
Dean Liao88b93192014-10-23 19:37:41 +0800407 @staticmethod
408 def log_ec_panic_info():
409 """Logs EC panic info into logging.info.
410
411 It logs an error message in logging.exception if an exception is raised
412 when getting EC panic info.
413 For unsupported device, it logs unsupport message in logging.info
414
415 Returns:
416 EC panic info string.
417 """
Vic Yang079f9872013-07-01 11:32:00 +0800418 try:
Hung-Te Linb6287242016-05-18 14:39:05 +0800419 ec_panic_info = device_utils.CreateDUTInterface().ec.GetECPanicInfo()
Vic Yang079f9872013-07-01 11:32:00 +0800420 logging.info('EC panic info after reboot:\n%s\n', ec_panic_info)
Dean Liao88b93192014-10-23 19:37:41 +0800421 return ec_panic_info
422 except NotImplementedError:
423 logging.info('EC panic info is not supported')
Vic Yang079f9872013-07-01 11:32:00 +0800424 except: # pylint: disable=W0702
425 logging.exception('Error retrieving EC panic info')
426
Ricky Liang48e47f92014-02-26 19:31:51 +0800427 def shutdown(self, operation):
428 """Starts shutdown procedure.
429
430 Args:
Vic (Chun-Ju) Yang05b0d952014-04-28 17:39:09 +0800431 operation: The shutdown operation (reboot, full_reboot, or halt).
Ricky Liang48e47f92014-02-26 19:31:51 +0800432 """
433 active_tests = []
434 for test in self.test_list.walk():
435 if not test.is_leaf():
436 continue
437
438 test_state = test.get_state()
439 if test_state.status == TestState.ACTIVE:
440 active_tests.append(test)
441
Ricky Liang48e47f92014-02-26 19:31:51 +0800442 if not (len(active_tests) == 1 and
443 isinstance(active_tests[0], factory.ShutdownStep)):
444 logging.error(
445 'Calling Goofy shutdown outside of the shutdown factory test')
446 return
447
448 logging.info('Start Goofy shutdown (%s)', operation)
449 # Save pending test list in the state server
450 self.state_instance.set_shared_data(
451 'tests_after_shutdown',
452 [t.path for t in self.tests_to_run])
453 # Save shutdown time
454 self.state_instance.set_shared_data('shutdown_time', time.time())
455
456 with self.env.lock:
457 self.event_log.Log('shutdown', operation=operation)
458 shutdown_result = self.env.shutdown(operation)
459 if shutdown_result:
460 # That's all, folks!
Peter Ammon1e1ec572014-06-26 17:56:32 -0700461 self.run_enqueue(None)
Ricky Liang48e47f92014-02-26 19:31:51 +0800462 else:
463 # Just pass (e.g., in the chroot).
464 self.state_instance.set_shared_data('tests_after_shutdown', None)
465 # Send event with no fields to indicate that there is no
466 # longer a pending shutdown.
467 self.event_client.post_event(Event(Event.Type.PENDING_SHUTDOWN))
468
469 def handle_shutdown_complete(self, test):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800470 """Handles the case where a shutdown was detected during a shutdown step.
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800471
Ricky Liang6fe218c2013-12-27 15:17:17 +0800472 Args:
473 test: The ShutdownStep.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800474 """
Jon Salz0697cbf2012-07-04 15:14:04 +0800475 test_state = test.update_state(increment_shutdown_count=1)
476 logging.info('Detected shutdown (%d of %d)',
Ricky Liang48e47f92014-02-26 19:31:51 +0800477 test_state.shutdown_count, test.iterations)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800478
Ricky Liang48e47f92014-02-26 19:31:51 +0800479 # Insert current shutdown test at the front of the list of tests to run
480 # after shutdown. This is to continue on post-shutdown verification in the
481 # shutdown step.
482 tests_after_shutdown = self.state_instance.get_shared_data(
483 'tests_after_shutdown', optional=True)
484 if not tests_after_shutdown:
485 self.state_instance.set_shared_data('tests_after_shutdown', [test.path])
486 elif isinstance(tests_after_shutdown, list):
487 self.state_instance.set_shared_data(
488 'tests_after_shutdown', [test.path] + tests_after_shutdown)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800489
Ricky Liang48e47f92014-02-26 19:31:51 +0800490 # Set 'post_shutdown' to inform shutdown test that a shutdown just occurred.
Ricky Liangb7eb8772014-09-15 18:05:22 +0800491 self.state_instance.set_shared_data(
492 state.POST_SHUTDOWN_TAG % test.path,
493 self.state_instance.get_test_state(test.path).invocation)
Jon Salz258a40c2012-04-19 12:34:01 +0800494
Jon Salz0697cbf2012-07-04 15:14:04 +0800495 def init_states(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800496 """Initializes all states on startup."""
Jon Salz0697cbf2012-07-04 15:14:04 +0800497 for test in self.test_list.get_all_tests():
498 # Make sure the state server knows about all the tests,
499 # defaulting to an untested state.
500 test.update_state(update_parent=False, visible=False)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800501
Jon Salz0697cbf2012-07-04 15:14:04 +0800502 var_log_messages = None
Vic Yanga9c32212012-08-16 20:07:54 +0800503 mosys_log = None
Vic Yange4c275d2012-08-28 01:50:20 +0800504 ec_console_log = None
Vic Yang079f9872013-07-01 11:32:00 +0800505 ec_panic_info = None
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800506
Jon Salz0697cbf2012-07-04 15:14:04 +0800507 # Any 'active' tests should be marked as failed now.
508 for test in self.test_list.walk():
Jon Salza6711d72012-07-18 14:33:03 +0800509 if not test.is_leaf():
510 # Don't bother with parents; they will be updated when their
511 # children are updated.
512 continue
513
Jon Salz0697cbf2012-07-04 15:14:04 +0800514 test_state = test.get_state()
515 if test_state.status != TestState.ACTIVE:
516 continue
517 if isinstance(test, factory.ShutdownStep):
518 # Shutdown while the test was active - that's good.
Ricky Liang48e47f92014-02-26 19:31:51 +0800519 self.handle_shutdown_complete(test)
Jon Salz0697cbf2012-07-04 15:14:04 +0800520 else:
521 # Unexpected shutdown. Grab /var/log/messages for context.
522 if var_log_messages is None:
523 try:
524 var_log_messages = (
Hung-Te Lin1a4e30c2016-01-08 23:25:10 +0800525 sys_utils.GetVarLogMessagesBeforeReboot())
Jon Salz0697cbf2012-07-04 15:14:04 +0800526 # Write it to the log, to make it easier to
527 # correlate with /var/log/messages.
528 logging.info(
Ricky Liang45c73e72015-01-15 15:00:30 +0800529 'Unexpected shutdown. '
530 'Tail of /var/log/messages before last reboot:\n'
531 '%s', ('\n'.join(
532 ' ' + x for x in var_log_messages)))
Jon Salz0697cbf2012-07-04 15:14:04 +0800533 except: # pylint: disable=W0702
534 logging.exception('Unable to grok /var/log/messages')
535 var_log_messages = []
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800536
Hung-Te Linf5f2d7f2016-01-08 17:12:46 +0800537 if mosys_log is None and not sys_utils.InChroot():
Jon Salz008f4ea2012-08-28 05:39:45 +0800538 try:
Hung-Te Lin4e6357c2016-01-08 14:32:00 +0800539 mosys_log = process_utils.Spawn(
Jon Salz008f4ea2012-08-28 05:39:45 +0800540 ['mosys', 'eventlog', 'list'],
541 read_stdout=True, log_stderr_on_error=True).stdout_data
542 # Write it to the log also.
543 logging.info('System eventlog from mosys:\n%s\n', mosys_log)
544 except: # pylint: disable=W0702
545 logging.exception('Unable to read mosys eventlog')
Vic Yanga9c32212012-08-16 20:07:54 +0800546
Vic Yange4c275d2012-08-28 01:50:20 +0800547 if ec_console_log is None:
Dean Liao88b93192014-10-23 19:37:41 +0800548 ec_console_log = self.log_ec_console()
Vic Yange4c275d2012-08-28 01:50:20 +0800549
Vic Yang079f9872013-07-01 11:32:00 +0800550 if ec_panic_info is None:
Dean Liao88b93192014-10-23 19:37:41 +0800551 ec_panic_info = self.log_ec_panic_info()
Vic Yang079f9872013-07-01 11:32:00 +0800552
Jon Salz0697cbf2012-07-04 15:14:04 +0800553 error_msg = 'Unexpected shutdown while test was running'
Chun-Ta Lin53cbbd52016-06-08 21:42:19 +0800554 # TODO(itspeter): Add testlog to collect expired session infos.
Jon Salz0697cbf2012-07-04 15:14:04 +0800555 self.event_log.Log('end_test',
Ricky Liang45c73e72015-01-15 15:00:30 +0800556 path=test.path,
557 status=TestState.FAILED,
558 invocation=test.get_state().invocation,
559 error_msg=error_msg,
560 var_log_messages='\n'.join(var_log_messages),
561 mosys_log=mosys_log)
Jon Salz0697cbf2012-07-04 15:14:04 +0800562 test.update_state(
Ricky Liang45c73e72015-01-15 15:00:30 +0800563 status=TestState.FAILED,
564 error_msg=error_msg)
Chun-Ta Lin87c2dac2015-05-02 01:35:01 -0700565 # Trigger the OnTestFailure callback.
Claire Changd1961a22015-08-05 16:15:55 +0800566 self.run_queue.put(lambda: self.test_fail(test))
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800567
Jon Salz50efe942012-07-26 11:54:10 +0800568 if not test.never_fails:
569 # For "never_fails" tests (such as "Start"), don't cancel
570 # pending tests, since reboot is expected.
571 factory.console.info('Unexpected shutdown while test %s '
572 'running; cancelling any pending tests',
573 test.path)
574 self.state_instance.set_shared_data('tests_after_shutdown', [])
Jon Salz69806bb2012-07-20 18:05:02 +0800575
Jon Salz008f4ea2012-08-28 05:39:45 +0800576 self.update_skipped_tests()
577
578 def update_skipped_tests(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800579 """Updates skipped states based on run_if."""
Jon Salz885dcac2013-07-23 16:39:50 +0800580 env = TestArgEnv()
Ricky Liang45c73e72015-01-15 15:00:30 +0800581
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800582 # Gets all run_if evaluation, and stores results in skip_map.
583 skip_map = dict()
Jon Salz008f4ea2012-08-28 05:39:45 +0800584 for t in self.test_list.walk():
Wei-Han Chene3284922016-11-01 17:21:27 +0800585 skip_map[t.path] = not t.evaluate_run_if(env,
586 shopfloor.get_selected_aux_data)
Jon Salz885dcac2013-07-23 16:39:50 +0800587
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800588 # Propagates the skip value from root of tree and updates skip_map.
589 def _update_skip_map_from_node(test, skip_from_parent):
590 """Updates skip_map from a given node.
Jon Salz885dcac2013-07-23 16:39:50 +0800591
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800592 Given a FactoryTest node and the skip value from parent, updates the
593 skip value of current node in the skip_map if skip value from parent is
594 True. If this node has children, recursively propagate this value to all
595 its children, that is, all its subtests.
596 Note that this function only updates value in skip_map, not the actual
597 test_list tree.
Jon Salz008f4ea2012-08-28 05:39:45 +0800598
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800599 Args:
600 test: The given FactoryTest object. It is a node in the test_list tree.
601 skip_from_parent: The skip value which propagates from the parent of
602 input node.
603 """
604 skip_this_tree = skip_from_parent or skip_map[test.path]
605 if skip_this_tree:
606 logging.info('Skip from node %r', test.path)
607 skip_map[test.path] = True
608 if test.is_leaf():
609 return
610 # Propagates skip value to its subtests
611 for subtest in test.subtests:
612 _update_skip_map_from_node(subtest, skip_this_tree)
613
614 _update_skip_map_from_node(self.test_list, False)
615
616 # Updates the skip value from skip_map to test_list tree. Also, updates test
617 # status if needed.
618 for t in self.test_list.walk():
619 skip = skip_map[t.path]
620 test_state = t.get_state()
621 if ((not skip) and
622 (test_state.status == TestState.PASSED) and
623 (test_state.error_msg == TestState.SKIPPED_MSG)):
624 # It was marked as skipped before, but now we need to run it.
625 # Mark as untested.
626 t.update_state(skip=skip, status=TestState.UNTESTED, error_msg='')
627 else:
628 t.update_state(skip=skip)
Jon Salz008f4ea2012-08-28 05:39:45 +0800629
Jon Salz0697cbf2012-07-04 15:14:04 +0800630 def handle_event(self, event):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800631 """Handles an event from the event server."""
Jon Salz0697cbf2012-07-04 15:14:04 +0800632 handler = self.event_handlers.get(event.type)
633 if handler:
634 handler(event)
635 else:
636 # We don't register handlers for all event types - just ignore
637 # this event.
638 logging.debug('Unbound event type %s', event.type)
Jon Salz4f6c7172012-06-11 20:45:36 +0800639
Vic Yangaabf9fd2013-04-09 18:56:13 +0800640 def check_critical_factory_note(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800641 """Returns True if the last factory note is critical."""
Vic Yangaabf9fd2013-04-09 18:56:13 +0800642 notes = self.state_instance.get_shared_data('factory_note', True)
643 return notes and notes[-1]['level'] == 'CRITICAL'
644
Hung-Te Linef7f2be2015-07-20 20:38:51 +0800645 def schedule_restart(self):
646 """Schedules a restart event when any invocation is completed."""
647 self.is_restart_requested = True
648
649 def invocation_completion(self):
650 """Callback when an invocation is completed."""
651 if self.is_restart_requested:
652 logging.info('Restart by scheduled event.')
653 self.is_restart_requested = False
654 self.restart_tests()
655 else:
656 self.run_next_test()
657
Jon Salz0697cbf2012-07-04 15:14:04 +0800658 def run_next_test(self):
henryhsu4cc6b022014-04-22 17:12:42 +0800659 """Runs the next eligible test (or tests) in self.tests_to_run.
660
661 We have three kinds of the next eligible test:
662 1. normal
663 2. backgroundable
664 3. force_background
665
666 And we have four situations of the ongoing invocations:
667 a. only a running normal test
668 b. all running tests are backgroundable
669 c. all running tests are force_background
670 d. all running tests are any combination of backgroundable and
671 force_background
672
673 When a test would like to be run, it must follow the rules:
674 [1] cannot run with [abd]
675 [2] cannot run with [a]
676 All the other combinations are allowed
677 """
Jon Salz0697cbf2012-07-04 15:14:04 +0800678 self.reap_completed_tests()
Vic Yangaabf9fd2013-04-09 18:56:13 +0800679 if self.tests_to_run and self.check_critical_factory_note():
680 self.tests_to_run.clear()
681 return
Jon Salz0697cbf2012-07-04 15:14:04 +0800682 while self.tests_to_run:
Ricky Liang6fe218c2013-12-27 15:17:17 +0800683 logging.debug('Tests to run: %s', [x.path for x in self.tests_to_run])
Jon Salz94eb56f2012-06-12 18:01:12 +0800684
Jon Salz0697cbf2012-07-04 15:14:04 +0800685 test = self.tests_to_run[0]
Jon Salz94eb56f2012-06-12 18:01:12 +0800686
Jon Salz0697cbf2012-07-04 15:14:04 +0800687 if test in self.invocations:
688 logging.info('Next test %s is already running', test.path)
689 self.tests_to_run.popleft()
690 return
Jon Salz94eb56f2012-06-12 18:01:12 +0800691
Jon Salza1412922012-07-23 16:04:17 +0800692 for requirement in test.require_run:
693 for i in requirement.test.walk():
694 if i.get_state().status == TestState.ACTIVE:
Jon Salz304a75d2012-07-06 11:14:15 +0800695 logging.info('Waiting for active test %s to complete '
Jon Salza1412922012-07-23 16:04:17 +0800696 'before running %s', i.path, test.path)
Jon Salz304a75d2012-07-06 11:14:15 +0800697 return
698
henryhsu4cc6b022014-04-22 17:12:42 +0800699 def is_normal_test(test):
700 return not (test.backgroundable or test.force_background)
701
702 # [1] cannot run with [abd].
703 if self.invocations and is_normal_test(test) and any(
704 [not x.force_background for x in self.invocations]):
705 logging.info('Waiting for non-force_background tests to '
706 'complete before running %s', test.path)
707 return
708
709 # [2] cannot run with [a].
710 if self.invocations and test.backgroundable and any(
711 [is_normal_test(x) for x in self.invocations]):
712 logging.info('Waiting for normal tests to '
713 'complete before running %s', test.path)
Jon Salz0697cbf2012-07-04 15:14:04 +0800714 return
Jon Salz94eb56f2012-06-12 18:01:12 +0800715
Jon Salz3e6f5202012-10-15 15:08:29 +0800716 if test.get_state().skip:
717 factory.console.info('Skipping test %s', test.path)
718 test.update_state(status=TestState.PASSED,
719 error_msg=TestState.SKIPPED_MSG)
720 self.tests_to_run.popleft()
721 continue
722
Jon Salz0697cbf2012-07-04 15:14:04 +0800723 self.tests_to_run.popleft()
Jon Salz94eb56f2012-06-12 18:01:12 +0800724
Jon Salz304a75d2012-07-06 11:14:15 +0800725 untested = set()
Jon Salza1412922012-07-23 16:04:17 +0800726 for requirement in test.require_run:
727 for i in requirement.test.walk():
728 if i == test:
Jon Salz304a75d2012-07-06 11:14:15 +0800729 # We've hit this test itself; stop checking
730 break
Jon Salza1412922012-07-23 16:04:17 +0800731 if ((i.get_state().status == TestState.UNTESTED) or
732 (requirement.passed and i.get_state().status !=
733 TestState.PASSED)):
Jon Salz304a75d2012-07-06 11:14:15 +0800734 # Found an untested test; move on to the next
735 # element in require_run.
Jon Salza1412922012-07-23 16:04:17 +0800736 untested.add(i)
Jon Salz304a75d2012-07-06 11:14:15 +0800737 break
738
739 if untested:
740 untested_paths = ', '.join(sorted([x.path for x in untested]))
741 if self.state_instance.get_shared_data('engineering_mode',
742 optional=True):
743 # In engineering mode, we'll let it go.
744 factory.console.warn('In engineering mode; running '
745 '%s even though required tests '
746 '[%s] have not completed',
747 test.path, untested_paths)
748 else:
749 # Not in engineering mode; mark it failed.
750 error_msg = ('Required tests [%s] have not been run yet'
751 % untested_paths)
752 factory.console.error('Not running %s: %s',
753 test.path, error_msg)
754 test.update_state(status=TestState.FAILED,
755 error_msg=error_msg)
756 continue
757
Ricky Liang48e47f92014-02-26 19:31:51 +0800758 if (isinstance(test, factory.ShutdownStep) and
Ricky Liangb7eb8772014-09-15 18:05:22 +0800759 self.state_instance.get_shared_data(
760 state.POST_SHUTDOWN_TAG % test.path, optional=True)):
Ricky Liang48e47f92014-02-26 19:31:51 +0800761 # Invoking post shutdown method of shutdown test. We should retain the
762 # iterations_left and retries_left of the original test state.
763 test_state = self.state_instance.get_test_state(test.path)
764 self._run_test(test, test_state.iterations_left,
765 test_state.retries_left)
766 else:
767 # Starts a new test run; reset iterations and retries.
768 self._run_test(test, test.iterations, test.retries)
Jon Salz1acc8742012-07-17 17:45:55 +0800769
Cheng-Yi Chiangce05c002013-04-04 02:13:17 +0800770 def _run_test(self, test, iterations_left=None, retries_left=None):
Vic Yanga3cecf82014-12-26 00:44:21 -0800771 if not self._ui_initialized and not test.is_no_host():
772 self.init_ui()
Vic Yang08505c72015-01-06 17:01:53 -0800773 invoc = TestInvocation(
Hung-Te Linef7f2be2015-07-20 20:38:51 +0800774 self, test, on_completion=self.invocation_completion,
Claire Changd1961a22015-08-05 16:15:55 +0800775 on_test_failure=lambda: self.test_fail(test))
Jon Salz1acc8742012-07-17 17:45:55 +0800776 new_state = test.update_state(
Ricky Liang48e47f92014-02-26 19:31:51 +0800777 status=TestState.ACTIVE, increment_count=1, error_msg='',
778 invocation=invoc.uuid, iterations_left=iterations_left,
779 retries_left=retries_left,
780 visible=(self.visible_test == test))
Jon Salz1acc8742012-07-17 17:45:55 +0800781 invoc.count = new_state.count
782
783 self.invocations[test] = invoc
784 if self.visible_test is None and test.has_ui:
785 self.set_visible_test(test)
Earl Oua3bca122016-10-21 16:00:30 +0800786 self.check_plugins()
Jon Salz1acc8742012-07-17 17:45:55 +0800787 invoc.start()
Jon Salz5f2a0672012-05-22 17:14:06 +0800788
Earl Oua3bca122016-10-21 16:00:30 +0800789 def check_plugins(self):
790 """Check plugins to be paused or resumed."""
791 exclusive_resources = set()
792 for test in self.invocations:
793 exclusive_resources = exclusive_resources.union(
794 test.get_exclusive_resources())
795 self.plugin_controller.PauseAndResumePluginByResource(exclusive_resources)
796
cychiang21886742012-07-05 15:16:32 +0800797 def check_for_updates(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800798 """Schedules an asynchronous check for updates if necessary."""
cychiang21886742012-07-05 15:16:32 +0800799 if not self.test_list.options.update_period_secs:
800 # Not enabled.
801 return
802
803 now = time.time()
804 if self.last_update_check and (
805 now - self.last_update_check <
806 self.test_list.options.update_period_secs):
807 # Not yet time for another check.
808 return
809
810 self.last_update_check = now
811
812 def handle_check_for_update(reached_shopfloor, md5sum, needs_update):
813 if reached_shopfloor:
814 new_update_md5sum = md5sum if needs_update else None
Hung-Te Line594e5d2015-12-16 02:36:05 +0800815 if self.dut.info.update_md5sum != new_update_md5sum:
cychiang21886742012-07-05 15:16:32 +0800816 logging.info('Received new update MD5SUM: %s', new_update_md5sum)
Hung-Te Line594e5d2015-12-16 02:36:05 +0800817 self.dut.info.Overrides('update_md5sum', new_update_md5sum)
Peter Ammon1e1ec572014-06-26 17:56:32 -0700818 self.run_enqueue(self.update_system_info)
Cheng-Yi Chiang194d3c02015-03-16 14:37:15 +0800819 else:
820 if not self._suppress_periodic_update_messages:
821 logging.warning('Suppress error messages for periodic update checking'
822 ' after the first one.')
823 self._suppress_periodic_update_messages = True
cychiang21886742012-07-05 15:16:32 +0800824
825 updater.CheckForUpdateAsync(
Ricky Liang45c73e72015-01-15 15:00:30 +0800826 handle_check_for_update,
Cheng-Yi Chiang194d3c02015-03-16 14:37:15 +0800827 self.test_list.options.shopfloor_timeout_secs,
828 self._suppress_periodic_update_messages)
cychiang21886742012-07-05 15:16:32 +0800829
Jon Salza6711d72012-07-18 14:33:03 +0800830 def cancel_pending_tests(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800831 """Cancels any tests in the run queue."""
Jon Salza6711d72012-07-18 14:33:03 +0800832 self.run_tests([])
833
Ricky Liang4bff3e32014-02-20 18:46:11 +0800834 def restore_active_run_state(self):
835 """Restores active run id and the list of scheduled tests."""
836 self.run_id = self.state_instance.get_shared_data('run_id', optional=True)
837 self.scheduled_run_tests = self.state_instance.get_shared_data(
838 'scheduled_run_tests', optional=True)
839
840 def set_active_run_state(self):
841 """Sets active run id and the list of scheduled tests."""
842 self.run_id = str(uuid.uuid4())
843 self.scheduled_run_tests = [test.path for test in self.tests_to_run]
844 self.state_instance.set_shared_data('run_id', self.run_id)
845 self.state_instance.set_shared_data('scheduled_run_tests',
846 self.scheduled_run_tests)
847
Chih-Yu Huang85dc63c2015-08-12 15:21:28 +0800848 def run_tests(self, subtrees, status_filter=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800849 """Runs tests under subtree.
Jon Salz258a40c2012-04-19 12:34:01 +0800850
Jon Salz0697cbf2012-07-04 15:14:04 +0800851 The tests are run in order unless one fails (then stops).
852 Backgroundable tests are run simultaneously; when a foreground test is
853 encountered, we wait for all active tests to finish before continuing.
Jon Salzb1b39092012-05-03 02:05:09 +0800854
Ricky Liang6fe218c2013-12-27 15:17:17 +0800855 Args:
856 subtrees: Node or nodes containing tests to run (may either be
857 a single test or a list). Duplicates will be ignored.
Chih-Yu Huang85dc63c2015-08-12 15:21:28 +0800858 status_filter: List of available test states. Only run the tests which
859 states are in the list. Set to None if all test states are available.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800860 """
Hung-Te Lin410f70a2015-12-15 14:53:42 +0800861 self.dut.hooks.OnTestStart()
Vic Yang08505c72015-01-06 17:01:53 -0800862
Jon Salz0697cbf2012-07-04 15:14:04 +0800863 if type(subtrees) != list:
864 subtrees = [subtrees]
Jon Salz258a40c2012-04-19 12:34:01 +0800865
Jon Salz0697cbf2012-07-04 15:14:04 +0800866 # Nodes we've seen so far, to avoid duplicates.
867 seen = set()
Jon Salz94eb56f2012-06-12 18:01:12 +0800868
Jon Salz0697cbf2012-07-04 15:14:04 +0800869 self.tests_to_run = deque()
870 for subtree in subtrees:
871 for test in subtree.walk():
872 if test in seen:
873 continue
874 seen.add(test)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800875
Jon Salz0697cbf2012-07-04 15:14:04 +0800876 if not test.is_leaf():
877 continue
Chih-Yu Huang85dc63c2015-08-12 15:21:28 +0800878 if (status_filter is not None and
879 test.get_state().status not in status_filter):
Jon Salz0697cbf2012-07-04 15:14:04 +0800880 continue
881 self.tests_to_run.append(test)
Ricky Liang4bff3e32014-02-20 18:46:11 +0800882 if subtrees:
883 self.set_active_run_state()
Jon Salz0697cbf2012-07-04 15:14:04 +0800884 self.run_next_test()
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800885
Jon Salz0697cbf2012-07-04 15:14:04 +0800886 def reap_completed_tests(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800887 """Removes completed tests from the set of active tests.
Jon Salz0697cbf2012-07-04 15:14:04 +0800888
889 Also updates the visible test if it was reaped.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800890 """
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +0800891 test_completed = False
Jon Salz0697cbf2012-07-04 15:14:04 +0800892 for t, v in dict(self.invocations).iteritems():
893 if v.is_completed():
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +0800894 test_completed = True
Jon Salz1acc8742012-07-17 17:45:55 +0800895 new_state = t.update_state(**v.update_state_on_completion)
Jon Salz0697cbf2012-07-04 15:14:04 +0800896 del self.invocations[t]
897
Johny Lin62ed2a32015-05-13 11:57:12 +0800898 # Stop on failure if flag is true and there is no retry chances.
Chun-Ta Lin54e17e42012-09-06 22:05:13 +0800899 if (self.test_list.options.stop_on_failure and
Johny Lin62ed2a32015-05-13 11:57:12 +0800900 new_state.retries_left < 0 and
Chun-Ta Lin54e17e42012-09-06 22:05:13 +0800901 new_state.status == TestState.FAILED):
902 # Clean all the tests to cause goofy to stop.
903 self.tests_to_run = []
Ricky Liang45c73e72015-01-15 15:00:30 +0800904 factory.console.info('Stop on failure triggered. Empty the queue.')
Chun-Ta Lin54e17e42012-09-06 22:05:13 +0800905
Jon Salz1acc8742012-07-17 17:45:55 +0800906 if new_state.iterations_left and new_state.status == TestState.PASSED:
907 # Play it again, Sam!
908 self._run_test(t)
Cheng-Yi Chiangce05c002013-04-04 02:13:17 +0800909 # new_state.retries_left is obtained after update.
910 # For retries_left == 0, test can still be run for the last time.
911 elif (new_state.retries_left >= 0 and
912 new_state.status == TestState.FAILED):
913 # Still have to retry, Sam!
914 self._run_test(t)
Jon Salz1acc8742012-07-17 17:45:55 +0800915
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +0800916 if test_completed:
Vic Yangf01c59f2013-04-19 17:37:56 +0800917 self.log_watcher.KickWatchThread()
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +0800918
Jon Salz0697cbf2012-07-04 15:14:04 +0800919 if (self.visible_test is None or
Jon Salz85a39882012-07-05 16:45:04 +0800920 self.visible_test not in self.invocations):
Jon Salz0697cbf2012-07-04 15:14:04 +0800921 self.set_visible_test(None)
922 # Make the first running test, if any, the visible test
923 for t in self.test_list.walk():
924 if t in self.invocations:
925 self.set_visible_test(t)
926 break
927
Jon Salz6dc031d2013-06-19 13:06:23 +0800928 def kill_active_tests(self, abort, root=None, reason=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800929 """Kills and waits for all active tests.
Jon Salz0697cbf2012-07-04 15:14:04 +0800930
Jon Salz85a39882012-07-05 16:45:04 +0800931 Args:
932 abort: True to change state of killed tests to FAILED, False for
Jon Salz0697cbf2012-07-04 15:14:04 +0800933 UNTESTED.
Jon Salz85a39882012-07-05 16:45:04 +0800934 root: If set, only kills tests with root as an ancestor.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800935 reason: If set, the abort reason.
936 """
Jon Salz0697cbf2012-07-04 15:14:04 +0800937 self.reap_completed_tests()
938 for test, invoc in self.invocations.items():
Jon Salz85a39882012-07-05 16:45:04 +0800939 if root and not test.has_ancestor(root):
940 continue
941
Ricky Liang45c73e72015-01-15 15:00:30 +0800942 factory.console.info('Killing active test %s...', test.path)
Jon Salz6dc031d2013-06-19 13:06:23 +0800943 invoc.abort_and_join(reason)
Ricky Liang45c73e72015-01-15 15:00:30 +0800944 factory.console.info('Killed %s', test.path)
Jon Salz1acc8742012-07-17 17:45:55 +0800945 test.update_state(**invoc.update_state_on_completion)
Jon Salz0697cbf2012-07-04 15:14:04 +0800946 del self.invocations[test]
Jon Salz1acc8742012-07-17 17:45:55 +0800947
Jon Salz0697cbf2012-07-04 15:14:04 +0800948 if not abort:
949 test.update_state(status=TestState.UNTESTED)
950 self.reap_completed_tests()
951
Jon Salz6dc031d2013-06-19 13:06:23 +0800952 def stop(self, root=None, fail=False, reason=None):
953 self.kill_active_tests(fail, root, reason)
Jon Salz85a39882012-07-05 16:45:04 +0800954 # Remove any tests in the run queue under the root.
955 self.tests_to_run = deque([x for x in self.tests_to_run
956 if root and not x.has_ancestor(root)])
957 self.run_next_test()
Jon Salz0697cbf2012-07-04 15:14:04 +0800958
Jon Salz4712ac72013-02-07 17:12:05 +0800959 def clear_state(self, root=None):
Jon Salzd7550792013-07-12 05:49:27 +0800960 if root is None:
961 root = self.test_list
Jon Salz6dc031d2013-06-19 13:06:23 +0800962 self.stop(root, reason='Clearing test state')
Jon Salz4712ac72013-02-07 17:12:05 +0800963 for f in root.walk():
964 if f.is_leaf():
965 f.update_state(status=TestState.UNTESTED)
966
Jon Salz6dc031d2013-06-19 13:06:23 +0800967 def abort_active_tests(self, reason=None):
968 self.kill_active_tests(True, reason=reason)
Jon Salz0697cbf2012-07-04 15:14:04 +0800969
970 def main(self):
Jon Salzeff94182013-06-19 15:06:28 +0800971 syslog.openlog('goofy')
972
Jon Salz0697cbf2012-07-04 15:14:04 +0800973 try:
Jon Salzd7550792013-07-12 05:49:27 +0800974 self.status = Status.INITIALIZING
Jon Salz0697cbf2012-07-04 15:14:04 +0800975 self.init()
976 self.event_log.Log('goofy_init',
Ricky Liang45c73e72015-01-15 15:00:30 +0800977 success=True)
Chun-Ta Lin53cbbd52016-06-08 21:42:19 +0800978 testlog.Log(
Joel Kitching9eb203a2016-04-21 15:36:30 +0800979 testlog.StationInit({
Chun-Ta Lin53cbbd52016-06-08 21:42:19 +0800980 'stationDeviceId': testlog_goofy.GetDeviceID(),
Joel Kitching21bc69b2016-07-13 08:29:52 -0700981 'stationInstallationId': testlog_goofy.GetInstallationID(),
Chun-Ta Lin53cbbd52016-06-08 21:42:19 +0800982 'count': testlog_goofy.GetInitCount(),
Joel Kitching9eb203a2016-04-21 15:36:30 +0800983 'success': True}))
Jon Salz0697cbf2012-07-04 15:14:04 +0800984 except:
Joel Kitching9eb203a2016-04-21 15:36:30 +0800985 try:
986 if self.event_log:
Jon Salz0697cbf2012-07-04 15:14:04 +0800987 self.event_log.Log('goofy_init',
Ricky Liang45c73e72015-01-15 15:00:30 +0800988 success=False,
989 trace=traceback.format_exc())
Chun-Ta Lin53cbbd52016-06-08 21:42:19 +0800990 if self.testlog:
991 testlog.Log(
Joel Kitching9eb203a2016-04-21 15:36:30 +0800992 testlog.StationInit({
Chun-Ta Lin53cbbd52016-06-08 21:42:19 +0800993 'stationDeviceId': testlog_goofy.GetDeviceID(),
Joel Kitching21bc69b2016-07-13 08:29:52 -0700994 'stationInstallationId': testlog_goofy.GetInstallationID(),
Chun-Ta Lin53cbbd52016-06-08 21:42:19 +0800995 'count': testlog_goofy.GetInitCount(),
Joel Kitching9eb203a2016-04-21 15:36:30 +0800996 'success': False,
997 'failureMessage': traceback.format_exc()}))
998 except: # pylint: disable=W0702
999 pass
Jon Salz0697cbf2012-07-04 15:14:04 +08001000 raise
1001
Jon Salzd7550792013-07-12 05:49:27 +08001002 self.status = Status.RUNNING
Jon Salzeff94182013-06-19 15:06:28 +08001003 syslog.syslog('Goofy (factory test harness) starting')
Chun-Ta Lin5d12b592015-06-30 00:54:23 -07001004 syslog.syslog('Boot sequence = %d' % GetBootSequence())
Chun-Ta Lin53cbbd52016-06-08 21:42:19 +08001005 syslog.syslog('Goofy init count = %d' % testlog_goofy.GetInitCount())
Jon Salz0697cbf2012-07-04 15:14:04 +08001006 self.run()
1007
1008 def update_system_info(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001009 """Updates system info."""
Hung-Te Line594e5d2015-12-16 02:36:05 +08001010 info = self.dut.info.GetAll()
1011 self.state_instance.set_shared_data('system_info', info)
Jon Salz0697cbf2012-07-04 15:14:04 +08001012 self.event_client.post_event(Event(Event.Type.SYSTEM_INFO,
Hung-Te Line594e5d2015-12-16 02:36:05 +08001013 system_info=info))
1014 logging.info('System info: %r', info)
Jon Salz0697cbf2012-07-04 15:14:04 +08001015
Jon Salzeb42f0d2012-07-27 19:14:04 +08001016 def update_factory(self, auto_run_on_restart=False, post_update_hook=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001017 """Commences updating factory software.
Jon Salzeb42f0d2012-07-27 19:14:04 +08001018
1019 Args:
1020 auto_run_on_restart: Auto-run when the machine comes back up.
1021 post_update_hook: Code to call after update but immediately before
1022 restart.
1023
1024 Returns:
1025 Never if the update was successful (we just reboot).
1026 False if the update was unnecessary (no update available).
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001027 """
Jon Salz6dc031d2013-06-19 13:06:23 +08001028 self.kill_active_tests(False, reason='Factory software update')
Jon Salza6711d72012-07-18 14:33:03 +08001029 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +08001030
Jon Salz5c344f62012-07-13 14:31:16 +08001031 def pre_update_hook():
1032 if auto_run_on_restart:
1033 self.state_instance.set_shared_data('tests_after_shutdown',
1034 FORCE_AUTO_RUN)
1035 self.state_instance.close()
1036
Jon Salzeb42f0d2012-07-27 19:14:04 +08001037 if updater.TryUpdate(pre_update_hook=pre_update_hook):
1038 if post_update_hook:
1039 post_update_hook()
1040 self.env.shutdown('reboot')
Jon Salz0697cbf2012-07-04 15:14:04 +08001041
Ricky Liang8fecf412014-05-22 10:56:14 +08001042 def handle_sigint(self, dummy_signum, dummy_frame): # pylint: disable=W0613
Jon Salz77c151e2012-08-28 07:20:37 +08001043 logging.error('Received SIGINT')
Peter Ammon1e1ec572014-06-26 17:56:32 -07001044 self.run_enqueue(None)
Jon Salz77c151e2012-08-28 07:20:37 +08001045 raise KeyboardInterrupt()
1046
Ricky Liang8fecf412014-05-22 10:56:14 +08001047 def handle_sigterm(self, dummy_signum, dummy_frame): # pylint: disable=W0613
1048 logging.error('Received SIGTERM')
Hung-Te Lin94ca4742014-07-09 20:13:50 +08001049 self.env.terminate()
1050 self.run_queue.put(None)
Ricky Liang8fecf412014-05-22 10:56:14 +08001051 raise RuntimeError('Received SIGTERM')
1052
Jon Salze12c2b32013-06-25 16:24:34 +08001053 def find_kcrashes(self):
1054 """Finds kcrash files, logs them, and marks them as seen."""
1055 seen_crashes = set(
1056 self.state_instance.get_shared_data('seen_crashes', optional=True)
1057 or [])
1058
1059 for path in glob.glob('/var/spool/crash/*'):
1060 if not os.path.isfile(path):
1061 continue
1062 if path in seen_crashes:
1063 continue
1064 try:
1065 stat = os.stat(path)
Hung-Te Lin4e6357c2016-01-08 14:32:00 +08001066 mtime = time_utils.TimeString(stat.st_mtime)
Jon Salze12c2b32013-06-25 16:24:34 +08001067 logging.info(
1068 'Found new crash file %s (%d bytes at %s)',
1069 path, stat.st_size, mtime)
1070 extra_log_args = {}
1071
1072 try:
1073 _, ext = os.path.splitext(path)
1074 if ext in ['.kcrash', '.meta']:
1075 ext = ext.replace('.', '')
1076 with open(path) as f:
1077 data = f.read(MAX_CRASH_FILE_SIZE)
1078 tell = f.tell()
1079 logging.info(
1080 'Contents of %s%s:%s',
1081 path,
1082 ('' if tell == stat.st_size
1083 else '(truncated to %d bytes)' % MAX_CRASH_FILE_SIZE),
1084 ('\n' + data).replace('\n', '\n ' + ext + '> '))
1085 extra_log_args['data'] = data
1086
1087 # Copy to /var/factory/kcrash for posterity
Joel Kitching625ff0f2016-05-16 14:59:40 -07001088 kcrash_dir = paths.GetFactoryRoot('kcrash')
Hung-Te Lin4e6357c2016-01-08 14:32:00 +08001089 file_utils.TryMakeDirs(kcrash_dir)
Jon Salze12c2b32013-06-25 16:24:34 +08001090 shutil.copy(path, kcrash_dir)
1091 logging.info('Copied to %s',
1092 os.path.join(kcrash_dir, os.path.basename(path)))
1093 finally:
1094 # Even if something goes wrong with the above, still try to
1095 # log to event log
1096 self.event_log.Log('crash_file',
1097 path=path, size=stat.st_size, mtime=mtime,
1098 **extra_log_args)
1099 except: # pylint: disable=W0702
1100 logging.exception('Unable to handle crash files %s', path)
1101 seen_crashes.add(path)
1102
1103 self.state_instance.set_shared_data('seen_crashes', list(seen_crashes))
1104
Jon Salz128b0932013-07-03 16:55:26 +08001105 def GetTestList(self, test_list_id):
1106 """Returns the test list with the given ID.
1107
1108 Raises:
1109 TestListError: The test list ID is not valid.
1110 """
1111 try:
1112 return self.test_lists[test_list_id]
1113 except KeyError:
1114 raise test_lists.TestListError(
1115 '%r is not a valid test list ID (available IDs are [%s])' % (
1116 test_list_id, ', '.join(sorted(self.test_lists.keys()))))
1117
1118 def InitTestLists(self):
Joel Kitching50a63ea2016-02-22 13:15:09 +08001119 """Reads in all test lists and sets the active test list.
1120
1121 Returns:
1122 True if the active test list could be set, False if failed.
1123 """
1124 startup_errors = []
1125 self.test_lists, failed_files = test_lists.BuildAllTestLists(
Ricky Liang27051552014-05-04 14:22:26 +08001126 force_generic=(self.options.automation_mode is not None))
Jon Salzd7550792013-07-12 05:49:27 +08001127 logging.info('Loaded test lists: [%s]',
1128 test_lists.DescribeTestLists(self.test_lists))
Jon Salz128b0932013-07-03 16:55:26 +08001129
Joel Kitching50a63ea2016-02-22 13:15:09 +08001130 # Check for any syntax errors in test list files.
1131 if failed_files:
1132 logging.info('Failed test list files: [%s]',
1133 ' '.join(failed_files.keys()))
1134 for f, exc_info in failed_files.iteritems():
1135 logging.error('Error in test list file: %s', f,
1136 exc_info=exc_info)
1137
1138 # Limit the stack trace to the very last entry.
1139 exc_type, exc_value, exc_traceback = exc_info
1140 while exc_traceback and exc_traceback.tb_next:
1141 exc_traceback = exc_traceback.tb_next
1142
1143 exc_string = ''.join(
1144 traceback.format_exception(
1145 exc_type, exc_value, exc_traceback)).rstrip()
1146 startup_errors.append('Error in test list file (%s):\n%s'
1147 % (f, exc_string))
1148
Jon Salz128b0932013-07-03 16:55:26 +08001149 if not self.options.test_list:
1150 self.options.test_list = test_lists.GetActiveTestListId()
1151
Joel Kitching50a63ea2016-02-22 13:15:09 +08001152 # Check for a non-existent test list ID.
1153 try:
Wei-Han Chen84fee7c2016-08-26 21:56:25 +08001154 self.test_list = self.GetTestList(self.options.test_list)
Joel Kitching50a63ea2016-02-22 13:15:09 +08001155 logging.info('Active test list: %s', self.test_list.test_list_id)
1156 except test_lists.TestListError as e:
1157 logging.exception('Invalid active test list: %s',
1158 self.options.test_list)
1159 startup_errors.append(e.message)
Jon Salz128b0932013-07-03 16:55:26 +08001160
Joel Kitching50a63ea2016-02-22 13:15:09 +08001161 # We may have failed loading the active test list.
1162 if self.test_list:
Joel Kitching50a63ea2016-02-22 13:15:09 +08001163 self.test_list.state_instance = self.state_instance
Jon Salz128b0932013-07-03 16:55:26 +08001164
Joel Kitching50a63ea2016-02-22 13:15:09 +08001165 # Prepare DUT link.
1166 if self.test_list.options.dut_options:
1167 logging.info('dut_options set by %s: %r', self.test_list.test_list_id,
1168 self.test_list.options.dut_options)
Hung-Te Linb6287242016-05-18 14:39:05 +08001169 device_utils.PrepareDUTLink(**self.test_list.options.dut_options)
Wei-Han Chene8a025f2016-01-14 16:42:02 +08001170
Joel Kitching50a63ea2016-02-22 13:15:09 +08001171 # Show all startup errors.
1172 if startup_errors:
1173 self.state_instance.set_shared_data(
1174 'startup_error', '\n\n'.join(startup_errors))
1175
1176 # Only return False if failed to load the active test list.
1177 return bool(self.test_list)
Jon Salz128b0932013-07-03 16:55:26 +08001178
Shuo-Peng Liao268b40b2013-07-01 15:58:59 +08001179 def init_hooks(self):
1180 """Initializes hooks.
1181
1182 Must run after self.test_list ready.
1183 """
Shuo-Peng Liao52b90da2013-06-30 17:00:06 +08001184 module, cls = self.test_list.options.hooks_class.rsplit('.', 1)
1185 self.hooks = getattr(__import__(module, fromlist=[cls]), cls)()
1186 assert isinstance(self.hooks, factory.Hooks), (
Ricky Liang45c73e72015-01-15 15:00:30 +08001187 'hooks should be of type Hooks but is %r' % type(self.hooks))
Shuo-Peng Liao52b90da2013-06-30 17:00:06 +08001188 self.hooks.test_list = self.test_list
Shuo-Peng Liao268b40b2013-07-01 15:58:59 +08001189 self.hooks.OnCreatedTestList()
Shuo-Peng Liao52b90da2013-06-30 17:00:06 +08001190
Vic Yanga3cecf82014-12-26 00:44:21 -08001191 def init_ui(self):
1192 """Initialize UI."""
1193 self._ui_initialized = True
1194 if self.options.ui == 'chrome':
Hung-Te Lin8f6a3782015-01-06 22:58:32 +08001195 if self.options.monolithic:
Hung-Te Lin7bd55312014-12-30 16:43:36 +08001196 self.env.launch_chrome()
1197 else:
1198 # The presenter is responsible for launching Chrome. Let's just
1199 # wait here.
1200 self.env.controller_ready_for_ui()
Vic Yanga3cecf82014-12-26 00:44:21 -08001201 logging.info('Waiting for a web socket connection')
1202 self.web_socket_manager.wait()
1203
1204 # Wait for the test widget size to be set; this is done in
1205 # an asynchronous RPC so there is a small chance that the
1206 # web socket might be opened first.
1207 for _ in range(100): # 10 s
1208 try:
1209 if self.state_instance.get_shared_data('test_widget_size'):
1210 break
1211 except KeyError:
1212 pass # Retry
1213 time.sleep(0.1) # 100 ms
1214 else:
1215 logging.warn('Never received test_widget_size from UI')
1216
Jon Salz0697cbf2012-07-04 15:14:04 +08001217 def init(self, args=None, env=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001218 """Initializes Goofy.
Jon Salz0697cbf2012-07-04 15:14:04 +08001219
1220 Args:
1221 args: A list of command-line arguments. Uses sys.argv if
1222 args is None.
1223 env: An Environment instance to use (or None to choose
1224 FakeChrootEnvironment or DUTEnvironment as appropriate).
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001225 """
Jon Salz0697cbf2012-07-04 15:14:04 +08001226 parser = OptionParser()
1227 parser.add_option('-v', '--verbose', dest='verbose',
Jon Salz8fa8e832012-07-13 19:04:09 +08001228 action='store_true',
1229 help='Enable debug logging')
Jon Salz0697cbf2012-07-04 15:14:04 +08001230 parser.add_option('--print_test_list', dest='print_test_list',
Wei-Han Chen84fee7c2016-08-26 21:56:25 +08001231 metavar='TEST_LIST_ID',
1232 help='Print the content of TEST_LIST_ID and exit')
Jon Salz0697cbf2012-07-04 15:14:04 +08001233 parser.add_option('--restart', dest='restart',
Jon Salz8fa8e832012-07-13 19:04:09 +08001234 action='store_true',
1235 help='Clear all test state')
Jon Salz0697cbf2012-07-04 15:14:04 +08001236 parser.add_option('--ui', dest='ui', type='choice',
Jon Salz7b5482e2014-08-04 17:48:41 +08001237 choices=['none', 'chrome'],
Jon Salz2f881df2013-02-01 17:00:35 +08001238 default='chrome',
Jon Salz8fa8e832012-07-13 19:04:09 +08001239 help='UI to use')
Jon Salz0697cbf2012-07-04 15:14:04 +08001240 parser.add_option('--ui_scale_factor', dest='ui_scale_factor',
Jon Salz8fa8e832012-07-13 19:04:09 +08001241 type='int', default=1,
1242 help=('Factor by which to scale UI '
1243 '(Chrome UI only)'))
Jon Salz0697cbf2012-07-04 15:14:04 +08001244 parser.add_option('--test_list', dest='test_list',
Wei-Han Chen84fee7c2016-08-26 21:56:25 +08001245 metavar='TEST_LIST_ID',
1246 help='Use test list whose id is TEST_LIST_ID')
Jon Salzc79a9982012-08-30 04:42:01 +08001247 parser.add_option('--dummy_shopfloor', action='store_true',
1248 help='Use a dummy shopfloor server')
Ricky Liang6fe218c2013-12-27 15:17:17 +08001249 parser.add_option('--automation-mode',
1250 choices=[m.lower() for m in AutomationMode],
Ricky Liang45c73e72015-01-15 15:00:30 +08001251 default='none', help='Factory test automation mode.')
Ricky Liang117484a2014-04-14 11:14:41 +08001252 parser.add_option('--no-auto-run-on-start', dest='auto_run_on_start',
1253 action='store_false', default=True,
1254 help=('do not automatically run the test list on goofy '
1255 'start; this is only valid when factory test '
1256 'automation is enabled'))
Chun-Ta Lina8dd3172014-11-26 16:15:13 +08001257 parser.add_option('--handshake_timeout', dest='handshake_timeout',
1258 type='float', default=0.3,
1259 help=('RPC timeout when doing handshake between device '
1260 'and presenter.'))
Vic Yang7d693c42014-09-14 09:52:39 +08001261 parser.add_option('--standalone', dest='standalone',
1262 action='store_true', default=False,
1263 help=('Assume the presenter is running on the same '
1264 'machines.'))
Hung-Te Lin8f6a3782015-01-06 22:58:32 +08001265 parser.add_option('--monolithic', dest='monolithic',
1266 action='store_true', default=False,
1267 help='Run in monolithic mode (without presenter)')
Jon Salz0697cbf2012-07-04 15:14:04 +08001268 (self.options, self.args) = parser.parse_args(args)
1269
Hung-Te Lina846f602014-07-04 20:32:22 +08001270 signal.signal(signal.SIGINT, self.handle_sigint)
1271 # TODO(hungte) SIGTERM does not work properly without Telemetry and should
1272 # be fixed.
Hung-Te Lina846f602014-07-04 20:32:22 +08001273
Jon Salz46b89562012-07-05 11:49:22 +08001274 # Make sure factory directories exist.
Joel Kitching625ff0f2016-05-16 14:59:40 -07001275 paths.GetLogRoot()
1276 paths.GetStateRoot()
1277 paths.GetTestDataRoot()
Jon Salz46b89562012-07-05 11:49:22 +08001278
Jon Salz0697cbf2012-07-04 15:14:04 +08001279 global _inited_logging # pylint: disable=W0603
1280 if not _inited_logging:
1281 factory.init_logging('goofy', verbose=self.options.verbose)
1282 _inited_logging = True
Jon Salz8fa8e832012-07-13 19:04:09 +08001283
Jon Salz0f996602012-10-03 15:26:48 +08001284 if self.options.print_test_list:
Wei-Han Chen84fee7c2016-08-26 21:56:25 +08001285 test_list = test_lists.BuildTestList(self.options.print_test_list)
1286 print(test_list.__repr__(recursive=True))
Jon Salz0f996602012-10-03 15:26:48 +08001287 sys.exit(0)
1288
Jon Salzee85d522012-07-17 14:34:46 +08001289 event_log.IncrementBootSequence()
Chun-Ta Lin53cbbd52016-06-08 21:42:19 +08001290 testlog_goofy.IncrementInitCount()
1291
Jon Salzd15bbcf2013-05-21 17:33:57 +08001292 # Don't defer logging the initial event, so we can make sure
1293 # that device_id, reimage_id, etc. are all set up.
1294 self.event_log = EventLog('goofy', defer=False)
Chun-Ta Lin53cbbd52016-06-08 21:42:19 +08001295 self.testlog = testlog.Testlog(
1296 log_root=paths.GetLogRoot(), uuid=self.uuid)
1297 # Direct the logging calls to testlog as well.
1298 testlog.CapturePythonLogging(
1299 callback=self.testlog.primary_json.Log,
1300 level=logging.getLogger().getEffectiveLevel())
Jon Salz0697cbf2012-07-04 15:14:04 +08001301
Jon Salz0697cbf2012-07-04 15:14:04 +08001302 if env:
1303 self.env = env
Hung-Te Linf5f2d7f2016-01-08 17:12:46 +08001304 elif sys_utils.InChroot():
Jon Salz0697cbf2012-07-04 15:14:04 +08001305 self.env = test_environment.FakeChrootEnvironment()
1306 logging.warn(
Ricky Liang45c73e72015-01-15 15:00:30 +08001307 'Using chroot environment: will not actually run autotests')
Hung-Te Lina846f602014-07-04 20:32:22 +08001308 elif self.options.ui == 'chrome':
Ricky Liang09d66d82014-09-25 11:20:54 +08001309 self.env = test_environment.DUTEnvironment()
Jon Salz0697cbf2012-07-04 15:14:04 +08001310 self.env.goofy = self
Vic Yanga4931152014-08-11 16:36:24 -07001311 # web_socket_manager will be initialized later
1312 # pylint: disable=W0108
1313 self.env.has_sockets = lambda: self.web_socket_manager.has_sockets()
Jon Salz0697cbf2012-07-04 15:14:04 +08001314
1315 if self.options.restart:
1316 state.clear_state()
1317
Hung-Te Linf5f2d7f2016-01-08 17:12:46 +08001318 if self.options.ui_scale_factor != 1 and sys_utils.InQEMU():
Jon Salz0697cbf2012-07-04 15:14:04 +08001319 logging.warn(
Ricky Liang45c73e72015-01-15 15:00:30 +08001320 'In QEMU; ignoring ui_scale_factor argument')
Jon Salz0697cbf2012-07-04 15:14:04 +08001321 self.options.ui_scale_factor = 1
1322
1323 logging.info('Started')
1324
Hung-Te Lin8f6a3782015-01-06 22:58:32 +08001325 if not self.options.monolithic:
Hung-Te Lin7bd55312014-12-30 16:43:36 +08001326 self.link_manager = PresenterLinkManager(
1327 check_interval=1,
1328 handshake_timeout=self.options.handshake_timeout,
1329 standalone=self.options.standalone)
Peter Ammon1e1ec572014-06-26 17:56:32 -07001330
Jon Salz0697cbf2012-07-04 15:14:04 +08001331 self.start_state_server()
1332 self.state_instance.set_shared_data('hwid_cfg', get_hwid_cfg())
1333 self.state_instance.set_shared_data('ui_scale_factor',
Ricky Liang09216dc2013-02-22 17:26:45 +08001334 self.options.ui_scale_factor)
Jon Salz0697cbf2012-07-04 15:14:04 +08001335 self.last_shutdown_time = (
Ricky Liang45c73e72015-01-15 15:00:30 +08001336 self.state_instance.get_shared_data('shutdown_time', optional=True))
Jon Salz0697cbf2012-07-04 15:14:04 +08001337 self.state_instance.del_shared_data('shutdown_time', optional=True)
Jon Salzb19ea072013-02-07 16:35:00 +08001338 self.state_instance.del_shared_data('startup_error', optional=True)
Jon Salz0697cbf2012-07-04 15:14:04 +08001339
Ricky Liang6fe218c2013-12-27 15:17:17 +08001340 self.options.automation_mode = ParseAutomationMode(
1341 self.options.automation_mode)
1342 self.state_instance.set_shared_data('automation_mode',
1343 self.options.automation_mode)
1344 self.state_instance.set_shared_data(
1345 'automation_mode_prompt',
1346 AutomationModePrompt[self.options.automation_mode])
1347
Joel Kitching50a63ea2016-02-22 13:15:09 +08001348 success = False
1349 exc_info = None
Jon Salz128b0932013-07-03 16:55:26 +08001350 try:
Joel Kitching50a63ea2016-02-22 13:15:09 +08001351 success = self.InitTestLists()
Jon Salz128b0932013-07-03 16:55:26 +08001352 except: # pylint: disable=W0702
Joel Kitching50a63ea2016-02-22 13:15:09 +08001353 exc_info = sys.exc_info()
1354
1355 if not success:
1356 if exc_info:
1357 logging.exception('Unable to initialize test lists')
1358 self.state_instance.set_shared_data(
1359 'startup_error',
1360 'Unable to initialize test lists\n%s' % (
1361 traceback.format_exc()))
Jon Salzb19ea072013-02-07 16:35:00 +08001362 if self.options.ui == 'chrome':
1363 # Create an empty test list with default options so that the rest of
1364 # startup can proceed.
1365 self.test_list = factory.FactoryTestList(
1366 [], self.state_instance, factory.Options())
1367 else:
1368 # Bail with an error; no point in starting up.
1369 sys.exit('No valid test list; exiting.')
1370
Shuo-Peng Liao268b40b2013-07-01 15:58:59 +08001371 self.init_hooks()
1372
Jon Salz822838b2013-03-25 17:32:33 +08001373 if self.test_list.options.clear_state_on_start:
1374 self.state_instance.clear_test_state()
1375
Jon Salz670ce062014-05-16 15:53:50 +08001376 # If the phase is invalid, this will raise a ValueError.
1377 phase.SetPersistentPhase(self.test_list.options.phase)
1378
Dean Liao85ca86f2014-11-03 12:28:08 +08001379 # For netboot firmware, mainfw_type should be 'netboot'.
Hung-Te Line594e5d2015-12-16 02:36:05 +08001380 if (self.dut.info.mainfw_type != 'nonchrome' and
1381 self.dut.info.firmware_version is None):
Ricky Liang45c73e72015-01-15 15:00:30 +08001382 self.state_instance.set_shared_data(
1383 'startup_error',
Vic Yang9bd4f772013-06-04 17:34:00 +08001384 'Netboot firmware detected\n'
1385 'Connect Ethernet and reboot to re-image.\n'
1386 u'侦测到网路开机固件\n'
1387 u'请连接乙太网并重启')
1388
Jon Salz0697cbf2012-07-04 15:14:04 +08001389 if not self.state_instance.has_shared_data('ui_lang'):
1390 self.state_instance.set_shared_data('ui_lang',
Ricky Liang45c73e72015-01-15 15:00:30 +08001391 self.test_list.options.ui_lang)
Jon Salz0697cbf2012-07-04 15:14:04 +08001392 self.state_instance.set_shared_data(
Ricky Liang45c73e72015-01-15 15:00:30 +08001393 'test_list_options',
1394 self.test_list.options.__dict__)
Jon Salz0697cbf2012-07-04 15:14:04 +08001395 self.state_instance.test_list = self.test_list
1396
Cheng-Yi Chiang39d32ad2013-07-23 15:02:38 +08001397 self.check_log_rotation()
Jon Salz83ef34b2012-11-01 19:46:35 +08001398
Jon Salz23926422012-09-01 03:38:13 +08001399 if self.options.dummy_shopfloor:
Ricky Liang45c73e72015-01-15 15:00:30 +08001400 os.environ[shopfloor.SHOPFLOOR_SERVER_ENV_VAR_NAME] = (
1401 'http://%s:%d/' %
Joel Kitchingb85ed7f2014-10-08 18:24:39 +08001402 (net_utils.LOCALHOST, shopfloor.DEFAULT_SERVER_PORT))
Hung-Te Lin4e6357c2016-01-08 14:32:00 +08001403 self.dummy_shopfloor = process_utils.Spawn(
Wei-Han Chen2ebb92d2016-01-12 14:51:41 +08001404 [os.path.join(paths.FACTORY_PATH, 'bin', 'shopfloor_server'),
Jon Salz23926422012-09-01 03:38:13 +08001405 '--dummy'])
1406 elif self.test_list.options.shopfloor_server_url:
1407 shopfloor.set_server_url(self.test_list.options.shopfloor_server_url)
Jon Salz2bf2f6b2013-03-28 18:49:26 +08001408 shopfloor.set_enabled(True)
Jon Salz23926422012-09-01 03:38:13 +08001409
Jon Salz0697cbf2012-07-04 15:14:04 +08001410 self.init_states()
1411 self.start_event_server()
Wei-Ning Huang38b75f02015-02-25 18:25:14 +08001412 self.start_terminal_server()
Hung-Te Lincc41d2a2014-10-29 13:35:20 +08001413
Earl Oua3bca122016-10-21 16:00:30 +08001414 # Load and run Goofy plugins.
1415 self.plugin_controller = plugin_controller.PluginController(
1416 self.test_list.options.plugin_config_name, self)
1417 self.plugin_controller.StartAllPlugins()
1418
Jon Salz0697cbf2012-07-04 15:14:04 +08001419 # Note that we create a log watcher even if
1420 # sync_event_log_period_secs isn't set (no background
1421 # syncing), since we may use it to flush event logs as well.
1422 self.log_watcher = EventLogWatcher(
Ricky Liang45c73e72015-01-15 15:00:30 +08001423 self.test_list.options.sync_event_log_period_secs,
1424 event_log_db_file=None,
1425 handle_event_logs_callback=self.handle_event_logs)
Jon Salz0697cbf2012-07-04 15:14:04 +08001426 if self.test_list.options.sync_event_log_period_secs:
1427 self.log_watcher.StartWatchThread()
1428
1429 self.update_system_info()
1430
1431 os.environ['CROS_FACTORY'] = '1'
1432 os.environ['CROS_DISABLE_SITE_SYSINFO'] = '1'
1433
Justin Chuang31b02432013-06-27 15:16:51 +08001434 # Startup hooks may want to skip some tests.
1435 self.update_skipped_tests()
Jon Salz416f9cc2013-05-10 18:32:50 +08001436
Jon Salze12c2b32013-06-25 16:24:34 +08001437 self.find_kcrashes()
1438
Shuo-Peng Liao268b40b2013-07-01 15:58:59 +08001439 # Should not move earlier.
1440 self.hooks.OnStartup()
1441
Ricky Liang36512a32014-07-25 11:47:04 +08001442 # Only after this point the Goofy backend is ready for UI connection.
1443 self.ready_for_ui_connection = True
1444
Ricky Liang650f6bf2012-09-28 13:22:54 +08001445 # Create download path for autotest beforehand or autotests run at
1446 # the same time might fail due to race condition.
Hung-Te Linf5f2d7f2016-01-08 17:12:46 +08001447 if not sys_utils.InChroot():
Hung-Te Lin4e6357c2016-01-08 14:32:00 +08001448 file_utils.TryMakeDirs(os.path.join('/usr/local/autotest', 'tests',
1449 'download'))
Ricky Liang650f6bf2012-09-28 13:22:54 +08001450
Jon Salz0697cbf2012-07-04 15:14:04 +08001451 def state_change_callback(test, test_state):
1452 self.event_client.post_event(
Ricky Liang4bff3e32014-02-20 18:46:11 +08001453 Event(Event.Type.STATE_CHANGE, path=test.path, state=test_state))
Jon Salz0697cbf2012-07-04 15:14:04 +08001454 self.test_list.state_change_callback = state_change_callback
Jon Salz73e0fd02012-04-04 11:46:38 +08001455
Vic Yange2c76a82014-10-30 12:48:19 -07001456 self.autotest_prespawner = prespawner.AutotestPrespawner()
1457 self.autotest_prespawner.start()
1458
1459 self.pytest_prespawner = prespawner.PytestPrespawner()
1460 self.pytest_prespawner.start()
Jon Salza6711d72012-07-18 14:33:03 +08001461
Ricky Liang48e47f92014-02-26 19:31:51 +08001462 tests_after_shutdown = self.state_instance.get_shared_data(
1463 'tests_after_shutdown', optional=True)
Jon Salz57717ca2012-04-04 16:47:25 +08001464
Jon Salz5c344f62012-07-13 14:31:16 +08001465 force_auto_run = (tests_after_shutdown == FORCE_AUTO_RUN)
1466 if not force_auto_run and tests_after_shutdown is not None:
Ricky Liang48e47f92014-02-26 19:31:51 +08001467 logging.info('Resuming tests after shutdown: %s', tests_after_shutdown)
Jon Salz0697cbf2012-07-04 15:14:04 +08001468 self.tests_to_run.extend(
Ricky Liang4bff3e32014-02-20 18:46:11 +08001469 self.test_list.lookup_path(t) for t in tests_after_shutdown)
Peter Ammon1e1ec572014-06-26 17:56:32 -07001470 self.run_enqueue(self.run_next_test)
Jon Salz0697cbf2012-07-04 15:14:04 +08001471 else:
Jon Salz5c344f62012-07-13 14:31:16 +08001472 if force_auto_run or self.test_list.options.auto_run_on_start:
Ricky Liang117484a2014-04-14 11:14:41 +08001473 # If automation mode is enabled, allow suppress auto_run_on_start.
1474 if (self.options.automation_mode == 'NONE' or
1475 self.options.auto_run_on_start):
Chih-Yu Huang85dc63c2015-08-12 15:21:28 +08001476 status_filter = [TestState.UNTESTED]
1477 if self.test_list.options.retry_failed_on_start:
1478 status_filter.append(TestState.FAILED)
1479 self.run_enqueue(lambda: self.run_tests(self.test_list, status_filter))
Jon Salz5c344f62012-07-13 14:31:16 +08001480 self.state_instance.set_shared_data('tests_after_shutdown', None)
Ricky Liang4bff3e32014-02-20 18:46:11 +08001481 self.restore_active_run_state()
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001482
Hung-Te Lin410f70a2015-12-15 14:53:42 +08001483 self.dut.hooks.OnTestStart()
Vic Yang08505c72015-01-06 17:01:53 -08001484
Dean Liao592e4d52013-01-10 20:06:39 +08001485 self.may_disable_cros_shortcut_keys()
1486
1487 def may_disable_cros_shortcut_keys(self):
1488 test_options = self.test_list.options
1489 if test_options.disable_cros_shortcut_keys:
1490 logging.info('Filter ChromeOS shortcut keys.')
1491 self.key_filter = KeyFilter(
1492 unmap_caps_lock=test_options.disable_caps_lock,
1493 caps_lock_keycode=test_options.caps_lock_keycode)
1494 self.key_filter.Start()
1495
Cheng-Yi Chiang39d32ad2013-07-23 15:02:38 +08001496 def check_log_rotation(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001497 """Checks log rotation file presence/absence according to test_list option.
Cheng-Yi Chiang39d32ad2013-07-23 15:02:38 +08001498
1499 Touch /var/lib/cleanup_logs_paused if test_list.options.disable_log_rotation
1500 is True, delete it otherwise. This must be done in idle loop because
1501 autotest client will touch /var/lib/cleanup_logs_paused each time it runs
1502 an autotest.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001503 """
Hung-Te Linf5f2d7f2016-01-08 17:12:46 +08001504 if sys_utils.InChroot():
Cheng-Yi Chiang39d32ad2013-07-23 15:02:38 +08001505 return
1506 try:
1507 if self.test_list.options.disable_log_rotation:
1508 open(CLEANUP_LOGS_PAUSED, 'w').close()
1509 else:
1510 file_utils.TryUnlink(CLEANUP_LOGS_PAUSED)
1511 except: # pylint: disable=W0702
1512 # Oh well. Logs an error (but no trace)
1513 logging.info(
1514 'Unable to %s %s: %s',
1515 'touch' if self.test_list.options.disable_log_rotation else 'delete',
Hung-Te Linf707b242016-01-08 23:11:42 +08001516 CLEANUP_LOGS_PAUSED, debug_utils.FormatExceptionOnly())
Cheng-Yi Chiang39d32ad2013-07-23 15:02:38 +08001517
Peter Ammon1e1ec572014-06-26 17:56:32 -07001518 def perform_periodic_tasks(self):
1519 """Override of base method to perform periodic work.
Vic Yang4953fc12012-07-26 16:19:53 +08001520
Peter Ammon1e1ec572014-06-26 17:56:32 -07001521 This method must not raise exceptions.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001522 """
Peter Ammon1e1ec572014-06-26 17:56:32 -07001523 super(Goofy, self).perform_periodic_tasks()
Jon Salzb22d1172012-08-06 10:38:57 +08001524
Earl Oua3bca122016-10-21 16:00:30 +08001525 self.check_plugins()
cychiang21886742012-07-05 15:16:32 +08001526 self.check_for_updates()
Cheng-Yi Chiang39d32ad2013-07-23 15:02:38 +08001527 self.check_log_rotation()
Jon Salz57717ca2012-04-04 16:47:25 +08001528
Cheng-Yi Chiangf5b21012015-03-17 15:37:14 +08001529 def handle_event_logs(self, chunks, periodic=False):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001530 """Callback for event watcher.
Jon Salz258a40c2012-04-19 12:34:01 +08001531
Jon Salz0697cbf2012-07-04 15:14:04 +08001532 Attempts to upload the event logs to the shopfloor server.
Vic Yang93027612013-05-06 02:42:49 +08001533
1534 Args:
Jon Salzd15bbcf2013-05-21 17:33:57 +08001535 chunks: A list of Chunk objects.
Cheng-Yi Chiangf5b21012015-03-17 15:37:14 +08001536 periodic: This event log handling is periodic. Error messages
1537 will only be shown for the first time.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001538 """
Vic Yang93027612013-05-06 02:42:49 +08001539 first_exception = None
1540 exception_count = 0
Cheng-Yi Chiangf5b21012015-03-17 15:37:14 +08001541 # Suppress error messages for periodic event syncing except for the
1542 # first time. If event syncing is not periodic, always show the error
1543 # messages.
1544 quiet = self._suppress_event_log_error_messages if periodic else False
Vic Yang93027612013-05-06 02:42:49 +08001545
Jon Salzd15bbcf2013-05-21 17:33:57 +08001546 for chunk in chunks:
Vic Yang93027612013-05-06 02:42:49 +08001547 try:
Jon Salzcddb6402013-05-23 12:56:42 +08001548 description = 'event logs (%s)' % str(chunk)
Vic Yang93027612013-05-06 02:42:49 +08001549 start_time = time.time()
1550 shopfloor_client = shopfloor.get_instance(
Ricky Liang45c73e72015-01-15 15:00:30 +08001551 detect=True,
Cheng-Yi Chiangf5b21012015-03-17 15:37:14 +08001552 timeout=self.test_list.options.shopfloor_timeout_secs,
1553 quiet=quiet)
Ricky Liang45c73e72015-01-15 15:00:30 +08001554 shopfloor_client.UploadEvent(chunk.log_name + '.' +
Jon Salzd15bbcf2013-05-21 17:33:57 +08001555 event_log.GetReimageId(),
1556 Binary(chunk.chunk))
Vic Yang93027612013-05-06 02:42:49 +08001557 logging.info(
Ricky Liang45c73e72015-01-15 15:00:30 +08001558 'Successfully synced %s in %.03f s',
1559 description, time.time() - start_time)
1560 except: # pylint: disable=W0702
Hung-Te Linf707b242016-01-08 23:11:42 +08001561 first_exception = (first_exception or
1562 (chunk.log_name + ': ' +
1563 debug_utils.FormatExceptionOnly()))
Vic Yang93027612013-05-06 02:42:49 +08001564 exception_count += 1
1565
1566 if exception_count:
1567 if exception_count == 1:
1568 msg = 'Log upload failed: %s' % first_exception
1569 else:
1570 msg = '%d log upload failed; first is: %s' % (
1571 exception_count, first_exception)
Cheng-Yi Chiangf5b21012015-03-17 15:37:14 +08001572 # For periodic event log syncing, only show the first error messages.
1573 if periodic:
1574 if not self._suppress_event_log_error_messages:
1575 self._suppress_event_log_error_messages = True
1576 logging.warning('Suppress periodic shopfloor error messages for '
1577 'event log syncing after the first one.')
1578 raise Exception(msg)
1579 # For event log syncing by request, show the error messages.
1580 else:
1581 raise Exception(msg)
Vic Yang93027612013-05-06 02:42:49 +08001582
Ricky Liang45c73e72015-01-15 15:00:30 +08001583 def run_tests_with_status(self, statuses_to_run, starting_at=None, root=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001584 """Runs all top-level tests with a particular status.
Jon Salz0405ab52012-03-16 15:26:52 +08001585
Jon Salz0697cbf2012-07-04 15:14:04 +08001586 All active tests, plus any tests to re-run, are reset.
Jon Salz57717ca2012-04-04 16:47:25 +08001587
Jon Salz0697cbf2012-07-04 15:14:04 +08001588 Args:
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001589 statuses_to_run: The particular status that caller wants to run.
Jon Salz0697cbf2012-07-04 15:14:04 +08001590 starting_at: If provided, only auto-runs tests beginning with
1591 this test.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001592 root: The root of tests to run. If not provided, it will be
1593 the root of all tests.
1594 """
Jon Salz0697cbf2012-07-04 15:14:04 +08001595 root = root or self.test_list
Jon Salz57717ca2012-04-04 16:47:25 +08001596
Jon Salz0697cbf2012-07-04 15:14:04 +08001597 if starting_at:
1598 # Make sure they passed a test, not a string.
1599 assert isinstance(starting_at, factory.FactoryTest)
Jon Salz0405ab52012-03-16 15:26:52 +08001600
Jon Salz0697cbf2012-07-04 15:14:04 +08001601 tests_to_reset = []
1602 tests_to_run = []
Jon Salz0405ab52012-03-16 15:26:52 +08001603
Jon Salz0697cbf2012-07-04 15:14:04 +08001604 found_starting_at = False
Jon Salz0405ab52012-03-16 15:26:52 +08001605
Jon Salz0697cbf2012-07-04 15:14:04 +08001606 for test in root.get_top_level_tests():
1607 if starting_at:
1608 if test == starting_at:
1609 # We've found starting_at; do auto-run on all
1610 # subsequent tests.
1611 found_starting_at = True
1612 if not found_starting_at:
1613 # Don't start this guy yet
1614 continue
Jon Salz0405ab52012-03-16 15:26:52 +08001615
Jon Salz0697cbf2012-07-04 15:14:04 +08001616 status = test.get_state().status
1617 if status == TestState.ACTIVE or status in statuses_to_run:
1618 # Reset the test (later; we will need to abort
1619 # all active tests first).
1620 tests_to_reset.append(test)
1621 if status in statuses_to_run:
1622 tests_to_run.append(test)
Jon Salz0405ab52012-03-16 15:26:52 +08001623
Jon Salz6dc031d2013-06-19 13:06:23 +08001624 self.abort_active_tests('Operator requested run/re-run of certain tests')
Jon Salz258a40c2012-04-19 12:34:01 +08001625
Jon Salz0697cbf2012-07-04 15:14:04 +08001626 # Reset all statuses of the tests to run (in case any tests were active;
1627 # we want them to be run again).
1628 for test_to_reset in tests_to_reset:
1629 for test in test_to_reset.walk():
1630 test.update_state(status=TestState.UNTESTED)
Jon Salz57717ca2012-04-04 16:47:25 +08001631
Chih-Yu Huang85dc63c2015-08-12 15:21:28 +08001632 self.run_tests(tests_to_run, [TestState.UNTESTED])
Jon Salz0405ab52012-03-16 15:26:52 +08001633
Jon Salz0697cbf2012-07-04 15:14:04 +08001634 def restart_tests(self, root=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001635 """Restarts all tests."""
Jon Salz0697cbf2012-07-04 15:14:04 +08001636 root = root or self.test_list
Jon Salz0405ab52012-03-16 15:26:52 +08001637
Jon Salz6dc031d2013-06-19 13:06:23 +08001638 self.abort_active_tests('Operator requested restart of certain tests')
Jon Salz0697cbf2012-07-04 15:14:04 +08001639 for test in root.walk():
Ricky Liangfea4ac92014-08-21 11:55:59 +08001640 test.update_state(status=TestState.UNTESTED)
Jon Salz0697cbf2012-07-04 15:14:04 +08001641 self.run_tests(root)
Hung-Te Lin96632362012-03-20 21:14:18 +08001642
Jon Salz0697cbf2012-07-04 15:14:04 +08001643 def auto_run(self, starting_at=None, root=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001644 """"Auto-runs" tests that have not been run yet.
Hung-Te Lin96632362012-03-20 21:14:18 +08001645
Jon Salz0697cbf2012-07-04 15:14:04 +08001646 Args:
1647 starting_at: If provide, only auto-runs tests beginning with
1648 this test.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001649 root: If provided, the root of tests to run. If not provided, the root
1650 will be test_list (root of all tests).
1651 """
Jon Salz0697cbf2012-07-04 15:14:04 +08001652 root = root or self.test_list
1653 self.run_tests_with_status([TestState.UNTESTED, TestState.ACTIVE],
Ricky Liang45c73e72015-01-15 15:00:30 +08001654 starting_at=starting_at,
1655 root=root)
Jon Salz968e90b2012-03-18 16:12:43 +08001656
Jon Salz0697cbf2012-07-04 15:14:04 +08001657 def handle_switch_test(self, event):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001658 """Switches to a particular test.
Jon Salz0405ab52012-03-16 15:26:52 +08001659
Ricky Liang6fe218c2013-12-27 15:17:17 +08001660 Args:
1661 event: The SWITCH_TEST event.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001662 """
Jon Salz0697cbf2012-07-04 15:14:04 +08001663 test = self.test_list.lookup_path(event.path)
1664 if not test:
1665 logging.error('Unknown test %r', event.key)
1666 return
Jon Salz73e0fd02012-04-04 11:46:38 +08001667
Jon Salz0697cbf2012-07-04 15:14:04 +08001668 invoc = self.invocations.get(test)
1669 if invoc and test.backgroundable:
1670 # Already running: just bring to the front if it
1671 # has a UI.
1672 logging.info('Setting visible test to %s', test.path)
Jon Salz36fbbb52012-07-05 13:45:06 +08001673 self.set_visible_test(test)
Jon Salz0697cbf2012-07-04 15:14:04 +08001674 return
Jon Salz73e0fd02012-04-04 11:46:38 +08001675
Jon Salz6dc031d2013-06-19 13:06:23 +08001676 self.abort_active_tests('Operator requested abort (switch_test)')
Jon Salz0697cbf2012-07-04 15:14:04 +08001677 for t in test.walk():
1678 t.update_state(status=TestState.UNTESTED)
Jon Salz73e0fd02012-04-04 11:46:38 +08001679
Jon Salz0697cbf2012-07-04 15:14:04 +08001680 if self.test_list.options.auto_run_on_keypress:
1681 self.auto_run(starting_at=test)
1682 else:
1683 self.run_tests(test)
Jon Salz73e0fd02012-04-04 11:46:38 +08001684
Wei-Ning Huang38b75f02015-02-25 18:25:14 +08001685 def handle_key_filter_mode(self, event):
1686 if self.key_filter:
1687 if getattr(event, 'enabled'):
1688 self.key_filter.Start()
1689 else:
1690 self.key_filter.Stop()
1691
Jon Salz0697cbf2012-07-04 15:14:04 +08001692 def wait(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001693 """Waits for all pending invocations.
Jon Salz0697cbf2012-07-04 15:14:04 +08001694
1695 Useful for testing.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001696 """
Jon Salz1acc8742012-07-17 17:45:55 +08001697 while self.invocations:
1698 for k, v in self.invocations.iteritems():
1699 logging.info('Waiting for %s to complete...', k)
1700 v.thread.join()
1701 self.reap_completed_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +08001702
Claire Changd1961a22015-08-05 16:15:55 +08001703 def test_fail(self, test):
Hung-Te Lin410f70a2015-12-15 14:53:42 +08001704 self.dut.hooks.OnTestFailure(test)
Claire Changd1961a22015-08-05 16:15:55 +08001705 if self.link_manager:
1706 self.link_manager.UpdateStatus(False)
1707
Wei-Han Chenced08ef2016-11-08 09:40:02 +08001708class TestListIterator(object):
1709 """An iterator of test list.
1710
1711 * The iterator will return next test to run when "next()" is called.
1712 * A status filter can be applied to skip some tests according to their states.
1713 * The iterator is loosely bind to FactoryTestList, that is you can change the
1714 test list object of the iterator. If the iterator can find the last test it
1715 returned, the iterator will continue on next test in the new test list.
1716 * This object should implement pickle protocol to be able to save and reload
1717 by python shelve.
1718 (https://docs.python.org/2/library/pickle.html#pickle-protocol)
1719 """
1720
1721 def __init__(self, root, status_filter=None, test_list=None):
1722 """Constructor of TestListIterator.
1723
1724 Args:
1725 root: the root of the subtree to iterate. The iterator will only iterates
1726 tests that is in the subtree. Use 'test_list' object as root will make
1727 this iterator walks entire tree.
1728 status_filter: if given, only tests with these statuses will be returned.
1729 The filter only applies on leaf tests (tests without subtests) or
1730 parallel tests, doesn't apply on test groups.
1731 test_list: a FactoryTestList object this iterator should iterate. Can be
1732 updated by `set_test_list()` function.
1733 """
1734 if isinstance(root, factory.FactoryTest):
1735 self.stack = [root.path]
1736 else:
1737 assert isinstance(root, str)
1738 self.stack = [root]
1739
1740 self.status_filter = status_filter
1741 self.test_list = test_list
1742 self.inited = False
1743
1744 def __getstate__(self):
1745 return dict(stack=self.stack,
1746 status_filter=self.status_filter,
1747 inited=self.inited)
1748
1749 def __setstate__(self, pickled_state):
1750 self.stack = pickled_state['stack']
1751 self.status_filter = pickled_state['status_filter']
1752 self.inited = pickled_state['inited']
1753 self.test_list = None # we didn't serialize the test_list, set it to None
1754
1755 def set_test_list(self, test_list):
1756 assert isinstance(test_list, factory.FactoryTestList)
1757 self.test_list = test_list
1758
1759 def _find_first_leaf_or_parallel_test(self):
1760 while True:
1761 test = self.test_list.lookup_path(self.stack[-1])
1762 if test.is_leaf():
1763 break
1764 # TODO(stimim): check if this test should be run in parallel
1765 self.stack.append(test.subtests[0].path)
1766
1767 def get(self):
1768 """Returns the current test item.
1769
1770 If self.next() is never called before (self.inited == False), this function
1771 will return None.
1772
1773 If the last invocation of self.next() returned a test path, then this
1774 function will return the same test path.
1775
1776 If the last invocation of self.next() raised `StopIteration` exception, this
1777 function will return None.
1778 """
1779 if not self.inited:
1780 return None
1781 if not self.stack:
1782 return None
1783 return self.stack[-1]
1784
1785 def next(self):
1786 """Returns path to the test that should start now.
1787
1788 The returned test could be a leaf factory test (factory test that does not
1789 have any subtests), or a parallel test (a factory test that has subtests but
1790 all of them will be run in parallel).
1791
1792 Returns:
1793 a string the is the path of the test (use test_list.lookup_path(path) to
1794 get the real test object).
1795 """
1796 assert isinstance(self.test_list, factory.FactoryTestList), (
1797 'test_list is not set (call set_test_list() to set test list)')
1798
1799 if not self.stack:
1800 raise StopIteration
1801
1802 if not self.inited:
1803 self._find_first_leaf_or_parallel_test()
1804 self.inited = True
1805 return self.stack[-1]
1806
1807 path = self.stack.pop()
1808 test = self.test_list.lookup_path(path)
1809
1810 if not test:
1811 # cannot find the test we were running, maybe the test list is changed
1812 # between serialization and deserialization, just stop
1813 raise StopIteration
1814
1815 # TODO(stimim): check if previous test failed
1816
1817 # find the next object in parent
1818 if not self.stack:
1819 # oh, there is no parent
1820 raise StopIteration
1821
1822 found_current_test = False
1823 found_next_test = False
1824 for subtest in test.parent.subtests:
1825 if found_current_test:
1826 self.stack.append(subtest.path)
1827 found_next_test = True
1828 break
1829 if path == subtest.path:
1830 # find current, the next one is what we want
1831 found_current_test = True
1832
1833 if found_next_test:
1834 self._find_first_leaf_or_parallel_test()
1835 return self.stack[-1]
1836
1837 assert found_current_test
1838 # next test is not found, it means that we just finished all subtests in
1839 # parent.
1840 # TODO(stimim): should run teardown here
1841
1842 return self.next()
1843
1844
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001845if __name__ == '__main__':
Peter Ammona3d298c2014-09-23 10:11:02 -07001846 Goofy.run_main_and_exit()