blob: 2612ab18b2a630dcb2f030a8b572f5cee242ee31 [file] [log] [blame]
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001#!/usr/bin/python -u
Hung-Te Linf2f78f72012-02-08 19:27:11 +08002# -*- coding: utf-8 -*-
3#
Jon Salz37eccbd2012-05-25 16:06:52 +08004# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
Hung-Te Linf2f78f72012-02-08 19:27:11 +08005# Use of this source code is governed by a BSD-style license that can be
6# found in the LICENSE file.
7
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08008"""The main factory flow that runs the factory test and finalizes a device."""
Hung-Te Linf2f78f72012-02-08 19:27:11 +08009
Joel Kitchingb85ed7f2014-10-08 18:24:39 +080010from __future__ import print_function
11
Jon Salze12c2b32013-06-25 16:24:34 +080012import glob
Jon Salz0405ab52012-03-16 15:26:52 +080013import logging
14import os
Jon Salze12c2b32013-06-25 16:24:34 +080015import shutil
Jon Salz77c151e2012-08-28 07:20:37 +080016import signal
Jon Salz0405ab52012-03-16 15:26:52 +080017import sys
Jon Salzeff94182013-06-19 15:06:28 +080018import syslog
Jon Salz0405ab52012-03-16 15:26:52 +080019import threading
20import time
21import traceback
Jon Salz258a40c2012-04-19 12:34:01 +080022import uuid
Jon Salzb10cf512012-08-09 17:29:21 +080023from xmlrpclib import Binary
Hung-Te Linf2f78f72012-02-08 19:27:11 +080024from collections import deque
25from optparse import OptionParser
Hung-Te Linf2f78f72012-02-08 19:27:11 +080026
Jon Salz0697cbf2012-07-04 15:14:04 +080027import factory_common # pylint: disable=W0611
Hung-Te Linb6287242016-05-18 14:39:05 +080028from cros.factory.device import device_utils
29from cros.factory.device import DeviceException
Hung-Te Lincc41d2a2014-10-29 13:35:20 +080030from cros.factory.goofy import connection_manager
Vic Yangd80ea752014-09-24 16:07:14 +080031from cros.factory.goofy import test_environment
32from cros.factory.goofy import time_sanitizer
33from cros.factory.goofy import updater
34from cros.factory.goofy.goofy_base import GoofyBase
35from cros.factory.goofy.goofy_rpc import GoofyRPC
36from cros.factory.goofy.invocation import TestArgEnv
37from cros.factory.goofy.invocation import TestInvocation
38from cros.factory.goofy.link_manager import PresenterLinkManager
Vic Yange2c76a82014-10-30 12:48:19 -070039from cros.factory.goofy import prespawner
Vic Yangd80ea752014-09-24 16:07:14 +080040from cros.factory.goofy.system_log_manager import SystemLogManager
Wei-Ning Huang38b75f02015-02-25 18:25:14 +080041from cros.factory.goofy.terminal_manager import TerminalManager
Vic Yangd80ea752014-09-24 16:07:14 +080042from cros.factory.goofy.web_socket_manager import WebSocketManager
jcliangcd688182012-08-20 21:01:26 +080043from cros.factory.test import factory
Jon Salz51528e12012-07-02 18:54:45 +080044from cros.factory.test import shopfloor
Hung-Te Lin6a72c642015-12-13 22:09:09 +080045from cros.factory.test import state
Hung-Te Linb6287242016-05-18 14:39:05 +080046from cros.factory.test import testlog
47from cros.factory.test import testlog_goofy
48from cros.factory.test.e2e_test.common import AutomationMode
49from cros.factory.test.e2e_test.common import AutomationModePrompt
50from cros.factory.test.e2e_test.common import ParseAutomationMode
51from cros.factory.test.env import paths
Jon Salz83591782012-06-26 11:09:58 +080052from cros.factory.test.event import Event
53from cros.factory.test.event import EventClient
54from cros.factory.test.event import EventServer
Hung-Te Linb6287242016-05-18 14:39:05 +080055from cros.factory.test import event_log
56from cros.factory.test.event_log import EventLog
57from cros.factory.test.event_log import FloatDigit
58from cros.factory.test.event_log import GetBootSequence
Hung-Te Lin91492a12014-11-25 18:56:30 +080059from cros.factory.test.event_log_watcher import EventLogWatcher
jcliangcd688182012-08-20 21:01:26 +080060from cros.factory.test.factory import TestState
Hung-Te Lin3f096842016-01-13 17:37:06 +080061from cros.factory.test.rules import phase
Wei-Han Chen2ebb92d2016-01-12 14:51:41 +080062from cros.factory.test.test_lists import test_lists
Hung-Te Linc367ac02015-12-22 19:33:23 +080063from cros.factory.test.utils.charge_manager import ChargeManager
64from cros.factory.test.utils.core_dump_manager import CoreDumpManager
65from cros.factory.test.utils.cpufreq_manager import CpufreqManager
Hung-Te Lind3ee0102015-12-28 17:21:50 +080066from cros.factory.tools import disk_space
Hung-Te Linb6287242016-05-18 14:39:05 +080067from cros.factory.tools.key_filter import KeyFilter
Hung-Te Linf707b242016-01-08 23:11:42 +080068from cros.factory.utils import debug_utils
Jon Salz2af235d2013-06-24 14:47:21 +080069from cros.factory.utils import file_utils
Joel Kitchingb85ed7f2014-10-08 18:24:39 +080070from cros.factory.utils import net_utils
Hung-Te Lin4e6357c2016-01-08 14:32:00 +080071from cros.factory.utils import process_utils
72from cros.factory.utils import sys_utils
73from cros.factory.utils import time_utils
Hung-Te Linf707b242016-01-08 23:11:42 +080074from cros.factory.utils import type_utils
Hung-Te Linf2f78f72012-02-08 19:27:11 +080075
76
Hung-Te Linf2f78f72012-02-08 19:27:11 +080077HWID_CFG_PATH = '/usr/local/share/chromeos-hwid/cfg'
Joel Kitching625ff0f2016-05-16 14:59:40 -070078CACHES_DIR = os.path.join(paths.GetStateRoot(), 'caches')
Hung-Te Linf2f78f72012-02-08 19:27:11 +080079
Cheng-Yi Chiang39d32ad2013-07-23 15:02:38 +080080CLEANUP_LOGS_PAUSED = '/var/lib/cleanup_logs_paused'
81
Jon Salz5c344f62012-07-13 14:31:16 +080082# Value for tests_after_shutdown that forces auto-run (e.g., after
83# a factory update, when the available set of tests might change).
84FORCE_AUTO_RUN = 'force_auto_run'
85
Justin Chuang83813982013-05-13 01:26:32 +080086# Sync disks when battery level is higher than this value.
87# Otherwise, power loss during disk sync operation may incur even worse outcome.
88MIN_BATTERY_LEVEL_FOR_DISK_SYNC = 1.0
89
Ricky Liang45c73e72015-01-15 15:00:30 +080090MAX_CRASH_FILE_SIZE = 64 * 1024
Jon Salze12c2b32013-06-25 16:24:34 +080091
Hung-Te Linf707b242016-01-08 23:11:42 +080092Status = type_utils.Enum(['UNINITIALIZED', 'INITIALIZING', 'RUNNING',
Wei-Han Chen2ebb92d2016-01-12 14:51:41 +080093 'TERMINATING', 'TERMINATED'])
Jon Salzd7550792013-07-12 05:49:27 +080094
Ricky Liang45c73e72015-01-15 15:00:30 +080095
Hung-Te Linf2f78f72012-02-08 19:27:11 +080096def get_hwid_cfg():
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +080097 """Returns the HWID config tag, or an empty string if none can be found."""
Jon Salz0697cbf2012-07-04 15:14:04 +080098 if 'CROS_HWID' in os.environ:
99 return os.environ['CROS_HWID']
100 if os.path.exists(HWID_CFG_PATH):
Ricky Liang45c73e72015-01-15 15:00:30 +0800101 with open(HWID_CFG_PATH, 'r') as hwid_cfg_handle:
Jon Salz0697cbf2012-07-04 15:14:04 +0800102 return hwid_cfg_handle.read().strip()
103 return ''
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800104
105
Jon Salz73e0fd02012-04-04 11:46:38 +0800106_inited_logging = False
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800107
Ricky Liang45c73e72015-01-15 15:00:30 +0800108
Peter Ammon1e1ec572014-06-26 17:56:32 -0700109class Goofy(GoofyBase):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800110 """The main factory flow.
Jon Salz0697cbf2012-07-04 15:14:04 +0800111
112 Note that all methods in this class must be invoked from the main
113 (event) thread. Other threads, such as callbacks and TestInvocation
114 methods, should instead post events on the run queue.
115
116 TODO: Unit tests. (chrome-os-partner:7409)
117
118 Properties:
119 uuid: A unique UUID for this invocation of Goofy.
120 state_instance: An instance of FactoryState.
121 state_server: The FactoryState XML/RPC server.
122 state_server_thread: A thread running state_server.
123 event_server: The EventServer socket server.
124 event_server_thread: A thread running event_server.
125 event_client: A client to the event server.
126 connection_manager: The connection_manager object.
Cheng-Yi Chiang835f2682013-05-06 22:15:48 +0800127 system_log_manager: The SystemLogManager object.
128 core_dump_manager: The CoreDumpManager object.
Jon Salz0697cbf2012-07-04 15:14:04 +0800129 ui_process: The factory ui process object.
Jon Salz0697cbf2012-07-04 15:14:04 +0800130 invocations: A map from FactoryTest objects to the corresponding
131 TestInvocations objects representing active tests.
132 tests_to_run: A deque of tests that should be run when the current
133 test(s) complete.
134 options: Command-line options.
135 args: Command-line args.
136 test_list: The test list.
Jon Salz128b0932013-07-03 16:55:26 +0800137 test_lists: All new-style test lists.
Ricky Liang4bff3e32014-02-20 18:46:11 +0800138 run_id: The identifier for latest test run.
139 scheduled_run_tests: The list of tests scheduled for latest test run.
Jon Salz0697cbf2012-07-04 15:14:04 +0800140 event_handlers: Map of Event.Type to the method used to handle that
141 event. If the method has an 'event' argument, the event is passed
142 to the handler.
Jon Salz3c493bb2013-02-07 17:24:58 +0800143 last_log_disk_space_message: The last message we logged about disk space
144 (to avoid duplication).
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +0800145 last_kick_sync_time: The last time to kick system_log_manager to sync
146 because of core dump files (to avoid kicking too soon then abort the
147 sync.)
Jon Salz416f9cc2013-05-10 18:32:50 +0800148 hooks: A Hooks object containing hooks for various Goofy actions.
Jon Salzd7550792013-07-12 05:49:27 +0800149 status: The current Goofy status (a member of the Status enum).
Peter Ammon948b7172014-07-15 12:43:06 -0700150 link_manager: Instance of PresenterLinkManager for communicating
151 with GoofyPresenter
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800152 """
Ricky Liang45c73e72015-01-15 15:00:30 +0800153
Jon Salz0697cbf2012-07-04 15:14:04 +0800154 def __init__(self):
Peter Ammon1e1ec572014-06-26 17:56:32 -0700155 super(Goofy, self).__init__()
Jon Salz0697cbf2012-07-04 15:14:04 +0800156 self.uuid = str(uuid.uuid4())
157 self.state_instance = None
158 self.state_server = None
159 self.state_server_thread = None
Jon Salz16d10542012-07-23 12:18:45 +0800160 self.goofy_rpc = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800161 self.event_server = None
162 self.event_server_thread = None
163 self.event_client = None
164 self.connection_manager = None
Vic Yang4953fc12012-07-26 16:19:53 +0800165 self.charge_manager = None
Dean Liao88b93192014-10-23 19:37:41 +0800166 self._can_charge = True
Jon Salz8fa8e832012-07-13 19:04:09 +0800167 self.time_sanitizer = None
168 self.time_synced = False
Jon Salz0697cbf2012-07-04 15:14:04 +0800169 self.log_watcher = None
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +0800170 self.system_log_manager = None
Cheng-Yi Chiang835f2682013-05-06 22:15:48 +0800171 self.core_dump_manager = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800172 self.event_log = None
Chun-Ta Lin53cbbd52016-06-08 21:42:19 +0800173 self.testlog = None
Vic Yange2c76a82014-10-30 12:48:19 -0700174 self.autotest_prespawner = None
175 self.pytest_prespawner = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800176 self.ui_process = None
Vic Yanga3cecf82014-12-26 00:44:21 -0800177 self._ui_initialized = False
Jon Salzc79a9982012-08-30 04:42:01 +0800178 self.dummy_shopfloor = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800179 self.invocations = {}
180 self.tests_to_run = deque()
181 self.visible_test = None
182 self.chrome = None
Jon Salz416f9cc2013-05-10 18:32:50 +0800183 self.hooks = None
Vic Yangd8990da2013-06-27 16:57:43 +0800184 self.cpu_usage_watcher = None
Hung-Te Lin23cb7612016-01-19 19:19:32 +0800185 self.thermal_watcher = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800186
187 self.options = None
188 self.args = None
189 self.test_list = None
Jon Salz128b0932013-07-03 16:55:26 +0800190 self.test_lists = None
Ricky Liang4bff3e32014-02-20 18:46:11 +0800191 self.run_id = None
192 self.scheduled_run_tests = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800193 self.env = None
Jon Salzb22d1172012-08-06 10:38:57 +0800194 self.last_idle = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800195 self.last_shutdown_time = None
cychiang21886742012-07-05 15:16:32 +0800196 self.last_update_check = None
Cheng-Yi Chiang194d3c02015-03-16 14:37:15 +0800197 self._suppress_periodic_update_messages = False
Cheng-Yi Chiangf5b21012015-03-17 15:37:14 +0800198 self._suppress_event_log_error_messages = False
Jon Salz8fa8e832012-07-13 19:04:09 +0800199 self.last_sync_time = None
Jon Salzb92c5112012-09-21 15:40:11 +0800200 self.last_log_disk_space_time = None
Jon Salz3c493bb2013-02-07 17:24:58 +0800201 self.last_log_disk_space_message = None
Justin Chuang83813982013-05-13 01:26:32 +0800202 self.last_check_battery_time = None
203 self.last_check_battery_message = None
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +0800204 self.last_kick_sync_time = None
Vic Yang311ddb82012-09-26 12:08:28 +0800205 self.exclusive_items = set()
Dean Liao592e4d52013-01-10 20:06:39 +0800206 self.key_filter = None
Jon Salzce6a7f82013-06-10 18:22:54 +0800207 self.cpufreq_manager = None
Jon Salzd7550792013-07-12 05:49:27 +0800208 self.status = Status.UNINITIALIZED
Ricky Liang36512a32014-07-25 11:47:04 +0800209 self.ready_for_ui_connection = False
Peter Ammon1e1ec572014-06-26 17:56:32 -0700210 self.link_manager = None
Hung-Te Linef7f2be2015-07-20 20:38:51 +0800211 self.is_restart_requested = False
Jon Salz0697cbf2012-07-04 15:14:04 +0800212
Hung-Te Lin6a72c642015-12-13 22:09:09 +0800213 # TODO(hungte) Support controlling remote DUT.
Hung-Te Linb6287242016-05-18 14:39:05 +0800214 self.dut = device_utils.CreateDUTInterface()
Hung-Te Lin6a72c642015-12-13 22:09:09 +0800215
Jon Salz85a39882012-07-05 16:45:04 +0800216 def test_or_root(event, parent_or_group=True):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800217 """Returns the test affected by a particular event.
Jon Salz85a39882012-07-05 16:45:04 +0800218
219 Args:
220 event: The event containing an optional 'path' attribute.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800221 parent_or_group: If True, returns the top-level parent for a test (the
Jon Salz85a39882012-07-05 16:45:04 +0800222 root node of the tests that need to be run together if the given test
223 path is to be run).
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800224 """
Jon Salz0697cbf2012-07-04 15:14:04 +0800225 try:
226 path = event.path
227 except AttributeError:
228 path = None
229
230 if path:
Jon Salz85a39882012-07-05 16:45:04 +0800231 test = self.test_list.lookup_path(path)
232 if parent_or_group:
233 test = test.get_top_level_parent_or_group()
234 return test
Jon Salz0697cbf2012-07-04 15:14:04 +0800235 else:
236 return self.test_list
237
238 self.event_handlers = {
Ricky Liang45c73e72015-01-15 15:00:30 +0800239 Event.Type.SWITCH_TEST: self.handle_switch_test,
240 Event.Type.SHOW_NEXT_ACTIVE_TEST:
241 lambda event: self.show_next_active_test(),
242 Event.Type.RESTART_TESTS:
243 lambda event: self.restart_tests(root=test_or_root(event)),
244 Event.Type.AUTO_RUN:
245 lambda event: self.auto_run(root=test_or_root(event)),
246 Event.Type.RE_RUN_FAILED:
247 lambda event: self.re_run_failed(root=test_or_root(event)),
248 Event.Type.RUN_TESTS_WITH_STATUS:
249 lambda event: self.run_tests_with_status(
250 event.status,
251 root=test_or_root(event)),
252 Event.Type.REVIEW:
253 lambda event: self.show_review_information(),
254 Event.Type.UPDATE_SYSTEM_INFO:
255 lambda event: self.update_system_info(),
256 Event.Type.STOP:
257 lambda event: self.stop(root=test_or_root(event, False),
258 fail=getattr(event, 'fail', False),
259 reason=getattr(event, 'reason', None)),
260 Event.Type.SET_VISIBLE_TEST:
261 lambda event: self.set_visible_test(
262 self.test_list.lookup_path(event.path)),
263 Event.Type.CLEAR_STATE:
264 lambda event: self.clear_state(
265 self.test_list.lookup_path(event.path)),
Wei-Ning Huang38b75f02015-02-25 18:25:14 +0800266 Event.Type.KEY_FILTER_MODE: self.handle_key_filter_mode,
Jon Salz0697cbf2012-07-04 15:14:04 +0800267 }
268
Jon Salz0697cbf2012-07-04 15:14:04 +0800269 self.web_socket_manager = None
Wei-Ning Huang38b75f02015-02-25 18:25:14 +0800270 self.terminal_manager = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800271
272 def destroy(self):
Ricky Liang74237a02014-09-18 15:11:23 +0800273 """Performs any shutdown tasks. Overrides base class method."""
Jon Salzd7550792013-07-12 05:49:27 +0800274 self.status = Status.TERMINATING
Jon Salz0697cbf2012-07-04 15:14:04 +0800275 if self.chrome:
276 self.chrome.kill()
277 self.chrome = None
Jon Salzc79a9982012-08-30 04:42:01 +0800278 if self.dummy_shopfloor:
279 self.dummy_shopfloor.kill()
280 self.dummy_shopfloor = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800281 if self.ui_process:
Hung-Te Lin4e6357c2016-01-08 14:32:00 +0800282 process_utils.KillProcessTree(self.ui_process, 'ui')
Jon Salz0697cbf2012-07-04 15:14:04 +0800283 self.ui_process = None
284 if self.web_socket_manager:
285 logging.info('Stopping web sockets')
286 self.web_socket_manager.close()
287 self.web_socket_manager = None
288 if self.state_server_thread:
289 logging.info('Stopping state server')
290 self.state_server.shutdown()
291 self.state_server_thread.join()
292 self.state_server.server_close()
293 self.state_server_thread = None
294 if self.state_instance:
295 self.state_instance.close()
296 if self.event_server_thread:
297 logging.info('Stopping event server')
298 self.event_server.shutdown() # pylint: disable=E1101
299 self.event_server_thread.join()
300 self.event_server.server_close()
301 self.event_server_thread = None
302 if self.log_watcher:
303 if self.log_watcher.IsThreadStarted():
304 self.log_watcher.StopWatchThread()
305 self.log_watcher = None
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +0800306 if self.system_log_manager:
307 if self.system_log_manager.IsThreadRunning():
Cheng-Yi Chianga0f6eff2014-01-09 18:27:22 +0800308 self.system_log_manager.Stop()
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +0800309 self.system_log_manager = None
Vic Yange2c76a82014-10-30 12:48:19 -0700310 if self.autotest_prespawner:
311 logging.info('Stopping autotest prespawner')
312 self.autotest_prespawner.stop()
313 self.autotest_prespawner = None
314 if self.pytest_prespawner:
315 logging.info('Stopping pytest prespawner')
316 self.pytest_prespawner.stop()
317 self.pytest_prespawner = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800318 if self.event_client:
319 logging.info('Closing event client')
320 self.event_client.close()
321 self.event_client = None
Jon Salzddf0d052013-06-18 12:52:44 +0800322 if self.cpufreq_manager:
323 self.cpufreq_manager.Stop()
Jon Salz0697cbf2012-07-04 15:14:04 +0800324 if self.event_log:
325 self.event_log.Close()
326 self.event_log = None
Chun-Ta Lin53cbbd52016-06-08 21:42:19 +0800327 if self.testlog:
328 self.testlog.Close()
329 self.testlog = None
Dean Liao592e4d52013-01-10 20:06:39 +0800330 if self.key_filter:
331 self.key_filter.Stop()
Vic Yangd8990da2013-06-27 16:57:43 +0800332 if self.cpu_usage_watcher:
333 self.cpu_usage_watcher.terminate()
Hung-Te Lin23cb7612016-01-19 19:19:32 +0800334 if self.thermal_watcher:
335 self.thermal_watcher.terminate()
Peter Ammon1e1ec572014-06-26 17:56:32 -0700336 if self.link_manager:
337 self.link_manager.Stop()
338 self.link_manager = None
Dean Liao592e4d52013-01-10 20:06:39 +0800339
Peter Ammon1e1ec572014-06-26 17:56:32 -0700340 super(Goofy, self).destroy()
Jon Salz0697cbf2012-07-04 15:14:04 +0800341 logging.info('Done destroying Goofy')
Jon Salzd7550792013-07-12 05:49:27 +0800342 self.status = Status.TERMINATED
Jon Salz0697cbf2012-07-04 15:14:04 +0800343
344 def start_state_server(self):
Jon Salz2af235d2013-06-24 14:47:21 +0800345 # Before starting state server, remount stateful partitions with
346 # no commit flag. The default commit time (commit=600) makes corruption
347 # too likely.
Hung-Te Lin1968d9c2016-01-08 22:55:46 +0800348 sys_utils.ResetCommitTime()
Jon Salz2af235d2013-06-24 14:47:21 +0800349
Jon Salz0697cbf2012-07-04 15:14:04 +0800350 self.state_instance, self.state_server = (
Ricky Liang45c73e72015-01-15 15:00:30 +0800351 state.create_server(bind_address='0.0.0.0'))
Jon Salz16d10542012-07-23 12:18:45 +0800352 self.goofy_rpc = GoofyRPC(self)
353 self.goofy_rpc.RegisterMethods(self.state_instance)
Jon Salz0697cbf2012-07-04 15:14:04 +0800354 logging.info('Starting state server')
355 self.state_server_thread = threading.Thread(
Ricky Liang45c73e72015-01-15 15:00:30 +0800356 target=self.state_server.serve_forever,
357 name='StateServer')
Jon Salz0697cbf2012-07-04 15:14:04 +0800358 self.state_server_thread.start()
359
360 def start_event_server(self):
361 self.event_server = EventServer()
362 logging.info('Starting factory event server')
363 self.event_server_thread = threading.Thread(
Ricky Liang45c73e72015-01-15 15:00:30 +0800364 target=self.event_server.serve_forever,
365 name='EventServer') # pylint: disable=E1101
Jon Salz0697cbf2012-07-04 15:14:04 +0800366 self.event_server_thread.start()
367
368 self.event_client = EventClient(
Ricky Liang45c73e72015-01-15 15:00:30 +0800369 callback=self.handle_event, event_loop=self.run_queue)
Jon Salz0697cbf2012-07-04 15:14:04 +0800370
371 self.web_socket_manager = WebSocketManager(self.uuid)
Ricky Liang45c73e72015-01-15 15:00:30 +0800372 self.state_server.add_handler('/event',
373 self.web_socket_manager.handle_web_socket)
Jon Salz0697cbf2012-07-04 15:14:04 +0800374
Wei-Ning Huang38b75f02015-02-25 18:25:14 +0800375 def start_terminal_server(self):
376 self.terminal_manager = TerminalManager()
377 self.state_server.add_handler('/pty',
378 self.terminal_manager.handle_web_socket)
379
Jon Salz0697cbf2012-07-04 15:14:04 +0800380 def start_ui(self):
381 ui_proc_args = [
Wei-Han Chen2ebb92d2016-01-12 14:51:41 +0800382 os.path.join(paths.FACTORY_PACKAGE_PATH, 'test', 'ui.py'),
Ricky Liang45c73e72015-01-15 15:00:30 +0800383 self.options.test_list
384 ]
Jon Salz0697cbf2012-07-04 15:14:04 +0800385 if self.options.verbose:
386 ui_proc_args.append('-v')
387 logging.info('Starting ui %s', ui_proc_args)
Hung-Te Lin4e6357c2016-01-08 14:32:00 +0800388 self.ui_process = process_utils.Spawn(ui_proc_args)
Jon Salz0697cbf2012-07-04 15:14:04 +0800389 logging.info('Waiting for UI to come up...')
390 self.event_client.wait(
Ricky Liang45c73e72015-01-15 15:00:30 +0800391 lambda event: event.type == Event.Type.UI_READY)
Jon Salz0697cbf2012-07-04 15:14:04 +0800392 logging.info('UI has started')
393
394 def set_visible_test(self, test):
395 if self.visible_test == test:
396 return
Jon Salz2f2d42c2012-07-30 12:30:34 +0800397 if test and not test.has_ui:
398 return
Jon Salz0697cbf2012-07-04 15:14:04 +0800399
400 if test:
401 test.update_state(visible=True)
402 if self.visible_test:
403 self.visible_test.update_state(visible=False)
404 self.visible_test = test
405
Ricky Liang48e47f92014-02-26 19:31:51 +0800406 def log_startup_messages(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800407 """Logs the tail of var/log/messages and mosys and EC console logs."""
Jon Salzd4306c82012-11-30 15:16:36 +0800408 # TODO(jsalz): This is mostly a copy-and-paste of code in init_states,
409 # for factory-3004.B only. Consolidate and merge back to ToT.
Hung-Te Linf5f2d7f2016-01-08 17:12:46 +0800410 if sys_utils.InChroot():
Jon Salzd4306c82012-11-30 15:16:36 +0800411 return
412
413 try:
Hung-Te Lin1a4e30c2016-01-08 23:25:10 +0800414 var_log_messages = sys_utils.GetVarLogMessagesBeforeReboot()
Jon Salzd4306c82012-11-30 15:16:36 +0800415 logging.info(
Ricky Liang45c73e72015-01-15 15:00:30 +0800416 'Tail of /var/log/messages before last reboot:\n'
417 '%s', ('\n'.join(
418 ' ' + x for x in var_log_messages)))
Jon Salzd4306c82012-11-30 15:16:36 +0800419 except: # pylint: disable=W0702
420 logging.exception('Unable to grok /var/log/messages')
421
422 try:
Hung-Te Lin4e6357c2016-01-08 14:32:00 +0800423 mosys_log = process_utils.Spawn(
Jon Salzd4306c82012-11-30 15:16:36 +0800424 ['mosys', 'eventlog', 'list'],
425 read_stdout=True, log_stderr_on_error=True).stdout_data
426 logging.info('System eventlog from mosys:\n%s\n', mosys_log)
427 except: # pylint: disable=W0702
428 logging.exception('Unable to read mosys eventlog')
429
Dean Liao88b93192014-10-23 19:37:41 +0800430 self.log_ec_console()
431 self.log_ec_panic_info()
432
433 @staticmethod
434 def log_ec_console():
435 """Logs EC console log into logging.info.
436
437 It logs an error message in logging.exception if an exception is raised
438 when getting EC console log.
439 For unsupported device, it logs unsupport message in logging.info
440
441 Returns:
442 EC console log string.
443 """
Jon Salzd4306c82012-11-30 15:16:36 +0800444 try:
Hung-Te Linb6287242016-05-18 14:39:05 +0800445 ec_console_log = device_utils.CreateDUTInterface().ec.GetECConsoleLog()
Jon Salzd4306c82012-11-30 15:16:36 +0800446 logging.info('EC console log after reboot:\n%s\n', ec_console_log)
Dean Liao88b93192014-10-23 19:37:41 +0800447 return ec_console_log
448 except NotImplementedError:
449 logging.info('EC console log not supported')
Jon Salzd4306c82012-11-30 15:16:36 +0800450 except: # pylint: disable=W0702
451 logging.exception('Error retrieving EC console log')
452
Dean Liao88b93192014-10-23 19:37:41 +0800453 @staticmethod
454 def log_ec_panic_info():
455 """Logs EC panic info into logging.info.
456
457 It logs an error message in logging.exception if an exception is raised
458 when getting EC panic info.
459 For unsupported device, it logs unsupport message in logging.info
460
461 Returns:
462 EC panic info string.
463 """
Vic Yang079f9872013-07-01 11:32:00 +0800464 try:
Hung-Te Linb6287242016-05-18 14:39:05 +0800465 ec_panic_info = device_utils.CreateDUTInterface().ec.GetECPanicInfo()
Vic Yang079f9872013-07-01 11:32:00 +0800466 logging.info('EC panic info after reboot:\n%s\n', ec_panic_info)
Dean Liao88b93192014-10-23 19:37:41 +0800467 return ec_panic_info
468 except NotImplementedError:
469 logging.info('EC panic info is not supported')
Vic Yang079f9872013-07-01 11:32:00 +0800470 except: # pylint: disable=W0702
471 logging.exception('Error retrieving EC panic info')
472
Ricky Liang48e47f92014-02-26 19:31:51 +0800473 def shutdown(self, operation):
474 """Starts shutdown procedure.
475
476 Args:
Vic (Chun-Ju) Yang05b0d952014-04-28 17:39:09 +0800477 operation: The shutdown operation (reboot, full_reboot, or halt).
Ricky Liang48e47f92014-02-26 19:31:51 +0800478 """
479 active_tests = []
480 for test in self.test_list.walk():
481 if not test.is_leaf():
482 continue
483
484 test_state = test.get_state()
485 if test_state.status == TestState.ACTIVE:
486 active_tests.append(test)
487
Ricky Liang48e47f92014-02-26 19:31:51 +0800488 if not (len(active_tests) == 1 and
489 isinstance(active_tests[0], factory.ShutdownStep)):
490 logging.error(
491 'Calling Goofy shutdown outside of the shutdown factory test')
492 return
493
494 logging.info('Start Goofy shutdown (%s)', operation)
495 # Save pending test list in the state server
496 self.state_instance.set_shared_data(
497 'tests_after_shutdown',
498 [t.path for t in self.tests_to_run])
499 # Save shutdown time
500 self.state_instance.set_shared_data('shutdown_time', time.time())
501
502 with self.env.lock:
503 self.event_log.Log('shutdown', operation=operation)
504 shutdown_result = self.env.shutdown(operation)
505 if shutdown_result:
506 # That's all, folks!
Peter Ammon1e1ec572014-06-26 17:56:32 -0700507 self.run_enqueue(None)
Ricky Liang48e47f92014-02-26 19:31:51 +0800508 else:
509 # Just pass (e.g., in the chroot).
510 self.state_instance.set_shared_data('tests_after_shutdown', None)
511 # Send event with no fields to indicate that there is no
512 # longer a pending shutdown.
513 self.event_client.post_event(Event(Event.Type.PENDING_SHUTDOWN))
514
515 def handle_shutdown_complete(self, test):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800516 """Handles the case where a shutdown was detected during a shutdown step.
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800517
Ricky Liang6fe218c2013-12-27 15:17:17 +0800518 Args:
519 test: The ShutdownStep.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800520 """
Jon Salz0697cbf2012-07-04 15:14:04 +0800521 test_state = test.update_state(increment_shutdown_count=1)
522 logging.info('Detected shutdown (%d of %d)',
Ricky Liang48e47f92014-02-26 19:31:51 +0800523 test_state.shutdown_count, test.iterations)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800524
Ricky Liang48e47f92014-02-26 19:31:51 +0800525 # Insert current shutdown test at the front of the list of tests to run
526 # after shutdown. This is to continue on post-shutdown verification in the
527 # shutdown step.
528 tests_after_shutdown = self.state_instance.get_shared_data(
529 'tests_after_shutdown', optional=True)
530 if not tests_after_shutdown:
531 self.state_instance.set_shared_data('tests_after_shutdown', [test.path])
532 elif isinstance(tests_after_shutdown, list):
533 self.state_instance.set_shared_data(
534 'tests_after_shutdown', [test.path] + tests_after_shutdown)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800535
Ricky Liang48e47f92014-02-26 19:31:51 +0800536 # Set 'post_shutdown' to inform shutdown test that a shutdown just occurred.
Ricky Liangb7eb8772014-09-15 18:05:22 +0800537 self.state_instance.set_shared_data(
538 state.POST_SHUTDOWN_TAG % test.path,
539 self.state_instance.get_test_state(test.path).invocation)
Jon Salz258a40c2012-04-19 12:34:01 +0800540
Jon Salz0697cbf2012-07-04 15:14:04 +0800541 def init_states(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800542 """Initializes all states on startup."""
Jon Salz0697cbf2012-07-04 15:14:04 +0800543 for test in self.test_list.get_all_tests():
544 # Make sure the state server knows about all the tests,
545 # defaulting to an untested state.
546 test.update_state(update_parent=False, visible=False)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800547
Jon Salz0697cbf2012-07-04 15:14:04 +0800548 var_log_messages = None
Vic Yanga9c32212012-08-16 20:07:54 +0800549 mosys_log = None
Vic Yange4c275d2012-08-28 01:50:20 +0800550 ec_console_log = None
Vic Yang079f9872013-07-01 11:32:00 +0800551 ec_panic_info = None
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800552
Jon Salz0697cbf2012-07-04 15:14:04 +0800553 # Any 'active' tests should be marked as failed now.
554 for test in self.test_list.walk():
Jon Salza6711d72012-07-18 14:33:03 +0800555 if not test.is_leaf():
556 # Don't bother with parents; they will be updated when their
557 # children are updated.
558 continue
559
Jon Salz0697cbf2012-07-04 15:14:04 +0800560 test_state = test.get_state()
561 if test_state.status != TestState.ACTIVE:
562 continue
563 if isinstance(test, factory.ShutdownStep):
564 # Shutdown while the test was active - that's good.
Ricky Liang48e47f92014-02-26 19:31:51 +0800565 self.handle_shutdown_complete(test)
Jon Salz0697cbf2012-07-04 15:14:04 +0800566 else:
567 # Unexpected shutdown. Grab /var/log/messages for context.
568 if var_log_messages is None:
569 try:
570 var_log_messages = (
Hung-Te Lin1a4e30c2016-01-08 23:25:10 +0800571 sys_utils.GetVarLogMessagesBeforeReboot())
Jon Salz0697cbf2012-07-04 15:14:04 +0800572 # Write it to the log, to make it easier to
573 # correlate with /var/log/messages.
574 logging.info(
Ricky Liang45c73e72015-01-15 15:00:30 +0800575 'Unexpected shutdown. '
576 'Tail of /var/log/messages before last reboot:\n'
577 '%s', ('\n'.join(
578 ' ' + x for x in var_log_messages)))
Jon Salz0697cbf2012-07-04 15:14:04 +0800579 except: # pylint: disable=W0702
580 logging.exception('Unable to grok /var/log/messages')
581 var_log_messages = []
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800582
Hung-Te Linf5f2d7f2016-01-08 17:12:46 +0800583 if mosys_log is None and not sys_utils.InChroot():
Jon Salz008f4ea2012-08-28 05:39:45 +0800584 try:
Hung-Te Lin4e6357c2016-01-08 14:32:00 +0800585 mosys_log = process_utils.Spawn(
Jon Salz008f4ea2012-08-28 05:39:45 +0800586 ['mosys', 'eventlog', 'list'],
587 read_stdout=True, log_stderr_on_error=True).stdout_data
588 # Write it to the log also.
589 logging.info('System eventlog from mosys:\n%s\n', mosys_log)
590 except: # pylint: disable=W0702
591 logging.exception('Unable to read mosys eventlog')
Vic Yanga9c32212012-08-16 20:07:54 +0800592
Vic Yange4c275d2012-08-28 01:50:20 +0800593 if ec_console_log is None:
Dean Liao88b93192014-10-23 19:37:41 +0800594 ec_console_log = self.log_ec_console()
Vic Yange4c275d2012-08-28 01:50:20 +0800595
Vic Yang079f9872013-07-01 11:32:00 +0800596 if ec_panic_info is None:
Dean Liao88b93192014-10-23 19:37:41 +0800597 ec_panic_info = self.log_ec_panic_info()
Vic Yang079f9872013-07-01 11:32:00 +0800598
Jon Salz0697cbf2012-07-04 15:14:04 +0800599 error_msg = 'Unexpected shutdown while test was running'
Chun-Ta Lin53cbbd52016-06-08 21:42:19 +0800600 # TODO(itspeter): Add testlog to collect expired session infos.
Jon Salz0697cbf2012-07-04 15:14:04 +0800601 self.event_log.Log('end_test',
Ricky Liang45c73e72015-01-15 15:00:30 +0800602 path=test.path,
603 status=TestState.FAILED,
604 invocation=test.get_state().invocation,
605 error_msg=error_msg,
606 var_log_messages='\n'.join(var_log_messages),
607 mosys_log=mosys_log)
Jon Salz0697cbf2012-07-04 15:14:04 +0800608 test.update_state(
Ricky Liang45c73e72015-01-15 15:00:30 +0800609 status=TestState.FAILED,
610 error_msg=error_msg)
Chun-Ta Lin87c2dac2015-05-02 01:35:01 -0700611 # Trigger the OnTestFailure callback.
Claire Changd1961a22015-08-05 16:15:55 +0800612 self.run_queue.put(lambda: self.test_fail(test))
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800613
Jon Salz50efe942012-07-26 11:54:10 +0800614 if not test.never_fails:
615 # For "never_fails" tests (such as "Start"), don't cancel
616 # pending tests, since reboot is expected.
617 factory.console.info('Unexpected shutdown while test %s '
618 'running; cancelling any pending tests',
619 test.path)
620 self.state_instance.set_shared_data('tests_after_shutdown', [])
Jon Salz69806bb2012-07-20 18:05:02 +0800621
Jon Salz008f4ea2012-08-28 05:39:45 +0800622 self.update_skipped_tests()
623
624 def update_skipped_tests(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800625 """Updates skipped states based on run_if."""
Jon Salz885dcac2013-07-23 16:39:50 +0800626 env = TestArgEnv()
Ricky Liang45c73e72015-01-15 15:00:30 +0800627
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800628 def _evaluate_skip_from_run_if(test):
629 """Returns the run_if evaluation of the test.
630
631 Args:
632 test: A FactoryTest object.
633
634 Returns:
635 The run_if evaluation result. Returns False if the test has no
636 run_if argument.
637 """
638 value = None
639 if test.run_if_expr:
640 try:
641 value = test.run_if_expr(env)
642 except: # pylint: disable=W0702
643 logging.exception('Unable to evaluate run_if expression for %s',
644 test.path)
645 # But keep going; we have no choice. This will end up
646 # always activating the test.
647 elif test.run_if_table_name:
648 try:
649 aux = shopfloor.get_selected_aux_data(test.run_if_table_name)
650 value = aux.get(test.run_if_col)
651 except ValueError:
652 # Not available; assume it shouldn't be skipped
653 pass
654
655 if value is None:
656 skip = False
657 else:
658 skip = (not value) ^ t.run_if_not
659 return skip
660
661 # Gets all run_if evaluation, and stores results in skip_map.
662 skip_map = dict()
Jon Salz008f4ea2012-08-28 05:39:45 +0800663 for t in self.test_list.walk():
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800664 skip_map[t.path] = _evaluate_skip_from_run_if(t)
Jon Salz885dcac2013-07-23 16:39:50 +0800665
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800666 # Propagates the skip value from root of tree and updates skip_map.
667 def _update_skip_map_from_node(test, skip_from_parent):
668 """Updates skip_map from a given node.
Jon Salz885dcac2013-07-23 16:39:50 +0800669
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800670 Given a FactoryTest node and the skip value from parent, updates the
671 skip value of current node in the skip_map if skip value from parent is
672 True. If this node has children, recursively propagate this value to all
673 its children, that is, all its subtests.
674 Note that this function only updates value in skip_map, not the actual
675 test_list tree.
Jon Salz008f4ea2012-08-28 05:39:45 +0800676
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800677 Args:
678 test: The given FactoryTest object. It is a node in the test_list tree.
679 skip_from_parent: The skip value which propagates from the parent of
680 input node.
681 """
682 skip_this_tree = skip_from_parent or skip_map[test.path]
683 if skip_this_tree:
684 logging.info('Skip from node %r', test.path)
685 skip_map[test.path] = True
686 if test.is_leaf():
687 return
688 # Propagates skip value to its subtests
689 for subtest in test.subtests:
690 _update_skip_map_from_node(subtest, skip_this_tree)
691
692 _update_skip_map_from_node(self.test_list, False)
693
694 # Updates the skip value from skip_map to test_list tree. Also, updates test
695 # status if needed.
696 for t in self.test_list.walk():
697 skip = skip_map[t.path]
698 test_state = t.get_state()
699 if ((not skip) and
700 (test_state.status == TestState.PASSED) and
701 (test_state.error_msg == TestState.SKIPPED_MSG)):
702 # It was marked as skipped before, but now we need to run it.
703 # Mark as untested.
704 t.update_state(skip=skip, status=TestState.UNTESTED, error_msg='')
705 else:
706 t.update_state(skip=skip)
Jon Salz008f4ea2012-08-28 05:39:45 +0800707
Jon Salz0697cbf2012-07-04 15:14:04 +0800708 def show_next_active_test(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800709 """Rotates to the next visible active test."""
Jon Salz0697cbf2012-07-04 15:14:04 +0800710 self.reap_completed_tests()
711 active_tests = [
Ricky Liang45c73e72015-01-15 15:00:30 +0800712 t for t in self.test_list.walk()
713 if t.is_leaf() and t.get_state().status == TestState.ACTIVE]
Jon Salz0697cbf2012-07-04 15:14:04 +0800714 if not active_tests:
715 return
Jon Salz4f6c7172012-06-11 20:45:36 +0800716
Jon Salz0697cbf2012-07-04 15:14:04 +0800717 try:
718 next_test = active_tests[
Ricky Liang45c73e72015-01-15 15:00:30 +0800719 (active_tests.index(self.visible_test) + 1) % len(active_tests)]
Jon Salz0697cbf2012-07-04 15:14:04 +0800720 except ValueError: # visible_test not present in active_tests
721 next_test = active_tests[0]
Jon Salz4f6c7172012-06-11 20:45:36 +0800722
Jon Salz0697cbf2012-07-04 15:14:04 +0800723 self.set_visible_test(next_test)
Jon Salz4f6c7172012-06-11 20:45:36 +0800724
Jon Salz0697cbf2012-07-04 15:14:04 +0800725 def handle_event(self, event):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800726 """Handles an event from the event server."""
Jon Salz0697cbf2012-07-04 15:14:04 +0800727 handler = self.event_handlers.get(event.type)
728 if handler:
729 handler(event)
730 else:
731 # We don't register handlers for all event types - just ignore
732 # this event.
733 logging.debug('Unbound event type %s', event.type)
Jon Salz4f6c7172012-06-11 20:45:36 +0800734
Vic Yangaabf9fd2013-04-09 18:56:13 +0800735 def check_critical_factory_note(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800736 """Returns True if the last factory note is critical."""
Vic Yangaabf9fd2013-04-09 18:56:13 +0800737 notes = self.state_instance.get_shared_data('factory_note', True)
738 return notes and notes[-1]['level'] == 'CRITICAL'
739
Hung-Te Linef7f2be2015-07-20 20:38:51 +0800740 def schedule_restart(self):
741 """Schedules a restart event when any invocation is completed."""
742 self.is_restart_requested = True
743
744 def invocation_completion(self):
745 """Callback when an invocation is completed."""
746 if self.is_restart_requested:
747 logging.info('Restart by scheduled event.')
748 self.is_restart_requested = False
749 self.restart_tests()
750 else:
751 self.run_next_test()
752
Jon Salz0697cbf2012-07-04 15:14:04 +0800753 def run_next_test(self):
henryhsu4cc6b022014-04-22 17:12:42 +0800754 """Runs the next eligible test (or tests) in self.tests_to_run.
755
756 We have three kinds of the next eligible test:
757 1. normal
758 2. backgroundable
759 3. force_background
760
761 And we have four situations of the ongoing invocations:
762 a. only a running normal test
763 b. all running tests are backgroundable
764 c. all running tests are force_background
765 d. all running tests are any combination of backgroundable and
766 force_background
767
768 When a test would like to be run, it must follow the rules:
769 [1] cannot run with [abd]
770 [2] cannot run with [a]
771 All the other combinations are allowed
772 """
Jon Salz0697cbf2012-07-04 15:14:04 +0800773 self.reap_completed_tests()
Vic Yangaabf9fd2013-04-09 18:56:13 +0800774 if self.tests_to_run and self.check_critical_factory_note():
775 self.tests_to_run.clear()
776 return
Jon Salz0697cbf2012-07-04 15:14:04 +0800777 while self.tests_to_run:
Ricky Liang6fe218c2013-12-27 15:17:17 +0800778 logging.debug('Tests to run: %s', [x.path for x in self.tests_to_run])
Jon Salz94eb56f2012-06-12 18:01:12 +0800779
Jon Salz0697cbf2012-07-04 15:14:04 +0800780 test = self.tests_to_run[0]
Jon Salz94eb56f2012-06-12 18:01:12 +0800781
Jon Salz0697cbf2012-07-04 15:14:04 +0800782 if test in self.invocations:
783 logging.info('Next test %s is already running', test.path)
784 self.tests_to_run.popleft()
785 return
Jon Salz94eb56f2012-06-12 18:01:12 +0800786
Jon Salza1412922012-07-23 16:04:17 +0800787 for requirement in test.require_run:
788 for i in requirement.test.walk():
789 if i.get_state().status == TestState.ACTIVE:
Jon Salz304a75d2012-07-06 11:14:15 +0800790 logging.info('Waiting for active test %s to complete '
Jon Salza1412922012-07-23 16:04:17 +0800791 'before running %s', i.path, test.path)
Jon Salz304a75d2012-07-06 11:14:15 +0800792 return
793
henryhsu4cc6b022014-04-22 17:12:42 +0800794 def is_normal_test(test):
795 return not (test.backgroundable or test.force_background)
796
797 # [1] cannot run with [abd].
798 if self.invocations and is_normal_test(test) and any(
799 [not x.force_background for x in self.invocations]):
800 logging.info('Waiting for non-force_background tests to '
801 'complete before running %s', test.path)
802 return
803
804 # [2] cannot run with [a].
805 if self.invocations and test.backgroundable and any(
806 [is_normal_test(x) for x in self.invocations]):
807 logging.info('Waiting for normal tests to '
808 'complete before running %s', test.path)
Jon Salz0697cbf2012-07-04 15:14:04 +0800809 return
Jon Salz94eb56f2012-06-12 18:01:12 +0800810
Jon Salz3e6f5202012-10-15 15:08:29 +0800811 if test.get_state().skip:
812 factory.console.info('Skipping test %s', test.path)
813 test.update_state(status=TestState.PASSED,
814 error_msg=TestState.SKIPPED_MSG)
815 self.tests_to_run.popleft()
816 continue
817
Jon Salz0697cbf2012-07-04 15:14:04 +0800818 self.tests_to_run.popleft()
Jon Salz94eb56f2012-06-12 18:01:12 +0800819
Jon Salz304a75d2012-07-06 11:14:15 +0800820 untested = set()
Jon Salza1412922012-07-23 16:04:17 +0800821 for requirement in test.require_run:
822 for i in requirement.test.walk():
823 if i == test:
Jon Salz304a75d2012-07-06 11:14:15 +0800824 # We've hit this test itself; stop checking
825 break
Jon Salza1412922012-07-23 16:04:17 +0800826 if ((i.get_state().status == TestState.UNTESTED) or
827 (requirement.passed and i.get_state().status !=
828 TestState.PASSED)):
Jon Salz304a75d2012-07-06 11:14:15 +0800829 # Found an untested test; move on to the next
830 # element in require_run.
Jon Salza1412922012-07-23 16:04:17 +0800831 untested.add(i)
Jon Salz304a75d2012-07-06 11:14:15 +0800832 break
833
834 if untested:
835 untested_paths = ', '.join(sorted([x.path for x in untested]))
836 if self.state_instance.get_shared_data('engineering_mode',
837 optional=True):
838 # In engineering mode, we'll let it go.
839 factory.console.warn('In engineering mode; running '
840 '%s even though required tests '
841 '[%s] have not completed',
842 test.path, untested_paths)
843 else:
844 # Not in engineering mode; mark it failed.
845 error_msg = ('Required tests [%s] have not been run yet'
846 % untested_paths)
847 factory.console.error('Not running %s: %s',
848 test.path, error_msg)
849 test.update_state(status=TestState.FAILED,
850 error_msg=error_msg)
851 continue
852
Ricky Liang48e47f92014-02-26 19:31:51 +0800853 if (isinstance(test, factory.ShutdownStep) and
Ricky Liangb7eb8772014-09-15 18:05:22 +0800854 self.state_instance.get_shared_data(
855 state.POST_SHUTDOWN_TAG % test.path, optional=True)):
Ricky Liang48e47f92014-02-26 19:31:51 +0800856 # Invoking post shutdown method of shutdown test. We should retain the
857 # iterations_left and retries_left of the original test state.
858 test_state = self.state_instance.get_test_state(test.path)
859 self._run_test(test, test_state.iterations_left,
860 test_state.retries_left)
861 else:
862 # Starts a new test run; reset iterations and retries.
863 self._run_test(test, test.iterations, test.retries)
Jon Salz1acc8742012-07-17 17:45:55 +0800864
Cheng-Yi Chiangce05c002013-04-04 02:13:17 +0800865 def _run_test(self, test, iterations_left=None, retries_left=None):
Vic Yanga3cecf82014-12-26 00:44:21 -0800866 if not self._ui_initialized and not test.is_no_host():
867 self.init_ui()
Vic Yang08505c72015-01-06 17:01:53 -0800868 invoc = TestInvocation(
Hung-Te Linef7f2be2015-07-20 20:38:51 +0800869 self, test, on_completion=self.invocation_completion,
Claire Changd1961a22015-08-05 16:15:55 +0800870 on_test_failure=lambda: self.test_fail(test))
Jon Salz1acc8742012-07-17 17:45:55 +0800871 new_state = test.update_state(
Ricky Liang48e47f92014-02-26 19:31:51 +0800872 status=TestState.ACTIVE, increment_count=1, error_msg='',
873 invocation=invoc.uuid, iterations_left=iterations_left,
874 retries_left=retries_left,
875 visible=(self.visible_test == test))
Jon Salz1acc8742012-07-17 17:45:55 +0800876 invoc.count = new_state.count
877
878 self.invocations[test] = invoc
879 if self.visible_test is None and test.has_ui:
880 self.set_visible_test(test)
Vic Yang311ddb82012-09-26 12:08:28 +0800881 self.check_exclusive()
Jon Salz1acc8742012-07-17 17:45:55 +0800882 invoc.start()
Jon Salz5f2a0672012-05-22 17:14:06 +0800883
Vic Yang311ddb82012-09-26 12:08:28 +0800884 def check_exclusive(self):
Jon Salzce6a7f82013-06-10 18:22:54 +0800885 # alias since this is really long
886 EXCL_OPT = factory.FactoryTest.EXCLUSIVE_OPTIONS
887
Vic Yang311ddb82012-09-26 12:08:28 +0800888 current_exclusive_items = set([
Jon Salzce6a7f82013-06-10 18:22:54 +0800889 item for item in EXCL_OPT
Vic Yang311ddb82012-09-26 12:08:28 +0800890 if any([test.is_exclusive(item) for test in self.invocations])])
891
892 new_exclusive_items = current_exclusive_items - self.exclusive_items
Jon Salzce6a7f82013-06-10 18:22:54 +0800893 if EXCL_OPT.NETWORKING in new_exclusive_items:
Vic Yang311ddb82012-09-26 12:08:28 +0800894 logging.info('Disabling network')
895 self.connection_manager.DisableNetworking()
Jon Salzce6a7f82013-06-10 18:22:54 +0800896 if EXCL_OPT.CHARGER in new_exclusive_items:
Vic Yang311ddb82012-09-26 12:08:28 +0800897 logging.info('Stop controlling charger')
898
899 new_non_exclusive_items = self.exclusive_items - current_exclusive_items
Jon Salzce6a7f82013-06-10 18:22:54 +0800900 if EXCL_OPT.NETWORKING in new_non_exclusive_items:
Vic Yang311ddb82012-09-26 12:08:28 +0800901 logging.info('Re-enabling network')
902 self.connection_manager.EnableNetworking()
Jon Salzce6a7f82013-06-10 18:22:54 +0800903 if EXCL_OPT.CHARGER in new_non_exclusive_items:
Vic Yang311ddb82012-09-26 12:08:28 +0800904 logging.info('Start controlling charger')
905
Jon Salzce6a7f82013-06-10 18:22:54 +0800906 if self.cpufreq_manager:
907 enabled = EXCL_OPT.CPUFREQ not in current_exclusive_items
908 try:
909 self.cpufreq_manager.SetEnabled(enabled)
910 except: # pylint: disable=W0702
911 logging.exception('Unable to %s cpufreq services',
912 'enable' if enabled else 'disable')
913
Ricky Liang0f9978e2015-01-30 08:19:17 +0000914 # Only adjust charge state if not excluded
915 if (EXCL_OPT.CHARGER not in current_exclusive_items and
Hung-Te Linf5f2d7f2016-01-08 17:12:46 +0800916 not sys_utils.InChroot()):
Ricky Liang0f9978e2015-01-30 08:19:17 +0000917 if self.charge_manager:
Cheng-Yi Chiangd8186952013-04-04 23:41:14 +0800918 self.charge_manager.AdjustChargeState()
Vic Yang311ddb82012-09-26 12:08:28 +0800919
920 self.exclusive_items = current_exclusive_items
Jon Salz5da61e62012-05-31 13:06:22 +0800921
Dean Liao88b93192014-10-23 19:37:41 +0800922 def charge(self):
923 """Charges the board.
924
925 It won't try again if last time SetChargeState raised an exception.
926 """
927 if not self._can_charge:
928 return
929
930 try:
Ricky Liang9ac35e02015-01-30 16:01:32 +0800931 if self.charge_manager:
932 self.charge_manager.StartCharging()
933 else:
Hung-Te Lin6a72c642015-12-13 22:09:09 +0800934 self.dut.power.SetChargeState(self.dut.power.ChargeState.CHARGE)
Dean Liao88b93192014-10-23 19:37:41 +0800935 except NotImplementedError:
936 logging.info('Charging is not supported')
937 self._can_charge = False
Hung-Te Linb6287242016-05-18 14:39:05 +0800938 except DeviceException:
Dean Liao88b93192014-10-23 19:37:41 +0800939 logging.exception('Unable to set charge state on this board')
940 self._can_charge = False
941
cychiang21886742012-07-05 15:16:32 +0800942 def check_for_updates(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800943 """Schedules an asynchronous check for updates if necessary."""
cychiang21886742012-07-05 15:16:32 +0800944 if not self.test_list.options.update_period_secs:
945 # Not enabled.
946 return
947
948 now = time.time()
949 if self.last_update_check and (
950 now - self.last_update_check <
951 self.test_list.options.update_period_secs):
952 # Not yet time for another check.
953 return
954
955 self.last_update_check = now
956
957 def handle_check_for_update(reached_shopfloor, md5sum, needs_update):
958 if reached_shopfloor:
959 new_update_md5sum = md5sum if needs_update else None
Hung-Te Line594e5d2015-12-16 02:36:05 +0800960 if self.dut.info.update_md5sum != new_update_md5sum:
cychiang21886742012-07-05 15:16:32 +0800961 logging.info('Received new update MD5SUM: %s', new_update_md5sum)
Hung-Te Line594e5d2015-12-16 02:36:05 +0800962 self.dut.info.Overrides('update_md5sum', new_update_md5sum)
Peter Ammon1e1ec572014-06-26 17:56:32 -0700963 self.run_enqueue(self.update_system_info)
Cheng-Yi Chiang194d3c02015-03-16 14:37:15 +0800964 else:
965 if not self._suppress_periodic_update_messages:
966 logging.warning('Suppress error messages for periodic update checking'
967 ' after the first one.')
968 self._suppress_periodic_update_messages = True
cychiang21886742012-07-05 15:16:32 +0800969
970 updater.CheckForUpdateAsync(
Ricky Liang45c73e72015-01-15 15:00:30 +0800971 handle_check_for_update,
Cheng-Yi Chiang194d3c02015-03-16 14:37:15 +0800972 self.test_list.options.shopfloor_timeout_secs,
973 self._suppress_periodic_update_messages)
cychiang21886742012-07-05 15:16:32 +0800974
Jon Salza6711d72012-07-18 14:33:03 +0800975 def cancel_pending_tests(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800976 """Cancels any tests in the run queue."""
Jon Salza6711d72012-07-18 14:33:03 +0800977 self.run_tests([])
978
Ricky Liang4bff3e32014-02-20 18:46:11 +0800979 def restore_active_run_state(self):
980 """Restores active run id and the list of scheduled tests."""
981 self.run_id = self.state_instance.get_shared_data('run_id', optional=True)
982 self.scheduled_run_tests = self.state_instance.get_shared_data(
983 'scheduled_run_tests', optional=True)
984
985 def set_active_run_state(self):
986 """Sets active run id and the list of scheduled tests."""
987 self.run_id = str(uuid.uuid4())
988 self.scheduled_run_tests = [test.path for test in self.tests_to_run]
989 self.state_instance.set_shared_data('run_id', self.run_id)
990 self.state_instance.set_shared_data('scheduled_run_tests',
991 self.scheduled_run_tests)
992
Chih-Yu Huang85dc63c2015-08-12 15:21:28 +0800993 def run_tests(self, subtrees, status_filter=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800994 """Runs tests under subtree.
Jon Salz258a40c2012-04-19 12:34:01 +0800995
Jon Salz0697cbf2012-07-04 15:14:04 +0800996 The tests are run in order unless one fails (then stops).
997 Backgroundable tests are run simultaneously; when a foreground test is
998 encountered, we wait for all active tests to finish before continuing.
Jon Salzb1b39092012-05-03 02:05:09 +0800999
Ricky Liang6fe218c2013-12-27 15:17:17 +08001000 Args:
1001 subtrees: Node or nodes containing tests to run (may either be
1002 a single test or a list). Duplicates will be ignored.
Chih-Yu Huang85dc63c2015-08-12 15:21:28 +08001003 status_filter: List of available test states. Only run the tests which
1004 states are in the list. Set to None if all test states are available.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001005 """
Hung-Te Lin410f70a2015-12-15 14:53:42 +08001006 self.dut.hooks.OnTestStart()
Vic Yang08505c72015-01-06 17:01:53 -08001007
Jon Salz0697cbf2012-07-04 15:14:04 +08001008 if type(subtrees) != list:
1009 subtrees = [subtrees]
Jon Salz258a40c2012-04-19 12:34:01 +08001010
Jon Salz0697cbf2012-07-04 15:14:04 +08001011 # Nodes we've seen so far, to avoid duplicates.
1012 seen = set()
Jon Salz94eb56f2012-06-12 18:01:12 +08001013
Jon Salz0697cbf2012-07-04 15:14:04 +08001014 self.tests_to_run = deque()
1015 for subtree in subtrees:
1016 for test in subtree.walk():
1017 if test in seen:
1018 continue
1019 seen.add(test)
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001020
Jon Salz0697cbf2012-07-04 15:14:04 +08001021 if not test.is_leaf():
1022 continue
Chih-Yu Huang85dc63c2015-08-12 15:21:28 +08001023 if (status_filter is not None and
1024 test.get_state().status not in status_filter):
Jon Salz0697cbf2012-07-04 15:14:04 +08001025 continue
1026 self.tests_to_run.append(test)
Ricky Liang4bff3e32014-02-20 18:46:11 +08001027 if subtrees:
1028 self.set_active_run_state()
Jon Salz0697cbf2012-07-04 15:14:04 +08001029 self.run_next_test()
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001030
Jon Salz0697cbf2012-07-04 15:14:04 +08001031 def reap_completed_tests(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001032 """Removes completed tests from the set of active tests.
Jon Salz0697cbf2012-07-04 15:14:04 +08001033
1034 Also updates the visible test if it was reaped.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001035 """
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +08001036 test_completed = False
Jon Salz0697cbf2012-07-04 15:14:04 +08001037 for t, v in dict(self.invocations).iteritems():
1038 if v.is_completed():
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +08001039 test_completed = True
Jon Salz1acc8742012-07-17 17:45:55 +08001040 new_state = t.update_state(**v.update_state_on_completion)
Jon Salz0697cbf2012-07-04 15:14:04 +08001041 del self.invocations[t]
1042
Johny Lin62ed2a32015-05-13 11:57:12 +08001043 # Stop on failure if flag is true and there is no retry chances.
Chun-Ta Lin54e17e42012-09-06 22:05:13 +08001044 if (self.test_list.options.stop_on_failure and
Johny Lin62ed2a32015-05-13 11:57:12 +08001045 new_state.retries_left < 0 and
Chun-Ta Lin54e17e42012-09-06 22:05:13 +08001046 new_state.status == TestState.FAILED):
1047 # Clean all the tests to cause goofy to stop.
1048 self.tests_to_run = []
Ricky Liang45c73e72015-01-15 15:00:30 +08001049 factory.console.info('Stop on failure triggered. Empty the queue.')
Chun-Ta Lin54e17e42012-09-06 22:05:13 +08001050
Jon Salz1acc8742012-07-17 17:45:55 +08001051 if new_state.iterations_left and new_state.status == TestState.PASSED:
1052 # Play it again, Sam!
1053 self._run_test(t)
Cheng-Yi Chiangce05c002013-04-04 02:13:17 +08001054 # new_state.retries_left is obtained after update.
1055 # For retries_left == 0, test can still be run for the last time.
1056 elif (new_state.retries_left >= 0 and
1057 new_state.status == TestState.FAILED):
1058 # Still have to retry, Sam!
1059 self._run_test(t)
Jon Salz1acc8742012-07-17 17:45:55 +08001060
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +08001061 if test_completed:
Vic Yangf01c59f2013-04-19 17:37:56 +08001062 self.log_watcher.KickWatchThread()
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +08001063
Jon Salz0697cbf2012-07-04 15:14:04 +08001064 if (self.visible_test is None or
Jon Salz85a39882012-07-05 16:45:04 +08001065 self.visible_test not in self.invocations):
Jon Salz0697cbf2012-07-04 15:14:04 +08001066 self.set_visible_test(None)
1067 # Make the first running test, if any, the visible test
1068 for t in self.test_list.walk():
1069 if t in self.invocations:
1070 self.set_visible_test(t)
1071 break
1072
Jon Salz6dc031d2013-06-19 13:06:23 +08001073 def kill_active_tests(self, abort, root=None, reason=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001074 """Kills and waits for all active tests.
Jon Salz0697cbf2012-07-04 15:14:04 +08001075
Jon Salz85a39882012-07-05 16:45:04 +08001076 Args:
1077 abort: True to change state of killed tests to FAILED, False for
Jon Salz0697cbf2012-07-04 15:14:04 +08001078 UNTESTED.
Jon Salz85a39882012-07-05 16:45:04 +08001079 root: If set, only kills tests with root as an ancestor.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001080 reason: If set, the abort reason.
1081 """
Jon Salz0697cbf2012-07-04 15:14:04 +08001082 self.reap_completed_tests()
1083 for test, invoc in self.invocations.items():
Jon Salz85a39882012-07-05 16:45:04 +08001084 if root and not test.has_ancestor(root):
1085 continue
1086
Ricky Liang45c73e72015-01-15 15:00:30 +08001087 factory.console.info('Killing active test %s...', test.path)
Jon Salz6dc031d2013-06-19 13:06:23 +08001088 invoc.abort_and_join(reason)
Ricky Liang45c73e72015-01-15 15:00:30 +08001089 factory.console.info('Killed %s', test.path)
Jon Salz1acc8742012-07-17 17:45:55 +08001090 test.update_state(**invoc.update_state_on_completion)
Jon Salz0697cbf2012-07-04 15:14:04 +08001091 del self.invocations[test]
Jon Salz1acc8742012-07-17 17:45:55 +08001092
Jon Salz0697cbf2012-07-04 15:14:04 +08001093 if not abort:
1094 test.update_state(status=TestState.UNTESTED)
1095 self.reap_completed_tests()
1096
Jon Salz6dc031d2013-06-19 13:06:23 +08001097 def stop(self, root=None, fail=False, reason=None):
1098 self.kill_active_tests(fail, root, reason)
Jon Salz85a39882012-07-05 16:45:04 +08001099 # Remove any tests in the run queue under the root.
1100 self.tests_to_run = deque([x for x in self.tests_to_run
1101 if root and not x.has_ancestor(root)])
1102 self.run_next_test()
Jon Salz0697cbf2012-07-04 15:14:04 +08001103
Jon Salz4712ac72013-02-07 17:12:05 +08001104 def clear_state(self, root=None):
Jon Salzd7550792013-07-12 05:49:27 +08001105 if root is None:
1106 root = self.test_list
Jon Salz6dc031d2013-06-19 13:06:23 +08001107 self.stop(root, reason='Clearing test state')
Jon Salz4712ac72013-02-07 17:12:05 +08001108 for f in root.walk():
1109 if f.is_leaf():
1110 f.update_state(status=TestState.UNTESTED)
1111
Jon Salz6dc031d2013-06-19 13:06:23 +08001112 def abort_active_tests(self, reason=None):
1113 self.kill_active_tests(True, reason=reason)
Jon Salz0697cbf2012-07-04 15:14:04 +08001114
1115 def main(self):
Jon Salzeff94182013-06-19 15:06:28 +08001116 syslog.openlog('goofy')
1117
Jon Salz0697cbf2012-07-04 15:14:04 +08001118 try:
Jon Salzd7550792013-07-12 05:49:27 +08001119 self.status = Status.INITIALIZING
Jon Salz0697cbf2012-07-04 15:14:04 +08001120 self.init()
1121 self.event_log.Log('goofy_init',
Ricky Liang45c73e72015-01-15 15:00:30 +08001122 success=True)
Chun-Ta Lin53cbbd52016-06-08 21:42:19 +08001123 testlog.Log(
Joel Kitching9eb203a2016-04-21 15:36:30 +08001124 testlog.StationInit({
Chun-Ta Lin53cbbd52016-06-08 21:42:19 +08001125 'stationDeviceId': testlog_goofy.GetDeviceID(),
Joel Kitching21bc69b2016-07-13 08:29:52 -07001126 'stationInstallationId': testlog_goofy.GetInstallationID(),
Chun-Ta Lin53cbbd52016-06-08 21:42:19 +08001127 'count': testlog_goofy.GetInitCount(),
Joel Kitching9eb203a2016-04-21 15:36:30 +08001128 'success': True}))
Jon Salz0697cbf2012-07-04 15:14:04 +08001129 except:
Joel Kitching9eb203a2016-04-21 15:36:30 +08001130 try:
1131 if self.event_log:
Jon Salz0697cbf2012-07-04 15:14:04 +08001132 self.event_log.Log('goofy_init',
Ricky Liang45c73e72015-01-15 15:00:30 +08001133 success=False,
1134 trace=traceback.format_exc())
Chun-Ta Lin53cbbd52016-06-08 21:42:19 +08001135 if self.testlog:
1136 testlog.Log(
Joel Kitching9eb203a2016-04-21 15:36:30 +08001137 testlog.StationInit({
Chun-Ta Lin53cbbd52016-06-08 21:42:19 +08001138 'stationDeviceId': testlog_goofy.GetDeviceID(),
Joel Kitching21bc69b2016-07-13 08:29:52 -07001139 'stationInstallationId': testlog_goofy.GetInstallationID(),
Chun-Ta Lin53cbbd52016-06-08 21:42:19 +08001140 'count': testlog_goofy.GetInitCount(),
Joel Kitching9eb203a2016-04-21 15:36:30 +08001141 'success': False,
1142 'failureMessage': traceback.format_exc()}))
1143 except: # pylint: disable=W0702
1144 pass
Jon Salz0697cbf2012-07-04 15:14:04 +08001145 raise
1146
Jon Salzd7550792013-07-12 05:49:27 +08001147 self.status = Status.RUNNING
Jon Salzeff94182013-06-19 15:06:28 +08001148 syslog.syslog('Goofy (factory test harness) starting')
Chun-Ta Lin5d12b592015-06-30 00:54:23 -07001149 syslog.syslog('Boot sequence = %d' % GetBootSequence())
Chun-Ta Lin53cbbd52016-06-08 21:42:19 +08001150 syslog.syslog('Goofy init count = %d' % testlog_goofy.GetInitCount())
Jon Salz0697cbf2012-07-04 15:14:04 +08001151 self.run()
1152
1153 def update_system_info(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001154 """Updates system info."""
Hung-Te Line594e5d2015-12-16 02:36:05 +08001155 info = self.dut.info.GetAll()
1156 self.state_instance.set_shared_data('system_info', info)
Jon Salz0697cbf2012-07-04 15:14:04 +08001157 self.event_client.post_event(Event(Event.Type.SYSTEM_INFO,
Hung-Te Line594e5d2015-12-16 02:36:05 +08001158 system_info=info))
1159 logging.info('System info: %r', info)
Jon Salz0697cbf2012-07-04 15:14:04 +08001160
Jon Salzeb42f0d2012-07-27 19:14:04 +08001161 def update_factory(self, auto_run_on_restart=False, post_update_hook=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001162 """Commences updating factory software.
Jon Salzeb42f0d2012-07-27 19:14:04 +08001163
1164 Args:
1165 auto_run_on_restart: Auto-run when the machine comes back up.
1166 post_update_hook: Code to call after update but immediately before
1167 restart.
1168
1169 Returns:
1170 Never if the update was successful (we just reboot).
1171 False if the update was unnecessary (no update available).
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001172 """
Jon Salz6dc031d2013-06-19 13:06:23 +08001173 self.kill_active_tests(False, reason='Factory software update')
Jon Salza6711d72012-07-18 14:33:03 +08001174 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +08001175
Jon Salz5c344f62012-07-13 14:31:16 +08001176 def pre_update_hook():
1177 if auto_run_on_restart:
1178 self.state_instance.set_shared_data('tests_after_shutdown',
1179 FORCE_AUTO_RUN)
1180 self.state_instance.close()
1181
Jon Salzeb42f0d2012-07-27 19:14:04 +08001182 if updater.TryUpdate(pre_update_hook=pre_update_hook):
1183 if post_update_hook:
1184 post_update_hook()
1185 self.env.shutdown('reboot')
Jon Salz0697cbf2012-07-04 15:14:04 +08001186
Ricky Liang8fecf412014-05-22 10:56:14 +08001187 def handle_sigint(self, dummy_signum, dummy_frame): # pylint: disable=W0613
Jon Salz77c151e2012-08-28 07:20:37 +08001188 logging.error('Received SIGINT')
Peter Ammon1e1ec572014-06-26 17:56:32 -07001189 self.run_enqueue(None)
Jon Salz77c151e2012-08-28 07:20:37 +08001190 raise KeyboardInterrupt()
1191
Ricky Liang8fecf412014-05-22 10:56:14 +08001192 def handle_sigterm(self, dummy_signum, dummy_frame): # pylint: disable=W0613
1193 logging.error('Received SIGTERM')
Hung-Te Lin94ca4742014-07-09 20:13:50 +08001194 self.env.terminate()
1195 self.run_queue.put(None)
Ricky Liang8fecf412014-05-22 10:56:14 +08001196 raise RuntimeError('Received SIGTERM')
1197
Jon Salze12c2b32013-06-25 16:24:34 +08001198 def find_kcrashes(self):
1199 """Finds kcrash files, logs them, and marks them as seen."""
1200 seen_crashes = set(
1201 self.state_instance.get_shared_data('seen_crashes', optional=True)
1202 or [])
1203
1204 for path in glob.glob('/var/spool/crash/*'):
1205 if not os.path.isfile(path):
1206 continue
1207 if path in seen_crashes:
1208 continue
1209 try:
1210 stat = os.stat(path)
Hung-Te Lin4e6357c2016-01-08 14:32:00 +08001211 mtime = time_utils.TimeString(stat.st_mtime)
Jon Salze12c2b32013-06-25 16:24:34 +08001212 logging.info(
1213 'Found new crash file %s (%d bytes at %s)',
1214 path, stat.st_size, mtime)
1215 extra_log_args = {}
1216
1217 try:
1218 _, ext = os.path.splitext(path)
1219 if ext in ['.kcrash', '.meta']:
1220 ext = ext.replace('.', '')
1221 with open(path) as f:
1222 data = f.read(MAX_CRASH_FILE_SIZE)
1223 tell = f.tell()
1224 logging.info(
1225 'Contents of %s%s:%s',
1226 path,
1227 ('' if tell == stat.st_size
1228 else '(truncated to %d bytes)' % MAX_CRASH_FILE_SIZE),
1229 ('\n' + data).replace('\n', '\n ' + ext + '> '))
1230 extra_log_args['data'] = data
1231
1232 # Copy to /var/factory/kcrash for posterity
Joel Kitching625ff0f2016-05-16 14:59:40 -07001233 kcrash_dir = paths.GetFactoryRoot('kcrash')
Hung-Te Lin4e6357c2016-01-08 14:32:00 +08001234 file_utils.TryMakeDirs(kcrash_dir)
Jon Salze12c2b32013-06-25 16:24:34 +08001235 shutil.copy(path, kcrash_dir)
1236 logging.info('Copied to %s',
1237 os.path.join(kcrash_dir, os.path.basename(path)))
1238 finally:
1239 # Even if something goes wrong with the above, still try to
1240 # log to event log
1241 self.event_log.Log('crash_file',
1242 path=path, size=stat.st_size, mtime=mtime,
1243 **extra_log_args)
1244 except: # pylint: disable=W0702
1245 logging.exception('Unable to handle crash files %s', path)
1246 seen_crashes.add(path)
1247
1248 self.state_instance.set_shared_data('seen_crashes', list(seen_crashes))
1249
Jon Salz128b0932013-07-03 16:55:26 +08001250 def GetTestList(self, test_list_id):
1251 """Returns the test list with the given ID.
1252
1253 Raises:
1254 TestListError: The test list ID is not valid.
1255 """
1256 try:
1257 return self.test_lists[test_list_id]
1258 except KeyError:
1259 raise test_lists.TestListError(
1260 '%r is not a valid test list ID (available IDs are [%s])' % (
1261 test_list_id, ', '.join(sorted(self.test_lists.keys()))))
1262
1263 def InitTestLists(self):
Joel Kitching50a63ea2016-02-22 13:15:09 +08001264 """Reads in all test lists and sets the active test list.
1265
1266 Returns:
1267 True if the active test list could be set, False if failed.
1268 """
1269 startup_errors = []
1270 self.test_lists, failed_files = test_lists.BuildAllTestLists(
Ricky Liang27051552014-05-04 14:22:26 +08001271 force_generic=(self.options.automation_mode is not None))
Jon Salzd7550792013-07-12 05:49:27 +08001272 logging.info('Loaded test lists: [%s]',
1273 test_lists.DescribeTestLists(self.test_lists))
Jon Salz128b0932013-07-03 16:55:26 +08001274
Joel Kitching50a63ea2016-02-22 13:15:09 +08001275 # Check for any syntax errors in test list files.
1276 if failed_files:
1277 logging.info('Failed test list files: [%s]',
1278 ' '.join(failed_files.keys()))
1279 for f, exc_info in failed_files.iteritems():
1280 logging.error('Error in test list file: %s', f,
1281 exc_info=exc_info)
1282
1283 # Limit the stack trace to the very last entry.
1284 exc_type, exc_value, exc_traceback = exc_info
1285 while exc_traceback and exc_traceback.tb_next:
1286 exc_traceback = exc_traceback.tb_next
1287
1288 exc_string = ''.join(
1289 traceback.format_exception(
1290 exc_type, exc_value, exc_traceback)).rstrip()
1291 startup_errors.append('Error in test list file (%s):\n%s'
1292 % (f, exc_string))
1293
Jon Salz128b0932013-07-03 16:55:26 +08001294 if not self.options.test_list:
1295 self.options.test_list = test_lists.GetActiveTestListId()
1296
Joel Kitching50a63ea2016-02-22 13:15:09 +08001297 # Check for a non-existent test list ID.
1298 try:
1299 if os.sep in self.options.test_list:
1300 # It's a path pointing to an old-style test list; use it.
1301 self.test_list = factory.read_test_list(self.options.test_list)
1302 else:
1303 self.test_list = self.GetTestList(self.options.test_list)
1304 logging.info('Active test list: %s', self.test_list.test_list_id)
1305 except test_lists.TestListError as e:
1306 logging.exception('Invalid active test list: %s',
1307 self.options.test_list)
1308 startup_errors.append(e.message)
Jon Salz128b0932013-07-03 16:55:26 +08001309
Joel Kitching50a63ea2016-02-22 13:15:09 +08001310 # We may have failed loading the active test list.
1311 if self.test_list:
1312 if isinstance(self.test_list, test_lists.OldStyleTestList):
1313 # Actually load it in. (See OldStyleTestList for an explanation
1314 # of why this is necessary.)
1315 self.test_list = self.test_list.Load()
Jon Salz128b0932013-07-03 16:55:26 +08001316
Joel Kitching50a63ea2016-02-22 13:15:09 +08001317 self.test_list.state_instance = self.state_instance
Jon Salz128b0932013-07-03 16:55:26 +08001318
Joel Kitching50a63ea2016-02-22 13:15:09 +08001319 # Prepare DUT link.
1320 if self.test_list.options.dut_options:
1321 logging.info('dut_options set by %s: %r', self.test_list.test_list_id,
1322 self.test_list.options.dut_options)
Hung-Te Linb6287242016-05-18 14:39:05 +08001323 device_utils.PrepareDUTLink(**self.test_list.options.dut_options)
Wei-Han Chene8a025f2016-01-14 16:42:02 +08001324
Joel Kitching50a63ea2016-02-22 13:15:09 +08001325 # Show all startup errors.
1326 if startup_errors:
1327 self.state_instance.set_shared_data(
1328 'startup_error', '\n\n'.join(startup_errors))
1329
1330 # Only return False if failed to load the active test list.
1331 return bool(self.test_list)
Jon Salz128b0932013-07-03 16:55:26 +08001332
Shuo-Peng Liao268b40b2013-07-01 15:58:59 +08001333 def init_hooks(self):
1334 """Initializes hooks.
1335
1336 Must run after self.test_list ready.
1337 """
Shuo-Peng Liao52b90da2013-06-30 17:00:06 +08001338 module, cls = self.test_list.options.hooks_class.rsplit('.', 1)
1339 self.hooks = getattr(__import__(module, fromlist=[cls]), cls)()
1340 assert isinstance(self.hooks, factory.Hooks), (
Ricky Liang45c73e72015-01-15 15:00:30 +08001341 'hooks should be of type Hooks but is %r' % type(self.hooks))
Shuo-Peng Liao52b90da2013-06-30 17:00:06 +08001342 self.hooks.test_list = self.test_list
Shuo-Peng Liao268b40b2013-07-01 15:58:59 +08001343 self.hooks.OnCreatedTestList()
Shuo-Peng Liao52b90da2013-06-30 17:00:06 +08001344
Vic Yanga3cecf82014-12-26 00:44:21 -08001345 def init_ui(self):
1346 """Initialize UI."""
1347 self._ui_initialized = True
1348 if self.options.ui == 'chrome':
Hung-Te Lin8f6a3782015-01-06 22:58:32 +08001349 if self.options.monolithic:
Hung-Te Lin7bd55312014-12-30 16:43:36 +08001350 self.env.launch_chrome()
1351 else:
1352 # The presenter is responsible for launching Chrome. Let's just
1353 # wait here.
1354 self.env.controller_ready_for_ui()
Vic Yanga3cecf82014-12-26 00:44:21 -08001355 logging.info('Waiting for a web socket connection')
1356 self.web_socket_manager.wait()
1357
1358 # Wait for the test widget size to be set; this is done in
1359 # an asynchronous RPC so there is a small chance that the
1360 # web socket might be opened first.
1361 for _ in range(100): # 10 s
1362 try:
1363 if self.state_instance.get_shared_data('test_widget_size'):
1364 break
1365 except KeyError:
1366 pass # Retry
1367 time.sleep(0.1) # 100 ms
1368 else:
1369 logging.warn('Never received test_widget_size from UI')
1370
Jon Salz0697cbf2012-07-04 15:14:04 +08001371 def init(self, args=None, env=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001372 """Initializes Goofy.
Jon Salz0697cbf2012-07-04 15:14:04 +08001373
1374 Args:
1375 args: A list of command-line arguments. Uses sys.argv if
1376 args is None.
1377 env: An Environment instance to use (or None to choose
1378 FakeChrootEnvironment or DUTEnvironment as appropriate).
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001379 """
Jon Salz0697cbf2012-07-04 15:14:04 +08001380 parser = OptionParser()
1381 parser.add_option('-v', '--verbose', dest='verbose',
Jon Salz8fa8e832012-07-13 19:04:09 +08001382 action='store_true',
1383 help='Enable debug logging')
Jon Salz0697cbf2012-07-04 15:14:04 +08001384 parser.add_option('--print_test_list', dest='print_test_list',
Jon Salz8fa8e832012-07-13 19:04:09 +08001385 metavar='FILE',
1386 help='Read and print test list FILE, and exit')
Jon Salz0697cbf2012-07-04 15:14:04 +08001387 parser.add_option('--restart', dest='restart',
Jon Salz8fa8e832012-07-13 19:04:09 +08001388 action='store_true',
1389 help='Clear all test state')
Jon Salz0697cbf2012-07-04 15:14:04 +08001390 parser.add_option('--ui', dest='ui', type='choice',
Jon Salz7b5482e2014-08-04 17:48:41 +08001391 choices=['none', 'chrome'],
Jon Salz2f881df2013-02-01 17:00:35 +08001392 default='chrome',
Jon Salz8fa8e832012-07-13 19:04:09 +08001393 help='UI to use')
Jon Salz0697cbf2012-07-04 15:14:04 +08001394 parser.add_option('--ui_scale_factor', dest='ui_scale_factor',
Jon Salz8fa8e832012-07-13 19:04:09 +08001395 type='int', default=1,
1396 help=('Factor by which to scale UI '
1397 '(Chrome UI only)'))
Jon Salz0697cbf2012-07-04 15:14:04 +08001398 parser.add_option('--test_list', dest='test_list',
Jon Salz8fa8e832012-07-13 19:04:09 +08001399 metavar='FILE',
1400 help='Use FILE as test list')
Jon Salzc79a9982012-08-30 04:42:01 +08001401 parser.add_option('--dummy_shopfloor', action='store_true',
1402 help='Use a dummy shopfloor server')
Hung-Te Lincc41d2a2014-10-29 13:35:20 +08001403 parser.add_option('--dummy_connection_manager', action='store_true',
1404 help='Use a dummy connection manager')
Ricky Liang6fe218c2013-12-27 15:17:17 +08001405 parser.add_option('--automation-mode',
1406 choices=[m.lower() for m in AutomationMode],
Ricky Liang45c73e72015-01-15 15:00:30 +08001407 default='none', help='Factory test automation mode.')
Ricky Liang117484a2014-04-14 11:14:41 +08001408 parser.add_option('--no-auto-run-on-start', dest='auto_run_on_start',
1409 action='store_false', default=True,
1410 help=('do not automatically run the test list on goofy '
1411 'start; this is only valid when factory test '
1412 'automation is enabled'))
Chun-Ta Lina8dd3172014-11-26 16:15:13 +08001413 parser.add_option('--handshake_timeout', dest='handshake_timeout',
1414 type='float', default=0.3,
1415 help=('RPC timeout when doing handshake between device '
1416 'and presenter.'))
Vic Yang7d693c42014-09-14 09:52:39 +08001417 parser.add_option('--standalone', dest='standalone',
1418 action='store_true', default=False,
1419 help=('Assume the presenter is running on the same '
1420 'machines.'))
Hung-Te Lin8f6a3782015-01-06 22:58:32 +08001421 parser.add_option('--monolithic', dest='monolithic',
1422 action='store_true', default=False,
1423 help='Run in monolithic mode (without presenter)')
Jon Salz0697cbf2012-07-04 15:14:04 +08001424 (self.options, self.args) = parser.parse_args(args)
1425
Hung-Te Lina846f602014-07-04 20:32:22 +08001426 signal.signal(signal.SIGINT, self.handle_sigint)
1427 # TODO(hungte) SIGTERM does not work properly without Telemetry and should
1428 # be fixed.
Hung-Te Lina846f602014-07-04 20:32:22 +08001429
Jon Salz46b89562012-07-05 11:49:22 +08001430 # Make sure factory directories exist.
Joel Kitching625ff0f2016-05-16 14:59:40 -07001431 paths.GetLogRoot()
1432 paths.GetStateRoot()
1433 paths.GetTestDataRoot()
Jon Salz46b89562012-07-05 11:49:22 +08001434
Jon Salz0697cbf2012-07-04 15:14:04 +08001435 global _inited_logging # pylint: disable=W0603
1436 if not _inited_logging:
1437 factory.init_logging('goofy', verbose=self.options.verbose)
1438 _inited_logging = True
Jon Salz8fa8e832012-07-13 19:04:09 +08001439
Jon Salz0f996602012-10-03 15:26:48 +08001440 if self.options.print_test_list:
Joel Kitchingb85ed7f2014-10-08 18:24:39 +08001441 print(factory.read_test_list(
1442 self.options.print_test_list).__repr__(recursive=True))
Jon Salz0f996602012-10-03 15:26:48 +08001443 sys.exit(0)
1444
Jon Salzee85d522012-07-17 14:34:46 +08001445 event_log.IncrementBootSequence()
Chun-Ta Lin53cbbd52016-06-08 21:42:19 +08001446 testlog_goofy.IncrementInitCount()
1447
Jon Salzd15bbcf2013-05-21 17:33:57 +08001448 # Don't defer logging the initial event, so we can make sure
1449 # that device_id, reimage_id, etc. are all set up.
1450 self.event_log = EventLog('goofy', defer=False)
Chun-Ta Lin53cbbd52016-06-08 21:42:19 +08001451 self.testlog = testlog.Testlog(
1452 log_root=paths.GetLogRoot(), uuid=self.uuid)
1453 # Direct the logging calls to testlog as well.
1454 testlog.CapturePythonLogging(
1455 callback=self.testlog.primary_json.Log,
1456 level=logging.getLogger().getEffectiveLevel())
Jon Salz0697cbf2012-07-04 15:14:04 +08001457
Jon Salz0697cbf2012-07-04 15:14:04 +08001458 if env:
1459 self.env = env
Hung-Te Linf5f2d7f2016-01-08 17:12:46 +08001460 elif sys_utils.InChroot():
Jon Salz0697cbf2012-07-04 15:14:04 +08001461 self.env = test_environment.FakeChrootEnvironment()
1462 logging.warn(
Ricky Liang45c73e72015-01-15 15:00:30 +08001463 'Using chroot environment: will not actually run autotests')
Hung-Te Lina846f602014-07-04 20:32:22 +08001464 elif self.options.ui == 'chrome':
Ricky Liang09d66d82014-09-25 11:20:54 +08001465 self.env = test_environment.DUTEnvironment()
Jon Salz0697cbf2012-07-04 15:14:04 +08001466 self.env.goofy = self
Vic Yanga4931152014-08-11 16:36:24 -07001467 # web_socket_manager will be initialized later
1468 # pylint: disable=W0108
1469 self.env.has_sockets = lambda: self.web_socket_manager.has_sockets()
Jon Salz0697cbf2012-07-04 15:14:04 +08001470
1471 if self.options.restart:
1472 state.clear_state()
1473
Hung-Te Linf5f2d7f2016-01-08 17:12:46 +08001474 if self.options.ui_scale_factor != 1 and sys_utils.InQEMU():
Jon Salz0697cbf2012-07-04 15:14:04 +08001475 logging.warn(
Ricky Liang45c73e72015-01-15 15:00:30 +08001476 'In QEMU; ignoring ui_scale_factor argument')
Jon Salz0697cbf2012-07-04 15:14:04 +08001477 self.options.ui_scale_factor = 1
1478
1479 logging.info('Started')
1480
Hung-Te Lin8f6a3782015-01-06 22:58:32 +08001481 if not self.options.monolithic:
Hung-Te Lin7bd55312014-12-30 16:43:36 +08001482 self.link_manager = PresenterLinkManager(
1483 check_interval=1,
1484 handshake_timeout=self.options.handshake_timeout,
1485 standalone=self.options.standalone)
Peter Ammon1e1ec572014-06-26 17:56:32 -07001486
Jon Salz0697cbf2012-07-04 15:14:04 +08001487 self.start_state_server()
1488 self.state_instance.set_shared_data('hwid_cfg', get_hwid_cfg())
1489 self.state_instance.set_shared_data('ui_scale_factor',
Ricky Liang09216dc2013-02-22 17:26:45 +08001490 self.options.ui_scale_factor)
Jon Salz0697cbf2012-07-04 15:14:04 +08001491 self.last_shutdown_time = (
Ricky Liang45c73e72015-01-15 15:00:30 +08001492 self.state_instance.get_shared_data('shutdown_time', optional=True))
Jon Salz0697cbf2012-07-04 15:14:04 +08001493 self.state_instance.del_shared_data('shutdown_time', optional=True)
Jon Salzb19ea072013-02-07 16:35:00 +08001494 self.state_instance.del_shared_data('startup_error', optional=True)
Jon Salz0697cbf2012-07-04 15:14:04 +08001495
Ricky Liang6fe218c2013-12-27 15:17:17 +08001496 self.options.automation_mode = ParseAutomationMode(
1497 self.options.automation_mode)
1498 self.state_instance.set_shared_data('automation_mode',
1499 self.options.automation_mode)
1500 self.state_instance.set_shared_data(
1501 'automation_mode_prompt',
1502 AutomationModePrompt[self.options.automation_mode])
1503
Joel Kitching50a63ea2016-02-22 13:15:09 +08001504 success = False
1505 exc_info = None
Jon Salz128b0932013-07-03 16:55:26 +08001506 try:
Joel Kitching50a63ea2016-02-22 13:15:09 +08001507 success = self.InitTestLists()
Jon Salz128b0932013-07-03 16:55:26 +08001508 except: # pylint: disable=W0702
Joel Kitching50a63ea2016-02-22 13:15:09 +08001509 exc_info = sys.exc_info()
1510
1511 if not success:
1512 if exc_info:
1513 logging.exception('Unable to initialize test lists')
1514 self.state_instance.set_shared_data(
1515 'startup_error',
1516 'Unable to initialize test lists\n%s' % (
1517 traceback.format_exc()))
Jon Salzb19ea072013-02-07 16:35:00 +08001518 if self.options.ui == 'chrome':
1519 # Create an empty test list with default options so that the rest of
1520 # startup can proceed.
1521 self.test_list = factory.FactoryTestList(
1522 [], self.state_instance, factory.Options())
1523 else:
1524 # Bail with an error; no point in starting up.
1525 sys.exit('No valid test list; exiting.')
1526
Shuo-Peng Liao268b40b2013-07-01 15:58:59 +08001527 self.init_hooks()
1528
Jon Salz822838b2013-03-25 17:32:33 +08001529 if self.test_list.options.clear_state_on_start:
1530 self.state_instance.clear_test_state()
1531
Jon Salz670ce062014-05-16 15:53:50 +08001532 # If the phase is invalid, this will raise a ValueError.
1533 phase.SetPersistentPhase(self.test_list.options.phase)
1534
Dean Liao85ca86f2014-11-03 12:28:08 +08001535 # For netboot firmware, mainfw_type should be 'netboot'.
Hung-Te Line594e5d2015-12-16 02:36:05 +08001536 if (self.dut.info.mainfw_type != 'nonchrome' and
1537 self.dut.info.firmware_version is None):
Ricky Liang45c73e72015-01-15 15:00:30 +08001538 self.state_instance.set_shared_data(
1539 'startup_error',
Vic Yang9bd4f772013-06-04 17:34:00 +08001540 'Netboot firmware detected\n'
1541 'Connect Ethernet and reboot to re-image.\n'
1542 u'侦测到网路开机固件\n'
1543 u'请连接乙太网并重启')
1544
Jon Salz0697cbf2012-07-04 15:14:04 +08001545 if not self.state_instance.has_shared_data('ui_lang'):
1546 self.state_instance.set_shared_data('ui_lang',
Ricky Liang45c73e72015-01-15 15:00:30 +08001547 self.test_list.options.ui_lang)
Jon Salz0697cbf2012-07-04 15:14:04 +08001548 self.state_instance.set_shared_data(
Ricky Liang45c73e72015-01-15 15:00:30 +08001549 'test_list_options',
1550 self.test_list.options.__dict__)
Jon Salz0697cbf2012-07-04 15:14:04 +08001551 self.state_instance.test_list = self.test_list
1552
Cheng-Yi Chiang39d32ad2013-07-23 15:02:38 +08001553 self.check_log_rotation()
Jon Salz83ef34b2012-11-01 19:46:35 +08001554
Jon Salz23926422012-09-01 03:38:13 +08001555 if self.options.dummy_shopfloor:
Ricky Liang45c73e72015-01-15 15:00:30 +08001556 os.environ[shopfloor.SHOPFLOOR_SERVER_ENV_VAR_NAME] = (
1557 'http://%s:%d/' %
Joel Kitchingb85ed7f2014-10-08 18:24:39 +08001558 (net_utils.LOCALHOST, shopfloor.DEFAULT_SERVER_PORT))
Hung-Te Lin4e6357c2016-01-08 14:32:00 +08001559 self.dummy_shopfloor = process_utils.Spawn(
Wei-Han Chen2ebb92d2016-01-12 14:51:41 +08001560 [os.path.join(paths.FACTORY_PATH, 'bin', 'shopfloor_server'),
Jon Salz23926422012-09-01 03:38:13 +08001561 '--dummy'])
1562 elif self.test_list.options.shopfloor_server_url:
1563 shopfloor.set_server_url(self.test_list.options.shopfloor_server_url)
Jon Salz2bf2f6b2013-03-28 18:49:26 +08001564 shopfloor.set_enabled(True)
Jon Salz23926422012-09-01 03:38:13 +08001565
Hung-Te Linf5f2d7f2016-01-08 17:12:46 +08001566 if self.test_list.options.time_sanitizer and not sys_utils.InChroot():
Jon Salz8fa8e832012-07-13 19:04:09 +08001567 self.time_sanitizer = time_sanitizer.TimeSanitizer(
Ricky Liang45c73e72015-01-15 15:00:30 +08001568 base_time=time_sanitizer.GetBaseTimeFromFile(
1569 # lsb-factory is written by the factory install shim during
1570 # installation, so it should have a good time obtained from
1571 # the mini-Omaha server. If it's not available, we'll use
1572 # /etc/lsb-factory (which will be much older, but reasonably
1573 # sane) and rely on a shopfloor sync to set a more accurate
1574 # time.
1575 '/usr/local/etc/lsb-factory',
1576 '/etc/lsb-release'))
Jon Salz8fa8e832012-07-13 19:04:09 +08001577 self.time_sanitizer.RunOnce()
1578
Vic Yangd8990da2013-06-27 16:57:43 +08001579 if self.test_list.options.check_cpu_usage_period_secs:
Hung-Te Lin4e6357c2016-01-08 14:32:00 +08001580 self.cpu_usage_watcher = process_utils.Spawn(
Ricky Liang45c73e72015-01-15 15:00:30 +08001581 ['py/tools/cpu_usage_monitor.py', '-p',
1582 str(self.test_list.options.check_cpu_usage_period_secs)],
Wei-Han Chen2ebb92d2016-01-12 14:51:41 +08001583 cwd=paths.FACTORY_PATH)
Vic Yangd8990da2013-06-27 16:57:43 +08001584
Chun-Ta Lin5d12b592015-06-30 00:54:23 -07001585 # Enable thermal monitor
1586 if self.test_list.options.thermal_monitor_period_secs > 0:
Hung-Te Lin23cb7612016-01-19 19:19:32 +08001587 self.thermal_watcher = process_utils.Spawn(
Chun-Ta Lin5d12b592015-06-30 00:54:23 -07001588 ['py/tools/thermal_monitor.py',
1589 '-p', str(self.test_list.options.thermal_monitor_period_secs),
1590 '-d', str(self.test_list.options.thermal_monitor_delta)],
Wei-Han Chen2ebb92d2016-01-12 14:51:41 +08001591 cwd=paths.FACTORY_PATH)
Chun-Ta Lin5d12b592015-06-30 00:54:23 -07001592
Jon Salz0697cbf2012-07-04 15:14:04 +08001593 self.init_states()
1594 self.start_event_server()
Wei-Ning Huang38b75f02015-02-25 18:25:14 +08001595 self.start_terminal_server()
Hung-Te Lincc41d2a2014-10-29 13:35:20 +08001596
1597 if self.options.dummy_connection_manager:
1598 # Override network manager creation to dummy implmenetation.
1599 logging.info('Using dummy network manager (--dummy_connection_manager).')
1600 self.connection_manager = connection_manager.DummyConnectionManager()
1601 else:
1602 self.connection_manager = self.env.create_connection_manager(
1603 self.test_list.options.wlans,
Mao Huang4340c632015-04-14 14:35:22 +08001604 self.test_list.options.scan_wifi_period_secs,
1605 self.test_list.options.override_blacklisted_network_devices)
Hung-Te Lincc41d2a2014-10-29 13:35:20 +08001606
Jon Salz0697cbf2012-07-04 15:14:04 +08001607 # Note that we create a log watcher even if
1608 # sync_event_log_period_secs isn't set (no background
1609 # syncing), since we may use it to flush event logs as well.
1610 self.log_watcher = EventLogWatcher(
Ricky Liang45c73e72015-01-15 15:00:30 +08001611 self.test_list.options.sync_event_log_period_secs,
1612 event_log_db_file=None,
1613 handle_event_logs_callback=self.handle_event_logs)
Jon Salz0697cbf2012-07-04 15:14:04 +08001614 if self.test_list.options.sync_event_log_period_secs:
1615 self.log_watcher.StartWatchThread()
1616
Cheng-Yi Chianga0f6eff2014-01-09 18:27:22 +08001617 # Creates a system log manager to scan logs periocially.
1618 # A scan includes clearing logs and optionally syncing logs if
1619 # enable_syng_log is True. We kick it to sync logs.
1620 self.system_log_manager = SystemLogManager(
Ricky Liang45c73e72015-01-15 15:00:30 +08001621 sync_log_paths=self.test_list.options.sync_log_paths,
1622 sync_log_period_secs=self.test_list.options.sync_log_period_secs,
1623 scan_log_period_secs=self.test_list.options.scan_log_period_secs,
1624 clear_log_paths=self.test_list.options.clear_log_paths,
1625 clear_log_excluded_paths=self.test_list.options.clear_log_excluded_paths)
Cheng-Yi Chianga0f6eff2014-01-09 18:27:22 +08001626 self.system_log_manager.Start()
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +08001627
Jon Salz0697cbf2012-07-04 15:14:04 +08001628 self.update_system_info()
1629
Vic Yang4953fc12012-07-26 16:19:53 +08001630 assert ((self.test_list.options.min_charge_pct is None) ==
1631 (self.test_list.options.max_charge_pct is None))
Hung-Te Linf5f2d7f2016-01-08 17:12:46 +08001632 if sys_utils.InChroot():
Vic Yange83d9a12013-04-19 20:00:20 +08001633 logging.info('In chroot, ignoring charge manager and charge state')
Ricky Liangc392a1c2014-06-20 18:24:59 +08001634 elif (self.test_list.options.enable_charge_manager and
1635 self.test_list.options.min_charge_pct is not None):
Vic Yang4953fc12012-07-26 16:19:53 +08001636 self.charge_manager = ChargeManager(self.test_list.options.min_charge_pct,
1637 self.test_list.options.max_charge_pct)
Hung-Te Linc17b3d82015-12-15 15:26:08 +08001638 self.dut.status.Overrides('charge_manager', self.charge_manager)
Cheng-Yi Chiangd8186952013-04-04 23:41:14 +08001639 else:
1640 # Goofy should set charger state to charge if charge_manager is disabled.
Dean Liao88b93192014-10-23 19:37:41 +08001641 self.charge()
Vic Yang4953fc12012-07-26 16:19:53 +08001642
Vic Yang6cee2472014-10-22 17:18:52 -07001643 if CoreDumpManager.CoreDumpEnabled():
1644 self.core_dump_manager = CoreDumpManager(
1645 self.test_list.options.core_dump_watchlist)
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001646
Jon Salz0697cbf2012-07-04 15:14:04 +08001647 os.environ['CROS_FACTORY'] = '1'
1648 os.environ['CROS_DISABLE_SITE_SYSINFO'] = '1'
1649
Hung-Te Linf5f2d7f2016-01-08 17:12:46 +08001650 if not sys_utils.InChroot() and self.test_list.options.use_cpufreq_manager:
Ricky Liangecddbd42014-07-24 11:32:10 +08001651 logging.info('Enabling CPU frequency manager')
Jon Salzddf0d052013-06-18 12:52:44 +08001652 self.cpufreq_manager = CpufreqManager(event_log=self.event_log)
Jon Salzce6a7f82013-06-10 18:22:54 +08001653
Justin Chuang31b02432013-06-27 15:16:51 +08001654 # Startup hooks may want to skip some tests.
1655 self.update_skipped_tests()
Jon Salz416f9cc2013-05-10 18:32:50 +08001656
Jon Salze12c2b32013-06-25 16:24:34 +08001657 self.find_kcrashes()
1658
Shuo-Peng Liao268b40b2013-07-01 15:58:59 +08001659 # Should not move earlier.
1660 self.hooks.OnStartup()
1661
Ricky Liang36512a32014-07-25 11:47:04 +08001662 # Only after this point the Goofy backend is ready for UI connection.
1663 self.ready_for_ui_connection = True
1664
Ricky Liang650f6bf2012-09-28 13:22:54 +08001665 # Create download path for autotest beforehand or autotests run at
1666 # the same time might fail due to race condition.
Hung-Te Linf5f2d7f2016-01-08 17:12:46 +08001667 if not sys_utils.InChroot():
Hung-Te Lin4e6357c2016-01-08 14:32:00 +08001668 file_utils.TryMakeDirs(os.path.join('/usr/local/autotest', 'tests',
1669 'download'))
Ricky Liang650f6bf2012-09-28 13:22:54 +08001670
Jon Salz0697cbf2012-07-04 15:14:04 +08001671 def state_change_callback(test, test_state):
1672 self.event_client.post_event(
Ricky Liang4bff3e32014-02-20 18:46:11 +08001673 Event(Event.Type.STATE_CHANGE, path=test.path, state=test_state))
Jon Salz0697cbf2012-07-04 15:14:04 +08001674 self.test_list.state_change_callback = state_change_callback
Jon Salz73e0fd02012-04-04 11:46:38 +08001675
Vic Yange2c76a82014-10-30 12:48:19 -07001676 self.autotest_prespawner = prespawner.AutotestPrespawner()
1677 self.autotest_prespawner.start()
1678
1679 self.pytest_prespawner = prespawner.PytestPrespawner()
1680 self.pytest_prespawner.start()
Jon Salza6711d72012-07-18 14:33:03 +08001681
Ricky Liang48e47f92014-02-26 19:31:51 +08001682 tests_after_shutdown = self.state_instance.get_shared_data(
1683 'tests_after_shutdown', optional=True)
Jon Salz57717ca2012-04-04 16:47:25 +08001684
Jon Salz5c344f62012-07-13 14:31:16 +08001685 force_auto_run = (tests_after_shutdown == FORCE_AUTO_RUN)
1686 if not force_auto_run and tests_after_shutdown is not None:
Ricky Liang48e47f92014-02-26 19:31:51 +08001687 logging.info('Resuming tests after shutdown: %s', tests_after_shutdown)
Jon Salz0697cbf2012-07-04 15:14:04 +08001688 self.tests_to_run.extend(
Ricky Liang4bff3e32014-02-20 18:46:11 +08001689 self.test_list.lookup_path(t) for t in tests_after_shutdown)
Peter Ammon1e1ec572014-06-26 17:56:32 -07001690 self.run_enqueue(self.run_next_test)
Jon Salz0697cbf2012-07-04 15:14:04 +08001691 else:
Jon Salz5c344f62012-07-13 14:31:16 +08001692 if force_auto_run or self.test_list.options.auto_run_on_start:
Ricky Liang117484a2014-04-14 11:14:41 +08001693 # If automation mode is enabled, allow suppress auto_run_on_start.
1694 if (self.options.automation_mode == 'NONE' or
1695 self.options.auto_run_on_start):
Chih-Yu Huang85dc63c2015-08-12 15:21:28 +08001696 status_filter = [TestState.UNTESTED]
1697 if self.test_list.options.retry_failed_on_start:
1698 status_filter.append(TestState.FAILED)
1699 self.run_enqueue(lambda: self.run_tests(self.test_list, status_filter))
Jon Salz5c344f62012-07-13 14:31:16 +08001700 self.state_instance.set_shared_data('tests_after_shutdown', None)
Ricky Liang4bff3e32014-02-20 18:46:11 +08001701 self.restore_active_run_state()
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001702
Hung-Te Lin410f70a2015-12-15 14:53:42 +08001703 self.dut.hooks.OnTestStart()
Vic Yang08505c72015-01-06 17:01:53 -08001704
Dean Liao592e4d52013-01-10 20:06:39 +08001705 self.may_disable_cros_shortcut_keys()
1706
1707 def may_disable_cros_shortcut_keys(self):
1708 test_options = self.test_list.options
1709 if test_options.disable_cros_shortcut_keys:
1710 logging.info('Filter ChromeOS shortcut keys.')
1711 self.key_filter = KeyFilter(
1712 unmap_caps_lock=test_options.disable_caps_lock,
1713 caps_lock_keycode=test_options.caps_lock_keycode)
1714 self.key_filter.Start()
1715
Jon Salz0e6532d2012-10-25 16:30:11 +08001716 def _should_sync_time(self, foreground=False):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001717 """Returns True if we should attempt syncing time with shopfloor.
Jon Salz0e6532d2012-10-25 16:30:11 +08001718
1719 Args:
1720 foreground: If True, synchronizes even if background syncing
1721 is disabled (e.g., in explicit sync requests from the
1722 SyncShopfloor test).
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001723 """
Jon Salz0e6532d2012-10-25 16:30:11 +08001724 return ((foreground or
1725 self.test_list.options.sync_time_period_secs) and
Jon Salz54882d02012-08-31 01:57:54 +08001726 self.time_sanitizer and
1727 (not self.time_synced) and
Hung-Te Linf5f2d7f2016-01-08 17:12:46 +08001728 (not sys_utils.InChroot()))
Jon Salz54882d02012-08-31 01:57:54 +08001729
Jon Salz0e6532d2012-10-25 16:30:11 +08001730 def sync_time_with_shopfloor_server(self, foreground=False):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001731 """Syncs time with shopfloor server, if not yet synced.
Jon Salz54882d02012-08-31 01:57:54 +08001732
Jon Salz0e6532d2012-10-25 16:30:11 +08001733 Args:
1734 foreground: If True, synchronizes even if background syncing
1735 is disabled (e.g., in explicit sync requests from the
1736 SyncShopfloor test).
1737
Jon Salz54882d02012-08-31 01:57:54 +08001738 Returns:
1739 False if no time sanitizer is available, or True if this sync (or a
1740 previous sync) succeeded.
1741
1742 Raises:
1743 Exception if unable to contact the shopfloor server.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001744 """
Jon Salz0e6532d2012-10-25 16:30:11 +08001745 if self._should_sync_time(foreground):
Jon Salz54882d02012-08-31 01:57:54 +08001746 self.time_sanitizer.SyncWithShopfloor()
1747 self.time_synced = True
1748 return self.time_synced
1749
Jon Salzb92c5112012-09-21 15:40:11 +08001750 def log_disk_space_stats(self):
Hung-Te Linf5f2d7f2016-01-08 17:12:46 +08001751 if (sys_utils.InChroot() or
Jon Salz18e0e022013-06-11 17:13:39 +08001752 not self.test_list.options.log_disk_space_period_secs):
Jon Salzb92c5112012-09-21 15:40:11 +08001753 return
1754
1755 now = time.time()
1756 if (self.last_log_disk_space_time and
1757 now - self.last_log_disk_space_time <
1758 self.test_list.options.log_disk_space_period_secs):
1759 return
1760 self.last_log_disk_space_time = now
1761
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001762 # Upload event if stateful partition usage is above threshold.
1763 # Stateful partition is mounted on /usr/local, while
1764 # encrypted stateful partition is mounted on /var.
1765 # If there are too much logs in the factory process,
1766 # these two partitions might get full.
Jon Salzb92c5112012-09-21 15:40:11 +08001767 try:
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001768 vfs_infos = disk_space.GetAllVFSInfo()
1769 stateful_info, encrypted_info = None, None
1770 for vfs_info in vfs_infos.values():
1771 if '/usr/local' in vfs_info.mount_points:
1772 stateful_info = vfs_info
1773 if '/var' in vfs_info.mount_points:
1774 encrypted_info = vfs_info
1775
1776 stateful = disk_space.GetPartitionUsage(stateful_info)
1777 encrypted = disk_space.GetPartitionUsage(encrypted_info)
1778
Ricky Liang45c73e72015-01-15 15:00:30 +08001779 above_threshold = (
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001780 self.test_list.options.stateful_usage_threshold and
1781 max(stateful.bytes_used_pct,
1782 stateful.inodes_used_pct,
1783 encrypted.bytes_used_pct,
1784 encrypted.inodes_used_pct) >
Ricky Liang45c73e72015-01-15 15:00:30 +08001785 self.test_list.options.stateful_usage_threshold)
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001786
1787 if above_threshold:
1788 self.event_log.Log('stateful_partition_usage',
Ricky Liang45c73e72015-01-15 15:00:30 +08001789 partitions={
1790 'stateful': {
1791 'bytes_used_pct': FloatDigit(stateful.bytes_used_pct, 2),
1792 'inodes_used_pct': FloatDigit(stateful.inodes_used_pct, 2)},
1793 'encrypted_stateful': {
1794 'bytes_used_pct': FloatDigit(encrypted.bytes_used_pct, 2),
1795 'inodes_used_pct': FloatDigit(encrypted.inodes_used_pct, 2)}
1796 })
Cheng-Yi Chiang1b722322015-03-16 20:07:03 +08001797 self.log_watcher.KickWatchThread()
Hung-Te Linf5f2d7f2016-01-08 17:12:46 +08001798 if (not sys_utils.InChroot() and
Cheng-Yi Chiang00798e72013-06-20 18:16:39 +08001799 self.test_list.options.stateful_usage_above_threshold_action):
Hung-Te Lin4e6357c2016-01-08 14:32:00 +08001800 process_utils.Spawn(
1801 self.test_list.options.stateful_usage_above_threshold_action,
1802 call=True)
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001803
1804 message = disk_space.FormatSpaceUsedAll(vfs_infos)
Jon Salz3c493bb2013-02-07 17:24:58 +08001805 if message != self.last_log_disk_space_message:
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001806 if above_threshold:
1807 logging.warning(message)
1808 else:
1809 logging.info(message)
Jon Salz3c493bb2013-02-07 17:24:58 +08001810 self.last_log_disk_space_message = message
Jon Salzb92c5112012-09-21 15:40:11 +08001811 except: # pylint: disable=W0702
1812 logging.exception('Unable to get disk space used')
1813
Justin Chuang83813982013-05-13 01:26:32 +08001814 def check_battery(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001815 """Checks the current battery status.
Justin Chuang83813982013-05-13 01:26:32 +08001816
1817 Logs current battery charging level and status to log. If the battery level
1818 is lower below warning_low_battery_pct, send warning event to shopfloor.
1819 If the battery level is lower below critical_low_battery_pct, flush disks.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001820 """
Justin Chuang83813982013-05-13 01:26:32 +08001821 if not self.test_list.options.check_battery_period_secs:
1822 return
1823
1824 now = time.time()
1825 if (self.last_check_battery_time and
1826 now - self.last_check_battery_time <
1827 self.test_list.options.check_battery_period_secs):
1828 return
1829 self.last_check_battery_time = now
1830
1831 message = ''
1832 log_level = logging.INFO
1833 try:
Hung-Te Lin6a72c642015-12-13 22:09:09 +08001834 power = self.dut.power
Justin Chuang83813982013-05-13 01:26:32 +08001835 if not power.CheckBatteryPresent():
1836 message = 'Battery is not present'
1837 else:
1838 ac_present = power.CheckACPresent()
1839 charge_pct = power.GetChargePct(get_float=True)
1840 message = ('Current battery level %.1f%%, AC charger is %s' %
1841 (charge_pct, 'connected' if ac_present else 'disconnected'))
1842
1843 if charge_pct > self.test_list.options.critical_low_battery_pct:
1844 critical_low_battery = False
1845 else:
1846 critical_low_battery = True
1847 # Only sync disks when battery level is still above minimum
1848 # value. This can be used for offline analysis when shopfloor cannot
1849 # be connected.
1850 if charge_pct > MIN_BATTERY_LEVEL_FOR_DISK_SYNC:
1851 logging.warning('disk syncing for critical low battery situation')
1852 os.system('sync; sync; sync')
1853 else:
1854 logging.warning('disk syncing is cancelled '
1855 'because battery level is lower than %.1f',
1856 MIN_BATTERY_LEVEL_FOR_DISK_SYNC)
1857
1858 # Notify shopfloor server
1859 if (critical_low_battery or
1860 (not ac_present and
1861 charge_pct <= self.test_list.options.warning_low_battery_pct)):
1862 log_level = logging.WARNING
1863
1864 self.event_log.Log('low_battery',
1865 battery_level=charge_pct,
1866 charger_connected=ac_present,
1867 critical=critical_low_battery)
1868 self.log_watcher.KickWatchThread()
Cheng-Yi Chianga0f6eff2014-01-09 18:27:22 +08001869 if self.test_list.options.enable_sync_log:
1870 self.system_log_manager.KickToSync()
Ricky Liang45c73e72015-01-15 15:00:30 +08001871 except: # pylint: disable=W0702
Justin Chuang83813982013-05-13 01:26:32 +08001872 logging.exception('Unable to check battery or notify shopfloor')
1873 finally:
1874 if message != self.last_check_battery_message:
1875 logging.log(log_level, message)
1876 self.last_check_battery_message = message
1877
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001878 def check_core_dump(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001879 """Checks if there is any core dumped file.
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001880
1881 Removes unwanted core dump files immediately.
1882 Syncs those files matching watch list to server with a delay between
1883 each sync. After the files have been synced to server, deletes the files.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001884 """
Vic Yang6cee2472014-10-22 17:18:52 -07001885 if not self.core_dump_manager:
1886 return
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001887 core_dump_files = self.core_dump_manager.ScanFiles()
1888 if core_dump_files:
1889 now = time.time()
1890 if (self.last_kick_sync_time and now - self.last_kick_sync_time <
1891 self.test_list.options.kick_sync_min_interval_secs):
1892 return
1893 self.last_kick_sync_time = now
1894
1895 # Sends event to server
1896 self.event_log.Log('core_dumped', files=core_dump_files)
1897 self.log_watcher.KickWatchThread()
1898
1899 # Syncs files to server
Cheng-Yi Chianga0f6eff2014-01-09 18:27:22 +08001900 if self.test_list.options.enable_sync_log:
1901 self.system_log_manager.KickToSync(
Cheng-Yi Chiangd3516a32013-07-17 15:30:47 +08001902 core_dump_files, self.core_dump_manager.ClearFiles)
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001903
Cheng-Yi Chiang39d32ad2013-07-23 15:02:38 +08001904 def check_log_rotation(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001905 """Checks log rotation file presence/absence according to test_list option.
Cheng-Yi Chiang39d32ad2013-07-23 15:02:38 +08001906
1907 Touch /var/lib/cleanup_logs_paused if test_list.options.disable_log_rotation
1908 is True, delete it otherwise. This must be done in idle loop because
1909 autotest client will touch /var/lib/cleanup_logs_paused each time it runs
1910 an autotest.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001911 """
Hung-Te Linf5f2d7f2016-01-08 17:12:46 +08001912 if sys_utils.InChroot():
Cheng-Yi Chiang39d32ad2013-07-23 15:02:38 +08001913 return
1914 try:
1915 if self.test_list.options.disable_log_rotation:
1916 open(CLEANUP_LOGS_PAUSED, 'w').close()
1917 else:
1918 file_utils.TryUnlink(CLEANUP_LOGS_PAUSED)
1919 except: # pylint: disable=W0702
1920 # Oh well. Logs an error (but no trace)
1921 logging.info(
1922 'Unable to %s %s: %s',
1923 'touch' if self.test_list.options.disable_log_rotation else 'delete',
Hung-Te Linf707b242016-01-08 23:11:42 +08001924 CLEANUP_LOGS_PAUSED, debug_utils.FormatExceptionOnly())
Cheng-Yi Chiang39d32ad2013-07-23 15:02:38 +08001925
Jon Salz8fa8e832012-07-13 19:04:09 +08001926 def sync_time_in_background(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001927 """Writes out current time and tries to sync with shopfloor server."""
Jon Salzb22d1172012-08-06 10:38:57 +08001928 if not self.time_sanitizer:
1929 return
1930
1931 # Write out the current time.
1932 self.time_sanitizer.SaveTime()
1933
Jon Salz54882d02012-08-31 01:57:54 +08001934 if not self._should_sync_time():
Jon Salz8fa8e832012-07-13 19:04:09 +08001935 return
1936
1937 now = time.time()
1938 if self.last_sync_time and (
1939 now - self.last_sync_time <
1940 self.test_list.options.sync_time_period_secs):
1941 # Not yet time for another check.
1942 return
1943 self.last_sync_time = now
1944
1945 def target():
1946 try:
Jon Salz54882d02012-08-31 01:57:54 +08001947 self.sync_time_with_shopfloor_server()
Jon Salz8fa8e832012-07-13 19:04:09 +08001948 except: # pylint: disable=W0702
1949 # Oh well. Log an error (but no trace)
1950 logging.info(
Ricky Liang45c73e72015-01-15 15:00:30 +08001951 'Unable to get time from shopfloor server: %s',
Hung-Te Linf707b242016-01-08 23:11:42 +08001952 debug_utils.FormatExceptionOnly())
Jon Salz8fa8e832012-07-13 19:04:09 +08001953
1954 thread = threading.Thread(target=target)
1955 thread.daemon = True
1956 thread.start()
1957
Peter Ammon1e1ec572014-06-26 17:56:32 -07001958 def perform_periodic_tasks(self):
1959 """Override of base method to perform periodic work.
Vic Yang4953fc12012-07-26 16:19:53 +08001960
Peter Ammon1e1ec572014-06-26 17:56:32 -07001961 This method must not raise exceptions.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001962 """
Peter Ammon1e1ec572014-06-26 17:56:32 -07001963 super(Goofy, self).perform_periodic_tasks()
Jon Salzb22d1172012-08-06 10:38:57 +08001964
Vic Yang311ddb82012-09-26 12:08:28 +08001965 self.check_exclusive()
cychiang21886742012-07-05 15:16:32 +08001966 self.check_for_updates()
Jon Salz8fa8e832012-07-13 19:04:09 +08001967 self.sync_time_in_background()
Jon Salzb92c5112012-09-21 15:40:11 +08001968 self.log_disk_space_stats()
Justin Chuang83813982013-05-13 01:26:32 +08001969 self.check_battery()
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001970 self.check_core_dump()
Cheng-Yi Chiang39d32ad2013-07-23 15:02:38 +08001971 self.check_log_rotation()
Jon Salz57717ca2012-04-04 16:47:25 +08001972
Cheng-Yi Chiangf5b21012015-03-17 15:37:14 +08001973 def handle_event_logs(self, chunks, periodic=False):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001974 """Callback for event watcher.
Jon Salz258a40c2012-04-19 12:34:01 +08001975
Jon Salz0697cbf2012-07-04 15:14:04 +08001976 Attempts to upload the event logs to the shopfloor server.
Vic Yang93027612013-05-06 02:42:49 +08001977
1978 Args:
Jon Salzd15bbcf2013-05-21 17:33:57 +08001979 chunks: A list of Chunk objects.
Cheng-Yi Chiangf5b21012015-03-17 15:37:14 +08001980 periodic: This event log handling is periodic. Error messages
1981 will only be shown for the first time.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001982 """
Vic Yang93027612013-05-06 02:42:49 +08001983 first_exception = None
1984 exception_count = 0
Cheng-Yi Chiangf5b21012015-03-17 15:37:14 +08001985 # Suppress error messages for periodic event syncing except for the
1986 # first time. If event syncing is not periodic, always show the error
1987 # messages.
1988 quiet = self._suppress_event_log_error_messages if periodic else False
Vic Yang93027612013-05-06 02:42:49 +08001989
Jon Salzd15bbcf2013-05-21 17:33:57 +08001990 for chunk in chunks:
Vic Yang93027612013-05-06 02:42:49 +08001991 try:
Jon Salzcddb6402013-05-23 12:56:42 +08001992 description = 'event logs (%s)' % str(chunk)
Vic Yang93027612013-05-06 02:42:49 +08001993 start_time = time.time()
1994 shopfloor_client = shopfloor.get_instance(
Ricky Liang45c73e72015-01-15 15:00:30 +08001995 detect=True,
Cheng-Yi Chiangf5b21012015-03-17 15:37:14 +08001996 timeout=self.test_list.options.shopfloor_timeout_secs,
1997 quiet=quiet)
Ricky Liang45c73e72015-01-15 15:00:30 +08001998 shopfloor_client.UploadEvent(chunk.log_name + '.' +
Jon Salzd15bbcf2013-05-21 17:33:57 +08001999 event_log.GetReimageId(),
2000 Binary(chunk.chunk))
Vic Yang93027612013-05-06 02:42:49 +08002001 logging.info(
Ricky Liang45c73e72015-01-15 15:00:30 +08002002 'Successfully synced %s in %.03f s',
2003 description, time.time() - start_time)
2004 except: # pylint: disable=W0702
Hung-Te Linf707b242016-01-08 23:11:42 +08002005 first_exception = (first_exception or
2006 (chunk.log_name + ': ' +
2007 debug_utils.FormatExceptionOnly()))
Vic Yang93027612013-05-06 02:42:49 +08002008 exception_count += 1
2009
2010 if exception_count:
2011 if exception_count == 1:
2012 msg = 'Log upload failed: %s' % first_exception
2013 else:
2014 msg = '%d log upload failed; first is: %s' % (
2015 exception_count, first_exception)
Cheng-Yi Chiangf5b21012015-03-17 15:37:14 +08002016 # For periodic event log syncing, only show the first error messages.
2017 if periodic:
2018 if not self._suppress_event_log_error_messages:
2019 self._suppress_event_log_error_messages = True
2020 logging.warning('Suppress periodic shopfloor error messages for '
2021 'event log syncing after the first one.')
2022 raise Exception(msg)
2023 # For event log syncing by request, show the error messages.
2024 else:
2025 raise Exception(msg)
Vic Yang93027612013-05-06 02:42:49 +08002026
Ricky Liang45c73e72015-01-15 15:00:30 +08002027 def run_tests_with_status(self, statuses_to_run, starting_at=None, root=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08002028 """Runs all top-level tests with a particular status.
Jon Salz0405ab52012-03-16 15:26:52 +08002029
Jon Salz0697cbf2012-07-04 15:14:04 +08002030 All active tests, plus any tests to re-run, are reset.
Jon Salz57717ca2012-04-04 16:47:25 +08002031
Jon Salz0697cbf2012-07-04 15:14:04 +08002032 Args:
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08002033 statuses_to_run: The particular status that caller wants to run.
Jon Salz0697cbf2012-07-04 15:14:04 +08002034 starting_at: If provided, only auto-runs tests beginning with
2035 this test.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08002036 root: The root of tests to run. If not provided, it will be
2037 the root of all tests.
2038 """
Jon Salz0697cbf2012-07-04 15:14:04 +08002039 root = root or self.test_list
Jon Salz57717ca2012-04-04 16:47:25 +08002040
Jon Salz0697cbf2012-07-04 15:14:04 +08002041 if starting_at:
2042 # Make sure they passed a test, not a string.
2043 assert isinstance(starting_at, factory.FactoryTest)
Jon Salz0405ab52012-03-16 15:26:52 +08002044
Jon Salz0697cbf2012-07-04 15:14:04 +08002045 tests_to_reset = []
2046 tests_to_run = []
Jon Salz0405ab52012-03-16 15:26:52 +08002047
Jon Salz0697cbf2012-07-04 15:14:04 +08002048 found_starting_at = False
Jon Salz0405ab52012-03-16 15:26:52 +08002049
Jon Salz0697cbf2012-07-04 15:14:04 +08002050 for test in root.get_top_level_tests():
2051 if starting_at:
2052 if test == starting_at:
2053 # We've found starting_at; do auto-run on all
2054 # subsequent tests.
2055 found_starting_at = True
2056 if not found_starting_at:
2057 # Don't start this guy yet
2058 continue
Jon Salz0405ab52012-03-16 15:26:52 +08002059
Jon Salz0697cbf2012-07-04 15:14:04 +08002060 status = test.get_state().status
2061 if status == TestState.ACTIVE or status in statuses_to_run:
2062 # Reset the test (later; we will need to abort
2063 # all active tests first).
2064 tests_to_reset.append(test)
2065 if status in statuses_to_run:
2066 tests_to_run.append(test)
Jon Salz0405ab52012-03-16 15:26:52 +08002067
Jon Salz6dc031d2013-06-19 13:06:23 +08002068 self.abort_active_tests('Operator requested run/re-run of certain tests')
Jon Salz258a40c2012-04-19 12:34:01 +08002069
Jon Salz0697cbf2012-07-04 15:14:04 +08002070 # Reset all statuses of the tests to run (in case any tests were active;
2071 # we want them to be run again).
2072 for test_to_reset in tests_to_reset:
2073 for test in test_to_reset.walk():
2074 test.update_state(status=TestState.UNTESTED)
Jon Salz57717ca2012-04-04 16:47:25 +08002075
Chih-Yu Huang85dc63c2015-08-12 15:21:28 +08002076 self.run_tests(tests_to_run, [TestState.UNTESTED])
Jon Salz0405ab52012-03-16 15:26:52 +08002077
Jon Salz0697cbf2012-07-04 15:14:04 +08002078 def restart_tests(self, root=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08002079 """Restarts all tests."""
Jon Salz0697cbf2012-07-04 15:14:04 +08002080 root = root or self.test_list
Jon Salz0405ab52012-03-16 15:26:52 +08002081
Jon Salz6dc031d2013-06-19 13:06:23 +08002082 self.abort_active_tests('Operator requested restart of certain tests')
Jon Salz0697cbf2012-07-04 15:14:04 +08002083 for test in root.walk():
Ricky Liangfea4ac92014-08-21 11:55:59 +08002084 test.update_state(status=TestState.UNTESTED)
Jon Salz0697cbf2012-07-04 15:14:04 +08002085 self.run_tests(root)
Hung-Te Lin96632362012-03-20 21:14:18 +08002086
Jon Salz0697cbf2012-07-04 15:14:04 +08002087 def auto_run(self, starting_at=None, root=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08002088 """"Auto-runs" tests that have not been run yet.
Hung-Te Lin96632362012-03-20 21:14:18 +08002089
Jon Salz0697cbf2012-07-04 15:14:04 +08002090 Args:
2091 starting_at: If provide, only auto-runs tests beginning with
2092 this test.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08002093 root: If provided, the root of tests to run. If not provided, the root
2094 will be test_list (root of all tests).
2095 """
Jon Salz0697cbf2012-07-04 15:14:04 +08002096 root = root or self.test_list
2097 self.run_tests_with_status([TestState.UNTESTED, TestState.ACTIVE],
Ricky Liang45c73e72015-01-15 15:00:30 +08002098 starting_at=starting_at,
2099 root=root)
Jon Salz968e90b2012-03-18 16:12:43 +08002100
Jon Salz0697cbf2012-07-04 15:14:04 +08002101 def re_run_failed(self, root=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08002102 """Re-runs failed tests."""
Jon Salz0697cbf2012-07-04 15:14:04 +08002103 root = root or self.test_list
2104 self.run_tests_with_status([TestState.FAILED], root=root)
Jon Salz57717ca2012-04-04 16:47:25 +08002105
Jon Salz0697cbf2012-07-04 15:14:04 +08002106 def show_review_information(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08002107 """Event handler for showing review information screen.
Jon Salz57717ca2012-04-04 16:47:25 +08002108
Peter Ammon1e1ec572014-06-26 17:56:32 -07002109 The information screen is rendered by main UI program (ui.py), so in
Jon Salz0697cbf2012-07-04 15:14:04 +08002110 goofy we only need to kill all active tests, set them as untested, and
2111 clear remaining tests.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08002112 """
Jon Salz0697cbf2012-07-04 15:14:04 +08002113 self.kill_active_tests(False)
Jon Salza6711d72012-07-18 14:33:03 +08002114 self.cancel_pending_tests()
Jon Salz57717ca2012-04-04 16:47:25 +08002115
Jon Salz0697cbf2012-07-04 15:14:04 +08002116 def handle_switch_test(self, event):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08002117 """Switches to a particular test.
Jon Salz0405ab52012-03-16 15:26:52 +08002118
Ricky Liang6fe218c2013-12-27 15:17:17 +08002119 Args:
2120 event: The SWITCH_TEST event.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08002121 """
Jon Salz0697cbf2012-07-04 15:14:04 +08002122 test = self.test_list.lookup_path(event.path)
2123 if not test:
2124 logging.error('Unknown test %r', event.key)
2125 return
Jon Salz73e0fd02012-04-04 11:46:38 +08002126
Jon Salz0697cbf2012-07-04 15:14:04 +08002127 invoc = self.invocations.get(test)
2128 if invoc and test.backgroundable:
2129 # Already running: just bring to the front if it
2130 # has a UI.
2131 logging.info('Setting visible test to %s', test.path)
Jon Salz36fbbb52012-07-05 13:45:06 +08002132 self.set_visible_test(test)
Jon Salz0697cbf2012-07-04 15:14:04 +08002133 return
Jon Salz73e0fd02012-04-04 11:46:38 +08002134
Jon Salz6dc031d2013-06-19 13:06:23 +08002135 self.abort_active_tests('Operator requested abort (switch_test)')
Jon Salz0697cbf2012-07-04 15:14:04 +08002136 for t in test.walk():
2137 t.update_state(status=TestState.UNTESTED)
Jon Salz73e0fd02012-04-04 11:46:38 +08002138
Jon Salz0697cbf2012-07-04 15:14:04 +08002139 if self.test_list.options.auto_run_on_keypress:
2140 self.auto_run(starting_at=test)
2141 else:
2142 self.run_tests(test)
Jon Salz73e0fd02012-04-04 11:46:38 +08002143
Wei-Ning Huang38b75f02015-02-25 18:25:14 +08002144 def handle_key_filter_mode(self, event):
2145 if self.key_filter:
2146 if getattr(event, 'enabled'):
2147 self.key_filter.Start()
2148 else:
2149 self.key_filter.Stop()
2150
Jon Salz0697cbf2012-07-04 15:14:04 +08002151 def wait(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08002152 """Waits for all pending invocations.
Jon Salz0697cbf2012-07-04 15:14:04 +08002153
2154 Useful for testing.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08002155 """
Jon Salz1acc8742012-07-17 17:45:55 +08002156 while self.invocations:
2157 for k, v in self.invocations.iteritems():
2158 logging.info('Waiting for %s to complete...', k)
2159 v.thread.join()
2160 self.reap_completed_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +08002161
Claire Changd1961a22015-08-05 16:15:55 +08002162 def test_fail(self, test):
Hung-Te Lin410f70a2015-12-15 14:53:42 +08002163 self.dut.hooks.OnTestFailure(test)
Claire Changd1961a22015-08-05 16:15:55 +08002164 if self.link_manager:
2165 self.link_manager.UpdateStatus(False)
2166
Hung-Te Linf2f78f72012-02-08 19:27:11 +08002167if __name__ == '__main__':
Peter Ammona3d298c2014-09-23 10:11:02 -07002168 Goofy.run_main_and_exit()