blob: 9f5583ea24b0401ebd7ff556e29df88c10fe4351 [file] [log] [blame]
Yilin Yang19da6932019-12-10 13:39:28 +08001#!/usr/bin/env python3
Hung-Te Lin1990b742017-08-09 17:34:57 +08002# Copyright 2012 The Chromium OS Authors. All rights reserved.
Hung-Te Linf2f78f72012-02-08 19:27:11 +08003# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08006"""The main factory flow that runs the factory test and finalizes a device."""
Hung-Te Linf2f78f72012-02-08 19:27:11 +08007
Joel Kitchingb85ed7f2014-10-08 18:24:39 +08008from __future__ import print_function
9
Yilin Yang92930ce2020-03-19 09:58:49 +080010import argparse
Jon Salz0405ab52012-03-16 15:26:52 +080011import logging
12import os
Yilin Yang8b7f5192020-01-08 11:43:00 +080013import queue
Jon Salz77c151e2012-08-28 07:20:37 +080014import signal
Jon Salz0405ab52012-03-16 15:26:52 +080015import sys
Jon Salz0405ab52012-03-16 15:26:52 +080016import threading
17import time
18import traceback
Jon Salz258a40c2012-04-19 12:34:01 +080019import uuid
Yilin Yange02d5722019-10-23 11:07:36 +080020import xmlrpc.client
Hung-Te Linf2f78f72012-02-08 19:27:11 +080021
Yilin Yangea784662019-09-26 13:51:03 +080022from six import iteritems
Yilin Yang8cd83462019-09-25 10:20:36 +080023
Hung-Te Linb6287242016-05-18 14:39:05 +080024from cros.factory.device import device_utils
Vic Yangd80ea752014-09-24 16:07:14 +080025from cros.factory.goofy.goofy_rpc import GoofyRPC
Earl Ouacbe99c2017-02-21 16:04:19 +080026from cros.factory.goofy import goofy_server
Wei-Han Chen1a114682017-10-02 10:33:54 +080027from cros.factory.goofy import hooks
Vic Yangd80ea752014-09-24 16:07:14 +080028from cros.factory.goofy.invocation import TestInvocation
Earl Oua3bca122016-10-21 16:00:30 +080029from cros.factory.goofy.plugins import plugin_controller
Vic Yange2c76a82014-10-30 12:48:19 -070030from cros.factory.goofy import prespawner
Earl Oua3bca122016-10-21 16:00:30 +080031from cros.factory.goofy import test_environment
Wei-Han Chenc17b4112016-11-22 14:56:51 +080032from cros.factory.goofy.test_list_iterator import TestListIterator
Earl Oua3bca122016-10-21 16:00:30 +080033from cros.factory.goofy import updater
Vic Yangd80ea752014-09-24 16:07:14 +080034from cros.factory.goofy.web_socket_manager import WebSocketManager
Wei-Han Chen109d76f2017-08-08 18:50:35 +080035from cros.factory.test import device_data
Earl Ouacbe99c2017-02-21 16:04:19 +080036from cros.factory.test.env import goofy_proxy
Hung-Te Linb6287242016-05-18 14:39:05 +080037from cros.factory.test.env import paths
Jon Salz83591782012-06-26 11:09:58 +080038from cros.factory.test.event import Event
Jon Salz83591782012-06-26 11:09:58 +080039from cros.factory.test.event import EventServer
Peter Shih67c7c0f2018-02-26 11:23:59 +080040from cros.factory.test.event import ThreadingEventClient
Hung-Te Linb6287242016-05-18 14:39:05 +080041from cros.factory.test import event_log
42from cros.factory.test.event_log import EventLog
Hung-Te Linb6287242016-05-18 14:39:05 +080043from cros.factory.test.event_log import GetBootSequence
Hung-Te Lin91492a12014-11-25 18:56:30 +080044from cros.factory.test.event_log_watcher import EventLogWatcher
Peter Shihf65db932017-03-22 17:06:34 +080045from cros.factory.test.i18n import test_ui as i18n_test_ui
Peter Shih80e78b42017-03-10 17:00:56 +080046from cros.factory.test.i18n import translation
Hung-Te Lin3f096842016-01-13 17:37:06 +080047from cros.factory.test.rules import phase
Hung-Te Lind151bf32017-08-30 11:05:47 +080048from cros.factory.test import server_proxy
Hung-Te Linda8eb992017-09-28 03:27:12 +080049from cros.factory.test import session
Earl Oua3bca122016-10-21 16:00:30 +080050from cros.factory.test import state
Wei-Han Chen3b030492017-10-12 11:43:27 +080051from cros.factory.test.state import TestState
Wei-Han Chen16cc5dd2017-04-27 17:38:53 +080052from cros.factory.test.test_lists import manager
Wei-Han Chen03113912017-09-29 15:58:25 +080053from cros.factory.test.test_lists import test_object
chuntseneb33f9d2017-05-12 13:38:17 +080054from cros.factory.testlog import testlog
Wei-Han Chen78f35f62017-03-06 20:11:20 +080055from cros.factory.utils import config_utils
Hung-Te Linf707b242016-01-08 23:11:42 +080056from cros.factory.utils import debug_utils
Jon Salz2af235d2013-06-24 14:47:21 +080057from cros.factory.utils import file_utils
Hung-Te Lin8fc0d652017-09-21 13:05:44 +080058from cros.factory.utils import log_utils
Joel Kitchingb85ed7f2014-10-08 18:24:39 +080059from cros.factory.utils import net_utils
Peter Shihdb06b092018-04-16 16:55:38 +080060from cros.factory.utils import process_utils
Hung-Te Lin4e6357c2016-01-08 14:32:00 +080061from cros.factory.utils import sys_utils
Hung-Te Linf707b242016-01-08 23:11:42 +080062from cros.factory.utils import type_utils
Hung-Te Linf2f78f72012-02-08 19:27:11 +080063
Earl Ou6de96c02017-05-19 18:51:28 +080064from cros.factory.external import syslog
65
Hung-Te Linf2f78f72012-02-08 19:27:11 +080066
Hung-Te Linf2f78f72012-02-08 19:27:11 +080067HWID_CFG_PATH = '/usr/local/share/chromeos-hwid/cfg'
Peter Shihb4e49352017-05-25 17:35:11 +080068CACHES_DIR = os.path.join(paths.DATA_STATE_DIR, 'caches')
Hung-Te Linf2f78f72012-02-08 19:27:11 +080069
Jon Salz5c344f62012-07-13 14:31:16 +080070# Value for tests_after_shutdown that forces auto-run (e.g., after
71# a factory update, when the available set of tests might change).
72FORCE_AUTO_RUN = 'force_auto_run'
73
Wei-Han Chenc17b4112016-11-22 14:56:51 +080074# Key to load the test list iterator after shutdown test
75TESTS_AFTER_SHUTDOWN = 'tests_after_shutdown'
76
Marco Chena20766e2018-09-27 18:29:35 +080077# Key to store active test list id.
78ACTIVE_TEST_LIST_ID = 'active_test_list_id'
79
Hung-Te Linf707b242016-01-08 23:11:42 +080080Status = type_utils.Enum(['UNINITIALIZED', 'INITIALIZING', 'RUNNING',
Wei-Han Chen2ebb92d2016-01-12 14:51:41 +080081 'TERMINATING', 'TERMINATED'])
Jon Salzd7550792013-07-12 05:49:27 +080082
Hung-Te Lina452d4d2017-10-25 17:46:14 +080083RUN_QUEUE_TIMEOUT_SECS = 10
84
Peter Shih658d41d2018-04-16 15:42:00 +080085
Hung-Te Lina452d4d2017-10-25 17:46:14 +080086class Goofy(object):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +080087 """The main factory flow.
Jon Salz0697cbf2012-07-04 15:14:04 +080088
89 Note that all methods in this class must be invoked from the main
90 (event) thread. Other threads, such as callbacks and TestInvocation
91 methods, should instead post events on the run queue.
92
93 TODO: Unit tests. (chrome-os-partner:7409)
94
95 Properties:
Hung-Te Lina452d4d2017-10-25 17:46:14 +080096 run_queue: A queue of callbacks to invoke from the main thread.
97 exceptions: List of exceptions encountered in invocation threads.
98 last_idle: The most recent time of invoking the idle queue handler, or none.
Jon Salz0697cbf2012-07-04 15:14:04 +080099 uuid: A unique UUID for this invocation of Goofy.
100 state_instance: An instance of FactoryState.
101 state_server: The FactoryState XML/RPC server.
102 state_server_thread: A thread running state_server.
103 event_server: The EventServer socket server.
104 event_server_thread: A thread running event_server.
105 event_client: A client to the event server.
Earl Oua3bca122016-10-21 16:00:30 +0800106 plugin_controller: The PluginController object.
Peter Shih06d08212018-01-19 17:15:57 +0800107 invocations: A map from TestInvocation uuid to the corresponding
Jon Salz0697cbf2012-07-04 15:14:04 +0800108 TestInvocations objects representing active tests.
Jon Salz0697cbf2012-07-04 15:14:04 +0800109 args: Command-line args.
110 test_list: The test list.
Jon Salz128b0932013-07-03 16:55:26 +0800111 test_lists: All new-style test lists.
Ricky Liang4bff3e32014-02-20 18:46:11 +0800112 run_id: The identifier for latest test run.
113 scheduled_run_tests: The list of tests scheduled for latest test run.
Jon Salz0697cbf2012-07-04 15:14:04 +0800114 event_handlers: Map of Event.Type to the method used to handle that
115 event. If the method has an 'event' argument, the event is passed
116 to the handler.
Jon Salz416f9cc2013-05-10 18:32:50 +0800117 hooks: A Hooks object containing hooks for various Goofy actions.
Jon Salzd7550792013-07-12 05:49:27 +0800118 status: The current Goofy status (a member of the Status enum).
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800119 """
Ricky Liang45c73e72015-01-15 15:00:30 +0800120
Jon Salz0697cbf2012-07-04 15:14:04 +0800121 def __init__(self):
Yilin Yang8b7f5192020-01-08 11:43:00 +0800122 self.run_queue = queue.Queue()
Hung-Te Lina452d4d2017-10-25 17:46:14 +0800123 self.exceptions = []
124 self.last_idle = None
125
Jon Salz0697cbf2012-07-04 15:14:04 +0800126 self.uuid = str(uuid.uuid4())
127 self.state_instance = None
Earl Ouacbe99c2017-02-21 16:04:19 +0800128 self.goofy_server = None
129 self.goofy_server_thread = None
Jon Salz16d10542012-07-23 12:18:45 +0800130 self.goofy_rpc = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800131 self.event_server = None
132 self.event_server_thread = None
133 self.event_client = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800134 self.log_watcher = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800135 self.event_log = None
Chun-Ta Lin53cbbd52016-06-08 21:42:19 +0800136 self.testlog = None
Earl Oua3bca122016-10-21 16:00:30 +0800137 self.plugin_controller = None
Vic Yange2c76a82014-10-30 12:48:19 -0700138 self.pytest_prespawner = None
Vic Yanga3cecf82014-12-26 00:44:21 -0800139 self._ui_initialized = False
Jon Salz0697cbf2012-07-04 15:14:04 +0800140 self.invocations = {}
Jon Salz0697cbf2012-07-04 15:14:04 +0800141 self.chrome = None
Jon Salz416f9cc2013-05-10 18:32:50 +0800142 self.hooks = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800143
Jon Salz0697cbf2012-07-04 15:14:04 +0800144 self.args = None
145 self.test_list = None
Jon Salz128b0932013-07-03 16:55:26 +0800146 self.test_lists = None
Ricky Liang4bff3e32014-02-20 18:46:11 +0800147 self.run_id = None
148 self.scheduled_run_tests = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800149 self.env = None
Jon Salzb22d1172012-08-06 10:38:57 +0800150 self.last_idle = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800151 self.last_shutdown_time = None
cychiang21886742012-07-05 15:16:32 +0800152 self.last_update_check = None
Cheng-Yi Chiang194d3c02015-03-16 14:37:15 +0800153 self._suppress_periodic_update_messages = False
Cheng-Yi Chiangf5b21012015-03-17 15:37:14 +0800154 self._suppress_event_log_error_messages = False
Earl Ouab979142016-10-25 16:48:06 +0800155 self.exclusive_resources = set()
Jon Salzd7550792013-07-12 05:49:27 +0800156 self.status = Status.UNINITIALIZED
Ricky Liang36512a32014-07-25 11:47:04 +0800157 self.ready_for_ui_connection = False
Hung-Te Linef7f2be2015-07-20 20:38:51 +0800158 self.is_restart_requested = False
Wei-Han Chenc17b4112016-11-22 14:56:51 +0800159 self.test_list_iterator = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800160
Wei-Han Chen16cc5dd2017-04-27 17:38:53 +0800161 self.test_list_manager = manager.Manager()
162
Hung-Te Lin6a72c642015-12-13 22:09:09 +0800163 # TODO(hungte) Support controlling remote DUT.
Hung-Te Linb6287242016-05-18 14:39:05 +0800164 self.dut = device_utils.CreateDUTInterface()
Hung-Te Lin6a72c642015-12-13 22:09:09 +0800165
Peter Shih658d41d2018-04-16 15:42:00 +0800166 def TestOrRoot(event, parent_or_group=True):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800167 """Returns the test affected by a particular event.
Jon Salz85a39882012-07-05 16:45:04 +0800168
169 Args:
170 event: The event containing an optional 'path' attribute.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800171 parent_or_group: If True, returns the top-level parent for a test (the
Jon Salz85a39882012-07-05 16:45:04 +0800172 root node of the tests that need to be run together if the given test
173 path is to be run).
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800174 """
Jon Salz0697cbf2012-07-04 15:14:04 +0800175 try:
176 path = event.path
177 except AttributeError:
178 path = None
179
180 if path:
Wei-Han Chen3ae204c2017-04-28 19:36:55 +0800181 test = self.test_list.LookupPath(path)
Jon Salz85a39882012-07-05 16:45:04 +0800182 if parent_or_group:
Wei-Han Chen3ae204c2017-04-28 19:36:55 +0800183 test = test.GetTopLevelParentOrGroup()
Jon Salz85a39882012-07-05 16:45:04 +0800184 return test
Jon Salz0697cbf2012-07-04 15:14:04 +0800185 else:
Peter Shih999faf72017-07-07 11:32:42 +0800186 return self.test_list.ToFactoryTestList()
Jon Salz0697cbf2012-07-04 15:14:04 +0800187
188 self.event_handlers = {
Ricky Liang45c73e72015-01-15 15:00:30 +0800189 Event.Type.RESTART_TESTS:
Peter Shih658d41d2018-04-16 15:42:00 +0800190 lambda event: self.RestartTests(root=TestOrRoot(event)),
Ricky Liang45c73e72015-01-15 15:00:30 +0800191 Event.Type.AUTO_RUN:
Peter Shih658d41d2018-04-16 15:42:00 +0800192 lambda event: self._AutoRun(root=TestOrRoot(event)),
Ricky Liang45c73e72015-01-15 15:00:30 +0800193 Event.Type.RUN_TESTS_WITH_STATUS:
Peter Shih658d41d2018-04-16 15:42:00 +0800194 lambda event: self._RunTestsWithStatus(
Ricky Liang45c73e72015-01-15 15:00:30 +0800195 event.status,
Peter Shih658d41d2018-04-16 15:42:00 +0800196 root=TestOrRoot(event)),
Ricky Liang45c73e72015-01-15 15:00:30 +0800197 Event.Type.UPDATE_SYSTEM_INFO:
Peter Shih658d41d2018-04-16 15:42:00 +0800198 lambda event: self._UpdateSystemInfo(),
Ricky Liang45c73e72015-01-15 15:00:30 +0800199 Event.Type.STOP:
Peter Shih658d41d2018-04-16 15:42:00 +0800200 lambda event: self.Stop(root=TestOrRoot(event, False),
Ricky Liang45c73e72015-01-15 15:00:30 +0800201 fail=getattr(event, 'fail', False),
202 reason=getattr(event, 'reason', None)),
Ricky Liang45c73e72015-01-15 15:00:30 +0800203 Event.Type.CLEAR_STATE:
Peter Shih658d41d2018-04-16 15:42:00 +0800204 lambda event: self.ClearState(
Wei-Han Chen3ae204c2017-04-28 19:36:55 +0800205 self.test_list.LookupPath(event.path)),
cyuehe4d8bda2019-11-25 12:57:20 +0800206 Event.Type.SET_ITERATIONS_AND_RETRIES:
207 lambda event: self.SetIterationsAndRetries(
208 test=self.test_list.LookupPath(event.path),
209 iterations=getattr(event, 'iterations', None),
210 retries=getattr(event, 'retries', None)),
Jon Salz0697cbf2012-07-04 15:14:04 +0800211 }
212
Jon Salz0697cbf2012-07-04 15:14:04 +0800213 self.web_socket_manager = None
214
Peter Shih658d41d2018-04-16 15:42:00 +0800215 def Destroy(self):
Hung-Te Lina452d4d2017-10-25 17:46:14 +0800216 """Performs any shutdown tasks."""
chuntsen9d675c62017-06-20 14:35:30 +0800217 # To avoid race condition when running shutdown test.
Yilin Yang90761402020-05-14 13:23:05 +0800218 for invoc in self.invocations.values():
Peter Shih06d08212018-01-19 17:15:57 +0800219 logging.info('Waiting for %s to complete...', invoc.test)
chuntsen9d675c62017-06-20 14:35:30 +0800220 invoc.thread.join(3) # Timeout in 3 seconds.
221
Jon Salzd7550792013-07-12 05:49:27 +0800222 self.status = Status.TERMINATING
Jon Salz0697cbf2012-07-04 15:14:04 +0800223 if self.chrome:
224 self.chrome.kill()
225 self.chrome = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800226 if self.web_socket_manager:
227 logging.info('Stopping web sockets')
228 self.web_socket_manager.close()
229 self.web_socket_manager = None
Earl Ouacbe99c2017-02-21 16:04:19 +0800230 if self.goofy_server_thread:
231 logging.info('Stopping goofy server')
Peter Shih0a6ae8d2017-10-23 17:59:42 +0800232 net_utils.ShutdownTCPServer(self.goofy_server)
Earl Ouacbe99c2017-02-21 16:04:19 +0800233 self.goofy_server_thread.join()
234 self.goofy_server.server_close()
235 self.goofy_server_thread = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800236 if self.state_instance:
Fei Shaobcaa52b2018-09-28 13:27:15 +0800237 self.state_instance.Close()
Jon Salz0697cbf2012-07-04 15:14:04 +0800238 if self.event_server_thread:
239 logging.info('Stopping event server')
Peter Shihce9490e2017-05-11 14:32:12 +0800240 net_utils.ShutdownTCPServer(self.event_server)
Jon Salz0697cbf2012-07-04 15:14:04 +0800241 self.event_server_thread.join()
242 self.event_server.server_close()
243 self.event_server_thread = None
244 if self.log_watcher:
245 if self.log_watcher.IsThreadStarted():
246 self.log_watcher.StopWatchThread()
247 self.log_watcher = None
Vic Yange2c76a82014-10-30 12:48:19 -0700248 if self.pytest_prespawner:
249 logging.info('Stopping pytest prespawner')
250 self.pytest_prespawner.stop()
251 self.pytest_prespawner = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800252 if self.event_client:
253 logging.info('Closing event client')
254 self.event_client.close()
255 self.event_client = None
256 if self.event_log:
257 self.event_log.Close()
258 self.event_log = None
Chun-Ta Lin53cbbd52016-06-08 21:42:19 +0800259 if self.testlog:
260 self.testlog.Close()
261 self.testlog = None
Earl Oua3bca122016-10-21 16:00:30 +0800262 if self.plugin_controller:
263 self.plugin_controller.StopAndDestroyAllPlugins()
264 self.plugin_controller = None
Dean Liao592e4d52013-01-10 20:06:39 +0800265
Peter Shih658d41d2018-04-16 15:42:00 +0800266 self._CheckExceptions()
Jon Salz0697cbf2012-07-04 15:14:04 +0800267 logging.info('Done destroying Goofy')
Jon Salzd7550792013-07-12 05:49:27 +0800268 self.status = Status.TERMINATED
Jon Salz0697cbf2012-07-04 15:14:04 +0800269
Peter Shih658d41d2018-04-16 15:42:00 +0800270 def _InitGoofyServer(self):
Earl Ouacbe99c2017-02-21 16:04:19 +0800271 self.goofy_server = goofy_server.GoofyServer(
Shen-En Shihd5b96bf2017-08-09 17:47:21 +0800272 (goofy_proxy.DEFAULT_GOOFY_BIND, goofy_proxy.DEFAULT_GOOFY_PORT))
Earl Ouacbe99c2017-02-21 16:04:19 +0800273 self.goofy_server_thread = threading.Thread(
274 target=self.goofy_server.serve_forever,
275 name='GoofyServer')
Peter Shihdb06b092018-04-16 16:55:38 +0800276 self.goofy_server_thread.daemon = True
Earl Ouacbe99c2017-02-21 16:04:19 +0800277
Peter Shih658d41d2018-04-16 15:42:00 +0800278 def _InitStaticFiles(self):
Peter Shih7cc81b12017-08-24 13:04:46 +0800279 static_path = os.path.join(paths.FACTORY_PYTHON_PACKAGE_DIR, 'goofy/static')
Earl Ouacbe99c2017-02-21 16:04:19 +0800280 # Setup static file path
Peter Shih7cc81b12017-08-24 13:04:46 +0800281 self.goofy_server.RegisterPath('/', static_path)
Earl Ouacbe99c2017-02-21 16:04:19 +0800282
Peter Shih658d41d2018-04-16 15:42:00 +0800283 def _InitStateInstance(self):
Jon Salz2af235d2013-06-24 14:47:21 +0800284 # Before starting state server, remount stateful partitions with
285 # no commit flag. The default commit time (commit=600) makes corruption
286 # too likely.
Hung-Te Lin1968d9c2016-01-08 22:55:46 +0800287 sys_utils.ResetCommitTime()
Marco Chena20766e2018-09-27 18:29:35 +0800288
Earl Ouacbe99c2017-02-21 16:04:19 +0800289 self.state_instance = state.FactoryState()
Yong Hongf879cbd2018-11-08 16:06:52 +0800290 self.last_shutdown_time = (
291 self.state_instance.DataShelfGetValue('shutdown_time', optional=True))
292 self.state_instance.DataShelfDeleteKeys('shutdown_time', optional=True)
293 self.state_instance.DataShelfDeleteKeys('startup_error', optional=True)
Marco Chenda8f6d42018-10-02 22:31:53 +0800294
Yong Hongf879cbd2018-11-08 16:06:52 +0800295 def _ResetStateInstance(self):
296 PRESERVED_KEYS = ['startup_error']
Marco Chena20766e2018-09-27 18:29:35 +0800297
Yong Hongf879cbd2018-11-08 16:06:52 +0800298 # Backup the required data.
299 preserved_data = {
300 key: self.state_instance.DataShelfGetValue(key, optional=True)
301 for key in PRESERVED_KEYS}
302
303 # Reset the state instance.
304 self.state_instance.Close()
305 state.ClearState()
306 self.state_instance = state.FactoryState()
307
308 # Write back the preserved data.
Yilin Yangea784662019-09-26 13:51:03 +0800309 for key, value in iteritems(preserved_data):
Yong Hongf879cbd2018-11-08 16:06:52 +0800310 if value is not None:
311 self.state_instance.DataShelfSetValue(key, value)
312
313 def _InitGoofyRPC(self):
Earl Ouacbe99c2017-02-21 16:04:19 +0800314 self.goofy_server.AddRPCInstance(goofy_proxy.STATE_URL, self.state_instance)
Jon Salz2af235d2013-06-24 14:47:21 +0800315
Earl Ouacbe99c2017-02-21 16:04:19 +0800316 # Setup Goofy RPC.
317 # TODO(shunhsingou): separate goofy_rpc and state server instead of
318 # injecting goofy_rpc functions into state.
Jon Salz16d10542012-07-23 12:18:45 +0800319 self.goofy_rpc = GoofyRPC(self)
320 self.goofy_rpc.RegisterMethods(self.state_instance)
Jon Salz0697cbf2012-07-04 15:14:04 +0800321
Peter Shih658d41d2018-04-16 15:42:00 +0800322 def _InitI18n(self):
Peter Shih80e78b42017-03-10 17:00:56 +0800323 js_data = 'var goofy_i18n_data = %s;' % translation.GetAllI18nDataJS()
Peter Shihce03c2e2017-03-21 17:36:10 +0800324 self.goofy_server.RegisterData('/js/goofy-translations.js',
325 'application/javascript', js_data)
Peter Shihf65db932017-03-22 17:06:34 +0800326 self.goofy_server.RegisterData('/css/i18n.css',
327 'text/css', i18n_test_ui.GetStyleSheet())
Peter Shih80e78b42017-03-10 17:00:56 +0800328
Peter Shih658d41d2018-04-16 15:42:00 +0800329 def _StartEventServer(self):
Jon Salz0697cbf2012-07-04 15:14:04 +0800330 self.event_server = EventServer()
331 logging.info('Starting factory event server')
Peter Shihdb06b092018-04-16 16:55:38 +0800332 self.event_server_thread = process_utils.StartDaemonThread(
Ricky Liang45c73e72015-01-15 15:00:30 +0800333 target=self.event_server.serve_forever,
Peter Shihfdf17682017-05-26 11:38:39 +0800334 name='EventServer')
Jon Salz0697cbf2012-07-04 15:14:04 +0800335
Peter Shih533566a2018-09-05 17:48:03 +0800336 # pylint 1.5.6 has a false negative on nested lambda, see
337 # https://github.com/PyCQA/pylint/issues/760.
338 # pylint: disable=undefined-variable
Shen-En Shihd7359cc2017-10-03 16:01:47 +0800339 self.event_client = ThreadingEventClient(
Peter Shih658d41d2018-04-16 15:42:00 +0800340 callback=lambda event: self.RunEnqueue(lambda: self.HandleEvent(event)))
Peter Shih533566a2018-09-05 17:48:03 +0800341 # pylint: enable=undefined-variable
Jon Salz0697cbf2012-07-04 15:14:04 +0800342
343 self.web_socket_manager = WebSocketManager(self.uuid)
Earl Ouacbe99c2017-02-21 16:04:19 +0800344 self.goofy_server.AddHTTPGetHandler(
345 '/event', self.web_socket_manager.handle_web_socket)
Jon Salz0697cbf2012-07-04 15:14:04 +0800346
Peter Shih658d41d2018-04-16 15:42:00 +0800347 def Shutdown(self, operation):
Ricky Liang48e47f92014-02-26 19:31:51 +0800348 """Starts shutdown procedure.
349
350 Args:
Vic (Chun-Ju) Yang05b0d952014-04-28 17:39:09 +0800351 operation: The shutdown operation (reboot, full_reboot, or halt).
Ricky Liang48e47f92014-02-26 19:31:51 +0800352 """
353 active_tests = []
Wei-Han Chen3ae204c2017-04-28 19:36:55 +0800354 for test in self.test_list.Walk():
355 if not test.IsLeaf():
Ricky Liang48e47f92014-02-26 19:31:51 +0800356 continue
357
Wei-Han Chen3ae204c2017-04-28 19:36:55 +0800358 test_state = test.GetState()
Ricky Liang48e47f92014-02-26 19:31:51 +0800359 if test_state.status == TestState.ACTIVE:
360 active_tests.append(test)
361
Fei Shao243bd6f2019-07-10 20:28:22 +0800362 if operation == 'force_halt':
363 # force_halt is a special halt request that shuts DUT down without going
364 # through shutdown.py.
365 # The use case can be like: if operators need to temporarily shutdown all
366 # DUTs (e.g. charging or leaving production line) but don't want to press
367 # power button for 10s on each, they can now use 'DUT Shutdown' in CrOS
368 # Factory Menu to perform force shutdown.
369 if active_tests:
370 message = ('Can not force halt while tests are running. '
371 'Stop all the tests and try again.')
372 session.console.error(message)
373 return
374 operation = 'halt'
375 elif not (len(active_tests) == 1 and
376 isinstance(active_tests[0], test_object.ShutdownStep)):
Ricky Liang48e47f92014-02-26 19:31:51 +0800377 logging.error(
378 'Calling Goofy shutdown outside of the shutdown factory test')
379 return
380
381 logging.info('Start Goofy shutdown (%s)', operation)
382 # Save pending test list in the state server
Fei Shaoee5943d2018-10-10 09:41:41 +0800383 self.state_instance.DataShelfSetValue(
Wei-Han Chenc17b4112016-11-22 14:56:51 +0800384 TESTS_AFTER_SHUTDOWN, self.test_list_iterator)
Ricky Liang48e47f92014-02-26 19:31:51 +0800385 # Save shutdown time
Fei Shaoee5943d2018-10-10 09:41:41 +0800386 self.state_instance.DataShelfSetValue('shutdown_time', time.time())
Ricky Liang48e47f92014-02-26 19:31:51 +0800387
388 with self.env.lock:
389 self.event_log.Log('shutdown', operation=operation)
390 shutdown_result = self.env.shutdown(operation)
391 if shutdown_result:
392 # That's all, folks!
Peter Shih658d41d2018-04-16 15:42:00 +0800393 self.RunEnqueue(None)
Ricky Liang48e47f92014-02-26 19:31:51 +0800394 else:
395 # Just pass (e.g., in the chroot).
Fei Shaoee5943d2018-10-10 09:41:41 +0800396 self.state_instance.DataShelfSetValue(TESTS_AFTER_SHUTDOWN, None)
Ricky Liang48e47f92014-02-26 19:31:51 +0800397 # Send event with no fields to indicate that there is no
398 # longer a pending shutdown.
399 self.event_client.post_event(Event(Event.Type.PENDING_SHUTDOWN))
400
Peter Shih658d41d2018-04-16 15:42:00 +0800401 def _HandleShutdownComplete(self, test):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800402 """Handles the case where a shutdown was detected during a shutdown step.
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800403
Ricky Liang6fe218c2013-12-27 15:17:17 +0800404 Args:
405 test: The ShutdownStep.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800406 """
Wei-Han Chen3ae204c2017-04-28 19:36:55 +0800407 test_state = test.UpdateState(increment_shutdown_count=1)
Jon Salz0697cbf2012-07-04 15:14:04 +0800408 logging.info('Detected shutdown (%d of %d)',
Ricky Liang48e47f92014-02-26 19:31:51 +0800409 test_state.shutdown_count, test.iterations)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800410
Fei Shaoee5943d2018-10-10 09:41:41 +0800411 tests_after_shutdown = self.state_instance.DataShelfGetValue(
Wei-Han Chenc17b4112016-11-22 14:56:51 +0800412 TESTS_AFTER_SHUTDOWN, optional=True)
413
414 # Make this shutdown test the next test to run. This is to continue on
415 # post-shutdown verification in the shutdown step.
Ricky Liang48e47f92014-02-26 19:31:51 +0800416 if not tests_after_shutdown:
Kitty Liu443e01a2019-11-13 14:36:20 +0800417 goofy_error = 'TESTS_AFTER_SHUTDOWN is not set'
Fei Shaoee5943d2018-10-10 09:41:41 +0800418 self.state_instance.DataShelfSetValue(
Wei-Han Chenc17b4112016-11-22 14:56:51 +0800419 TESTS_AFTER_SHUTDOWN, TestListIterator(test))
420 else:
Wei-Han Chen29663c12017-06-27 10:28:54 +0800421 goofy_error = tests_after_shutdown.RestartLastTest()
Fei Shaoee5943d2018-10-10 09:41:41 +0800422 self.state_instance.DataShelfSetValue(
Wei-Han Chenc17b4112016-11-22 14:56:51 +0800423 TESTS_AFTER_SHUTDOWN, tests_after_shutdown)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800424
Ricky Liang48e47f92014-02-26 19:31:51 +0800425 # Set 'post_shutdown' to inform shutdown test that a shutdown just occurred.
Fei Shaoee5943d2018-10-10 09:41:41 +0800426 self.state_instance.DataShelfSetValue(
Wei-Han Chen29663c12017-06-27 10:28:54 +0800427 state.KEY_POST_SHUTDOWN % test.path,
Fei Shaobcaa52b2018-09-28 13:27:15 +0800428 {'invocation': self.state_instance.GetTestState(test.path).invocation,
Wei-Han Chen29663c12017-06-27 10:28:54 +0800429 'goofy_error': goofy_error})
Jon Salz258a40c2012-04-19 12:34:01 +0800430
Peter Shih658d41d2018-04-16 15:42:00 +0800431 def _InitStates(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800432 """Initializes all states on startup."""
Wei-Han Chen3ae204c2017-04-28 19:36:55 +0800433 for test in self.test_list.GetAllTests():
Jon Salz0697cbf2012-07-04 15:14:04 +0800434 # Make sure the state server knows about all the tests,
435 # defaulting to an untested state.
Peter Shih6e578272017-09-12 17:41:43 +0800436 test.UpdateState(update_parent=False)
cyuehe4d8bda2019-11-25 12:57:20 +0800437 for test in self.test_list.GetAllTests():
438 test_state = test.GetState()
439 self.SetIterationsAndRetries(test,
440 test_state.iterations, test_state.retries)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800441
Earl Ouf76e55c2017-03-07 11:48:34 +0800442 is_unexpected_shutdown = False
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800443
Jon Salz0697cbf2012-07-04 15:14:04 +0800444 # Any 'active' tests should be marked as failed now.
Wei-Han Chen3ae204c2017-04-28 19:36:55 +0800445 for test in self.test_list.Walk():
446 if not test.IsLeaf():
Jon Salza6711d72012-07-18 14:33:03 +0800447 # Don't bother with parents; they will be updated when their
448 # children are updated.
449 continue
450
Wei-Han Chen3ae204c2017-04-28 19:36:55 +0800451 test_state = test.GetState()
Jon Salz0697cbf2012-07-04 15:14:04 +0800452 if test_state.status != TestState.ACTIVE:
453 continue
Wei-Han Chen03113912017-09-29 15:58:25 +0800454 if isinstance(test, test_object.ShutdownStep):
Jon Salz0697cbf2012-07-04 15:14:04 +0800455 # Shutdown while the test was active - that's good.
Peter Shih658d41d2018-04-16 15:42:00 +0800456 self._HandleShutdownComplete(test)
Shen-En Shihef6c5ae2017-12-21 14:26:47 +0800457 elif test.allow_reboot:
458 is_unexpected_shutdown = True
459 test.UpdateState(status=TestState.UNTESTED)
460 # For "allow_reboot" tests (such as "Start"), don't cancel
461 # pending tests, since reboot is expected.
462 session.console.info('Unexpected shutdown while test %s was running. '
463 'The test is marked as allow_reboot, continuing '
464 'on pending tests.',
465 test.path)
Jon Salz0697cbf2012-07-04 15:14:04 +0800466 else:
Peter Shih658d41d2018-04-16 15:42:00 +0800467 def GetUnexpectedShutdownTestRun():
chuntsen61522442017-08-11 14:40:29 +0800468 """Returns a StationTestRun for test not collected properly"""
469 station_test_run = testlog.StationTestRun()
chuntsendf856b32018-06-14 15:49:47 +0800470 station_test_run['status'] = testlog.StationTestRun.STATUS.FAIL
chuntsen921aa872018-06-15 16:28:44 +0800471 station_test_run['endTime'] = time.time()
chuntsen61522442017-08-11 14:40:29 +0800472 station_test_run.AddFailure(
473 'GoofyErrorMsg', 'Unexpected shutdown while test was running')
474 return station_test_run
475
Earl Ouf76e55c2017-03-07 11:48:34 +0800476 is_unexpected_shutdown = True
Jon Salz0697cbf2012-07-04 15:14:04 +0800477 error_msg = 'Unexpected shutdown while test was running'
478 self.event_log.Log('end_test',
Ricky Liang45c73e72015-01-15 15:00:30 +0800479 path=test.path,
480 status=TestState.FAILED,
Wei-Han Chen3ae204c2017-04-28 19:36:55 +0800481 invocation=test.GetState().invocation,
Earl Ouf76e55c2017-03-07 11:48:34 +0800482 error_msg=error_msg)
chuntsen61522442017-08-11 14:40:29 +0800483 testlog.CollectExpiredSessions(paths.DATA_LOG_DIR,
Peter Shih658d41d2018-04-16 15:42:00 +0800484 GetUnexpectedShutdownTestRun())
Wei-Han Chen3ae204c2017-04-28 19:36:55 +0800485 test.UpdateState(
Ricky Liang45c73e72015-01-15 15:00:30 +0800486 status=TestState.FAILED,
487 error_msg=error_msg)
Chun-Ta Lin87c2dac2015-05-02 01:35:01 -0700488 # Trigger the OnTestFailure callback.
Peter Shih658d41d2018-04-16 15:42:00 +0800489 self.RunEnqueue(lambda: self._TestFail(test))
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800490
Shen-En Shihef6c5ae2017-12-21 14:26:47 +0800491 session.console.info('Unexpected shutdown while test %s '
492 'running; cancelling any pending tests',
493 test.path)
494 # cancel pending tests by replace the iterator with an empty one
Fei Shaoee5943d2018-10-10 09:41:41 +0800495 self.state_instance.DataShelfSetValue(
Shen-En Shihef6c5ae2017-12-21 14:26:47 +0800496 TESTS_AFTER_SHUTDOWN,
497 TestListIterator(None))
Jon Salz008f4ea2012-08-28 05:39:45 +0800498
Earl Ouf76e55c2017-03-07 11:48:34 +0800499 if is_unexpected_shutdown:
500 logging.warning("Unexpected shutdown.")
Wei-Han Chen8d7fbc42017-10-18 19:20:47 +0800501 self.hooks.OnUnexpectedReboot(self)
Earl Ouf76e55c2017-03-07 11:48:34 +0800502
Wei-Han Chen109d76f2017-08-08 18:50:35 +0800503 if self.test_list.options.read_device_data_from_vpd_on_init:
504 vpd_data = {}
505 for section in [device_data.NAME_RO, device_data.NAME_RW]:
506 try:
507 vpd_data[section] = self.dut.vpd.boot.GetPartition(section).GetAll()
508 except Exception:
Hung-Te Lin1be934e2018-03-29 17:59:49 +0800509 logging.warning('Failed to read %s_VPD, ignored...', section.upper())
Wei-Han Chen109d76f2017-08-08 18:50:35 +0800510 # using None for key_map will use default key_map
511 device_data.UpdateDeviceDataFromVPD(None, vpd_data)
512
Wei-Han Chen212d2af2017-08-03 18:12:23 +0800513 # state_instance is initialized, we can mark skipped and waived tests now.
514 self.test_list.SetSkippedAndWaivedTests()
515
Peter Shih658d41d2018-04-16 15:42:00 +0800516 def HandleEvent(self, event):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800517 """Handles an event from the event server."""
Jon Salz0697cbf2012-07-04 15:14:04 +0800518 handler = self.event_handlers.get(event.type)
519 if handler:
520 handler(event)
521 else:
522 # We don't register handlers for all event types - just ignore
523 # this event.
524 logging.debug('Unbound event type %s', event.type)
Jon Salz4f6c7172012-06-11 20:45:36 +0800525
Peter Shih658d41d2018-04-16 15:42:00 +0800526 def _CheckCriticalFactoryNote(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800527 """Returns True if the last factory note is critical."""
Fei Shaoee5943d2018-10-10 09:41:41 +0800528 notes = self.state_instance.DataShelfGetValue('factory_note', optional=True)
Vic Yangaabf9fd2013-04-09 18:56:13 +0800529 return notes and notes[-1]['level'] == 'CRITICAL'
530
Peter Shih658d41d2018-04-16 15:42:00 +0800531 def ScheduleRestart(self):
Hung-Te Linef7f2be2015-07-20 20:38:51 +0800532 """Schedules a restart event when any invocation is completed."""
533 self.is_restart_requested = True
534
Peter Shih658d41d2018-04-16 15:42:00 +0800535 def _InvocationCompletion(self):
Hung-Te Linef7f2be2015-07-20 20:38:51 +0800536 """Callback when an invocation is completed."""
537 if self.is_restart_requested:
538 logging.info('Restart by scheduled event.')
539 self.is_restart_requested = False
Peter Shih658d41d2018-04-16 15:42:00 +0800540 self.RestartTests()
Hung-Te Linef7f2be2015-07-20 20:38:51 +0800541 else:
Peter Shih658d41d2018-04-16 15:42:00 +0800542 self._RunNextTest()
Hung-Te Linef7f2be2015-07-20 20:38:51 +0800543
Peter Shih658d41d2018-04-16 15:42:00 +0800544 def _RunNextTest(self):
Wei-Han Chenc17b4112016-11-22 14:56:51 +0800545 """Runs the next eligible test.
henryhsu4cc6b022014-04-22 17:12:42 +0800546
Wei-Han Chenc17b4112016-11-22 14:56:51 +0800547 self.test_list_iterator (a TestListIterator object) will determine which
548 test should be run.
henryhsu4cc6b022014-04-22 17:12:42 +0800549 """
Peter Shih658d41d2018-04-16 15:42:00 +0800550 self.ReapCompletedTests()
Wei-Han Chenc17b4112016-11-22 14:56:51 +0800551
552 if self.invocations:
553 # there are tests still running, we cannot start new tests
Vic Yangaabf9fd2013-04-09 18:56:13 +0800554 return
Jon Salz94eb56f2012-06-12 18:01:12 +0800555
Peter Shih658d41d2018-04-16 15:42:00 +0800556 if self._CheckCriticalFactoryNote():
Wei-Han Chenc17b4112016-11-22 14:56:51 +0800557 logging.info('has critical factory note, stop running')
Wei-Han Chenbcac7252017-04-21 19:46:51 +0800558 self.test_list_iterator.Stop()
Wei-Han Chenc17b4112016-11-22 14:56:51 +0800559 return
Jon Salz94eb56f2012-06-12 18:01:12 +0800560
Wei-Han Chenc17b4112016-11-22 14:56:51 +0800561 while True:
562 try:
Yilin Yange5868f22019-10-23 18:18:08 +0800563 path = next(self.test_list_iterator)
Wei-Han Chen3ae204c2017-04-28 19:36:55 +0800564 test = self.test_list.LookupPath(path)
Wei-Han Chenc17b4112016-11-22 14:56:51 +0800565 except StopIteration:
566 logging.info('no next test, stop running')
Jon Salz0697cbf2012-07-04 15:14:04 +0800567 return
Jon Salz94eb56f2012-06-12 18:01:12 +0800568
Wei-Han Chenc17b4112016-11-22 14:56:51 +0800569 # check if we have run all required tests
Jon Salz304a75d2012-07-06 11:14:15 +0800570 untested = set()
Jon Salza1412922012-07-23 16:04:17 +0800571 for requirement in test.require_run:
Wei-Han Chen3ae204c2017-04-28 19:36:55 +0800572 for i in requirement.test.Walk():
Jon Salza1412922012-07-23 16:04:17 +0800573 if i == test:
Jon Salz304a75d2012-07-06 11:14:15 +0800574 # We've hit this test itself; stop checking
575 break
Wei-Han Chen3ae204c2017-04-28 19:36:55 +0800576 if ((i.GetState().status == TestState.UNTESTED) or
Wei-Han Chen3a160172017-07-11 17:31:28 +0800577 (requirement.passed and
578 i.GetState().status not in [TestState.SKIPPED,
579 TestState.PASSED])):
Jon Salz304a75d2012-07-06 11:14:15 +0800580 # Found an untested test; move on to the next
581 # element in require_run.
Jon Salza1412922012-07-23 16:04:17 +0800582 untested.add(i)
Jon Salz304a75d2012-07-06 11:14:15 +0800583 break
584
585 if untested:
586 untested_paths = ', '.join(sorted([x.path for x in untested]))
Fei Shaoee5943d2018-10-10 09:41:41 +0800587 if self.state_instance.DataShelfGetValue('engineering_mode',
588 optional=True):
589
Jon Salz304a75d2012-07-06 11:14:15 +0800590 # In engineering mode, we'll let it go.
Hung-Te Lin03f1fc22017-10-16 16:38:31 +0800591 session.console.warn('In engineering mode; running '
Jon Salz304a75d2012-07-06 11:14:15 +0800592 '%s even though required tests '
593 '[%s] have not completed',
594 test.path, untested_paths)
595 else:
596 # Not in engineering mode; mark it failed.
597 error_msg = ('Required tests [%s] have not been run yet'
598 % untested_paths)
Hung-Te Lin03f1fc22017-10-16 16:38:31 +0800599 session.console.error('Not running %s: %s',
Jon Salz304a75d2012-07-06 11:14:15 +0800600 test.path, error_msg)
Wei-Han Chen3ae204c2017-04-28 19:36:55 +0800601 test.UpdateState(status=TestState.FAILED,
602 error_msg=error_msg)
Jon Salz304a75d2012-07-06 11:14:15 +0800603 continue
604
Wei-Han Chenc17b4112016-11-22 14:56:51 +0800605 # okay, let's run the test
Wei-Han Chen03113912017-09-29 15:58:25 +0800606 if (isinstance(test, test_object.ShutdownStep) and
Fei Shaoee5943d2018-10-10 09:41:41 +0800607 self.state_instance.DataShelfGetValue(
Wei-Han Chen29663c12017-06-27 10:28:54 +0800608 state.KEY_POST_SHUTDOWN % test.path, optional=True)):
Ricky Liang48e47f92014-02-26 19:31:51 +0800609 # Invoking post shutdown method of shutdown test. We should retain the
610 # iterations_left and retries_left of the original test state.
Fei Shaobcaa52b2018-09-28 13:27:15 +0800611 test_state = self.state_instance.GetTestState(test.path)
Peter Shih658d41d2018-04-16 15:42:00 +0800612 self._RunTest(test, test_state.iterations_left, test_state.retries_left)
Ricky Liang48e47f92014-02-26 19:31:51 +0800613 else:
614 # Starts a new test run; reset iterations and retries.
Peter Shih658d41d2018-04-16 15:42:00 +0800615 self._RunTest(test, test.iterations, test.retries)
Wei-Han Chenc17b4112016-11-22 14:56:51 +0800616 return # to leave while
Jon Salz1acc8742012-07-17 17:45:55 +0800617
Peter Shih658d41d2018-04-16 15:42:00 +0800618 def _RunTest(self, test, iterations_left=None, retries_left=None,
619 set_layout=True):
Wei-Han Chenc17b4112016-11-22 14:56:51 +0800620 """Invokes the test.
621
622 The argument `test` should be either a leaf test (no subtests) or a parallel
623 test (all subtests should be run in parallel).
624 """
Yilin Yang92930ce2020-03-19 09:58:49 +0800625 if (self.args.goofy_ui and not self._ui_initialized and
Peter Shih2c2bf262018-01-19 15:31:39 +0800626 not test.IsNoHost()):
Peter Shih658d41d2018-04-16 15:42:00 +0800627 self.InitUI()
Jon Salz1acc8742012-07-17 17:45:55 +0800628
Peter Shih13d2ced2017-09-25 16:25:09 +0800629 if set_layout:
630 self.event_client.post_event(
631 Event(
632 Event.Type.SET_TEST_UI_LAYOUT,
633 layout_type=test.layout_type,
634 layout_options=test.layout_options))
635
Wei-Han Chen3ae204c2017-04-28 19:36:55 +0800636 if test.IsLeaf():
Wei-Han Chenc17b4112016-11-22 14:56:51 +0800637 invoc = TestInvocation(
Peter Shih658d41d2018-04-16 15:42:00 +0800638 self, test, on_completion=self._InvocationCompletion,
639 on_test_failure=lambda: self._TestFail(test))
Wei-Han Chen3ae204c2017-04-28 19:36:55 +0800640 new_state = test.UpdateState(
Wei-Han Chenc17b4112016-11-22 14:56:51 +0800641 status=TestState.ACTIVE, increment_count=1, error_msg='',
642 invocation=invoc.uuid, iterations_left=iterations_left,
Peter Shihf5c048d2017-09-01 17:57:51 +0800643 retries_left=retries_left)
Wei-Han Chenc17b4112016-11-22 14:56:51 +0800644 invoc.count = new_state.count
Peter Shih06d08212018-01-19 17:15:57 +0800645 self.invocations[invoc.uuid] = invoc
Peter Shihb2ecd552017-08-24 17:48:58 +0800646 # Send a INIT_TEST_UI event here, so the test UI are initialized in
647 # order, and the tab order would be same as test list order when there
648 # are parallel tests with UI.
649 self.event_client.post_event(
650 Event(
651 Event.Type.INIT_TEST_UI,
Peter Shihb2ecd552017-08-24 17:48:58 +0800652 test=test.path,
653 invocation=invoc.uuid))
Peter Shih658d41d2018-04-16 15:42:00 +0800654 self._CheckPlugins()
Peter Shih0d4f77a2018-01-19 16:15:49 +0800655 invoc.Start()
Wei-Han Chendc3e3ba2017-07-05 16:49:09 +0800656 elif test.parallel:
Wei-Han Chenc17b4112016-11-22 14:56:51 +0800657 for subtest in test.subtests:
Fei Shao96164bb2019-12-27 12:15:22 +0800658 # Pass the service lists defined in parallel group down to each
659 # subtest.
660 # Subtests of a parallel group are not allowed to have their own
661 # service lists, so it's fine to override the lists with parallel
662 # group's.
663 subtest.enable_services = test.enable_services
664 subtest.disable_services = test.disable_services
665
Wei-Han Chenc17b4112016-11-22 14:56:51 +0800666 # TODO(stimim): what if the subtests *must* be run in parallel?
667 # for example, stressapptest and countdown test.
668
669 # Make sure we don't need to skip it:
Wei-Han Chenbcac7252017-04-21 19:46:51 +0800670 if not self.test_list_iterator.CheckSkip(subtest):
Peter Shih658d41d2018-04-16 15:42:00 +0800671 self._RunTest(subtest, subtest.iterations, subtest.retries,
672 set_layout=False)
Wei-Han Chendc3e3ba2017-07-05 16:49:09 +0800673 else:
674 # This should never happen, there must be something wrong.
675 # However, we can't raise an exception, otherwise goofy will be closed
676 logging.critical(
677 'Goofy should not get a non-leaf test that is not parallel: %r',
678 test)
Hung-Te Lin03f1fc22017-10-16 16:38:31 +0800679 session.console.critical(
Wei-Han Chendc3e3ba2017-07-05 16:49:09 +0800680 'Goofy should not get a non-leaf test that is not parallel: %r',
681 test)
Jon Salz5f2a0672012-05-22 17:14:06 +0800682
Peter Shih658d41d2018-04-16 15:42:00 +0800683 def Run(self):
Hung-Te Lina452d4d2017-10-25 17:46:14 +0800684 """Runs Goofy."""
685 # Process events forever.
Peter Shih658d41d2018-04-16 15:42:00 +0800686 while self.RunOnce(True):
Hung-Te Lina452d4d2017-10-25 17:46:14 +0800687 pass
688
Peter Shih658d41d2018-04-16 15:42:00 +0800689 def RunEnqueue(self, val):
Hung-Te Lina452d4d2017-10-25 17:46:14 +0800690 """Enqueues an object on the event loop.
691
692 Generally this is a function. It may also be None to indicate that the
693 run queue should shut down.
694 """
695 self.run_queue.put(val)
696
Peter Shih658d41d2018-04-16 15:42:00 +0800697 def RunOnce(self, block=False):
Hung-Te Lina452d4d2017-10-25 17:46:14 +0800698 """Runs all items pending in the event loop.
699
700 Args:
701 block: If true, block until at least one event is processed.
702
703 Returns:
704 True to keep going or False to shut down.
705 """
706 events = type_utils.DrainQueue(self.run_queue)
707 while not events:
708 # Nothing on the run queue.
Peter Shih658d41d2018-04-16 15:42:00 +0800709 self._RunQueueIdle()
Hung-Te Lina452d4d2017-10-25 17:46:14 +0800710 if block:
711 # Block for at least one event...
712 try:
713 events.append(self.run_queue.get(timeout=RUN_QUEUE_TIMEOUT_SECS))
Yilin Yang8b7f5192020-01-08 11:43:00 +0800714 except queue.Empty:
Peter Shih658d41d2018-04-16 15:42:00 +0800715 # Keep going (calling _RunQueueIdle() again at the top of
Hung-Te Lina452d4d2017-10-25 17:46:14 +0800716 # the loop)
717 continue
718 # ...and grab anything else that showed up at the same
719 # time.
720 events.extend(type_utils.DrainQueue(self.run_queue))
721 else:
722 break
723
724 for event in events:
725 if not event:
726 # Shutdown request.
727 self.run_queue.task_done()
728 return False
729
730 try:
731 event()
732 except Exception:
733 logging.exception('Error in event loop')
Peter Shih658d41d2018-04-16 15:42:00 +0800734 self._RecordExceptions(
735 traceback.format_exception_only(*sys.exc_info()[:2]))
Hung-Te Lina452d4d2017-10-25 17:46:14 +0800736 # But keep going
737 finally:
738 self.run_queue.task_done()
739 return True
740
Peter Shih658d41d2018-04-16 15:42:00 +0800741 def _RunQueueIdle(self):
Hung-Te Lina452d4d2017-10-25 17:46:14 +0800742 """Invoked when the run queue has no events.
743
744 This method must not raise exception.
745 """
746 now = time.time()
747 if (self.last_idle and
748 now < (self.last_idle + RUN_QUEUE_TIMEOUT_SECS - 1)):
749 # Don't run more often than once every (RUN_QUEUE_TIMEOUT_SECS -
750 # 1) seconds.
751 return
752
753 self.last_idle = now
Peter Shih658d41d2018-04-16 15:42:00 +0800754 self._PerformPeriodicTasks()
Hung-Te Lina452d4d2017-10-25 17:46:14 +0800755
Peter Shih658d41d2018-04-16 15:42:00 +0800756 def _CheckExceptions(self):
Hung-Te Lina452d4d2017-10-25 17:46:14 +0800757 """Raises an error if any exceptions have occurred in
758 invocation threads.
759 """
760 if self.exceptions:
761 raise RuntimeError('Exception in invocation thread: %r' %
762 self.exceptions)
763
Peter Shih658d41d2018-04-16 15:42:00 +0800764 def _RecordExceptions(self, msg):
Hung-Te Lina452d4d2017-10-25 17:46:14 +0800765 """Records an exception in an invocation thread.
766
767 An exception with the given message will be rethrown when
768 Goofy is destroyed.
769 """
770 self.exceptions.append(msg)
771
772 @staticmethod
Peter Shih658d41d2018-04-16 15:42:00 +0800773 def DrainNondaemonThreads():
Hung-Te Lina452d4d2017-10-25 17:46:14 +0800774 """Wait for all non-current non-daemon threads to exit.
775
776 This is performed by the Python runtime in an atexit handler,
777 but this implementation allows us to do more detailed logging, and
778 to support control-C for abrupt shutdown.
779 """
780 cur_thread = threading.current_thread()
781 all_threads_joined = False
782 while not all_threads_joined:
783 for thread in threading.enumerate():
784 if not thread.daemon and thread.is_alive() and thread is not cur_thread:
785 logging.info("Waiting for thread '%s'...", thread.name)
786 thread.join()
787 # We break rather than continue on because the thread list
788 # may have changed while we waited
789 break
790 else:
791 # No threads remain
792 all_threads_joined = True
793 return all_threads_joined
794
795 @staticmethod
Peter Shih658d41d2018-04-16 15:42:00 +0800796 def RunMainAndExit():
Hung-Te Lina452d4d2017-10-25 17:46:14 +0800797 """Instantiate the receiver, run its main function, and exit when done.
798
799 This static method is the "entry point" for Goofy.
800 It instantiates the receiver and invokes its main function, while
801 handling exceptions. When main() finishes (normally or via an exception),
802 it exits the process.
803 """
804 try:
805 cls = Goofy
806 goofy = cls()
807 except Exception:
808 logging.info('Failed to instantiate %s, shutting down.', cls.__name__)
809 traceback.print_exc()
810 os._exit(1) # pylint: disable=protected-access
811 sys.exit(1)
812
813 try:
Peter Shih658d41d2018-04-16 15:42:00 +0800814 goofy.Main()
Hung-Te Lina452d4d2017-10-25 17:46:14 +0800815 except SystemExit:
816 # Propagate SystemExit without logging.
817 raise
818 except KeyboardInterrupt:
819 logging.info('Interrupted, shutting down...')
820 except Exception:
821 # Log the error before trying to shut down
822 logging.exception('Error in main loop')
823 raise
824 finally:
825 try:
826 # We drain threads manually, rather than letting Python do it,
827 # so that we can report to the user which threads are stuck
Peter Shih658d41d2018-04-16 15:42:00 +0800828 goofy.Destroy()
829 cls.DrainNondaemonThreads()
Hung-Te Lina452d4d2017-10-25 17:46:14 +0800830 except (KeyboardInterrupt, Exception):
831 # We got a keyboard interrupt while attempting to shut down.
832 # The user is waiting impatiently! This can happen if threads get stuck.
833 # We need to exit via os._exit, not sys.exit, because sys.exit() will
834 # run the main thread's atexit handler, which waits for all threads to
835 # exit, which is likely how we got stuck in the first place. However, we
836 # do want to capture all logs, so we shut down logging gracefully.
837 logging.info('Graceful shutdown interrupted, shutting down abruptly')
838 logging.shutdown()
839 os._exit(1) # pylint: disable=protected-access
840 # Normal exit path
841 sys.exit(0)
842
Peter Shih658d41d2018-04-16 15:42:00 +0800843 def _CheckPlugins(self):
Earl Oua3bca122016-10-21 16:00:30 +0800844 """Check plugins to be paused or resumed."""
845 exclusive_resources = set()
Yilin Yang90761402020-05-14 13:23:05 +0800846 for invoc in self.invocations.values():
Earl Oua3bca122016-10-21 16:00:30 +0800847 exclusive_resources = exclusive_resources.union(
Peter Shih06d08212018-01-19 17:15:57 +0800848 invoc.test.GetExclusiveResources())
Earl Oua3bca122016-10-21 16:00:30 +0800849 self.plugin_controller.PauseAndResumePluginByResource(exclusive_resources)
850
Peter Shih658d41d2018-04-16 15:42:00 +0800851 def _CheckForUpdates(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800852 """Schedules an asynchronous check for updates if necessary."""
cychiang21886742012-07-05 15:16:32 +0800853 if not self.test_list.options.update_period_secs:
854 # Not enabled.
855 return
856
857 now = time.time()
858 if self.last_update_check and (
859 now - self.last_update_check <
860 self.test_list.options.update_period_secs):
861 # Not yet time for another check.
862 return
863
864 self.last_update_check = now
865
Peter Shih658d41d2018-04-16 15:42:00 +0800866 def _HandleCheckForUpdate(reached_server, toolkit_version, needs_update):
Hung-Te Lind151bf32017-08-30 11:05:47 +0800867 if reached_server:
You-Cheng Syud4a24bf2017-08-21 17:56:48 +0800868 new_update_toolkit_version = toolkit_version if needs_update else None
869 if self.dut.info.update_toolkit_version != new_update_toolkit_version:
870 logging.info('Received new update TOOLKIT_VERSION: %s',
871 new_update_toolkit_version)
872 self.dut.info.Overrides('update_toolkit_version',
873 new_update_toolkit_version)
Peter Shih658d41d2018-04-16 15:42:00 +0800874 self.RunEnqueue(self._UpdateSystemInfo)
You-Cheng Syud4a24bf2017-08-21 17:56:48 +0800875 elif not self._suppress_periodic_update_messages:
876 logging.warning('Suppress error messages for periodic update checking '
877 'after the first one.')
878 self._suppress_periodic_update_messages = True
cychiang21886742012-07-05 15:16:32 +0800879
880 updater.CheckForUpdateAsync(
Peter Shih658d41d2018-04-16 15:42:00 +0800881 _HandleCheckForUpdate, None, self._suppress_periodic_update_messages)
cychiang21886742012-07-05 15:16:32 +0800882
Peter Shih658d41d2018-04-16 15:42:00 +0800883 def CancelPendingTests(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800884 """Cancels any tests in the run queue."""
Peter Shih658d41d2018-04-16 15:42:00 +0800885 self._RunTests(None)
Jon Salza6711d72012-07-18 14:33:03 +0800886
Peter Shih658d41d2018-04-16 15:42:00 +0800887 def _RestoreActiveRunState(self):
Ricky Liang4bff3e32014-02-20 18:46:11 +0800888 """Restores active run id and the list of scheduled tests."""
Fei Shaoee5943d2018-10-10 09:41:41 +0800889 self.run_id = self.state_instance.DataShelfGetValue('run_id', optional=True)
890 self.scheduled_run_tests = self.state_instance.DataShelfGetValue(
Ricky Liang4bff3e32014-02-20 18:46:11 +0800891 'scheduled_run_tests', optional=True)
892
Peter Shih658d41d2018-04-16 15:42:00 +0800893 def _SetActiveRunState(self):
Ricky Liang4bff3e32014-02-20 18:46:11 +0800894 """Sets active run id and the list of scheduled tests."""
895 self.run_id = str(uuid.uuid4())
Wei-Han Chenc17b4112016-11-22 14:56:51 +0800896 # try our best to predict which tests will be run.
Wei-Han Chenbcac7252017-04-21 19:46:51 +0800897 self.scheduled_run_tests = self.test_list_iterator.GetPendingTests()
Fei Shaoee5943d2018-10-10 09:41:41 +0800898 self.state_instance.DataShelfSetValue('run_id', self.run_id)
899 self.state_instance.DataShelfSetValue('scheduled_run_tests',
900 self.scheduled_run_tests)
Ricky Liang4bff3e32014-02-20 18:46:11 +0800901
Peter Shih658d41d2018-04-16 15:42:00 +0800902 def _RunTests(self, subtree, status_filter=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800903 """Runs tests under subtree.
Jon Salz258a40c2012-04-19 12:34:01 +0800904
Wei-Han Chenc17b4112016-11-22 14:56:51 +0800905 Run tests under a given subtree.
Jon Salzb1b39092012-05-03 02:05:09 +0800906
Ricky Liang6fe218c2013-12-27 15:17:17 +0800907 Args:
Wei-Han Chenc17b4112016-11-22 14:56:51 +0800908 subtree: root of subtree to run or None to run nothing.
Chih-Yu Huang85dc63c2015-08-12 15:21:28 +0800909 status_filter: List of available test states. Only run the tests which
910 states are in the list. Set to None if all test states are available.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800911 """
Hung-Te Lin793d6572017-09-04 18:17:56 +0800912 self.hooks.OnTestStart()
Wei-Han Chenc17b4112016-11-22 14:56:51 +0800913 self.test_list_iterator = TestListIterator(
914 subtree, status_filter, self.test_list)
915 if subtree is not None:
Peter Shih658d41d2018-04-16 15:42:00 +0800916 self._SetActiveRunState()
917 self._RunNextTest()
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800918
Peter Shih658d41d2018-04-16 15:42:00 +0800919 def ReapCompletedTests(self):
Peter Shih0d4f77a2018-01-19 16:15:49 +0800920 """Removes completed tests from the set of active tests."""
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +0800921 test_completed = False
Peter Shih06d08212018-01-19 17:15:57 +0800922 # Since items are removed while iterating, make a copy using values()
923 # instead of itervalues().
Yilin Yang3580e242019-12-12 09:34:31 +0800924 for invoc in list(self.invocations.values()):
Peter Shih06d08212018-01-19 17:15:57 +0800925 test = invoc.test
926 if invoc.IsCompleted():
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +0800927 test_completed = True
Peter Shih06d08212018-01-19 17:15:57 +0800928 new_state = test.UpdateState(**invoc.update_state_on_completion)
929 del self.invocations[invoc.uuid]
Jon Salz0697cbf2012-07-04 15:14:04 +0800930
Johny Lin62ed2a32015-05-13 11:57:12 +0800931 # Stop on failure if flag is true and there is no retry chances.
Chun-Ta Lin54e17e42012-09-06 22:05:13 +0800932 if (self.test_list.options.stop_on_failure and
Johny Lin62ed2a32015-05-13 11:57:12 +0800933 new_state.retries_left < 0 and
Chun-Ta Lin54e17e42012-09-06 22:05:13 +0800934 new_state.status == TestState.FAILED):
935 # Clean all the tests to cause goofy to stop.
Hung-Te Lin03f1fc22017-10-16 16:38:31 +0800936 session.console.info('Stop on failure triggered. Empty the queue.')
Peter Shih658d41d2018-04-16 15:42:00 +0800937 self.CancelPendingTests()
Chun-Ta Lin54e17e42012-09-06 22:05:13 +0800938
Jon Salz1acc8742012-07-17 17:45:55 +0800939 if new_state.iterations_left and new_state.status == TestState.PASSED:
940 # Play it again, Sam!
Peter Shih658d41d2018-04-16 15:42:00 +0800941 self._RunTest(test)
Cheng-Yi Chiangce05c002013-04-04 02:13:17 +0800942 # new_state.retries_left is obtained after update.
943 # For retries_left == 0, test can still be run for the last time.
944 elif (new_state.retries_left >= 0 and
945 new_state.status == TestState.FAILED):
946 # Still have to retry, Sam!
Peter Shih658d41d2018-04-16 15:42:00 +0800947 self._RunTest(test)
Jon Salz1acc8742012-07-17 17:45:55 +0800948
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +0800949 if test_completed:
Vic Yangf01c59f2013-04-19 17:37:56 +0800950 self.log_watcher.KickWatchThread()
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +0800951
Peter Shih658d41d2018-04-16 15:42:00 +0800952 def _KillActiveTests(self, abort, root=None, reason=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800953 """Kills and waits for all active tests.
Jon Salz0697cbf2012-07-04 15:14:04 +0800954
Jon Salz85a39882012-07-05 16:45:04 +0800955 Args:
956 abort: True to change state of killed tests to FAILED, False for
Jon Salz0697cbf2012-07-04 15:14:04 +0800957 UNTESTED.
Jon Salz85a39882012-07-05 16:45:04 +0800958 root: If set, only kills tests with root as an ancestor.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800959 reason: If set, the abort reason.
960 """
Peter Shih658d41d2018-04-16 15:42:00 +0800961 self.ReapCompletedTests()
Peter Shih06d08212018-01-19 17:15:57 +0800962 # Since items are removed while iterating, make a copy using values()
963 # instead of itervalues().
Yilin Yang3580e242019-12-12 09:34:31 +0800964 for invoc in list(self.invocations.values()):
Peter Shih06d08212018-01-19 17:15:57 +0800965 test = invoc.test
Wei-Han Chen3ae204c2017-04-28 19:36:55 +0800966 if root and not test.HasAncestor(root):
Jon Salz85a39882012-07-05 16:45:04 +0800967 continue
968
Hung-Te Lin03f1fc22017-10-16 16:38:31 +0800969 session.console.info('Killing active test %s...', test.path)
Peter Shih0d4f77a2018-01-19 16:15:49 +0800970 invoc.AbortAndJoin(reason)
Hung-Te Lin03f1fc22017-10-16 16:38:31 +0800971 session.console.info('Killed %s', test.path)
Wei-Han Chen3ae204c2017-04-28 19:36:55 +0800972 test.UpdateState(**invoc.update_state_on_completion)
Peter Shih06d08212018-01-19 17:15:57 +0800973 del self.invocations[invoc.uuid]
Jon Salz1acc8742012-07-17 17:45:55 +0800974
Jon Salz0697cbf2012-07-04 15:14:04 +0800975 if not abort:
Wei-Han Chen3ae204c2017-04-28 19:36:55 +0800976 test.UpdateState(status=TestState.UNTESTED)
Peter Shih658d41d2018-04-16 15:42:00 +0800977 self.ReapCompletedTests()
Jon Salz0697cbf2012-07-04 15:14:04 +0800978
Peter Shih658d41d2018-04-16 15:42:00 +0800979 def Stop(self, root=None, fail=False, reason=None):
980 self._KillActiveTests(fail, root, reason)
Wei-Han Chenc17b4112016-11-22 14:56:51 +0800981
Wei-Han Chenbcac7252017-04-21 19:46:51 +0800982 self.test_list_iterator.Stop(root)
Peter Shih658d41d2018-04-16 15:42:00 +0800983 self._RunNextTest()
Jon Salz0697cbf2012-07-04 15:14:04 +0800984
Peter Shih658d41d2018-04-16 15:42:00 +0800985 def ClearState(self, root=None):
Jon Salzd7550792013-07-12 05:49:27 +0800986 if root is None:
987 root = self.test_list
Peter Shih658d41d2018-04-16 15:42:00 +0800988 self.Stop(root, reason='Clearing test state')
Wei-Han Chen3ae204c2017-04-28 19:36:55 +0800989 for f in root.Walk():
cyuehe4d8bda2019-11-25 12:57:20 +0800990 f.UpdateState(status=TestState.UNTESTED if f.IsLeaf() else None,
991 iterations=f.default_iterations,
992 retries=f.default_retries)
993
994 def SetIterationsAndRetries(self, test, iterations, retries):
995 """Set iterations and retries in goofy, ui, and shelf.
996
997 If both iterations and retries are None, then set both value to default.
998 If any of the two is invalid, then the function does nothing but logs.
999 """
1000 if iterations is None and retries is None:
1001 iterations = test.default_iterations
1002 retries = test.default_retries
1003 try:
1004 test.SetIterationsAndRetries(iterations, retries)
1005 test.UpdateState(iterations=iterations, retries=retries)
1006 except ValueError:
1007 logging.exception('Unable to set iterations and retries.')
Jon Salz4712ac72013-02-07 17:12:05 +08001008
Peter Shih658d41d2018-04-16 15:42:00 +08001009 def _AbortActiveTests(self, reason=None):
1010 self._KillActiveTests(True, reason=reason)
Jon Salz0697cbf2012-07-04 15:14:04 +08001011
Peter Shih658d41d2018-04-16 15:42:00 +08001012 def Main(self):
Jon Salzeff94182013-06-19 15:06:28 +08001013 syslog.openlog('goofy')
1014
Jon Salz0697cbf2012-07-04 15:14:04 +08001015 try:
Jon Salzd7550792013-07-12 05:49:27 +08001016 self.status = Status.INITIALIZING
Peter Shih658d41d2018-04-16 15:42:00 +08001017 self.Init()
Jon Salz0697cbf2012-07-04 15:14:04 +08001018 self.event_log.Log('goofy_init',
Ricky Liang45c73e72015-01-15 15:00:30 +08001019 success=True)
Chun-Ta Lin53cbbd52016-06-08 21:42:19 +08001020 testlog.Log(
Joel Kitching9eb203a2016-04-21 15:36:30 +08001021 testlog.StationInit({
Hung-Te Linda8eb992017-09-28 03:27:12 +08001022 'stationDeviceId': session.GetDeviceID(),
1023 'stationInstallationId': session.GetInstallationID(),
1024 'count': session.GetInitCount(),
Joel Kitching9eb203a2016-04-21 15:36:30 +08001025 'success': True}))
Hung-Te Linc8174b52017-06-02 11:11:45 +08001026 except Exception:
Joel Kitching9eb203a2016-04-21 15:36:30 +08001027 try:
1028 if self.event_log:
Jon Salz0697cbf2012-07-04 15:14:04 +08001029 self.event_log.Log('goofy_init',
Ricky Liang45c73e72015-01-15 15:00:30 +08001030 success=False,
1031 trace=traceback.format_exc())
Chun-Ta Lin53cbbd52016-06-08 21:42:19 +08001032 if self.testlog:
1033 testlog.Log(
Joel Kitching9eb203a2016-04-21 15:36:30 +08001034 testlog.StationInit({
Hung-Te Linda8eb992017-09-28 03:27:12 +08001035 'stationDeviceId': session.GetDeviceID(),
1036 'stationInstallationId': session.GetInstallationID(),
1037 'count': session.GetInitCount(),
Joel Kitching9eb203a2016-04-21 15:36:30 +08001038 'success': False,
1039 'failureMessage': traceback.format_exc()}))
Hung-Te Linc8174b52017-06-02 11:11:45 +08001040 except Exception:
Joel Kitching9eb203a2016-04-21 15:36:30 +08001041 pass
Jon Salz0697cbf2012-07-04 15:14:04 +08001042 raise
1043
Jon Salzd7550792013-07-12 05:49:27 +08001044 self.status = Status.RUNNING
Jon Salzeff94182013-06-19 15:06:28 +08001045 syslog.syslog('Goofy (factory test harness) starting')
Chun-Ta Lin5d12b592015-06-30 00:54:23 -07001046 syslog.syslog('Boot sequence = %d' % GetBootSequence())
Hung-Te Linda8eb992017-09-28 03:27:12 +08001047 syslog.syslog('Goofy init count = %d' % session.GetInitCount())
Peter Shih658d41d2018-04-16 15:42:00 +08001048 self.Run()
Jon Salz0697cbf2012-07-04 15:14:04 +08001049
Peter Shih658d41d2018-04-16 15:42:00 +08001050 def _UpdateSystemInfo(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001051 """Updates system info."""
Shen-En Shihce8ffe02017-08-01 18:58:09 +08001052 logging.info('Received a notify to update system info.')
1053 self.dut.info.Invalidate()
1054
1055 # Propagate this notify to goofy components
1056 try:
1057 status_monitor = plugin_controller.GetPluginRPCProxy(
1058 'status_monitor.status_monitor')
1059 status_monitor.UpdateDeviceInfo()
1060 except Exception:
1061 logging.debug('Failed to update status monitor plugin.')
Jon Salz0697cbf2012-07-04 15:14:04 +08001062
Peter Shih658d41d2018-04-16 15:42:00 +08001063 def SetForceAutoRun(self):
Fei Shaoee5943d2018-10-10 09:41:41 +08001064 self.state_instance.DataShelfSetValue(TESTS_AFTER_SHUTDOWN, FORCE_AUTO_RUN)
Wei-Han Chen8d7fbc42017-10-18 19:20:47 +08001065
Peter Shih658d41d2018-04-16 15:42:00 +08001066 def UpdateFactory(self, auto_run_on_restart=False, post_update_hook=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001067 """Commences updating factory software.
Jon Salzeb42f0d2012-07-27 19:14:04 +08001068
1069 Args:
1070 auto_run_on_restart: Auto-run when the machine comes back up.
1071 post_update_hook: Code to call after update but immediately before
1072 restart.
1073
1074 Returns:
1075 Never if the update was successful (we just reboot).
1076 False if the update was unnecessary (no update available).
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001077 """
Peter Shih658d41d2018-04-16 15:42:00 +08001078 self._KillActiveTests(False, reason='Factory software update')
1079 self.CancelPendingTests()
Jon Salz0697cbf2012-07-04 15:14:04 +08001080
Peter Shih658d41d2018-04-16 15:42:00 +08001081 def PreUpdateHook():
Jon Salz5c344f62012-07-13 14:31:16 +08001082 if auto_run_on_restart:
Peter Shih658d41d2018-04-16 15:42:00 +08001083 self.SetForceAutoRun()
Marco Chen13394912018-10-11 22:00:34 +08001084 self.state_instance.Close()
Jon Salz5c344f62012-07-13 14:31:16 +08001085
Peter Shih658d41d2018-04-16 15:42:00 +08001086 if updater.TryUpdate(pre_update_hook=PreUpdateHook):
Jon Salzeb42f0d2012-07-27 19:14:04 +08001087 if post_update_hook:
1088 post_update_hook()
1089 self.env.shutdown('reboot')
Jon Salz0697cbf2012-07-04 15:14:04 +08001090
Peter Shih658d41d2018-04-16 15:42:00 +08001091 def _HandleSignal(self, signum, unused_frame):
chuntsen9d675c62017-06-20 14:35:30 +08001092 names = [signame for signame in dir(signal) if signame.startswith('SIG') and
1093 getattr(signal, signame) == signum]
1094 signal_name = ', '.join(names) if names else 'UNKNOWN'
1095 logging.error('Received signal %s(%d)', signal_name, signum)
Peter Shih658d41d2018-04-16 15:42:00 +08001096 self.RunEnqueue(None)
Peter Shihbe962972018-02-23 12:46:41 +08001097 raise KeyboardInterrupt
Jon Salz77c151e2012-08-28 07:20:37 +08001098
Jon Salz128b0932013-07-03 16:55:26 +08001099 def GetTestList(self, test_list_id):
1100 """Returns the test list with the given ID.
1101
1102 Raises:
1103 TestListError: The test list ID is not valid.
1104 """
1105 try:
1106 return self.test_lists[test_list_id]
1107 except KeyError:
Peter Shihd14623e2017-11-14 15:12:54 +08001108 raise type_utils.TestListError(
Wei-Han Chendbc0fa22017-09-28 10:29:53 +08001109 '%r is not a valid test list ID (available IDs are %r)' % (
1110 test_list_id, sorted(self.test_lists.keys())))
Jon Salz128b0932013-07-03 16:55:26 +08001111
Chih-Yu Huang1725d622017-03-24 16:08:35 +08001112 def _RecordStartError(self, error_message):
1113 """Appends the startup error message into the shared data."""
1114 KEY = 'startup_error'
Fei Shaoee5943d2018-10-10 09:41:41 +08001115 data = self.state_instance.DataShelfGetValue(KEY, optional=True)
Chih-Yu Huang1725d622017-03-24 16:08:35 +08001116 new_data = '%s\n\n%s' % (data, error_message) if data else error_message
Fei Shaoee5943d2018-10-10 09:41:41 +08001117 self.state_instance.DataShelfSetValue(KEY, new_data)
Chih-Yu Huang1725d622017-03-24 16:08:35 +08001118
Peter Shih658d41d2018-04-16 15:42:00 +08001119 def _InitTestLists(self):
Joel Kitching50a63ea2016-02-22 13:15:09 +08001120 """Reads in all test lists and sets the active test list.
1121
1122 Returns:
1123 True if the active test list could be set, False if failed.
1124 """
Joel Kitching50a63ea2016-02-22 13:15:09 +08001125 try:
Yong Hongf879cbd2018-11-08 16:06:52 +08001126 startup_errors = []
Jon Salz128b0932013-07-03 16:55:26 +08001127
Yong Hong5ec7a7a2018-11-08 17:00:32 +08001128 self.test_lists, failed_test_lists = (
1129 self.test_list_manager.BuildAllTestLists())
Yong Hongf879cbd2018-11-08 16:06:52 +08001130
1131 logging.info('Loaded test lists: %r', sorted(self.test_lists.keys()))
1132
1133 # Check for any syntax errors in test list files.
Yong Hong5ec7a7a2018-11-08 17:00:32 +08001134 if failed_test_lists:
1135 logging.info('Failed test list IDs: [%s]',
1136 ' '.join(failed_test_lists.keys()))
Yilin Yangea784662019-09-26 13:51:03 +08001137 for test_list_id, reason in iteritems(failed_test_lists):
Yong Hong5ec7a7a2018-11-08 17:00:32 +08001138 logging.error('Error in test list %s: %s', test_list_id, reason)
1139 startup_errors.append('Error in test list %s:\n%s'
1140 % (test_list_id, reason))
Yong Hongf879cbd2018-11-08 16:06:52 +08001141
1142 active_test_list = self.test_list_manager.GetActiveTestListId()
1143
1144 # Check for a non-existent test list ID.
1145 try:
1146 self.test_list = self.GetTestList(active_test_list)
1147 logging.info('Active test list: %s', self.test_list.test_list_id)
1148 except type_utils.TestListError as e:
1149 logging.exception('Invalid active test list: %s', active_test_list)
Yilin Yang58948af2019-10-30 18:28:55 +08001150 startup_errors.append(str(e))
Yong Hongf879cbd2018-11-08 16:06:52 +08001151
1152 # Show all startup errors.
1153 if startup_errors:
1154 self._RecordStartError('\n\n'.join(startup_errors))
1155
1156 except Exception:
1157 logging.exception('Unable to initialize test lists')
1158 self._RecordStartError(
1159 'Unable to initialize test lists\n%s' % traceback.format_exc())
1160
1161 success = bool(self.test_list)
1162 if not success:
1163 # Create an empty test list with default options so that the rest of
1164 # startup can proceed.
1165 # A message box will pop up in UI for the error details.
1166 self.test_list = manager.DummyTestList(self.test_list_manager)
1167
1168 # After SKU ID is updated and DUT is reboot, test list might be switched
1169 # because model name is changed too. In this case, shared state should be
1170 # cleared; otherwise shared data like TESTS_AFTER_SHUTDOWN prevents tests
1171 # from running automatically.
1172 previous_id = self.state_instance.DataShelfGetValue(ACTIVE_TEST_LIST_ID,
1173 optional=True)
1174 if previous_id != self.test_list.test_list_id:
1175 logging.info('Test list is changed from %s to %s.',
1176 previous_id, self.test_list.test_list_id)
1177 if previous_id:
1178 self._ResetStateInstance()
1179
1180 self.state_instance.DataShelfSetValue(ACTIVE_TEST_LIST_ID,
1181 self.test_list.test_list_id)
1182
1183 self.test_list.state_instance = self.state_instance
Joel Kitching50a63ea2016-02-22 13:15:09 +08001184
1185 # Only return False if failed to load the active test list.
Yong Hongf879cbd2018-11-08 16:06:52 +08001186 return success
Jon Salz128b0932013-07-03 16:55:26 +08001187
Peter Shih658d41d2018-04-16 15:42:00 +08001188 def _InitHooks(self):
Shuo-Peng Liao268b40b2013-07-01 15:58:59 +08001189 """Initializes hooks.
1190
1191 Must run after self.test_list ready.
1192 """
Shuo-Peng Liao52b90da2013-06-30 17:00:06 +08001193 module, cls = self.test_list.options.hooks_class.rsplit('.', 1)
1194 self.hooks = getattr(__import__(module, fromlist=[cls]), cls)()
Wei-Han Chen1a114682017-10-02 10:33:54 +08001195 assert isinstance(self.hooks, hooks.Hooks), (
Ricky Liang45c73e72015-01-15 15:00:30 +08001196 'hooks should be of type Hooks but is %r' % type(self.hooks))
Shuo-Peng Liao52b90da2013-06-30 17:00:06 +08001197 self.hooks.test_list = self.test_list
Shuo-Peng Liao268b40b2013-07-01 15:58:59 +08001198 self.hooks.OnCreatedTestList()
Shuo-Peng Liao52b90da2013-06-30 17:00:06 +08001199
Peter Shih658d41d2018-04-16 15:42:00 +08001200 def InitUI(self):
Vic Yanga3cecf82014-12-26 00:44:21 -08001201 """Initialize UI."""
Shen-En Shih65619f42017-10-02 16:52:10 +08001202 logging.info('Waiting for a web socket connection')
1203 self.web_socket_manager.wait()
Vic Yanga3cecf82014-12-26 00:44:21 -08001204 self._ui_initialized = True
Vic Yanga3cecf82014-12-26 00:44:21 -08001205
Hung-Te Lin9d81ac72017-09-21 12:58:01 +08001206 @staticmethod
1207 def GetCommandLineArgsParser():
1208 """Returns a parser for Goofy command line arguments."""
Yilin Yang92930ce2020-03-19 09:58:49 +08001209 parser = argparse.ArgumentParser()
1210 parser.add_argument('-v', '--verbose', action='store_true',
1211 help='Enable debug logging')
1212 parser.add_argument('--restart', action='store_true',
1213 help='Clear all test state')
1214 parser.add_argument('--no-goofy-ui', dest='goofy_ui',
1215 action='store_false', default=True,
1216 help='start without Goofy UI')
Hung-Te Lin9d81ac72017-09-21 12:58:01 +08001217 return parser
1218
Shen-En Shih8227d5d2018-02-06 19:45:39 +08001219 def _PrepareDUTLink(self):
1220 # TODO(akahuang): Move this part into a pytest.
1221 # Prepare DUT link after the plugins start running, because the link might
1222 # need the network connection.
1223
1224 dut_options = self.test_list.options.dut_options
1225 if dut_options:
1226 logging.info('dut_options set by %s: %r', self.test_list.test_list_id,
1227 self.test_list.options.dut_options)
1228
Peter Shih658d41d2018-04-16 15:42:00 +08001229 def PrepareLink():
Shen-En Shih8227d5d2018-02-06 19:45:39 +08001230 try:
1231 device_utils.PrepareDUTLink(**dut_options)
1232 except Exception:
1233 logging.exception('Unable to prepare DUT link.')
1234
Peter Shihdb06b092018-04-16 16:55:38 +08001235 process_utils.StartDaemonThread(target=PrepareLink)
Shen-En Shih8227d5d2018-02-06 19:45:39 +08001236
Peter Shih658d41d2018-04-16 15:42:00 +08001237 def Init(self, args=None, env=None):
Hung-Te Lin9d81ac72017-09-21 12:58:01 +08001238 """Initializes Goofy.
1239
1240 Args:
Shen-En Shihe05cbbc2017-10-02 16:47:30 +08001241 args: A list of command-line arguments. Uses sys.argv if args is None.
1242 env: An Environment instance to use (or None to use DUTEnvironment).
Hung-Te Lin9d81ac72017-09-21 12:58:01 +08001243 """
Yilin Yang92930ce2020-03-19 09:58:49 +08001244 self.args = self.GetCommandLineArgsParser().parse_args(args)
Jon Salz0697cbf2012-07-04 15:14:04 +08001245
Peter Shih658d41d2018-04-16 15:42:00 +08001246 signal.signal(signal.SIGINT, self._HandleSignal)
1247 signal.signal(signal.SIGTERM, self._HandleSignal)
Hung-Te Lina846f602014-07-04 20:32:22 +08001248 # TODO(hungte) SIGTERM does not work properly without Telemetry and should
1249 # be fixed.
Hung-Te Lina846f602014-07-04 20:32:22 +08001250
Jon Salz46b89562012-07-05 11:49:22 +08001251 # Make sure factory directories exist.
Peter Shihb4e49352017-05-25 17:35:11 +08001252 for path in [
1253 paths.DATA_LOG_DIR, paths.DATA_STATE_DIR, paths.DATA_TESTS_DIR]:
1254 file_utils.TryMakeDirs(path)
Jon Salz46b89562012-07-05 11:49:22 +08001255
Wei-Han Chen78f35f62017-03-06 20:11:20 +08001256 try:
1257 goofy_default_options = config_utils.LoadConfig(validate_schema=False)
Yilin Yangea784662019-09-26 13:51:03 +08001258 for key, value in iteritems(goofy_default_options):
Yilin Yang92930ce2020-03-19 09:58:49 +08001259 if getattr(self.args, key, None) is None:
1260 logging.info('self.args.%s = %r', key, value)
1261 setattr(self.args, key, value)
Wei-Han Chen78f35f62017-03-06 20:11:20 +08001262 except Exception:
1263 logging.exception('failed to load goofy overriding options')
1264
Jon Salzee85d522012-07-17 14:34:46 +08001265 event_log.IncrementBootSequence()
Hung-Te Linda8eb992017-09-28 03:27:12 +08001266 session.IncrementInitCount()
Chun-Ta Lin53cbbd52016-06-08 21:42:19 +08001267
Jon Salzd15bbcf2013-05-21 17:33:57 +08001268 # Don't defer logging the initial event, so we can make sure
1269 # that device_id, reimage_id, etc. are all set up.
1270 self.event_log = EventLog('goofy', defer=False)
Chun-Ta Lin53cbbd52016-06-08 21:42:19 +08001271 self.testlog = testlog.Testlog(
Peter Shihb4e49352017-05-25 17:35:11 +08001272 log_root=paths.DATA_LOG_DIR, uuid=self.uuid,
Hung-Te Linda8eb992017-09-28 03:27:12 +08001273 stationDeviceId=session.GetDeviceID(),
1274 stationInstallationId=session.GetInstallationID())
Jon Salz0697cbf2012-07-04 15:14:04 +08001275
Jon Salz0697cbf2012-07-04 15:14:04 +08001276 if env:
1277 self.env = env
Shen-En Shihe05cbbc2017-10-02 16:47:30 +08001278 else:
Ricky Liang09d66d82014-09-25 11:20:54 +08001279 self.env = test_environment.DUTEnvironment()
Jon Salz0697cbf2012-07-04 15:14:04 +08001280 self.env.goofy = self
1281
Yilin Yang92930ce2020-03-19 09:58:49 +08001282 if self.args.restart:
Fei Shaobcaa52b2018-09-28 13:27:15 +08001283 state.ClearState()
Jon Salz0697cbf2012-07-04 15:14:04 +08001284
Peter Shih658d41d2018-04-16 15:42:00 +08001285 self._InitGoofyServer()
Peter Shihf821c6a2018-03-05 13:31:22 +08001286 # Both the i18n file and index.html should be registered to Goofy before we
1287 # start the Goofy server, to avoid race condition that Goofy would return
1288 # 404 not found before index.html is registered.
Peter Shih658d41d2018-04-16 15:42:00 +08001289 self._InitI18n()
1290 self._InitStaticFiles()
Peter Shihf821c6a2018-03-05 13:31:22 +08001291
1292 logging.info('Starting goofy server')
1293 self.goofy_server_thread.start()
1294
Marco Chena20766e2018-09-27 18:29:35 +08001295 self._InitStateInstance()
Marco Chena20766e2018-09-27 18:29:35 +08001296
Yong Hongf879cbd2018-11-08 16:06:52 +08001297 # _InitTestLists might reset the state_instance, all initializations which
1298 # rely on the state_instance need to be done after this step.
1299 success = self._InitTestLists()
1300
1301 self._InitGoofyRPC()
Jon Salzb19ea072013-02-07 16:35:00 +08001302
Peter Shih658d41d2018-04-16 15:42:00 +08001303 self._InitHooks()
chuntsen6780ea22017-12-12 14:53:53 +08001304 self.testlog.init_hooks(self.test_list.options.testlog_hooks)
Shuo-Peng Liao268b40b2013-07-01 15:58:59 +08001305
Jon Salz822838b2013-03-25 17:32:33 +08001306 if self.test_list.options.clear_state_on_start:
Wei-Han Chendcecbea2018-03-14 19:00:23 +08001307 # TODO(stimim): Perhaps we should check if we are running `shutdown` test?
Fei Shaobcaa52b2018-09-28 13:27:15 +08001308 self.state_instance.ClearTestState()
Jon Salz822838b2013-03-25 17:32:33 +08001309
Jon Salz670ce062014-05-16 15:53:50 +08001310 # If the phase is invalid, this will raise a ValueError.
1311 phase.SetPersistentPhase(self.test_list.options.phase)
1312
Fei Shaoee5943d2018-10-10 09:41:41 +08001313 if not self.state_instance.DataShelfHasKey('ui_locale'):
Hung-Te Lin134403c2017-08-23 17:30:17 +08001314 ui_locale = self.test_list.options.ui_locale
Fei Shaoee5943d2018-10-10 09:41:41 +08001315 self.state_instance.DataShelfSetValue('ui_locale', ui_locale)
1316 self.state_instance.DataShelfSetValue(
Ricky Liang45c73e72015-01-15 15:00:30 +08001317 'test_list_options',
Peter Shih90425db2017-08-02 15:53:48 +08001318 self.test_list.options.ToDict())
Jon Salz0697cbf2012-07-04 15:14:04 +08001319 self.state_instance.test_list = self.test_list
1320
Peter Shih658d41d2018-04-16 15:42:00 +08001321 self._InitStates()
1322 self._StartEventServer()
Hung-Te Lincc41d2a2014-10-29 13:35:20 +08001323
Earl Oua3bca122016-10-21 16:00:30 +08001324 # Load and run Goofy plugins.
1325 self.plugin_controller = plugin_controller.PluginController(
1326 self.test_list.options.plugin_config_name, self)
1327 self.plugin_controller.StartAllPlugins()
1328
Chih-Yu Huang97103ae2017-03-20 18:22:54 +08001329 if success:
Shen-En Shih8227d5d2018-02-06 19:45:39 +08001330 self._PrepareDUTLink()
Chih-Yu Huang97103ae2017-03-20 18:22:54 +08001331
Jon Salz0697cbf2012-07-04 15:14:04 +08001332 # Note that we create a log watcher even if
1333 # sync_event_log_period_secs isn't set (no background
1334 # syncing), since we may use it to flush event logs as well.
1335 self.log_watcher = EventLogWatcher(
Ricky Liang45c73e72015-01-15 15:00:30 +08001336 self.test_list.options.sync_event_log_period_secs,
1337 event_log_db_file=None,
Peter Shih658d41d2018-04-16 15:42:00 +08001338 handle_event_logs_callback=self._HandleEventLogs)
Jon Salz0697cbf2012-07-04 15:14:04 +08001339 if self.test_list.options.sync_event_log_period_secs:
1340 self.log_watcher.StartWatchThread()
1341
Shen-En Shihf4ad32f2017-07-31 15:56:39 +08001342 self.event_client.post_event(
1343 Event(Event.Type.UPDATE_SYSTEM_INFO))
Jon Salz0697cbf2012-07-04 15:14:04 +08001344
1345 os.environ['CROS_FACTORY'] = '1'
1346 os.environ['CROS_DISABLE_SITE_SYSINFO'] = '1'
1347
Shuo-Peng Liao268b40b2013-07-01 15:58:59 +08001348 # Should not move earlier.
1349 self.hooks.OnStartup()
1350
Ricky Liang36512a32014-07-25 11:47:04 +08001351 # Only after this point the Goofy backend is ready for UI connection.
1352 self.ready_for_ui_connection = True
1353
Jon Salz0697cbf2012-07-04 15:14:04 +08001354 def state_change_callback(test, test_state):
1355 self.event_client.post_event(
Peter Shihd46c5fd2017-09-22 15:28:42 +08001356 Event(
1357 Event.Type.STATE_CHANGE,
1358 path=test.path,
1359 state=test_state.ToStruct()))
Jon Salz0697cbf2012-07-04 15:14:04 +08001360 self.test_list.state_change_callback = state_change_callback
Jon Salz73e0fd02012-04-04 11:46:38 +08001361
Vic Yange2c76a82014-10-30 12:48:19 -07001362 self.pytest_prespawner = prespawner.PytestPrespawner()
1363 self.pytest_prespawner.start()
Jon Salza6711d72012-07-18 14:33:03 +08001364
Fei Shaoee5943d2018-10-10 09:41:41 +08001365 tests_after_shutdown = self.state_instance.DataShelfGetValue(
Wei-Han Chenc17b4112016-11-22 14:56:51 +08001366 TESTS_AFTER_SHUTDOWN, optional=True)
Jon Salz5c344f62012-07-13 14:31:16 +08001367 force_auto_run = (tests_after_shutdown == FORCE_AUTO_RUN)
Wei-Han Chenc17b4112016-11-22 14:56:51 +08001368
Jon Salz5c344f62012-07-13 14:31:16 +08001369 if not force_auto_run and tests_after_shutdown is not None:
Wei-Han Chenc17b4112016-11-22 14:56:51 +08001370 logging.info('Resuming tests after shutdown: %r', tests_after_shutdown)
1371 self.test_list_iterator = tests_after_shutdown
Wei-Han Chenbcac7252017-04-21 19:46:51 +08001372 self.test_list_iterator.SetTestList(self.test_list)
Peter Shih658d41d2018-04-16 15:42:00 +08001373 self.RunEnqueue(self._RunNextTest)
Wei-Han Chenc17b4112016-11-22 14:56:51 +08001374 elif force_auto_run or self.test_list.options.auto_run_on_start:
Peter Shih53323922018-01-02 15:02:21 +08001375 status_filter = [TestState.UNTESTED]
1376 if self.test_list.options.retry_failed_on_start:
1377 status_filter.append(TestState.FAILED)
Peter Shih658d41d2018-04-16 15:42:00 +08001378 self.RunEnqueue(lambda: self._RunTests(self.test_list, status_filter))
Fei Shaoee5943d2018-10-10 09:41:41 +08001379 self.state_instance.DataShelfSetValue(TESTS_AFTER_SHUTDOWN, None)
Peter Shih658d41d2018-04-16 15:42:00 +08001380 self._RestoreActiveRunState()
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001381
Hung-Te Lin793d6572017-09-04 18:17:56 +08001382 self.hooks.OnTestStart()
Vic Yang08505c72015-01-06 17:01:53 -08001383
Peter Shih658d41d2018-04-16 15:42:00 +08001384 def _PerformPeriodicTasks(self):
Hung-Te Lina452d4d2017-10-25 17:46:14 +08001385 """Perform any periodic work.
Vic Yang4953fc12012-07-26 16:19:53 +08001386
Peter Ammon1e1ec572014-06-26 17:56:32 -07001387 This method must not raise exceptions.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001388 """
Peter Shih658d41d2018-04-16 15:42:00 +08001389 self._CheckPlugins()
1390 self._CheckForUpdates()
Jon Salz57717ca2012-04-04 16:47:25 +08001391
Peter Shih658d41d2018-04-16 15:42:00 +08001392 def _HandleEventLogs(self, chunks, periodic=False):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001393 """Callback for event watcher.
Jon Salz258a40c2012-04-19 12:34:01 +08001394
Hung-Te Lind151bf32017-08-30 11:05:47 +08001395 Attempts to upload the event logs to the factory server.
Vic Yang93027612013-05-06 02:42:49 +08001396
1397 Args:
Jon Salzd15bbcf2013-05-21 17:33:57 +08001398 chunks: A list of Chunk objects.
Cheng-Yi Chiangf5b21012015-03-17 15:37:14 +08001399 periodic: This event log handling is periodic. Error messages
1400 will only be shown for the first time.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001401 """
Vic Yang93027612013-05-06 02:42:49 +08001402 first_exception = None
1403 exception_count = 0
1404
Jon Salzd15bbcf2013-05-21 17:33:57 +08001405 for chunk in chunks:
Vic Yang93027612013-05-06 02:42:49 +08001406 try:
Jon Salzcddb6402013-05-23 12:56:42 +08001407 description = 'event logs (%s)' % str(chunk)
Vic Yang93027612013-05-06 02:42:49 +08001408 start_time = time.time()
Peter Shihfdc09c72018-08-06 17:04:49 +08001409 proxy = server_proxy.GetServerProxy()
Hung-Te Lind151bf32017-08-30 11:05:47 +08001410 proxy.UploadEvent(
1411 chunk.log_name + '.' + event_log.GetReimageId(),
Yilin Yangf6994c22019-12-09 16:17:21 +08001412 xmlrpc.client.Binary(chunk.chunk.encode('utf-8')))
Vic Yang93027612013-05-06 02:42:49 +08001413 logging.info(
Ricky Liang45c73e72015-01-15 15:00:30 +08001414 'Successfully synced %s in %.03f s',
1415 description, time.time() - start_time)
Hung-Te Linc8174b52017-06-02 11:11:45 +08001416 except Exception:
Hung-Te Linf707b242016-01-08 23:11:42 +08001417 first_exception = (first_exception or
1418 (chunk.log_name + ': ' +
1419 debug_utils.FormatExceptionOnly()))
Vic Yang93027612013-05-06 02:42:49 +08001420 exception_count += 1
1421
1422 if exception_count:
1423 if exception_count == 1:
1424 msg = 'Log upload failed: %s' % first_exception
1425 else:
1426 msg = '%d log upload failed; first is: %s' % (
1427 exception_count, first_exception)
Cheng-Yi Chiangf5b21012015-03-17 15:37:14 +08001428 # For periodic event log syncing, only show the first error messages.
1429 if periodic:
1430 if not self._suppress_event_log_error_messages:
1431 self._suppress_event_log_error_messages = True
Hung-Te Lind151bf32017-08-30 11:05:47 +08001432 logging.warning('Suppress periodic factory server error messages for '
Cheng-Yi Chiangf5b21012015-03-17 15:37:14 +08001433 'event log syncing after the first one.')
1434 raise Exception(msg)
1435 # For event log syncing by request, show the error messages.
1436 else:
1437 raise Exception(msg)
Vic Yang93027612013-05-06 02:42:49 +08001438
Peter Shih658d41d2018-04-16 15:42:00 +08001439 def _RunTestsWithStatus(self, statuses_to_run, root=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001440 """Runs all top-level tests with a particular status.
Jon Salz0405ab52012-03-16 15:26:52 +08001441
Jon Salz0697cbf2012-07-04 15:14:04 +08001442 All active tests, plus any tests to re-run, are reset.
Jon Salz57717ca2012-04-04 16:47:25 +08001443
Jon Salz0697cbf2012-07-04 15:14:04 +08001444 Args:
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001445 statuses_to_run: The particular status that caller wants to run.
Jon Salz0697cbf2012-07-04 15:14:04 +08001446 starting_at: If provided, only auto-runs tests beginning with
1447 this test.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001448 root: The root of tests to run. If not provided, it will be
1449 the root of all tests.
1450 """
Jon Salz0697cbf2012-07-04 15:14:04 +08001451 root = root or self.test_list
Peter Shih658d41d2018-04-16 15:42:00 +08001452 self._AbortActiveTests('Operator requested run/re-run of certain tests')
1453 self._RunTests(root, status_filter=statuses_to_run)
Jon Salz0405ab52012-03-16 15:26:52 +08001454
Peter Shih658d41d2018-04-16 15:42:00 +08001455 def RestartTests(self, root=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001456 """Restarts all tests."""
Jon Salz0697cbf2012-07-04 15:14:04 +08001457 root = root or self.test_list
Jon Salz0405ab52012-03-16 15:26:52 +08001458
Peter Shih658d41d2018-04-16 15:42:00 +08001459 self._AbortActiveTests('Operator requested restart of certain tests')
Wei-Han Chen3ae204c2017-04-28 19:36:55 +08001460 for test in root.Walk():
1461 test.UpdateState(status=TestState.UNTESTED)
Peter Shih658d41d2018-04-16 15:42:00 +08001462 self._RunTests(root)
Hung-Te Lin96632362012-03-20 21:14:18 +08001463
Peter Shih658d41d2018-04-16 15:42:00 +08001464 def _AutoRun(self, root=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001465 """"Auto-runs" tests that have not been run yet.
Hung-Te Lin96632362012-03-20 21:14:18 +08001466
Jon Salz0697cbf2012-07-04 15:14:04 +08001467 Args:
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001468 root: If provided, the root of tests to run. If not provided, the root
1469 will be test_list (root of all tests).
1470 """
Jon Salz0697cbf2012-07-04 15:14:04 +08001471 root = root or self.test_list
Peter Shih658d41d2018-04-16 15:42:00 +08001472 self._RunTestsWithStatus([TestState.UNTESTED, TestState.ACTIVE], root=root)
Jon Salz968e90b2012-03-18 16:12:43 +08001473
Peter Shih658d41d2018-04-16 15:42:00 +08001474 def Wait(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001475 """Waits for all pending invocations.
Jon Salz0697cbf2012-07-04 15:14:04 +08001476
1477 Useful for testing.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001478 """
Jon Salz1acc8742012-07-17 17:45:55 +08001479 while self.invocations:
Yilin Yang90761402020-05-14 13:23:05 +08001480 for invoc in self.invocations.values():
Peter Shih06d08212018-01-19 17:15:57 +08001481 logging.info('Waiting for %s to complete...', invoc.test)
1482 invoc.thread.join()
Peter Shih658d41d2018-04-16 15:42:00 +08001483 self.ReapCompletedTests()
Jon Salz0697cbf2012-07-04 15:14:04 +08001484
Peter Shih658d41d2018-04-16 15:42:00 +08001485 def _TestFail(self, test):
Hung-Te Lin793d6572017-09-04 18:17:56 +08001486 self.hooks.OnTestFailure(test)
Claire Changd1961a22015-08-05 16:15:55 +08001487
Wei-Han Chenced08ef2016-11-08 09:40:02 +08001488
Hung-Te Lin9d81ac72017-09-21 12:58:01 +08001489def main():
1490 # Logging should be solved first.
Yilin Yang92930ce2020-03-19 09:58:49 +08001491 args = Goofy.GetCommandLineArgsParser().parse_args()
1492 log_utils.InitLogging(verbose=args.verbose)
Hung-Te Lin9d81ac72017-09-21 12:58:01 +08001493
Peter Shih658d41d2018-04-16 15:42:00 +08001494 Goofy.RunMainAndExit()
Hung-Te Lin9d81ac72017-09-21 12:58:01 +08001495
1496
1497if __name__ == '__main__':
1498 main()