blob: e147694a7774fd140d44c21100d85b1eb2cd5ae5 [file] [log] [blame]
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001#!/usr/bin/python -u
Hung-Te Linf2f78f72012-02-08 19:27:11 +08002# -*- coding: utf-8 -*-
3#
Jon Salz37eccbd2012-05-25 16:06:52 +08004# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
Hung-Te Linf2f78f72012-02-08 19:27:11 +08005# Use of this source code is governed by a BSD-style license that can be
6# found in the LICENSE file.
7
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08008"""The main factory flow that runs the factory test and finalizes a device."""
Hung-Te Linf2f78f72012-02-08 19:27:11 +08009
Joel Kitchingb85ed7f2014-10-08 18:24:39 +080010from __future__ import print_function
11
Jon Salze12c2b32013-06-25 16:24:34 +080012import glob
Jon Salz0405ab52012-03-16 15:26:52 +080013import logging
14import os
Jon Salze12c2b32013-06-25 16:24:34 +080015import shutil
Jon Salz77c151e2012-08-28 07:20:37 +080016import signal
Jon Salz0405ab52012-03-16 15:26:52 +080017import sys
Jon Salzeff94182013-06-19 15:06:28 +080018import syslog
Jon Salz0405ab52012-03-16 15:26:52 +080019import threading
20import time
21import traceback
Jon Salz258a40c2012-04-19 12:34:01 +080022import uuid
Jon Salzb10cf512012-08-09 17:29:21 +080023from xmlrpclib import Binary
Hung-Te Linf2f78f72012-02-08 19:27:11 +080024from collections import deque
25from optparse import OptionParser
Hung-Te Linf2f78f72012-02-08 19:27:11 +080026
Jon Salz0697cbf2012-07-04 15:14:04 +080027import factory_common # pylint: disable=W0611
Hung-Te Lin91492a12014-11-25 18:56:30 +080028from cros.factory.test import event_log
Chun-Ta Lin5d12b592015-06-30 00:54:23 -070029from cros.factory.test.event_log import EventLog, FloatDigit, GetBootSequence
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
Hung-Te Lin6a72c642015-12-13 22:09:09 +080043from cros.factory.test import dut
jcliangcd688182012-08-20 21:01:26 +080044from cros.factory.test import factory
Jon Salz51528e12012-07-02 18:54:45 +080045from cros.factory.test import shopfloor
Hung-Te Lin6a72c642015-12-13 22:09:09 +080046from cros.factory.test import state
Wei-Han Chen2ebb92d2016-01-12 14:51:41 +080047from cros.factory.test.env import paths
Wei-Han Chene8a025f2016-01-14 16:42:02 +080048from cros.factory.test.dut import utils as dut_utils
Ricky Liang6fe218c2013-12-27 15:17:17 +080049from cros.factory.test.e2e_test.common import (
50 AutomationMode, AutomationModePrompt, ParseAutomationMode)
Jon Salz83591782012-06-26 11:09:58 +080051from cros.factory.test.event import Event
52from cros.factory.test.event import EventClient
53from cros.factory.test.event import EventServer
Hung-Te Lin91492a12014-11-25 18:56:30 +080054from cros.factory.test.event_log_watcher import EventLogWatcher
jcliangcd688182012-08-20 21:01:26 +080055from cros.factory.test.factory import TestState
Hung-Te Lin3f096842016-01-13 17:37:06 +080056from cros.factory.test.rules import phase
Wei-Han Chen2ebb92d2016-01-12 14:51:41 +080057from cros.factory.test.test_lists import test_lists
Hung-Te Linc367ac02015-12-22 19:33:23 +080058from cros.factory.test.utils.charge_manager import ChargeManager
59from cros.factory.test.utils.core_dump_manager import CoreDumpManager
60from cros.factory.test.utils.cpufreq_manager import CpufreqManager
Dean Liao592e4d52013-01-10 20:06:39 +080061from cros.factory.tools.key_filter import KeyFilter
Hung-Te Lind3ee0102015-12-28 17:21:50 +080062from cros.factory.tools import disk_space
Hung-Te Linf707b242016-01-08 23:11:42 +080063from cros.factory.utils import debug_utils
Jon Salz2af235d2013-06-24 14:47:21 +080064from cros.factory.utils import file_utils
Joel Kitchingb85ed7f2014-10-08 18:24:39 +080065from cros.factory.utils import net_utils
Hung-Te Lin4e6357c2016-01-08 14:32:00 +080066from cros.factory.utils import process_utils
67from cros.factory.utils import sys_utils
68from cros.factory.utils import time_utils
Hung-Te Linf707b242016-01-08 23:11:42 +080069from cros.factory.utils import type_utils
Hung-Te Linf2f78f72012-02-08 19:27:11 +080070
71
Hung-Te Linf2f78f72012-02-08 19:27:11 +080072HWID_CFG_PATH = '/usr/local/share/chromeos-hwid/cfg'
Ricky Liang45c73e72015-01-15 15:00:30 +080073CACHES_DIR = os.path.join(factory.get_state_root(), 'caches')
Hung-Te Linf2f78f72012-02-08 19:27:11 +080074
Cheng-Yi Chiang39d32ad2013-07-23 15:02:38 +080075CLEANUP_LOGS_PAUSED = '/var/lib/cleanup_logs_paused'
76
Jon Salz5c344f62012-07-13 14:31:16 +080077# Value for tests_after_shutdown that forces auto-run (e.g., after
78# a factory update, when the available set of tests might change).
79FORCE_AUTO_RUN = 'force_auto_run'
80
Justin Chuang83813982013-05-13 01:26:32 +080081# Sync disks when battery level is higher than this value.
82# Otherwise, power loss during disk sync operation may incur even worse outcome.
83MIN_BATTERY_LEVEL_FOR_DISK_SYNC = 1.0
84
Ricky Liang45c73e72015-01-15 15:00:30 +080085MAX_CRASH_FILE_SIZE = 64 * 1024
Jon Salze12c2b32013-06-25 16:24:34 +080086
Hung-Te Linf707b242016-01-08 23:11:42 +080087Status = type_utils.Enum(['UNINITIALIZED', 'INITIALIZING', 'RUNNING',
Wei-Han Chen2ebb92d2016-01-12 14:51:41 +080088 'TERMINATING', 'TERMINATED'])
Jon Salzd7550792013-07-12 05:49:27 +080089
Ricky Liang45c73e72015-01-15 15:00:30 +080090
Hung-Te Linf2f78f72012-02-08 19:27:11 +080091def get_hwid_cfg():
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +080092 """Returns the HWID config tag, or an empty string if none can be found."""
Jon Salz0697cbf2012-07-04 15:14:04 +080093 if 'CROS_HWID' in os.environ:
94 return os.environ['CROS_HWID']
95 if os.path.exists(HWID_CFG_PATH):
Ricky Liang45c73e72015-01-15 15:00:30 +080096 with open(HWID_CFG_PATH, 'r') as hwid_cfg_handle:
Jon Salz0697cbf2012-07-04 15:14:04 +080097 return hwid_cfg_handle.read().strip()
98 return ''
Hung-Te Linf2f78f72012-02-08 19:27:11 +080099
100
Jon Salz73e0fd02012-04-04 11:46:38 +0800101_inited_logging = False
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800102
Ricky Liang45c73e72015-01-15 15:00:30 +0800103
Peter Ammon1e1ec572014-06-26 17:56:32 -0700104class Goofy(GoofyBase):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800105 """The main factory flow.
Jon Salz0697cbf2012-07-04 15:14:04 +0800106
107 Note that all methods in this class must be invoked from the main
108 (event) thread. Other threads, such as callbacks and TestInvocation
109 methods, should instead post events on the run queue.
110
111 TODO: Unit tests. (chrome-os-partner:7409)
112
113 Properties:
114 uuid: A unique UUID for this invocation of Goofy.
115 state_instance: An instance of FactoryState.
116 state_server: The FactoryState XML/RPC server.
117 state_server_thread: A thread running state_server.
118 event_server: The EventServer socket server.
119 event_server_thread: A thread running event_server.
120 event_client: A client to the event server.
121 connection_manager: The connection_manager object.
Cheng-Yi Chiang835f2682013-05-06 22:15:48 +0800122 system_log_manager: The SystemLogManager object.
123 core_dump_manager: The CoreDumpManager object.
Jon Salz0697cbf2012-07-04 15:14:04 +0800124 ui_process: The factory ui process object.
Jon Salz0697cbf2012-07-04 15:14:04 +0800125 invocations: A map from FactoryTest objects to the corresponding
126 TestInvocations objects representing active tests.
127 tests_to_run: A deque of tests that should be run when the current
128 test(s) complete.
129 options: Command-line options.
130 args: Command-line args.
131 test_list: The test list.
Jon Salz128b0932013-07-03 16:55:26 +0800132 test_lists: All new-style test lists.
Ricky Liang4bff3e32014-02-20 18:46:11 +0800133 run_id: The identifier for latest test run.
134 scheduled_run_tests: The list of tests scheduled for latest test run.
Jon Salz0697cbf2012-07-04 15:14:04 +0800135 event_handlers: Map of Event.Type to the method used to handle that
136 event. If the method has an 'event' argument, the event is passed
137 to the handler.
Jon Salz3c493bb2013-02-07 17:24:58 +0800138 last_log_disk_space_message: The last message we logged about disk space
139 (to avoid duplication).
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +0800140 last_kick_sync_time: The last time to kick system_log_manager to sync
141 because of core dump files (to avoid kicking too soon then abort the
142 sync.)
Jon Salz416f9cc2013-05-10 18:32:50 +0800143 hooks: A Hooks object containing hooks for various Goofy actions.
Jon Salzd7550792013-07-12 05:49:27 +0800144 status: The current Goofy status (a member of the Status enum).
Peter Ammon948b7172014-07-15 12:43:06 -0700145 link_manager: Instance of PresenterLinkManager for communicating
146 with GoofyPresenter
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800147 """
Ricky Liang45c73e72015-01-15 15:00:30 +0800148
Jon Salz0697cbf2012-07-04 15:14:04 +0800149 def __init__(self):
Peter Ammon1e1ec572014-06-26 17:56:32 -0700150 super(Goofy, self).__init__()
Jon Salz0697cbf2012-07-04 15:14:04 +0800151 self.uuid = str(uuid.uuid4())
152 self.state_instance = None
153 self.state_server = None
154 self.state_server_thread = None
Jon Salz16d10542012-07-23 12:18:45 +0800155 self.goofy_rpc = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800156 self.event_server = None
157 self.event_server_thread = None
158 self.event_client = None
159 self.connection_manager = None
Vic Yang4953fc12012-07-26 16:19:53 +0800160 self.charge_manager = None
Dean Liao88b93192014-10-23 19:37:41 +0800161 self._can_charge = True
Jon Salz8fa8e832012-07-13 19:04:09 +0800162 self.time_sanitizer = None
163 self.time_synced = False
Jon Salz0697cbf2012-07-04 15:14:04 +0800164 self.log_watcher = None
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +0800165 self.system_log_manager = None
Cheng-Yi Chiang835f2682013-05-06 22:15:48 +0800166 self.core_dump_manager = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800167 self.event_log = None
Vic Yange2c76a82014-10-30 12:48:19 -0700168 self.autotest_prespawner = None
169 self.pytest_prespawner = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800170 self.ui_process = None
Vic Yanga3cecf82014-12-26 00:44:21 -0800171 self._ui_initialized = False
Jon Salzc79a9982012-08-30 04:42:01 +0800172 self.dummy_shopfloor = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800173 self.invocations = {}
174 self.tests_to_run = deque()
175 self.visible_test = None
176 self.chrome = None
Jon Salz416f9cc2013-05-10 18:32:50 +0800177 self.hooks = None
Vic Yangd8990da2013-06-27 16:57:43 +0800178 self.cpu_usage_watcher = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800179
180 self.options = None
181 self.args = None
182 self.test_list = None
Jon Salz128b0932013-07-03 16:55:26 +0800183 self.test_lists = None
Ricky Liang4bff3e32014-02-20 18:46:11 +0800184 self.run_id = None
185 self.scheduled_run_tests = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800186 self.env = None
Jon Salzb22d1172012-08-06 10:38:57 +0800187 self.last_idle = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800188 self.last_shutdown_time = None
cychiang21886742012-07-05 15:16:32 +0800189 self.last_update_check = None
Cheng-Yi Chiang194d3c02015-03-16 14:37:15 +0800190 self._suppress_periodic_update_messages = False
Cheng-Yi Chiangf5b21012015-03-17 15:37:14 +0800191 self._suppress_event_log_error_messages = False
Jon Salz8fa8e832012-07-13 19:04:09 +0800192 self.last_sync_time = None
Jon Salzb92c5112012-09-21 15:40:11 +0800193 self.last_log_disk_space_time = None
Jon Salz3c493bb2013-02-07 17:24:58 +0800194 self.last_log_disk_space_message = None
Justin Chuang83813982013-05-13 01:26:32 +0800195 self.last_check_battery_time = None
196 self.last_check_battery_message = None
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +0800197 self.last_kick_sync_time = None
Vic Yang311ddb82012-09-26 12:08:28 +0800198 self.exclusive_items = set()
Jon Salz0f996602012-10-03 15:26:48 +0800199 self.event_log = None
Dean Liao592e4d52013-01-10 20:06:39 +0800200 self.key_filter = None
Jon Salzce6a7f82013-06-10 18:22:54 +0800201 self.cpufreq_manager = None
Jon Salzd7550792013-07-12 05:49:27 +0800202 self.status = Status.UNINITIALIZED
Ricky Liang36512a32014-07-25 11:47:04 +0800203 self.ready_for_ui_connection = False
Peter Ammon1e1ec572014-06-26 17:56:32 -0700204 self.link_manager = None
Hung-Te Linef7f2be2015-07-20 20:38:51 +0800205 self.is_restart_requested = False
Jon Salz0697cbf2012-07-04 15:14:04 +0800206
Hung-Te Lin6a72c642015-12-13 22:09:09 +0800207 # TODO(hungte) Support controlling remote DUT.
208 self.dut = dut.Create()
209
Jon Salz85a39882012-07-05 16:45:04 +0800210 def test_or_root(event, parent_or_group=True):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800211 """Returns the test affected by a particular event.
Jon Salz85a39882012-07-05 16:45:04 +0800212
213 Args:
214 event: The event containing an optional 'path' attribute.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800215 parent_or_group: If True, returns the top-level parent for a test (the
Jon Salz85a39882012-07-05 16:45:04 +0800216 root node of the tests that need to be run together if the given test
217 path is to be run).
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800218 """
Jon Salz0697cbf2012-07-04 15:14:04 +0800219 try:
220 path = event.path
221 except AttributeError:
222 path = None
223
224 if path:
Jon Salz85a39882012-07-05 16:45:04 +0800225 test = self.test_list.lookup_path(path)
226 if parent_or_group:
227 test = test.get_top_level_parent_or_group()
228 return test
Jon Salz0697cbf2012-07-04 15:14:04 +0800229 else:
230 return self.test_list
231
232 self.event_handlers = {
Ricky Liang45c73e72015-01-15 15:00:30 +0800233 Event.Type.SWITCH_TEST: self.handle_switch_test,
234 Event.Type.SHOW_NEXT_ACTIVE_TEST:
235 lambda event: self.show_next_active_test(),
236 Event.Type.RESTART_TESTS:
237 lambda event: self.restart_tests(root=test_or_root(event)),
238 Event.Type.AUTO_RUN:
239 lambda event: self.auto_run(root=test_or_root(event)),
240 Event.Type.RE_RUN_FAILED:
241 lambda event: self.re_run_failed(root=test_or_root(event)),
242 Event.Type.RUN_TESTS_WITH_STATUS:
243 lambda event: self.run_tests_with_status(
244 event.status,
245 root=test_or_root(event)),
246 Event.Type.REVIEW:
247 lambda event: self.show_review_information(),
248 Event.Type.UPDATE_SYSTEM_INFO:
249 lambda event: self.update_system_info(),
250 Event.Type.STOP:
251 lambda event: self.stop(root=test_or_root(event, False),
252 fail=getattr(event, 'fail', False),
253 reason=getattr(event, 'reason', None)),
254 Event.Type.SET_VISIBLE_TEST:
255 lambda event: self.set_visible_test(
256 self.test_list.lookup_path(event.path)),
257 Event.Type.CLEAR_STATE:
258 lambda event: self.clear_state(
259 self.test_list.lookup_path(event.path)),
Wei-Ning Huang38b75f02015-02-25 18:25:14 +0800260 Event.Type.KEY_FILTER_MODE: self.handle_key_filter_mode,
Jon Salz0697cbf2012-07-04 15:14:04 +0800261 }
262
Jon Salz0697cbf2012-07-04 15:14:04 +0800263 self.web_socket_manager = None
Wei-Ning Huang38b75f02015-02-25 18:25:14 +0800264 self.terminal_manager = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800265
266 def destroy(self):
Ricky Liang74237a02014-09-18 15:11:23 +0800267 """Performs any shutdown tasks. Overrides base class method."""
Jon Salzd7550792013-07-12 05:49:27 +0800268 self.status = Status.TERMINATING
Jon Salz0697cbf2012-07-04 15:14:04 +0800269 if self.chrome:
270 self.chrome.kill()
271 self.chrome = None
Jon Salzc79a9982012-08-30 04:42:01 +0800272 if self.dummy_shopfloor:
273 self.dummy_shopfloor.kill()
274 self.dummy_shopfloor = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800275 if self.ui_process:
Hung-Te Lin4e6357c2016-01-08 14:32:00 +0800276 process_utils.KillProcessTree(self.ui_process, 'ui')
Jon Salz0697cbf2012-07-04 15:14:04 +0800277 self.ui_process = None
278 if self.web_socket_manager:
279 logging.info('Stopping web sockets')
280 self.web_socket_manager.close()
281 self.web_socket_manager = None
282 if self.state_server_thread:
283 logging.info('Stopping state server')
284 self.state_server.shutdown()
285 self.state_server_thread.join()
286 self.state_server.server_close()
287 self.state_server_thread = None
288 if self.state_instance:
289 self.state_instance.close()
290 if self.event_server_thread:
291 logging.info('Stopping event server')
292 self.event_server.shutdown() # pylint: disable=E1101
293 self.event_server_thread.join()
294 self.event_server.server_close()
295 self.event_server_thread = None
296 if self.log_watcher:
297 if self.log_watcher.IsThreadStarted():
298 self.log_watcher.StopWatchThread()
299 self.log_watcher = None
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +0800300 if self.system_log_manager:
301 if self.system_log_manager.IsThreadRunning():
Cheng-Yi Chianga0f6eff2014-01-09 18:27:22 +0800302 self.system_log_manager.Stop()
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +0800303 self.system_log_manager = None
Vic Yange2c76a82014-10-30 12:48:19 -0700304 if self.autotest_prespawner:
305 logging.info('Stopping autotest prespawner')
306 self.autotest_prespawner.stop()
307 self.autotest_prespawner = None
308 if self.pytest_prespawner:
309 logging.info('Stopping pytest prespawner')
310 self.pytest_prespawner.stop()
311 self.pytest_prespawner = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800312 if self.event_client:
313 logging.info('Closing event client')
314 self.event_client.close()
315 self.event_client = None
Jon Salzddf0d052013-06-18 12:52:44 +0800316 if self.cpufreq_manager:
317 self.cpufreq_manager.Stop()
Jon Salz0697cbf2012-07-04 15:14:04 +0800318 if self.event_log:
319 self.event_log.Close()
320 self.event_log = None
Dean Liao592e4d52013-01-10 20:06:39 +0800321 if self.key_filter:
322 self.key_filter.Stop()
Vic Yangd8990da2013-06-27 16:57:43 +0800323 if self.cpu_usage_watcher:
324 self.cpu_usage_watcher.terminate()
Peter Ammon1e1ec572014-06-26 17:56:32 -0700325 if self.link_manager:
326 self.link_manager.Stop()
327 self.link_manager = None
Dean Liao592e4d52013-01-10 20:06:39 +0800328
Peter Ammon1e1ec572014-06-26 17:56:32 -0700329 super(Goofy, self).destroy()
Jon Salz0697cbf2012-07-04 15:14:04 +0800330 logging.info('Done destroying Goofy')
Jon Salzd7550792013-07-12 05:49:27 +0800331 self.status = Status.TERMINATED
Jon Salz0697cbf2012-07-04 15:14:04 +0800332
333 def start_state_server(self):
Jon Salz2af235d2013-06-24 14:47:21 +0800334 # Before starting state server, remount stateful partitions with
335 # no commit flag. The default commit time (commit=600) makes corruption
336 # too likely.
Hung-Te Lin1968d9c2016-01-08 22:55:46 +0800337 sys_utils.ResetCommitTime()
Jon Salz2af235d2013-06-24 14:47:21 +0800338
Jon Salz0697cbf2012-07-04 15:14:04 +0800339 self.state_instance, self.state_server = (
Ricky Liang45c73e72015-01-15 15:00:30 +0800340 state.create_server(bind_address='0.0.0.0'))
Jon Salz16d10542012-07-23 12:18:45 +0800341 self.goofy_rpc = GoofyRPC(self)
342 self.goofy_rpc.RegisterMethods(self.state_instance)
Jon Salz0697cbf2012-07-04 15:14:04 +0800343 logging.info('Starting state server')
344 self.state_server_thread = threading.Thread(
Ricky Liang45c73e72015-01-15 15:00:30 +0800345 target=self.state_server.serve_forever,
346 name='StateServer')
Jon Salz0697cbf2012-07-04 15:14:04 +0800347 self.state_server_thread.start()
348
349 def start_event_server(self):
350 self.event_server = EventServer()
351 logging.info('Starting factory event server')
352 self.event_server_thread = threading.Thread(
Ricky Liang45c73e72015-01-15 15:00:30 +0800353 target=self.event_server.serve_forever,
354 name='EventServer') # pylint: disable=E1101
Jon Salz0697cbf2012-07-04 15:14:04 +0800355 self.event_server_thread.start()
356
357 self.event_client = EventClient(
Ricky Liang45c73e72015-01-15 15:00:30 +0800358 callback=self.handle_event, event_loop=self.run_queue)
Jon Salz0697cbf2012-07-04 15:14:04 +0800359
360 self.web_socket_manager = WebSocketManager(self.uuid)
Ricky Liang45c73e72015-01-15 15:00:30 +0800361 self.state_server.add_handler('/event',
362 self.web_socket_manager.handle_web_socket)
Jon Salz0697cbf2012-07-04 15:14:04 +0800363
Wei-Ning Huang38b75f02015-02-25 18:25:14 +0800364 def start_terminal_server(self):
365 self.terminal_manager = TerminalManager()
366 self.state_server.add_handler('/pty',
367 self.terminal_manager.handle_web_socket)
368
Jon Salz0697cbf2012-07-04 15:14:04 +0800369 def start_ui(self):
370 ui_proc_args = [
Wei-Han Chen2ebb92d2016-01-12 14:51:41 +0800371 os.path.join(paths.FACTORY_PACKAGE_PATH, 'test', 'ui.py'),
Ricky Liang45c73e72015-01-15 15:00:30 +0800372 self.options.test_list
373 ]
Jon Salz0697cbf2012-07-04 15:14:04 +0800374 if self.options.verbose:
375 ui_proc_args.append('-v')
376 logging.info('Starting ui %s', ui_proc_args)
Hung-Te Lin4e6357c2016-01-08 14:32:00 +0800377 self.ui_process = process_utils.Spawn(ui_proc_args)
Jon Salz0697cbf2012-07-04 15:14:04 +0800378 logging.info('Waiting for UI to come up...')
379 self.event_client.wait(
Ricky Liang45c73e72015-01-15 15:00:30 +0800380 lambda event: event.type == Event.Type.UI_READY)
Jon Salz0697cbf2012-07-04 15:14:04 +0800381 logging.info('UI has started')
382
383 def set_visible_test(self, test):
384 if self.visible_test == test:
385 return
Jon Salz2f2d42c2012-07-30 12:30:34 +0800386 if test and not test.has_ui:
387 return
Jon Salz0697cbf2012-07-04 15:14:04 +0800388
389 if test:
390 test.update_state(visible=True)
391 if self.visible_test:
392 self.visible_test.update_state(visible=False)
393 self.visible_test = test
394
Ricky Liang48e47f92014-02-26 19:31:51 +0800395 def log_startup_messages(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800396 """Logs the tail of var/log/messages and mosys and EC console logs."""
Jon Salzd4306c82012-11-30 15:16:36 +0800397 # TODO(jsalz): This is mostly a copy-and-paste of code in init_states,
398 # for factory-3004.B only. Consolidate and merge back to ToT.
Hung-Te Linf5f2d7f2016-01-08 17:12:46 +0800399 if sys_utils.InChroot():
Jon Salzd4306c82012-11-30 15:16:36 +0800400 return
401
402 try:
Hung-Te Lin1a4e30c2016-01-08 23:25:10 +0800403 var_log_messages = sys_utils.GetVarLogMessagesBeforeReboot()
Jon Salzd4306c82012-11-30 15:16:36 +0800404 logging.info(
Ricky Liang45c73e72015-01-15 15:00:30 +0800405 'Tail of /var/log/messages before last reboot:\n'
406 '%s', ('\n'.join(
407 ' ' + x for x in var_log_messages)))
Jon Salzd4306c82012-11-30 15:16:36 +0800408 except: # pylint: disable=W0702
409 logging.exception('Unable to grok /var/log/messages')
410
411 try:
Hung-Te Lin4e6357c2016-01-08 14:32:00 +0800412 mosys_log = process_utils.Spawn(
Jon Salzd4306c82012-11-30 15:16:36 +0800413 ['mosys', 'eventlog', 'list'],
414 read_stdout=True, log_stderr_on_error=True).stdout_data
415 logging.info('System eventlog from mosys:\n%s\n', mosys_log)
416 except: # pylint: disable=W0702
417 logging.exception('Unable to read mosys eventlog')
418
Dean Liao88b93192014-10-23 19:37:41 +0800419 self.log_ec_console()
420 self.log_ec_panic_info()
421
422 @staticmethod
423 def log_ec_console():
424 """Logs EC console log into logging.info.
425
426 It logs an error message in logging.exception if an exception is raised
427 when getting EC console log.
428 For unsupported device, it logs unsupport message in logging.info
429
430 Returns:
431 EC console log string.
432 """
Jon Salzd4306c82012-11-30 15:16:36 +0800433 try:
Hung-Te Linb3a09642015-12-14 18:57:23 +0800434 ec_console_log = dut.Create().ec.GetECConsoleLog()
Jon Salzd4306c82012-11-30 15:16:36 +0800435 logging.info('EC console log after reboot:\n%s\n', ec_console_log)
Dean Liao88b93192014-10-23 19:37:41 +0800436 return ec_console_log
437 except NotImplementedError:
438 logging.info('EC console log not supported')
Jon Salzd4306c82012-11-30 15:16:36 +0800439 except: # pylint: disable=W0702
440 logging.exception('Error retrieving EC console log')
441
Dean Liao88b93192014-10-23 19:37:41 +0800442 @staticmethod
443 def log_ec_panic_info():
444 """Logs EC panic info into logging.info.
445
446 It logs an error message in logging.exception if an exception is raised
447 when getting EC panic info.
448 For unsupported device, it logs unsupport message in logging.info
449
450 Returns:
451 EC panic info string.
452 """
Vic Yang079f9872013-07-01 11:32:00 +0800453 try:
Hung-Te Linb3a09642015-12-14 18:57:23 +0800454 ec_panic_info = dut.Create().ec.GetECPanicInfo()
Vic Yang079f9872013-07-01 11:32:00 +0800455 logging.info('EC panic info after reboot:\n%s\n', ec_panic_info)
Dean Liao88b93192014-10-23 19:37:41 +0800456 return ec_panic_info
457 except NotImplementedError:
458 logging.info('EC panic info is not supported')
Vic Yang079f9872013-07-01 11:32:00 +0800459 except: # pylint: disable=W0702
460 logging.exception('Error retrieving EC panic info')
461
Ricky Liang48e47f92014-02-26 19:31:51 +0800462 def shutdown(self, operation):
463 """Starts shutdown procedure.
464
465 Args:
Vic (Chun-Ju) Yang05b0d952014-04-28 17:39:09 +0800466 operation: The shutdown operation (reboot, full_reboot, or halt).
Ricky Liang48e47f92014-02-26 19:31:51 +0800467 """
468 active_tests = []
469 for test in self.test_list.walk():
470 if not test.is_leaf():
471 continue
472
473 test_state = test.get_state()
474 if test_state.status == TestState.ACTIVE:
475 active_tests.append(test)
476
Ricky Liang48e47f92014-02-26 19:31:51 +0800477 if not (len(active_tests) == 1 and
478 isinstance(active_tests[0], factory.ShutdownStep)):
479 logging.error(
480 'Calling Goofy shutdown outside of the shutdown factory test')
481 return
482
483 logging.info('Start Goofy shutdown (%s)', operation)
484 # Save pending test list in the state server
485 self.state_instance.set_shared_data(
486 'tests_after_shutdown',
487 [t.path for t in self.tests_to_run])
488 # Save shutdown time
489 self.state_instance.set_shared_data('shutdown_time', time.time())
490
491 with self.env.lock:
492 self.event_log.Log('shutdown', operation=operation)
493 shutdown_result = self.env.shutdown(operation)
494 if shutdown_result:
495 # That's all, folks!
Peter Ammon1e1ec572014-06-26 17:56:32 -0700496 self.run_enqueue(None)
Ricky Liang48e47f92014-02-26 19:31:51 +0800497 else:
498 # Just pass (e.g., in the chroot).
499 self.state_instance.set_shared_data('tests_after_shutdown', None)
500 # Send event with no fields to indicate that there is no
501 # longer a pending shutdown.
502 self.event_client.post_event(Event(Event.Type.PENDING_SHUTDOWN))
503
504 def handle_shutdown_complete(self, test):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800505 """Handles the case where a shutdown was detected during a shutdown step.
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800506
Ricky Liang6fe218c2013-12-27 15:17:17 +0800507 Args:
508 test: The ShutdownStep.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800509 """
Jon Salz0697cbf2012-07-04 15:14:04 +0800510 test_state = test.update_state(increment_shutdown_count=1)
511 logging.info('Detected shutdown (%d of %d)',
Ricky Liang48e47f92014-02-26 19:31:51 +0800512 test_state.shutdown_count, test.iterations)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800513
Ricky Liang48e47f92014-02-26 19:31:51 +0800514 # Insert current shutdown test at the front of the list of tests to run
515 # after shutdown. This is to continue on post-shutdown verification in the
516 # shutdown step.
517 tests_after_shutdown = self.state_instance.get_shared_data(
518 'tests_after_shutdown', optional=True)
519 if not tests_after_shutdown:
520 self.state_instance.set_shared_data('tests_after_shutdown', [test.path])
521 elif isinstance(tests_after_shutdown, list):
522 self.state_instance.set_shared_data(
523 'tests_after_shutdown', [test.path] + tests_after_shutdown)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800524
Ricky Liang48e47f92014-02-26 19:31:51 +0800525 # Set 'post_shutdown' to inform shutdown test that a shutdown just occurred.
Ricky Liangb7eb8772014-09-15 18:05:22 +0800526 self.state_instance.set_shared_data(
527 state.POST_SHUTDOWN_TAG % test.path,
528 self.state_instance.get_test_state(test.path).invocation)
Jon Salz258a40c2012-04-19 12:34:01 +0800529
Jon Salz0697cbf2012-07-04 15:14:04 +0800530 def init_states(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800531 """Initializes all states on startup."""
Jon Salz0697cbf2012-07-04 15:14:04 +0800532 for test in self.test_list.get_all_tests():
533 # Make sure the state server knows about all the tests,
534 # defaulting to an untested state.
535 test.update_state(update_parent=False, visible=False)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800536
Jon Salz0697cbf2012-07-04 15:14:04 +0800537 var_log_messages = None
Vic Yanga9c32212012-08-16 20:07:54 +0800538 mosys_log = None
Vic Yange4c275d2012-08-28 01:50:20 +0800539 ec_console_log = None
Vic Yang079f9872013-07-01 11:32:00 +0800540 ec_panic_info = None
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800541
Jon Salz0697cbf2012-07-04 15:14:04 +0800542 # Any 'active' tests should be marked as failed now.
543 for test in self.test_list.walk():
Jon Salza6711d72012-07-18 14:33:03 +0800544 if not test.is_leaf():
545 # Don't bother with parents; they will be updated when their
546 # children are updated.
547 continue
548
Jon Salz0697cbf2012-07-04 15:14:04 +0800549 test_state = test.get_state()
550 if test_state.status != TestState.ACTIVE:
551 continue
552 if isinstance(test, factory.ShutdownStep):
553 # Shutdown while the test was active - that's good.
Ricky Liang48e47f92014-02-26 19:31:51 +0800554 self.handle_shutdown_complete(test)
Jon Salz0697cbf2012-07-04 15:14:04 +0800555 else:
556 # Unexpected shutdown. Grab /var/log/messages for context.
557 if var_log_messages is None:
558 try:
559 var_log_messages = (
Hung-Te Lin1a4e30c2016-01-08 23:25:10 +0800560 sys_utils.GetVarLogMessagesBeforeReboot())
Jon Salz0697cbf2012-07-04 15:14:04 +0800561 # Write it to the log, to make it easier to
562 # correlate with /var/log/messages.
563 logging.info(
Ricky Liang45c73e72015-01-15 15:00:30 +0800564 'Unexpected shutdown. '
565 'Tail of /var/log/messages before last reboot:\n'
566 '%s', ('\n'.join(
567 ' ' + x for x in var_log_messages)))
Jon Salz0697cbf2012-07-04 15:14:04 +0800568 except: # pylint: disable=W0702
569 logging.exception('Unable to grok /var/log/messages')
570 var_log_messages = []
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800571
Hung-Te Linf5f2d7f2016-01-08 17:12:46 +0800572 if mosys_log is None and not sys_utils.InChroot():
Jon Salz008f4ea2012-08-28 05:39:45 +0800573 try:
Hung-Te Lin4e6357c2016-01-08 14:32:00 +0800574 mosys_log = process_utils.Spawn(
Jon Salz008f4ea2012-08-28 05:39:45 +0800575 ['mosys', 'eventlog', 'list'],
576 read_stdout=True, log_stderr_on_error=True).stdout_data
577 # Write it to the log also.
578 logging.info('System eventlog from mosys:\n%s\n', mosys_log)
579 except: # pylint: disable=W0702
580 logging.exception('Unable to read mosys eventlog')
Vic Yanga9c32212012-08-16 20:07:54 +0800581
Vic Yange4c275d2012-08-28 01:50:20 +0800582 if ec_console_log is None:
Dean Liao88b93192014-10-23 19:37:41 +0800583 ec_console_log = self.log_ec_console()
Vic Yange4c275d2012-08-28 01:50:20 +0800584
Vic Yang079f9872013-07-01 11:32:00 +0800585 if ec_panic_info is None:
Dean Liao88b93192014-10-23 19:37:41 +0800586 ec_panic_info = self.log_ec_panic_info()
Vic Yang079f9872013-07-01 11:32:00 +0800587
Jon Salz0697cbf2012-07-04 15:14:04 +0800588 error_msg = 'Unexpected shutdown while test was running'
589 self.event_log.Log('end_test',
Ricky Liang45c73e72015-01-15 15:00:30 +0800590 path=test.path,
591 status=TestState.FAILED,
592 invocation=test.get_state().invocation,
593 error_msg=error_msg,
594 var_log_messages='\n'.join(var_log_messages),
595 mosys_log=mosys_log)
Jon Salz0697cbf2012-07-04 15:14:04 +0800596 test.update_state(
Ricky Liang45c73e72015-01-15 15:00:30 +0800597 status=TestState.FAILED,
598 error_msg=error_msg)
Chun-Ta Lin87c2dac2015-05-02 01:35:01 -0700599 # Trigger the OnTestFailure callback.
Claire Changd1961a22015-08-05 16:15:55 +0800600 self.run_queue.put(lambda: self.test_fail(test))
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800601
Jon Salz50efe942012-07-26 11:54:10 +0800602 if not test.never_fails:
603 # For "never_fails" tests (such as "Start"), don't cancel
604 # pending tests, since reboot is expected.
605 factory.console.info('Unexpected shutdown while test %s '
606 'running; cancelling any pending tests',
607 test.path)
608 self.state_instance.set_shared_data('tests_after_shutdown', [])
Jon Salz69806bb2012-07-20 18:05:02 +0800609
Jon Salz008f4ea2012-08-28 05:39:45 +0800610 self.update_skipped_tests()
611
612 def update_skipped_tests(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800613 """Updates skipped states based on run_if."""
Jon Salz885dcac2013-07-23 16:39:50 +0800614 env = TestArgEnv()
Ricky Liang45c73e72015-01-15 15:00:30 +0800615
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800616 def _evaluate_skip_from_run_if(test):
617 """Returns the run_if evaluation of the test.
618
619 Args:
620 test: A FactoryTest object.
621
622 Returns:
623 The run_if evaluation result. Returns False if the test has no
624 run_if argument.
625 """
626 value = None
627 if test.run_if_expr:
628 try:
629 value = test.run_if_expr(env)
630 except: # pylint: disable=W0702
631 logging.exception('Unable to evaluate run_if expression for %s',
632 test.path)
633 # But keep going; we have no choice. This will end up
634 # always activating the test.
635 elif test.run_if_table_name:
636 try:
637 aux = shopfloor.get_selected_aux_data(test.run_if_table_name)
638 value = aux.get(test.run_if_col)
639 except ValueError:
640 # Not available; assume it shouldn't be skipped
641 pass
642
643 if value is None:
644 skip = False
645 else:
646 skip = (not value) ^ t.run_if_not
647 return skip
648
649 # Gets all run_if evaluation, and stores results in skip_map.
650 skip_map = dict()
Jon Salz008f4ea2012-08-28 05:39:45 +0800651 for t in self.test_list.walk():
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800652 skip_map[t.path] = _evaluate_skip_from_run_if(t)
Jon Salz885dcac2013-07-23 16:39:50 +0800653
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800654 # Propagates the skip value from root of tree and updates skip_map.
655 def _update_skip_map_from_node(test, skip_from_parent):
656 """Updates skip_map from a given node.
Jon Salz885dcac2013-07-23 16:39:50 +0800657
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800658 Given a FactoryTest node and the skip value from parent, updates the
659 skip value of current node in the skip_map if skip value from parent is
660 True. If this node has children, recursively propagate this value to all
661 its children, that is, all its subtests.
662 Note that this function only updates value in skip_map, not the actual
663 test_list tree.
Jon Salz008f4ea2012-08-28 05:39:45 +0800664
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800665 Args:
666 test: The given FactoryTest object. It is a node in the test_list tree.
667 skip_from_parent: The skip value which propagates from the parent of
668 input node.
669 """
670 skip_this_tree = skip_from_parent or skip_map[test.path]
671 if skip_this_tree:
672 logging.info('Skip from node %r', test.path)
673 skip_map[test.path] = True
674 if test.is_leaf():
675 return
676 # Propagates skip value to its subtests
677 for subtest in test.subtests:
678 _update_skip_map_from_node(subtest, skip_this_tree)
679
680 _update_skip_map_from_node(self.test_list, False)
681
682 # Updates the skip value from skip_map to test_list tree. Also, updates test
683 # status if needed.
684 for t in self.test_list.walk():
685 skip = skip_map[t.path]
686 test_state = t.get_state()
687 if ((not skip) and
688 (test_state.status == TestState.PASSED) and
689 (test_state.error_msg == TestState.SKIPPED_MSG)):
690 # It was marked as skipped before, but now we need to run it.
691 # Mark as untested.
692 t.update_state(skip=skip, status=TestState.UNTESTED, error_msg='')
693 else:
694 t.update_state(skip=skip)
Jon Salz008f4ea2012-08-28 05:39:45 +0800695
Jon Salz0697cbf2012-07-04 15:14:04 +0800696 def show_next_active_test(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800697 """Rotates to the next visible active test."""
Jon Salz0697cbf2012-07-04 15:14:04 +0800698 self.reap_completed_tests()
699 active_tests = [
Ricky Liang45c73e72015-01-15 15:00:30 +0800700 t for t in self.test_list.walk()
701 if t.is_leaf() and t.get_state().status == TestState.ACTIVE]
Jon Salz0697cbf2012-07-04 15:14:04 +0800702 if not active_tests:
703 return
Jon Salz4f6c7172012-06-11 20:45:36 +0800704
Jon Salz0697cbf2012-07-04 15:14:04 +0800705 try:
706 next_test = active_tests[
Ricky Liang45c73e72015-01-15 15:00:30 +0800707 (active_tests.index(self.visible_test) + 1) % len(active_tests)]
Jon Salz0697cbf2012-07-04 15:14:04 +0800708 except ValueError: # visible_test not present in active_tests
709 next_test = active_tests[0]
Jon Salz4f6c7172012-06-11 20:45:36 +0800710
Jon Salz0697cbf2012-07-04 15:14:04 +0800711 self.set_visible_test(next_test)
Jon Salz4f6c7172012-06-11 20:45:36 +0800712
Jon Salz0697cbf2012-07-04 15:14:04 +0800713 def handle_event(self, event):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800714 """Handles an event from the event server."""
Jon Salz0697cbf2012-07-04 15:14:04 +0800715 handler = self.event_handlers.get(event.type)
716 if handler:
717 handler(event)
718 else:
719 # We don't register handlers for all event types - just ignore
720 # this event.
721 logging.debug('Unbound event type %s', event.type)
Jon Salz4f6c7172012-06-11 20:45:36 +0800722
Vic Yangaabf9fd2013-04-09 18:56:13 +0800723 def check_critical_factory_note(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800724 """Returns True if the last factory note is critical."""
Vic Yangaabf9fd2013-04-09 18:56:13 +0800725 notes = self.state_instance.get_shared_data('factory_note', True)
726 return notes and notes[-1]['level'] == 'CRITICAL'
727
Hung-Te Linef7f2be2015-07-20 20:38:51 +0800728 def schedule_restart(self):
729 """Schedules a restart event when any invocation is completed."""
730 self.is_restart_requested = True
731
732 def invocation_completion(self):
733 """Callback when an invocation is completed."""
734 if self.is_restart_requested:
735 logging.info('Restart by scheduled event.')
736 self.is_restart_requested = False
737 self.restart_tests()
738 else:
739 self.run_next_test()
740
Jon Salz0697cbf2012-07-04 15:14:04 +0800741 def run_next_test(self):
henryhsu4cc6b022014-04-22 17:12:42 +0800742 """Runs the next eligible test (or tests) in self.tests_to_run.
743
744 We have three kinds of the next eligible test:
745 1. normal
746 2. backgroundable
747 3. force_background
748
749 And we have four situations of the ongoing invocations:
750 a. only a running normal test
751 b. all running tests are backgroundable
752 c. all running tests are force_background
753 d. all running tests are any combination of backgroundable and
754 force_background
755
756 When a test would like to be run, it must follow the rules:
757 [1] cannot run with [abd]
758 [2] cannot run with [a]
759 All the other combinations are allowed
760 """
Jon Salz0697cbf2012-07-04 15:14:04 +0800761 self.reap_completed_tests()
Vic Yangaabf9fd2013-04-09 18:56:13 +0800762 if self.tests_to_run and self.check_critical_factory_note():
763 self.tests_to_run.clear()
764 return
Jon Salz0697cbf2012-07-04 15:14:04 +0800765 while self.tests_to_run:
Ricky Liang6fe218c2013-12-27 15:17:17 +0800766 logging.debug('Tests to run: %s', [x.path for x in self.tests_to_run])
Jon Salz94eb56f2012-06-12 18:01:12 +0800767
Jon Salz0697cbf2012-07-04 15:14:04 +0800768 test = self.tests_to_run[0]
Jon Salz94eb56f2012-06-12 18:01:12 +0800769
Jon Salz0697cbf2012-07-04 15:14:04 +0800770 if test in self.invocations:
771 logging.info('Next test %s is already running', test.path)
772 self.tests_to_run.popleft()
773 return
Jon Salz94eb56f2012-06-12 18:01:12 +0800774
Jon Salza1412922012-07-23 16:04:17 +0800775 for requirement in test.require_run:
776 for i in requirement.test.walk():
777 if i.get_state().status == TestState.ACTIVE:
Jon Salz304a75d2012-07-06 11:14:15 +0800778 logging.info('Waiting for active test %s to complete '
Jon Salza1412922012-07-23 16:04:17 +0800779 'before running %s', i.path, test.path)
Jon Salz304a75d2012-07-06 11:14:15 +0800780 return
781
henryhsu4cc6b022014-04-22 17:12:42 +0800782 def is_normal_test(test):
783 return not (test.backgroundable or test.force_background)
784
785 # [1] cannot run with [abd].
786 if self.invocations and is_normal_test(test) and any(
787 [not x.force_background for x in self.invocations]):
788 logging.info('Waiting for non-force_background tests to '
789 'complete before running %s', test.path)
790 return
791
792 # [2] cannot run with [a].
793 if self.invocations and test.backgroundable and any(
794 [is_normal_test(x) for x in self.invocations]):
795 logging.info('Waiting for normal tests to '
796 'complete before running %s', test.path)
Jon Salz0697cbf2012-07-04 15:14:04 +0800797 return
Jon Salz94eb56f2012-06-12 18:01:12 +0800798
Jon Salz3e6f5202012-10-15 15:08:29 +0800799 if test.get_state().skip:
800 factory.console.info('Skipping test %s', test.path)
801 test.update_state(status=TestState.PASSED,
802 error_msg=TestState.SKIPPED_MSG)
803 self.tests_to_run.popleft()
804 continue
805
Jon Salz0697cbf2012-07-04 15:14:04 +0800806 self.tests_to_run.popleft()
Jon Salz94eb56f2012-06-12 18:01:12 +0800807
Jon Salz304a75d2012-07-06 11:14:15 +0800808 untested = set()
Jon Salza1412922012-07-23 16:04:17 +0800809 for requirement in test.require_run:
810 for i in requirement.test.walk():
811 if i == test:
Jon Salz304a75d2012-07-06 11:14:15 +0800812 # We've hit this test itself; stop checking
813 break
Jon Salza1412922012-07-23 16:04:17 +0800814 if ((i.get_state().status == TestState.UNTESTED) or
815 (requirement.passed and i.get_state().status !=
816 TestState.PASSED)):
Jon Salz304a75d2012-07-06 11:14:15 +0800817 # Found an untested test; move on to the next
818 # element in require_run.
Jon Salza1412922012-07-23 16:04:17 +0800819 untested.add(i)
Jon Salz304a75d2012-07-06 11:14:15 +0800820 break
821
822 if untested:
823 untested_paths = ', '.join(sorted([x.path for x in untested]))
824 if self.state_instance.get_shared_data('engineering_mode',
825 optional=True):
826 # In engineering mode, we'll let it go.
827 factory.console.warn('In engineering mode; running '
828 '%s even though required tests '
829 '[%s] have not completed',
830 test.path, untested_paths)
831 else:
832 # Not in engineering mode; mark it failed.
833 error_msg = ('Required tests [%s] have not been run yet'
834 % untested_paths)
835 factory.console.error('Not running %s: %s',
836 test.path, error_msg)
837 test.update_state(status=TestState.FAILED,
838 error_msg=error_msg)
839 continue
840
Ricky Liang48e47f92014-02-26 19:31:51 +0800841 if (isinstance(test, factory.ShutdownStep) and
Ricky Liangb7eb8772014-09-15 18:05:22 +0800842 self.state_instance.get_shared_data(
843 state.POST_SHUTDOWN_TAG % test.path, optional=True)):
Ricky Liang48e47f92014-02-26 19:31:51 +0800844 # Invoking post shutdown method of shutdown test. We should retain the
845 # iterations_left and retries_left of the original test state.
846 test_state = self.state_instance.get_test_state(test.path)
847 self._run_test(test, test_state.iterations_left,
848 test_state.retries_left)
849 else:
850 # Starts a new test run; reset iterations and retries.
851 self._run_test(test, test.iterations, test.retries)
Jon Salz1acc8742012-07-17 17:45:55 +0800852
Cheng-Yi Chiangce05c002013-04-04 02:13:17 +0800853 def _run_test(self, test, iterations_left=None, retries_left=None):
Vic Yanga3cecf82014-12-26 00:44:21 -0800854 if not self._ui_initialized and not test.is_no_host():
855 self.init_ui()
Vic Yang08505c72015-01-06 17:01:53 -0800856 invoc = TestInvocation(
Hung-Te Linef7f2be2015-07-20 20:38:51 +0800857 self, test, on_completion=self.invocation_completion,
Claire Changd1961a22015-08-05 16:15:55 +0800858 on_test_failure=lambda: self.test_fail(test))
Jon Salz1acc8742012-07-17 17:45:55 +0800859 new_state = test.update_state(
Ricky Liang48e47f92014-02-26 19:31:51 +0800860 status=TestState.ACTIVE, increment_count=1, error_msg='',
861 invocation=invoc.uuid, iterations_left=iterations_left,
862 retries_left=retries_left,
863 visible=(self.visible_test == test))
Jon Salz1acc8742012-07-17 17:45:55 +0800864 invoc.count = new_state.count
865
866 self.invocations[test] = invoc
867 if self.visible_test is None and test.has_ui:
868 self.set_visible_test(test)
Vic Yang311ddb82012-09-26 12:08:28 +0800869 self.check_exclusive()
Jon Salz1acc8742012-07-17 17:45:55 +0800870 invoc.start()
Jon Salz5f2a0672012-05-22 17:14:06 +0800871
Vic Yang311ddb82012-09-26 12:08:28 +0800872 def check_exclusive(self):
Jon Salzce6a7f82013-06-10 18:22:54 +0800873 # alias since this is really long
874 EXCL_OPT = factory.FactoryTest.EXCLUSIVE_OPTIONS
875
Vic Yang311ddb82012-09-26 12:08:28 +0800876 current_exclusive_items = set([
Jon Salzce6a7f82013-06-10 18:22:54 +0800877 item for item in EXCL_OPT
Vic Yang311ddb82012-09-26 12:08:28 +0800878 if any([test.is_exclusive(item) for test in self.invocations])])
879
880 new_exclusive_items = current_exclusive_items - self.exclusive_items
Jon Salzce6a7f82013-06-10 18:22:54 +0800881 if EXCL_OPT.NETWORKING in new_exclusive_items:
Vic Yang311ddb82012-09-26 12:08:28 +0800882 logging.info('Disabling network')
883 self.connection_manager.DisableNetworking()
Jon Salzce6a7f82013-06-10 18:22:54 +0800884 if EXCL_OPT.CHARGER in new_exclusive_items:
Vic Yang311ddb82012-09-26 12:08:28 +0800885 logging.info('Stop controlling charger')
886
887 new_non_exclusive_items = self.exclusive_items - current_exclusive_items
Jon Salzce6a7f82013-06-10 18:22:54 +0800888 if EXCL_OPT.NETWORKING in new_non_exclusive_items:
Vic Yang311ddb82012-09-26 12:08:28 +0800889 logging.info('Re-enabling network')
890 self.connection_manager.EnableNetworking()
Jon Salzce6a7f82013-06-10 18:22:54 +0800891 if EXCL_OPT.CHARGER in new_non_exclusive_items:
Vic Yang311ddb82012-09-26 12:08:28 +0800892 logging.info('Start controlling charger')
893
Jon Salzce6a7f82013-06-10 18:22:54 +0800894 if self.cpufreq_manager:
895 enabled = EXCL_OPT.CPUFREQ not in current_exclusive_items
896 try:
897 self.cpufreq_manager.SetEnabled(enabled)
898 except: # pylint: disable=W0702
899 logging.exception('Unable to %s cpufreq services',
900 'enable' if enabled else 'disable')
901
Ricky Liang0f9978e2015-01-30 08:19:17 +0000902 # Only adjust charge state if not excluded
903 if (EXCL_OPT.CHARGER not in current_exclusive_items and
Hung-Te Linf5f2d7f2016-01-08 17:12:46 +0800904 not sys_utils.InChroot()):
Ricky Liang0f9978e2015-01-30 08:19:17 +0000905 if self.charge_manager:
Cheng-Yi Chiangd8186952013-04-04 23:41:14 +0800906 self.charge_manager.AdjustChargeState()
907 else:
Dean Liao88b93192014-10-23 19:37:41 +0800908 self.charge()
Vic Yang311ddb82012-09-26 12:08:28 +0800909
910 self.exclusive_items = current_exclusive_items
Jon Salz5da61e62012-05-31 13:06:22 +0800911
Dean Liao88b93192014-10-23 19:37:41 +0800912 def charge(self):
913 """Charges the board.
914
915 It won't try again if last time SetChargeState raised an exception.
916 """
917 if not self._can_charge:
918 return
919
920 try:
Ricky Liang9ac35e02015-01-30 16:01:32 +0800921 if self.charge_manager:
922 self.charge_manager.StartCharging()
923 else:
Hung-Te Lin6a72c642015-12-13 22:09:09 +0800924 self.dut.power.SetChargeState(self.dut.power.ChargeState.CHARGE)
Dean Liao88b93192014-10-23 19:37:41 +0800925 except NotImplementedError:
926 logging.info('Charging is not supported')
927 self._can_charge = False
Hung-Te Lin6a72c642015-12-13 22:09:09 +0800928 except dut.DUTException:
Dean Liao88b93192014-10-23 19:37:41 +0800929 logging.exception('Unable to set charge state on this board')
930 self._can_charge = False
931
cychiang21886742012-07-05 15:16:32 +0800932 def check_for_updates(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800933 """Schedules an asynchronous check for updates if necessary."""
cychiang21886742012-07-05 15:16:32 +0800934 if not self.test_list.options.update_period_secs:
935 # Not enabled.
936 return
937
938 now = time.time()
939 if self.last_update_check and (
940 now - self.last_update_check <
941 self.test_list.options.update_period_secs):
942 # Not yet time for another check.
943 return
944
945 self.last_update_check = now
946
947 def handle_check_for_update(reached_shopfloor, md5sum, needs_update):
948 if reached_shopfloor:
949 new_update_md5sum = md5sum if needs_update else None
Hung-Te Line594e5d2015-12-16 02:36:05 +0800950 if self.dut.info.update_md5sum != new_update_md5sum:
cychiang21886742012-07-05 15:16:32 +0800951 logging.info('Received new update MD5SUM: %s', new_update_md5sum)
Hung-Te Line594e5d2015-12-16 02:36:05 +0800952 self.dut.info.Overrides('update_md5sum', new_update_md5sum)
Peter Ammon1e1ec572014-06-26 17:56:32 -0700953 self.run_enqueue(self.update_system_info)
Cheng-Yi Chiang194d3c02015-03-16 14:37:15 +0800954 else:
955 if not self._suppress_periodic_update_messages:
956 logging.warning('Suppress error messages for periodic update checking'
957 ' after the first one.')
958 self._suppress_periodic_update_messages = True
cychiang21886742012-07-05 15:16:32 +0800959
960 updater.CheckForUpdateAsync(
Ricky Liang45c73e72015-01-15 15:00:30 +0800961 handle_check_for_update,
Cheng-Yi Chiang194d3c02015-03-16 14:37:15 +0800962 self.test_list.options.shopfloor_timeout_secs,
963 self._suppress_periodic_update_messages)
cychiang21886742012-07-05 15:16:32 +0800964
Jon Salza6711d72012-07-18 14:33:03 +0800965 def cancel_pending_tests(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800966 """Cancels any tests in the run queue."""
Jon Salza6711d72012-07-18 14:33:03 +0800967 self.run_tests([])
968
Ricky Liang4bff3e32014-02-20 18:46:11 +0800969 def restore_active_run_state(self):
970 """Restores active run id and the list of scheduled tests."""
971 self.run_id = self.state_instance.get_shared_data('run_id', optional=True)
972 self.scheduled_run_tests = self.state_instance.get_shared_data(
973 'scheduled_run_tests', optional=True)
974
975 def set_active_run_state(self):
976 """Sets active run id and the list of scheduled tests."""
977 self.run_id = str(uuid.uuid4())
978 self.scheduled_run_tests = [test.path for test in self.tests_to_run]
979 self.state_instance.set_shared_data('run_id', self.run_id)
980 self.state_instance.set_shared_data('scheduled_run_tests',
981 self.scheduled_run_tests)
982
Chih-Yu Huang85dc63c2015-08-12 15:21:28 +0800983 def run_tests(self, subtrees, status_filter=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800984 """Runs tests under subtree.
Jon Salz258a40c2012-04-19 12:34:01 +0800985
Jon Salz0697cbf2012-07-04 15:14:04 +0800986 The tests are run in order unless one fails (then stops).
987 Backgroundable tests are run simultaneously; when a foreground test is
988 encountered, we wait for all active tests to finish before continuing.
Jon Salzb1b39092012-05-03 02:05:09 +0800989
Ricky Liang6fe218c2013-12-27 15:17:17 +0800990 Args:
991 subtrees: Node or nodes containing tests to run (may either be
992 a single test or a list). Duplicates will be ignored.
Chih-Yu Huang85dc63c2015-08-12 15:21:28 +0800993 status_filter: List of available test states. Only run the tests which
994 states are in the list. Set to None if all test states are available.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800995 """
Hung-Te Lin410f70a2015-12-15 14:53:42 +0800996 self.dut.hooks.OnTestStart()
Vic Yang08505c72015-01-06 17:01:53 -0800997
Jon Salz0697cbf2012-07-04 15:14:04 +0800998 if type(subtrees) != list:
999 subtrees = [subtrees]
Jon Salz258a40c2012-04-19 12:34:01 +08001000
Jon Salz0697cbf2012-07-04 15:14:04 +08001001 # Nodes we've seen so far, to avoid duplicates.
1002 seen = set()
Jon Salz94eb56f2012-06-12 18:01:12 +08001003
Jon Salz0697cbf2012-07-04 15:14:04 +08001004 self.tests_to_run = deque()
1005 for subtree in subtrees:
1006 for test in subtree.walk():
1007 if test in seen:
1008 continue
1009 seen.add(test)
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001010
Jon Salz0697cbf2012-07-04 15:14:04 +08001011 if not test.is_leaf():
1012 continue
Chih-Yu Huang85dc63c2015-08-12 15:21:28 +08001013 if (status_filter is not None and
1014 test.get_state().status not in status_filter):
Jon Salz0697cbf2012-07-04 15:14:04 +08001015 continue
1016 self.tests_to_run.append(test)
Ricky Liang4bff3e32014-02-20 18:46:11 +08001017 if subtrees:
1018 self.set_active_run_state()
Jon Salz0697cbf2012-07-04 15:14:04 +08001019 self.run_next_test()
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001020
Jon Salz0697cbf2012-07-04 15:14:04 +08001021 def reap_completed_tests(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001022 """Removes completed tests from the set of active tests.
Jon Salz0697cbf2012-07-04 15:14:04 +08001023
1024 Also updates the visible test if it was reaped.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001025 """
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +08001026 test_completed = False
Jon Salz0697cbf2012-07-04 15:14:04 +08001027 for t, v in dict(self.invocations).iteritems():
1028 if v.is_completed():
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +08001029 test_completed = True
Jon Salz1acc8742012-07-17 17:45:55 +08001030 new_state = t.update_state(**v.update_state_on_completion)
Jon Salz0697cbf2012-07-04 15:14:04 +08001031 del self.invocations[t]
1032
Johny Lin62ed2a32015-05-13 11:57:12 +08001033 # Stop on failure if flag is true and there is no retry chances.
Chun-Ta Lin54e17e42012-09-06 22:05:13 +08001034 if (self.test_list.options.stop_on_failure and
Johny Lin62ed2a32015-05-13 11:57:12 +08001035 new_state.retries_left < 0 and
Chun-Ta Lin54e17e42012-09-06 22:05:13 +08001036 new_state.status == TestState.FAILED):
1037 # Clean all the tests to cause goofy to stop.
1038 self.tests_to_run = []
Ricky Liang45c73e72015-01-15 15:00:30 +08001039 factory.console.info('Stop on failure triggered. Empty the queue.')
Chun-Ta Lin54e17e42012-09-06 22:05:13 +08001040
Jon Salz1acc8742012-07-17 17:45:55 +08001041 if new_state.iterations_left and new_state.status == TestState.PASSED:
1042 # Play it again, Sam!
1043 self._run_test(t)
Cheng-Yi Chiangce05c002013-04-04 02:13:17 +08001044 # new_state.retries_left is obtained after update.
1045 # For retries_left == 0, test can still be run for the last time.
1046 elif (new_state.retries_left >= 0 and
1047 new_state.status == TestState.FAILED):
1048 # Still have to retry, Sam!
1049 self._run_test(t)
Jon Salz1acc8742012-07-17 17:45:55 +08001050
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +08001051 if test_completed:
Vic Yangf01c59f2013-04-19 17:37:56 +08001052 self.log_watcher.KickWatchThread()
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +08001053
Jon Salz0697cbf2012-07-04 15:14:04 +08001054 if (self.visible_test is None or
Jon Salz85a39882012-07-05 16:45:04 +08001055 self.visible_test not in self.invocations):
Jon Salz0697cbf2012-07-04 15:14:04 +08001056 self.set_visible_test(None)
1057 # Make the first running test, if any, the visible test
1058 for t in self.test_list.walk():
1059 if t in self.invocations:
1060 self.set_visible_test(t)
1061 break
1062
Jon Salz6dc031d2013-06-19 13:06:23 +08001063 def kill_active_tests(self, abort, root=None, reason=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001064 """Kills and waits for all active tests.
Jon Salz0697cbf2012-07-04 15:14:04 +08001065
Jon Salz85a39882012-07-05 16:45:04 +08001066 Args:
1067 abort: True to change state of killed tests to FAILED, False for
Jon Salz0697cbf2012-07-04 15:14:04 +08001068 UNTESTED.
Jon Salz85a39882012-07-05 16:45:04 +08001069 root: If set, only kills tests with root as an ancestor.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001070 reason: If set, the abort reason.
1071 """
Jon Salz0697cbf2012-07-04 15:14:04 +08001072 self.reap_completed_tests()
1073 for test, invoc in self.invocations.items():
Jon Salz85a39882012-07-05 16:45:04 +08001074 if root and not test.has_ancestor(root):
1075 continue
1076
Ricky Liang45c73e72015-01-15 15:00:30 +08001077 factory.console.info('Killing active test %s...', test.path)
Jon Salz6dc031d2013-06-19 13:06:23 +08001078 invoc.abort_and_join(reason)
Ricky Liang45c73e72015-01-15 15:00:30 +08001079 factory.console.info('Killed %s', test.path)
Jon Salz1acc8742012-07-17 17:45:55 +08001080 test.update_state(**invoc.update_state_on_completion)
Jon Salz0697cbf2012-07-04 15:14:04 +08001081 del self.invocations[test]
Jon Salz1acc8742012-07-17 17:45:55 +08001082
Jon Salz0697cbf2012-07-04 15:14:04 +08001083 if not abort:
1084 test.update_state(status=TestState.UNTESTED)
1085 self.reap_completed_tests()
1086
Jon Salz6dc031d2013-06-19 13:06:23 +08001087 def stop(self, root=None, fail=False, reason=None):
1088 self.kill_active_tests(fail, root, reason)
Jon Salz85a39882012-07-05 16:45:04 +08001089 # Remove any tests in the run queue under the root.
1090 self.tests_to_run = deque([x for x in self.tests_to_run
1091 if root and not x.has_ancestor(root)])
1092 self.run_next_test()
Jon Salz0697cbf2012-07-04 15:14:04 +08001093
Jon Salz4712ac72013-02-07 17:12:05 +08001094 def clear_state(self, root=None):
Jon Salzd7550792013-07-12 05:49:27 +08001095 if root is None:
1096 root = self.test_list
Jon Salz6dc031d2013-06-19 13:06:23 +08001097 self.stop(root, reason='Clearing test state')
Jon Salz4712ac72013-02-07 17:12:05 +08001098 for f in root.walk():
1099 if f.is_leaf():
1100 f.update_state(status=TestState.UNTESTED)
1101
Jon Salz6dc031d2013-06-19 13:06:23 +08001102 def abort_active_tests(self, reason=None):
1103 self.kill_active_tests(True, reason=reason)
Jon Salz0697cbf2012-07-04 15:14:04 +08001104
1105 def main(self):
Jon Salzeff94182013-06-19 15:06:28 +08001106 syslog.openlog('goofy')
1107
Jon Salz0697cbf2012-07-04 15:14:04 +08001108 try:
Jon Salzd7550792013-07-12 05:49:27 +08001109 self.status = Status.INITIALIZING
Jon Salz0697cbf2012-07-04 15:14:04 +08001110 self.init()
1111 self.event_log.Log('goofy_init',
Ricky Liang45c73e72015-01-15 15:00:30 +08001112 success=True)
Jon Salz0697cbf2012-07-04 15:14:04 +08001113 except:
1114 if self.event_log:
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001115 try:
Jon Salz0697cbf2012-07-04 15:14:04 +08001116 self.event_log.Log('goofy_init',
Ricky Liang45c73e72015-01-15 15:00:30 +08001117 success=False,
1118 trace=traceback.format_exc())
Jon Salz0697cbf2012-07-04 15:14:04 +08001119 except: # pylint: disable=W0702
1120 pass
1121 raise
1122
Jon Salzd7550792013-07-12 05:49:27 +08001123 self.status = Status.RUNNING
Jon Salzeff94182013-06-19 15:06:28 +08001124 syslog.syslog('Goofy (factory test harness) starting')
Chun-Ta Lin5d12b592015-06-30 00:54:23 -07001125 syslog.syslog('Boot sequence = %d' % GetBootSequence())
Jon Salz0697cbf2012-07-04 15:14:04 +08001126 self.run()
1127
1128 def update_system_info(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001129 """Updates system info."""
Hung-Te Line594e5d2015-12-16 02:36:05 +08001130 info = self.dut.info.GetAll()
1131 self.state_instance.set_shared_data('system_info', info)
Jon Salz0697cbf2012-07-04 15:14:04 +08001132 self.event_client.post_event(Event(Event.Type.SYSTEM_INFO,
Hung-Te Line594e5d2015-12-16 02:36:05 +08001133 system_info=info))
1134 logging.info('System info: %r', info)
Jon Salz0697cbf2012-07-04 15:14:04 +08001135
Jon Salzeb42f0d2012-07-27 19:14:04 +08001136 def update_factory(self, auto_run_on_restart=False, post_update_hook=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001137 """Commences updating factory software.
Jon Salzeb42f0d2012-07-27 19:14:04 +08001138
1139 Args:
1140 auto_run_on_restart: Auto-run when the machine comes back up.
1141 post_update_hook: Code to call after update but immediately before
1142 restart.
1143
1144 Returns:
1145 Never if the update was successful (we just reboot).
1146 False if the update was unnecessary (no update available).
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001147 """
Jon Salz6dc031d2013-06-19 13:06:23 +08001148 self.kill_active_tests(False, reason='Factory software update')
Jon Salza6711d72012-07-18 14:33:03 +08001149 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +08001150
Jon Salz5c344f62012-07-13 14:31:16 +08001151 def pre_update_hook():
1152 if auto_run_on_restart:
1153 self.state_instance.set_shared_data('tests_after_shutdown',
1154 FORCE_AUTO_RUN)
1155 self.state_instance.close()
1156
Jon Salzeb42f0d2012-07-27 19:14:04 +08001157 if updater.TryUpdate(pre_update_hook=pre_update_hook):
1158 if post_update_hook:
1159 post_update_hook()
1160 self.env.shutdown('reboot')
Jon Salz0697cbf2012-07-04 15:14:04 +08001161
Ricky Liang8fecf412014-05-22 10:56:14 +08001162 def handle_sigint(self, dummy_signum, dummy_frame): # pylint: disable=W0613
Jon Salz77c151e2012-08-28 07:20:37 +08001163 logging.error('Received SIGINT')
Peter Ammon1e1ec572014-06-26 17:56:32 -07001164 self.run_enqueue(None)
Jon Salz77c151e2012-08-28 07:20:37 +08001165 raise KeyboardInterrupt()
1166
Ricky Liang8fecf412014-05-22 10:56:14 +08001167 def handle_sigterm(self, dummy_signum, dummy_frame): # pylint: disable=W0613
1168 logging.error('Received SIGTERM')
Hung-Te Lin94ca4742014-07-09 20:13:50 +08001169 self.env.terminate()
1170 self.run_queue.put(None)
Ricky Liang8fecf412014-05-22 10:56:14 +08001171 raise RuntimeError('Received SIGTERM')
1172
Jon Salze12c2b32013-06-25 16:24:34 +08001173 def find_kcrashes(self):
1174 """Finds kcrash files, logs them, and marks them as seen."""
1175 seen_crashes = set(
1176 self.state_instance.get_shared_data('seen_crashes', optional=True)
1177 or [])
1178
1179 for path in glob.glob('/var/spool/crash/*'):
1180 if not os.path.isfile(path):
1181 continue
1182 if path in seen_crashes:
1183 continue
1184 try:
1185 stat = os.stat(path)
Hung-Te Lin4e6357c2016-01-08 14:32:00 +08001186 mtime = time_utils.TimeString(stat.st_mtime)
Jon Salze12c2b32013-06-25 16:24:34 +08001187 logging.info(
1188 'Found new crash file %s (%d bytes at %s)',
1189 path, stat.st_size, mtime)
1190 extra_log_args = {}
1191
1192 try:
1193 _, ext = os.path.splitext(path)
1194 if ext in ['.kcrash', '.meta']:
1195 ext = ext.replace('.', '')
1196 with open(path) as f:
1197 data = f.read(MAX_CRASH_FILE_SIZE)
1198 tell = f.tell()
1199 logging.info(
1200 'Contents of %s%s:%s',
1201 path,
1202 ('' if tell == stat.st_size
1203 else '(truncated to %d bytes)' % MAX_CRASH_FILE_SIZE),
1204 ('\n' + data).replace('\n', '\n ' + ext + '> '))
1205 extra_log_args['data'] = data
1206
1207 # Copy to /var/factory/kcrash for posterity
1208 kcrash_dir = factory.get_factory_root('kcrash')
Hung-Te Lin4e6357c2016-01-08 14:32:00 +08001209 file_utils.TryMakeDirs(kcrash_dir)
Jon Salze12c2b32013-06-25 16:24:34 +08001210 shutil.copy(path, kcrash_dir)
1211 logging.info('Copied to %s',
1212 os.path.join(kcrash_dir, os.path.basename(path)))
1213 finally:
1214 # Even if something goes wrong with the above, still try to
1215 # log to event log
1216 self.event_log.Log('crash_file',
1217 path=path, size=stat.st_size, mtime=mtime,
1218 **extra_log_args)
1219 except: # pylint: disable=W0702
1220 logging.exception('Unable to handle crash files %s', path)
1221 seen_crashes.add(path)
1222
1223 self.state_instance.set_shared_data('seen_crashes', list(seen_crashes))
1224
Jon Salz128b0932013-07-03 16:55:26 +08001225 def GetTestList(self, test_list_id):
1226 """Returns the test list with the given ID.
1227
1228 Raises:
1229 TestListError: The test list ID is not valid.
1230 """
1231 try:
1232 return self.test_lists[test_list_id]
1233 except KeyError:
1234 raise test_lists.TestListError(
1235 '%r is not a valid test list ID (available IDs are [%s])' % (
1236 test_list_id, ', '.join(sorted(self.test_lists.keys()))))
1237
1238 def InitTestLists(self):
1239 """Reads in all test lists and sets the active test list."""
Ricky Liang27051552014-05-04 14:22:26 +08001240 self.test_lists = test_lists.BuildAllTestLists(
1241 force_generic=(self.options.automation_mode is not None))
Jon Salzd7550792013-07-12 05:49:27 +08001242 logging.info('Loaded test lists: [%s]',
1243 test_lists.DescribeTestLists(self.test_lists))
Jon Salz128b0932013-07-03 16:55:26 +08001244
1245 if not self.options.test_list:
1246 self.options.test_list = test_lists.GetActiveTestListId()
1247
1248 if os.sep in self.options.test_list:
1249 # It's a path pointing to an old-style test list; use it.
1250 self.test_list = factory.read_test_list(self.options.test_list)
1251 else:
1252 self.test_list = self.GetTestList(self.options.test_list)
1253
1254 logging.info('Active test list: %s', self.test_list.test_list_id)
1255
1256 if isinstance(self.test_list, test_lists.OldStyleTestList):
1257 # Actually load it in. (See OldStyleTestList for an explanation
1258 # of why this is necessary.)
1259 self.test_list = self.test_list.Load()
1260
Wei-Han Chene8a025f2016-01-14 16:42:02 +08001261 if self.test_list.options.dut_options:
1262 logging.info('dut_options set by %s: %r', self.test_list.test_list_id,
1263 self.test_list.options.dut_options)
1264 dut_utils.PrepareLink(**self.test_list.options.dut_options)
1265
Jon Salz128b0932013-07-03 16:55:26 +08001266 self.test_list.state_instance = self.state_instance
1267
Shuo-Peng Liao268b40b2013-07-01 15:58:59 +08001268 def init_hooks(self):
1269 """Initializes hooks.
1270
1271 Must run after self.test_list ready.
1272 """
Shuo-Peng Liao52b90da2013-06-30 17:00:06 +08001273 module, cls = self.test_list.options.hooks_class.rsplit('.', 1)
1274 self.hooks = getattr(__import__(module, fromlist=[cls]), cls)()
1275 assert isinstance(self.hooks, factory.Hooks), (
Ricky Liang45c73e72015-01-15 15:00:30 +08001276 'hooks should be of type Hooks but is %r' % type(self.hooks))
Shuo-Peng Liao52b90da2013-06-30 17:00:06 +08001277 self.hooks.test_list = self.test_list
Shuo-Peng Liao268b40b2013-07-01 15:58:59 +08001278 self.hooks.OnCreatedTestList()
Shuo-Peng Liao52b90da2013-06-30 17:00:06 +08001279
Vic Yanga3cecf82014-12-26 00:44:21 -08001280 def init_ui(self):
1281 """Initialize UI."""
1282 self._ui_initialized = True
1283 if self.options.ui == 'chrome':
Hung-Te Lin8f6a3782015-01-06 22:58:32 +08001284 if self.options.monolithic:
Hung-Te Lin7bd55312014-12-30 16:43:36 +08001285 self.env.launch_chrome()
1286 else:
1287 # The presenter is responsible for launching Chrome. Let's just
1288 # wait here.
1289 self.env.controller_ready_for_ui()
Vic Yanga3cecf82014-12-26 00:44:21 -08001290 logging.info('Waiting for a web socket connection')
1291 self.web_socket_manager.wait()
1292
1293 # Wait for the test widget size to be set; this is done in
1294 # an asynchronous RPC so there is a small chance that the
1295 # web socket might be opened first.
1296 for _ in range(100): # 10 s
1297 try:
1298 if self.state_instance.get_shared_data('test_widget_size'):
1299 break
1300 except KeyError:
1301 pass # Retry
1302 time.sleep(0.1) # 100 ms
1303 else:
1304 logging.warn('Never received test_widget_size from UI')
1305
Hung-Te Lin7bd55312014-12-30 16:43:36 +08001306 logging.info('Waiting for a web socket connection')
1307 self.web_socket_manager.wait()
1308
Jon Salz0697cbf2012-07-04 15:14:04 +08001309 def init(self, args=None, env=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001310 """Initializes Goofy.
Jon Salz0697cbf2012-07-04 15:14:04 +08001311
1312 Args:
1313 args: A list of command-line arguments. Uses sys.argv if
1314 args is None.
1315 env: An Environment instance to use (or None to choose
1316 FakeChrootEnvironment or DUTEnvironment as appropriate).
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001317 """
Jon Salz0697cbf2012-07-04 15:14:04 +08001318 parser = OptionParser()
1319 parser.add_option('-v', '--verbose', dest='verbose',
Jon Salz8fa8e832012-07-13 19:04:09 +08001320 action='store_true',
1321 help='Enable debug logging')
Jon Salz0697cbf2012-07-04 15:14:04 +08001322 parser.add_option('--print_test_list', dest='print_test_list',
Jon Salz8fa8e832012-07-13 19:04:09 +08001323 metavar='FILE',
1324 help='Read and print test list FILE, and exit')
Jon Salz0697cbf2012-07-04 15:14:04 +08001325 parser.add_option('--restart', dest='restart',
Jon Salz8fa8e832012-07-13 19:04:09 +08001326 action='store_true',
1327 help='Clear all test state')
Jon Salz0697cbf2012-07-04 15:14:04 +08001328 parser.add_option('--ui', dest='ui', type='choice',
Jon Salz7b5482e2014-08-04 17:48:41 +08001329 choices=['none', 'chrome'],
Jon Salz2f881df2013-02-01 17:00:35 +08001330 default='chrome',
Jon Salz8fa8e832012-07-13 19:04:09 +08001331 help='UI to use')
Jon Salz0697cbf2012-07-04 15:14:04 +08001332 parser.add_option('--ui_scale_factor', dest='ui_scale_factor',
Jon Salz8fa8e832012-07-13 19:04:09 +08001333 type='int', default=1,
1334 help=('Factor by which to scale UI '
1335 '(Chrome UI only)'))
Jon Salz0697cbf2012-07-04 15:14:04 +08001336 parser.add_option('--test_list', dest='test_list',
Jon Salz8fa8e832012-07-13 19:04:09 +08001337 metavar='FILE',
1338 help='Use FILE as test list')
Jon Salzc79a9982012-08-30 04:42:01 +08001339 parser.add_option('--dummy_shopfloor', action='store_true',
1340 help='Use a dummy shopfloor server')
Hung-Te Lincc41d2a2014-10-29 13:35:20 +08001341 parser.add_option('--dummy_connection_manager', action='store_true',
1342 help='Use a dummy connection manager')
Ricky Liang6fe218c2013-12-27 15:17:17 +08001343 parser.add_option('--automation-mode',
1344 choices=[m.lower() for m in AutomationMode],
Ricky Liang45c73e72015-01-15 15:00:30 +08001345 default='none', help='Factory test automation mode.')
Ricky Liang117484a2014-04-14 11:14:41 +08001346 parser.add_option('--no-auto-run-on-start', dest='auto_run_on_start',
1347 action='store_false', default=True,
1348 help=('do not automatically run the test list on goofy '
1349 'start; this is only valid when factory test '
1350 'automation is enabled'))
Chun-Ta Lina8dd3172014-11-26 16:15:13 +08001351 parser.add_option('--handshake_timeout', dest='handshake_timeout',
1352 type='float', default=0.3,
1353 help=('RPC timeout when doing handshake between device '
1354 'and presenter.'))
Vic Yang7d693c42014-09-14 09:52:39 +08001355 parser.add_option('--standalone', dest='standalone',
1356 action='store_true', default=False,
1357 help=('Assume the presenter is running on the same '
1358 'machines.'))
Hung-Te Lin8f6a3782015-01-06 22:58:32 +08001359 parser.add_option('--monolithic', dest='monolithic',
1360 action='store_true', default=False,
1361 help='Run in monolithic mode (without presenter)')
Jon Salz0697cbf2012-07-04 15:14:04 +08001362 (self.options, self.args) = parser.parse_args(args)
1363
Hung-Te Lina846f602014-07-04 20:32:22 +08001364 signal.signal(signal.SIGINT, self.handle_sigint)
1365 # TODO(hungte) SIGTERM does not work properly without Telemetry and should
1366 # be fixed.
Hung-Te Lina846f602014-07-04 20:32:22 +08001367
Jon Salz46b89562012-07-05 11:49:22 +08001368 # Make sure factory directories exist.
1369 factory.get_log_root()
1370 factory.get_state_root()
1371 factory.get_test_data_root()
1372
Jon Salz0697cbf2012-07-04 15:14:04 +08001373 global _inited_logging # pylint: disable=W0603
1374 if not _inited_logging:
1375 factory.init_logging('goofy', verbose=self.options.verbose)
1376 _inited_logging = True
Jon Salz8fa8e832012-07-13 19:04:09 +08001377
Jon Salz0f996602012-10-03 15:26:48 +08001378 if self.options.print_test_list:
Joel Kitchingb85ed7f2014-10-08 18:24:39 +08001379 print(factory.read_test_list(
1380 self.options.print_test_list).__repr__(recursive=True))
Jon Salz0f996602012-10-03 15:26:48 +08001381 sys.exit(0)
1382
Jon Salzee85d522012-07-17 14:34:46 +08001383 event_log.IncrementBootSequence()
Jon Salzd15bbcf2013-05-21 17:33:57 +08001384 # Don't defer logging the initial event, so we can make sure
1385 # that device_id, reimage_id, etc. are all set up.
1386 self.event_log = EventLog('goofy', defer=False)
Jon Salz0697cbf2012-07-04 15:14:04 +08001387
Jon Salz0697cbf2012-07-04 15:14:04 +08001388 if env:
1389 self.env = env
Hung-Te Linf5f2d7f2016-01-08 17:12:46 +08001390 elif sys_utils.InChroot():
Jon Salz0697cbf2012-07-04 15:14:04 +08001391 self.env = test_environment.FakeChrootEnvironment()
1392 logging.warn(
Ricky Liang45c73e72015-01-15 15:00:30 +08001393 'Using chroot environment: will not actually run autotests')
Hung-Te Lina846f602014-07-04 20:32:22 +08001394 elif self.options.ui == 'chrome':
Ricky Liang09d66d82014-09-25 11:20:54 +08001395 self.env = test_environment.DUTEnvironment()
Jon Salz0697cbf2012-07-04 15:14:04 +08001396 self.env.goofy = self
Vic Yanga4931152014-08-11 16:36:24 -07001397 # web_socket_manager will be initialized later
1398 # pylint: disable=W0108
1399 self.env.has_sockets = lambda: self.web_socket_manager.has_sockets()
Jon Salz0697cbf2012-07-04 15:14:04 +08001400
1401 if self.options.restart:
1402 state.clear_state()
1403
Hung-Te Linf5f2d7f2016-01-08 17:12:46 +08001404 if self.options.ui_scale_factor != 1 and sys_utils.InQEMU():
Jon Salz0697cbf2012-07-04 15:14:04 +08001405 logging.warn(
Ricky Liang45c73e72015-01-15 15:00:30 +08001406 'In QEMU; ignoring ui_scale_factor argument')
Jon Salz0697cbf2012-07-04 15:14:04 +08001407 self.options.ui_scale_factor = 1
1408
1409 logging.info('Started')
1410
Hung-Te Lin8f6a3782015-01-06 22:58:32 +08001411 if not self.options.monolithic:
Hung-Te Lin7bd55312014-12-30 16:43:36 +08001412 self.link_manager = PresenterLinkManager(
1413 check_interval=1,
1414 handshake_timeout=self.options.handshake_timeout,
1415 standalone=self.options.standalone)
Peter Ammon1e1ec572014-06-26 17:56:32 -07001416
Jon Salz0697cbf2012-07-04 15:14:04 +08001417 self.start_state_server()
1418 self.state_instance.set_shared_data('hwid_cfg', get_hwid_cfg())
1419 self.state_instance.set_shared_data('ui_scale_factor',
Ricky Liang09216dc2013-02-22 17:26:45 +08001420 self.options.ui_scale_factor)
Jon Salz0697cbf2012-07-04 15:14:04 +08001421 self.last_shutdown_time = (
Ricky Liang45c73e72015-01-15 15:00:30 +08001422 self.state_instance.get_shared_data('shutdown_time', optional=True))
Jon Salz0697cbf2012-07-04 15:14:04 +08001423 self.state_instance.del_shared_data('shutdown_time', optional=True)
Jon Salzb19ea072013-02-07 16:35:00 +08001424 self.state_instance.del_shared_data('startup_error', optional=True)
Jon Salz0697cbf2012-07-04 15:14:04 +08001425
Ricky Liang6fe218c2013-12-27 15:17:17 +08001426 self.options.automation_mode = ParseAutomationMode(
1427 self.options.automation_mode)
1428 self.state_instance.set_shared_data('automation_mode',
1429 self.options.automation_mode)
1430 self.state_instance.set_shared_data(
1431 'automation_mode_prompt',
1432 AutomationModePrompt[self.options.automation_mode])
1433
Jon Salz128b0932013-07-03 16:55:26 +08001434 try:
1435 self.InitTestLists()
1436 except: # pylint: disable=W0702
1437 logging.exception('Unable to initialize test lists')
1438 self.state_instance.set_shared_data(
1439 'startup_error',
1440 'Unable to initialize test lists\n%s' % (
1441 traceback.format_exc()))
Jon Salzb19ea072013-02-07 16:35:00 +08001442 if self.options.ui == 'chrome':
1443 # Create an empty test list with default options so that the rest of
1444 # startup can proceed.
1445 self.test_list = factory.FactoryTestList(
1446 [], self.state_instance, factory.Options())
1447 else:
1448 # Bail with an error; no point in starting up.
1449 sys.exit('No valid test list; exiting.')
1450
Shuo-Peng Liao268b40b2013-07-01 15:58:59 +08001451 self.init_hooks()
1452
Jon Salz822838b2013-03-25 17:32:33 +08001453 if self.test_list.options.clear_state_on_start:
1454 self.state_instance.clear_test_state()
1455
Jon Salz670ce062014-05-16 15:53:50 +08001456 # If the phase is invalid, this will raise a ValueError.
1457 phase.SetPersistentPhase(self.test_list.options.phase)
1458
Dean Liao85ca86f2014-11-03 12:28:08 +08001459 # For netboot firmware, mainfw_type should be 'netboot'.
Hung-Te Line594e5d2015-12-16 02:36:05 +08001460 if (self.dut.info.mainfw_type != 'nonchrome' and
1461 self.dut.info.firmware_version is None):
Ricky Liang45c73e72015-01-15 15:00:30 +08001462 self.state_instance.set_shared_data(
1463 'startup_error',
Vic Yang9bd4f772013-06-04 17:34:00 +08001464 'Netboot firmware detected\n'
1465 'Connect Ethernet and reboot to re-image.\n'
1466 u'侦测到网路开机固件\n'
1467 u'请连接乙太网并重启')
1468
Jon Salz0697cbf2012-07-04 15:14:04 +08001469 if not self.state_instance.has_shared_data('ui_lang'):
1470 self.state_instance.set_shared_data('ui_lang',
Ricky Liang45c73e72015-01-15 15:00:30 +08001471 self.test_list.options.ui_lang)
Jon Salz0697cbf2012-07-04 15:14:04 +08001472 self.state_instance.set_shared_data(
Ricky Liang45c73e72015-01-15 15:00:30 +08001473 'test_list_options',
1474 self.test_list.options.__dict__)
Jon Salz0697cbf2012-07-04 15:14:04 +08001475 self.state_instance.test_list = self.test_list
1476
Cheng-Yi Chiang39d32ad2013-07-23 15:02:38 +08001477 self.check_log_rotation()
Jon Salz83ef34b2012-11-01 19:46:35 +08001478
Jon Salz23926422012-09-01 03:38:13 +08001479 if self.options.dummy_shopfloor:
Ricky Liang45c73e72015-01-15 15:00:30 +08001480 os.environ[shopfloor.SHOPFLOOR_SERVER_ENV_VAR_NAME] = (
1481 'http://%s:%d/' %
Joel Kitchingb85ed7f2014-10-08 18:24:39 +08001482 (net_utils.LOCALHOST, shopfloor.DEFAULT_SERVER_PORT))
Hung-Te Lin4e6357c2016-01-08 14:32:00 +08001483 self.dummy_shopfloor = process_utils.Spawn(
Wei-Han Chen2ebb92d2016-01-12 14:51:41 +08001484 [os.path.join(paths.FACTORY_PATH, 'bin', 'shopfloor_server'),
Jon Salz23926422012-09-01 03:38:13 +08001485 '--dummy'])
1486 elif self.test_list.options.shopfloor_server_url:
1487 shopfloor.set_server_url(self.test_list.options.shopfloor_server_url)
Jon Salz2bf2f6b2013-03-28 18:49:26 +08001488 shopfloor.set_enabled(True)
Jon Salz23926422012-09-01 03:38:13 +08001489
Hung-Te Linf5f2d7f2016-01-08 17:12:46 +08001490 if self.test_list.options.time_sanitizer and not sys_utils.InChroot():
Jon Salz8fa8e832012-07-13 19:04:09 +08001491 self.time_sanitizer = time_sanitizer.TimeSanitizer(
Ricky Liang45c73e72015-01-15 15:00:30 +08001492 base_time=time_sanitizer.GetBaseTimeFromFile(
1493 # lsb-factory is written by the factory install shim during
1494 # installation, so it should have a good time obtained from
1495 # the mini-Omaha server. If it's not available, we'll use
1496 # /etc/lsb-factory (which will be much older, but reasonably
1497 # sane) and rely on a shopfloor sync to set a more accurate
1498 # time.
1499 '/usr/local/etc/lsb-factory',
1500 '/etc/lsb-release'))
Jon Salz8fa8e832012-07-13 19:04:09 +08001501 self.time_sanitizer.RunOnce()
1502
Vic Yangd8990da2013-06-27 16:57:43 +08001503 if self.test_list.options.check_cpu_usage_period_secs:
Hung-Te Lin4e6357c2016-01-08 14:32:00 +08001504 self.cpu_usage_watcher = process_utils.Spawn(
Ricky Liang45c73e72015-01-15 15:00:30 +08001505 ['py/tools/cpu_usage_monitor.py', '-p',
1506 str(self.test_list.options.check_cpu_usage_period_secs)],
Wei-Han Chen2ebb92d2016-01-12 14:51:41 +08001507 cwd=paths.FACTORY_PATH)
Vic Yangd8990da2013-06-27 16:57:43 +08001508
Chun-Ta Lin5d12b592015-06-30 00:54:23 -07001509 # Enable thermal monitor
1510 if self.test_list.options.thermal_monitor_period_secs > 0:
Hung-Te Lin4e6357c2016-01-08 14:32:00 +08001511 self.cpu_usage_watcher = process_utils.Spawn(
Chun-Ta Lin5d12b592015-06-30 00:54:23 -07001512 ['py/tools/thermal_monitor.py',
1513 '-p', str(self.test_list.options.thermal_monitor_period_secs),
1514 '-d', str(self.test_list.options.thermal_monitor_delta)],
Wei-Han Chen2ebb92d2016-01-12 14:51:41 +08001515 cwd=paths.FACTORY_PATH)
Chun-Ta Lin5d12b592015-06-30 00:54:23 -07001516
Jon Salz0697cbf2012-07-04 15:14:04 +08001517 self.init_states()
1518 self.start_event_server()
Wei-Ning Huang38b75f02015-02-25 18:25:14 +08001519 self.start_terminal_server()
Hung-Te Lincc41d2a2014-10-29 13:35:20 +08001520
1521 if self.options.dummy_connection_manager:
1522 # Override network manager creation to dummy implmenetation.
1523 logging.info('Using dummy network manager (--dummy_connection_manager).')
1524 self.connection_manager = connection_manager.DummyConnectionManager()
1525 else:
1526 self.connection_manager = self.env.create_connection_manager(
1527 self.test_list.options.wlans,
Mao Huang4340c632015-04-14 14:35:22 +08001528 self.test_list.options.scan_wifi_period_secs,
1529 self.test_list.options.override_blacklisted_network_devices)
Hung-Te Lincc41d2a2014-10-29 13:35:20 +08001530
Jon Salz0697cbf2012-07-04 15:14:04 +08001531 # Note that we create a log watcher even if
1532 # sync_event_log_period_secs isn't set (no background
1533 # syncing), since we may use it to flush event logs as well.
1534 self.log_watcher = EventLogWatcher(
Ricky Liang45c73e72015-01-15 15:00:30 +08001535 self.test_list.options.sync_event_log_period_secs,
1536 event_log_db_file=None,
1537 handle_event_logs_callback=self.handle_event_logs)
Jon Salz0697cbf2012-07-04 15:14:04 +08001538 if self.test_list.options.sync_event_log_period_secs:
1539 self.log_watcher.StartWatchThread()
1540
Cheng-Yi Chianga0f6eff2014-01-09 18:27:22 +08001541 # Creates a system log manager to scan logs periocially.
1542 # A scan includes clearing logs and optionally syncing logs if
1543 # enable_syng_log is True. We kick it to sync logs.
1544 self.system_log_manager = SystemLogManager(
Ricky Liang45c73e72015-01-15 15:00:30 +08001545 sync_log_paths=self.test_list.options.sync_log_paths,
1546 sync_log_period_secs=self.test_list.options.sync_log_period_secs,
1547 scan_log_period_secs=self.test_list.options.scan_log_period_secs,
1548 clear_log_paths=self.test_list.options.clear_log_paths,
1549 clear_log_excluded_paths=self.test_list.options.clear_log_excluded_paths)
Cheng-Yi Chianga0f6eff2014-01-09 18:27:22 +08001550 self.system_log_manager.Start()
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +08001551
Jon Salz0697cbf2012-07-04 15:14:04 +08001552 self.update_system_info()
1553
Vic Yang4953fc12012-07-26 16:19:53 +08001554 assert ((self.test_list.options.min_charge_pct is None) ==
1555 (self.test_list.options.max_charge_pct is None))
Hung-Te Linf5f2d7f2016-01-08 17:12:46 +08001556 if sys_utils.InChroot():
Vic Yange83d9a12013-04-19 20:00:20 +08001557 logging.info('In chroot, ignoring charge manager and charge state')
Ricky Liangc392a1c2014-06-20 18:24:59 +08001558 elif (self.test_list.options.enable_charge_manager and
1559 self.test_list.options.min_charge_pct is not None):
Vic Yang4953fc12012-07-26 16:19:53 +08001560 self.charge_manager = ChargeManager(self.test_list.options.min_charge_pct,
1561 self.test_list.options.max_charge_pct)
Hung-Te Linc17b3d82015-12-15 15:26:08 +08001562 self.dut.status.Overrides('charge_manager', self.charge_manager)
Cheng-Yi Chiangd8186952013-04-04 23:41:14 +08001563 else:
1564 # Goofy should set charger state to charge if charge_manager is disabled.
Dean Liao88b93192014-10-23 19:37:41 +08001565 self.charge()
Vic Yang4953fc12012-07-26 16:19:53 +08001566
Vic Yang6cee2472014-10-22 17:18:52 -07001567 if CoreDumpManager.CoreDumpEnabled():
1568 self.core_dump_manager = CoreDumpManager(
1569 self.test_list.options.core_dump_watchlist)
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001570
Jon Salz0697cbf2012-07-04 15:14:04 +08001571 os.environ['CROS_FACTORY'] = '1'
1572 os.environ['CROS_DISABLE_SITE_SYSINFO'] = '1'
1573
Hung-Te Linf5f2d7f2016-01-08 17:12:46 +08001574 if not sys_utils.InChroot() and self.test_list.options.use_cpufreq_manager:
Ricky Liangecddbd42014-07-24 11:32:10 +08001575 logging.info('Enabling CPU frequency manager')
Jon Salzddf0d052013-06-18 12:52:44 +08001576 self.cpufreq_manager = CpufreqManager(event_log=self.event_log)
Jon Salzce6a7f82013-06-10 18:22:54 +08001577
Justin Chuang31b02432013-06-27 15:16:51 +08001578 # Startup hooks may want to skip some tests.
1579 self.update_skipped_tests()
Jon Salz416f9cc2013-05-10 18:32:50 +08001580
Jon Salze12c2b32013-06-25 16:24:34 +08001581 self.find_kcrashes()
1582
Shuo-Peng Liao268b40b2013-07-01 15:58:59 +08001583 # Should not move earlier.
1584 self.hooks.OnStartup()
1585
Ricky Liang36512a32014-07-25 11:47:04 +08001586 # Only after this point the Goofy backend is ready for UI connection.
1587 self.ready_for_ui_connection = True
1588
Ricky Liang650f6bf2012-09-28 13:22:54 +08001589 # Create download path for autotest beforehand or autotests run at
1590 # the same time might fail due to race condition.
Hung-Te Linf5f2d7f2016-01-08 17:12:46 +08001591 if not sys_utils.InChroot():
Hung-Te Lin4e6357c2016-01-08 14:32:00 +08001592 file_utils.TryMakeDirs(os.path.join('/usr/local/autotest', 'tests',
1593 'download'))
Ricky Liang650f6bf2012-09-28 13:22:54 +08001594
Jon Salz0697cbf2012-07-04 15:14:04 +08001595 def state_change_callback(test, test_state):
1596 self.event_client.post_event(
Ricky Liang4bff3e32014-02-20 18:46:11 +08001597 Event(Event.Type.STATE_CHANGE, path=test.path, state=test_state))
Jon Salz0697cbf2012-07-04 15:14:04 +08001598 self.test_list.state_change_callback = state_change_callback
Jon Salz73e0fd02012-04-04 11:46:38 +08001599
Vic Yange2c76a82014-10-30 12:48:19 -07001600 self.autotest_prespawner = prespawner.AutotestPrespawner()
1601 self.autotest_prespawner.start()
1602
1603 self.pytest_prespawner = prespawner.PytestPrespawner()
1604 self.pytest_prespawner.start()
Jon Salza6711d72012-07-18 14:33:03 +08001605
Ricky Liang48e47f92014-02-26 19:31:51 +08001606 tests_after_shutdown = self.state_instance.get_shared_data(
1607 'tests_after_shutdown', optional=True)
Jon Salz57717ca2012-04-04 16:47:25 +08001608
Jon Salz5c344f62012-07-13 14:31:16 +08001609 force_auto_run = (tests_after_shutdown == FORCE_AUTO_RUN)
1610 if not force_auto_run and tests_after_shutdown is not None:
Ricky Liang48e47f92014-02-26 19:31:51 +08001611 logging.info('Resuming tests after shutdown: %s', tests_after_shutdown)
Jon Salz0697cbf2012-07-04 15:14:04 +08001612 self.tests_to_run.extend(
Ricky Liang4bff3e32014-02-20 18:46:11 +08001613 self.test_list.lookup_path(t) for t in tests_after_shutdown)
Peter Ammon1e1ec572014-06-26 17:56:32 -07001614 self.run_enqueue(self.run_next_test)
Jon Salz0697cbf2012-07-04 15:14:04 +08001615 else:
Jon Salz5c344f62012-07-13 14:31:16 +08001616 if force_auto_run or self.test_list.options.auto_run_on_start:
Ricky Liang117484a2014-04-14 11:14:41 +08001617 # If automation mode is enabled, allow suppress auto_run_on_start.
1618 if (self.options.automation_mode == 'NONE' or
1619 self.options.auto_run_on_start):
Chih-Yu Huang85dc63c2015-08-12 15:21:28 +08001620 status_filter = [TestState.UNTESTED]
1621 if self.test_list.options.retry_failed_on_start:
1622 status_filter.append(TestState.FAILED)
1623 self.run_enqueue(lambda: self.run_tests(self.test_list, status_filter))
Jon Salz5c344f62012-07-13 14:31:16 +08001624 self.state_instance.set_shared_data('tests_after_shutdown', None)
Ricky Liang4bff3e32014-02-20 18:46:11 +08001625 self.restore_active_run_state()
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001626
Hung-Te Lin410f70a2015-12-15 14:53:42 +08001627 self.dut.hooks.OnTestStart()
Vic Yang08505c72015-01-06 17:01:53 -08001628
Dean Liao592e4d52013-01-10 20:06:39 +08001629 self.may_disable_cros_shortcut_keys()
1630
1631 def may_disable_cros_shortcut_keys(self):
1632 test_options = self.test_list.options
1633 if test_options.disable_cros_shortcut_keys:
1634 logging.info('Filter ChromeOS shortcut keys.')
1635 self.key_filter = KeyFilter(
1636 unmap_caps_lock=test_options.disable_caps_lock,
1637 caps_lock_keycode=test_options.caps_lock_keycode)
1638 self.key_filter.Start()
1639
Jon Salz0e6532d2012-10-25 16:30:11 +08001640 def _should_sync_time(self, foreground=False):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001641 """Returns True if we should attempt syncing time with shopfloor.
Jon Salz0e6532d2012-10-25 16:30:11 +08001642
1643 Args:
1644 foreground: If True, synchronizes even if background syncing
1645 is disabled (e.g., in explicit sync requests from the
1646 SyncShopfloor test).
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001647 """
Jon Salz0e6532d2012-10-25 16:30:11 +08001648 return ((foreground or
1649 self.test_list.options.sync_time_period_secs) and
Jon Salz54882d02012-08-31 01:57:54 +08001650 self.time_sanitizer and
1651 (not self.time_synced) and
Hung-Te Linf5f2d7f2016-01-08 17:12:46 +08001652 (not sys_utils.InChroot()))
Jon Salz54882d02012-08-31 01:57:54 +08001653
Jon Salz0e6532d2012-10-25 16:30:11 +08001654 def sync_time_with_shopfloor_server(self, foreground=False):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001655 """Syncs time with shopfloor server, if not yet synced.
Jon Salz54882d02012-08-31 01:57:54 +08001656
Jon Salz0e6532d2012-10-25 16:30:11 +08001657 Args:
1658 foreground: If True, synchronizes even if background syncing
1659 is disabled (e.g., in explicit sync requests from the
1660 SyncShopfloor test).
1661
Jon Salz54882d02012-08-31 01:57:54 +08001662 Returns:
1663 False if no time sanitizer is available, or True if this sync (or a
1664 previous sync) succeeded.
1665
1666 Raises:
1667 Exception if unable to contact the shopfloor server.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001668 """
Jon Salz0e6532d2012-10-25 16:30:11 +08001669 if self._should_sync_time(foreground):
Jon Salz54882d02012-08-31 01:57:54 +08001670 self.time_sanitizer.SyncWithShopfloor()
1671 self.time_synced = True
1672 return self.time_synced
1673
Jon Salzb92c5112012-09-21 15:40:11 +08001674 def log_disk_space_stats(self):
Hung-Te Linf5f2d7f2016-01-08 17:12:46 +08001675 if (sys_utils.InChroot() or
Jon Salz18e0e022013-06-11 17:13:39 +08001676 not self.test_list.options.log_disk_space_period_secs):
Jon Salzb92c5112012-09-21 15:40:11 +08001677 return
1678
1679 now = time.time()
1680 if (self.last_log_disk_space_time and
1681 now - self.last_log_disk_space_time <
1682 self.test_list.options.log_disk_space_period_secs):
1683 return
1684 self.last_log_disk_space_time = now
1685
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001686 # Upload event if stateful partition usage is above threshold.
1687 # Stateful partition is mounted on /usr/local, while
1688 # encrypted stateful partition is mounted on /var.
1689 # If there are too much logs in the factory process,
1690 # these two partitions might get full.
Jon Salzb92c5112012-09-21 15:40:11 +08001691 try:
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001692 vfs_infos = disk_space.GetAllVFSInfo()
1693 stateful_info, encrypted_info = None, None
1694 for vfs_info in vfs_infos.values():
1695 if '/usr/local' in vfs_info.mount_points:
1696 stateful_info = vfs_info
1697 if '/var' in vfs_info.mount_points:
1698 encrypted_info = vfs_info
1699
1700 stateful = disk_space.GetPartitionUsage(stateful_info)
1701 encrypted = disk_space.GetPartitionUsage(encrypted_info)
1702
Ricky Liang45c73e72015-01-15 15:00:30 +08001703 above_threshold = (
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001704 self.test_list.options.stateful_usage_threshold and
1705 max(stateful.bytes_used_pct,
1706 stateful.inodes_used_pct,
1707 encrypted.bytes_used_pct,
1708 encrypted.inodes_used_pct) >
Ricky Liang45c73e72015-01-15 15:00:30 +08001709 self.test_list.options.stateful_usage_threshold)
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001710
1711 if above_threshold:
1712 self.event_log.Log('stateful_partition_usage',
Ricky Liang45c73e72015-01-15 15:00:30 +08001713 partitions={
1714 'stateful': {
1715 'bytes_used_pct': FloatDigit(stateful.bytes_used_pct, 2),
1716 'inodes_used_pct': FloatDigit(stateful.inodes_used_pct, 2)},
1717 'encrypted_stateful': {
1718 'bytes_used_pct': FloatDigit(encrypted.bytes_used_pct, 2),
1719 'inodes_used_pct': FloatDigit(encrypted.inodes_used_pct, 2)}
1720 })
Cheng-Yi Chiang1b722322015-03-16 20:07:03 +08001721 self.log_watcher.KickWatchThread()
Hung-Te Linf5f2d7f2016-01-08 17:12:46 +08001722 if (not sys_utils.InChroot() and
Cheng-Yi Chiang00798e72013-06-20 18:16:39 +08001723 self.test_list.options.stateful_usage_above_threshold_action):
Hung-Te Lin4e6357c2016-01-08 14:32:00 +08001724 process_utils.Spawn(
1725 self.test_list.options.stateful_usage_above_threshold_action,
1726 call=True)
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001727
1728 message = disk_space.FormatSpaceUsedAll(vfs_infos)
Jon Salz3c493bb2013-02-07 17:24:58 +08001729 if message != self.last_log_disk_space_message:
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001730 if above_threshold:
1731 logging.warning(message)
1732 else:
1733 logging.info(message)
Jon Salz3c493bb2013-02-07 17:24:58 +08001734 self.last_log_disk_space_message = message
Jon Salzb92c5112012-09-21 15:40:11 +08001735 except: # pylint: disable=W0702
1736 logging.exception('Unable to get disk space used')
1737
Justin Chuang83813982013-05-13 01:26:32 +08001738 def check_battery(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001739 """Checks the current battery status.
Justin Chuang83813982013-05-13 01:26:32 +08001740
1741 Logs current battery charging level and status to log. If the battery level
1742 is lower below warning_low_battery_pct, send warning event to shopfloor.
1743 If the battery level is lower below critical_low_battery_pct, flush disks.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001744 """
Justin Chuang83813982013-05-13 01:26:32 +08001745 if not self.test_list.options.check_battery_period_secs:
1746 return
1747
1748 now = time.time()
1749 if (self.last_check_battery_time and
1750 now - self.last_check_battery_time <
1751 self.test_list.options.check_battery_period_secs):
1752 return
1753 self.last_check_battery_time = now
1754
1755 message = ''
1756 log_level = logging.INFO
1757 try:
Hung-Te Lin6a72c642015-12-13 22:09:09 +08001758 power = self.dut.power
Justin Chuang83813982013-05-13 01:26:32 +08001759 if not power.CheckBatteryPresent():
1760 message = 'Battery is not present'
1761 else:
1762 ac_present = power.CheckACPresent()
1763 charge_pct = power.GetChargePct(get_float=True)
1764 message = ('Current battery level %.1f%%, AC charger is %s' %
1765 (charge_pct, 'connected' if ac_present else 'disconnected'))
1766
1767 if charge_pct > self.test_list.options.critical_low_battery_pct:
1768 critical_low_battery = False
1769 else:
1770 critical_low_battery = True
1771 # Only sync disks when battery level is still above minimum
1772 # value. This can be used for offline analysis when shopfloor cannot
1773 # be connected.
1774 if charge_pct > MIN_BATTERY_LEVEL_FOR_DISK_SYNC:
1775 logging.warning('disk syncing for critical low battery situation')
1776 os.system('sync; sync; sync')
1777 else:
1778 logging.warning('disk syncing is cancelled '
1779 'because battery level is lower than %.1f',
1780 MIN_BATTERY_LEVEL_FOR_DISK_SYNC)
1781
1782 # Notify shopfloor server
1783 if (critical_low_battery or
1784 (not ac_present and
1785 charge_pct <= self.test_list.options.warning_low_battery_pct)):
1786 log_level = logging.WARNING
1787
1788 self.event_log.Log('low_battery',
1789 battery_level=charge_pct,
1790 charger_connected=ac_present,
1791 critical=critical_low_battery)
1792 self.log_watcher.KickWatchThread()
Cheng-Yi Chianga0f6eff2014-01-09 18:27:22 +08001793 if self.test_list.options.enable_sync_log:
1794 self.system_log_manager.KickToSync()
Ricky Liang45c73e72015-01-15 15:00:30 +08001795 except: # pylint: disable=W0702
Justin Chuang83813982013-05-13 01:26:32 +08001796 logging.exception('Unable to check battery or notify shopfloor')
1797 finally:
1798 if message != self.last_check_battery_message:
1799 logging.log(log_level, message)
1800 self.last_check_battery_message = message
1801
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001802 def check_core_dump(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001803 """Checks if there is any core dumped file.
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001804
1805 Removes unwanted core dump files immediately.
1806 Syncs those files matching watch list to server with a delay between
1807 each sync. After the files have been synced to server, deletes the files.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001808 """
Vic Yang6cee2472014-10-22 17:18:52 -07001809 if not self.core_dump_manager:
1810 return
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001811 core_dump_files = self.core_dump_manager.ScanFiles()
1812 if core_dump_files:
1813 now = time.time()
1814 if (self.last_kick_sync_time and now - self.last_kick_sync_time <
1815 self.test_list.options.kick_sync_min_interval_secs):
1816 return
1817 self.last_kick_sync_time = now
1818
1819 # Sends event to server
1820 self.event_log.Log('core_dumped', files=core_dump_files)
1821 self.log_watcher.KickWatchThread()
1822
1823 # Syncs files to server
Cheng-Yi Chianga0f6eff2014-01-09 18:27:22 +08001824 if self.test_list.options.enable_sync_log:
1825 self.system_log_manager.KickToSync(
Cheng-Yi Chiangd3516a32013-07-17 15:30:47 +08001826 core_dump_files, self.core_dump_manager.ClearFiles)
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001827
Cheng-Yi Chiang39d32ad2013-07-23 15:02:38 +08001828 def check_log_rotation(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001829 """Checks log rotation file presence/absence according to test_list option.
Cheng-Yi Chiang39d32ad2013-07-23 15:02:38 +08001830
1831 Touch /var/lib/cleanup_logs_paused if test_list.options.disable_log_rotation
1832 is True, delete it otherwise. This must be done in idle loop because
1833 autotest client will touch /var/lib/cleanup_logs_paused each time it runs
1834 an autotest.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001835 """
Hung-Te Linf5f2d7f2016-01-08 17:12:46 +08001836 if sys_utils.InChroot():
Cheng-Yi Chiang39d32ad2013-07-23 15:02:38 +08001837 return
1838 try:
1839 if self.test_list.options.disable_log_rotation:
1840 open(CLEANUP_LOGS_PAUSED, 'w').close()
1841 else:
1842 file_utils.TryUnlink(CLEANUP_LOGS_PAUSED)
1843 except: # pylint: disable=W0702
1844 # Oh well. Logs an error (but no trace)
1845 logging.info(
1846 'Unable to %s %s: %s',
1847 'touch' if self.test_list.options.disable_log_rotation else 'delete',
Hung-Te Linf707b242016-01-08 23:11:42 +08001848 CLEANUP_LOGS_PAUSED, debug_utils.FormatExceptionOnly())
Cheng-Yi Chiang39d32ad2013-07-23 15:02:38 +08001849
Jon Salz8fa8e832012-07-13 19:04:09 +08001850 def sync_time_in_background(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001851 """Writes out current time and tries to sync with shopfloor server."""
Jon Salzb22d1172012-08-06 10:38:57 +08001852 if not self.time_sanitizer:
1853 return
1854
1855 # Write out the current time.
1856 self.time_sanitizer.SaveTime()
1857
Jon Salz54882d02012-08-31 01:57:54 +08001858 if not self._should_sync_time():
Jon Salz8fa8e832012-07-13 19:04:09 +08001859 return
1860
1861 now = time.time()
1862 if self.last_sync_time and (
1863 now - self.last_sync_time <
1864 self.test_list.options.sync_time_period_secs):
1865 # Not yet time for another check.
1866 return
1867 self.last_sync_time = now
1868
1869 def target():
1870 try:
Jon Salz54882d02012-08-31 01:57:54 +08001871 self.sync_time_with_shopfloor_server()
Jon Salz8fa8e832012-07-13 19:04:09 +08001872 except: # pylint: disable=W0702
1873 # Oh well. Log an error (but no trace)
1874 logging.info(
Ricky Liang45c73e72015-01-15 15:00:30 +08001875 'Unable to get time from shopfloor server: %s',
Hung-Te Linf707b242016-01-08 23:11:42 +08001876 debug_utils.FormatExceptionOnly())
Jon Salz8fa8e832012-07-13 19:04:09 +08001877
1878 thread = threading.Thread(target=target)
1879 thread.daemon = True
1880 thread.start()
1881
Peter Ammon1e1ec572014-06-26 17:56:32 -07001882 def perform_periodic_tasks(self):
1883 """Override of base method to perform periodic work.
Vic Yang4953fc12012-07-26 16:19:53 +08001884
Peter Ammon1e1ec572014-06-26 17:56:32 -07001885 This method must not raise exceptions.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001886 """
Peter Ammon1e1ec572014-06-26 17:56:32 -07001887 super(Goofy, self).perform_periodic_tasks()
Jon Salzb22d1172012-08-06 10:38:57 +08001888
Vic Yang311ddb82012-09-26 12:08:28 +08001889 self.check_exclusive()
cychiang21886742012-07-05 15:16:32 +08001890 self.check_for_updates()
Jon Salz8fa8e832012-07-13 19:04:09 +08001891 self.sync_time_in_background()
Jon Salzb92c5112012-09-21 15:40:11 +08001892 self.log_disk_space_stats()
Justin Chuang83813982013-05-13 01:26:32 +08001893 self.check_battery()
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001894 self.check_core_dump()
Cheng-Yi Chiang39d32ad2013-07-23 15:02:38 +08001895 self.check_log_rotation()
Jon Salz57717ca2012-04-04 16:47:25 +08001896
Cheng-Yi Chiangf5b21012015-03-17 15:37:14 +08001897 def handle_event_logs(self, chunks, periodic=False):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001898 """Callback for event watcher.
Jon Salz258a40c2012-04-19 12:34:01 +08001899
Jon Salz0697cbf2012-07-04 15:14:04 +08001900 Attempts to upload the event logs to the shopfloor server.
Vic Yang93027612013-05-06 02:42:49 +08001901
1902 Args:
Jon Salzd15bbcf2013-05-21 17:33:57 +08001903 chunks: A list of Chunk objects.
Cheng-Yi Chiangf5b21012015-03-17 15:37:14 +08001904 periodic: This event log handling is periodic. Error messages
1905 will only be shown for the first time.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001906 """
Vic Yang93027612013-05-06 02:42:49 +08001907 first_exception = None
1908 exception_count = 0
Cheng-Yi Chiangf5b21012015-03-17 15:37:14 +08001909 # Suppress error messages for periodic event syncing except for the
1910 # first time. If event syncing is not periodic, always show the error
1911 # messages.
1912 quiet = self._suppress_event_log_error_messages if periodic else False
Vic Yang93027612013-05-06 02:42:49 +08001913
Jon Salzd15bbcf2013-05-21 17:33:57 +08001914 for chunk in chunks:
Vic Yang93027612013-05-06 02:42:49 +08001915 try:
Jon Salzcddb6402013-05-23 12:56:42 +08001916 description = 'event logs (%s)' % str(chunk)
Vic Yang93027612013-05-06 02:42:49 +08001917 start_time = time.time()
1918 shopfloor_client = shopfloor.get_instance(
Ricky Liang45c73e72015-01-15 15:00:30 +08001919 detect=True,
Cheng-Yi Chiangf5b21012015-03-17 15:37:14 +08001920 timeout=self.test_list.options.shopfloor_timeout_secs,
1921 quiet=quiet)
Ricky Liang45c73e72015-01-15 15:00:30 +08001922 shopfloor_client.UploadEvent(chunk.log_name + '.' +
Jon Salzd15bbcf2013-05-21 17:33:57 +08001923 event_log.GetReimageId(),
1924 Binary(chunk.chunk))
Vic Yang93027612013-05-06 02:42:49 +08001925 logging.info(
Ricky Liang45c73e72015-01-15 15:00:30 +08001926 'Successfully synced %s in %.03f s',
1927 description, time.time() - start_time)
1928 except: # pylint: disable=W0702
Hung-Te Linf707b242016-01-08 23:11:42 +08001929 first_exception = (first_exception or
1930 (chunk.log_name + ': ' +
1931 debug_utils.FormatExceptionOnly()))
Vic Yang93027612013-05-06 02:42:49 +08001932 exception_count += 1
1933
1934 if exception_count:
1935 if exception_count == 1:
1936 msg = 'Log upload failed: %s' % first_exception
1937 else:
1938 msg = '%d log upload failed; first is: %s' % (
1939 exception_count, first_exception)
Cheng-Yi Chiangf5b21012015-03-17 15:37:14 +08001940 # For periodic event log syncing, only show the first error messages.
1941 if periodic:
1942 if not self._suppress_event_log_error_messages:
1943 self._suppress_event_log_error_messages = True
1944 logging.warning('Suppress periodic shopfloor error messages for '
1945 'event log syncing after the first one.')
1946 raise Exception(msg)
1947 # For event log syncing by request, show the error messages.
1948 else:
1949 raise Exception(msg)
Vic Yang93027612013-05-06 02:42:49 +08001950
Ricky Liang45c73e72015-01-15 15:00:30 +08001951 def run_tests_with_status(self, statuses_to_run, starting_at=None, root=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001952 """Runs all top-level tests with a particular status.
Jon Salz0405ab52012-03-16 15:26:52 +08001953
Jon Salz0697cbf2012-07-04 15:14:04 +08001954 All active tests, plus any tests to re-run, are reset.
Jon Salz57717ca2012-04-04 16:47:25 +08001955
Jon Salz0697cbf2012-07-04 15:14:04 +08001956 Args:
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001957 statuses_to_run: The particular status that caller wants to run.
Jon Salz0697cbf2012-07-04 15:14:04 +08001958 starting_at: If provided, only auto-runs tests beginning with
1959 this test.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001960 root: The root of tests to run. If not provided, it will be
1961 the root of all tests.
1962 """
Jon Salz0697cbf2012-07-04 15:14:04 +08001963 root = root or self.test_list
Jon Salz57717ca2012-04-04 16:47:25 +08001964
Jon Salz0697cbf2012-07-04 15:14:04 +08001965 if starting_at:
1966 # Make sure they passed a test, not a string.
1967 assert isinstance(starting_at, factory.FactoryTest)
Jon Salz0405ab52012-03-16 15:26:52 +08001968
Jon Salz0697cbf2012-07-04 15:14:04 +08001969 tests_to_reset = []
1970 tests_to_run = []
Jon Salz0405ab52012-03-16 15:26:52 +08001971
Jon Salz0697cbf2012-07-04 15:14:04 +08001972 found_starting_at = False
Jon Salz0405ab52012-03-16 15:26:52 +08001973
Jon Salz0697cbf2012-07-04 15:14:04 +08001974 for test in root.get_top_level_tests():
1975 if starting_at:
1976 if test == starting_at:
1977 # We've found starting_at; do auto-run on all
1978 # subsequent tests.
1979 found_starting_at = True
1980 if not found_starting_at:
1981 # Don't start this guy yet
1982 continue
Jon Salz0405ab52012-03-16 15:26:52 +08001983
Jon Salz0697cbf2012-07-04 15:14:04 +08001984 status = test.get_state().status
1985 if status == TestState.ACTIVE or status in statuses_to_run:
1986 # Reset the test (later; we will need to abort
1987 # all active tests first).
1988 tests_to_reset.append(test)
1989 if status in statuses_to_run:
1990 tests_to_run.append(test)
Jon Salz0405ab52012-03-16 15:26:52 +08001991
Jon Salz6dc031d2013-06-19 13:06:23 +08001992 self.abort_active_tests('Operator requested run/re-run of certain tests')
Jon Salz258a40c2012-04-19 12:34:01 +08001993
Jon Salz0697cbf2012-07-04 15:14:04 +08001994 # Reset all statuses of the tests to run (in case any tests were active;
1995 # we want them to be run again).
1996 for test_to_reset in tests_to_reset:
1997 for test in test_to_reset.walk():
1998 test.update_state(status=TestState.UNTESTED)
Jon Salz57717ca2012-04-04 16:47:25 +08001999
Chih-Yu Huang85dc63c2015-08-12 15:21:28 +08002000 self.run_tests(tests_to_run, [TestState.UNTESTED])
Jon Salz0405ab52012-03-16 15:26:52 +08002001
Jon Salz0697cbf2012-07-04 15:14:04 +08002002 def restart_tests(self, root=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08002003 """Restarts all tests."""
Jon Salz0697cbf2012-07-04 15:14:04 +08002004 root = root or self.test_list
Jon Salz0405ab52012-03-16 15:26:52 +08002005
Jon Salz6dc031d2013-06-19 13:06:23 +08002006 self.abort_active_tests('Operator requested restart of certain tests')
Jon Salz0697cbf2012-07-04 15:14:04 +08002007 for test in root.walk():
Ricky Liangfea4ac92014-08-21 11:55:59 +08002008 test.update_state(status=TestState.UNTESTED)
Jon Salz0697cbf2012-07-04 15:14:04 +08002009 self.run_tests(root)
Hung-Te Lin96632362012-03-20 21:14:18 +08002010
Jon Salz0697cbf2012-07-04 15:14:04 +08002011 def auto_run(self, starting_at=None, root=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08002012 """"Auto-runs" tests that have not been run yet.
Hung-Te Lin96632362012-03-20 21:14:18 +08002013
Jon Salz0697cbf2012-07-04 15:14:04 +08002014 Args:
2015 starting_at: If provide, only auto-runs tests beginning with
2016 this test.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08002017 root: If provided, the root of tests to run. If not provided, the root
2018 will be test_list (root of all tests).
2019 """
Jon Salz0697cbf2012-07-04 15:14:04 +08002020 root = root or self.test_list
2021 self.run_tests_with_status([TestState.UNTESTED, TestState.ACTIVE],
Ricky Liang45c73e72015-01-15 15:00:30 +08002022 starting_at=starting_at,
2023 root=root)
Jon Salz968e90b2012-03-18 16:12:43 +08002024
Jon Salz0697cbf2012-07-04 15:14:04 +08002025 def re_run_failed(self, root=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08002026 """Re-runs failed tests."""
Jon Salz0697cbf2012-07-04 15:14:04 +08002027 root = root or self.test_list
2028 self.run_tests_with_status([TestState.FAILED], root=root)
Jon Salz57717ca2012-04-04 16:47:25 +08002029
Jon Salz0697cbf2012-07-04 15:14:04 +08002030 def show_review_information(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08002031 """Event handler for showing review information screen.
Jon Salz57717ca2012-04-04 16:47:25 +08002032
Peter Ammon1e1ec572014-06-26 17:56:32 -07002033 The information screen is rendered by main UI program (ui.py), so in
Jon Salz0697cbf2012-07-04 15:14:04 +08002034 goofy we only need to kill all active tests, set them as untested, and
2035 clear remaining tests.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08002036 """
Jon Salz0697cbf2012-07-04 15:14:04 +08002037 self.kill_active_tests(False)
Jon Salza6711d72012-07-18 14:33:03 +08002038 self.cancel_pending_tests()
Jon Salz57717ca2012-04-04 16:47:25 +08002039
Jon Salz0697cbf2012-07-04 15:14:04 +08002040 def handle_switch_test(self, event):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08002041 """Switches to a particular test.
Jon Salz0405ab52012-03-16 15:26:52 +08002042
Ricky Liang6fe218c2013-12-27 15:17:17 +08002043 Args:
2044 event: The SWITCH_TEST event.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08002045 """
Jon Salz0697cbf2012-07-04 15:14:04 +08002046 test = self.test_list.lookup_path(event.path)
2047 if not test:
2048 logging.error('Unknown test %r', event.key)
2049 return
Jon Salz73e0fd02012-04-04 11:46:38 +08002050
Jon Salz0697cbf2012-07-04 15:14:04 +08002051 invoc = self.invocations.get(test)
2052 if invoc and test.backgroundable:
2053 # Already running: just bring to the front if it
2054 # has a UI.
2055 logging.info('Setting visible test to %s', test.path)
Jon Salz36fbbb52012-07-05 13:45:06 +08002056 self.set_visible_test(test)
Jon Salz0697cbf2012-07-04 15:14:04 +08002057 return
Jon Salz73e0fd02012-04-04 11:46:38 +08002058
Jon Salz6dc031d2013-06-19 13:06:23 +08002059 self.abort_active_tests('Operator requested abort (switch_test)')
Jon Salz0697cbf2012-07-04 15:14:04 +08002060 for t in test.walk():
2061 t.update_state(status=TestState.UNTESTED)
Jon Salz73e0fd02012-04-04 11:46:38 +08002062
Jon Salz0697cbf2012-07-04 15:14:04 +08002063 if self.test_list.options.auto_run_on_keypress:
2064 self.auto_run(starting_at=test)
2065 else:
2066 self.run_tests(test)
Jon Salz73e0fd02012-04-04 11:46:38 +08002067
Wei-Ning Huang38b75f02015-02-25 18:25:14 +08002068 def handle_key_filter_mode(self, event):
2069 if self.key_filter:
2070 if getattr(event, 'enabled'):
2071 self.key_filter.Start()
2072 else:
2073 self.key_filter.Stop()
2074
Jon Salz0697cbf2012-07-04 15:14:04 +08002075 def wait(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08002076 """Waits for all pending invocations.
Jon Salz0697cbf2012-07-04 15:14:04 +08002077
2078 Useful for testing.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08002079 """
Jon Salz1acc8742012-07-17 17:45:55 +08002080 while self.invocations:
2081 for k, v in self.invocations.iteritems():
2082 logging.info('Waiting for %s to complete...', k)
2083 v.thread.join()
2084 self.reap_completed_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +08002085
Claire Changd1961a22015-08-05 16:15:55 +08002086 def test_fail(self, test):
Hung-Te Lin410f70a2015-12-15 14:53:42 +08002087 self.dut.hooks.OnTestFailure(test)
Claire Changd1961a22015-08-05 16:15:55 +08002088 if self.link_manager:
2089 self.link_manager.UpdateStatus(False)
2090
Hung-Te Linf2f78f72012-02-08 19:27:11 +08002091if __name__ == '__main__':
Peter Ammona3d298c2014-09-23 10:11:02 -07002092 Goofy.run_main_and_exit()