blob: ac3dc26d215d506ed373ebd0dc8ad704bb027011 [file] [log] [blame]
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001#!/usr/bin/python -u
Hung-Te Linf2f78f72012-02-08 19:27:11 +08002# -*- coding: utf-8 -*-
3#
Jon Salz37eccbd2012-05-25 16:06:52 +08004# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
Hung-Te Linf2f78f72012-02-08 19:27:11 +08005# Use of this source code is governed by a BSD-style license that can be
6# found in the LICENSE file.
7
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08008"""The main factory flow that runs the factory test and finalizes a device."""
Hung-Te Linf2f78f72012-02-08 19:27:11 +08009
Joel Kitchingb85ed7f2014-10-08 18:24:39 +080010from __future__ import print_function
11
Jon Salze12c2b32013-06-25 16:24:34 +080012import glob
Jon Salz0405ab52012-03-16 15:26:52 +080013import logging
14import os
Jon Salze12c2b32013-06-25 16:24:34 +080015import shutil
Jon Salz77c151e2012-08-28 07:20:37 +080016import signal
Jon Salz0405ab52012-03-16 15:26:52 +080017import sys
Jon Salzeff94182013-06-19 15:06:28 +080018import syslog
Jon Salz0405ab52012-03-16 15:26:52 +080019import threading
20import time
21import traceback
Jon Salz258a40c2012-04-19 12:34:01 +080022import uuid
Jon Salzb10cf512012-08-09 17:29:21 +080023from xmlrpclib import Binary
Hung-Te Linf2f78f72012-02-08 19:27:11 +080024from collections import deque
25from optparse import OptionParser
Hung-Te Linf2f78f72012-02-08 19:27:11 +080026
Jon Salz0697cbf2012-07-04 15:14:04 +080027import factory_common # pylint: disable=W0611
Hung-Te Lin91492a12014-11-25 18:56:30 +080028from cros.factory.test import event_log
jcliangcd688182012-08-20 21:01:26 +080029from cros.factory import system
Chun-Ta Lin5d12b592015-06-30 00:54:23 -070030from cros.factory.test.event_log import EventLog, FloatDigit, GetBootSequence
Hung-Te Lincc41d2a2014-10-29 13:35:20 +080031from cros.factory.goofy import connection_manager
Vic Yangd80ea752014-09-24 16:07:14 +080032from cros.factory.goofy import test_environment
33from cros.factory.goofy import time_sanitizer
34from cros.factory.goofy import updater
35from cros.factory.goofy.goofy_base import GoofyBase
36from cros.factory.goofy.goofy_rpc import GoofyRPC
37from cros.factory.goofy.invocation import TestArgEnv
38from cros.factory.goofy.invocation import TestInvocation
39from cros.factory.goofy.link_manager import PresenterLinkManager
Vic Yange2c76a82014-10-30 12:48:19 -070040from cros.factory.goofy import prespawner
Vic Yangd80ea752014-09-24 16:07:14 +080041from cros.factory.goofy.system_log_manager import SystemLogManager
Wei-Ning Huang38b75f02015-02-25 18:25:14 +080042from cros.factory.goofy.terminal_manager import TerminalManager
Vic Yangd80ea752014-09-24 16:07:14 +080043from cros.factory.goofy.web_socket_manager import WebSocketManager
Jon Salzb92c5112012-09-21 15:40:11 +080044from cros.factory.system import disk_space
Hung-Te Lin6a72c642015-12-13 22:09:09 +080045from cros.factory.test import dut
jcliangcd688182012-08-20 21:01:26 +080046from cros.factory.test import factory
Jon Salz670ce062014-05-16 15:53:50 +080047from cros.factory.test import phase
Jon Salz51528e12012-07-02 18:54:45 +080048from cros.factory.test import shopfloor
Hung-Te Lin6a72c642015-12-13 22:09:09 +080049from cros.factory.test import state
Jon Salz83591782012-06-26 11:09:58 +080050from cros.factory.test import utils
Jon Salz128b0932013-07-03 16:55:26 +080051from cros.factory.test.test_lists import test_lists
Ricky Liang6fe218c2013-12-27 15:17:17 +080052from cros.factory.test.e2e_test.common import (
53 AutomationMode, AutomationModePrompt, ParseAutomationMode)
Jon Salz83591782012-06-26 11:09:58 +080054from cros.factory.test.event import Event
55from cros.factory.test.event import EventClient
56from cros.factory.test.event import EventServer
Hung-Te Lin91492a12014-11-25 18:56:30 +080057from cros.factory.test.event_log_watcher import EventLogWatcher
jcliangcd688182012-08-20 21:01:26 +080058from cros.factory.test.factory import TestState
Hung-Te Linc367ac02015-12-22 19:33:23 +080059from cros.factory.test.utils.charge_manager import ChargeManager
60from cros.factory.test.utils.core_dump_manager import CoreDumpManager
61from cros.factory.test.utils.cpufreq_manager import CpufreqManager
Dean Liao592e4d52013-01-10 20:06:39 +080062from cros.factory.tools.key_filter import KeyFilter
Jon Salz2af235d2013-06-24 14:47:21 +080063from cros.factory.utils import file_utils
Joel Kitchingb85ed7f2014-10-08 18:24:39 +080064from cros.factory.utils import net_utils
Jon Salz78c32392012-07-25 14:18:29 +080065from cros.factory.utils.process_utils import Spawn
Hung-Te Linc367ac02015-12-22 19:33:23 +080066from cros.factory.utils.type_utils import Enum
Hung-Te Linf2f78f72012-02-08 19:27:11 +080067
68
Hung-Te Linf2f78f72012-02-08 19:27:11 +080069HWID_CFG_PATH = '/usr/local/share/chromeos-hwid/cfg'
Ricky Liang45c73e72015-01-15 15:00:30 +080070CACHES_DIR = os.path.join(factory.get_state_root(), 'caches')
Hung-Te Linf2f78f72012-02-08 19:27:11 +080071
Cheng-Yi Chiang39d32ad2013-07-23 15:02:38 +080072CLEANUP_LOGS_PAUSED = '/var/lib/cleanup_logs_paused'
73
Jon Salz5c344f62012-07-13 14:31:16 +080074# Value for tests_after_shutdown that forces auto-run (e.g., after
75# a factory update, when the available set of tests might change).
76FORCE_AUTO_RUN = 'force_auto_run'
77
Justin Chuang83813982013-05-13 01:26:32 +080078# Sync disks when battery level is higher than this value.
79# Otherwise, power loss during disk sync operation may incur even worse outcome.
80MIN_BATTERY_LEVEL_FOR_DISK_SYNC = 1.0
81
Ricky Liang45c73e72015-01-15 15:00:30 +080082MAX_CRASH_FILE_SIZE = 64 * 1024
Jon Salze12c2b32013-06-25 16:24:34 +080083
Jon Salzd7550792013-07-12 05:49:27 +080084Status = Enum(['UNINITIALIZED', 'INITIALIZING', 'RUNNING',
85 'TERMINATING', 'TERMINATED'])
86
Ricky Liang45c73e72015-01-15 15:00:30 +080087
Hung-Te Linf2f78f72012-02-08 19:27:11 +080088def get_hwid_cfg():
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +080089 """Returns the HWID config tag, or an empty string if none can be found."""
Jon Salz0697cbf2012-07-04 15:14:04 +080090 if 'CROS_HWID' in os.environ:
91 return os.environ['CROS_HWID']
92 if os.path.exists(HWID_CFG_PATH):
Ricky Liang45c73e72015-01-15 15:00:30 +080093 with open(HWID_CFG_PATH, 'r') as hwid_cfg_handle:
Jon Salz0697cbf2012-07-04 15:14:04 +080094 return hwid_cfg_handle.read().strip()
95 return ''
Hung-Te Linf2f78f72012-02-08 19:27:11 +080096
97
Jon Salz73e0fd02012-04-04 11:46:38 +080098_inited_logging = False
Hung-Te Linf2f78f72012-02-08 19:27:11 +080099
Ricky Liang45c73e72015-01-15 15:00:30 +0800100
Peter Ammon1e1ec572014-06-26 17:56:32 -0700101class Goofy(GoofyBase):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800102 """The main factory flow.
Jon Salz0697cbf2012-07-04 15:14:04 +0800103
104 Note that all methods in this class must be invoked from the main
105 (event) thread. Other threads, such as callbacks and TestInvocation
106 methods, should instead post events on the run queue.
107
108 TODO: Unit tests. (chrome-os-partner:7409)
109
110 Properties:
111 uuid: A unique UUID for this invocation of Goofy.
112 state_instance: An instance of FactoryState.
113 state_server: The FactoryState XML/RPC server.
114 state_server_thread: A thread running state_server.
115 event_server: The EventServer socket server.
116 event_server_thread: A thread running event_server.
117 event_client: A client to the event server.
118 connection_manager: The connection_manager object.
Cheng-Yi Chiang835f2682013-05-06 22:15:48 +0800119 system_log_manager: The SystemLogManager object.
120 core_dump_manager: The CoreDumpManager object.
Jon Salz0697cbf2012-07-04 15:14:04 +0800121 ui_process: The factory ui process object.
Jon Salz0697cbf2012-07-04 15:14:04 +0800122 invocations: A map from FactoryTest objects to the corresponding
123 TestInvocations objects representing active tests.
124 tests_to_run: A deque of tests that should be run when the current
125 test(s) complete.
126 options: Command-line options.
127 args: Command-line args.
128 test_list: The test list.
Jon Salz128b0932013-07-03 16:55:26 +0800129 test_lists: All new-style test lists.
Ricky Liang4bff3e32014-02-20 18:46:11 +0800130 run_id: The identifier for latest test run.
131 scheduled_run_tests: The list of tests scheduled for latest test run.
Jon Salz0697cbf2012-07-04 15:14:04 +0800132 event_handlers: Map of Event.Type to the method used to handle that
133 event. If the method has an 'event' argument, the event is passed
134 to the handler.
Jon Salz3c493bb2013-02-07 17:24:58 +0800135 last_log_disk_space_message: The last message we logged about disk space
136 (to avoid duplication).
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +0800137 last_kick_sync_time: The last time to kick system_log_manager to sync
138 because of core dump files (to avoid kicking too soon then abort the
139 sync.)
Jon Salz416f9cc2013-05-10 18:32:50 +0800140 hooks: A Hooks object containing hooks for various Goofy actions.
Jon Salzd7550792013-07-12 05:49:27 +0800141 status: The current Goofy status (a member of the Status enum).
Peter Ammon948b7172014-07-15 12:43:06 -0700142 link_manager: Instance of PresenterLinkManager for communicating
143 with GoofyPresenter
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800144 """
Ricky Liang45c73e72015-01-15 15:00:30 +0800145
Jon Salz0697cbf2012-07-04 15:14:04 +0800146 def __init__(self):
Peter Ammon1e1ec572014-06-26 17:56:32 -0700147 super(Goofy, self).__init__()
Jon Salz0697cbf2012-07-04 15:14:04 +0800148 self.uuid = str(uuid.uuid4())
149 self.state_instance = None
150 self.state_server = None
151 self.state_server_thread = None
Jon Salz16d10542012-07-23 12:18:45 +0800152 self.goofy_rpc = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800153 self.event_server = None
154 self.event_server_thread = None
155 self.event_client = None
156 self.connection_manager = None
Vic Yang4953fc12012-07-26 16:19:53 +0800157 self.charge_manager = None
Dean Liao88b93192014-10-23 19:37:41 +0800158 self._can_charge = True
Jon Salz8fa8e832012-07-13 19:04:09 +0800159 self.time_sanitizer = None
160 self.time_synced = False
Jon Salz0697cbf2012-07-04 15:14:04 +0800161 self.log_watcher = None
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +0800162 self.system_log_manager = None
Cheng-Yi Chiang835f2682013-05-06 22:15:48 +0800163 self.core_dump_manager = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800164 self.event_log = None
Vic Yange2c76a82014-10-30 12:48:19 -0700165 self.autotest_prespawner = None
166 self.pytest_prespawner = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800167 self.ui_process = None
Vic Yanga3cecf82014-12-26 00:44:21 -0800168 self._ui_initialized = False
Jon Salzc79a9982012-08-30 04:42:01 +0800169 self.dummy_shopfloor = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800170 self.invocations = {}
171 self.tests_to_run = deque()
172 self.visible_test = None
173 self.chrome = None
Jon Salz416f9cc2013-05-10 18:32:50 +0800174 self.hooks = None
Vic Yangd8990da2013-06-27 16:57:43 +0800175 self.cpu_usage_watcher = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800176
177 self.options = None
178 self.args = None
179 self.test_list = None
Jon Salz128b0932013-07-03 16:55:26 +0800180 self.test_lists = None
Ricky Liang4bff3e32014-02-20 18:46:11 +0800181 self.run_id = None
182 self.scheduled_run_tests = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800183 self.env = None
Jon Salzb22d1172012-08-06 10:38:57 +0800184 self.last_idle = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800185 self.last_shutdown_time = None
cychiang21886742012-07-05 15:16:32 +0800186 self.last_update_check = None
Cheng-Yi Chiang194d3c02015-03-16 14:37:15 +0800187 self._suppress_periodic_update_messages = False
Cheng-Yi Chiangf5b21012015-03-17 15:37:14 +0800188 self._suppress_event_log_error_messages = False
Jon Salz8fa8e832012-07-13 19:04:09 +0800189 self.last_sync_time = None
Jon Salzb92c5112012-09-21 15:40:11 +0800190 self.last_log_disk_space_time = None
Jon Salz3c493bb2013-02-07 17:24:58 +0800191 self.last_log_disk_space_message = None
Justin Chuang83813982013-05-13 01:26:32 +0800192 self.last_check_battery_time = None
193 self.last_check_battery_message = None
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +0800194 self.last_kick_sync_time = None
Vic Yang311ddb82012-09-26 12:08:28 +0800195 self.exclusive_items = set()
Jon Salz0f996602012-10-03 15:26:48 +0800196 self.event_log = None
Dean Liao592e4d52013-01-10 20:06:39 +0800197 self.key_filter = None
Jon Salzce6a7f82013-06-10 18:22:54 +0800198 self.cpufreq_manager = None
Jon Salzd7550792013-07-12 05:49:27 +0800199 self.status = Status.UNINITIALIZED
Ricky Liang36512a32014-07-25 11:47:04 +0800200 self.ready_for_ui_connection = False
Peter Ammon1e1ec572014-06-26 17:56:32 -0700201 self.link_manager = None
Hung-Te Linef7f2be2015-07-20 20:38:51 +0800202 self.is_restart_requested = False
Jon Salz0697cbf2012-07-04 15:14:04 +0800203
Hung-Te Lin6a72c642015-12-13 22:09:09 +0800204 # TODO(hungte) Support controlling remote DUT.
205 self.dut = dut.Create()
206
Jon Salz85a39882012-07-05 16:45:04 +0800207 def test_or_root(event, parent_or_group=True):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800208 """Returns the test affected by a particular event.
Jon Salz85a39882012-07-05 16:45:04 +0800209
210 Args:
211 event: The event containing an optional 'path' attribute.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800212 parent_or_group: If True, returns the top-level parent for a test (the
Jon Salz85a39882012-07-05 16:45:04 +0800213 root node of the tests that need to be run together if the given test
214 path is to be run).
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800215 """
Jon Salz0697cbf2012-07-04 15:14:04 +0800216 try:
217 path = event.path
218 except AttributeError:
219 path = None
220
221 if path:
Jon Salz85a39882012-07-05 16:45:04 +0800222 test = self.test_list.lookup_path(path)
223 if parent_or_group:
224 test = test.get_top_level_parent_or_group()
225 return test
Jon Salz0697cbf2012-07-04 15:14:04 +0800226 else:
227 return self.test_list
228
229 self.event_handlers = {
Ricky Liang45c73e72015-01-15 15:00:30 +0800230 Event.Type.SWITCH_TEST: self.handle_switch_test,
231 Event.Type.SHOW_NEXT_ACTIVE_TEST:
232 lambda event: self.show_next_active_test(),
233 Event.Type.RESTART_TESTS:
234 lambda event: self.restart_tests(root=test_or_root(event)),
235 Event.Type.AUTO_RUN:
236 lambda event: self.auto_run(root=test_or_root(event)),
237 Event.Type.RE_RUN_FAILED:
238 lambda event: self.re_run_failed(root=test_or_root(event)),
239 Event.Type.RUN_TESTS_WITH_STATUS:
240 lambda event: self.run_tests_with_status(
241 event.status,
242 root=test_or_root(event)),
243 Event.Type.REVIEW:
244 lambda event: self.show_review_information(),
245 Event.Type.UPDATE_SYSTEM_INFO:
246 lambda event: self.update_system_info(),
247 Event.Type.STOP:
248 lambda event: self.stop(root=test_or_root(event, False),
249 fail=getattr(event, 'fail', False),
250 reason=getattr(event, 'reason', None)),
251 Event.Type.SET_VISIBLE_TEST:
252 lambda event: self.set_visible_test(
253 self.test_list.lookup_path(event.path)),
254 Event.Type.CLEAR_STATE:
255 lambda event: self.clear_state(
256 self.test_list.lookup_path(event.path)),
Wei-Ning Huang38b75f02015-02-25 18:25:14 +0800257 Event.Type.KEY_FILTER_MODE: self.handle_key_filter_mode,
Jon Salz0697cbf2012-07-04 15:14:04 +0800258 }
259
Jon Salz0697cbf2012-07-04 15:14:04 +0800260 self.web_socket_manager = None
Wei-Ning Huang38b75f02015-02-25 18:25:14 +0800261 self.terminal_manager = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800262
263 def destroy(self):
Ricky Liang74237a02014-09-18 15:11:23 +0800264 """Performs any shutdown tasks. Overrides base class method."""
Jon Salzd7550792013-07-12 05:49:27 +0800265 self.status = Status.TERMINATING
Jon Salz0697cbf2012-07-04 15:14:04 +0800266 if self.chrome:
267 self.chrome.kill()
268 self.chrome = None
Jon Salzc79a9982012-08-30 04:42:01 +0800269 if self.dummy_shopfloor:
270 self.dummy_shopfloor.kill()
271 self.dummy_shopfloor = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800272 if self.ui_process:
273 utils.kill_process_tree(self.ui_process, 'ui')
274 self.ui_process = None
275 if self.web_socket_manager:
276 logging.info('Stopping web sockets')
277 self.web_socket_manager.close()
278 self.web_socket_manager = None
279 if self.state_server_thread:
280 logging.info('Stopping state server')
281 self.state_server.shutdown()
282 self.state_server_thread.join()
283 self.state_server.server_close()
284 self.state_server_thread = None
285 if self.state_instance:
286 self.state_instance.close()
287 if self.event_server_thread:
288 logging.info('Stopping event server')
289 self.event_server.shutdown() # pylint: disable=E1101
290 self.event_server_thread.join()
291 self.event_server.server_close()
292 self.event_server_thread = None
293 if self.log_watcher:
294 if self.log_watcher.IsThreadStarted():
295 self.log_watcher.StopWatchThread()
296 self.log_watcher = None
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +0800297 if self.system_log_manager:
298 if self.system_log_manager.IsThreadRunning():
Cheng-Yi Chianga0f6eff2014-01-09 18:27:22 +0800299 self.system_log_manager.Stop()
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +0800300 self.system_log_manager = None
Vic Yange2c76a82014-10-30 12:48:19 -0700301 if self.autotest_prespawner:
302 logging.info('Stopping autotest prespawner')
303 self.autotest_prespawner.stop()
304 self.autotest_prespawner = None
305 if self.pytest_prespawner:
306 logging.info('Stopping pytest prespawner')
307 self.pytest_prespawner.stop()
308 self.pytest_prespawner = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800309 if self.event_client:
310 logging.info('Closing event client')
311 self.event_client.close()
312 self.event_client = None
Jon Salzddf0d052013-06-18 12:52:44 +0800313 if self.cpufreq_manager:
314 self.cpufreq_manager.Stop()
Jon Salz0697cbf2012-07-04 15:14:04 +0800315 if self.event_log:
316 self.event_log.Close()
317 self.event_log = None
Dean Liao592e4d52013-01-10 20:06:39 +0800318 if self.key_filter:
319 self.key_filter.Stop()
Vic Yangd8990da2013-06-27 16:57:43 +0800320 if self.cpu_usage_watcher:
321 self.cpu_usage_watcher.terminate()
Peter Ammon1e1ec572014-06-26 17:56:32 -0700322 if self.link_manager:
323 self.link_manager.Stop()
324 self.link_manager = None
Dean Liao592e4d52013-01-10 20:06:39 +0800325
Peter Ammon1e1ec572014-06-26 17:56:32 -0700326 super(Goofy, self).destroy()
Jon Salz0697cbf2012-07-04 15:14:04 +0800327 logging.info('Done destroying Goofy')
Jon Salzd7550792013-07-12 05:49:27 +0800328 self.status = Status.TERMINATED
Jon Salz0697cbf2012-07-04 15:14:04 +0800329
330 def start_state_server(self):
Jon Salz2af235d2013-06-24 14:47:21 +0800331 # Before starting state server, remount stateful partitions with
332 # no commit flag. The default commit time (commit=600) makes corruption
333 # too likely.
Hung-Te Lind59dbfa2014-08-27 12:27:53 +0800334 utils.ResetCommitTime()
Jon Salz2af235d2013-06-24 14:47:21 +0800335
Jon Salz0697cbf2012-07-04 15:14:04 +0800336 self.state_instance, self.state_server = (
Ricky Liang45c73e72015-01-15 15:00:30 +0800337 state.create_server(bind_address='0.0.0.0'))
Jon Salz16d10542012-07-23 12:18:45 +0800338 self.goofy_rpc = GoofyRPC(self)
339 self.goofy_rpc.RegisterMethods(self.state_instance)
Jon Salz0697cbf2012-07-04 15:14:04 +0800340 logging.info('Starting state server')
341 self.state_server_thread = threading.Thread(
Ricky Liang45c73e72015-01-15 15:00:30 +0800342 target=self.state_server.serve_forever,
343 name='StateServer')
Jon Salz0697cbf2012-07-04 15:14:04 +0800344 self.state_server_thread.start()
345
346 def start_event_server(self):
347 self.event_server = EventServer()
348 logging.info('Starting factory event server')
349 self.event_server_thread = threading.Thread(
Ricky Liang45c73e72015-01-15 15:00:30 +0800350 target=self.event_server.serve_forever,
351 name='EventServer') # pylint: disable=E1101
Jon Salz0697cbf2012-07-04 15:14:04 +0800352 self.event_server_thread.start()
353
354 self.event_client = EventClient(
Ricky Liang45c73e72015-01-15 15:00:30 +0800355 callback=self.handle_event, event_loop=self.run_queue)
Jon Salz0697cbf2012-07-04 15:14:04 +0800356
357 self.web_socket_manager = WebSocketManager(self.uuid)
Ricky Liang45c73e72015-01-15 15:00:30 +0800358 self.state_server.add_handler('/event',
359 self.web_socket_manager.handle_web_socket)
Jon Salz0697cbf2012-07-04 15:14:04 +0800360
Wei-Ning Huang38b75f02015-02-25 18:25:14 +0800361 def start_terminal_server(self):
362 self.terminal_manager = TerminalManager()
363 self.state_server.add_handler('/pty',
364 self.terminal_manager.handle_web_socket)
365
Jon Salz0697cbf2012-07-04 15:14:04 +0800366 def start_ui(self):
367 ui_proc_args = [
Ricky Liang45c73e72015-01-15 15:00:30 +0800368 os.path.join(factory.FACTORY_PACKAGE_PATH, 'test', 'ui.py'),
369 self.options.test_list
370 ]
Jon Salz0697cbf2012-07-04 15:14:04 +0800371 if self.options.verbose:
372 ui_proc_args.append('-v')
373 logging.info('Starting ui %s', ui_proc_args)
Jon Salz78c32392012-07-25 14:18:29 +0800374 self.ui_process = Spawn(ui_proc_args)
Jon Salz0697cbf2012-07-04 15:14:04 +0800375 logging.info('Waiting for UI to come up...')
376 self.event_client.wait(
Ricky Liang45c73e72015-01-15 15:00:30 +0800377 lambda event: event.type == Event.Type.UI_READY)
Jon Salz0697cbf2012-07-04 15:14:04 +0800378 logging.info('UI has started')
379
380 def set_visible_test(self, test):
381 if self.visible_test == test:
382 return
Jon Salz2f2d42c2012-07-30 12:30:34 +0800383 if test and not test.has_ui:
384 return
Jon Salz0697cbf2012-07-04 15:14:04 +0800385
386 if test:
387 test.update_state(visible=True)
388 if self.visible_test:
389 self.visible_test.update_state(visible=False)
390 self.visible_test = test
391
Ricky Liang48e47f92014-02-26 19:31:51 +0800392 def log_startup_messages(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800393 """Logs the tail of var/log/messages and mosys and EC console logs."""
Jon Salzd4306c82012-11-30 15:16:36 +0800394 # TODO(jsalz): This is mostly a copy-and-paste of code in init_states,
395 # for factory-3004.B only. Consolidate and merge back to ToT.
396 if utils.in_chroot():
397 return
398
399 try:
Ricky Liang45c73e72015-01-15 15:00:30 +0800400 var_log_messages = utils.var_log_messages_before_reboot()
Jon Salzd4306c82012-11-30 15:16:36 +0800401 logging.info(
Ricky Liang45c73e72015-01-15 15:00:30 +0800402 'Tail of /var/log/messages before last reboot:\n'
403 '%s', ('\n'.join(
404 ' ' + x for x in var_log_messages)))
Jon Salzd4306c82012-11-30 15:16:36 +0800405 except: # pylint: disable=W0702
406 logging.exception('Unable to grok /var/log/messages')
407
408 try:
Ricky Liang117484a2014-04-14 11:14:41 +0800409 mosys_log = Spawn(
Jon Salzd4306c82012-11-30 15:16:36 +0800410 ['mosys', 'eventlog', 'list'],
411 read_stdout=True, log_stderr_on_error=True).stdout_data
412 logging.info('System eventlog from mosys:\n%s\n', mosys_log)
413 except: # pylint: disable=W0702
414 logging.exception('Unable to read mosys eventlog')
415
Dean Liao88b93192014-10-23 19:37:41 +0800416 self.log_ec_console()
417 self.log_ec_panic_info()
418
419 @staticmethod
420 def log_ec_console():
421 """Logs EC console log into logging.info.
422
423 It logs an error message in logging.exception if an exception is raised
424 when getting EC console log.
425 For unsupported device, it logs unsupport message in logging.info
426
427 Returns:
428 EC console log string.
429 """
Jon Salzd4306c82012-11-30 15:16:36 +0800430 try:
Hung-Te Linb3a09642015-12-14 18:57:23 +0800431 ec_console_log = dut.Create().ec.GetECConsoleLog()
Jon Salzd4306c82012-11-30 15:16:36 +0800432 logging.info('EC console log after reboot:\n%s\n', ec_console_log)
Dean Liao88b93192014-10-23 19:37:41 +0800433 return ec_console_log
434 except NotImplementedError:
435 logging.info('EC console log not supported')
Jon Salzd4306c82012-11-30 15:16:36 +0800436 except: # pylint: disable=W0702
437 logging.exception('Error retrieving EC console log')
438
Dean Liao88b93192014-10-23 19:37:41 +0800439 @staticmethod
440 def log_ec_panic_info():
441 """Logs EC panic info into logging.info.
442
443 It logs an error message in logging.exception if an exception is raised
444 when getting EC panic info.
445 For unsupported device, it logs unsupport message in logging.info
446
447 Returns:
448 EC panic info string.
449 """
Vic Yang079f9872013-07-01 11:32:00 +0800450 try:
Hung-Te Linb3a09642015-12-14 18:57:23 +0800451 ec_panic_info = dut.Create().ec.GetECPanicInfo()
Vic Yang079f9872013-07-01 11:32:00 +0800452 logging.info('EC panic info after reboot:\n%s\n', ec_panic_info)
Dean Liao88b93192014-10-23 19:37:41 +0800453 return ec_panic_info
454 except NotImplementedError:
455 logging.info('EC panic info is not supported')
Vic Yang079f9872013-07-01 11:32:00 +0800456 except: # pylint: disable=W0702
457 logging.exception('Error retrieving EC panic info')
458
Ricky Liang48e47f92014-02-26 19:31:51 +0800459 def shutdown(self, operation):
460 """Starts shutdown procedure.
461
462 Args:
Vic (Chun-Ju) Yang05b0d952014-04-28 17:39:09 +0800463 operation: The shutdown operation (reboot, full_reboot, or halt).
Ricky Liang48e47f92014-02-26 19:31:51 +0800464 """
465 active_tests = []
466 for test in self.test_list.walk():
467 if not test.is_leaf():
468 continue
469
470 test_state = test.get_state()
471 if test_state.status == TestState.ACTIVE:
472 active_tests.append(test)
473
Ricky Liang48e47f92014-02-26 19:31:51 +0800474 if not (len(active_tests) == 1 and
475 isinstance(active_tests[0], factory.ShutdownStep)):
476 logging.error(
477 'Calling Goofy shutdown outside of the shutdown factory test')
478 return
479
480 logging.info('Start Goofy shutdown (%s)', operation)
481 # Save pending test list in the state server
482 self.state_instance.set_shared_data(
483 'tests_after_shutdown',
484 [t.path for t in self.tests_to_run])
485 # Save shutdown time
486 self.state_instance.set_shared_data('shutdown_time', time.time())
487
488 with self.env.lock:
489 self.event_log.Log('shutdown', operation=operation)
490 shutdown_result = self.env.shutdown(operation)
491 if shutdown_result:
492 # That's all, folks!
Peter Ammon1e1ec572014-06-26 17:56:32 -0700493 self.run_enqueue(None)
Ricky Liang48e47f92014-02-26 19:31:51 +0800494 else:
495 # Just pass (e.g., in the chroot).
496 self.state_instance.set_shared_data('tests_after_shutdown', None)
497 # Send event with no fields to indicate that there is no
498 # longer a pending shutdown.
499 self.event_client.post_event(Event(Event.Type.PENDING_SHUTDOWN))
500
501 def handle_shutdown_complete(self, test):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800502 """Handles the case where a shutdown was detected during a shutdown step.
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800503
Ricky Liang6fe218c2013-12-27 15:17:17 +0800504 Args:
505 test: The ShutdownStep.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800506 """
Jon Salz0697cbf2012-07-04 15:14:04 +0800507 test_state = test.update_state(increment_shutdown_count=1)
508 logging.info('Detected shutdown (%d of %d)',
Ricky Liang48e47f92014-02-26 19:31:51 +0800509 test_state.shutdown_count, test.iterations)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800510
Ricky Liang48e47f92014-02-26 19:31:51 +0800511 # Insert current shutdown test at the front of the list of tests to run
512 # after shutdown. This is to continue on post-shutdown verification in the
513 # shutdown step.
514 tests_after_shutdown = self.state_instance.get_shared_data(
515 'tests_after_shutdown', optional=True)
516 if not tests_after_shutdown:
517 self.state_instance.set_shared_data('tests_after_shutdown', [test.path])
518 elif isinstance(tests_after_shutdown, list):
519 self.state_instance.set_shared_data(
520 'tests_after_shutdown', [test.path] + tests_after_shutdown)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800521
Ricky Liang48e47f92014-02-26 19:31:51 +0800522 # Set 'post_shutdown' to inform shutdown test that a shutdown just occurred.
Ricky Liangb7eb8772014-09-15 18:05:22 +0800523 self.state_instance.set_shared_data(
524 state.POST_SHUTDOWN_TAG % test.path,
525 self.state_instance.get_test_state(test.path).invocation)
Jon Salz258a40c2012-04-19 12:34:01 +0800526
Jon Salz0697cbf2012-07-04 15:14:04 +0800527 def init_states(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800528 """Initializes all states on startup."""
Jon Salz0697cbf2012-07-04 15:14:04 +0800529 for test in self.test_list.get_all_tests():
530 # Make sure the state server knows about all the tests,
531 # defaulting to an untested state.
532 test.update_state(update_parent=False, visible=False)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800533
Jon Salz0697cbf2012-07-04 15:14:04 +0800534 var_log_messages = None
Vic Yanga9c32212012-08-16 20:07:54 +0800535 mosys_log = None
Vic Yange4c275d2012-08-28 01:50:20 +0800536 ec_console_log = None
Vic Yang079f9872013-07-01 11:32:00 +0800537 ec_panic_info = None
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800538
Jon Salz0697cbf2012-07-04 15:14:04 +0800539 # Any 'active' tests should be marked as failed now.
540 for test in self.test_list.walk():
Jon Salza6711d72012-07-18 14:33:03 +0800541 if not test.is_leaf():
542 # Don't bother with parents; they will be updated when their
543 # children are updated.
544 continue
545
Jon Salz0697cbf2012-07-04 15:14:04 +0800546 test_state = test.get_state()
547 if test_state.status != TestState.ACTIVE:
548 continue
549 if isinstance(test, factory.ShutdownStep):
550 # Shutdown while the test was active - that's good.
Ricky Liang48e47f92014-02-26 19:31:51 +0800551 self.handle_shutdown_complete(test)
Jon Salz0697cbf2012-07-04 15:14:04 +0800552 else:
553 # Unexpected shutdown. Grab /var/log/messages for context.
554 if var_log_messages is None:
555 try:
556 var_log_messages = (
Ricky Liang45c73e72015-01-15 15:00:30 +0800557 utils.var_log_messages_before_reboot())
Jon Salz0697cbf2012-07-04 15:14:04 +0800558 # Write it to the log, to make it easier to
559 # correlate with /var/log/messages.
560 logging.info(
Ricky Liang45c73e72015-01-15 15:00:30 +0800561 'Unexpected shutdown. '
562 'Tail of /var/log/messages before last reboot:\n'
563 '%s', ('\n'.join(
564 ' ' + x for x in var_log_messages)))
Jon Salz0697cbf2012-07-04 15:14:04 +0800565 except: # pylint: disable=W0702
566 logging.exception('Unable to grok /var/log/messages')
567 var_log_messages = []
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800568
Jon Salz008f4ea2012-08-28 05:39:45 +0800569 if mosys_log is None and not utils.in_chroot():
570 try:
Ricky Liang117484a2014-04-14 11:14:41 +0800571 mosys_log = Spawn(
Jon Salz008f4ea2012-08-28 05:39:45 +0800572 ['mosys', 'eventlog', 'list'],
573 read_stdout=True, log_stderr_on_error=True).stdout_data
574 # Write it to the log also.
575 logging.info('System eventlog from mosys:\n%s\n', mosys_log)
576 except: # pylint: disable=W0702
577 logging.exception('Unable to read mosys eventlog')
Vic Yanga9c32212012-08-16 20:07:54 +0800578
Vic Yange4c275d2012-08-28 01:50:20 +0800579 if ec_console_log is None:
Dean Liao88b93192014-10-23 19:37:41 +0800580 ec_console_log = self.log_ec_console()
Vic Yange4c275d2012-08-28 01:50:20 +0800581
Vic Yang079f9872013-07-01 11:32:00 +0800582 if ec_panic_info is None:
Dean Liao88b93192014-10-23 19:37:41 +0800583 ec_panic_info = self.log_ec_panic_info()
Vic Yang079f9872013-07-01 11:32:00 +0800584
Jon Salz0697cbf2012-07-04 15:14:04 +0800585 error_msg = 'Unexpected shutdown while test was running'
586 self.event_log.Log('end_test',
Ricky Liang45c73e72015-01-15 15:00:30 +0800587 path=test.path,
588 status=TestState.FAILED,
589 invocation=test.get_state().invocation,
590 error_msg=error_msg,
591 var_log_messages='\n'.join(var_log_messages),
592 mosys_log=mosys_log)
Jon Salz0697cbf2012-07-04 15:14:04 +0800593 test.update_state(
Ricky Liang45c73e72015-01-15 15:00:30 +0800594 status=TestState.FAILED,
595 error_msg=error_msg)
Chun-Ta Lin87c2dac2015-05-02 01:35:01 -0700596 # Trigger the OnTestFailure callback.
Claire Changd1961a22015-08-05 16:15:55 +0800597 self.run_queue.put(lambda: self.test_fail(test))
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800598
Jon Salz50efe942012-07-26 11:54:10 +0800599 if not test.never_fails:
600 # For "never_fails" tests (such as "Start"), don't cancel
601 # pending tests, since reboot is expected.
602 factory.console.info('Unexpected shutdown while test %s '
603 'running; cancelling any pending tests',
604 test.path)
605 self.state_instance.set_shared_data('tests_after_shutdown', [])
Jon Salz69806bb2012-07-20 18:05:02 +0800606
Jon Salz008f4ea2012-08-28 05:39:45 +0800607 self.update_skipped_tests()
608
609 def update_skipped_tests(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800610 """Updates skipped states based on run_if."""
Jon Salz885dcac2013-07-23 16:39:50 +0800611 env = TestArgEnv()
Ricky Liang45c73e72015-01-15 15:00:30 +0800612
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800613 def _evaluate_skip_from_run_if(test):
614 """Returns the run_if evaluation of the test.
615
616 Args:
617 test: A FactoryTest object.
618
619 Returns:
620 The run_if evaluation result. Returns False if the test has no
621 run_if argument.
622 """
623 value = None
624 if test.run_if_expr:
625 try:
626 value = test.run_if_expr(env)
627 except: # pylint: disable=W0702
628 logging.exception('Unable to evaluate run_if expression for %s',
629 test.path)
630 # But keep going; we have no choice. This will end up
631 # always activating the test.
632 elif test.run_if_table_name:
633 try:
634 aux = shopfloor.get_selected_aux_data(test.run_if_table_name)
635 value = aux.get(test.run_if_col)
636 except ValueError:
637 # Not available; assume it shouldn't be skipped
638 pass
639
640 if value is None:
641 skip = False
642 else:
643 skip = (not value) ^ t.run_if_not
644 return skip
645
646 # Gets all run_if evaluation, and stores results in skip_map.
647 skip_map = dict()
Jon Salz008f4ea2012-08-28 05:39:45 +0800648 for t in self.test_list.walk():
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800649 skip_map[t.path] = _evaluate_skip_from_run_if(t)
Jon Salz885dcac2013-07-23 16:39:50 +0800650
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800651 # Propagates the skip value from root of tree and updates skip_map.
652 def _update_skip_map_from_node(test, skip_from_parent):
653 """Updates skip_map from a given node.
Jon Salz885dcac2013-07-23 16:39:50 +0800654
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800655 Given a FactoryTest node and the skip value from parent, updates the
656 skip value of current node in the skip_map if skip value from parent is
657 True. If this node has children, recursively propagate this value to all
658 its children, that is, all its subtests.
659 Note that this function only updates value in skip_map, not the actual
660 test_list tree.
Jon Salz008f4ea2012-08-28 05:39:45 +0800661
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800662 Args:
663 test: The given FactoryTest object. It is a node in the test_list tree.
664 skip_from_parent: The skip value which propagates from the parent of
665 input node.
666 """
667 skip_this_tree = skip_from_parent or skip_map[test.path]
668 if skip_this_tree:
669 logging.info('Skip from node %r', test.path)
670 skip_map[test.path] = True
671 if test.is_leaf():
672 return
673 # Propagates skip value to its subtests
674 for subtest in test.subtests:
675 _update_skip_map_from_node(subtest, skip_this_tree)
676
677 _update_skip_map_from_node(self.test_list, False)
678
679 # Updates the skip value from skip_map to test_list tree. Also, updates test
680 # status if needed.
681 for t in self.test_list.walk():
682 skip = skip_map[t.path]
683 test_state = t.get_state()
684 if ((not skip) and
685 (test_state.status == TestState.PASSED) and
686 (test_state.error_msg == TestState.SKIPPED_MSG)):
687 # It was marked as skipped before, but now we need to run it.
688 # Mark as untested.
689 t.update_state(skip=skip, status=TestState.UNTESTED, error_msg='')
690 else:
691 t.update_state(skip=skip)
Jon Salz008f4ea2012-08-28 05:39:45 +0800692
Jon Salz0697cbf2012-07-04 15:14:04 +0800693 def show_next_active_test(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800694 """Rotates to the next visible active test."""
Jon Salz0697cbf2012-07-04 15:14:04 +0800695 self.reap_completed_tests()
696 active_tests = [
Ricky Liang45c73e72015-01-15 15:00:30 +0800697 t for t in self.test_list.walk()
698 if t.is_leaf() and t.get_state().status == TestState.ACTIVE]
Jon Salz0697cbf2012-07-04 15:14:04 +0800699 if not active_tests:
700 return
Jon Salz4f6c7172012-06-11 20:45:36 +0800701
Jon Salz0697cbf2012-07-04 15:14:04 +0800702 try:
703 next_test = active_tests[
Ricky Liang45c73e72015-01-15 15:00:30 +0800704 (active_tests.index(self.visible_test) + 1) % len(active_tests)]
Jon Salz0697cbf2012-07-04 15:14:04 +0800705 except ValueError: # visible_test not present in active_tests
706 next_test = active_tests[0]
Jon Salz4f6c7172012-06-11 20:45:36 +0800707
Jon Salz0697cbf2012-07-04 15:14:04 +0800708 self.set_visible_test(next_test)
Jon Salz4f6c7172012-06-11 20:45:36 +0800709
Jon Salz0697cbf2012-07-04 15:14:04 +0800710 def handle_event(self, event):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800711 """Handles an event from the event server."""
Jon Salz0697cbf2012-07-04 15:14:04 +0800712 handler = self.event_handlers.get(event.type)
713 if handler:
714 handler(event)
715 else:
716 # We don't register handlers for all event types - just ignore
717 # this event.
718 logging.debug('Unbound event type %s', event.type)
Jon Salz4f6c7172012-06-11 20:45:36 +0800719
Vic Yangaabf9fd2013-04-09 18:56:13 +0800720 def check_critical_factory_note(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800721 """Returns True if the last factory note is critical."""
Vic Yangaabf9fd2013-04-09 18:56:13 +0800722 notes = self.state_instance.get_shared_data('factory_note', True)
723 return notes and notes[-1]['level'] == 'CRITICAL'
724
Hung-Te Linef7f2be2015-07-20 20:38:51 +0800725 def schedule_restart(self):
726 """Schedules a restart event when any invocation is completed."""
727 self.is_restart_requested = True
728
729 def invocation_completion(self):
730 """Callback when an invocation is completed."""
731 if self.is_restart_requested:
732 logging.info('Restart by scheduled event.')
733 self.is_restart_requested = False
734 self.restart_tests()
735 else:
736 self.run_next_test()
737
Jon Salz0697cbf2012-07-04 15:14:04 +0800738 def run_next_test(self):
henryhsu4cc6b022014-04-22 17:12:42 +0800739 """Runs the next eligible test (or tests) in self.tests_to_run.
740
741 We have three kinds of the next eligible test:
742 1. normal
743 2. backgroundable
744 3. force_background
745
746 And we have four situations of the ongoing invocations:
747 a. only a running normal test
748 b. all running tests are backgroundable
749 c. all running tests are force_background
750 d. all running tests are any combination of backgroundable and
751 force_background
752
753 When a test would like to be run, it must follow the rules:
754 [1] cannot run with [abd]
755 [2] cannot run with [a]
756 All the other combinations are allowed
757 """
Jon Salz0697cbf2012-07-04 15:14:04 +0800758 self.reap_completed_tests()
Vic Yangaabf9fd2013-04-09 18:56:13 +0800759 if self.tests_to_run and self.check_critical_factory_note():
760 self.tests_to_run.clear()
761 return
Jon Salz0697cbf2012-07-04 15:14:04 +0800762 while self.tests_to_run:
Ricky Liang6fe218c2013-12-27 15:17:17 +0800763 logging.debug('Tests to run: %s', [x.path for x in self.tests_to_run])
Jon Salz94eb56f2012-06-12 18:01:12 +0800764
Jon Salz0697cbf2012-07-04 15:14:04 +0800765 test = self.tests_to_run[0]
Jon Salz94eb56f2012-06-12 18:01:12 +0800766
Jon Salz0697cbf2012-07-04 15:14:04 +0800767 if test in self.invocations:
768 logging.info('Next test %s is already running', test.path)
769 self.tests_to_run.popleft()
770 return
Jon Salz94eb56f2012-06-12 18:01:12 +0800771
Jon Salza1412922012-07-23 16:04:17 +0800772 for requirement in test.require_run:
773 for i in requirement.test.walk():
774 if i.get_state().status == TestState.ACTIVE:
Jon Salz304a75d2012-07-06 11:14:15 +0800775 logging.info('Waiting for active test %s to complete '
Jon Salza1412922012-07-23 16:04:17 +0800776 'before running %s', i.path, test.path)
Jon Salz304a75d2012-07-06 11:14:15 +0800777 return
778
henryhsu4cc6b022014-04-22 17:12:42 +0800779 def is_normal_test(test):
780 return not (test.backgroundable or test.force_background)
781
782 # [1] cannot run with [abd].
783 if self.invocations and is_normal_test(test) and any(
784 [not x.force_background for x in self.invocations]):
785 logging.info('Waiting for non-force_background tests to '
786 'complete before running %s', test.path)
787 return
788
789 # [2] cannot run with [a].
790 if self.invocations and test.backgroundable and any(
791 [is_normal_test(x) for x in self.invocations]):
792 logging.info('Waiting for normal tests to '
793 'complete before running %s', test.path)
Jon Salz0697cbf2012-07-04 15:14:04 +0800794 return
Jon Salz94eb56f2012-06-12 18:01:12 +0800795
Jon Salz3e6f5202012-10-15 15:08:29 +0800796 if test.get_state().skip:
797 factory.console.info('Skipping test %s', test.path)
798 test.update_state(status=TestState.PASSED,
799 error_msg=TestState.SKIPPED_MSG)
800 self.tests_to_run.popleft()
801 continue
802
Jon Salz0697cbf2012-07-04 15:14:04 +0800803 self.tests_to_run.popleft()
Jon Salz94eb56f2012-06-12 18:01:12 +0800804
Jon Salz304a75d2012-07-06 11:14:15 +0800805 untested = set()
Jon Salza1412922012-07-23 16:04:17 +0800806 for requirement in test.require_run:
807 for i in requirement.test.walk():
808 if i == test:
Jon Salz304a75d2012-07-06 11:14:15 +0800809 # We've hit this test itself; stop checking
810 break
Jon Salza1412922012-07-23 16:04:17 +0800811 if ((i.get_state().status == TestState.UNTESTED) or
812 (requirement.passed and i.get_state().status !=
813 TestState.PASSED)):
Jon Salz304a75d2012-07-06 11:14:15 +0800814 # Found an untested test; move on to the next
815 # element in require_run.
Jon Salza1412922012-07-23 16:04:17 +0800816 untested.add(i)
Jon Salz304a75d2012-07-06 11:14:15 +0800817 break
818
819 if untested:
820 untested_paths = ', '.join(sorted([x.path for x in untested]))
821 if self.state_instance.get_shared_data('engineering_mode',
822 optional=True):
823 # In engineering mode, we'll let it go.
824 factory.console.warn('In engineering mode; running '
825 '%s even though required tests '
826 '[%s] have not completed',
827 test.path, untested_paths)
828 else:
829 # Not in engineering mode; mark it failed.
830 error_msg = ('Required tests [%s] have not been run yet'
831 % untested_paths)
832 factory.console.error('Not running %s: %s',
833 test.path, error_msg)
834 test.update_state(status=TestState.FAILED,
835 error_msg=error_msg)
836 continue
837
Ricky Liang48e47f92014-02-26 19:31:51 +0800838 if (isinstance(test, factory.ShutdownStep) and
Ricky Liangb7eb8772014-09-15 18:05:22 +0800839 self.state_instance.get_shared_data(
840 state.POST_SHUTDOWN_TAG % test.path, optional=True)):
Ricky Liang48e47f92014-02-26 19:31:51 +0800841 # Invoking post shutdown method of shutdown test. We should retain the
842 # iterations_left and retries_left of the original test state.
843 test_state = self.state_instance.get_test_state(test.path)
844 self._run_test(test, test_state.iterations_left,
845 test_state.retries_left)
846 else:
847 # Starts a new test run; reset iterations and retries.
848 self._run_test(test, test.iterations, test.retries)
Jon Salz1acc8742012-07-17 17:45:55 +0800849
Cheng-Yi Chiangce05c002013-04-04 02:13:17 +0800850 def _run_test(self, test, iterations_left=None, retries_left=None):
Vic Yanga3cecf82014-12-26 00:44:21 -0800851 if not self._ui_initialized and not test.is_no_host():
852 self.init_ui()
Vic Yang08505c72015-01-06 17:01:53 -0800853 invoc = TestInvocation(
Hung-Te Linef7f2be2015-07-20 20:38:51 +0800854 self, test, on_completion=self.invocation_completion,
Claire Changd1961a22015-08-05 16:15:55 +0800855 on_test_failure=lambda: self.test_fail(test))
Jon Salz1acc8742012-07-17 17:45:55 +0800856 new_state = test.update_state(
Ricky Liang48e47f92014-02-26 19:31:51 +0800857 status=TestState.ACTIVE, increment_count=1, error_msg='',
858 invocation=invoc.uuid, iterations_left=iterations_left,
859 retries_left=retries_left,
860 visible=(self.visible_test == test))
Jon Salz1acc8742012-07-17 17:45:55 +0800861 invoc.count = new_state.count
862
863 self.invocations[test] = invoc
864 if self.visible_test is None and test.has_ui:
865 self.set_visible_test(test)
Vic Yang311ddb82012-09-26 12:08:28 +0800866 self.check_exclusive()
Jon Salz1acc8742012-07-17 17:45:55 +0800867 invoc.start()
Jon Salz5f2a0672012-05-22 17:14:06 +0800868
Vic Yang311ddb82012-09-26 12:08:28 +0800869 def check_exclusive(self):
Jon Salzce6a7f82013-06-10 18:22:54 +0800870 # alias since this is really long
871 EXCL_OPT = factory.FactoryTest.EXCLUSIVE_OPTIONS
872
Vic Yang311ddb82012-09-26 12:08:28 +0800873 current_exclusive_items = set([
Jon Salzce6a7f82013-06-10 18:22:54 +0800874 item for item in EXCL_OPT
Vic Yang311ddb82012-09-26 12:08:28 +0800875 if any([test.is_exclusive(item) for test in self.invocations])])
876
877 new_exclusive_items = current_exclusive_items - self.exclusive_items
Jon Salzce6a7f82013-06-10 18:22:54 +0800878 if EXCL_OPT.NETWORKING in new_exclusive_items:
Vic Yang311ddb82012-09-26 12:08:28 +0800879 logging.info('Disabling network')
880 self.connection_manager.DisableNetworking()
Jon Salzce6a7f82013-06-10 18:22:54 +0800881 if EXCL_OPT.CHARGER in new_exclusive_items:
Vic Yang311ddb82012-09-26 12:08:28 +0800882 logging.info('Stop controlling charger')
883
884 new_non_exclusive_items = self.exclusive_items - current_exclusive_items
Jon Salzce6a7f82013-06-10 18:22:54 +0800885 if EXCL_OPT.NETWORKING in new_non_exclusive_items:
Vic Yang311ddb82012-09-26 12:08:28 +0800886 logging.info('Re-enabling network')
887 self.connection_manager.EnableNetworking()
Jon Salzce6a7f82013-06-10 18:22:54 +0800888 if EXCL_OPT.CHARGER in new_non_exclusive_items:
Vic Yang311ddb82012-09-26 12:08:28 +0800889 logging.info('Start controlling charger')
890
Jon Salzce6a7f82013-06-10 18:22:54 +0800891 if self.cpufreq_manager:
892 enabled = EXCL_OPT.CPUFREQ not in current_exclusive_items
893 try:
894 self.cpufreq_manager.SetEnabled(enabled)
895 except: # pylint: disable=W0702
896 logging.exception('Unable to %s cpufreq services',
897 'enable' if enabled else 'disable')
898
Ricky Liang0f9978e2015-01-30 08:19:17 +0000899 # Only adjust charge state if not excluded
900 if (EXCL_OPT.CHARGER not in current_exclusive_items and
901 not utils.in_chroot()):
902 if self.charge_manager:
Cheng-Yi Chiangd8186952013-04-04 23:41:14 +0800903 self.charge_manager.AdjustChargeState()
904 else:
Dean Liao88b93192014-10-23 19:37:41 +0800905 self.charge()
Vic Yang311ddb82012-09-26 12:08:28 +0800906
907 self.exclusive_items = current_exclusive_items
Jon Salz5da61e62012-05-31 13:06:22 +0800908
Dean Liao88b93192014-10-23 19:37:41 +0800909 def charge(self):
910 """Charges the board.
911
912 It won't try again if last time SetChargeState raised an exception.
913 """
914 if not self._can_charge:
915 return
916
917 try:
Ricky Liang9ac35e02015-01-30 16:01:32 +0800918 if self.charge_manager:
919 self.charge_manager.StartCharging()
920 else:
Hung-Te Lin6a72c642015-12-13 22:09:09 +0800921 self.dut.power.SetChargeState(self.dut.power.ChargeState.CHARGE)
Dean Liao88b93192014-10-23 19:37:41 +0800922 except NotImplementedError:
923 logging.info('Charging is not supported')
924 self._can_charge = False
Hung-Te Lin6a72c642015-12-13 22:09:09 +0800925 except dut.DUTException:
Dean Liao88b93192014-10-23 19:37:41 +0800926 logging.exception('Unable to set charge state on this board')
927 self._can_charge = False
928
cychiang21886742012-07-05 15:16:32 +0800929 def check_for_updates(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800930 """Schedules an asynchronous check for updates if necessary."""
cychiang21886742012-07-05 15:16:32 +0800931 if not self.test_list.options.update_period_secs:
932 # Not enabled.
933 return
934
935 now = time.time()
936 if self.last_update_check and (
937 now - self.last_update_check <
938 self.test_list.options.update_period_secs):
939 # Not yet time for another check.
940 return
941
942 self.last_update_check = now
943
944 def handle_check_for_update(reached_shopfloor, md5sum, needs_update):
945 if reached_shopfloor:
946 new_update_md5sum = md5sum if needs_update else None
Hung-Te Lin8fa29062015-11-25 18:00:59 +0800947 if system.state.SystemInfo.update_md5sum != new_update_md5sum:
cychiang21886742012-07-05 15:16:32 +0800948 logging.info('Received new update MD5SUM: %s', new_update_md5sum)
Hung-Te Lin8fa29062015-11-25 18:00:59 +0800949 system.state.SystemInfo.update_md5sum = new_update_md5sum
Peter Ammon1e1ec572014-06-26 17:56:32 -0700950 self.run_enqueue(self.update_system_info)
Cheng-Yi Chiang194d3c02015-03-16 14:37:15 +0800951 else:
952 if not self._suppress_periodic_update_messages:
953 logging.warning('Suppress error messages for periodic update checking'
954 ' after the first one.')
955 self._suppress_periodic_update_messages = True
cychiang21886742012-07-05 15:16:32 +0800956
957 updater.CheckForUpdateAsync(
Ricky Liang45c73e72015-01-15 15:00:30 +0800958 handle_check_for_update,
Cheng-Yi Chiang194d3c02015-03-16 14:37:15 +0800959 self.test_list.options.shopfloor_timeout_secs,
960 self._suppress_periodic_update_messages)
cychiang21886742012-07-05 15:16:32 +0800961
Jon Salza6711d72012-07-18 14:33:03 +0800962 def cancel_pending_tests(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800963 """Cancels any tests in the run queue."""
Jon Salza6711d72012-07-18 14:33:03 +0800964 self.run_tests([])
965
Ricky Liang4bff3e32014-02-20 18:46:11 +0800966 def restore_active_run_state(self):
967 """Restores active run id and the list of scheduled tests."""
968 self.run_id = self.state_instance.get_shared_data('run_id', optional=True)
969 self.scheduled_run_tests = self.state_instance.get_shared_data(
970 'scheduled_run_tests', optional=True)
971
972 def set_active_run_state(self):
973 """Sets active run id and the list of scheduled tests."""
974 self.run_id = str(uuid.uuid4())
975 self.scheduled_run_tests = [test.path for test in self.tests_to_run]
976 self.state_instance.set_shared_data('run_id', self.run_id)
977 self.state_instance.set_shared_data('scheduled_run_tests',
978 self.scheduled_run_tests)
979
Chih-Yu Huang85dc63c2015-08-12 15:21:28 +0800980 def run_tests(self, subtrees, status_filter=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800981 """Runs tests under subtree.
Jon Salz258a40c2012-04-19 12:34:01 +0800982
Jon Salz0697cbf2012-07-04 15:14:04 +0800983 The tests are run in order unless one fails (then stops).
984 Backgroundable tests are run simultaneously; when a foreground test is
985 encountered, we wait for all active tests to finish before continuing.
Jon Salzb1b39092012-05-03 02:05:09 +0800986
Ricky Liang6fe218c2013-12-27 15:17:17 +0800987 Args:
988 subtrees: Node or nodes containing tests to run (may either be
989 a single test or a list). Duplicates will be ignored.
Chih-Yu Huang85dc63c2015-08-12 15:21:28 +0800990 status_filter: List of available test states. Only run the tests which
991 states are in the list. Set to None if all test states are available.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800992 """
Hung-Te Lin410f70a2015-12-15 14:53:42 +0800993 self.dut.hooks.OnTestStart()
Vic Yang08505c72015-01-06 17:01:53 -0800994
Jon Salz0697cbf2012-07-04 15:14:04 +0800995 if type(subtrees) != list:
996 subtrees = [subtrees]
Jon Salz258a40c2012-04-19 12:34:01 +0800997
Jon Salz0697cbf2012-07-04 15:14:04 +0800998 # Nodes we've seen so far, to avoid duplicates.
999 seen = set()
Jon Salz94eb56f2012-06-12 18:01:12 +08001000
Jon Salz0697cbf2012-07-04 15:14:04 +08001001 self.tests_to_run = deque()
1002 for subtree in subtrees:
1003 for test in subtree.walk():
1004 if test in seen:
1005 continue
1006 seen.add(test)
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001007
Jon Salz0697cbf2012-07-04 15:14:04 +08001008 if not test.is_leaf():
1009 continue
Chih-Yu Huang85dc63c2015-08-12 15:21:28 +08001010 if (status_filter is not None and
1011 test.get_state().status not in status_filter):
Jon Salz0697cbf2012-07-04 15:14:04 +08001012 continue
1013 self.tests_to_run.append(test)
Ricky Liang4bff3e32014-02-20 18:46:11 +08001014 if subtrees:
1015 self.set_active_run_state()
Jon Salz0697cbf2012-07-04 15:14:04 +08001016 self.run_next_test()
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001017
Jon Salz0697cbf2012-07-04 15:14:04 +08001018 def reap_completed_tests(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001019 """Removes completed tests from the set of active tests.
Jon Salz0697cbf2012-07-04 15:14:04 +08001020
1021 Also updates the visible test if it was reaped.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001022 """
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +08001023 test_completed = False
Jon Salz0697cbf2012-07-04 15:14:04 +08001024 for t, v in dict(self.invocations).iteritems():
1025 if v.is_completed():
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +08001026 test_completed = True
Jon Salz1acc8742012-07-17 17:45:55 +08001027 new_state = t.update_state(**v.update_state_on_completion)
Jon Salz0697cbf2012-07-04 15:14:04 +08001028 del self.invocations[t]
1029
Johny Lin62ed2a32015-05-13 11:57:12 +08001030 # Stop on failure if flag is true and there is no retry chances.
Chun-Ta Lin54e17e42012-09-06 22:05:13 +08001031 if (self.test_list.options.stop_on_failure and
Johny Lin62ed2a32015-05-13 11:57:12 +08001032 new_state.retries_left < 0 and
Chun-Ta Lin54e17e42012-09-06 22:05:13 +08001033 new_state.status == TestState.FAILED):
1034 # Clean all the tests to cause goofy to stop.
1035 self.tests_to_run = []
Ricky Liang45c73e72015-01-15 15:00:30 +08001036 factory.console.info('Stop on failure triggered. Empty the queue.')
Chun-Ta Lin54e17e42012-09-06 22:05:13 +08001037
Jon Salz1acc8742012-07-17 17:45:55 +08001038 if new_state.iterations_left and new_state.status == TestState.PASSED:
1039 # Play it again, Sam!
1040 self._run_test(t)
Cheng-Yi Chiangce05c002013-04-04 02:13:17 +08001041 # new_state.retries_left is obtained after update.
1042 # For retries_left == 0, test can still be run for the last time.
1043 elif (new_state.retries_left >= 0 and
1044 new_state.status == TestState.FAILED):
1045 # Still have to retry, Sam!
1046 self._run_test(t)
Jon Salz1acc8742012-07-17 17:45:55 +08001047
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +08001048 if test_completed:
Vic Yangf01c59f2013-04-19 17:37:56 +08001049 self.log_watcher.KickWatchThread()
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +08001050
Jon Salz0697cbf2012-07-04 15:14:04 +08001051 if (self.visible_test is None or
Jon Salz85a39882012-07-05 16:45:04 +08001052 self.visible_test not in self.invocations):
Jon Salz0697cbf2012-07-04 15:14:04 +08001053 self.set_visible_test(None)
1054 # Make the first running test, if any, the visible test
1055 for t in self.test_list.walk():
1056 if t in self.invocations:
1057 self.set_visible_test(t)
1058 break
1059
Jon Salz6dc031d2013-06-19 13:06:23 +08001060 def kill_active_tests(self, abort, root=None, reason=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001061 """Kills and waits for all active tests.
Jon Salz0697cbf2012-07-04 15:14:04 +08001062
Jon Salz85a39882012-07-05 16:45:04 +08001063 Args:
1064 abort: True to change state of killed tests to FAILED, False for
Jon Salz0697cbf2012-07-04 15:14:04 +08001065 UNTESTED.
Jon Salz85a39882012-07-05 16:45:04 +08001066 root: If set, only kills tests with root as an ancestor.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001067 reason: If set, the abort reason.
1068 """
Jon Salz0697cbf2012-07-04 15:14:04 +08001069 self.reap_completed_tests()
1070 for test, invoc in self.invocations.items():
Jon Salz85a39882012-07-05 16:45:04 +08001071 if root and not test.has_ancestor(root):
1072 continue
1073
Ricky Liang45c73e72015-01-15 15:00:30 +08001074 factory.console.info('Killing active test %s...', test.path)
Jon Salz6dc031d2013-06-19 13:06:23 +08001075 invoc.abort_and_join(reason)
Ricky Liang45c73e72015-01-15 15:00:30 +08001076 factory.console.info('Killed %s', test.path)
Jon Salz1acc8742012-07-17 17:45:55 +08001077 test.update_state(**invoc.update_state_on_completion)
Jon Salz0697cbf2012-07-04 15:14:04 +08001078 del self.invocations[test]
Jon Salz1acc8742012-07-17 17:45:55 +08001079
Jon Salz0697cbf2012-07-04 15:14:04 +08001080 if not abort:
1081 test.update_state(status=TestState.UNTESTED)
1082 self.reap_completed_tests()
1083
Jon Salz6dc031d2013-06-19 13:06:23 +08001084 def stop(self, root=None, fail=False, reason=None):
1085 self.kill_active_tests(fail, root, reason)
Jon Salz85a39882012-07-05 16:45:04 +08001086 # Remove any tests in the run queue under the root.
1087 self.tests_to_run = deque([x for x in self.tests_to_run
1088 if root and not x.has_ancestor(root)])
1089 self.run_next_test()
Jon Salz0697cbf2012-07-04 15:14:04 +08001090
Jon Salz4712ac72013-02-07 17:12:05 +08001091 def clear_state(self, root=None):
Jon Salzd7550792013-07-12 05:49:27 +08001092 if root is None:
1093 root = self.test_list
Jon Salz6dc031d2013-06-19 13:06:23 +08001094 self.stop(root, reason='Clearing test state')
Jon Salz4712ac72013-02-07 17:12:05 +08001095 for f in root.walk():
1096 if f.is_leaf():
1097 f.update_state(status=TestState.UNTESTED)
1098
Jon Salz6dc031d2013-06-19 13:06:23 +08001099 def abort_active_tests(self, reason=None):
1100 self.kill_active_tests(True, reason=reason)
Jon Salz0697cbf2012-07-04 15:14:04 +08001101
1102 def main(self):
Jon Salzeff94182013-06-19 15:06:28 +08001103 syslog.openlog('goofy')
1104
Jon Salz0697cbf2012-07-04 15:14:04 +08001105 try:
Jon Salzd7550792013-07-12 05:49:27 +08001106 self.status = Status.INITIALIZING
Jon Salz0697cbf2012-07-04 15:14:04 +08001107 self.init()
1108 self.event_log.Log('goofy_init',
Ricky Liang45c73e72015-01-15 15:00:30 +08001109 success=True)
Jon Salz0697cbf2012-07-04 15:14:04 +08001110 except:
1111 if self.event_log:
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001112 try:
Jon Salz0697cbf2012-07-04 15:14:04 +08001113 self.event_log.Log('goofy_init',
Ricky Liang45c73e72015-01-15 15:00:30 +08001114 success=False,
1115 trace=traceback.format_exc())
Jon Salz0697cbf2012-07-04 15:14:04 +08001116 except: # pylint: disable=W0702
1117 pass
1118 raise
1119
Jon Salzd7550792013-07-12 05:49:27 +08001120 self.status = Status.RUNNING
Jon Salzeff94182013-06-19 15:06:28 +08001121 syslog.syslog('Goofy (factory test harness) starting')
Chun-Ta Lin5d12b592015-06-30 00:54:23 -07001122 syslog.syslog('Boot sequence = %d' % GetBootSequence())
Jon Salz0697cbf2012-07-04 15:14:04 +08001123 self.run()
1124
1125 def update_system_info(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001126 """Updates system info."""
Hung-Te Lin8fa29062015-11-25 18:00:59 +08001127 system_info = system.state.SystemInfo()
Jon Salz0697cbf2012-07-04 15:14:04 +08001128 self.state_instance.set_shared_data('system_info', system_info.__dict__)
1129 self.event_client.post_event(Event(Event.Type.SYSTEM_INFO,
Ricky Liang45c73e72015-01-15 15:00:30 +08001130 system_info=system_info.__dict__))
Jon Salz0697cbf2012-07-04 15:14:04 +08001131 logging.info('System info: %r', system_info.__dict__)
1132
Jon Salzeb42f0d2012-07-27 19:14:04 +08001133 def update_factory(self, auto_run_on_restart=False, post_update_hook=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001134 """Commences updating factory software.
Jon Salzeb42f0d2012-07-27 19:14:04 +08001135
1136 Args:
1137 auto_run_on_restart: Auto-run when the machine comes back up.
1138 post_update_hook: Code to call after update but immediately before
1139 restart.
1140
1141 Returns:
1142 Never if the update was successful (we just reboot).
1143 False if the update was unnecessary (no update available).
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001144 """
Jon Salz6dc031d2013-06-19 13:06:23 +08001145 self.kill_active_tests(False, reason='Factory software update')
Jon Salza6711d72012-07-18 14:33:03 +08001146 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +08001147
Jon Salz5c344f62012-07-13 14:31:16 +08001148 def pre_update_hook():
1149 if auto_run_on_restart:
1150 self.state_instance.set_shared_data('tests_after_shutdown',
1151 FORCE_AUTO_RUN)
1152 self.state_instance.close()
1153
Jon Salzeb42f0d2012-07-27 19:14:04 +08001154 if updater.TryUpdate(pre_update_hook=pre_update_hook):
1155 if post_update_hook:
1156 post_update_hook()
1157 self.env.shutdown('reboot')
Jon Salz0697cbf2012-07-04 15:14:04 +08001158
Ricky Liang8fecf412014-05-22 10:56:14 +08001159 def handle_sigint(self, dummy_signum, dummy_frame): # pylint: disable=W0613
Jon Salz77c151e2012-08-28 07:20:37 +08001160 logging.error('Received SIGINT')
Peter Ammon1e1ec572014-06-26 17:56:32 -07001161 self.run_enqueue(None)
Jon Salz77c151e2012-08-28 07:20:37 +08001162 raise KeyboardInterrupt()
1163
Ricky Liang8fecf412014-05-22 10:56:14 +08001164 def handle_sigterm(self, dummy_signum, dummy_frame): # pylint: disable=W0613
1165 logging.error('Received SIGTERM')
Hung-Te Lin94ca4742014-07-09 20:13:50 +08001166 self.env.terminate()
1167 self.run_queue.put(None)
Ricky Liang8fecf412014-05-22 10:56:14 +08001168 raise RuntimeError('Received SIGTERM')
1169
Jon Salze12c2b32013-06-25 16:24:34 +08001170 def find_kcrashes(self):
1171 """Finds kcrash files, logs them, and marks them as seen."""
1172 seen_crashes = set(
1173 self.state_instance.get_shared_data('seen_crashes', optional=True)
1174 or [])
1175
1176 for path in glob.glob('/var/spool/crash/*'):
1177 if not os.path.isfile(path):
1178 continue
1179 if path in seen_crashes:
1180 continue
1181 try:
1182 stat = os.stat(path)
1183 mtime = utils.TimeString(stat.st_mtime)
1184 logging.info(
1185 'Found new crash file %s (%d bytes at %s)',
1186 path, stat.st_size, mtime)
1187 extra_log_args = {}
1188
1189 try:
1190 _, ext = os.path.splitext(path)
1191 if ext in ['.kcrash', '.meta']:
1192 ext = ext.replace('.', '')
1193 with open(path) as f:
1194 data = f.read(MAX_CRASH_FILE_SIZE)
1195 tell = f.tell()
1196 logging.info(
1197 'Contents of %s%s:%s',
1198 path,
1199 ('' if tell == stat.st_size
1200 else '(truncated to %d bytes)' % MAX_CRASH_FILE_SIZE),
1201 ('\n' + data).replace('\n', '\n ' + ext + '> '))
1202 extra_log_args['data'] = data
1203
1204 # Copy to /var/factory/kcrash for posterity
1205 kcrash_dir = factory.get_factory_root('kcrash')
1206 utils.TryMakeDirs(kcrash_dir)
1207 shutil.copy(path, kcrash_dir)
1208 logging.info('Copied to %s',
1209 os.path.join(kcrash_dir, os.path.basename(path)))
1210 finally:
1211 # Even if something goes wrong with the above, still try to
1212 # log to event log
1213 self.event_log.Log('crash_file',
1214 path=path, size=stat.st_size, mtime=mtime,
1215 **extra_log_args)
1216 except: # pylint: disable=W0702
1217 logging.exception('Unable to handle crash files %s', path)
1218 seen_crashes.add(path)
1219
1220 self.state_instance.set_shared_data('seen_crashes', list(seen_crashes))
1221
Jon Salz128b0932013-07-03 16:55:26 +08001222 def GetTestList(self, test_list_id):
1223 """Returns the test list with the given ID.
1224
1225 Raises:
1226 TestListError: The test list ID is not valid.
1227 """
1228 try:
1229 return self.test_lists[test_list_id]
1230 except KeyError:
1231 raise test_lists.TestListError(
1232 '%r is not a valid test list ID (available IDs are [%s])' % (
1233 test_list_id, ', '.join(sorted(self.test_lists.keys()))))
1234
1235 def InitTestLists(self):
1236 """Reads in all test lists and sets the active test list."""
Ricky Liang27051552014-05-04 14:22:26 +08001237 self.test_lists = test_lists.BuildAllTestLists(
1238 force_generic=(self.options.automation_mode is not None))
Jon Salzd7550792013-07-12 05:49:27 +08001239 logging.info('Loaded test lists: [%s]',
1240 test_lists.DescribeTestLists(self.test_lists))
Jon Salz128b0932013-07-03 16:55:26 +08001241
1242 if not self.options.test_list:
1243 self.options.test_list = test_lists.GetActiveTestListId()
1244
1245 if os.sep in self.options.test_list:
1246 # It's a path pointing to an old-style test list; use it.
1247 self.test_list = factory.read_test_list(self.options.test_list)
1248 else:
1249 self.test_list = self.GetTestList(self.options.test_list)
1250
1251 logging.info('Active test list: %s', self.test_list.test_list_id)
1252
1253 if isinstance(self.test_list, test_lists.OldStyleTestList):
1254 # Actually load it in. (See OldStyleTestList for an explanation
1255 # of why this is necessary.)
1256 self.test_list = self.test_list.Load()
1257
1258 self.test_list.state_instance = self.state_instance
1259
Shuo-Peng Liao268b40b2013-07-01 15:58:59 +08001260 def init_hooks(self):
1261 """Initializes hooks.
1262
1263 Must run after self.test_list ready.
1264 """
Shuo-Peng Liao52b90da2013-06-30 17:00:06 +08001265 module, cls = self.test_list.options.hooks_class.rsplit('.', 1)
1266 self.hooks = getattr(__import__(module, fromlist=[cls]), cls)()
1267 assert isinstance(self.hooks, factory.Hooks), (
Ricky Liang45c73e72015-01-15 15:00:30 +08001268 'hooks should be of type Hooks but is %r' % type(self.hooks))
Shuo-Peng Liao52b90da2013-06-30 17:00:06 +08001269 self.hooks.test_list = self.test_list
Shuo-Peng Liao268b40b2013-07-01 15:58:59 +08001270 self.hooks.OnCreatedTestList()
Shuo-Peng Liao52b90da2013-06-30 17:00:06 +08001271
Vic Yanga3cecf82014-12-26 00:44:21 -08001272 def init_ui(self):
1273 """Initialize UI."""
1274 self._ui_initialized = True
1275 if self.options.ui == 'chrome':
Hung-Te Lin8f6a3782015-01-06 22:58:32 +08001276 if self.options.monolithic:
Hung-Te Lin7bd55312014-12-30 16:43:36 +08001277 self.env.launch_chrome()
1278 else:
1279 # The presenter is responsible for launching Chrome. Let's just
1280 # wait here.
1281 self.env.controller_ready_for_ui()
Vic Yanga3cecf82014-12-26 00:44:21 -08001282 logging.info('Waiting for a web socket connection')
1283 self.web_socket_manager.wait()
1284
1285 # Wait for the test widget size to be set; this is done in
1286 # an asynchronous RPC so there is a small chance that the
1287 # web socket might be opened first.
1288 for _ in range(100): # 10 s
1289 try:
1290 if self.state_instance.get_shared_data('test_widget_size'):
1291 break
1292 except KeyError:
1293 pass # Retry
1294 time.sleep(0.1) # 100 ms
1295 else:
1296 logging.warn('Never received test_widget_size from UI')
1297
Hung-Te Lin7bd55312014-12-30 16:43:36 +08001298 logging.info('Waiting for a web socket connection')
1299 self.web_socket_manager.wait()
1300
Jon Salz0697cbf2012-07-04 15:14:04 +08001301 def init(self, args=None, env=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001302 """Initializes Goofy.
Jon Salz0697cbf2012-07-04 15:14:04 +08001303
1304 Args:
1305 args: A list of command-line arguments. Uses sys.argv if
1306 args is None.
1307 env: An Environment instance to use (or None to choose
1308 FakeChrootEnvironment or DUTEnvironment as appropriate).
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001309 """
Jon Salz0697cbf2012-07-04 15:14:04 +08001310 parser = OptionParser()
1311 parser.add_option('-v', '--verbose', dest='verbose',
Jon Salz8fa8e832012-07-13 19:04:09 +08001312 action='store_true',
1313 help='Enable debug logging')
Jon Salz0697cbf2012-07-04 15:14:04 +08001314 parser.add_option('--print_test_list', dest='print_test_list',
Jon Salz8fa8e832012-07-13 19:04:09 +08001315 metavar='FILE',
1316 help='Read and print test list FILE, and exit')
Jon Salz0697cbf2012-07-04 15:14:04 +08001317 parser.add_option('--restart', dest='restart',
Jon Salz8fa8e832012-07-13 19:04:09 +08001318 action='store_true',
1319 help='Clear all test state')
Jon Salz0697cbf2012-07-04 15:14:04 +08001320 parser.add_option('--ui', dest='ui', type='choice',
Jon Salz7b5482e2014-08-04 17:48:41 +08001321 choices=['none', 'chrome'],
Jon Salz2f881df2013-02-01 17:00:35 +08001322 default='chrome',
Jon Salz8fa8e832012-07-13 19:04:09 +08001323 help='UI to use')
Jon Salz0697cbf2012-07-04 15:14:04 +08001324 parser.add_option('--ui_scale_factor', dest='ui_scale_factor',
Jon Salz8fa8e832012-07-13 19:04:09 +08001325 type='int', default=1,
1326 help=('Factor by which to scale UI '
1327 '(Chrome UI only)'))
Jon Salz0697cbf2012-07-04 15:14:04 +08001328 parser.add_option('--test_list', dest='test_list',
Jon Salz8fa8e832012-07-13 19:04:09 +08001329 metavar='FILE',
1330 help='Use FILE as test list')
Jon Salzc79a9982012-08-30 04:42:01 +08001331 parser.add_option('--dummy_shopfloor', action='store_true',
1332 help='Use a dummy shopfloor server')
Hung-Te Lincc41d2a2014-10-29 13:35:20 +08001333 parser.add_option('--dummy_connection_manager', action='store_true',
1334 help='Use a dummy connection manager')
Ricky Liang6fe218c2013-12-27 15:17:17 +08001335 parser.add_option('--automation-mode',
1336 choices=[m.lower() for m in AutomationMode],
Ricky Liang45c73e72015-01-15 15:00:30 +08001337 default='none', help='Factory test automation mode.')
Ricky Liang117484a2014-04-14 11:14:41 +08001338 parser.add_option('--no-auto-run-on-start', dest='auto_run_on_start',
1339 action='store_false', default=True,
1340 help=('do not automatically run the test list on goofy '
1341 'start; this is only valid when factory test '
1342 'automation is enabled'))
Chun-Ta Lina8dd3172014-11-26 16:15:13 +08001343 parser.add_option('--handshake_timeout', dest='handshake_timeout',
1344 type='float', default=0.3,
1345 help=('RPC timeout when doing handshake between device '
1346 'and presenter.'))
Vic Yang7d693c42014-09-14 09:52:39 +08001347 parser.add_option('--standalone', dest='standalone',
1348 action='store_true', default=False,
1349 help=('Assume the presenter is running on the same '
1350 'machines.'))
Hung-Te Lin8f6a3782015-01-06 22:58:32 +08001351 parser.add_option('--monolithic', dest='monolithic',
1352 action='store_true', default=False,
1353 help='Run in monolithic mode (without presenter)')
Jon Salz0697cbf2012-07-04 15:14:04 +08001354 (self.options, self.args) = parser.parse_args(args)
1355
Hung-Te Lina846f602014-07-04 20:32:22 +08001356 signal.signal(signal.SIGINT, self.handle_sigint)
1357 # TODO(hungte) SIGTERM does not work properly without Telemetry and should
1358 # be fixed.
Hung-Te Lina846f602014-07-04 20:32:22 +08001359
Jon Salz46b89562012-07-05 11:49:22 +08001360 # Make sure factory directories exist.
1361 factory.get_log_root()
1362 factory.get_state_root()
1363 factory.get_test_data_root()
1364
Jon Salz0697cbf2012-07-04 15:14:04 +08001365 global _inited_logging # pylint: disable=W0603
1366 if not _inited_logging:
1367 factory.init_logging('goofy', verbose=self.options.verbose)
1368 _inited_logging = True
Jon Salz8fa8e832012-07-13 19:04:09 +08001369
Jon Salz0f996602012-10-03 15:26:48 +08001370 if self.options.print_test_list:
Joel Kitchingb85ed7f2014-10-08 18:24:39 +08001371 print(factory.read_test_list(
1372 self.options.print_test_list).__repr__(recursive=True))
Jon Salz0f996602012-10-03 15:26:48 +08001373 sys.exit(0)
1374
Jon Salzee85d522012-07-17 14:34:46 +08001375 event_log.IncrementBootSequence()
Jon Salzd15bbcf2013-05-21 17:33:57 +08001376 # Don't defer logging the initial event, so we can make sure
1377 # that device_id, reimage_id, etc. are all set up.
1378 self.event_log = EventLog('goofy', defer=False)
Jon Salz0697cbf2012-07-04 15:14:04 +08001379
Jon Salz0697cbf2012-07-04 15:14:04 +08001380 if env:
1381 self.env = env
1382 elif factory.in_chroot():
1383 self.env = test_environment.FakeChrootEnvironment()
1384 logging.warn(
Ricky Liang45c73e72015-01-15 15:00:30 +08001385 'Using chroot environment: will not actually run autotests')
Hung-Te Lina846f602014-07-04 20:32:22 +08001386 elif self.options.ui == 'chrome':
Ricky Liang09d66d82014-09-25 11:20:54 +08001387 self.env = test_environment.DUTEnvironment()
Jon Salz0697cbf2012-07-04 15:14:04 +08001388 self.env.goofy = self
Vic Yanga4931152014-08-11 16:36:24 -07001389 # web_socket_manager will be initialized later
1390 # pylint: disable=W0108
1391 self.env.has_sockets = lambda: self.web_socket_manager.has_sockets()
Jon Salz0697cbf2012-07-04 15:14:04 +08001392
1393 if self.options.restart:
1394 state.clear_state()
1395
Jon Salz0697cbf2012-07-04 15:14:04 +08001396 if self.options.ui_scale_factor != 1 and utils.in_qemu():
1397 logging.warn(
Ricky Liang45c73e72015-01-15 15:00:30 +08001398 'In QEMU; ignoring ui_scale_factor argument')
Jon Salz0697cbf2012-07-04 15:14:04 +08001399 self.options.ui_scale_factor = 1
1400
1401 logging.info('Started')
1402
Hung-Te Lin8f6a3782015-01-06 22:58:32 +08001403 if not self.options.monolithic:
Hung-Te Lin7bd55312014-12-30 16:43:36 +08001404 self.link_manager = PresenterLinkManager(
1405 check_interval=1,
1406 handshake_timeout=self.options.handshake_timeout,
1407 standalone=self.options.standalone)
Peter Ammon1e1ec572014-06-26 17:56:32 -07001408
Jon Salz0697cbf2012-07-04 15:14:04 +08001409 self.start_state_server()
1410 self.state_instance.set_shared_data('hwid_cfg', get_hwid_cfg())
1411 self.state_instance.set_shared_data('ui_scale_factor',
Ricky Liang09216dc2013-02-22 17:26:45 +08001412 self.options.ui_scale_factor)
Jon Salz0697cbf2012-07-04 15:14:04 +08001413 self.last_shutdown_time = (
Ricky Liang45c73e72015-01-15 15:00:30 +08001414 self.state_instance.get_shared_data('shutdown_time', optional=True))
Jon Salz0697cbf2012-07-04 15:14:04 +08001415 self.state_instance.del_shared_data('shutdown_time', optional=True)
Jon Salzb19ea072013-02-07 16:35:00 +08001416 self.state_instance.del_shared_data('startup_error', optional=True)
Jon Salz0697cbf2012-07-04 15:14:04 +08001417
Ricky Liang6fe218c2013-12-27 15:17:17 +08001418 self.options.automation_mode = ParseAutomationMode(
1419 self.options.automation_mode)
1420 self.state_instance.set_shared_data('automation_mode',
1421 self.options.automation_mode)
1422 self.state_instance.set_shared_data(
1423 'automation_mode_prompt',
1424 AutomationModePrompt[self.options.automation_mode])
1425
Jon Salz128b0932013-07-03 16:55:26 +08001426 try:
1427 self.InitTestLists()
1428 except: # pylint: disable=W0702
1429 logging.exception('Unable to initialize test lists')
1430 self.state_instance.set_shared_data(
1431 'startup_error',
1432 'Unable to initialize test lists\n%s' % (
1433 traceback.format_exc()))
Jon Salzb19ea072013-02-07 16:35:00 +08001434 if self.options.ui == 'chrome':
1435 # Create an empty test list with default options so that the rest of
1436 # startup can proceed.
1437 self.test_list = factory.FactoryTestList(
1438 [], self.state_instance, factory.Options())
1439 else:
1440 # Bail with an error; no point in starting up.
1441 sys.exit('No valid test list; exiting.')
1442
Shuo-Peng Liao268b40b2013-07-01 15:58:59 +08001443 self.init_hooks()
1444
Jon Salz822838b2013-03-25 17:32:33 +08001445 if self.test_list.options.clear_state_on_start:
1446 self.state_instance.clear_test_state()
1447
Jon Salz670ce062014-05-16 15:53:50 +08001448 # If the phase is invalid, this will raise a ValueError.
1449 phase.SetPersistentPhase(self.test_list.options.phase)
1450
Dean Liao85ca86f2014-11-03 12:28:08 +08001451 # For netboot firmware, mainfw_type should be 'netboot'.
Hung-Te Lin8fa29062015-11-25 18:00:59 +08001452 if (system.state.SystemInfo().mainfw_type != 'nonchrome' and
1453 system.state.SystemInfo().firmware_version is None):
Ricky Liang45c73e72015-01-15 15:00:30 +08001454 self.state_instance.set_shared_data(
1455 'startup_error',
Vic Yang9bd4f772013-06-04 17:34:00 +08001456 'Netboot firmware detected\n'
1457 'Connect Ethernet and reboot to re-image.\n'
1458 u'侦测到网路开机固件\n'
1459 u'请连接乙太网并重启')
1460
Jon Salz0697cbf2012-07-04 15:14:04 +08001461 if not self.state_instance.has_shared_data('ui_lang'):
1462 self.state_instance.set_shared_data('ui_lang',
Ricky Liang45c73e72015-01-15 15:00:30 +08001463 self.test_list.options.ui_lang)
Jon Salz0697cbf2012-07-04 15:14:04 +08001464 self.state_instance.set_shared_data(
Ricky Liang45c73e72015-01-15 15:00:30 +08001465 'test_list_options',
1466 self.test_list.options.__dict__)
Jon Salz0697cbf2012-07-04 15:14:04 +08001467 self.state_instance.test_list = self.test_list
1468
Cheng-Yi Chiang39d32ad2013-07-23 15:02:38 +08001469 self.check_log_rotation()
Jon Salz83ef34b2012-11-01 19:46:35 +08001470
Jon Salz23926422012-09-01 03:38:13 +08001471 if self.options.dummy_shopfloor:
Ricky Liang45c73e72015-01-15 15:00:30 +08001472 os.environ[shopfloor.SHOPFLOOR_SERVER_ENV_VAR_NAME] = (
1473 'http://%s:%d/' %
Joel Kitchingb85ed7f2014-10-08 18:24:39 +08001474 (net_utils.LOCALHOST, shopfloor.DEFAULT_SERVER_PORT))
Jon Salz23926422012-09-01 03:38:13 +08001475 self.dummy_shopfloor = Spawn(
1476 [os.path.join(factory.FACTORY_PATH, 'bin', 'shopfloor_server'),
1477 '--dummy'])
1478 elif self.test_list.options.shopfloor_server_url:
1479 shopfloor.set_server_url(self.test_list.options.shopfloor_server_url)
Jon Salz2bf2f6b2013-03-28 18:49:26 +08001480 shopfloor.set_enabled(True)
Jon Salz23926422012-09-01 03:38:13 +08001481
Jon Salz0f996602012-10-03 15:26:48 +08001482 if self.test_list.options.time_sanitizer and not utils.in_chroot():
Jon Salz8fa8e832012-07-13 19:04:09 +08001483 self.time_sanitizer = time_sanitizer.TimeSanitizer(
Ricky Liang45c73e72015-01-15 15:00:30 +08001484 base_time=time_sanitizer.GetBaseTimeFromFile(
1485 # lsb-factory is written by the factory install shim during
1486 # installation, so it should have a good time obtained from
1487 # the mini-Omaha server. If it's not available, we'll use
1488 # /etc/lsb-factory (which will be much older, but reasonably
1489 # sane) and rely on a shopfloor sync to set a more accurate
1490 # time.
1491 '/usr/local/etc/lsb-factory',
1492 '/etc/lsb-release'))
Jon Salz8fa8e832012-07-13 19:04:09 +08001493 self.time_sanitizer.RunOnce()
1494
Vic Yangd8990da2013-06-27 16:57:43 +08001495 if self.test_list.options.check_cpu_usage_period_secs:
Ricky Liang45c73e72015-01-15 15:00:30 +08001496 self.cpu_usage_watcher = Spawn(
1497 ['py/tools/cpu_usage_monitor.py', '-p',
1498 str(self.test_list.options.check_cpu_usage_period_secs)],
Vic Yangd8990da2013-06-27 16:57:43 +08001499 cwd=factory.FACTORY_PATH)
1500
Chun-Ta Lin5d12b592015-06-30 00:54:23 -07001501 # Enable thermal monitor
1502 if self.test_list.options.thermal_monitor_period_secs > 0:
1503 self.cpu_usage_watcher = Spawn(
1504 ['py/tools/thermal_monitor.py',
1505 '-p', str(self.test_list.options.thermal_monitor_period_secs),
1506 '-d', str(self.test_list.options.thermal_monitor_delta)],
1507 cwd=factory.FACTORY_PATH)
1508
Jon Salz0697cbf2012-07-04 15:14:04 +08001509 self.init_states()
1510 self.start_event_server()
Wei-Ning Huang38b75f02015-02-25 18:25:14 +08001511 self.start_terminal_server()
Hung-Te Lincc41d2a2014-10-29 13:35:20 +08001512
1513 if self.options.dummy_connection_manager:
1514 # Override network manager creation to dummy implmenetation.
1515 logging.info('Using dummy network manager (--dummy_connection_manager).')
1516 self.connection_manager = connection_manager.DummyConnectionManager()
1517 else:
1518 self.connection_manager = self.env.create_connection_manager(
1519 self.test_list.options.wlans,
Mao Huang4340c632015-04-14 14:35:22 +08001520 self.test_list.options.scan_wifi_period_secs,
1521 self.test_list.options.override_blacklisted_network_devices)
Hung-Te Lincc41d2a2014-10-29 13:35:20 +08001522
Jon Salz0697cbf2012-07-04 15:14:04 +08001523 # Note that we create a log watcher even if
1524 # sync_event_log_period_secs isn't set (no background
1525 # syncing), since we may use it to flush event logs as well.
1526 self.log_watcher = EventLogWatcher(
Ricky Liang45c73e72015-01-15 15:00:30 +08001527 self.test_list.options.sync_event_log_period_secs,
1528 event_log_db_file=None,
1529 handle_event_logs_callback=self.handle_event_logs)
Jon Salz0697cbf2012-07-04 15:14:04 +08001530 if self.test_list.options.sync_event_log_period_secs:
1531 self.log_watcher.StartWatchThread()
1532
Cheng-Yi Chianga0f6eff2014-01-09 18:27:22 +08001533 # Creates a system log manager to scan logs periocially.
1534 # A scan includes clearing logs and optionally syncing logs if
1535 # enable_syng_log is True. We kick it to sync logs.
1536 self.system_log_manager = SystemLogManager(
Ricky Liang45c73e72015-01-15 15:00:30 +08001537 sync_log_paths=self.test_list.options.sync_log_paths,
1538 sync_log_period_secs=self.test_list.options.sync_log_period_secs,
1539 scan_log_period_secs=self.test_list.options.scan_log_period_secs,
1540 clear_log_paths=self.test_list.options.clear_log_paths,
1541 clear_log_excluded_paths=self.test_list.options.clear_log_excluded_paths)
Cheng-Yi Chianga0f6eff2014-01-09 18:27:22 +08001542 self.system_log_manager.Start()
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +08001543
Jon Salz0697cbf2012-07-04 15:14:04 +08001544 self.update_system_info()
1545
Vic Yang4953fc12012-07-26 16:19:53 +08001546 assert ((self.test_list.options.min_charge_pct is None) ==
1547 (self.test_list.options.max_charge_pct is None))
Vic Yange83d9a12013-04-19 20:00:20 +08001548 if utils.in_chroot():
1549 logging.info('In chroot, ignoring charge manager and charge state')
Ricky Liangc392a1c2014-06-20 18:24:59 +08001550 elif (self.test_list.options.enable_charge_manager and
1551 self.test_list.options.min_charge_pct is not None):
Vic Yang4953fc12012-07-26 16:19:53 +08001552 self.charge_manager = ChargeManager(self.test_list.options.min_charge_pct,
1553 self.test_list.options.max_charge_pct)
Hung-Te Linc17b3d82015-12-15 15:26:08 +08001554 self.dut.status.Overrides('charge_manager', self.charge_manager)
Cheng-Yi Chiangd8186952013-04-04 23:41:14 +08001555 else:
1556 # Goofy should set charger state to charge if charge_manager is disabled.
Dean Liao88b93192014-10-23 19:37:41 +08001557 self.charge()
Vic Yang4953fc12012-07-26 16:19:53 +08001558
Vic Yang6cee2472014-10-22 17:18:52 -07001559 if CoreDumpManager.CoreDumpEnabled():
1560 self.core_dump_manager = CoreDumpManager(
1561 self.test_list.options.core_dump_watchlist)
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001562
Jon Salz0697cbf2012-07-04 15:14:04 +08001563 os.environ['CROS_FACTORY'] = '1'
1564 os.environ['CROS_DISABLE_SITE_SYSINFO'] = '1'
1565
Shuo-Peng Liao1ff502e2013-06-30 18:37:02 +08001566 if not utils.in_chroot() and self.test_list.options.use_cpufreq_manager:
Ricky Liangecddbd42014-07-24 11:32:10 +08001567 logging.info('Enabling CPU frequency manager')
Jon Salzddf0d052013-06-18 12:52:44 +08001568 self.cpufreq_manager = CpufreqManager(event_log=self.event_log)
Jon Salzce6a7f82013-06-10 18:22:54 +08001569
Justin Chuang31b02432013-06-27 15:16:51 +08001570 # Startup hooks may want to skip some tests.
1571 self.update_skipped_tests()
Jon Salz416f9cc2013-05-10 18:32:50 +08001572
Jon Salze12c2b32013-06-25 16:24:34 +08001573 self.find_kcrashes()
1574
Shuo-Peng Liao268b40b2013-07-01 15:58:59 +08001575 # Should not move earlier.
1576 self.hooks.OnStartup()
1577
Ricky Liang36512a32014-07-25 11:47:04 +08001578 # Only after this point the Goofy backend is ready for UI connection.
1579 self.ready_for_ui_connection = True
1580
Ricky Liang650f6bf2012-09-28 13:22:54 +08001581 # Create download path for autotest beforehand or autotests run at
1582 # the same time might fail due to race condition.
1583 if not factory.in_chroot():
1584 utils.TryMakeDirs(os.path.join('/usr/local/autotest', 'tests',
1585 'download'))
1586
Jon Salz0697cbf2012-07-04 15:14:04 +08001587 def state_change_callback(test, test_state):
1588 self.event_client.post_event(
Ricky Liang4bff3e32014-02-20 18:46:11 +08001589 Event(Event.Type.STATE_CHANGE, path=test.path, state=test_state))
Jon Salz0697cbf2012-07-04 15:14:04 +08001590 self.test_list.state_change_callback = state_change_callback
Jon Salz73e0fd02012-04-04 11:46:38 +08001591
Vic Yange2c76a82014-10-30 12:48:19 -07001592 self.autotest_prespawner = prespawner.AutotestPrespawner()
1593 self.autotest_prespawner.start()
1594
1595 self.pytest_prespawner = prespawner.PytestPrespawner()
1596 self.pytest_prespawner.start()
Jon Salza6711d72012-07-18 14:33:03 +08001597
Ricky Liang48e47f92014-02-26 19:31:51 +08001598 tests_after_shutdown = self.state_instance.get_shared_data(
1599 'tests_after_shutdown', optional=True)
Jon Salz57717ca2012-04-04 16:47:25 +08001600
Jon Salz5c344f62012-07-13 14:31:16 +08001601 force_auto_run = (tests_after_shutdown == FORCE_AUTO_RUN)
1602 if not force_auto_run and tests_after_shutdown is not None:
Ricky Liang48e47f92014-02-26 19:31:51 +08001603 logging.info('Resuming tests after shutdown: %s', tests_after_shutdown)
Jon Salz0697cbf2012-07-04 15:14:04 +08001604 self.tests_to_run.extend(
Ricky Liang4bff3e32014-02-20 18:46:11 +08001605 self.test_list.lookup_path(t) for t in tests_after_shutdown)
Peter Ammon1e1ec572014-06-26 17:56:32 -07001606 self.run_enqueue(self.run_next_test)
Jon Salz0697cbf2012-07-04 15:14:04 +08001607 else:
Jon Salz5c344f62012-07-13 14:31:16 +08001608 if force_auto_run or self.test_list.options.auto_run_on_start:
Ricky Liang117484a2014-04-14 11:14:41 +08001609 # If automation mode is enabled, allow suppress auto_run_on_start.
1610 if (self.options.automation_mode == 'NONE' or
1611 self.options.auto_run_on_start):
Chih-Yu Huang85dc63c2015-08-12 15:21:28 +08001612 status_filter = [TestState.UNTESTED]
1613 if self.test_list.options.retry_failed_on_start:
1614 status_filter.append(TestState.FAILED)
1615 self.run_enqueue(lambda: self.run_tests(self.test_list, status_filter))
Jon Salz5c344f62012-07-13 14:31:16 +08001616 self.state_instance.set_shared_data('tests_after_shutdown', None)
Ricky Liang4bff3e32014-02-20 18:46:11 +08001617 self.restore_active_run_state()
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001618
Hung-Te Lin410f70a2015-12-15 14:53:42 +08001619 self.dut.hooks.OnTestStart()
Vic Yang08505c72015-01-06 17:01:53 -08001620
Dean Liao592e4d52013-01-10 20:06:39 +08001621 self.may_disable_cros_shortcut_keys()
1622
1623 def may_disable_cros_shortcut_keys(self):
1624 test_options = self.test_list.options
1625 if test_options.disable_cros_shortcut_keys:
1626 logging.info('Filter ChromeOS shortcut keys.')
1627 self.key_filter = KeyFilter(
1628 unmap_caps_lock=test_options.disable_caps_lock,
1629 caps_lock_keycode=test_options.caps_lock_keycode)
1630 self.key_filter.Start()
1631
Jon Salz0e6532d2012-10-25 16:30:11 +08001632 def _should_sync_time(self, foreground=False):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001633 """Returns True if we should attempt syncing time with shopfloor.
Jon Salz0e6532d2012-10-25 16:30:11 +08001634
1635 Args:
1636 foreground: If True, synchronizes even if background syncing
1637 is disabled (e.g., in explicit sync requests from the
1638 SyncShopfloor test).
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001639 """
Jon Salz0e6532d2012-10-25 16:30:11 +08001640 return ((foreground or
1641 self.test_list.options.sync_time_period_secs) and
Jon Salz54882d02012-08-31 01:57:54 +08001642 self.time_sanitizer and
1643 (not self.time_synced) and
1644 (not factory.in_chroot()))
1645
Jon Salz0e6532d2012-10-25 16:30:11 +08001646 def sync_time_with_shopfloor_server(self, foreground=False):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001647 """Syncs time with shopfloor server, if not yet synced.
Jon Salz54882d02012-08-31 01:57:54 +08001648
Jon Salz0e6532d2012-10-25 16:30:11 +08001649 Args:
1650 foreground: If True, synchronizes even if background syncing
1651 is disabled (e.g., in explicit sync requests from the
1652 SyncShopfloor test).
1653
Jon Salz54882d02012-08-31 01:57:54 +08001654 Returns:
1655 False if no time sanitizer is available, or True if this sync (or a
1656 previous sync) succeeded.
1657
1658 Raises:
1659 Exception if unable to contact the shopfloor server.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001660 """
Jon Salz0e6532d2012-10-25 16:30:11 +08001661 if self._should_sync_time(foreground):
Jon Salz54882d02012-08-31 01:57:54 +08001662 self.time_sanitizer.SyncWithShopfloor()
1663 self.time_synced = True
1664 return self.time_synced
1665
Jon Salzb92c5112012-09-21 15:40:11 +08001666 def log_disk_space_stats(self):
Jon Salz18e0e022013-06-11 17:13:39 +08001667 if (utils.in_chroot() or
1668 not self.test_list.options.log_disk_space_period_secs):
Jon Salzb92c5112012-09-21 15:40:11 +08001669 return
1670
1671 now = time.time()
1672 if (self.last_log_disk_space_time and
1673 now - self.last_log_disk_space_time <
1674 self.test_list.options.log_disk_space_period_secs):
1675 return
1676 self.last_log_disk_space_time = now
1677
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001678 # Upload event if stateful partition usage is above threshold.
1679 # Stateful partition is mounted on /usr/local, while
1680 # encrypted stateful partition is mounted on /var.
1681 # If there are too much logs in the factory process,
1682 # these two partitions might get full.
Jon Salzb92c5112012-09-21 15:40:11 +08001683 try:
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001684 vfs_infos = disk_space.GetAllVFSInfo()
1685 stateful_info, encrypted_info = None, None
1686 for vfs_info in vfs_infos.values():
1687 if '/usr/local' in vfs_info.mount_points:
1688 stateful_info = vfs_info
1689 if '/var' in vfs_info.mount_points:
1690 encrypted_info = vfs_info
1691
1692 stateful = disk_space.GetPartitionUsage(stateful_info)
1693 encrypted = disk_space.GetPartitionUsage(encrypted_info)
1694
Ricky Liang45c73e72015-01-15 15:00:30 +08001695 above_threshold = (
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001696 self.test_list.options.stateful_usage_threshold and
1697 max(stateful.bytes_used_pct,
1698 stateful.inodes_used_pct,
1699 encrypted.bytes_used_pct,
1700 encrypted.inodes_used_pct) >
Ricky Liang45c73e72015-01-15 15:00:30 +08001701 self.test_list.options.stateful_usage_threshold)
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001702
1703 if above_threshold:
1704 self.event_log.Log('stateful_partition_usage',
Ricky Liang45c73e72015-01-15 15:00:30 +08001705 partitions={
1706 'stateful': {
1707 'bytes_used_pct': FloatDigit(stateful.bytes_used_pct, 2),
1708 'inodes_used_pct': FloatDigit(stateful.inodes_used_pct, 2)},
1709 'encrypted_stateful': {
1710 'bytes_used_pct': FloatDigit(encrypted.bytes_used_pct, 2),
1711 'inodes_used_pct': FloatDigit(encrypted.inodes_used_pct, 2)}
1712 })
Cheng-Yi Chiang1b722322015-03-16 20:07:03 +08001713 self.log_watcher.KickWatchThread()
Cheng-Yi Chiang00798e72013-06-20 18:16:39 +08001714 if (not utils.in_chroot() and
1715 self.test_list.options.stateful_usage_above_threshold_action):
1716 Spawn(self.test_list.options.stateful_usage_above_threshold_action,
1717 call=True)
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001718
1719 message = disk_space.FormatSpaceUsedAll(vfs_infos)
Jon Salz3c493bb2013-02-07 17:24:58 +08001720 if message != self.last_log_disk_space_message:
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001721 if above_threshold:
1722 logging.warning(message)
1723 else:
1724 logging.info(message)
Jon Salz3c493bb2013-02-07 17:24:58 +08001725 self.last_log_disk_space_message = message
Jon Salzb92c5112012-09-21 15:40:11 +08001726 except: # pylint: disable=W0702
1727 logging.exception('Unable to get disk space used')
1728
Justin Chuang83813982013-05-13 01:26:32 +08001729 def check_battery(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001730 """Checks the current battery status.
Justin Chuang83813982013-05-13 01:26:32 +08001731
1732 Logs current battery charging level and status to log. If the battery level
1733 is lower below warning_low_battery_pct, send warning event to shopfloor.
1734 If the battery level is lower below critical_low_battery_pct, flush disks.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001735 """
Justin Chuang83813982013-05-13 01:26:32 +08001736 if not self.test_list.options.check_battery_period_secs:
1737 return
1738
1739 now = time.time()
1740 if (self.last_check_battery_time and
1741 now - self.last_check_battery_time <
1742 self.test_list.options.check_battery_period_secs):
1743 return
1744 self.last_check_battery_time = now
1745
1746 message = ''
1747 log_level = logging.INFO
1748 try:
Hung-Te Lin6a72c642015-12-13 22:09:09 +08001749 power = self.dut.power
Justin Chuang83813982013-05-13 01:26:32 +08001750 if not power.CheckBatteryPresent():
1751 message = 'Battery is not present'
1752 else:
1753 ac_present = power.CheckACPresent()
1754 charge_pct = power.GetChargePct(get_float=True)
1755 message = ('Current battery level %.1f%%, AC charger is %s' %
1756 (charge_pct, 'connected' if ac_present else 'disconnected'))
1757
1758 if charge_pct > self.test_list.options.critical_low_battery_pct:
1759 critical_low_battery = False
1760 else:
1761 critical_low_battery = True
1762 # Only sync disks when battery level is still above minimum
1763 # value. This can be used for offline analysis when shopfloor cannot
1764 # be connected.
1765 if charge_pct > MIN_BATTERY_LEVEL_FOR_DISK_SYNC:
1766 logging.warning('disk syncing for critical low battery situation')
1767 os.system('sync; sync; sync')
1768 else:
1769 logging.warning('disk syncing is cancelled '
1770 'because battery level is lower than %.1f',
1771 MIN_BATTERY_LEVEL_FOR_DISK_SYNC)
1772
1773 # Notify shopfloor server
1774 if (critical_low_battery or
1775 (not ac_present and
1776 charge_pct <= self.test_list.options.warning_low_battery_pct)):
1777 log_level = logging.WARNING
1778
1779 self.event_log.Log('low_battery',
1780 battery_level=charge_pct,
1781 charger_connected=ac_present,
1782 critical=critical_low_battery)
1783 self.log_watcher.KickWatchThread()
Cheng-Yi Chianga0f6eff2014-01-09 18:27:22 +08001784 if self.test_list.options.enable_sync_log:
1785 self.system_log_manager.KickToSync()
Ricky Liang45c73e72015-01-15 15:00:30 +08001786 except: # pylint: disable=W0702
Justin Chuang83813982013-05-13 01:26:32 +08001787 logging.exception('Unable to check battery or notify shopfloor')
1788 finally:
1789 if message != self.last_check_battery_message:
1790 logging.log(log_level, message)
1791 self.last_check_battery_message = message
1792
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001793 def check_core_dump(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001794 """Checks if there is any core dumped file.
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001795
1796 Removes unwanted core dump files immediately.
1797 Syncs those files matching watch list to server with a delay between
1798 each sync. After the files have been synced to server, deletes the files.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001799 """
Vic Yang6cee2472014-10-22 17:18:52 -07001800 if not self.core_dump_manager:
1801 return
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001802 core_dump_files = self.core_dump_manager.ScanFiles()
1803 if core_dump_files:
1804 now = time.time()
1805 if (self.last_kick_sync_time and now - self.last_kick_sync_time <
1806 self.test_list.options.kick_sync_min_interval_secs):
1807 return
1808 self.last_kick_sync_time = now
1809
1810 # Sends event to server
1811 self.event_log.Log('core_dumped', files=core_dump_files)
1812 self.log_watcher.KickWatchThread()
1813
1814 # Syncs files to server
Cheng-Yi Chianga0f6eff2014-01-09 18:27:22 +08001815 if self.test_list.options.enable_sync_log:
1816 self.system_log_manager.KickToSync(
Cheng-Yi Chiangd3516a32013-07-17 15:30:47 +08001817 core_dump_files, self.core_dump_manager.ClearFiles)
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001818
Cheng-Yi Chiang39d32ad2013-07-23 15:02:38 +08001819 def check_log_rotation(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001820 """Checks log rotation file presence/absence according to test_list option.
Cheng-Yi Chiang39d32ad2013-07-23 15:02:38 +08001821
1822 Touch /var/lib/cleanup_logs_paused if test_list.options.disable_log_rotation
1823 is True, delete it otherwise. This must be done in idle loop because
1824 autotest client will touch /var/lib/cleanup_logs_paused each time it runs
1825 an autotest.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001826 """
Cheng-Yi Chiang39d32ad2013-07-23 15:02:38 +08001827 if utils.in_chroot():
1828 return
1829 try:
1830 if self.test_list.options.disable_log_rotation:
1831 open(CLEANUP_LOGS_PAUSED, 'w').close()
1832 else:
1833 file_utils.TryUnlink(CLEANUP_LOGS_PAUSED)
1834 except: # pylint: disable=W0702
1835 # Oh well. Logs an error (but no trace)
1836 logging.info(
1837 'Unable to %s %s: %s',
1838 'touch' if self.test_list.options.disable_log_rotation else 'delete',
1839 CLEANUP_LOGS_PAUSED, utils.FormatExceptionOnly())
1840
Jon Salz8fa8e832012-07-13 19:04:09 +08001841 def sync_time_in_background(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001842 """Writes out current time and tries to sync with shopfloor server."""
Jon Salzb22d1172012-08-06 10:38:57 +08001843 if not self.time_sanitizer:
1844 return
1845
1846 # Write out the current time.
1847 self.time_sanitizer.SaveTime()
1848
Jon Salz54882d02012-08-31 01:57:54 +08001849 if not self._should_sync_time():
Jon Salz8fa8e832012-07-13 19:04:09 +08001850 return
1851
1852 now = time.time()
1853 if self.last_sync_time and (
1854 now - self.last_sync_time <
1855 self.test_list.options.sync_time_period_secs):
1856 # Not yet time for another check.
1857 return
1858 self.last_sync_time = now
1859
1860 def target():
1861 try:
Jon Salz54882d02012-08-31 01:57:54 +08001862 self.sync_time_with_shopfloor_server()
Jon Salz8fa8e832012-07-13 19:04:09 +08001863 except: # pylint: disable=W0702
1864 # Oh well. Log an error (but no trace)
1865 logging.info(
Ricky Liang45c73e72015-01-15 15:00:30 +08001866 'Unable to get time from shopfloor server: %s',
1867 utils.FormatExceptionOnly())
Jon Salz8fa8e832012-07-13 19:04:09 +08001868
1869 thread = threading.Thread(target=target)
1870 thread.daemon = True
1871 thread.start()
1872
Peter Ammon1e1ec572014-06-26 17:56:32 -07001873 def perform_periodic_tasks(self):
1874 """Override of base method to perform periodic work.
Vic Yang4953fc12012-07-26 16:19:53 +08001875
Peter Ammon1e1ec572014-06-26 17:56:32 -07001876 This method must not raise exceptions.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001877 """
Peter Ammon1e1ec572014-06-26 17:56:32 -07001878 super(Goofy, self).perform_periodic_tasks()
Jon Salzb22d1172012-08-06 10:38:57 +08001879
Vic Yang311ddb82012-09-26 12:08:28 +08001880 self.check_exclusive()
cychiang21886742012-07-05 15:16:32 +08001881 self.check_for_updates()
Jon Salz8fa8e832012-07-13 19:04:09 +08001882 self.sync_time_in_background()
Jon Salzb92c5112012-09-21 15:40:11 +08001883 self.log_disk_space_stats()
Justin Chuang83813982013-05-13 01:26:32 +08001884 self.check_battery()
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001885 self.check_core_dump()
Cheng-Yi Chiang39d32ad2013-07-23 15:02:38 +08001886 self.check_log_rotation()
Jon Salz57717ca2012-04-04 16:47:25 +08001887
Cheng-Yi Chiangf5b21012015-03-17 15:37:14 +08001888 def handle_event_logs(self, chunks, periodic=False):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001889 """Callback for event watcher.
Jon Salz258a40c2012-04-19 12:34:01 +08001890
Jon Salz0697cbf2012-07-04 15:14:04 +08001891 Attempts to upload the event logs to the shopfloor server.
Vic Yang93027612013-05-06 02:42:49 +08001892
1893 Args:
Jon Salzd15bbcf2013-05-21 17:33:57 +08001894 chunks: A list of Chunk objects.
Cheng-Yi Chiangf5b21012015-03-17 15:37:14 +08001895 periodic: This event log handling is periodic. Error messages
1896 will only be shown for the first time.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001897 """
Vic Yang93027612013-05-06 02:42:49 +08001898 first_exception = None
1899 exception_count = 0
Cheng-Yi Chiangf5b21012015-03-17 15:37:14 +08001900 # Suppress error messages for periodic event syncing except for the
1901 # first time. If event syncing is not periodic, always show the error
1902 # messages.
1903 quiet = self._suppress_event_log_error_messages if periodic else False
Vic Yang93027612013-05-06 02:42:49 +08001904
Jon Salzd15bbcf2013-05-21 17:33:57 +08001905 for chunk in chunks:
Vic Yang93027612013-05-06 02:42:49 +08001906 try:
Jon Salzcddb6402013-05-23 12:56:42 +08001907 description = 'event logs (%s)' % str(chunk)
Vic Yang93027612013-05-06 02:42:49 +08001908 start_time = time.time()
1909 shopfloor_client = shopfloor.get_instance(
Ricky Liang45c73e72015-01-15 15:00:30 +08001910 detect=True,
Cheng-Yi Chiangf5b21012015-03-17 15:37:14 +08001911 timeout=self.test_list.options.shopfloor_timeout_secs,
1912 quiet=quiet)
Ricky Liang45c73e72015-01-15 15:00:30 +08001913 shopfloor_client.UploadEvent(chunk.log_name + '.' +
Jon Salzd15bbcf2013-05-21 17:33:57 +08001914 event_log.GetReimageId(),
1915 Binary(chunk.chunk))
Vic Yang93027612013-05-06 02:42:49 +08001916 logging.info(
Ricky Liang45c73e72015-01-15 15:00:30 +08001917 'Successfully synced %s in %.03f s',
1918 description, time.time() - start_time)
1919 except: # pylint: disable=W0702
Jon Salzd15bbcf2013-05-21 17:33:57 +08001920 first_exception = (first_exception or (chunk.log_name + ': ' +
Vic Yang93027612013-05-06 02:42:49 +08001921 utils.FormatExceptionOnly()))
1922 exception_count += 1
1923
1924 if exception_count:
1925 if exception_count == 1:
1926 msg = 'Log upload failed: %s' % first_exception
1927 else:
1928 msg = '%d log upload failed; first is: %s' % (
1929 exception_count, first_exception)
Cheng-Yi Chiangf5b21012015-03-17 15:37:14 +08001930 # For periodic event log syncing, only show the first error messages.
1931 if periodic:
1932 if not self._suppress_event_log_error_messages:
1933 self._suppress_event_log_error_messages = True
1934 logging.warning('Suppress periodic shopfloor error messages for '
1935 'event log syncing after the first one.')
1936 raise Exception(msg)
1937 # For event log syncing by request, show the error messages.
1938 else:
1939 raise Exception(msg)
Vic Yang93027612013-05-06 02:42:49 +08001940
Ricky Liang45c73e72015-01-15 15:00:30 +08001941 def run_tests_with_status(self, statuses_to_run, starting_at=None, root=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001942 """Runs all top-level tests with a particular status.
Jon Salz0405ab52012-03-16 15:26:52 +08001943
Jon Salz0697cbf2012-07-04 15:14:04 +08001944 All active tests, plus any tests to re-run, are reset.
Jon Salz57717ca2012-04-04 16:47:25 +08001945
Jon Salz0697cbf2012-07-04 15:14:04 +08001946 Args:
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001947 statuses_to_run: The particular status that caller wants to run.
Jon Salz0697cbf2012-07-04 15:14:04 +08001948 starting_at: If provided, only auto-runs tests beginning with
1949 this test.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001950 root: The root of tests to run. If not provided, it will be
1951 the root of all tests.
1952 """
Jon Salz0697cbf2012-07-04 15:14:04 +08001953 root = root or self.test_list
Jon Salz57717ca2012-04-04 16:47:25 +08001954
Jon Salz0697cbf2012-07-04 15:14:04 +08001955 if starting_at:
1956 # Make sure they passed a test, not a string.
1957 assert isinstance(starting_at, factory.FactoryTest)
Jon Salz0405ab52012-03-16 15:26:52 +08001958
Jon Salz0697cbf2012-07-04 15:14:04 +08001959 tests_to_reset = []
1960 tests_to_run = []
Jon Salz0405ab52012-03-16 15:26:52 +08001961
Jon Salz0697cbf2012-07-04 15:14:04 +08001962 found_starting_at = False
Jon Salz0405ab52012-03-16 15:26:52 +08001963
Jon Salz0697cbf2012-07-04 15:14:04 +08001964 for test in root.get_top_level_tests():
1965 if starting_at:
1966 if test == starting_at:
1967 # We've found starting_at; do auto-run on all
1968 # subsequent tests.
1969 found_starting_at = True
1970 if not found_starting_at:
1971 # Don't start this guy yet
1972 continue
Jon Salz0405ab52012-03-16 15:26:52 +08001973
Jon Salz0697cbf2012-07-04 15:14:04 +08001974 status = test.get_state().status
1975 if status == TestState.ACTIVE or status in statuses_to_run:
1976 # Reset the test (later; we will need to abort
1977 # all active tests first).
1978 tests_to_reset.append(test)
1979 if status in statuses_to_run:
1980 tests_to_run.append(test)
Jon Salz0405ab52012-03-16 15:26:52 +08001981
Jon Salz6dc031d2013-06-19 13:06:23 +08001982 self.abort_active_tests('Operator requested run/re-run of certain tests')
Jon Salz258a40c2012-04-19 12:34:01 +08001983
Jon Salz0697cbf2012-07-04 15:14:04 +08001984 # Reset all statuses of the tests to run (in case any tests were active;
1985 # we want them to be run again).
1986 for test_to_reset in tests_to_reset:
1987 for test in test_to_reset.walk():
1988 test.update_state(status=TestState.UNTESTED)
Jon Salz57717ca2012-04-04 16:47:25 +08001989
Chih-Yu Huang85dc63c2015-08-12 15:21:28 +08001990 self.run_tests(tests_to_run, [TestState.UNTESTED])
Jon Salz0405ab52012-03-16 15:26:52 +08001991
Jon Salz0697cbf2012-07-04 15:14:04 +08001992 def restart_tests(self, root=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001993 """Restarts all tests."""
Jon Salz0697cbf2012-07-04 15:14:04 +08001994 root = root or self.test_list
Jon Salz0405ab52012-03-16 15:26:52 +08001995
Jon Salz6dc031d2013-06-19 13:06:23 +08001996 self.abort_active_tests('Operator requested restart of certain tests')
Jon Salz0697cbf2012-07-04 15:14:04 +08001997 for test in root.walk():
Ricky Liangfea4ac92014-08-21 11:55:59 +08001998 test.update_state(status=TestState.UNTESTED)
Jon Salz0697cbf2012-07-04 15:14:04 +08001999 self.run_tests(root)
Hung-Te Lin96632362012-03-20 21:14:18 +08002000
Jon Salz0697cbf2012-07-04 15:14:04 +08002001 def auto_run(self, starting_at=None, root=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08002002 """"Auto-runs" tests that have not been run yet.
Hung-Te Lin96632362012-03-20 21:14:18 +08002003
Jon Salz0697cbf2012-07-04 15:14:04 +08002004 Args:
2005 starting_at: If provide, only auto-runs tests beginning with
2006 this test.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08002007 root: If provided, the root of tests to run. If not provided, the root
2008 will be test_list (root of all tests).
2009 """
Jon Salz0697cbf2012-07-04 15:14:04 +08002010 root = root or self.test_list
2011 self.run_tests_with_status([TestState.UNTESTED, TestState.ACTIVE],
Ricky Liang45c73e72015-01-15 15:00:30 +08002012 starting_at=starting_at,
2013 root=root)
Jon Salz968e90b2012-03-18 16:12:43 +08002014
Jon Salz0697cbf2012-07-04 15:14:04 +08002015 def re_run_failed(self, root=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08002016 """Re-runs failed tests."""
Jon Salz0697cbf2012-07-04 15:14:04 +08002017 root = root or self.test_list
2018 self.run_tests_with_status([TestState.FAILED], root=root)
Jon Salz57717ca2012-04-04 16:47:25 +08002019
Jon Salz0697cbf2012-07-04 15:14:04 +08002020 def show_review_information(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08002021 """Event handler for showing review information screen.
Jon Salz57717ca2012-04-04 16:47:25 +08002022
Peter Ammon1e1ec572014-06-26 17:56:32 -07002023 The information screen is rendered by main UI program (ui.py), so in
Jon Salz0697cbf2012-07-04 15:14:04 +08002024 goofy we only need to kill all active tests, set them as untested, and
2025 clear remaining tests.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08002026 """
Jon Salz0697cbf2012-07-04 15:14:04 +08002027 self.kill_active_tests(False)
Jon Salza6711d72012-07-18 14:33:03 +08002028 self.cancel_pending_tests()
Jon Salz57717ca2012-04-04 16:47:25 +08002029
Jon Salz0697cbf2012-07-04 15:14:04 +08002030 def handle_switch_test(self, event):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08002031 """Switches to a particular test.
Jon Salz0405ab52012-03-16 15:26:52 +08002032
Ricky Liang6fe218c2013-12-27 15:17:17 +08002033 Args:
2034 event: The SWITCH_TEST event.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08002035 """
Jon Salz0697cbf2012-07-04 15:14:04 +08002036 test = self.test_list.lookup_path(event.path)
2037 if not test:
2038 logging.error('Unknown test %r', event.key)
2039 return
Jon Salz73e0fd02012-04-04 11:46:38 +08002040
Jon Salz0697cbf2012-07-04 15:14:04 +08002041 invoc = self.invocations.get(test)
2042 if invoc and test.backgroundable:
2043 # Already running: just bring to the front if it
2044 # has a UI.
2045 logging.info('Setting visible test to %s', test.path)
Jon Salz36fbbb52012-07-05 13:45:06 +08002046 self.set_visible_test(test)
Jon Salz0697cbf2012-07-04 15:14:04 +08002047 return
Jon Salz73e0fd02012-04-04 11:46:38 +08002048
Jon Salz6dc031d2013-06-19 13:06:23 +08002049 self.abort_active_tests('Operator requested abort (switch_test)')
Jon Salz0697cbf2012-07-04 15:14:04 +08002050 for t in test.walk():
2051 t.update_state(status=TestState.UNTESTED)
Jon Salz73e0fd02012-04-04 11:46:38 +08002052
Jon Salz0697cbf2012-07-04 15:14:04 +08002053 if self.test_list.options.auto_run_on_keypress:
2054 self.auto_run(starting_at=test)
2055 else:
2056 self.run_tests(test)
Jon Salz73e0fd02012-04-04 11:46:38 +08002057
Wei-Ning Huang38b75f02015-02-25 18:25:14 +08002058 def handle_key_filter_mode(self, event):
2059 if self.key_filter:
2060 if getattr(event, 'enabled'):
2061 self.key_filter.Start()
2062 else:
2063 self.key_filter.Stop()
2064
Jon Salz0697cbf2012-07-04 15:14:04 +08002065 def wait(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08002066 """Waits for all pending invocations.
Jon Salz0697cbf2012-07-04 15:14:04 +08002067
2068 Useful for testing.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08002069 """
Jon Salz1acc8742012-07-17 17:45:55 +08002070 while self.invocations:
2071 for k, v in self.invocations.iteritems():
2072 logging.info('Waiting for %s to complete...', k)
2073 v.thread.join()
2074 self.reap_completed_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +08002075
Claire Changd1961a22015-08-05 16:15:55 +08002076 def test_fail(self, test):
Hung-Te Lin410f70a2015-12-15 14:53:42 +08002077 self.dut.hooks.OnTestFailure(test)
Claire Changd1961a22015-08-05 16:15:55 +08002078 if self.link_manager:
2079 self.link_manager.UpdateStatus(False)
2080
Hung-Te Linf2f78f72012-02-08 19:27:11 +08002081if __name__ == '__main__':
Peter Ammona3d298c2014-09-23 10:11:02 -07002082 Goofy.run_main_and_exit()