blob: b4cd9a236e705d8227ed36472c2d3fa3bb259887 [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
Joel Kitching9eb203a2016-04-21 15:36:30 +080029from cros.factory.test import testlog
Chun-Ta Lin53cbbd52016-06-08 21:42:19 +080030from cros.factory.test import testlog_goofy
Joel Kitching4b1b6c02016-05-10 14:34:30 +080031from cros.factory.test.env import paths
Chun-Ta Lin5d12b592015-06-30 00:54:23 -070032from cros.factory.test.event_log import EventLog, FloatDigit, GetBootSequence
Hung-Te Lincc41d2a2014-10-29 13:35:20 +080033from cros.factory.goofy import connection_manager
Vic Yangd80ea752014-09-24 16:07:14 +080034from cros.factory.goofy import test_environment
35from cros.factory.goofy import time_sanitizer
36from cros.factory.goofy import updater
37from cros.factory.goofy.goofy_base import GoofyBase
38from cros.factory.goofy.goofy_rpc import GoofyRPC
39from cros.factory.goofy.invocation import TestArgEnv
40from cros.factory.goofy.invocation import TestInvocation
41from cros.factory.goofy.link_manager import PresenterLinkManager
Vic Yange2c76a82014-10-30 12:48:19 -070042from cros.factory.goofy import prespawner
Vic Yangd80ea752014-09-24 16:07:14 +080043from cros.factory.goofy.system_log_manager import SystemLogManager
Wei-Ning Huang38b75f02015-02-25 18:25:14 +080044from cros.factory.goofy.terminal_manager import TerminalManager
Vic Yangd80ea752014-09-24 16:07:14 +080045from cros.factory.goofy.web_socket_manager import WebSocketManager
Hung-Te Lin6a72c642015-12-13 22:09:09 +080046from cros.factory.test import dut
jcliangcd688182012-08-20 21:01:26 +080047from cros.factory.test import factory
Jon Salz51528e12012-07-02 18:54:45 +080048from cros.factory.test import shopfloor
Hung-Te Lin6a72c642015-12-13 22:09:09 +080049from cros.factory.test import state
Wei-Han Chene8a025f2016-01-14 16:42:02 +080050from cros.factory.test.dut import utils as dut_utils
Ricky Liang6fe218c2013-12-27 15:17:17 +080051from cros.factory.test.e2e_test.common import (
52 AutomationMode, AutomationModePrompt, ParseAutomationMode)
Jon Salz83591782012-06-26 11:09:58 +080053from cros.factory.test.event import Event
54from cros.factory.test.event import EventClient
55from cros.factory.test.event import EventServer
Hung-Te Lin91492a12014-11-25 18:56:30 +080056from cros.factory.test.event_log_watcher import EventLogWatcher
jcliangcd688182012-08-20 21:01:26 +080057from cros.factory.test.factory import TestState
Hung-Te Lin3f096842016-01-13 17:37:06 +080058from cros.factory.test.rules import phase
Wei-Han Chen2ebb92d2016-01-12 14:51:41 +080059from cros.factory.test.test_lists import test_lists
Hung-Te Linc367ac02015-12-22 19:33:23 +080060from cros.factory.test.utils.charge_manager import ChargeManager
61from cros.factory.test.utils.core_dump_manager import CoreDumpManager
62from cros.factory.test.utils.cpufreq_manager import CpufreqManager
Dean Liao592e4d52013-01-10 20:06:39 +080063from cros.factory.tools.key_filter import KeyFilter
Hung-Te Lind3ee0102015-12-28 17:21:50 +080064from cros.factory.tools import disk_space
Hung-Te Linf707b242016-01-08 23:11:42 +080065from cros.factory.utils import debug_utils
Jon Salz2af235d2013-06-24 14:47:21 +080066from cros.factory.utils import file_utils
Joel Kitchingb85ed7f2014-10-08 18:24:39 +080067from cros.factory.utils import net_utils
Hung-Te Lin4e6357c2016-01-08 14:32:00 +080068from cros.factory.utils import process_utils
69from cros.factory.utils import sys_utils
70from cros.factory.utils import time_utils
Hung-Te Linf707b242016-01-08 23:11:42 +080071from cros.factory.utils import type_utils
Hung-Te Linf2f78f72012-02-08 19:27:11 +080072
73
Hung-Te Linf2f78f72012-02-08 19:27:11 +080074HWID_CFG_PATH = '/usr/local/share/chromeos-hwid/cfg'
Joel Kitching625ff0f2016-05-16 14:59:40 -070075CACHES_DIR = os.path.join(paths.GetStateRoot(), 'caches')
Hung-Te Linf2f78f72012-02-08 19:27:11 +080076
Cheng-Yi Chiang39d32ad2013-07-23 15:02:38 +080077CLEANUP_LOGS_PAUSED = '/var/lib/cleanup_logs_paused'
78
Jon Salz5c344f62012-07-13 14:31:16 +080079# Value for tests_after_shutdown that forces auto-run (e.g., after
80# a factory update, when the available set of tests might change).
81FORCE_AUTO_RUN = 'force_auto_run'
82
Justin Chuang83813982013-05-13 01:26:32 +080083# Sync disks when battery level is higher than this value.
84# Otherwise, power loss during disk sync operation may incur even worse outcome.
85MIN_BATTERY_LEVEL_FOR_DISK_SYNC = 1.0
86
Ricky Liang45c73e72015-01-15 15:00:30 +080087MAX_CRASH_FILE_SIZE = 64 * 1024
Jon Salze12c2b32013-06-25 16:24:34 +080088
Hung-Te Linf707b242016-01-08 23:11:42 +080089Status = type_utils.Enum(['UNINITIALIZED', 'INITIALIZING', 'RUNNING',
Wei-Han Chen2ebb92d2016-01-12 14:51:41 +080090 'TERMINATING', 'TERMINATED'])
Jon Salzd7550792013-07-12 05:49:27 +080091
Ricky Liang45c73e72015-01-15 15:00:30 +080092
Hung-Te Linf2f78f72012-02-08 19:27:11 +080093def get_hwid_cfg():
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +080094 """Returns the HWID config tag, or an empty string if none can be found."""
Jon Salz0697cbf2012-07-04 15:14:04 +080095 if 'CROS_HWID' in os.environ:
96 return os.environ['CROS_HWID']
97 if os.path.exists(HWID_CFG_PATH):
Ricky Liang45c73e72015-01-15 15:00:30 +080098 with open(HWID_CFG_PATH, 'r') as hwid_cfg_handle:
Jon Salz0697cbf2012-07-04 15:14:04 +080099 return hwid_cfg_handle.read().strip()
100 return ''
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800101
102
Jon Salz73e0fd02012-04-04 11:46:38 +0800103_inited_logging = False
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800104
Ricky Liang45c73e72015-01-15 15:00:30 +0800105
Peter Ammon1e1ec572014-06-26 17:56:32 -0700106class Goofy(GoofyBase):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800107 """The main factory flow.
Jon Salz0697cbf2012-07-04 15:14:04 +0800108
109 Note that all methods in this class must be invoked from the main
110 (event) thread. Other threads, such as callbacks and TestInvocation
111 methods, should instead post events on the run queue.
112
113 TODO: Unit tests. (chrome-os-partner:7409)
114
115 Properties:
116 uuid: A unique UUID for this invocation of Goofy.
117 state_instance: An instance of FactoryState.
118 state_server: The FactoryState XML/RPC server.
119 state_server_thread: A thread running state_server.
120 event_server: The EventServer socket server.
121 event_server_thread: A thread running event_server.
122 event_client: A client to the event server.
123 connection_manager: The connection_manager object.
Cheng-Yi Chiang835f2682013-05-06 22:15:48 +0800124 system_log_manager: The SystemLogManager object.
125 core_dump_manager: The CoreDumpManager object.
Jon Salz0697cbf2012-07-04 15:14:04 +0800126 ui_process: The factory ui process object.
Jon Salz0697cbf2012-07-04 15:14:04 +0800127 invocations: A map from FactoryTest objects to the corresponding
128 TestInvocations objects representing active tests.
129 tests_to_run: A deque of tests that should be run when the current
130 test(s) complete.
131 options: Command-line options.
132 args: Command-line args.
133 test_list: The test list.
Jon Salz128b0932013-07-03 16:55:26 +0800134 test_lists: All new-style test lists.
Ricky Liang4bff3e32014-02-20 18:46:11 +0800135 run_id: The identifier for latest test run.
136 scheduled_run_tests: The list of tests scheduled for latest test run.
Jon Salz0697cbf2012-07-04 15:14:04 +0800137 event_handlers: Map of Event.Type to the method used to handle that
138 event. If the method has an 'event' argument, the event is passed
139 to the handler.
Jon Salz3c493bb2013-02-07 17:24:58 +0800140 last_log_disk_space_message: The last message we logged about disk space
141 (to avoid duplication).
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +0800142 last_kick_sync_time: The last time to kick system_log_manager to sync
143 because of core dump files (to avoid kicking too soon then abort the
144 sync.)
Jon Salz416f9cc2013-05-10 18:32:50 +0800145 hooks: A Hooks object containing hooks for various Goofy actions.
Jon Salzd7550792013-07-12 05:49:27 +0800146 status: The current Goofy status (a member of the Status enum).
Peter Ammon948b7172014-07-15 12:43:06 -0700147 link_manager: Instance of PresenterLinkManager for communicating
148 with GoofyPresenter
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800149 """
Ricky Liang45c73e72015-01-15 15:00:30 +0800150
Jon Salz0697cbf2012-07-04 15:14:04 +0800151 def __init__(self):
Peter Ammon1e1ec572014-06-26 17:56:32 -0700152 super(Goofy, self).__init__()
Jon Salz0697cbf2012-07-04 15:14:04 +0800153 self.uuid = str(uuid.uuid4())
154 self.state_instance = None
155 self.state_server = None
156 self.state_server_thread = None
Jon Salz16d10542012-07-23 12:18:45 +0800157 self.goofy_rpc = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800158 self.event_server = None
159 self.event_server_thread = None
160 self.event_client = None
161 self.connection_manager = None
Vic Yang4953fc12012-07-26 16:19:53 +0800162 self.charge_manager = None
Dean Liao88b93192014-10-23 19:37:41 +0800163 self._can_charge = True
Jon Salz8fa8e832012-07-13 19:04:09 +0800164 self.time_sanitizer = None
165 self.time_synced = False
Jon Salz0697cbf2012-07-04 15:14:04 +0800166 self.log_watcher = None
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +0800167 self.system_log_manager = None
Cheng-Yi Chiang835f2682013-05-06 22:15:48 +0800168 self.core_dump_manager = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800169 self.event_log = None
Chun-Ta Lin53cbbd52016-06-08 21:42:19 +0800170 self.testlog = None
Vic Yange2c76a82014-10-30 12:48:19 -0700171 self.autotest_prespawner = None
172 self.pytest_prespawner = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800173 self.ui_process = None
Vic Yanga3cecf82014-12-26 00:44:21 -0800174 self._ui_initialized = False
Jon Salzc79a9982012-08-30 04:42:01 +0800175 self.dummy_shopfloor = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800176 self.invocations = {}
177 self.tests_to_run = deque()
178 self.visible_test = None
179 self.chrome = None
Jon Salz416f9cc2013-05-10 18:32:50 +0800180 self.hooks = None
Vic Yangd8990da2013-06-27 16:57:43 +0800181 self.cpu_usage_watcher = None
Hung-Te Lin23cb7612016-01-19 19:19:32 +0800182 self.thermal_watcher = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800183
184 self.options = None
185 self.args = None
186 self.test_list = None
Jon Salz128b0932013-07-03 16:55:26 +0800187 self.test_lists = None
Ricky Liang4bff3e32014-02-20 18:46:11 +0800188 self.run_id = None
189 self.scheduled_run_tests = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800190 self.env = None
Jon Salzb22d1172012-08-06 10:38:57 +0800191 self.last_idle = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800192 self.last_shutdown_time = None
cychiang21886742012-07-05 15:16:32 +0800193 self.last_update_check = None
Cheng-Yi Chiang194d3c02015-03-16 14:37:15 +0800194 self._suppress_periodic_update_messages = False
Cheng-Yi Chiangf5b21012015-03-17 15:37:14 +0800195 self._suppress_event_log_error_messages = False
Jon Salz8fa8e832012-07-13 19:04:09 +0800196 self.last_sync_time = None
Jon Salzb92c5112012-09-21 15:40:11 +0800197 self.last_log_disk_space_time = None
Jon Salz3c493bb2013-02-07 17:24:58 +0800198 self.last_log_disk_space_message = None
Justin Chuang83813982013-05-13 01:26:32 +0800199 self.last_check_battery_time = None
200 self.last_check_battery_message = None
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +0800201 self.last_kick_sync_time = None
Vic Yang311ddb82012-09-26 12:08:28 +0800202 self.exclusive_items = set()
Dean Liao592e4d52013-01-10 20:06:39 +0800203 self.key_filter = None
Jon Salzce6a7f82013-06-10 18:22:54 +0800204 self.cpufreq_manager = None
Jon Salzd7550792013-07-12 05:49:27 +0800205 self.status = Status.UNINITIALIZED
Ricky Liang36512a32014-07-25 11:47:04 +0800206 self.ready_for_ui_connection = False
Peter Ammon1e1ec572014-06-26 17:56:32 -0700207 self.link_manager = None
Hung-Te Linef7f2be2015-07-20 20:38:51 +0800208 self.is_restart_requested = False
Jon Salz0697cbf2012-07-04 15:14:04 +0800209
Hung-Te Lin6a72c642015-12-13 22:09:09 +0800210 # TODO(hungte) Support controlling remote DUT.
211 self.dut = dut.Create()
212
Jon Salz85a39882012-07-05 16:45:04 +0800213 def test_or_root(event, parent_or_group=True):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800214 """Returns the test affected by a particular event.
Jon Salz85a39882012-07-05 16:45:04 +0800215
216 Args:
217 event: The event containing an optional 'path' attribute.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800218 parent_or_group: If True, returns the top-level parent for a test (the
Jon Salz85a39882012-07-05 16:45:04 +0800219 root node of the tests that need to be run together if the given test
220 path is to be run).
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800221 """
Jon Salz0697cbf2012-07-04 15:14:04 +0800222 try:
223 path = event.path
224 except AttributeError:
225 path = None
226
227 if path:
Jon Salz85a39882012-07-05 16:45:04 +0800228 test = self.test_list.lookup_path(path)
229 if parent_or_group:
230 test = test.get_top_level_parent_or_group()
231 return test
Jon Salz0697cbf2012-07-04 15:14:04 +0800232 else:
233 return self.test_list
234
235 self.event_handlers = {
Ricky Liang45c73e72015-01-15 15:00:30 +0800236 Event.Type.SWITCH_TEST: self.handle_switch_test,
237 Event.Type.SHOW_NEXT_ACTIVE_TEST:
238 lambda event: self.show_next_active_test(),
239 Event.Type.RESTART_TESTS:
240 lambda event: self.restart_tests(root=test_or_root(event)),
241 Event.Type.AUTO_RUN:
242 lambda event: self.auto_run(root=test_or_root(event)),
243 Event.Type.RE_RUN_FAILED:
244 lambda event: self.re_run_failed(root=test_or_root(event)),
245 Event.Type.RUN_TESTS_WITH_STATUS:
246 lambda event: self.run_tests_with_status(
247 event.status,
248 root=test_or_root(event)),
249 Event.Type.REVIEW:
250 lambda event: self.show_review_information(),
251 Event.Type.UPDATE_SYSTEM_INFO:
252 lambda event: self.update_system_info(),
253 Event.Type.STOP:
254 lambda event: self.stop(root=test_or_root(event, False),
255 fail=getattr(event, 'fail', False),
256 reason=getattr(event, 'reason', None)),
257 Event.Type.SET_VISIBLE_TEST:
258 lambda event: self.set_visible_test(
259 self.test_list.lookup_path(event.path)),
260 Event.Type.CLEAR_STATE:
261 lambda event: self.clear_state(
262 self.test_list.lookup_path(event.path)),
Wei-Ning Huang38b75f02015-02-25 18:25:14 +0800263 Event.Type.KEY_FILTER_MODE: self.handle_key_filter_mode,
Jon Salz0697cbf2012-07-04 15:14:04 +0800264 }
265
Jon Salz0697cbf2012-07-04 15:14:04 +0800266 self.web_socket_manager = None
Wei-Ning Huang38b75f02015-02-25 18:25:14 +0800267 self.terminal_manager = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800268
269 def destroy(self):
Ricky Liang74237a02014-09-18 15:11:23 +0800270 """Performs any shutdown tasks. Overrides base class method."""
Jon Salzd7550792013-07-12 05:49:27 +0800271 self.status = Status.TERMINATING
Jon Salz0697cbf2012-07-04 15:14:04 +0800272 if self.chrome:
273 self.chrome.kill()
274 self.chrome = None
Jon Salzc79a9982012-08-30 04:42:01 +0800275 if self.dummy_shopfloor:
276 self.dummy_shopfloor.kill()
277 self.dummy_shopfloor = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800278 if self.ui_process:
Hung-Te Lin4e6357c2016-01-08 14:32:00 +0800279 process_utils.KillProcessTree(self.ui_process, 'ui')
Jon Salz0697cbf2012-07-04 15:14:04 +0800280 self.ui_process = None
281 if self.web_socket_manager:
282 logging.info('Stopping web sockets')
283 self.web_socket_manager.close()
284 self.web_socket_manager = None
285 if self.state_server_thread:
286 logging.info('Stopping state server')
287 self.state_server.shutdown()
288 self.state_server_thread.join()
289 self.state_server.server_close()
290 self.state_server_thread = None
291 if self.state_instance:
292 self.state_instance.close()
293 if self.event_server_thread:
294 logging.info('Stopping event server')
295 self.event_server.shutdown() # pylint: disable=E1101
296 self.event_server_thread.join()
297 self.event_server.server_close()
298 self.event_server_thread = None
299 if self.log_watcher:
300 if self.log_watcher.IsThreadStarted():
301 self.log_watcher.StopWatchThread()
302 self.log_watcher = None
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +0800303 if self.system_log_manager:
304 if self.system_log_manager.IsThreadRunning():
Cheng-Yi Chianga0f6eff2014-01-09 18:27:22 +0800305 self.system_log_manager.Stop()
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +0800306 self.system_log_manager = None
Vic Yange2c76a82014-10-30 12:48:19 -0700307 if self.autotest_prespawner:
308 logging.info('Stopping autotest prespawner')
309 self.autotest_prespawner.stop()
310 self.autotest_prespawner = None
311 if self.pytest_prespawner:
312 logging.info('Stopping pytest prespawner')
313 self.pytest_prespawner.stop()
314 self.pytest_prespawner = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800315 if self.event_client:
316 logging.info('Closing event client')
317 self.event_client.close()
318 self.event_client = None
Jon Salzddf0d052013-06-18 12:52:44 +0800319 if self.cpufreq_manager:
320 self.cpufreq_manager.Stop()
Jon Salz0697cbf2012-07-04 15:14:04 +0800321 if self.event_log:
322 self.event_log.Close()
323 self.event_log = None
Chun-Ta Lin53cbbd52016-06-08 21:42:19 +0800324 if self.testlog:
325 self.testlog.Close()
326 self.testlog = None
Dean Liao592e4d52013-01-10 20:06:39 +0800327 if self.key_filter:
328 self.key_filter.Stop()
Vic Yangd8990da2013-06-27 16:57:43 +0800329 if self.cpu_usage_watcher:
330 self.cpu_usage_watcher.terminate()
Hung-Te Lin23cb7612016-01-19 19:19:32 +0800331 if self.thermal_watcher:
332 self.thermal_watcher.terminate()
Peter Ammon1e1ec572014-06-26 17:56:32 -0700333 if self.link_manager:
334 self.link_manager.Stop()
335 self.link_manager = None
Dean Liao592e4d52013-01-10 20:06:39 +0800336
Peter Ammon1e1ec572014-06-26 17:56:32 -0700337 super(Goofy, self).destroy()
Jon Salz0697cbf2012-07-04 15:14:04 +0800338 logging.info('Done destroying Goofy')
Jon Salzd7550792013-07-12 05:49:27 +0800339 self.status = Status.TERMINATED
Jon Salz0697cbf2012-07-04 15:14:04 +0800340
341 def start_state_server(self):
Jon Salz2af235d2013-06-24 14:47:21 +0800342 # Before starting state server, remount stateful partitions with
343 # no commit flag. The default commit time (commit=600) makes corruption
344 # too likely.
Hung-Te Lin1968d9c2016-01-08 22:55:46 +0800345 sys_utils.ResetCommitTime()
Jon Salz2af235d2013-06-24 14:47:21 +0800346
Jon Salz0697cbf2012-07-04 15:14:04 +0800347 self.state_instance, self.state_server = (
Ricky Liang45c73e72015-01-15 15:00:30 +0800348 state.create_server(bind_address='0.0.0.0'))
Jon Salz16d10542012-07-23 12:18:45 +0800349 self.goofy_rpc = GoofyRPC(self)
350 self.goofy_rpc.RegisterMethods(self.state_instance)
Jon Salz0697cbf2012-07-04 15:14:04 +0800351 logging.info('Starting state server')
352 self.state_server_thread = threading.Thread(
Ricky Liang45c73e72015-01-15 15:00:30 +0800353 target=self.state_server.serve_forever,
354 name='StateServer')
Jon Salz0697cbf2012-07-04 15:14:04 +0800355 self.state_server_thread.start()
356
357 def start_event_server(self):
358 self.event_server = EventServer()
359 logging.info('Starting factory event server')
360 self.event_server_thread = threading.Thread(
Ricky Liang45c73e72015-01-15 15:00:30 +0800361 target=self.event_server.serve_forever,
362 name='EventServer') # pylint: disable=E1101
Jon Salz0697cbf2012-07-04 15:14:04 +0800363 self.event_server_thread.start()
364
365 self.event_client = EventClient(
Ricky Liang45c73e72015-01-15 15:00:30 +0800366 callback=self.handle_event, event_loop=self.run_queue)
Jon Salz0697cbf2012-07-04 15:14:04 +0800367
368 self.web_socket_manager = WebSocketManager(self.uuid)
Ricky Liang45c73e72015-01-15 15:00:30 +0800369 self.state_server.add_handler('/event',
370 self.web_socket_manager.handle_web_socket)
Jon Salz0697cbf2012-07-04 15:14:04 +0800371
Wei-Ning Huang38b75f02015-02-25 18:25:14 +0800372 def start_terminal_server(self):
373 self.terminal_manager = TerminalManager()
374 self.state_server.add_handler('/pty',
375 self.terminal_manager.handle_web_socket)
376
Jon Salz0697cbf2012-07-04 15:14:04 +0800377 def start_ui(self):
378 ui_proc_args = [
Wei-Han Chen2ebb92d2016-01-12 14:51:41 +0800379 os.path.join(paths.FACTORY_PACKAGE_PATH, 'test', 'ui.py'),
Ricky Liang45c73e72015-01-15 15:00:30 +0800380 self.options.test_list
381 ]
Jon Salz0697cbf2012-07-04 15:14:04 +0800382 if self.options.verbose:
383 ui_proc_args.append('-v')
384 logging.info('Starting ui %s', ui_proc_args)
Hung-Te Lin4e6357c2016-01-08 14:32:00 +0800385 self.ui_process = process_utils.Spawn(ui_proc_args)
Jon Salz0697cbf2012-07-04 15:14:04 +0800386 logging.info('Waiting for UI to come up...')
387 self.event_client.wait(
Ricky Liang45c73e72015-01-15 15:00:30 +0800388 lambda event: event.type == Event.Type.UI_READY)
Jon Salz0697cbf2012-07-04 15:14:04 +0800389 logging.info('UI has started')
390
391 def set_visible_test(self, test):
392 if self.visible_test == test:
393 return
Jon Salz2f2d42c2012-07-30 12:30:34 +0800394 if test and not test.has_ui:
395 return
Jon Salz0697cbf2012-07-04 15:14:04 +0800396
397 if test:
398 test.update_state(visible=True)
399 if self.visible_test:
400 self.visible_test.update_state(visible=False)
401 self.visible_test = test
402
Ricky Liang48e47f92014-02-26 19:31:51 +0800403 def log_startup_messages(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800404 """Logs the tail of var/log/messages and mosys and EC console logs."""
Jon Salzd4306c82012-11-30 15:16:36 +0800405 # TODO(jsalz): This is mostly a copy-and-paste of code in init_states,
406 # for factory-3004.B only. Consolidate and merge back to ToT.
Hung-Te Linf5f2d7f2016-01-08 17:12:46 +0800407 if sys_utils.InChroot():
Jon Salzd4306c82012-11-30 15:16:36 +0800408 return
409
410 try:
Hung-Te Lin1a4e30c2016-01-08 23:25:10 +0800411 var_log_messages = sys_utils.GetVarLogMessagesBeforeReboot()
Jon Salzd4306c82012-11-30 15:16:36 +0800412 logging.info(
Ricky Liang45c73e72015-01-15 15:00:30 +0800413 'Tail of /var/log/messages before last reboot:\n'
414 '%s', ('\n'.join(
415 ' ' + x for x in var_log_messages)))
Jon Salzd4306c82012-11-30 15:16:36 +0800416 except: # pylint: disable=W0702
417 logging.exception('Unable to grok /var/log/messages')
418
419 try:
Hung-Te Lin4e6357c2016-01-08 14:32:00 +0800420 mosys_log = process_utils.Spawn(
Jon Salzd4306c82012-11-30 15:16:36 +0800421 ['mosys', 'eventlog', 'list'],
422 read_stdout=True, log_stderr_on_error=True).stdout_data
423 logging.info('System eventlog from mosys:\n%s\n', mosys_log)
424 except: # pylint: disable=W0702
425 logging.exception('Unable to read mosys eventlog')
426
Dean Liao88b93192014-10-23 19:37:41 +0800427 self.log_ec_console()
428 self.log_ec_panic_info()
429
430 @staticmethod
431 def log_ec_console():
432 """Logs EC console log into logging.info.
433
434 It logs an error message in logging.exception if an exception is raised
435 when getting EC console log.
436 For unsupported device, it logs unsupport message in logging.info
437
438 Returns:
439 EC console log string.
440 """
Jon Salzd4306c82012-11-30 15:16:36 +0800441 try:
Hung-Te Linb3a09642015-12-14 18:57:23 +0800442 ec_console_log = dut.Create().ec.GetECConsoleLog()
Jon Salzd4306c82012-11-30 15:16:36 +0800443 logging.info('EC console log after reboot:\n%s\n', ec_console_log)
Dean Liao88b93192014-10-23 19:37:41 +0800444 return ec_console_log
445 except NotImplementedError:
446 logging.info('EC console log not supported')
Jon Salzd4306c82012-11-30 15:16:36 +0800447 except: # pylint: disable=W0702
448 logging.exception('Error retrieving EC console log')
449
Dean Liao88b93192014-10-23 19:37:41 +0800450 @staticmethod
451 def log_ec_panic_info():
452 """Logs EC panic info into logging.info.
453
454 It logs an error message in logging.exception if an exception is raised
455 when getting EC panic info.
456 For unsupported device, it logs unsupport message in logging.info
457
458 Returns:
459 EC panic info string.
460 """
Vic Yang079f9872013-07-01 11:32:00 +0800461 try:
Hung-Te Linb3a09642015-12-14 18:57:23 +0800462 ec_panic_info = dut.Create().ec.GetECPanicInfo()
Vic Yang079f9872013-07-01 11:32:00 +0800463 logging.info('EC panic info after reboot:\n%s\n', ec_panic_info)
Dean Liao88b93192014-10-23 19:37:41 +0800464 return ec_panic_info
465 except NotImplementedError:
466 logging.info('EC panic info is not supported')
Vic Yang079f9872013-07-01 11:32:00 +0800467 except: # pylint: disable=W0702
468 logging.exception('Error retrieving EC panic info')
469
Ricky Liang48e47f92014-02-26 19:31:51 +0800470 def shutdown(self, operation):
471 """Starts shutdown procedure.
472
473 Args:
Vic (Chun-Ju) Yang05b0d952014-04-28 17:39:09 +0800474 operation: The shutdown operation (reboot, full_reboot, or halt).
Ricky Liang48e47f92014-02-26 19:31:51 +0800475 """
476 active_tests = []
477 for test in self.test_list.walk():
478 if not test.is_leaf():
479 continue
480
481 test_state = test.get_state()
482 if test_state.status == TestState.ACTIVE:
483 active_tests.append(test)
484
Ricky Liang48e47f92014-02-26 19:31:51 +0800485 if not (len(active_tests) == 1 and
486 isinstance(active_tests[0], factory.ShutdownStep)):
487 logging.error(
488 'Calling Goofy shutdown outside of the shutdown factory test')
489 return
490
491 logging.info('Start Goofy shutdown (%s)', operation)
492 # Save pending test list in the state server
493 self.state_instance.set_shared_data(
494 'tests_after_shutdown',
495 [t.path for t in self.tests_to_run])
496 # Save shutdown time
497 self.state_instance.set_shared_data('shutdown_time', time.time())
498
499 with self.env.lock:
500 self.event_log.Log('shutdown', operation=operation)
501 shutdown_result = self.env.shutdown(operation)
502 if shutdown_result:
503 # That's all, folks!
Peter Ammon1e1ec572014-06-26 17:56:32 -0700504 self.run_enqueue(None)
Ricky Liang48e47f92014-02-26 19:31:51 +0800505 else:
506 # Just pass (e.g., in the chroot).
507 self.state_instance.set_shared_data('tests_after_shutdown', None)
508 # Send event with no fields to indicate that there is no
509 # longer a pending shutdown.
510 self.event_client.post_event(Event(Event.Type.PENDING_SHUTDOWN))
511
512 def handle_shutdown_complete(self, test):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800513 """Handles the case where a shutdown was detected during a shutdown step.
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800514
Ricky Liang6fe218c2013-12-27 15:17:17 +0800515 Args:
516 test: The ShutdownStep.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800517 """
Jon Salz0697cbf2012-07-04 15:14:04 +0800518 test_state = test.update_state(increment_shutdown_count=1)
519 logging.info('Detected shutdown (%d of %d)',
Ricky Liang48e47f92014-02-26 19:31:51 +0800520 test_state.shutdown_count, test.iterations)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800521
Ricky Liang48e47f92014-02-26 19:31:51 +0800522 # Insert current shutdown test at the front of the list of tests to run
523 # after shutdown. This is to continue on post-shutdown verification in the
524 # shutdown step.
525 tests_after_shutdown = self.state_instance.get_shared_data(
526 'tests_after_shutdown', optional=True)
527 if not tests_after_shutdown:
528 self.state_instance.set_shared_data('tests_after_shutdown', [test.path])
529 elif isinstance(tests_after_shutdown, list):
530 self.state_instance.set_shared_data(
531 'tests_after_shutdown', [test.path] + tests_after_shutdown)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800532
Ricky Liang48e47f92014-02-26 19:31:51 +0800533 # Set 'post_shutdown' to inform shutdown test that a shutdown just occurred.
Ricky Liangb7eb8772014-09-15 18:05:22 +0800534 self.state_instance.set_shared_data(
535 state.POST_SHUTDOWN_TAG % test.path,
536 self.state_instance.get_test_state(test.path).invocation)
Jon Salz258a40c2012-04-19 12:34:01 +0800537
Jon Salz0697cbf2012-07-04 15:14:04 +0800538 def init_states(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800539 """Initializes all states on startup."""
Jon Salz0697cbf2012-07-04 15:14:04 +0800540 for test in self.test_list.get_all_tests():
541 # Make sure the state server knows about all the tests,
542 # defaulting to an untested state.
543 test.update_state(update_parent=False, visible=False)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800544
Jon Salz0697cbf2012-07-04 15:14:04 +0800545 var_log_messages = None
Vic Yanga9c32212012-08-16 20:07:54 +0800546 mosys_log = None
Vic Yange4c275d2012-08-28 01:50:20 +0800547 ec_console_log = None
Vic Yang079f9872013-07-01 11:32:00 +0800548 ec_panic_info = None
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800549
Jon Salz0697cbf2012-07-04 15:14:04 +0800550 # Any 'active' tests should be marked as failed now.
551 for test in self.test_list.walk():
Jon Salza6711d72012-07-18 14:33:03 +0800552 if not test.is_leaf():
553 # Don't bother with parents; they will be updated when their
554 # children are updated.
555 continue
556
Jon Salz0697cbf2012-07-04 15:14:04 +0800557 test_state = test.get_state()
558 if test_state.status != TestState.ACTIVE:
559 continue
560 if isinstance(test, factory.ShutdownStep):
561 # Shutdown while the test was active - that's good.
Ricky Liang48e47f92014-02-26 19:31:51 +0800562 self.handle_shutdown_complete(test)
Jon Salz0697cbf2012-07-04 15:14:04 +0800563 else:
564 # Unexpected shutdown. Grab /var/log/messages for context.
565 if var_log_messages is None:
566 try:
567 var_log_messages = (
Hung-Te Lin1a4e30c2016-01-08 23:25:10 +0800568 sys_utils.GetVarLogMessagesBeforeReboot())
Jon Salz0697cbf2012-07-04 15:14:04 +0800569 # Write it to the log, to make it easier to
570 # correlate with /var/log/messages.
571 logging.info(
Ricky Liang45c73e72015-01-15 15:00:30 +0800572 'Unexpected shutdown. '
573 'Tail of /var/log/messages before last reboot:\n'
574 '%s', ('\n'.join(
575 ' ' + x for x in var_log_messages)))
Jon Salz0697cbf2012-07-04 15:14:04 +0800576 except: # pylint: disable=W0702
577 logging.exception('Unable to grok /var/log/messages')
578 var_log_messages = []
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800579
Hung-Te Linf5f2d7f2016-01-08 17:12:46 +0800580 if mosys_log is None and not sys_utils.InChroot():
Jon Salz008f4ea2012-08-28 05:39:45 +0800581 try:
Hung-Te Lin4e6357c2016-01-08 14:32:00 +0800582 mosys_log = process_utils.Spawn(
Jon Salz008f4ea2012-08-28 05:39:45 +0800583 ['mosys', 'eventlog', 'list'],
584 read_stdout=True, log_stderr_on_error=True).stdout_data
585 # Write it to the log also.
586 logging.info('System eventlog from mosys:\n%s\n', mosys_log)
587 except: # pylint: disable=W0702
588 logging.exception('Unable to read mosys eventlog')
Vic Yanga9c32212012-08-16 20:07:54 +0800589
Vic Yange4c275d2012-08-28 01:50:20 +0800590 if ec_console_log is None:
Dean Liao88b93192014-10-23 19:37:41 +0800591 ec_console_log = self.log_ec_console()
Vic Yange4c275d2012-08-28 01:50:20 +0800592
Vic Yang079f9872013-07-01 11:32:00 +0800593 if ec_panic_info is None:
Dean Liao88b93192014-10-23 19:37:41 +0800594 ec_panic_info = self.log_ec_panic_info()
Vic Yang079f9872013-07-01 11:32:00 +0800595
Jon Salz0697cbf2012-07-04 15:14:04 +0800596 error_msg = 'Unexpected shutdown while test was running'
Chun-Ta Lin53cbbd52016-06-08 21:42:19 +0800597 # TODO(itspeter): Add testlog to collect expired session infos.
Jon Salz0697cbf2012-07-04 15:14:04 +0800598 self.event_log.Log('end_test',
Ricky Liang45c73e72015-01-15 15:00:30 +0800599 path=test.path,
600 status=TestState.FAILED,
601 invocation=test.get_state().invocation,
602 error_msg=error_msg,
603 var_log_messages='\n'.join(var_log_messages),
604 mosys_log=mosys_log)
Jon Salz0697cbf2012-07-04 15:14:04 +0800605 test.update_state(
Ricky Liang45c73e72015-01-15 15:00:30 +0800606 status=TestState.FAILED,
607 error_msg=error_msg)
Chun-Ta Lin87c2dac2015-05-02 01:35:01 -0700608 # Trigger the OnTestFailure callback.
Claire Changd1961a22015-08-05 16:15:55 +0800609 self.run_queue.put(lambda: self.test_fail(test))
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800610
Jon Salz50efe942012-07-26 11:54:10 +0800611 if not test.never_fails:
612 # For "never_fails" tests (such as "Start"), don't cancel
613 # pending tests, since reboot is expected.
614 factory.console.info('Unexpected shutdown while test %s '
615 'running; cancelling any pending tests',
616 test.path)
617 self.state_instance.set_shared_data('tests_after_shutdown', [])
Jon Salz69806bb2012-07-20 18:05:02 +0800618
Jon Salz008f4ea2012-08-28 05:39:45 +0800619 self.update_skipped_tests()
620
621 def update_skipped_tests(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800622 """Updates skipped states based on run_if."""
Jon Salz885dcac2013-07-23 16:39:50 +0800623 env = TestArgEnv()
Ricky Liang45c73e72015-01-15 15:00:30 +0800624
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800625 def _evaluate_skip_from_run_if(test):
626 """Returns the run_if evaluation of the test.
627
628 Args:
629 test: A FactoryTest object.
630
631 Returns:
632 The run_if evaluation result. Returns False if the test has no
633 run_if argument.
634 """
635 value = None
636 if test.run_if_expr:
637 try:
638 value = test.run_if_expr(env)
639 except: # pylint: disable=W0702
640 logging.exception('Unable to evaluate run_if expression for %s',
641 test.path)
642 # But keep going; we have no choice. This will end up
643 # always activating the test.
644 elif test.run_if_table_name:
645 try:
646 aux = shopfloor.get_selected_aux_data(test.run_if_table_name)
647 value = aux.get(test.run_if_col)
648 except ValueError:
649 # Not available; assume it shouldn't be skipped
650 pass
651
652 if value is None:
653 skip = False
654 else:
655 skip = (not value) ^ t.run_if_not
656 return skip
657
658 # Gets all run_if evaluation, and stores results in skip_map.
659 skip_map = dict()
Jon Salz008f4ea2012-08-28 05:39:45 +0800660 for t in self.test_list.walk():
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800661 skip_map[t.path] = _evaluate_skip_from_run_if(t)
Jon Salz885dcac2013-07-23 16:39:50 +0800662
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800663 # Propagates the skip value from root of tree and updates skip_map.
664 def _update_skip_map_from_node(test, skip_from_parent):
665 """Updates skip_map from a given node.
Jon Salz885dcac2013-07-23 16:39:50 +0800666
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800667 Given a FactoryTest node and the skip value from parent, updates the
668 skip value of current node in the skip_map if skip value from parent is
669 True. If this node has children, recursively propagate this value to all
670 its children, that is, all its subtests.
671 Note that this function only updates value in skip_map, not the actual
672 test_list tree.
Jon Salz008f4ea2012-08-28 05:39:45 +0800673
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800674 Args:
675 test: The given FactoryTest object. It is a node in the test_list tree.
676 skip_from_parent: The skip value which propagates from the parent of
677 input node.
678 """
679 skip_this_tree = skip_from_parent or skip_map[test.path]
680 if skip_this_tree:
681 logging.info('Skip from node %r', test.path)
682 skip_map[test.path] = True
683 if test.is_leaf():
684 return
685 # Propagates skip value to its subtests
686 for subtest in test.subtests:
687 _update_skip_map_from_node(subtest, skip_this_tree)
688
689 _update_skip_map_from_node(self.test_list, False)
690
691 # Updates the skip value from skip_map to test_list tree. Also, updates test
692 # status if needed.
693 for t in self.test_list.walk():
694 skip = skip_map[t.path]
695 test_state = t.get_state()
696 if ((not skip) and
697 (test_state.status == TestState.PASSED) and
698 (test_state.error_msg == TestState.SKIPPED_MSG)):
699 # It was marked as skipped before, but now we need to run it.
700 # Mark as untested.
701 t.update_state(skip=skip, status=TestState.UNTESTED, error_msg='')
702 else:
703 t.update_state(skip=skip)
Jon Salz008f4ea2012-08-28 05:39:45 +0800704
Jon Salz0697cbf2012-07-04 15:14:04 +0800705 def show_next_active_test(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800706 """Rotates to the next visible active test."""
Jon Salz0697cbf2012-07-04 15:14:04 +0800707 self.reap_completed_tests()
708 active_tests = [
Ricky Liang45c73e72015-01-15 15:00:30 +0800709 t for t in self.test_list.walk()
710 if t.is_leaf() and t.get_state().status == TestState.ACTIVE]
Jon Salz0697cbf2012-07-04 15:14:04 +0800711 if not active_tests:
712 return
Jon Salz4f6c7172012-06-11 20:45:36 +0800713
Jon Salz0697cbf2012-07-04 15:14:04 +0800714 try:
715 next_test = active_tests[
Ricky Liang45c73e72015-01-15 15:00:30 +0800716 (active_tests.index(self.visible_test) + 1) % len(active_tests)]
Jon Salz0697cbf2012-07-04 15:14:04 +0800717 except ValueError: # visible_test not present in active_tests
718 next_test = active_tests[0]
Jon Salz4f6c7172012-06-11 20:45:36 +0800719
Jon Salz0697cbf2012-07-04 15:14:04 +0800720 self.set_visible_test(next_test)
Jon Salz4f6c7172012-06-11 20:45:36 +0800721
Jon Salz0697cbf2012-07-04 15:14:04 +0800722 def handle_event(self, event):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800723 """Handles an event from the event server."""
Jon Salz0697cbf2012-07-04 15:14:04 +0800724 handler = self.event_handlers.get(event.type)
725 if handler:
726 handler(event)
727 else:
728 # We don't register handlers for all event types - just ignore
729 # this event.
730 logging.debug('Unbound event type %s', event.type)
Jon Salz4f6c7172012-06-11 20:45:36 +0800731
Vic Yangaabf9fd2013-04-09 18:56:13 +0800732 def check_critical_factory_note(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800733 """Returns True if the last factory note is critical."""
Vic Yangaabf9fd2013-04-09 18:56:13 +0800734 notes = self.state_instance.get_shared_data('factory_note', True)
735 return notes and notes[-1]['level'] == 'CRITICAL'
736
Hung-Te Linef7f2be2015-07-20 20:38:51 +0800737 def schedule_restart(self):
738 """Schedules a restart event when any invocation is completed."""
739 self.is_restart_requested = True
740
741 def invocation_completion(self):
742 """Callback when an invocation is completed."""
743 if self.is_restart_requested:
744 logging.info('Restart by scheduled event.')
745 self.is_restart_requested = False
746 self.restart_tests()
747 else:
748 self.run_next_test()
749
Jon Salz0697cbf2012-07-04 15:14:04 +0800750 def run_next_test(self):
henryhsu4cc6b022014-04-22 17:12:42 +0800751 """Runs the next eligible test (or tests) in self.tests_to_run.
752
753 We have three kinds of the next eligible test:
754 1. normal
755 2. backgroundable
756 3. force_background
757
758 And we have four situations of the ongoing invocations:
759 a. only a running normal test
760 b. all running tests are backgroundable
761 c. all running tests are force_background
762 d. all running tests are any combination of backgroundable and
763 force_background
764
765 When a test would like to be run, it must follow the rules:
766 [1] cannot run with [abd]
767 [2] cannot run with [a]
768 All the other combinations are allowed
769 """
Jon Salz0697cbf2012-07-04 15:14:04 +0800770 self.reap_completed_tests()
Vic Yangaabf9fd2013-04-09 18:56:13 +0800771 if self.tests_to_run and self.check_critical_factory_note():
772 self.tests_to_run.clear()
773 return
Jon Salz0697cbf2012-07-04 15:14:04 +0800774 while self.tests_to_run:
Ricky Liang6fe218c2013-12-27 15:17:17 +0800775 logging.debug('Tests to run: %s', [x.path for x in self.tests_to_run])
Jon Salz94eb56f2012-06-12 18:01:12 +0800776
Jon Salz0697cbf2012-07-04 15:14:04 +0800777 test = self.tests_to_run[0]
Jon Salz94eb56f2012-06-12 18:01:12 +0800778
Jon Salz0697cbf2012-07-04 15:14:04 +0800779 if test in self.invocations:
780 logging.info('Next test %s is already running', test.path)
781 self.tests_to_run.popleft()
782 return
Jon Salz94eb56f2012-06-12 18:01:12 +0800783
Jon Salza1412922012-07-23 16:04:17 +0800784 for requirement in test.require_run:
785 for i in requirement.test.walk():
786 if i.get_state().status == TestState.ACTIVE:
Jon Salz304a75d2012-07-06 11:14:15 +0800787 logging.info('Waiting for active test %s to complete '
Jon Salza1412922012-07-23 16:04:17 +0800788 'before running %s', i.path, test.path)
Jon Salz304a75d2012-07-06 11:14:15 +0800789 return
790
henryhsu4cc6b022014-04-22 17:12:42 +0800791 def is_normal_test(test):
792 return not (test.backgroundable or test.force_background)
793
794 # [1] cannot run with [abd].
795 if self.invocations and is_normal_test(test) and any(
796 [not x.force_background for x in self.invocations]):
797 logging.info('Waiting for non-force_background tests to '
798 'complete before running %s', test.path)
799 return
800
801 # [2] cannot run with [a].
802 if self.invocations and test.backgroundable and any(
803 [is_normal_test(x) for x in self.invocations]):
804 logging.info('Waiting for normal tests to '
805 'complete before running %s', test.path)
Jon Salz0697cbf2012-07-04 15:14:04 +0800806 return
Jon Salz94eb56f2012-06-12 18:01:12 +0800807
Jon Salz3e6f5202012-10-15 15:08:29 +0800808 if test.get_state().skip:
809 factory.console.info('Skipping test %s', test.path)
810 test.update_state(status=TestState.PASSED,
811 error_msg=TestState.SKIPPED_MSG)
812 self.tests_to_run.popleft()
813 continue
814
Jon Salz0697cbf2012-07-04 15:14:04 +0800815 self.tests_to_run.popleft()
Jon Salz94eb56f2012-06-12 18:01:12 +0800816
Jon Salz304a75d2012-07-06 11:14:15 +0800817 untested = set()
Jon Salza1412922012-07-23 16:04:17 +0800818 for requirement in test.require_run:
819 for i in requirement.test.walk():
820 if i == test:
Jon Salz304a75d2012-07-06 11:14:15 +0800821 # We've hit this test itself; stop checking
822 break
Jon Salza1412922012-07-23 16:04:17 +0800823 if ((i.get_state().status == TestState.UNTESTED) or
824 (requirement.passed and i.get_state().status !=
825 TestState.PASSED)):
Jon Salz304a75d2012-07-06 11:14:15 +0800826 # Found an untested test; move on to the next
827 # element in require_run.
Jon Salza1412922012-07-23 16:04:17 +0800828 untested.add(i)
Jon Salz304a75d2012-07-06 11:14:15 +0800829 break
830
831 if untested:
832 untested_paths = ', '.join(sorted([x.path for x in untested]))
833 if self.state_instance.get_shared_data('engineering_mode',
834 optional=True):
835 # In engineering mode, we'll let it go.
836 factory.console.warn('In engineering mode; running '
837 '%s even though required tests '
838 '[%s] have not completed',
839 test.path, untested_paths)
840 else:
841 # Not in engineering mode; mark it failed.
842 error_msg = ('Required tests [%s] have not been run yet'
843 % untested_paths)
844 factory.console.error('Not running %s: %s',
845 test.path, error_msg)
846 test.update_state(status=TestState.FAILED,
847 error_msg=error_msg)
848 continue
849
Ricky Liang48e47f92014-02-26 19:31:51 +0800850 if (isinstance(test, factory.ShutdownStep) and
Ricky Liangb7eb8772014-09-15 18:05:22 +0800851 self.state_instance.get_shared_data(
852 state.POST_SHUTDOWN_TAG % test.path, optional=True)):
Ricky Liang48e47f92014-02-26 19:31:51 +0800853 # Invoking post shutdown method of shutdown test. We should retain the
854 # iterations_left and retries_left of the original test state.
855 test_state = self.state_instance.get_test_state(test.path)
856 self._run_test(test, test_state.iterations_left,
857 test_state.retries_left)
858 else:
859 # Starts a new test run; reset iterations and retries.
860 self._run_test(test, test.iterations, test.retries)
Jon Salz1acc8742012-07-17 17:45:55 +0800861
Cheng-Yi Chiangce05c002013-04-04 02:13:17 +0800862 def _run_test(self, test, iterations_left=None, retries_left=None):
Vic Yanga3cecf82014-12-26 00:44:21 -0800863 if not self._ui_initialized and not test.is_no_host():
864 self.init_ui()
Vic Yang08505c72015-01-06 17:01:53 -0800865 invoc = TestInvocation(
Hung-Te Linef7f2be2015-07-20 20:38:51 +0800866 self, test, on_completion=self.invocation_completion,
Claire Changd1961a22015-08-05 16:15:55 +0800867 on_test_failure=lambda: self.test_fail(test))
Jon Salz1acc8742012-07-17 17:45:55 +0800868 new_state = test.update_state(
Ricky Liang48e47f92014-02-26 19:31:51 +0800869 status=TestState.ACTIVE, increment_count=1, error_msg='',
870 invocation=invoc.uuid, iterations_left=iterations_left,
871 retries_left=retries_left,
872 visible=(self.visible_test == test))
Jon Salz1acc8742012-07-17 17:45:55 +0800873 invoc.count = new_state.count
874
875 self.invocations[test] = invoc
876 if self.visible_test is None and test.has_ui:
877 self.set_visible_test(test)
Vic Yang311ddb82012-09-26 12:08:28 +0800878 self.check_exclusive()
Jon Salz1acc8742012-07-17 17:45:55 +0800879 invoc.start()
Jon Salz5f2a0672012-05-22 17:14:06 +0800880
Vic Yang311ddb82012-09-26 12:08:28 +0800881 def check_exclusive(self):
Jon Salzce6a7f82013-06-10 18:22:54 +0800882 # alias since this is really long
883 EXCL_OPT = factory.FactoryTest.EXCLUSIVE_OPTIONS
884
Vic Yang311ddb82012-09-26 12:08:28 +0800885 current_exclusive_items = set([
Jon Salzce6a7f82013-06-10 18:22:54 +0800886 item for item in EXCL_OPT
Vic Yang311ddb82012-09-26 12:08:28 +0800887 if any([test.is_exclusive(item) for test in self.invocations])])
888
889 new_exclusive_items = current_exclusive_items - self.exclusive_items
Jon Salzce6a7f82013-06-10 18:22:54 +0800890 if EXCL_OPT.NETWORKING in new_exclusive_items:
Vic Yang311ddb82012-09-26 12:08:28 +0800891 logging.info('Disabling network')
892 self.connection_manager.DisableNetworking()
Jon Salzce6a7f82013-06-10 18:22:54 +0800893 if EXCL_OPT.CHARGER in new_exclusive_items:
Vic Yang311ddb82012-09-26 12:08:28 +0800894 logging.info('Stop controlling charger')
895
896 new_non_exclusive_items = self.exclusive_items - current_exclusive_items
Jon Salzce6a7f82013-06-10 18:22:54 +0800897 if EXCL_OPT.NETWORKING in new_non_exclusive_items:
Vic Yang311ddb82012-09-26 12:08:28 +0800898 logging.info('Re-enabling network')
899 self.connection_manager.EnableNetworking()
Jon Salzce6a7f82013-06-10 18:22:54 +0800900 if EXCL_OPT.CHARGER in new_non_exclusive_items:
Vic Yang311ddb82012-09-26 12:08:28 +0800901 logging.info('Start controlling charger')
902
Jon Salzce6a7f82013-06-10 18:22:54 +0800903 if self.cpufreq_manager:
904 enabled = EXCL_OPT.CPUFREQ not in current_exclusive_items
905 try:
906 self.cpufreq_manager.SetEnabled(enabled)
907 except: # pylint: disable=W0702
908 logging.exception('Unable to %s cpufreq services',
909 'enable' if enabled else 'disable')
910
Ricky Liang0f9978e2015-01-30 08:19:17 +0000911 # Only adjust charge state if not excluded
912 if (EXCL_OPT.CHARGER not in current_exclusive_items and
Hung-Te Linf5f2d7f2016-01-08 17:12:46 +0800913 not sys_utils.InChroot()):
Ricky Liang0f9978e2015-01-30 08:19:17 +0000914 if self.charge_manager:
Cheng-Yi Chiangd8186952013-04-04 23:41:14 +0800915 self.charge_manager.AdjustChargeState()
Vic Yang311ddb82012-09-26 12:08:28 +0800916
917 self.exclusive_items = current_exclusive_items
Jon Salz5da61e62012-05-31 13:06:22 +0800918
Dean Liao88b93192014-10-23 19:37:41 +0800919 def charge(self):
920 """Charges the board.
921
922 It won't try again if last time SetChargeState raised an exception.
923 """
924 if not self._can_charge:
925 return
926
927 try:
Ricky Liang9ac35e02015-01-30 16:01:32 +0800928 if self.charge_manager:
929 self.charge_manager.StartCharging()
930 else:
Hung-Te Lin6a72c642015-12-13 22:09:09 +0800931 self.dut.power.SetChargeState(self.dut.power.ChargeState.CHARGE)
Dean Liao88b93192014-10-23 19:37:41 +0800932 except NotImplementedError:
933 logging.info('Charging is not supported')
934 self._can_charge = False
Hung-Te Lin6a72c642015-12-13 22:09:09 +0800935 except dut.DUTException:
Dean Liao88b93192014-10-23 19:37:41 +0800936 logging.exception('Unable to set charge state on this board')
937 self._can_charge = False
938
cychiang21886742012-07-05 15:16:32 +0800939 def check_for_updates(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800940 """Schedules an asynchronous check for updates if necessary."""
cychiang21886742012-07-05 15:16:32 +0800941 if not self.test_list.options.update_period_secs:
942 # Not enabled.
943 return
944
945 now = time.time()
946 if self.last_update_check and (
947 now - self.last_update_check <
948 self.test_list.options.update_period_secs):
949 # Not yet time for another check.
950 return
951
952 self.last_update_check = now
953
954 def handle_check_for_update(reached_shopfloor, md5sum, needs_update):
955 if reached_shopfloor:
956 new_update_md5sum = md5sum if needs_update else None
Hung-Te Line594e5d2015-12-16 02:36:05 +0800957 if self.dut.info.update_md5sum != new_update_md5sum:
cychiang21886742012-07-05 15:16:32 +0800958 logging.info('Received new update MD5SUM: %s', new_update_md5sum)
Hung-Te Line594e5d2015-12-16 02:36:05 +0800959 self.dut.info.Overrides('update_md5sum', new_update_md5sum)
Peter Ammon1e1ec572014-06-26 17:56:32 -0700960 self.run_enqueue(self.update_system_info)
Cheng-Yi Chiang194d3c02015-03-16 14:37:15 +0800961 else:
962 if not self._suppress_periodic_update_messages:
963 logging.warning('Suppress error messages for periodic update checking'
964 ' after the first one.')
965 self._suppress_periodic_update_messages = True
cychiang21886742012-07-05 15:16:32 +0800966
967 updater.CheckForUpdateAsync(
Ricky Liang45c73e72015-01-15 15:00:30 +0800968 handle_check_for_update,
Cheng-Yi Chiang194d3c02015-03-16 14:37:15 +0800969 self.test_list.options.shopfloor_timeout_secs,
970 self._suppress_periodic_update_messages)
cychiang21886742012-07-05 15:16:32 +0800971
Jon Salza6711d72012-07-18 14:33:03 +0800972 def cancel_pending_tests(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800973 """Cancels any tests in the run queue."""
Jon Salza6711d72012-07-18 14:33:03 +0800974 self.run_tests([])
975
Ricky Liang4bff3e32014-02-20 18:46:11 +0800976 def restore_active_run_state(self):
977 """Restores active run id and the list of scheduled tests."""
978 self.run_id = self.state_instance.get_shared_data('run_id', optional=True)
979 self.scheduled_run_tests = self.state_instance.get_shared_data(
980 'scheduled_run_tests', optional=True)
981
982 def set_active_run_state(self):
983 """Sets active run id and the list of scheduled tests."""
984 self.run_id = str(uuid.uuid4())
985 self.scheduled_run_tests = [test.path for test in self.tests_to_run]
986 self.state_instance.set_shared_data('run_id', self.run_id)
987 self.state_instance.set_shared_data('scheduled_run_tests',
988 self.scheduled_run_tests)
989
Chih-Yu Huang85dc63c2015-08-12 15:21:28 +0800990 def run_tests(self, subtrees, status_filter=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800991 """Runs tests under subtree.
Jon Salz258a40c2012-04-19 12:34:01 +0800992
Jon Salz0697cbf2012-07-04 15:14:04 +0800993 The tests are run in order unless one fails (then stops).
994 Backgroundable tests are run simultaneously; when a foreground test is
995 encountered, we wait for all active tests to finish before continuing.
Jon Salzb1b39092012-05-03 02:05:09 +0800996
Ricky Liang6fe218c2013-12-27 15:17:17 +0800997 Args:
998 subtrees: Node or nodes containing tests to run (may either be
999 a single test or a list). Duplicates will be ignored.
Chih-Yu Huang85dc63c2015-08-12 15:21:28 +08001000 status_filter: List of available test states. Only run the tests which
1001 states are in the list. Set to None if all test states are available.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001002 """
Hung-Te Lin410f70a2015-12-15 14:53:42 +08001003 self.dut.hooks.OnTestStart()
Vic Yang08505c72015-01-06 17:01:53 -08001004
Jon Salz0697cbf2012-07-04 15:14:04 +08001005 if type(subtrees) != list:
1006 subtrees = [subtrees]
Jon Salz258a40c2012-04-19 12:34:01 +08001007
Jon Salz0697cbf2012-07-04 15:14:04 +08001008 # Nodes we've seen so far, to avoid duplicates.
1009 seen = set()
Jon Salz94eb56f2012-06-12 18:01:12 +08001010
Jon Salz0697cbf2012-07-04 15:14:04 +08001011 self.tests_to_run = deque()
1012 for subtree in subtrees:
1013 for test in subtree.walk():
1014 if test in seen:
1015 continue
1016 seen.add(test)
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001017
Jon Salz0697cbf2012-07-04 15:14:04 +08001018 if not test.is_leaf():
1019 continue
Chih-Yu Huang85dc63c2015-08-12 15:21:28 +08001020 if (status_filter is not None and
1021 test.get_state().status not in status_filter):
Jon Salz0697cbf2012-07-04 15:14:04 +08001022 continue
1023 self.tests_to_run.append(test)
Ricky Liang4bff3e32014-02-20 18:46:11 +08001024 if subtrees:
1025 self.set_active_run_state()
Jon Salz0697cbf2012-07-04 15:14:04 +08001026 self.run_next_test()
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001027
Jon Salz0697cbf2012-07-04 15:14:04 +08001028 def reap_completed_tests(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001029 """Removes completed tests from the set of active tests.
Jon Salz0697cbf2012-07-04 15:14:04 +08001030
1031 Also updates the visible test if it was reaped.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001032 """
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +08001033 test_completed = False
Jon Salz0697cbf2012-07-04 15:14:04 +08001034 for t, v in dict(self.invocations).iteritems():
1035 if v.is_completed():
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +08001036 test_completed = True
Jon Salz1acc8742012-07-17 17:45:55 +08001037 new_state = t.update_state(**v.update_state_on_completion)
Jon Salz0697cbf2012-07-04 15:14:04 +08001038 del self.invocations[t]
1039
Johny Lin62ed2a32015-05-13 11:57:12 +08001040 # Stop on failure if flag is true and there is no retry chances.
Chun-Ta Lin54e17e42012-09-06 22:05:13 +08001041 if (self.test_list.options.stop_on_failure and
Johny Lin62ed2a32015-05-13 11:57:12 +08001042 new_state.retries_left < 0 and
Chun-Ta Lin54e17e42012-09-06 22:05:13 +08001043 new_state.status == TestState.FAILED):
1044 # Clean all the tests to cause goofy to stop.
1045 self.tests_to_run = []
Ricky Liang45c73e72015-01-15 15:00:30 +08001046 factory.console.info('Stop on failure triggered. Empty the queue.')
Chun-Ta Lin54e17e42012-09-06 22:05:13 +08001047
Jon Salz1acc8742012-07-17 17:45:55 +08001048 if new_state.iterations_left and new_state.status == TestState.PASSED:
1049 # Play it again, Sam!
1050 self._run_test(t)
Cheng-Yi Chiangce05c002013-04-04 02:13:17 +08001051 # new_state.retries_left is obtained after update.
1052 # For retries_left == 0, test can still be run for the last time.
1053 elif (new_state.retries_left >= 0 and
1054 new_state.status == TestState.FAILED):
1055 # Still have to retry, Sam!
1056 self._run_test(t)
Jon Salz1acc8742012-07-17 17:45:55 +08001057
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +08001058 if test_completed:
Vic Yangf01c59f2013-04-19 17:37:56 +08001059 self.log_watcher.KickWatchThread()
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +08001060
Jon Salz0697cbf2012-07-04 15:14:04 +08001061 if (self.visible_test is None or
Jon Salz85a39882012-07-05 16:45:04 +08001062 self.visible_test not in self.invocations):
Jon Salz0697cbf2012-07-04 15:14:04 +08001063 self.set_visible_test(None)
1064 # Make the first running test, if any, the visible test
1065 for t in self.test_list.walk():
1066 if t in self.invocations:
1067 self.set_visible_test(t)
1068 break
1069
Jon Salz6dc031d2013-06-19 13:06:23 +08001070 def kill_active_tests(self, abort, root=None, reason=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001071 """Kills and waits for all active tests.
Jon Salz0697cbf2012-07-04 15:14:04 +08001072
Jon Salz85a39882012-07-05 16:45:04 +08001073 Args:
1074 abort: True to change state of killed tests to FAILED, False for
Jon Salz0697cbf2012-07-04 15:14:04 +08001075 UNTESTED.
Jon Salz85a39882012-07-05 16:45:04 +08001076 root: If set, only kills tests with root as an ancestor.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001077 reason: If set, the abort reason.
1078 """
Jon Salz0697cbf2012-07-04 15:14:04 +08001079 self.reap_completed_tests()
1080 for test, invoc in self.invocations.items():
Jon Salz85a39882012-07-05 16:45:04 +08001081 if root and not test.has_ancestor(root):
1082 continue
1083
Ricky Liang45c73e72015-01-15 15:00:30 +08001084 factory.console.info('Killing active test %s...', test.path)
Jon Salz6dc031d2013-06-19 13:06:23 +08001085 invoc.abort_and_join(reason)
Ricky Liang45c73e72015-01-15 15:00:30 +08001086 factory.console.info('Killed %s', test.path)
Jon Salz1acc8742012-07-17 17:45:55 +08001087 test.update_state(**invoc.update_state_on_completion)
Jon Salz0697cbf2012-07-04 15:14:04 +08001088 del self.invocations[test]
Jon Salz1acc8742012-07-17 17:45:55 +08001089
Jon Salz0697cbf2012-07-04 15:14:04 +08001090 if not abort:
1091 test.update_state(status=TestState.UNTESTED)
1092 self.reap_completed_tests()
1093
Jon Salz6dc031d2013-06-19 13:06:23 +08001094 def stop(self, root=None, fail=False, reason=None):
1095 self.kill_active_tests(fail, root, reason)
Jon Salz85a39882012-07-05 16:45:04 +08001096 # Remove any tests in the run queue under the root.
1097 self.tests_to_run = deque([x for x in self.tests_to_run
1098 if root and not x.has_ancestor(root)])
1099 self.run_next_test()
Jon Salz0697cbf2012-07-04 15:14:04 +08001100
Jon Salz4712ac72013-02-07 17:12:05 +08001101 def clear_state(self, root=None):
Jon Salzd7550792013-07-12 05:49:27 +08001102 if root is None:
1103 root = self.test_list
Jon Salz6dc031d2013-06-19 13:06:23 +08001104 self.stop(root, reason='Clearing test state')
Jon Salz4712ac72013-02-07 17:12:05 +08001105 for f in root.walk():
1106 if f.is_leaf():
1107 f.update_state(status=TestState.UNTESTED)
1108
Jon Salz6dc031d2013-06-19 13:06:23 +08001109 def abort_active_tests(self, reason=None):
1110 self.kill_active_tests(True, reason=reason)
Jon Salz0697cbf2012-07-04 15:14:04 +08001111
1112 def main(self):
Jon Salzeff94182013-06-19 15:06:28 +08001113 syslog.openlog('goofy')
1114
Jon Salz0697cbf2012-07-04 15:14:04 +08001115 try:
Jon Salzd7550792013-07-12 05:49:27 +08001116 self.status = Status.INITIALIZING
Jon Salz0697cbf2012-07-04 15:14:04 +08001117 self.init()
1118 self.event_log.Log('goofy_init',
Ricky Liang45c73e72015-01-15 15:00:30 +08001119 success=True)
Chun-Ta Lin53cbbd52016-06-08 21:42:19 +08001120 testlog.Log(
Joel Kitching9eb203a2016-04-21 15:36:30 +08001121 testlog.StationInit({
Chun-Ta Lin53cbbd52016-06-08 21:42:19 +08001122 'stationDeviceId': testlog_goofy.GetDeviceID(),
Joel Kitching21bc69b2016-07-13 08:29:52 -07001123 'stationInstallationId': testlog_goofy.GetInstallationID(),
Chun-Ta Lin53cbbd52016-06-08 21:42:19 +08001124 'count': testlog_goofy.GetInitCount(),
Joel Kitching9eb203a2016-04-21 15:36:30 +08001125 'success': True}))
Jon Salz0697cbf2012-07-04 15:14:04 +08001126 except:
Joel Kitching9eb203a2016-04-21 15:36:30 +08001127 try:
1128 if self.event_log:
Jon Salz0697cbf2012-07-04 15:14:04 +08001129 self.event_log.Log('goofy_init',
Ricky Liang45c73e72015-01-15 15:00:30 +08001130 success=False,
1131 trace=traceback.format_exc())
Chun-Ta Lin53cbbd52016-06-08 21:42:19 +08001132 if self.testlog:
1133 testlog.Log(
Joel Kitching9eb203a2016-04-21 15:36:30 +08001134 testlog.StationInit({
Chun-Ta Lin53cbbd52016-06-08 21:42:19 +08001135 'stationDeviceId': testlog_goofy.GetDeviceID(),
Joel Kitching21bc69b2016-07-13 08:29:52 -07001136 'stationInstallationId': testlog_goofy.GetInstallationID(),
Chun-Ta Lin53cbbd52016-06-08 21:42:19 +08001137 'count': testlog_goofy.GetInitCount(),
Joel Kitching9eb203a2016-04-21 15:36:30 +08001138 'success': False,
1139 'failureMessage': traceback.format_exc()}))
1140 except: # pylint: disable=W0702
1141 pass
Jon Salz0697cbf2012-07-04 15:14:04 +08001142 raise
1143
Jon Salzd7550792013-07-12 05:49:27 +08001144 self.status = Status.RUNNING
Jon Salzeff94182013-06-19 15:06:28 +08001145 syslog.syslog('Goofy (factory test harness) starting')
Chun-Ta Lin5d12b592015-06-30 00:54:23 -07001146 syslog.syslog('Boot sequence = %d' % GetBootSequence())
Chun-Ta Lin53cbbd52016-06-08 21:42:19 +08001147 syslog.syslog('Goofy init count = %d' % testlog_goofy.GetInitCount())
Jon Salz0697cbf2012-07-04 15:14:04 +08001148 self.run()
1149
1150 def update_system_info(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001151 """Updates system info."""
Hung-Te Line594e5d2015-12-16 02:36:05 +08001152 info = self.dut.info.GetAll()
1153 self.state_instance.set_shared_data('system_info', info)
Jon Salz0697cbf2012-07-04 15:14:04 +08001154 self.event_client.post_event(Event(Event.Type.SYSTEM_INFO,
Hung-Te Line594e5d2015-12-16 02:36:05 +08001155 system_info=info))
1156 logging.info('System info: %r', info)
Jon Salz0697cbf2012-07-04 15:14:04 +08001157
Jon Salzeb42f0d2012-07-27 19:14:04 +08001158 def update_factory(self, auto_run_on_restart=False, post_update_hook=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001159 """Commences updating factory software.
Jon Salzeb42f0d2012-07-27 19:14:04 +08001160
1161 Args:
1162 auto_run_on_restart: Auto-run when the machine comes back up.
1163 post_update_hook: Code to call after update but immediately before
1164 restart.
1165
1166 Returns:
1167 Never if the update was successful (we just reboot).
1168 False if the update was unnecessary (no update available).
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001169 """
Jon Salz6dc031d2013-06-19 13:06:23 +08001170 self.kill_active_tests(False, reason='Factory software update')
Jon Salza6711d72012-07-18 14:33:03 +08001171 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +08001172
Jon Salz5c344f62012-07-13 14:31:16 +08001173 def pre_update_hook():
1174 if auto_run_on_restart:
1175 self.state_instance.set_shared_data('tests_after_shutdown',
1176 FORCE_AUTO_RUN)
1177 self.state_instance.close()
1178
Jon Salzeb42f0d2012-07-27 19:14:04 +08001179 if updater.TryUpdate(pre_update_hook=pre_update_hook):
1180 if post_update_hook:
1181 post_update_hook()
1182 self.env.shutdown('reboot')
Jon Salz0697cbf2012-07-04 15:14:04 +08001183
Ricky Liang8fecf412014-05-22 10:56:14 +08001184 def handle_sigint(self, dummy_signum, dummy_frame): # pylint: disable=W0613
Jon Salz77c151e2012-08-28 07:20:37 +08001185 logging.error('Received SIGINT')
Peter Ammon1e1ec572014-06-26 17:56:32 -07001186 self.run_enqueue(None)
Jon Salz77c151e2012-08-28 07:20:37 +08001187 raise KeyboardInterrupt()
1188
Ricky Liang8fecf412014-05-22 10:56:14 +08001189 def handle_sigterm(self, dummy_signum, dummy_frame): # pylint: disable=W0613
1190 logging.error('Received SIGTERM')
Hung-Te Lin94ca4742014-07-09 20:13:50 +08001191 self.env.terminate()
1192 self.run_queue.put(None)
Ricky Liang8fecf412014-05-22 10:56:14 +08001193 raise RuntimeError('Received SIGTERM')
1194
Jon Salze12c2b32013-06-25 16:24:34 +08001195 def find_kcrashes(self):
1196 """Finds kcrash files, logs them, and marks them as seen."""
1197 seen_crashes = set(
1198 self.state_instance.get_shared_data('seen_crashes', optional=True)
1199 or [])
1200
1201 for path in glob.glob('/var/spool/crash/*'):
1202 if not os.path.isfile(path):
1203 continue
1204 if path in seen_crashes:
1205 continue
1206 try:
1207 stat = os.stat(path)
Hung-Te Lin4e6357c2016-01-08 14:32:00 +08001208 mtime = time_utils.TimeString(stat.st_mtime)
Jon Salze12c2b32013-06-25 16:24:34 +08001209 logging.info(
1210 'Found new crash file %s (%d bytes at %s)',
1211 path, stat.st_size, mtime)
1212 extra_log_args = {}
1213
1214 try:
1215 _, ext = os.path.splitext(path)
1216 if ext in ['.kcrash', '.meta']:
1217 ext = ext.replace('.', '')
1218 with open(path) as f:
1219 data = f.read(MAX_CRASH_FILE_SIZE)
1220 tell = f.tell()
1221 logging.info(
1222 'Contents of %s%s:%s',
1223 path,
1224 ('' if tell == stat.st_size
1225 else '(truncated to %d bytes)' % MAX_CRASH_FILE_SIZE),
1226 ('\n' + data).replace('\n', '\n ' + ext + '> '))
1227 extra_log_args['data'] = data
1228
1229 # Copy to /var/factory/kcrash for posterity
Joel Kitching625ff0f2016-05-16 14:59:40 -07001230 kcrash_dir = paths.GetFactoryRoot('kcrash')
Hung-Te Lin4e6357c2016-01-08 14:32:00 +08001231 file_utils.TryMakeDirs(kcrash_dir)
Jon Salze12c2b32013-06-25 16:24:34 +08001232 shutil.copy(path, kcrash_dir)
1233 logging.info('Copied to %s',
1234 os.path.join(kcrash_dir, os.path.basename(path)))
1235 finally:
1236 # Even if something goes wrong with the above, still try to
1237 # log to event log
1238 self.event_log.Log('crash_file',
1239 path=path, size=stat.st_size, mtime=mtime,
1240 **extra_log_args)
1241 except: # pylint: disable=W0702
1242 logging.exception('Unable to handle crash files %s', path)
1243 seen_crashes.add(path)
1244
1245 self.state_instance.set_shared_data('seen_crashes', list(seen_crashes))
1246
Jon Salz128b0932013-07-03 16:55:26 +08001247 def GetTestList(self, test_list_id):
1248 """Returns the test list with the given ID.
1249
1250 Raises:
1251 TestListError: The test list ID is not valid.
1252 """
1253 try:
1254 return self.test_lists[test_list_id]
1255 except KeyError:
1256 raise test_lists.TestListError(
1257 '%r is not a valid test list ID (available IDs are [%s])' % (
1258 test_list_id, ', '.join(sorted(self.test_lists.keys()))))
1259
1260 def InitTestLists(self):
Joel Kitching50a63ea2016-02-22 13:15:09 +08001261 """Reads in all test lists and sets the active test list.
1262
1263 Returns:
1264 True if the active test list could be set, False if failed.
1265 """
1266 startup_errors = []
1267 self.test_lists, failed_files = test_lists.BuildAllTestLists(
Ricky Liang27051552014-05-04 14:22:26 +08001268 force_generic=(self.options.automation_mode is not None))
Jon Salzd7550792013-07-12 05:49:27 +08001269 logging.info('Loaded test lists: [%s]',
1270 test_lists.DescribeTestLists(self.test_lists))
Jon Salz128b0932013-07-03 16:55:26 +08001271
Joel Kitching50a63ea2016-02-22 13:15:09 +08001272 # Check for any syntax errors in test list files.
1273 if failed_files:
1274 logging.info('Failed test list files: [%s]',
1275 ' '.join(failed_files.keys()))
1276 for f, exc_info in failed_files.iteritems():
1277 logging.error('Error in test list file: %s', f,
1278 exc_info=exc_info)
1279
1280 # Limit the stack trace to the very last entry.
1281 exc_type, exc_value, exc_traceback = exc_info
1282 while exc_traceback and exc_traceback.tb_next:
1283 exc_traceback = exc_traceback.tb_next
1284
1285 exc_string = ''.join(
1286 traceback.format_exception(
1287 exc_type, exc_value, exc_traceback)).rstrip()
1288 startup_errors.append('Error in test list file (%s):\n%s'
1289 % (f, exc_string))
1290
Jon Salz128b0932013-07-03 16:55:26 +08001291 if not self.options.test_list:
1292 self.options.test_list = test_lists.GetActiveTestListId()
1293
Joel Kitching50a63ea2016-02-22 13:15:09 +08001294 # Check for a non-existent test list ID.
1295 try:
1296 if os.sep in self.options.test_list:
1297 # It's a path pointing to an old-style test list; use it.
1298 self.test_list = factory.read_test_list(self.options.test_list)
1299 else:
1300 self.test_list = self.GetTestList(self.options.test_list)
1301 logging.info('Active test list: %s', self.test_list.test_list_id)
1302 except test_lists.TestListError as e:
1303 logging.exception('Invalid active test list: %s',
1304 self.options.test_list)
1305 startup_errors.append(e.message)
Jon Salz128b0932013-07-03 16:55:26 +08001306
Joel Kitching50a63ea2016-02-22 13:15:09 +08001307 # We may have failed loading the active test list.
1308 if self.test_list:
1309 if isinstance(self.test_list, test_lists.OldStyleTestList):
1310 # Actually load it in. (See OldStyleTestList for an explanation
1311 # of why this is necessary.)
1312 self.test_list = self.test_list.Load()
Jon Salz128b0932013-07-03 16:55:26 +08001313
Joel Kitching50a63ea2016-02-22 13:15:09 +08001314 self.test_list.state_instance = self.state_instance
Jon Salz128b0932013-07-03 16:55:26 +08001315
Joel Kitching50a63ea2016-02-22 13:15:09 +08001316 # Prepare DUT link.
1317 if self.test_list.options.dut_options:
1318 logging.info('dut_options set by %s: %r', self.test_list.test_list_id,
1319 self.test_list.options.dut_options)
1320 dut_utils.PrepareLink(**self.test_list.options.dut_options)
Wei-Han Chene8a025f2016-01-14 16:42:02 +08001321
Joel Kitching50a63ea2016-02-22 13:15:09 +08001322 # Show all startup errors.
1323 if startup_errors:
1324 self.state_instance.set_shared_data(
1325 'startup_error', '\n\n'.join(startup_errors))
1326
1327 # Only return False if failed to load the active test list.
1328 return bool(self.test_list)
Jon Salz128b0932013-07-03 16:55:26 +08001329
Shuo-Peng Liao268b40b2013-07-01 15:58:59 +08001330 def init_hooks(self):
1331 """Initializes hooks.
1332
1333 Must run after self.test_list ready.
1334 """
Shuo-Peng Liao52b90da2013-06-30 17:00:06 +08001335 module, cls = self.test_list.options.hooks_class.rsplit('.', 1)
1336 self.hooks = getattr(__import__(module, fromlist=[cls]), cls)()
1337 assert isinstance(self.hooks, factory.Hooks), (
Ricky Liang45c73e72015-01-15 15:00:30 +08001338 'hooks should be of type Hooks but is %r' % type(self.hooks))
Shuo-Peng Liao52b90da2013-06-30 17:00:06 +08001339 self.hooks.test_list = self.test_list
Shuo-Peng Liao268b40b2013-07-01 15:58:59 +08001340 self.hooks.OnCreatedTestList()
Shuo-Peng Liao52b90da2013-06-30 17:00:06 +08001341
Vic Yanga3cecf82014-12-26 00:44:21 -08001342 def init_ui(self):
1343 """Initialize UI."""
1344 self._ui_initialized = True
1345 if self.options.ui == 'chrome':
Hung-Te Lin8f6a3782015-01-06 22:58:32 +08001346 if self.options.monolithic:
Hung-Te Lin7bd55312014-12-30 16:43:36 +08001347 self.env.launch_chrome()
1348 else:
1349 # The presenter is responsible for launching Chrome. Let's just
1350 # wait here.
1351 self.env.controller_ready_for_ui()
Vic Yanga3cecf82014-12-26 00:44:21 -08001352 logging.info('Waiting for a web socket connection')
1353 self.web_socket_manager.wait()
1354
1355 # Wait for the test widget size to be set; this is done in
1356 # an asynchronous RPC so there is a small chance that the
1357 # web socket might be opened first.
1358 for _ in range(100): # 10 s
1359 try:
1360 if self.state_instance.get_shared_data('test_widget_size'):
1361 break
1362 except KeyError:
1363 pass # Retry
1364 time.sleep(0.1) # 100 ms
1365 else:
1366 logging.warn('Never received test_widget_size from UI')
1367
Jon Salz0697cbf2012-07-04 15:14:04 +08001368 def init(self, args=None, env=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001369 """Initializes Goofy.
Jon Salz0697cbf2012-07-04 15:14:04 +08001370
1371 Args:
1372 args: A list of command-line arguments. Uses sys.argv if
1373 args is None.
1374 env: An Environment instance to use (or None to choose
1375 FakeChrootEnvironment or DUTEnvironment as appropriate).
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001376 """
Jon Salz0697cbf2012-07-04 15:14:04 +08001377 parser = OptionParser()
1378 parser.add_option('-v', '--verbose', dest='verbose',
Jon Salz8fa8e832012-07-13 19:04:09 +08001379 action='store_true',
1380 help='Enable debug logging')
Jon Salz0697cbf2012-07-04 15:14:04 +08001381 parser.add_option('--print_test_list', dest='print_test_list',
Jon Salz8fa8e832012-07-13 19:04:09 +08001382 metavar='FILE',
1383 help='Read and print test list FILE, and exit')
Jon Salz0697cbf2012-07-04 15:14:04 +08001384 parser.add_option('--restart', dest='restart',
Jon Salz8fa8e832012-07-13 19:04:09 +08001385 action='store_true',
1386 help='Clear all test state')
Jon Salz0697cbf2012-07-04 15:14:04 +08001387 parser.add_option('--ui', dest='ui', type='choice',
Jon Salz7b5482e2014-08-04 17:48:41 +08001388 choices=['none', 'chrome'],
Jon Salz2f881df2013-02-01 17:00:35 +08001389 default='chrome',
Jon Salz8fa8e832012-07-13 19:04:09 +08001390 help='UI to use')
Jon Salz0697cbf2012-07-04 15:14:04 +08001391 parser.add_option('--ui_scale_factor', dest='ui_scale_factor',
Jon Salz8fa8e832012-07-13 19:04:09 +08001392 type='int', default=1,
1393 help=('Factor by which to scale UI '
1394 '(Chrome UI only)'))
Jon Salz0697cbf2012-07-04 15:14:04 +08001395 parser.add_option('--test_list', dest='test_list',
Jon Salz8fa8e832012-07-13 19:04:09 +08001396 metavar='FILE',
1397 help='Use FILE as test list')
Jon Salzc79a9982012-08-30 04:42:01 +08001398 parser.add_option('--dummy_shopfloor', action='store_true',
1399 help='Use a dummy shopfloor server')
Hung-Te Lincc41d2a2014-10-29 13:35:20 +08001400 parser.add_option('--dummy_connection_manager', action='store_true',
1401 help='Use a dummy connection manager')
Ricky Liang6fe218c2013-12-27 15:17:17 +08001402 parser.add_option('--automation-mode',
1403 choices=[m.lower() for m in AutomationMode],
Ricky Liang45c73e72015-01-15 15:00:30 +08001404 default='none', help='Factory test automation mode.')
Ricky Liang117484a2014-04-14 11:14:41 +08001405 parser.add_option('--no-auto-run-on-start', dest='auto_run_on_start',
1406 action='store_false', default=True,
1407 help=('do not automatically run the test list on goofy '
1408 'start; this is only valid when factory test '
1409 'automation is enabled'))
Chun-Ta Lina8dd3172014-11-26 16:15:13 +08001410 parser.add_option('--handshake_timeout', dest='handshake_timeout',
1411 type='float', default=0.3,
1412 help=('RPC timeout when doing handshake between device '
1413 'and presenter.'))
Vic Yang7d693c42014-09-14 09:52:39 +08001414 parser.add_option('--standalone', dest='standalone',
1415 action='store_true', default=False,
1416 help=('Assume the presenter is running on the same '
1417 'machines.'))
Hung-Te Lin8f6a3782015-01-06 22:58:32 +08001418 parser.add_option('--monolithic', dest='monolithic',
1419 action='store_true', default=False,
1420 help='Run in monolithic mode (without presenter)')
Jon Salz0697cbf2012-07-04 15:14:04 +08001421 (self.options, self.args) = parser.parse_args(args)
1422
Hung-Te Lina846f602014-07-04 20:32:22 +08001423 signal.signal(signal.SIGINT, self.handle_sigint)
1424 # TODO(hungte) SIGTERM does not work properly without Telemetry and should
1425 # be fixed.
Hung-Te Lina846f602014-07-04 20:32:22 +08001426
Jon Salz46b89562012-07-05 11:49:22 +08001427 # Make sure factory directories exist.
Joel Kitching625ff0f2016-05-16 14:59:40 -07001428 paths.GetLogRoot()
1429 paths.GetStateRoot()
1430 paths.GetTestDataRoot()
Jon Salz46b89562012-07-05 11:49:22 +08001431
Jon Salz0697cbf2012-07-04 15:14:04 +08001432 global _inited_logging # pylint: disable=W0603
1433 if not _inited_logging:
1434 factory.init_logging('goofy', verbose=self.options.verbose)
1435 _inited_logging = True
Jon Salz8fa8e832012-07-13 19:04:09 +08001436
Jon Salz0f996602012-10-03 15:26:48 +08001437 if self.options.print_test_list:
Joel Kitchingb85ed7f2014-10-08 18:24:39 +08001438 print(factory.read_test_list(
1439 self.options.print_test_list).__repr__(recursive=True))
Jon Salz0f996602012-10-03 15:26:48 +08001440 sys.exit(0)
1441
Jon Salzee85d522012-07-17 14:34:46 +08001442 event_log.IncrementBootSequence()
Chun-Ta Lin53cbbd52016-06-08 21:42:19 +08001443 testlog_goofy.IncrementInitCount()
1444
Jon Salzd15bbcf2013-05-21 17:33:57 +08001445 # Don't defer logging the initial event, so we can make sure
1446 # that device_id, reimage_id, etc. are all set up.
1447 self.event_log = EventLog('goofy', defer=False)
Chun-Ta Lin53cbbd52016-06-08 21:42:19 +08001448 self.testlog = testlog.Testlog(
1449 log_root=paths.GetLogRoot(), uuid=self.uuid)
1450 # Direct the logging calls to testlog as well.
1451 testlog.CapturePythonLogging(
1452 callback=self.testlog.primary_json.Log,
1453 level=logging.getLogger().getEffectiveLevel())
Jon Salz0697cbf2012-07-04 15:14:04 +08001454
Jon Salz0697cbf2012-07-04 15:14:04 +08001455 if env:
1456 self.env = env
Hung-Te Linf5f2d7f2016-01-08 17:12:46 +08001457 elif sys_utils.InChroot():
Jon Salz0697cbf2012-07-04 15:14:04 +08001458 self.env = test_environment.FakeChrootEnvironment()
1459 logging.warn(
Ricky Liang45c73e72015-01-15 15:00:30 +08001460 'Using chroot environment: will not actually run autotests')
Hung-Te Lina846f602014-07-04 20:32:22 +08001461 elif self.options.ui == 'chrome':
Ricky Liang09d66d82014-09-25 11:20:54 +08001462 self.env = test_environment.DUTEnvironment()
Jon Salz0697cbf2012-07-04 15:14:04 +08001463 self.env.goofy = self
Vic Yanga4931152014-08-11 16:36:24 -07001464 # web_socket_manager will be initialized later
1465 # pylint: disable=W0108
1466 self.env.has_sockets = lambda: self.web_socket_manager.has_sockets()
Jon Salz0697cbf2012-07-04 15:14:04 +08001467
1468 if self.options.restart:
1469 state.clear_state()
1470
Hung-Te Linf5f2d7f2016-01-08 17:12:46 +08001471 if self.options.ui_scale_factor != 1 and sys_utils.InQEMU():
Jon Salz0697cbf2012-07-04 15:14:04 +08001472 logging.warn(
Ricky Liang45c73e72015-01-15 15:00:30 +08001473 'In QEMU; ignoring ui_scale_factor argument')
Jon Salz0697cbf2012-07-04 15:14:04 +08001474 self.options.ui_scale_factor = 1
1475
1476 logging.info('Started')
1477
Hung-Te Lin8f6a3782015-01-06 22:58:32 +08001478 if not self.options.monolithic:
Hung-Te Lin7bd55312014-12-30 16:43:36 +08001479 self.link_manager = PresenterLinkManager(
1480 check_interval=1,
1481 handshake_timeout=self.options.handshake_timeout,
1482 standalone=self.options.standalone)
Peter Ammon1e1ec572014-06-26 17:56:32 -07001483
Jon Salz0697cbf2012-07-04 15:14:04 +08001484 self.start_state_server()
1485 self.state_instance.set_shared_data('hwid_cfg', get_hwid_cfg())
1486 self.state_instance.set_shared_data('ui_scale_factor',
Ricky Liang09216dc2013-02-22 17:26:45 +08001487 self.options.ui_scale_factor)
Jon Salz0697cbf2012-07-04 15:14:04 +08001488 self.last_shutdown_time = (
Ricky Liang45c73e72015-01-15 15:00:30 +08001489 self.state_instance.get_shared_data('shutdown_time', optional=True))
Jon Salz0697cbf2012-07-04 15:14:04 +08001490 self.state_instance.del_shared_data('shutdown_time', optional=True)
Jon Salzb19ea072013-02-07 16:35:00 +08001491 self.state_instance.del_shared_data('startup_error', optional=True)
Jon Salz0697cbf2012-07-04 15:14:04 +08001492
Ricky Liang6fe218c2013-12-27 15:17:17 +08001493 self.options.automation_mode = ParseAutomationMode(
1494 self.options.automation_mode)
1495 self.state_instance.set_shared_data('automation_mode',
1496 self.options.automation_mode)
1497 self.state_instance.set_shared_data(
1498 'automation_mode_prompt',
1499 AutomationModePrompt[self.options.automation_mode])
1500
Joel Kitching50a63ea2016-02-22 13:15:09 +08001501 success = False
1502 exc_info = None
Jon Salz128b0932013-07-03 16:55:26 +08001503 try:
Joel Kitching50a63ea2016-02-22 13:15:09 +08001504 success = self.InitTestLists()
Jon Salz128b0932013-07-03 16:55:26 +08001505 except: # pylint: disable=W0702
Joel Kitching50a63ea2016-02-22 13:15:09 +08001506 exc_info = sys.exc_info()
1507
1508 if not success:
1509 if exc_info:
1510 logging.exception('Unable to initialize test lists')
1511 self.state_instance.set_shared_data(
1512 'startup_error',
1513 'Unable to initialize test lists\n%s' % (
1514 traceback.format_exc()))
Jon Salzb19ea072013-02-07 16:35:00 +08001515 if self.options.ui == 'chrome':
1516 # Create an empty test list with default options so that the rest of
1517 # startup can proceed.
1518 self.test_list = factory.FactoryTestList(
1519 [], self.state_instance, factory.Options())
1520 else:
1521 # Bail with an error; no point in starting up.
1522 sys.exit('No valid test list; exiting.')
1523
Shuo-Peng Liao268b40b2013-07-01 15:58:59 +08001524 self.init_hooks()
1525
Jon Salz822838b2013-03-25 17:32:33 +08001526 if self.test_list.options.clear_state_on_start:
1527 self.state_instance.clear_test_state()
1528
Jon Salz670ce062014-05-16 15:53:50 +08001529 # If the phase is invalid, this will raise a ValueError.
1530 phase.SetPersistentPhase(self.test_list.options.phase)
1531
Dean Liao85ca86f2014-11-03 12:28:08 +08001532 # For netboot firmware, mainfw_type should be 'netboot'.
Hung-Te Line594e5d2015-12-16 02:36:05 +08001533 if (self.dut.info.mainfw_type != 'nonchrome' and
1534 self.dut.info.firmware_version is None):
Ricky Liang45c73e72015-01-15 15:00:30 +08001535 self.state_instance.set_shared_data(
1536 'startup_error',
Vic Yang9bd4f772013-06-04 17:34:00 +08001537 'Netboot firmware detected\n'
1538 'Connect Ethernet and reboot to re-image.\n'
1539 u'侦测到网路开机固件\n'
1540 u'请连接乙太网并重启')
1541
Jon Salz0697cbf2012-07-04 15:14:04 +08001542 if not self.state_instance.has_shared_data('ui_lang'):
1543 self.state_instance.set_shared_data('ui_lang',
Ricky Liang45c73e72015-01-15 15:00:30 +08001544 self.test_list.options.ui_lang)
Jon Salz0697cbf2012-07-04 15:14:04 +08001545 self.state_instance.set_shared_data(
Ricky Liang45c73e72015-01-15 15:00:30 +08001546 'test_list_options',
1547 self.test_list.options.__dict__)
Jon Salz0697cbf2012-07-04 15:14:04 +08001548 self.state_instance.test_list = self.test_list
1549
Cheng-Yi Chiang39d32ad2013-07-23 15:02:38 +08001550 self.check_log_rotation()
Jon Salz83ef34b2012-11-01 19:46:35 +08001551
Jon Salz23926422012-09-01 03:38:13 +08001552 if self.options.dummy_shopfloor:
Ricky Liang45c73e72015-01-15 15:00:30 +08001553 os.environ[shopfloor.SHOPFLOOR_SERVER_ENV_VAR_NAME] = (
1554 'http://%s:%d/' %
Joel Kitchingb85ed7f2014-10-08 18:24:39 +08001555 (net_utils.LOCALHOST, shopfloor.DEFAULT_SERVER_PORT))
Hung-Te Lin4e6357c2016-01-08 14:32:00 +08001556 self.dummy_shopfloor = process_utils.Spawn(
Wei-Han Chen2ebb92d2016-01-12 14:51:41 +08001557 [os.path.join(paths.FACTORY_PATH, 'bin', 'shopfloor_server'),
Jon Salz23926422012-09-01 03:38:13 +08001558 '--dummy'])
1559 elif self.test_list.options.shopfloor_server_url:
1560 shopfloor.set_server_url(self.test_list.options.shopfloor_server_url)
Jon Salz2bf2f6b2013-03-28 18:49:26 +08001561 shopfloor.set_enabled(True)
Jon Salz23926422012-09-01 03:38:13 +08001562
Hung-Te Linf5f2d7f2016-01-08 17:12:46 +08001563 if self.test_list.options.time_sanitizer and not sys_utils.InChroot():
Jon Salz8fa8e832012-07-13 19:04:09 +08001564 self.time_sanitizer = time_sanitizer.TimeSanitizer(
Ricky Liang45c73e72015-01-15 15:00:30 +08001565 base_time=time_sanitizer.GetBaseTimeFromFile(
1566 # lsb-factory is written by the factory install shim during
1567 # installation, so it should have a good time obtained from
1568 # the mini-Omaha server. If it's not available, we'll use
1569 # /etc/lsb-factory (which will be much older, but reasonably
1570 # sane) and rely on a shopfloor sync to set a more accurate
1571 # time.
1572 '/usr/local/etc/lsb-factory',
1573 '/etc/lsb-release'))
Jon Salz8fa8e832012-07-13 19:04:09 +08001574 self.time_sanitizer.RunOnce()
1575
Vic Yangd8990da2013-06-27 16:57:43 +08001576 if self.test_list.options.check_cpu_usage_period_secs:
Hung-Te Lin4e6357c2016-01-08 14:32:00 +08001577 self.cpu_usage_watcher = process_utils.Spawn(
Ricky Liang45c73e72015-01-15 15:00:30 +08001578 ['py/tools/cpu_usage_monitor.py', '-p',
1579 str(self.test_list.options.check_cpu_usage_period_secs)],
Wei-Han Chen2ebb92d2016-01-12 14:51:41 +08001580 cwd=paths.FACTORY_PATH)
Vic Yangd8990da2013-06-27 16:57:43 +08001581
Chun-Ta Lin5d12b592015-06-30 00:54:23 -07001582 # Enable thermal monitor
1583 if self.test_list.options.thermal_monitor_period_secs > 0:
Hung-Te Lin23cb7612016-01-19 19:19:32 +08001584 self.thermal_watcher = process_utils.Spawn(
Chun-Ta Lin5d12b592015-06-30 00:54:23 -07001585 ['py/tools/thermal_monitor.py',
1586 '-p', str(self.test_list.options.thermal_monitor_period_secs),
1587 '-d', str(self.test_list.options.thermal_monitor_delta)],
Wei-Han Chen2ebb92d2016-01-12 14:51:41 +08001588 cwd=paths.FACTORY_PATH)
Chun-Ta Lin5d12b592015-06-30 00:54:23 -07001589
Jon Salz0697cbf2012-07-04 15:14:04 +08001590 self.init_states()
1591 self.start_event_server()
Wei-Ning Huang38b75f02015-02-25 18:25:14 +08001592 self.start_terminal_server()
Hung-Te Lincc41d2a2014-10-29 13:35:20 +08001593
1594 if self.options.dummy_connection_manager:
1595 # Override network manager creation to dummy implmenetation.
1596 logging.info('Using dummy network manager (--dummy_connection_manager).')
1597 self.connection_manager = connection_manager.DummyConnectionManager()
1598 else:
1599 self.connection_manager = self.env.create_connection_manager(
1600 self.test_list.options.wlans,
Mao Huang4340c632015-04-14 14:35:22 +08001601 self.test_list.options.scan_wifi_period_secs,
1602 self.test_list.options.override_blacklisted_network_devices)
Hung-Te Lincc41d2a2014-10-29 13:35:20 +08001603
Jon Salz0697cbf2012-07-04 15:14:04 +08001604 # Note that we create a log watcher even if
1605 # sync_event_log_period_secs isn't set (no background
1606 # syncing), since we may use it to flush event logs as well.
1607 self.log_watcher = EventLogWatcher(
Ricky Liang45c73e72015-01-15 15:00:30 +08001608 self.test_list.options.sync_event_log_period_secs,
1609 event_log_db_file=None,
1610 handle_event_logs_callback=self.handle_event_logs)
Jon Salz0697cbf2012-07-04 15:14:04 +08001611 if self.test_list.options.sync_event_log_period_secs:
1612 self.log_watcher.StartWatchThread()
1613
Cheng-Yi Chianga0f6eff2014-01-09 18:27:22 +08001614 # Creates a system log manager to scan logs periocially.
1615 # A scan includes clearing logs and optionally syncing logs if
1616 # enable_syng_log is True. We kick it to sync logs.
1617 self.system_log_manager = SystemLogManager(
Ricky Liang45c73e72015-01-15 15:00:30 +08001618 sync_log_paths=self.test_list.options.sync_log_paths,
1619 sync_log_period_secs=self.test_list.options.sync_log_period_secs,
1620 scan_log_period_secs=self.test_list.options.scan_log_period_secs,
1621 clear_log_paths=self.test_list.options.clear_log_paths,
1622 clear_log_excluded_paths=self.test_list.options.clear_log_excluded_paths)
Cheng-Yi Chianga0f6eff2014-01-09 18:27:22 +08001623 self.system_log_manager.Start()
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +08001624
Jon Salz0697cbf2012-07-04 15:14:04 +08001625 self.update_system_info()
1626
Vic Yang4953fc12012-07-26 16:19:53 +08001627 assert ((self.test_list.options.min_charge_pct is None) ==
1628 (self.test_list.options.max_charge_pct is None))
Hung-Te Linf5f2d7f2016-01-08 17:12:46 +08001629 if sys_utils.InChroot():
Vic Yange83d9a12013-04-19 20:00:20 +08001630 logging.info('In chroot, ignoring charge manager and charge state')
Ricky Liangc392a1c2014-06-20 18:24:59 +08001631 elif (self.test_list.options.enable_charge_manager and
1632 self.test_list.options.min_charge_pct is not None):
Vic Yang4953fc12012-07-26 16:19:53 +08001633 self.charge_manager = ChargeManager(self.test_list.options.min_charge_pct,
1634 self.test_list.options.max_charge_pct)
Hung-Te Linc17b3d82015-12-15 15:26:08 +08001635 self.dut.status.Overrides('charge_manager', self.charge_manager)
Cheng-Yi Chiangd8186952013-04-04 23:41:14 +08001636 else:
1637 # Goofy should set charger state to charge if charge_manager is disabled.
Dean Liao88b93192014-10-23 19:37:41 +08001638 self.charge()
Vic Yang4953fc12012-07-26 16:19:53 +08001639
Vic Yang6cee2472014-10-22 17:18:52 -07001640 if CoreDumpManager.CoreDumpEnabled():
1641 self.core_dump_manager = CoreDumpManager(
1642 self.test_list.options.core_dump_watchlist)
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001643
Jon Salz0697cbf2012-07-04 15:14:04 +08001644 os.environ['CROS_FACTORY'] = '1'
1645 os.environ['CROS_DISABLE_SITE_SYSINFO'] = '1'
1646
Hung-Te Linf5f2d7f2016-01-08 17:12:46 +08001647 if not sys_utils.InChroot() and self.test_list.options.use_cpufreq_manager:
Ricky Liangecddbd42014-07-24 11:32:10 +08001648 logging.info('Enabling CPU frequency manager')
Jon Salzddf0d052013-06-18 12:52:44 +08001649 self.cpufreq_manager = CpufreqManager(event_log=self.event_log)
Jon Salzce6a7f82013-06-10 18:22:54 +08001650
Justin Chuang31b02432013-06-27 15:16:51 +08001651 # Startup hooks may want to skip some tests.
1652 self.update_skipped_tests()
Jon Salz416f9cc2013-05-10 18:32:50 +08001653
Jon Salze12c2b32013-06-25 16:24:34 +08001654 self.find_kcrashes()
1655
Shuo-Peng Liao268b40b2013-07-01 15:58:59 +08001656 # Should not move earlier.
1657 self.hooks.OnStartup()
1658
Ricky Liang36512a32014-07-25 11:47:04 +08001659 # Only after this point the Goofy backend is ready for UI connection.
1660 self.ready_for_ui_connection = True
1661
Ricky Liang650f6bf2012-09-28 13:22:54 +08001662 # Create download path for autotest beforehand or autotests run at
1663 # the same time might fail due to race condition.
Hung-Te Linf5f2d7f2016-01-08 17:12:46 +08001664 if not sys_utils.InChroot():
Hung-Te Lin4e6357c2016-01-08 14:32:00 +08001665 file_utils.TryMakeDirs(os.path.join('/usr/local/autotest', 'tests',
1666 'download'))
Ricky Liang650f6bf2012-09-28 13:22:54 +08001667
Jon Salz0697cbf2012-07-04 15:14:04 +08001668 def state_change_callback(test, test_state):
1669 self.event_client.post_event(
Ricky Liang4bff3e32014-02-20 18:46:11 +08001670 Event(Event.Type.STATE_CHANGE, path=test.path, state=test_state))
Jon Salz0697cbf2012-07-04 15:14:04 +08001671 self.test_list.state_change_callback = state_change_callback
Jon Salz73e0fd02012-04-04 11:46:38 +08001672
Vic Yange2c76a82014-10-30 12:48:19 -07001673 self.autotest_prespawner = prespawner.AutotestPrespawner()
1674 self.autotest_prespawner.start()
1675
1676 self.pytest_prespawner = prespawner.PytestPrespawner()
1677 self.pytest_prespawner.start()
Jon Salza6711d72012-07-18 14:33:03 +08001678
Ricky Liang48e47f92014-02-26 19:31:51 +08001679 tests_after_shutdown = self.state_instance.get_shared_data(
1680 'tests_after_shutdown', optional=True)
Jon Salz57717ca2012-04-04 16:47:25 +08001681
Jon Salz5c344f62012-07-13 14:31:16 +08001682 force_auto_run = (tests_after_shutdown == FORCE_AUTO_RUN)
1683 if not force_auto_run and tests_after_shutdown is not None:
Ricky Liang48e47f92014-02-26 19:31:51 +08001684 logging.info('Resuming tests after shutdown: %s', tests_after_shutdown)
Jon Salz0697cbf2012-07-04 15:14:04 +08001685 self.tests_to_run.extend(
Ricky Liang4bff3e32014-02-20 18:46:11 +08001686 self.test_list.lookup_path(t) for t in tests_after_shutdown)
Peter Ammon1e1ec572014-06-26 17:56:32 -07001687 self.run_enqueue(self.run_next_test)
Jon Salz0697cbf2012-07-04 15:14:04 +08001688 else:
Jon Salz5c344f62012-07-13 14:31:16 +08001689 if force_auto_run or self.test_list.options.auto_run_on_start:
Ricky Liang117484a2014-04-14 11:14:41 +08001690 # If automation mode is enabled, allow suppress auto_run_on_start.
1691 if (self.options.automation_mode == 'NONE' or
1692 self.options.auto_run_on_start):
Chih-Yu Huang85dc63c2015-08-12 15:21:28 +08001693 status_filter = [TestState.UNTESTED]
1694 if self.test_list.options.retry_failed_on_start:
1695 status_filter.append(TestState.FAILED)
1696 self.run_enqueue(lambda: self.run_tests(self.test_list, status_filter))
Jon Salz5c344f62012-07-13 14:31:16 +08001697 self.state_instance.set_shared_data('tests_after_shutdown', None)
Ricky Liang4bff3e32014-02-20 18:46:11 +08001698 self.restore_active_run_state()
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001699
Hung-Te Lin410f70a2015-12-15 14:53:42 +08001700 self.dut.hooks.OnTestStart()
Vic Yang08505c72015-01-06 17:01:53 -08001701
Dean Liao592e4d52013-01-10 20:06:39 +08001702 self.may_disable_cros_shortcut_keys()
1703
1704 def may_disable_cros_shortcut_keys(self):
1705 test_options = self.test_list.options
1706 if test_options.disable_cros_shortcut_keys:
1707 logging.info('Filter ChromeOS shortcut keys.')
1708 self.key_filter = KeyFilter(
1709 unmap_caps_lock=test_options.disable_caps_lock,
1710 caps_lock_keycode=test_options.caps_lock_keycode)
1711 self.key_filter.Start()
1712
Jon Salz0e6532d2012-10-25 16:30:11 +08001713 def _should_sync_time(self, foreground=False):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001714 """Returns True if we should attempt syncing time with shopfloor.
Jon Salz0e6532d2012-10-25 16:30:11 +08001715
1716 Args:
1717 foreground: If True, synchronizes even if background syncing
1718 is disabled (e.g., in explicit sync requests from the
1719 SyncShopfloor test).
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001720 """
Jon Salz0e6532d2012-10-25 16:30:11 +08001721 return ((foreground or
1722 self.test_list.options.sync_time_period_secs) and
Jon Salz54882d02012-08-31 01:57:54 +08001723 self.time_sanitizer and
1724 (not self.time_synced) and
Hung-Te Linf5f2d7f2016-01-08 17:12:46 +08001725 (not sys_utils.InChroot()))
Jon Salz54882d02012-08-31 01:57:54 +08001726
Jon Salz0e6532d2012-10-25 16:30:11 +08001727 def sync_time_with_shopfloor_server(self, foreground=False):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001728 """Syncs time with shopfloor server, if not yet synced.
Jon Salz54882d02012-08-31 01:57:54 +08001729
Jon Salz0e6532d2012-10-25 16:30:11 +08001730 Args:
1731 foreground: If True, synchronizes even if background syncing
1732 is disabled (e.g., in explicit sync requests from the
1733 SyncShopfloor test).
1734
Jon Salz54882d02012-08-31 01:57:54 +08001735 Returns:
1736 False if no time sanitizer is available, or True if this sync (or a
1737 previous sync) succeeded.
1738
1739 Raises:
1740 Exception if unable to contact the shopfloor server.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001741 """
Jon Salz0e6532d2012-10-25 16:30:11 +08001742 if self._should_sync_time(foreground):
Jon Salz54882d02012-08-31 01:57:54 +08001743 self.time_sanitizer.SyncWithShopfloor()
1744 self.time_synced = True
1745 return self.time_synced
1746
Jon Salzb92c5112012-09-21 15:40:11 +08001747 def log_disk_space_stats(self):
Hung-Te Linf5f2d7f2016-01-08 17:12:46 +08001748 if (sys_utils.InChroot() or
Jon Salz18e0e022013-06-11 17:13:39 +08001749 not self.test_list.options.log_disk_space_period_secs):
Jon Salzb92c5112012-09-21 15:40:11 +08001750 return
1751
1752 now = time.time()
1753 if (self.last_log_disk_space_time and
1754 now - self.last_log_disk_space_time <
1755 self.test_list.options.log_disk_space_period_secs):
1756 return
1757 self.last_log_disk_space_time = now
1758
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001759 # Upload event if stateful partition usage is above threshold.
1760 # Stateful partition is mounted on /usr/local, while
1761 # encrypted stateful partition is mounted on /var.
1762 # If there are too much logs in the factory process,
1763 # these two partitions might get full.
Jon Salzb92c5112012-09-21 15:40:11 +08001764 try:
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001765 vfs_infos = disk_space.GetAllVFSInfo()
1766 stateful_info, encrypted_info = None, None
1767 for vfs_info in vfs_infos.values():
1768 if '/usr/local' in vfs_info.mount_points:
1769 stateful_info = vfs_info
1770 if '/var' in vfs_info.mount_points:
1771 encrypted_info = vfs_info
1772
1773 stateful = disk_space.GetPartitionUsage(stateful_info)
1774 encrypted = disk_space.GetPartitionUsage(encrypted_info)
1775
Ricky Liang45c73e72015-01-15 15:00:30 +08001776 above_threshold = (
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001777 self.test_list.options.stateful_usage_threshold and
1778 max(stateful.bytes_used_pct,
1779 stateful.inodes_used_pct,
1780 encrypted.bytes_used_pct,
1781 encrypted.inodes_used_pct) >
Ricky Liang45c73e72015-01-15 15:00:30 +08001782 self.test_list.options.stateful_usage_threshold)
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001783
1784 if above_threshold:
1785 self.event_log.Log('stateful_partition_usage',
Ricky Liang45c73e72015-01-15 15:00:30 +08001786 partitions={
1787 'stateful': {
1788 'bytes_used_pct': FloatDigit(stateful.bytes_used_pct, 2),
1789 'inodes_used_pct': FloatDigit(stateful.inodes_used_pct, 2)},
1790 'encrypted_stateful': {
1791 'bytes_used_pct': FloatDigit(encrypted.bytes_used_pct, 2),
1792 'inodes_used_pct': FloatDigit(encrypted.inodes_used_pct, 2)}
1793 })
Cheng-Yi Chiang1b722322015-03-16 20:07:03 +08001794 self.log_watcher.KickWatchThread()
Hung-Te Linf5f2d7f2016-01-08 17:12:46 +08001795 if (not sys_utils.InChroot() and
Cheng-Yi Chiang00798e72013-06-20 18:16:39 +08001796 self.test_list.options.stateful_usage_above_threshold_action):
Hung-Te Lin4e6357c2016-01-08 14:32:00 +08001797 process_utils.Spawn(
1798 self.test_list.options.stateful_usage_above_threshold_action,
1799 call=True)
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001800
1801 message = disk_space.FormatSpaceUsedAll(vfs_infos)
Jon Salz3c493bb2013-02-07 17:24:58 +08001802 if message != self.last_log_disk_space_message:
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001803 if above_threshold:
1804 logging.warning(message)
1805 else:
1806 logging.info(message)
Jon Salz3c493bb2013-02-07 17:24:58 +08001807 self.last_log_disk_space_message = message
Jon Salzb92c5112012-09-21 15:40:11 +08001808 except: # pylint: disable=W0702
1809 logging.exception('Unable to get disk space used')
1810
Justin Chuang83813982013-05-13 01:26:32 +08001811 def check_battery(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001812 """Checks the current battery status.
Justin Chuang83813982013-05-13 01:26:32 +08001813
1814 Logs current battery charging level and status to log. If the battery level
1815 is lower below warning_low_battery_pct, send warning event to shopfloor.
1816 If the battery level is lower below critical_low_battery_pct, flush disks.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001817 """
Justin Chuang83813982013-05-13 01:26:32 +08001818 if not self.test_list.options.check_battery_period_secs:
1819 return
1820
1821 now = time.time()
1822 if (self.last_check_battery_time and
1823 now - self.last_check_battery_time <
1824 self.test_list.options.check_battery_period_secs):
1825 return
1826 self.last_check_battery_time = now
1827
1828 message = ''
1829 log_level = logging.INFO
1830 try:
Hung-Te Lin6a72c642015-12-13 22:09:09 +08001831 power = self.dut.power
Justin Chuang83813982013-05-13 01:26:32 +08001832 if not power.CheckBatteryPresent():
1833 message = 'Battery is not present'
1834 else:
1835 ac_present = power.CheckACPresent()
1836 charge_pct = power.GetChargePct(get_float=True)
1837 message = ('Current battery level %.1f%%, AC charger is %s' %
1838 (charge_pct, 'connected' if ac_present else 'disconnected'))
1839
1840 if charge_pct > self.test_list.options.critical_low_battery_pct:
1841 critical_low_battery = False
1842 else:
1843 critical_low_battery = True
1844 # Only sync disks when battery level is still above minimum
1845 # value. This can be used for offline analysis when shopfloor cannot
1846 # be connected.
1847 if charge_pct > MIN_BATTERY_LEVEL_FOR_DISK_SYNC:
1848 logging.warning('disk syncing for critical low battery situation')
1849 os.system('sync; sync; sync')
1850 else:
1851 logging.warning('disk syncing is cancelled '
1852 'because battery level is lower than %.1f',
1853 MIN_BATTERY_LEVEL_FOR_DISK_SYNC)
1854
1855 # Notify shopfloor server
1856 if (critical_low_battery or
1857 (not ac_present and
1858 charge_pct <= self.test_list.options.warning_low_battery_pct)):
1859 log_level = logging.WARNING
1860
1861 self.event_log.Log('low_battery',
1862 battery_level=charge_pct,
1863 charger_connected=ac_present,
1864 critical=critical_low_battery)
1865 self.log_watcher.KickWatchThread()
Cheng-Yi Chianga0f6eff2014-01-09 18:27:22 +08001866 if self.test_list.options.enable_sync_log:
1867 self.system_log_manager.KickToSync()
Ricky Liang45c73e72015-01-15 15:00:30 +08001868 except: # pylint: disable=W0702
Justin Chuang83813982013-05-13 01:26:32 +08001869 logging.exception('Unable to check battery or notify shopfloor')
1870 finally:
1871 if message != self.last_check_battery_message:
1872 logging.log(log_level, message)
1873 self.last_check_battery_message = message
1874
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001875 def check_core_dump(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001876 """Checks if there is any core dumped file.
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001877
1878 Removes unwanted core dump files immediately.
1879 Syncs those files matching watch list to server with a delay between
1880 each sync. After the files have been synced to server, deletes the files.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001881 """
Vic Yang6cee2472014-10-22 17:18:52 -07001882 if not self.core_dump_manager:
1883 return
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001884 core_dump_files = self.core_dump_manager.ScanFiles()
1885 if core_dump_files:
1886 now = time.time()
1887 if (self.last_kick_sync_time and now - self.last_kick_sync_time <
1888 self.test_list.options.kick_sync_min_interval_secs):
1889 return
1890 self.last_kick_sync_time = now
1891
1892 # Sends event to server
1893 self.event_log.Log('core_dumped', files=core_dump_files)
1894 self.log_watcher.KickWatchThread()
1895
1896 # Syncs files to server
Cheng-Yi Chianga0f6eff2014-01-09 18:27:22 +08001897 if self.test_list.options.enable_sync_log:
1898 self.system_log_manager.KickToSync(
Cheng-Yi Chiangd3516a32013-07-17 15:30:47 +08001899 core_dump_files, self.core_dump_manager.ClearFiles)
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001900
Cheng-Yi Chiang39d32ad2013-07-23 15:02:38 +08001901 def check_log_rotation(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001902 """Checks log rotation file presence/absence according to test_list option.
Cheng-Yi Chiang39d32ad2013-07-23 15:02:38 +08001903
1904 Touch /var/lib/cleanup_logs_paused if test_list.options.disable_log_rotation
1905 is True, delete it otherwise. This must be done in idle loop because
1906 autotest client will touch /var/lib/cleanup_logs_paused each time it runs
1907 an autotest.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001908 """
Hung-Te Linf5f2d7f2016-01-08 17:12:46 +08001909 if sys_utils.InChroot():
Cheng-Yi Chiang39d32ad2013-07-23 15:02:38 +08001910 return
1911 try:
1912 if self.test_list.options.disable_log_rotation:
1913 open(CLEANUP_LOGS_PAUSED, 'w').close()
1914 else:
1915 file_utils.TryUnlink(CLEANUP_LOGS_PAUSED)
1916 except: # pylint: disable=W0702
1917 # Oh well. Logs an error (but no trace)
1918 logging.info(
1919 'Unable to %s %s: %s',
1920 'touch' if self.test_list.options.disable_log_rotation else 'delete',
Hung-Te Linf707b242016-01-08 23:11:42 +08001921 CLEANUP_LOGS_PAUSED, debug_utils.FormatExceptionOnly())
Cheng-Yi Chiang39d32ad2013-07-23 15:02:38 +08001922
Jon Salz8fa8e832012-07-13 19:04:09 +08001923 def sync_time_in_background(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001924 """Writes out current time and tries to sync with shopfloor server."""
Jon Salzb22d1172012-08-06 10:38:57 +08001925 if not self.time_sanitizer:
1926 return
1927
1928 # Write out the current time.
1929 self.time_sanitizer.SaveTime()
1930
Jon Salz54882d02012-08-31 01:57:54 +08001931 if not self._should_sync_time():
Jon Salz8fa8e832012-07-13 19:04:09 +08001932 return
1933
1934 now = time.time()
1935 if self.last_sync_time and (
1936 now - self.last_sync_time <
1937 self.test_list.options.sync_time_period_secs):
1938 # Not yet time for another check.
1939 return
1940 self.last_sync_time = now
1941
1942 def target():
1943 try:
Jon Salz54882d02012-08-31 01:57:54 +08001944 self.sync_time_with_shopfloor_server()
Jon Salz8fa8e832012-07-13 19:04:09 +08001945 except: # pylint: disable=W0702
1946 # Oh well. Log an error (but no trace)
1947 logging.info(
Ricky Liang45c73e72015-01-15 15:00:30 +08001948 'Unable to get time from shopfloor server: %s',
Hung-Te Linf707b242016-01-08 23:11:42 +08001949 debug_utils.FormatExceptionOnly())
Jon Salz8fa8e832012-07-13 19:04:09 +08001950
1951 thread = threading.Thread(target=target)
1952 thread.daemon = True
1953 thread.start()
1954
Peter Ammon1e1ec572014-06-26 17:56:32 -07001955 def perform_periodic_tasks(self):
1956 """Override of base method to perform periodic work.
Vic Yang4953fc12012-07-26 16:19:53 +08001957
Peter Ammon1e1ec572014-06-26 17:56:32 -07001958 This method must not raise exceptions.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001959 """
Peter Ammon1e1ec572014-06-26 17:56:32 -07001960 super(Goofy, self).perform_periodic_tasks()
Jon Salzb22d1172012-08-06 10:38:57 +08001961
Vic Yang311ddb82012-09-26 12:08:28 +08001962 self.check_exclusive()
cychiang21886742012-07-05 15:16:32 +08001963 self.check_for_updates()
Jon Salz8fa8e832012-07-13 19:04:09 +08001964 self.sync_time_in_background()
Jon Salzb92c5112012-09-21 15:40:11 +08001965 self.log_disk_space_stats()
Justin Chuang83813982013-05-13 01:26:32 +08001966 self.check_battery()
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001967 self.check_core_dump()
Cheng-Yi Chiang39d32ad2013-07-23 15:02:38 +08001968 self.check_log_rotation()
Jon Salz57717ca2012-04-04 16:47:25 +08001969
Cheng-Yi Chiangf5b21012015-03-17 15:37:14 +08001970 def handle_event_logs(self, chunks, periodic=False):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001971 """Callback for event watcher.
Jon Salz258a40c2012-04-19 12:34:01 +08001972
Jon Salz0697cbf2012-07-04 15:14:04 +08001973 Attempts to upload the event logs to the shopfloor server.
Vic Yang93027612013-05-06 02:42:49 +08001974
1975 Args:
Jon Salzd15bbcf2013-05-21 17:33:57 +08001976 chunks: A list of Chunk objects.
Cheng-Yi Chiangf5b21012015-03-17 15:37:14 +08001977 periodic: This event log handling is periodic. Error messages
1978 will only be shown for the first time.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001979 """
Vic Yang93027612013-05-06 02:42:49 +08001980 first_exception = None
1981 exception_count = 0
Cheng-Yi Chiangf5b21012015-03-17 15:37:14 +08001982 # Suppress error messages for periodic event syncing except for the
1983 # first time. If event syncing is not periodic, always show the error
1984 # messages.
1985 quiet = self._suppress_event_log_error_messages if periodic else False
Vic Yang93027612013-05-06 02:42:49 +08001986
Jon Salzd15bbcf2013-05-21 17:33:57 +08001987 for chunk in chunks:
Vic Yang93027612013-05-06 02:42:49 +08001988 try:
Jon Salzcddb6402013-05-23 12:56:42 +08001989 description = 'event logs (%s)' % str(chunk)
Vic Yang93027612013-05-06 02:42:49 +08001990 start_time = time.time()
1991 shopfloor_client = shopfloor.get_instance(
Ricky Liang45c73e72015-01-15 15:00:30 +08001992 detect=True,
Cheng-Yi Chiangf5b21012015-03-17 15:37:14 +08001993 timeout=self.test_list.options.shopfloor_timeout_secs,
1994 quiet=quiet)
Ricky Liang45c73e72015-01-15 15:00:30 +08001995 shopfloor_client.UploadEvent(chunk.log_name + '.' +
Jon Salzd15bbcf2013-05-21 17:33:57 +08001996 event_log.GetReimageId(),
1997 Binary(chunk.chunk))
Vic Yang93027612013-05-06 02:42:49 +08001998 logging.info(
Ricky Liang45c73e72015-01-15 15:00:30 +08001999 'Successfully synced %s in %.03f s',
2000 description, time.time() - start_time)
2001 except: # pylint: disable=W0702
Hung-Te Linf707b242016-01-08 23:11:42 +08002002 first_exception = (first_exception or
2003 (chunk.log_name + ': ' +
2004 debug_utils.FormatExceptionOnly()))
Vic Yang93027612013-05-06 02:42:49 +08002005 exception_count += 1
2006
2007 if exception_count:
2008 if exception_count == 1:
2009 msg = 'Log upload failed: %s' % first_exception
2010 else:
2011 msg = '%d log upload failed; first is: %s' % (
2012 exception_count, first_exception)
Cheng-Yi Chiangf5b21012015-03-17 15:37:14 +08002013 # For periodic event log syncing, only show the first error messages.
2014 if periodic:
2015 if not self._suppress_event_log_error_messages:
2016 self._suppress_event_log_error_messages = True
2017 logging.warning('Suppress periodic shopfloor error messages for '
2018 'event log syncing after the first one.')
2019 raise Exception(msg)
2020 # For event log syncing by request, show the error messages.
2021 else:
2022 raise Exception(msg)
Vic Yang93027612013-05-06 02:42:49 +08002023
Ricky Liang45c73e72015-01-15 15:00:30 +08002024 def run_tests_with_status(self, statuses_to_run, starting_at=None, root=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08002025 """Runs all top-level tests with a particular status.
Jon Salz0405ab52012-03-16 15:26:52 +08002026
Jon Salz0697cbf2012-07-04 15:14:04 +08002027 All active tests, plus any tests to re-run, are reset.
Jon Salz57717ca2012-04-04 16:47:25 +08002028
Jon Salz0697cbf2012-07-04 15:14:04 +08002029 Args:
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08002030 statuses_to_run: The particular status that caller wants to run.
Jon Salz0697cbf2012-07-04 15:14:04 +08002031 starting_at: If provided, only auto-runs tests beginning with
2032 this test.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08002033 root: The root of tests to run. If not provided, it will be
2034 the root of all tests.
2035 """
Jon Salz0697cbf2012-07-04 15:14:04 +08002036 root = root or self.test_list
Jon Salz57717ca2012-04-04 16:47:25 +08002037
Jon Salz0697cbf2012-07-04 15:14:04 +08002038 if starting_at:
2039 # Make sure they passed a test, not a string.
2040 assert isinstance(starting_at, factory.FactoryTest)
Jon Salz0405ab52012-03-16 15:26:52 +08002041
Jon Salz0697cbf2012-07-04 15:14:04 +08002042 tests_to_reset = []
2043 tests_to_run = []
Jon Salz0405ab52012-03-16 15:26:52 +08002044
Jon Salz0697cbf2012-07-04 15:14:04 +08002045 found_starting_at = False
Jon Salz0405ab52012-03-16 15:26:52 +08002046
Jon Salz0697cbf2012-07-04 15:14:04 +08002047 for test in root.get_top_level_tests():
2048 if starting_at:
2049 if test == starting_at:
2050 # We've found starting_at; do auto-run on all
2051 # subsequent tests.
2052 found_starting_at = True
2053 if not found_starting_at:
2054 # Don't start this guy yet
2055 continue
Jon Salz0405ab52012-03-16 15:26:52 +08002056
Jon Salz0697cbf2012-07-04 15:14:04 +08002057 status = test.get_state().status
2058 if status == TestState.ACTIVE or status in statuses_to_run:
2059 # Reset the test (later; we will need to abort
2060 # all active tests first).
2061 tests_to_reset.append(test)
2062 if status in statuses_to_run:
2063 tests_to_run.append(test)
Jon Salz0405ab52012-03-16 15:26:52 +08002064
Jon Salz6dc031d2013-06-19 13:06:23 +08002065 self.abort_active_tests('Operator requested run/re-run of certain tests')
Jon Salz258a40c2012-04-19 12:34:01 +08002066
Jon Salz0697cbf2012-07-04 15:14:04 +08002067 # Reset all statuses of the tests to run (in case any tests were active;
2068 # we want them to be run again).
2069 for test_to_reset in tests_to_reset:
2070 for test in test_to_reset.walk():
2071 test.update_state(status=TestState.UNTESTED)
Jon Salz57717ca2012-04-04 16:47:25 +08002072
Chih-Yu Huang85dc63c2015-08-12 15:21:28 +08002073 self.run_tests(tests_to_run, [TestState.UNTESTED])
Jon Salz0405ab52012-03-16 15:26:52 +08002074
Jon Salz0697cbf2012-07-04 15:14:04 +08002075 def restart_tests(self, root=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08002076 """Restarts all tests."""
Jon Salz0697cbf2012-07-04 15:14:04 +08002077 root = root or self.test_list
Jon Salz0405ab52012-03-16 15:26:52 +08002078
Jon Salz6dc031d2013-06-19 13:06:23 +08002079 self.abort_active_tests('Operator requested restart of certain tests')
Jon Salz0697cbf2012-07-04 15:14:04 +08002080 for test in root.walk():
Ricky Liangfea4ac92014-08-21 11:55:59 +08002081 test.update_state(status=TestState.UNTESTED)
Jon Salz0697cbf2012-07-04 15:14:04 +08002082 self.run_tests(root)
Hung-Te Lin96632362012-03-20 21:14:18 +08002083
Jon Salz0697cbf2012-07-04 15:14:04 +08002084 def auto_run(self, starting_at=None, root=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08002085 """"Auto-runs" tests that have not been run yet.
Hung-Te Lin96632362012-03-20 21:14:18 +08002086
Jon Salz0697cbf2012-07-04 15:14:04 +08002087 Args:
2088 starting_at: If provide, only auto-runs tests beginning with
2089 this test.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08002090 root: If provided, the root of tests to run. If not provided, the root
2091 will be test_list (root of all tests).
2092 """
Jon Salz0697cbf2012-07-04 15:14:04 +08002093 root = root or self.test_list
2094 self.run_tests_with_status([TestState.UNTESTED, TestState.ACTIVE],
Ricky Liang45c73e72015-01-15 15:00:30 +08002095 starting_at=starting_at,
2096 root=root)
Jon Salz968e90b2012-03-18 16:12:43 +08002097
Jon Salz0697cbf2012-07-04 15:14:04 +08002098 def re_run_failed(self, root=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08002099 """Re-runs failed tests."""
Jon Salz0697cbf2012-07-04 15:14:04 +08002100 root = root or self.test_list
2101 self.run_tests_with_status([TestState.FAILED], root=root)
Jon Salz57717ca2012-04-04 16:47:25 +08002102
Jon Salz0697cbf2012-07-04 15:14:04 +08002103 def show_review_information(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08002104 """Event handler for showing review information screen.
Jon Salz57717ca2012-04-04 16:47:25 +08002105
Peter Ammon1e1ec572014-06-26 17:56:32 -07002106 The information screen is rendered by main UI program (ui.py), so in
Jon Salz0697cbf2012-07-04 15:14:04 +08002107 goofy we only need to kill all active tests, set them as untested, and
2108 clear remaining tests.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08002109 """
Jon Salz0697cbf2012-07-04 15:14:04 +08002110 self.kill_active_tests(False)
Jon Salza6711d72012-07-18 14:33:03 +08002111 self.cancel_pending_tests()
Jon Salz57717ca2012-04-04 16:47:25 +08002112
Jon Salz0697cbf2012-07-04 15:14:04 +08002113 def handle_switch_test(self, event):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08002114 """Switches to a particular test.
Jon Salz0405ab52012-03-16 15:26:52 +08002115
Ricky Liang6fe218c2013-12-27 15:17:17 +08002116 Args:
2117 event: The SWITCH_TEST event.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08002118 """
Jon Salz0697cbf2012-07-04 15:14:04 +08002119 test = self.test_list.lookup_path(event.path)
2120 if not test:
2121 logging.error('Unknown test %r', event.key)
2122 return
Jon Salz73e0fd02012-04-04 11:46:38 +08002123
Jon Salz0697cbf2012-07-04 15:14:04 +08002124 invoc = self.invocations.get(test)
2125 if invoc and test.backgroundable:
2126 # Already running: just bring to the front if it
2127 # has a UI.
2128 logging.info('Setting visible test to %s', test.path)
Jon Salz36fbbb52012-07-05 13:45:06 +08002129 self.set_visible_test(test)
Jon Salz0697cbf2012-07-04 15:14:04 +08002130 return
Jon Salz73e0fd02012-04-04 11:46:38 +08002131
Jon Salz6dc031d2013-06-19 13:06:23 +08002132 self.abort_active_tests('Operator requested abort (switch_test)')
Jon Salz0697cbf2012-07-04 15:14:04 +08002133 for t in test.walk():
2134 t.update_state(status=TestState.UNTESTED)
Jon Salz73e0fd02012-04-04 11:46:38 +08002135
Jon Salz0697cbf2012-07-04 15:14:04 +08002136 if self.test_list.options.auto_run_on_keypress:
2137 self.auto_run(starting_at=test)
2138 else:
2139 self.run_tests(test)
Jon Salz73e0fd02012-04-04 11:46:38 +08002140
Wei-Ning Huang38b75f02015-02-25 18:25:14 +08002141 def handle_key_filter_mode(self, event):
2142 if self.key_filter:
2143 if getattr(event, 'enabled'):
2144 self.key_filter.Start()
2145 else:
2146 self.key_filter.Stop()
2147
Jon Salz0697cbf2012-07-04 15:14:04 +08002148 def wait(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08002149 """Waits for all pending invocations.
Jon Salz0697cbf2012-07-04 15:14:04 +08002150
2151 Useful for testing.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08002152 """
Jon Salz1acc8742012-07-17 17:45:55 +08002153 while self.invocations:
2154 for k, v in self.invocations.iteritems():
2155 logging.info('Waiting for %s to complete...', k)
2156 v.thread.join()
2157 self.reap_completed_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +08002158
Claire Changd1961a22015-08-05 16:15:55 +08002159 def test_fail(self, test):
Hung-Te Lin410f70a2015-12-15 14:53:42 +08002160 self.dut.hooks.OnTestFailure(test)
Claire Changd1961a22015-08-05 16:15:55 +08002161 if self.link_manager:
2162 self.link_manager.UpdateStatus(False)
2163
Hung-Te Linf2f78f72012-02-08 19:27:11 +08002164if __name__ == '__main__':
Peter Ammona3d298c2014-09-23 10:11:02 -07002165 Goofy.run_main_and_exit()