blob: d095c1ef01090f7e9f5eaafd3a04e64930801da0 [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
Jon Salze12c2b32013-06-25 16:24:34 +080010import glob
Jon Salz0405ab52012-03-16 15:26:52 +080011import logging
12import os
Jon Salz73e0fd02012-04-04 11:46:38 +080013import Queue
Jon Salze12c2b32013-06-25 16:24:34 +080014import shutil
Jon Salz77c151e2012-08-28 07:20:37 +080015import signal
Jon Salz0405ab52012-03-16 15:26:52 +080016import sys
Jon Salzeff94182013-06-19 15:06:28 +080017import syslog
Jon Salz0405ab52012-03-16 15:26:52 +080018import threading
19import time
20import traceback
Jon Salz258a40c2012-04-19 12:34:01 +080021import uuid
Jon Salzb10cf512012-08-09 17:29:21 +080022from xmlrpclib import Binary
Hung-Te Linf2f78f72012-02-08 19:27:11 +080023from collections import deque
24from optparse import OptionParser
Hung-Te Linf2f78f72012-02-08 19:27:11 +080025
Jon Salz0697cbf2012-07-04 15:14:04 +080026import factory_common # pylint: disable=W0611
jcliangcd688182012-08-20 21:01:26 +080027from cros.factory import event_log
28from cros.factory import system
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +080029from cros.factory.event_log import EventLog, FloatDigit
Tom Wai-Hong Tamd33723e2013-04-10 21:14:37 +080030from cros.factory.event_log_watcher import EventLogWatcher
jcliangcd688182012-08-20 21:01:26 +080031from cros.factory.goofy import test_environment
32from cros.factory.goofy import time_sanitizer
Jon Salz83591782012-06-26 11:09:58 +080033from cros.factory.goofy import updater
jcliangcd688182012-08-20 21:01:26 +080034from cros.factory.goofy.goofy_rpc import GoofyRPC
Jon Salz885dcac2013-07-23 16:39:50 +080035from cros.factory.goofy.invocation import TestArgEnv
jcliangcd688182012-08-20 21:01:26 +080036from cros.factory.goofy.invocation import TestInvocation
37from cros.factory.goofy.prespawner import Prespawner
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +080038from cros.factory.goofy.system_log_manager import SystemLogManager
jcliangcd688182012-08-20 21:01:26 +080039from cros.factory.goofy.web_socket_manager import WebSocketManager
Cheng-Yi Chiangd8186952013-04-04 23:41:14 +080040from cros.factory.system.board import Board, BoardException
jcliangcd688182012-08-20 21:01:26 +080041from cros.factory.system.charge_manager import ChargeManager
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +080042from cros.factory.system.core_dump_manager import CoreDumpManager
Jon Salzce6a7f82013-06-10 18:22:54 +080043from cros.factory.system.cpufreq_manager import CpufreqManager
Jon Salzb92c5112012-09-21 15:40:11 +080044from cros.factory.system import disk_space
jcliangcd688182012-08-20 21:01:26 +080045from cros.factory.test import factory
46from cros.factory.test import state
Jon Salz51528e12012-07-02 18:54:45 +080047from cros.factory.test import shopfloor
Jon Salz83591782012-06-26 11:09:58 +080048from cros.factory.test import utils
Jon Salz128b0932013-07-03 16:55:26 +080049from cros.factory.test.test_lists import test_lists
Ricky Liang6fe218c2013-12-27 15:17:17 +080050from cros.factory.test.e2e_test.common import (
51 AutomationMode, AutomationModePrompt, ParseAutomationMode)
Jon Salz83591782012-06-26 11:09:58 +080052from cros.factory.test.event import Event
53from cros.factory.test.event import EventClient
54from cros.factory.test.event import EventServer
jcliangcd688182012-08-20 21:01:26 +080055from cros.factory.test.factory import TestState
Jon Salzd7550792013-07-12 05:49:27 +080056from cros.factory.test.utils import Enum
Dean Liao592e4d52013-01-10 20:06:39 +080057from cros.factory.tools.key_filter import KeyFilter
Jon Salz2af235d2013-06-24 14:47:21 +080058from cros.factory.utils import file_utils
Jon Salz78c32392012-07-25 14:18:29 +080059from cros.factory.utils.process_utils import Spawn
Hung-Te Linf2f78f72012-02-08 19:27:11 +080060
61
Hung-Te Linf2f78f72012-02-08 19:27:11 +080062HWID_CFG_PATH = '/usr/local/share/chromeos-hwid/cfg'
Chun-ta Lin279e7e92013-02-19 17:40:39 +080063CACHES_DIR = os.path.join(factory.get_state_root(), "caches")
Hung-Te Linf2f78f72012-02-08 19:27:11 +080064
Cheng-Yi Chiang39d32ad2013-07-23 15:02:38 +080065CLEANUP_LOGS_PAUSED = '/var/lib/cleanup_logs_paused'
66
Jon Salz5c344f62012-07-13 14:31:16 +080067# Value for tests_after_shutdown that forces auto-run (e.g., after
68# a factory update, when the available set of tests might change).
69FORCE_AUTO_RUN = 'force_auto_run'
70
cychiang21886742012-07-05 15:16:32 +080071RUN_QUEUE_TIMEOUT_SECS = 10
72
Justin Chuang83813982013-05-13 01:26:32 +080073# Sync disks when battery level is higher than this value.
74# Otherwise, power loss during disk sync operation may incur even worse outcome.
75MIN_BATTERY_LEVEL_FOR_DISK_SYNC = 1.0
76
Jon Salze12c2b32013-06-25 16:24:34 +080077MAX_CRASH_FILE_SIZE = 64*1024
78
Jon Salz758e6cc2012-04-03 15:47:07 +080079GOOFY_IN_CHROOT_WARNING = '\n' + ('*' * 70) + '''
80You are running Goofy inside the chroot. Autotests are not supported.
81
82To use Goofy in the chroot, first install an Xvnc server:
83
Jon Salz0697cbf2012-07-04 15:14:04 +080084 sudo apt-get install tightvncserver
Jon Salz758e6cc2012-04-03 15:47:07 +080085
86...and then start a VNC X server outside the chroot:
87
Jon Salz0697cbf2012-07-04 15:14:04 +080088 vncserver :10 &
89 vncviewer :10
Jon Salz758e6cc2012-04-03 15:47:07 +080090
91...and run Goofy as follows:
92
Jon Salz0697cbf2012-07-04 15:14:04 +080093 env --unset=XAUTHORITY DISPLAY=localhost:10 python goofy.py
Jon Salz758e6cc2012-04-03 15:47:07 +080094''' + ('*' * 70)
Jon Salz73e0fd02012-04-04 11:46:38 +080095suppress_chroot_warning = False
Hung-Te Linf2f78f72012-02-08 19:27:11 +080096
Jon Salzd7550792013-07-12 05:49:27 +080097Status = Enum(['UNINITIALIZED', 'INITIALIZING', 'RUNNING',
98 'TERMINATING', 'TERMINATED'])
99
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800100def get_hwid_cfg():
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800101 """Returns the HWID config tag, or an empty string if none can be found."""
Jon Salz0697cbf2012-07-04 15:14:04 +0800102 if 'CROS_HWID' in os.environ:
103 return os.environ['CROS_HWID']
104 if os.path.exists(HWID_CFG_PATH):
105 with open(HWID_CFG_PATH, 'rt') as hwid_cfg_handle:
106 return hwid_cfg_handle.read().strip()
107 return ''
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800108
109
Jon Salz73e0fd02012-04-04 11:46:38 +0800110_inited_logging = False
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800111
112class Goofy(object):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800113 """The main factory flow.
Jon Salz0697cbf2012-07-04 15:14:04 +0800114
115 Note that all methods in this class must be invoked from the main
116 (event) thread. Other threads, such as callbacks and TestInvocation
117 methods, should instead post events on the run queue.
118
119 TODO: Unit tests. (chrome-os-partner:7409)
120
121 Properties:
122 uuid: A unique UUID for this invocation of Goofy.
123 state_instance: An instance of FactoryState.
124 state_server: The FactoryState XML/RPC server.
125 state_server_thread: A thread running state_server.
126 event_server: The EventServer socket server.
127 event_server_thread: A thread running event_server.
128 event_client: A client to the event server.
129 connection_manager: The connection_manager object.
Cheng-Yi Chiang835f2682013-05-06 22:15:48 +0800130 system_log_manager: The SystemLogManager object.
131 core_dump_manager: The CoreDumpManager object.
Jon Salz0697cbf2012-07-04 15:14:04 +0800132 ui_process: The factory ui process object.
133 run_queue: A queue of callbacks to invoke from the main thread.
134 invocations: A map from FactoryTest objects to the corresponding
135 TestInvocations objects representing active tests.
136 tests_to_run: A deque of tests that should be run when the current
137 test(s) complete.
138 options: Command-line options.
139 args: Command-line args.
140 test_list: The test list.
Jon Salz128b0932013-07-03 16:55:26 +0800141 test_lists: All new-style test lists.
Ricky Liang4bff3e32014-02-20 18:46:11 +0800142 run_id: The identifier for latest test run.
143 scheduled_run_tests: The list of tests scheduled for latest test run.
Jon Salz0697cbf2012-07-04 15:14:04 +0800144 event_handlers: Map of Event.Type to the method used to handle that
145 event. If the method has an 'event' argument, the event is passed
146 to the handler.
147 exceptions: Exceptions encountered in invocation threads.
Jon Salz3c493bb2013-02-07 17:24:58 +0800148 last_log_disk_space_message: The last message we logged about disk space
149 (to avoid duplication).
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +0800150 last_kick_sync_time: The last time to kick system_log_manager to sync
151 because of core dump files (to avoid kicking too soon then abort the
152 sync.)
Jon Salz416f9cc2013-05-10 18:32:50 +0800153 hooks: A Hooks object containing hooks for various Goofy actions.
Jon Salzd7550792013-07-12 05:49:27 +0800154 status: The current Goofy status (a member of the Status enum).
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800155 """
Jon Salz0697cbf2012-07-04 15:14:04 +0800156 def __init__(self):
157 self.uuid = str(uuid.uuid4())
158 self.state_instance = None
159 self.state_server = None
160 self.state_server_thread = None
Jon Salz16d10542012-07-23 12:18:45 +0800161 self.goofy_rpc = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800162 self.event_server = None
163 self.event_server_thread = None
164 self.event_client = None
165 self.connection_manager = None
Vic Yang4953fc12012-07-26 16:19:53 +0800166 self.charge_manager = None
Jon Salz8fa8e832012-07-13 19:04:09 +0800167 self.time_sanitizer = None
168 self.time_synced = False
Jon Salz0697cbf2012-07-04 15:14:04 +0800169 self.log_watcher = None
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +0800170 self.system_log_manager = None
Cheng-Yi Chiang835f2682013-05-06 22:15:48 +0800171 self.core_dump_manager = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800172 self.event_log = None
173 self.prespawner = None
174 self.ui_process = None
Jon Salzc79a9982012-08-30 04:42:01 +0800175 self.dummy_shopfloor = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800176 self.run_queue = Queue.Queue()
177 self.invocations = {}
178 self.tests_to_run = deque()
179 self.visible_test = None
180 self.chrome = None
Jon Salz416f9cc2013-05-10 18:32:50 +0800181 self.hooks = None
Vic Yangd8990da2013-06-27 16:57:43 +0800182 self.cpu_usage_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.on_ui_startup = []
191 self.env = None
Jon Salzb22d1172012-08-06 10:38:57 +0800192 self.last_idle = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800193 self.last_shutdown_time = None
cychiang21886742012-07-05 15:16:32 +0800194 self.last_update_check = None
Jon Salz8fa8e832012-07-13 19:04:09 +0800195 self.last_sync_time = None
Jon Salzb92c5112012-09-21 15:40:11 +0800196 self.last_log_disk_space_time = None
Jon Salz3c493bb2013-02-07 17:24:58 +0800197 self.last_log_disk_space_message = None
Justin Chuang83813982013-05-13 01:26:32 +0800198 self.last_check_battery_time = None
199 self.last_check_battery_message = None
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +0800200 self.last_kick_sync_time = None
Vic Yang311ddb82012-09-26 12:08:28 +0800201 self.exclusive_items = set()
Jon Salz0f996602012-10-03 15:26:48 +0800202 self.event_log = None
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
Jon Salz0697cbf2012-07-04 15:14:04 +0800206
Jon Salz85a39882012-07-05 16:45:04 +0800207 def test_or_root(event, parent_or_group=True):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800208 """Returns the test affected by a particular event.
Jon Salz85a39882012-07-05 16:45:04 +0800209
210 Args:
211 event: The event containing an optional 'path' attribute.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800212 parent_or_group: If True, returns the top-level parent for a test (the
Jon Salz85a39882012-07-05 16:45:04 +0800213 root node of the tests that need to be run together if the given test
214 path is to be run).
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800215 """
Jon Salz0697cbf2012-07-04 15:14:04 +0800216 try:
217 path = event.path
218 except AttributeError:
219 path = None
220
221 if path:
Jon Salz85a39882012-07-05 16:45:04 +0800222 test = self.test_list.lookup_path(path)
223 if parent_or_group:
224 test = test.get_top_level_parent_or_group()
225 return test
Jon Salz0697cbf2012-07-04 15:14:04 +0800226 else:
227 return self.test_list
228
229 self.event_handlers = {
230 Event.Type.SWITCH_TEST: self.handle_switch_test,
231 Event.Type.SHOW_NEXT_ACTIVE_TEST:
232 lambda event: self.show_next_active_test(),
233 Event.Type.RESTART_TESTS:
234 lambda event: self.restart_tests(root=test_or_root(event)),
235 Event.Type.AUTO_RUN:
236 lambda event: self.auto_run(root=test_or_root(event)),
237 Event.Type.RE_RUN_FAILED:
238 lambda event: self.re_run_failed(root=test_or_root(event)),
239 Event.Type.RUN_TESTS_WITH_STATUS:
240 lambda event: self.run_tests_with_status(
241 event.status,
242 root=test_or_root(event)),
243 Event.Type.REVIEW:
244 lambda event: self.show_review_information(),
245 Event.Type.UPDATE_SYSTEM_INFO:
246 lambda event: self.update_system_info(),
Jon Salz0697cbf2012-07-04 15:14:04 +0800247 Event.Type.STOP:
Jon Salz85a39882012-07-05 16:45:04 +0800248 lambda event: self.stop(root=test_or_root(event, False),
Jon Salz6dc031d2013-06-19 13:06:23 +0800249 fail=getattr(event, 'fail', False),
250 reason=getattr(event, 'reason', None)),
Jon Salz36fbbb52012-07-05 13:45:06 +0800251 Event.Type.SET_VISIBLE_TEST:
252 lambda event: self.set_visible_test(
253 self.test_list.lookup_path(event.path)),
Jon Salz4712ac72013-02-07 17:12:05 +0800254 Event.Type.CLEAR_STATE:
255 lambda event: self.clear_state(self.test_list.lookup_path(event.path)),
Jon Salz0697cbf2012-07-04 15:14:04 +0800256 }
257
258 self.exceptions = []
259 self.web_socket_manager = None
260
261 def destroy(self):
Jon Salzd7550792013-07-12 05:49:27 +0800262 self.status = Status.TERMINATING
Jon Salz0697cbf2012-07-04 15:14:04 +0800263 if self.chrome:
264 self.chrome.kill()
265 self.chrome = None
Jon Salzc79a9982012-08-30 04:42:01 +0800266 if self.dummy_shopfloor:
267 self.dummy_shopfloor.kill()
268 self.dummy_shopfloor = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800269 if self.ui_process:
270 utils.kill_process_tree(self.ui_process, 'ui')
271 self.ui_process = None
272 if self.web_socket_manager:
273 logging.info('Stopping web sockets')
274 self.web_socket_manager.close()
275 self.web_socket_manager = None
276 if self.state_server_thread:
277 logging.info('Stopping state server')
278 self.state_server.shutdown()
279 self.state_server_thread.join()
280 self.state_server.server_close()
281 self.state_server_thread = None
282 if self.state_instance:
283 self.state_instance.close()
284 if self.event_server_thread:
285 logging.info('Stopping event server')
286 self.event_server.shutdown() # pylint: disable=E1101
287 self.event_server_thread.join()
288 self.event_server.server_close()
289 self.event_server_thread = None
290 if self.log_watcher:
291 if self.log_watcher.IsThreadStarted():
292 self.log_watcher.StopWatchThread()
293 self.log_watcher = None
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +0800294 if self.system_log_manager:
295 if self.system_log_manager.IsThreadRunning():
Cheng-Yi Chianga0f6eff2014-01-09 18:27:22 +0800296 self.system_log_manager.Stop()
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +0800297 self.system_log_manager = None
Jon Salz0697cbf2012-07-04 15:14:04 +0800298 if self.prespawner:
299 logging.info('Stopping prespawner')
300 self.prespawner.stop()
301 self.prespawner = None
302 if self.event_client:
303 logging.info('Closing event client')
304 self.event_client.close()
305 self.event_client = None
Jon Salzddf0d052013-06-18 12:52:44 +0800306 if self.cpufreq_manager:
307 self.cpufreq_manager.Stop()
Jon Salz0697cbf2012-07-04 15:14:04 +0800308 if self.event_log:
309 self.event_log.Close()
310 self.event_log = None
Dean Liao592e4d52013-01-10 20:06:39 +0800311 if self.key_filter:
312 self.key_filter.Stop()
Vic Yangd8990da2013-06-27 16:57:43 +0800313 if self.cpu_usage_watcher:
314 self.cpu_usage_watcher.terminate()
Dean Liao592e4d52013-01-10 20:06:39 +0800315
Jon Salz0697cbf2012-07-04 15:14:04 +0800316 self.check_exceptions()
317 logging.info('Done destroying Goofy')
Jon Salzd7550792013-07-12 05:49:27 +0800318 self.status = Status.TERMINATED
Jon Salz0697cbf2012-07-04 15:14:04 +0800319
320 def start_state_server(self):
Jon Salz2af235d2013-06-24 14:47:21 +0800321 # Before starting state server, remount stateful partitions with
322 # no commit flag. The default commit time (commit=600) makes corruption
323 # too likely.
324 file_utils.ResetCommitTime()
325
Jon Salz0697cbf2012-07-04 15:14:04 +0800326 self.state_instance, self.state_server = (
327 state.create_server(bind_address='0.0.0.0'))
Jon Salz16d10542012-07-23 12:18:45 +0800328 self.goofy_rpc = GoofyRPC(self)
329 self.goofy_rpc.RegisterMethods(self.state_instance)
Jon Salz0697cbf2012-07-04 15:14:04 +0800330 logging.info('Starting state server')
331 self.state_server_thread = threading.Thread(
332 target=self.state_server.serve_forever,
333 name='StateServer')
334 self.state_server_thread.start()
335
336 def start_event_server(self):
337 self.event_server = EventServer()
338 logging.info('Starting factory event server')
339 self.event_server_thread = threading.Thread(
340 target=self.event_server.serve_forever,
341 name='EventServer') # pylint: disable=E1101
342 self.event_server_thread.start()
343
344 self.event_client = EventClient(
345 callback=self.handle_event, event_loop=self.run_queue)
346
347 self.web_socket_manager = WebSocketManager(self.uuid)
348 self.state_server.add_handler("/event",
349 self.web_socket_manager.handle_web_socket)
350
351 def start_ui(self):
352 ui_proc_args = [
353 os.path.join(factory.FACTORY_PACKAGE_PATH, 'test', 'ui.py'),
354 self.options.test_list]
355 if self.options.verbose:
356 ui_proc_args.append('-v')
357 logging.info('Starting ui %s', ui_proc_args)
Jon Salz78c32392012-07-25 14:18:29 +0800358 self.ui_process = Spawn(ui_proc_args)
Jon Salz0697cbf2012-07-04 15:14:04 +0800359 logging.info('Waiting for UI to come up...')
360 self.event_client.wait(
361 lambda event: event.type == Event.Type.UI_READY)
362 logging.info('UI has started')
363
364 def set_visible_test(self, test):
365 if self.visible_test == test:
366 return
Jon Salz2f2d42c2012-07-30 12:30:34 +0800367 if test and not test.has_ui:
368 return
Jon Salz0697cbf2012-07-04 15:14:04 +0800369
370 if test:
371 test.update_state(visible=True)
372 if self.visible_test:
373 self.visible_test.update_state(visible=False)
374 self.visible_test = test
375
Ricky Liang48e47f92014-02-26 19:31:51 +0800376 def log_startup_messages(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800377 """Logs the tail of var/log/messages and mosys and EC console logs."""
Jon Salzd4306c82012-11-30 15:16:36 +0800378 # TODO(jsalz): This is mostly a copy-and-paste of code in init_states,
379 # for factory-3004.B only. Consolidate and merge back to ToT.
380 if utils.in_chroot():
381 return
382
383 try:
384 var_log_messages = (
385 utils.var_log_messages_before_reboot())
386 logging.info(
387 'Tail of /var/log/messages before last reboot:\n'
388 '%s', ('\n'.join(
389 ' ' + x for x in var_log_messages)))
390 except: # pylint: disable=W0702
391 logging.exception('Unable to grok /var/log/messages')
392
393 try:
Ricky Liang117484a2014-04-14 11:14:41 +0800394 mosys_log = Spawn(
Jon Salzd4306c82012-11-30 15:16:36 +0800395 ['mosys', 'eventlog', 'list'],
396 read_stdout=True, log_stderr_on_error=True).stdout_data
397 logging.info('System eventlog from mosys:\n%s\n', mosys_log)
398 except: # pylint: disable=W0702
399 logging.exception('Unable to read mosys eventlog')
400
401 try:
Vic Yang8341dde2013-01-29 16:48:52 +0800402 board = system.GetBoard()
403 ec_console_log = board.GetECConsoleLog()
Jon Salzd4306c82012-11-30 15:16:36 +0800404 logging.info('EC console log after reboot:\n%s\n', ec_console_log)
405 except: # pylint: disable=W0702
406 logging.exception('Error retrieving EC console log')
407
Vic Yang079f9872013-07-01 11:32:00 +0800408 try:
409 board = system.GetBoard()
410 ec_panic_info = board.GetECPanicInfo()
411 logging.info('EC panic info after reboot:\n%s\n', ec_panic_info)
412 except: # pylint: disable=W0702
413 logging.exception('Error retrieving EC panic info')
414
Ricky Liang48e47f92014-02-26 19:31:51 +0800415 def shutdown(self, operation):
416 """Starts shutdown procedure.
417
418 Args:
Vic (Chun-Ju) Yang05b0d952014-04-28 17:39:09 +0800419 operation: The shutdown operation (reboot, full_reboot, or halt).
Ricky Liang48e47f92014-02-26 19:31:51 +0800420 """
421 active_tests = []
422 for test in self.test_list.walk():
423 if not test.is_leaf():
424 continue
425
426 test_state = test.get_state()
427 if test_state.status == TestState.ACTIVE:
428 active_tests.append(test)
429
430
431 if not (len(active_tests) == 1 and
432 isinstance(active_tests[0], factory.ShutdownStep)):
433 logging.error(
434 'Calling Goofy shutdown outside of the shutdown factory test')
435 return
436
437 logging.info('Start Goofy shutdown (%s)', operation)
438 # Save pending test list in the state server
439 self.state_instance.set_shared_data(
440 'tests_after_shutdown',
441 [t.path for t in self.tests_to_run])
442 # Save shutdown time
443 self.state_instance.set_shared_data('shutdown_time', time.time())
444
445 with self.env.lock:
446 self.event_log.Log('shutdown', operation=operation)
447 shutdown_result = self.env.shutdown(operation)
448 if shutdown_result:
449 # That's all, folks!
450 self.run_queue.put(None)
451 else:
452 # Just pass (e.g., in the chroot).
453 self.state_instance.set_shared_data('tests_after_shutdown', None)
454 # Send event with no fields to indicate that there is no
455 # longer a pending shutdown.
456 self.event_client.post_event(Event(Event.Type.PENDING_SHUTDOWN))
457
458 def handle_shutdown_complete(self, test):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800459 """Handles the case where a shutdown was detected during a shutdown step.
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800460
Ricky Liang6fe218c2013-12-27 15:17:17 +0800461 Args:
462 test: The ShutdownStep.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800463 """
Jon Salz0697cbf2012-07-04 15:14:04 +0800464 test_state = test.update_state(increment_shutdown_count=1)
465 logging.info('Detected shutdown (%d of %d)',
Ricky Liang48e47f92014-02-26 19:31:51 +0800466 test_state.shutdown_count, test.iterations)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800467
Ricky Liang48e47f92014-02-26 19:31:51 +0800468 # Insert current shutdown test at the front of the list of tests to run
469 # after shutdown. This is to continue on post-shutdown verification in the
470 # shutdown step.
471 tests_after_shutdown = self.state_instance.get_shared_data(
472 'tests_after_shutdown', optional=True)
473 if not tests_after_shutdown:
474 self.state_instance.set_shared_data('tests_after_shutdown', [test.path])
475 elif isinstance(tests_after_shutdown, list):
476 self.state_instance.set_shared_data(
477 'tests_after_shutdown', [test.path] + tests_after_shutdown)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800478
Ricky Liang48e47f92014-02-26 19:31:51 +0800479 # Set 'post_shutdown' to inform shutdown test that a shutdown just occurred.
480 self.state_instance.set_shared_data('post_shutdown', True)
Jon Salz258a40c2012-04-19 12:34:01 +0800481
Jon Salz0697cbf2012-07-04 15:14:04 +0800482 def init_states(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800483 """Initializes all states on startup."""
Jon Salz0697cbf2012-07-04 15:14:04 +0800484 for test in self.test_list.get_all_tests():
485 # Make sure the state server knows about all the tests,
486 # defaulting to an untested state.
487 test.update_state(update_parent=False, visible=False)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800488
Jon Salz0697cbf2012-07-04 15:14:04 +0800489 var_log_messages = None
Vic Yanga9c32212012-08-16 20:07:54 +0800490 mosys_log = None
Vic Yange4c275d2012-08-28 01:50:20 +0800491 ec_console_log = None
Vic Yang079f9872013-07-01 11:32:00 +0800492 ec_panic_info = None
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800493
Jon Salz0697cbf2012-07-04 15:14:04 +0800494 # Any 'active' tests should be marked as failed now.
495 for test in self.test_list.walk():
Jon Salza6711d72012-07-18 14:33:03 +0800496 if not test.is_leaf():
497 # Don't bother with parents; they will be updated when their
498 # children are updated.
499 continue
500
Jon Salz0697cbf2012-07-04 15:14:04 +0800501 test_state = test.get_state()
502 if test_state.status != TestState.ACTIVE:
503 continue
504 if isinstance(test, factory.ShutdownStep):
505 # Shutdown while the test was active - that's good.
Ricky Liang48e47f92014-02-26 19:31:51 +0800506 self.handle_shutdown_complete(test)
Jon Salz0697cbf2012-07-04 15:14:04 +0800507 else:
508 # Unexpected shutdown. Grab /var/log/messages for context.
509 if var_log_messages is None:
510 try:
511 var_log_messages = (
512 utils.var_log_messages_before_reboot())
513 # Write it to the log, to make it easier to
514 # correlate with /var/log/messages.
515 logging.info(
516 'Unexpected shutdown. '
517 'Tail of /var/log/messages before last reboot:\n'
518 '%s', ('\n'.join(
519 ' ' + x for x in var_log_messages)))
520 except: # pylint: disable=W0702
521 logging.exception('Unable to grok /var/log/messages')
522 var_log_messages = []
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800523
Jon Salz008f4ea2012-08-28 05:39:45 +0800524 if mosys_log is None and not utils.in_chroot():
525 try:
Ricky Liang117484a2014-04-14 11:14:41 +0800526 mosys_log = Spawn(
Jon Salz008f4ea2012-08-28 05:39:45 +0800527 ['mosys', 'eventlog', 'list'],
528 read_stdout=True, log_stderr_on_error=True).stdout_data
529 # Write it to the log also.
530 logging.info('System eventlog from mosys:\n%s\n', mosys_log)
531 except: # pylint: disable=W0702
532 logging.exception('Unable to read mosys eventlog')
Vic Yanga9c32212012-08-16 20:07:54 +0800533
Vic Yange4c275d2012-08-28 01:50:20 +0800534 if ec_console_log is None:
535 try:
Vic Yang8341dde2013-01-29 16:48:52 +0800536 board = system.GetBoard()
537 ec_console_log = board.GetECConsoleLog()
Vic Yange4c275d2012-08-28 01:50:20 +0800538 logging.info('EC console log after reboot:\n%s\n', ec_console_log)
Jon Salzfe1f6652012-09-07 05:40:14 +0800539 except: # pylint: disable=W0702
Vic Yange4c275d2012-08-28 01:50:20 +0800540 logging.exception('Error retrieving EC console log')
541
Vic Yang079f9872013-07-01 11:32:00 +0800542 if ec_panic_info is None:
543 try:
544 board = system.GetBoard()
545 ec_panic_info = board.GetECPanicInfo()
546 logging.info('EC panic info after reboot:\n%s\n', ec_panic_info)
547 except: # pylint: disable=W0702
548 logging.exception('Error retrieving EC panic info')
549
Jon Salz0697cbf2012-07-04 15:14:04 +0800550 error_msg = 'Unexpected shutdown while test was running'
551 self.event_log.Log('end_test',
552 path=test.path,
553 status=TestState.FAILED,
554 invocation=test.get_state().invocation,
555 error_msg=error_msg,
Vic Yanga9c32212012-08-16 20:07:54 +0800556 var_log_messages='\n'.join(var_log_messages),
557 mosys_log=mosys_log)
Jon Salz0697cbf2012-07-04 15:14:04 +0800558 test.update_state(
559 status=TestState.FAILED,
560 error_msg=error_msg)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800561
Jon Salz50efe942012-07-26 11:54:10 +0800562 if not test.never_fails:
563 # For "never_fails" tests (such as "Start"), don't cancel
564 # pending tests, since reboot is expected.
565 factory.console.info('Unexpected shutdown while test %s '
566 'running; cancelling any pending tests',
567 test.path)
568 self.state_instance.set_shared_data('tests_after_shutdown', [])
Jon Salz69806bb2012-07-20 18:05:02 +0800569
Jon Salz008f4ea2012-08-28 05:39:45 +0800570 self.update_skipped_tests()
571
572 def update_skipped_tests(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800573 """Updates skipped states based on run_if."""
Jon Salz885dcac2013-07-23 16:39:50 +0800574 env = TestArgEnv()
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800575 def _evaluate_skip_from_run_if(test):
576 """Returns the run_if evaluation of the test.
577
578 Args:
579 test: A FactoryTest object.
580
581 Returns:
582 The run_if evaluation result. Returns False if the test has no
583 run_if argument.
584 """
585 value = None
586 if test.run_if_expr:
587 try:
588 value = test.run_if_expr(env)
589 except: # pylint: disable=W0702
590 logging.exception('Unable to evaluate run_if expression for %s',
591 test.path)
592 # But keep going; we have no choice. This will end up
593 # always activating the test.
594 elif test.run_if_table_name:
595 try:
596 aux = shopfloor.get_selected_aux_data(test.run_if_table_name)
597 value = aux.get(test.run_if_col)
598 except ValueError:
599 # Not available; assume it shouldn't be skipped
600 pass
601
602 if value is None:
603 skip = False
604 else:
605 skip = (not value) ^ t.run_if_not
606 return skip
607
608 # Gets all run_if evaluation, and stores results in skip_map.
609 skip_map = dict()
Jon Salz008f4ea2012-08-28 05:39:45 +0800610 for t in self.test_list.walk():
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800611 skip_map[t.path] = _evaluate_skip_from_run_if(t)
Jon Salz885dcac2013-07-23 16:39:50 +0800612
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800613 # Propagates the skip value from root of tree and updates skip_map.
614 def _update_skip_map_from_node(test, skip_from_parent):
615 """Updates skip_map from a given node.
Jon Salz885dcac2013-07-23 16:39:50 +0800616
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800617 Given a FactoryTest node and the skip value from parent, updates the
618 skip value of current node in the skip_map if skip value from parent is
619 True. If this node has children, recursively propagate this value to all
620 its children, that is, all its subtests.
621 Note that this function only updates value in skip_map, not the actual
622 test_list tree.
Jon Salz008f4ea2012-08-28 05:39:45 +0800623
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800624 Args:
625 test: The given FactoryTest object. It is a node in the test_list tree.
626 skip_from_parent: The skip value which propagates from the parent of
627 input node.
628 """
629 skip_this_tree = skip_from_parent or skip_map[test.path]
630 if skip_this_tree:
631 logging.info('Skip from node %r', test.path)
632 skip_map[test.path] = True
633 if test.is_leaf():
634 return
635 # Propagates skip value to its subtests
636 for subtest in test.subtests:
637 _update_skip_map_from_node(subtest, skip_this_tree)
638
639 _update_skip_map_from_node(self.test_list, False)
640
641 # Updates the skip value from skip_map to test_list tree. Also, updates test
642 # status if needed.
643 for t in self.test_list.walk():
644 skip = skip_map[t.path]
645 test_state = t.get_state()
646 if ((not skip) and
647 (test_state.status == TestState.PASSED) and
648 (test_state.error_msg == TestState.SKIPPED_MSG)):
649 # It was marked as skipped before, but now we need to run it.
650 # Mark as untested.
651 t.update_state(skip=skip, status=TestState.UNTESTED, error_msg='')
652 else:
653 t.update_state(skip=skip)
Jon Salz008f4ea2012-08-28 05:39:45 +0800654
Jon Salz0697cbf2012-07-04 15:14:04 +0800655 def show_next_active_test(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800656 """Rotates to the next visible active test."""
Jon Salz0697cbf2012-07-04 15:14:04 +0800657 self.reap_completed_tests()
658 active_tests = [
659 t for t in self.test_list.walk()
660 if t.is_leaf() and t.get_state().status == TestState.ACTIVE]
661 if not active_tests:
662 return
Jon Salz4f6c7172012-06-11 20:45:36 +0800663
Jon Salz0697cbf2012-07-04 15:14:04 +0800664 try:
665 next_test = active_tests[
666 (active_tests.index(self.visible_test) + 1) % len(active_tests)]
667 except ValueError: # visible_test not present in active_tests
668 next_test = active_tests[0]
Jon Salz4f6c7172012-06-11 20:45:36 +0800669
Jon Salz0697cbf2012-07-04 15:14:04 +0800670 self.set_visible_test(next_test)
Jon Salz4f6c7172012-06-11 20:45:36 +0800671
Jon Salz0697cbf2012-07-04 15:14:04 +0800672 def handle_event(self, event):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800673 """Handles an event from the event server."""
Jon Salz0697cbf2012-07-04 15:14:04 +0800674 handler = self.event_handlers.get(event.type)
675 if handler:
676 handler(event)
677 else:
678 # We don't register handlers for all event types - just ignore
679 # this event.
680 logging.debug('Unbound event type %s', event.type)
Jon Salz4f6c7172012-06-11 20:45:36 +0800681
Vic Yangaabf9fd2013-04-09 18:56:13 +0800682 def check_critical_factory_note(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800683 """Returns True if the last factory note is critical."""
Vic Yangaabf9fd2013-04-09 18:56:13 +0800684 notes = self.state_instance.get_shared_data('factory_note', True)
685 return notes and notes[-1]['level'] == 'CRITICAL'
686
Jon Salz0697cbf2012-07-04 15:14:04 +0800687 def run_next_test(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800688 """Runs the next eligible test (or tests) in self.tests_to_run."""
Jon Salz0697cbf2012-07-04 15:14:04 +0800689 self.reap_completed_tests()
Vic Yangaabf9fd2013-04-09 18:56:13 +0800690 if self.tests_to_run and self.check_critical_factory_note():
691 self.tests_to_run.clear()
692 return
Jon Salz0697cbf2012-07-04 15:14:04 +0800693 while self.tests_to_run:
Ricky Liang6fe218c2013-12-27 15:17:17 +0800694 logging.debug('Tests to run: %s', [x.path for x in self.tests_to_run])
Jon Salz94eb56f2012-06-12 18:01:12 +0800695
Jon Salz0697cbf2012-07-04 15:14:04 +0800696 test = self.tests_to_run[0]
Jon Salz94eb56f2012-06-12 18:01:12 +0800697
Jon Salz0697cbf2012-07-04 15:14:04 +0800698 if test in self.invocations:
699 logging.info('Next test %s is already running', test.path)
700 self.tests_to_run.popleft()
701 return
Jon Salz94eb56f2012-06-12 18:01:12 +0800702
Jon Salza1412922012-07-23 16:04:17 +0800703 for requirement in test.require_run:
704 for i in requirement.test.walk():
705 if i.get_state().status == TestState.ACTIVE:
Jon Salz304a75d2012-07-06 11:14:15 +0800706 logging.info('Waiting for active test %s to complete '
Jon Salza1412922012-07-23 16:04:17 +0800707 'before running %s', i.path, test.path)
Jon Salz304a75d2012-07-06 11:14:15 +0800708 return
709
Jon Salz0697cbf2012-07-04 15:14:04 +0800710 if self.invocations and not (test.backgroundable and all(
711 [x.backgroundable for x in self.invocations])):
712 logging.debug('Waiting for non-backgroundable tests to '
Ricky Liang6fe218c2013-12-27 15:17:17 +0800713 'complete before running %s', test.path)
Jon Salz0697cbf2012-07-04 15:14:04 +0800714 return
Jon Salz94eb56f2012-06-12 18:01:12 +0800715
Jon Salz3e6f5202012-10-15 15:08:29 +0800716 if test.get_state().skip:
717 factory.console.info('Skipping test %s', test.path)
718 test.update_state(status=TestState.PASSED,
719 error_msg=TestState.SKIPPED_MSG)
720 self.tests_to_run.popleft()
721 continue
722
Jon Salz0697cbf2012-07-04 15:14:04 +0800723 self.tests_to_run.popleft()
Jon Salz94eb56f2012-06-12 18:01:12 +0800724
Jon Salz304a75d2012-07-06 11:14:15 +0800725 untested = set()
Jon Salza1412922012-07-23 16:04:17 +0800726 for requirement in test.require_run:
727 for i in requirement.test.walk():
728 if i == test:
Jon Salz304a75d2012-07-06 11:14:15 +0800729 # We've hit this test itself; stop checking
730 break
Jon Salza1412922012-07-23 16:04:17 +0800731 if ((i.get_state().status == TestState.UNTESTED) or
732 (requirement.passed and i.get_state().status !=
733 TestState.PASSED)):
Jon Salz304a75d2012-07-06 11:14:15 +0800734 # Found an untested test; move on to the next
735 # element in require_run.
Jon Salza1412922012-07-23 16:04:17 +0800736 untested.add(i)
Jon Salz304a75d2012-07-06 11:14:15 +0800737 break
738
739 if untested:
740 untested_paths = ', '.join(sorted([x.path for x in untested]))
741 if self.state_instance.get_shared_data('engineering_mode',
742 optional=True):
743 # In engineering mode, we'll let it go.
744 factory.console.warn('In engineering mode; running '
745 '%s even though required tests '
746 '[%s] have not completed',
747 test.path, untested_paths)
748 else:
749 # Not in engineering mode; mark it failed.
750 error_msg = ('Required tests [%s] have not been run yet'
751 % untested_paths)
752 factory.console.error('Not running %s: %s',
753 test.path, error_msg)
754 test.update_state(status=TestState.FAILED,
755 error_msg=error_msg)
756 continue
757
Ricky Liang48e47f92014-02-26 19:31:51 +0800758 if (isinstance(test, factory.ShutdownStep) and
759 self.state_instance.get_shared_data('post_shutdown', optional=True)):
760 # Invoking post shutdown method of shutdown test. We should retain the
761 # iterations_left and retries_left of the original test state.
762 test_state = self.state_instance.get_test_state(test.path)
763 self._run_test(test, test_state.iterations_left,
764 test_state.retries_left)
765 else:
766 # Starts a new test run; reset iterations and retries.
767 self._run_test(test, test.iterations, test.retries)
Jon Salz1acc8742012-07-17 17:45:55 +0800768
Cheng-Yi Chiangce05c002013-04-04 02:13:17 +0800769 def _run_test(self, test, iterations_left=None, retries_left=None):
Jon Salz1acc8742012-07-17 17:45:55 +0800770 invoc = TestInvocation(self, test, on_completion=self.run_next_test)
771 new_state = test.update_state(
Ricky Liang48e47f92014-02-26 19:31:51 +0800772 status=TestState.ACTIVE, increment_count=1, error_msg='',
773 invocation=invoc.uuid, iterations_left=iterations_left,
774 retries_left=retries_left,
775 visible=(self.visible_test == test))
Jon Salz1acc8742012-07-17 17:45:55 +0800776 invoc.count = new_state.count
777
778 self.invocations[test] = invoc
779 if self.visible_test is None and test.has_ui:
780 self.set_visible_test(test)
Vic Yang311ddb82012-09-26 12:08:28 +0800781 self.check_exclusive()
Jon Salz1acc8742012-07-17 17:45:55 +0800782 invoc.start()
Jon Salz5f2a0672012-05-22 17:14:06 +0800783
Vic Yang311ddb82012-09-26 12:08:28 +0800784 def check_exclusive(self):
Jon Salzce6a7f82013-06-10 18:22:54 +0800785 # alias since this is really long
786 EXCL_OPT = factory.FactoryTest.EXCLUSIVE_OPTIONS
787
Vic Yang311ddb82012-09-26 12:08:28 +0800788 current_exclusive_items = set([
Jon Salzce6a7f82013-06-10 18:22:54 +0800789 item for item in EXCL_OPT
Vic Yang311ddb82012-09-26 12:08:28 +0800790 if any([test.is_exclusive(item) for test in self.invocations])])
791
792 new_exclusive_items = current_exclusive_items - self.exclusive_items
Jon Salzce6a7f82013-06-10 18:22:54 +0800793 if EXCL_OPT.NETWORKING in new_exclusive_items:
Vic Yang311ddb82012-09-26 12:08:28 +0800794 logging.info('Disabling network')
795 self.connection_manager.DisableNetworking()
Jon Salzce6a7f82013-06-10 18:22:54 +0800796 if EXCL_OPT.CHARGER in new_exclusive_items:
Vic Yang311ddb82012-09-26 12:08:28 +0800797 logging.info('Stop controlling charger')
798
799 new_non_exclusive_items = self.exclusive_items - current_exclusive_items
Jon Salzce6a7f82013-06-10 18:22:54 +0800800 if EXCL_OPT.NETWORKING in new_non_exclusive_items:
Vic Yang311ddb82012-09-26 12:08:28 +0800801 logging.info('Re-enabling network')
802 self.connection_manager.EnableNetworking()
Jon Salzce6a7f82013-06-10 18:22:54 +0800803 if EXCL_OPT.CHARGER in new_non_exclusive_items:
Vic Yang311ddb82012-09-26 12:08:28 +0800804 logging.info('Start controlling charger')
805
Jon Salzce6a7f82013-06-10 18:22:54 +0800806 if self.cpufreq_manager:
807 enabled = EXCL_OPT.CPUFREQ not in current_exclusive_items
808 try:
809 self.cpufreq_manager.SetEnabled(enabled)
810 except: # pylint: disable=W0702
811 logging.exception('Unable to %s cpufreq services',
812 'enable' if enabled else 'disable')
813
Vic Yang311ddb82012-09-26 12:08:28 +0800814 # Only adjust charge state if not excluded
Jon Salzce6a7f82013-06-10 18:22:54 +0800815 if (EXCL_OPT.CHARGER not in current_exclusive_items and
816 not utils.in_chroot()):
Cheng-Yi Chiangd8186952013-04-04 23:41:14 +0800817 if self.charge_manager:
818 self.charge_manager.AdjustChargeState()
819 else:
820 try:
821 system.GetBoard().SetChargeState(Board.ChargeState.CHARGE)
822 except BoardException:
823 logging.exception('Unable to set charge state on this board')
Vic Yang311ddb82012-09-26 12:08:28 +0800824
825 self.exclusive_items = current_exclusive_items
Jon Salz5da61e62012-05-31 13:06:22 +0800826
cychiang21886742012-07-05 15:16:32 +0800827 def check_for_updates(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800828 """Schedules an asynchronous check for updates if necessary."""
cychiang21886742012-07-05 15:16:32 +0800829 if not self.test_list.options.update_period_secs:
830 # Not enabled.
831 return
832
833 now = time.time()
834 if self.last_update_check and (
835 now - self.last_update_check <
836 self.test_list.options.update_period_secs):
837 # Not yet time for another check.
838 return
839
840 self.last_update_check = now
841
842 def handle_check_for_update(reached_shopfloor, md5sum, needs_update):
843 if reached_shopfloor:
844 new_update_md5sum = md5sum if needs_update else None
845 if system.SystemInfo.update_md5sum != new_update_md5sum:
846 logging.info('Received new update MD5SUM: %s', new_update_md5sum)
847 system.SystemInfo.update_md5sum = new_update_md5sum
848 self.run_queue.put(self.update_system_info)
849
850 updater.CheckForUpdateAsync(
851 handle_check_for_update,
852 self.test_list.options.shopfloor_timeout_secs)
853
Jon Salza6711d72012-07-18 14:33:03 +0800854 def cancel_pending_tests(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800855 """Cancels any tests in the run queue."""
Jon Salza6711d72012-07-18 14:33:03 +0800856 self.run_tests([])
857
Ricky Liang4bff3e32014-02-20 18:46:11 +0800858 def restore_active_run_state(self):
859 """Restores active run id and the list of scheduled tests."""
860 self.run_id = self.state_instance.get_shared_data('run_id', optional=True)
861 self.scheduled_run_tests = self.state_instance.get_shared_data(
862 'scheduled_run_tests', optional=True)
863
864 def set_active_run_state(self):
865 """Sets active run id and the list of scheduled tests."""
866 self.run_id = str(uuid.uuid4())
867 self.scheduled_run_tests = [test.path for test in self.tests_to_run]
868 self.state_instance.set_shared_data('run_id', self.run_id)
869 self.state_instance.set_shared_data('scheduled_run_tests',
870 self.scheduled_run_tests)
871
Jon Salz0697cbf2012-07-04 15:14:04 +0800872 def run_tests(self, subtrees, untested_only=False):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800873 """Runs tests under subtree.
Jon Salz258a40c2012-04-19 12:34:01 +0800874
Jon Salz0697cbf2012-07-04 15:14:04 +0800875 The tests are run in order unless one fails (then stops).
876 Backgroundable tests are run simultaneously; when a foreground test is
877 encountered, we wait for all active tests to finish before continuing.
Jon Salzb1b39092012-05-03 02:05:09 +0800878
Ricky Liang6fe218c2013-12-27 15:17:17 +0800879 Args:
880 subtrees: Node or nodes containing tests to run (may either be
881 a single test or a list). Duplicates will be ignored.
882 untested_only: True to run untested tests only.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800883 """
Jon Salz0697cbf2012-07-04 15:14:04 +0800884 if type(subtrees) != list:
885 subtrees = [subtrees]
Jon Salz258a40c2012-04-19 12:34:01 +0800886
Jon Salz0697cbf2012-07-04 15:14:04 +0800887 # Nodes we've seen so far, to avoid duplicates.
888 seen = set()
Jon Salz94eb56f2012-06-12 18:01:12 +0800889
Jon Salz0697cbf2012-07-04 15:14:04 +0800890 self.tests_to_run = deque()
891 for subtree in subtrees:
892 for test in subtree.walk():
893 if test in seen:
894 continue
895 seen.add(test)
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800896
Jon Salz0697cbf2012-07-04 15:14:04 +0800897 if not test.is_leaf():
898 continue
Ricky Liang4bff3e32014-02-20 18:46:11 +0800899 if (untested_only and test.get_state().status != TestState.UNTESTED):
Jon Salz0697cbf2012-07-04 15:14:04 +0800900 continue
901 self.tests_to_run.append(test)
Ricky Liang4bff3e32014-02-20 18:46:11 +0800902 if subtrees:
903 self.set_active_run_state()
Jon Salz0697cbf2012-07-04 15:14:04 +0800904 self.run_next_test()
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800905
Jon Salz0697cbf2012-07-04 15:14:04 +0800906 def reap_completed_tests(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800907 """Removes completed tests from the set of active tests.
Jon Salz0697cbf2012-07-04 15:14:04 +0800908
909 Also updates the visible test if it was reaped.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800910 """
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +0800911 test_completed = False
Jon Salz0697cbf2012-07-04 15:14:04 +0800912 for t, v in dict(self.invocations).iteritems():
913 if v.is_completed():
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +0800914 test_completed = True
Jon Salz1acc8742012-07-17 17:45:55 +0800915 new_state = t.update_state(**v.update_state_on_completion)
Jon Salz0697cbf2012-07-04 15:14:04 +0800916 del self.invocations[t]
917
Chun-Ta Lin54e17e42012-09-06 22:05:13 +0800918 # Stop on failure if flag is true.
919 if (self.test_list.options.stop_on_failure and
920 new_state.status == TestState.FAILED):
921 # Clean all the tests to cause goofy to stop.
922 self.tests_to_run = []
923 factory.console.info("Stop on failure triggered. Empty the queue.")
924
Jon Salz1acc8742012-07-17 17:45:55 +0800925 if new_state.iterations_left and new_state.status == TestState.PASSED:
926 # Play it again, Sam!
927 self._run_test(t)
Cheng-Yi Chiangce05c002013-04-04 02:13:17 +0800928 # new_state.retries_left is obtained after update.
929 # For retries_left == 0, test can still be run for the last time.
930 elif (new_state.retries_left >= 0 and
931 new_state.status == TestState.FAILED):
932 # Still have to retry, Sam!
933 self._run_test(t)
Jon Salz1acc8742012-07-17 17:45:55 +0800934
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +0800935 if test_completed:
Vic Yangf01c59f2013-04-19 17:37:56 +0800936 self.log_watcher.KickWatchThread()
Cheng-Yi Chiang5ac22ca2013-04-12 17:45:26 +0800937
Jon Salz0697cbf2012-07-04 15:14:04 +0800938 if (self.visible_test is None or
Jon Salz85a39882012-07-05 16:45:04 +0800939 self.visible_test not in self.invocations):
Jon Salz0697cbf2012-07-04 15:14:04 +0800940 self.set_visible_test(None)
941 # Make the first running test, if any, the visible test
942 for t in self.test_list.walk():
943 if t in self.invocations:
944 self.set_visible_test(t)
945 break
946
Jon Salz6dc031d2013-06-19 13:06:23 +0800947 def kill_active_tests(self, abort, root=None, reason=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800948 """Kills and waits for all active tests.
Jon Salz0697cbf2012-07-04 15:14:04 +0800949
Jon Salz85a39882012-07-05 16:45:04 +0800950 Args:
951 abort: True to change state of killed tests to FAILED, False for
Jon Salz0697cbf2012-07-04 15:14:04 +0800952 UNTESTED.
Jon Salz85a39882012-07-05 16:45:04 +0800953 root: If set, only kills tests with root as an ancestor.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +0800954 reason: If set, the abort reason.
955 """
Jon Salz0697cbf2012-07-04 15:14:04 +0800956 self.reap_completed_tests()
957 for test, invoc in self.invocations.items():
Jon Salz85a39882012-07-05 16:45:04 +0800958 if root and not test.has_ancestor(root):
959 continue
960
Jon Salz0697cbf2012-07-04 15:14:04 +0800961 factory.console.info('Killing active test %s...' % test.path)
Jon Salz6dc031d2013-06-19 13:06:23 +0800962 invoc.abort_and_join(reason)
Jon Salz0697cbf2012-07-04 15:14:04 +0800963 factory.console.info('Killed %s' % test.path)
Jon Salz1acc8742012-07-17 17:45:55 +0800964 test.update_state(**invoc.update_state_on_completion)
Jon Salz0697cbf2012-07-04 15:14:04 +0800965 del self.invocations[test]
Jon Salz1acc8742012-07-17 17:45:55 +0800966
Jon Salz0697cbf2012-07-04 15:14:04 +0800967 if not abort:
968 test.update_state(status=TestState.UNTESTED)
969 self.reap_completed_tests()
970
Jon Salz6dc031d2013-06-19 13:06:23 +0800971 def stop(self, root=None, fail=False, reason=None):
972 self.kill_active_tests(fail, root, reason)
Jon Salz85a39882012-07-05 16:45:04 +0800973 # Remove any tests in the run queue under the root.
974 self.tests_to_run = deque([x for x in self.tests_to_run
975 if root and not x.has_ancestor(root)])
976 self.run_next_test()
Jon Salz0697cbf2012-07-04 15:14:04 +0800977
Jon Salz4712ac72013-02-07 17:12:05 +0800978 def clear_state(self, root=None):
Jon Salzd7550792013-07-12 05:49:27 +0800979 if root is None:
980 root = self.test_list
Jon Salz6dc031d2013-06-19 13:06:23 +0800981 self.stop(root, reason='Clearing test state')
Jon Salz4712ac72013-02-07 17:12:05 +0800982 for f in root.walk():
983 if f.is_leaf():
984 f.update_state(status=TestState.UNTESTED)
985
Jon Salz6dc031d2013-06-19 13:06:23 +0800986 def abort_active_tests(self, reason=None):
987 self.kill_active_tests(True, reason=reason)
Jon Salz0697cbf2012-07-04 15:14:04 +0800988
989 def main(self):
Jon Salzeff94182013-06-19 15:06:28 +0800990 syslog.openlog('goofy')
991
Jon Salz0697cbf2012-07-04 15:14:04 +0800992 try:
Jon Salzd7550792013-07-12 05:49:27 +0800993 self.status = Status.INITIALIZING
Jon Salz0697cbf2012-07-04 15:14:04 +0800994 self.init()
995 self.event_log.Log('goofy_init',
996 success=True)
997 except:
998 if self.event_log:
Hung-Te Linf2f78f72012-02-08 19:27:11 +0800999 try:
Jon Salz0697cbf2012-07-04 15:14:04 +08001000 self.event_log.Log('goofy_init',
1001 success=False,
1002 trace=traceback.format_exc())
1003 except: # pylint: disable=W0702
1004 pass
1005 raise
1006
Jon Salzd7550792013-07-12 05:49:27 +08001007 self.status = Status.RUNNING
Jon Salzeff94182013-06-19 15:06:28 +08001008 syslog.syslog('Goofy (factory test harness) starting')
Jon Salz0697cbf2012-07-04 15:14:04 +08001009 self.run()
1010
1011 def update_system_info(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001012 """Updates system info."""
Jon Salz0697cbf2012-07-04 15:14:04 +08001013 system_info = system.SystemInfo()
1014 self.state_instance.set_shared_data('system_info', system_info.__dict__)
1015 self.event_client.post_event(Event(Event.Type.SYSTEM_INFO,
1016 system_info=system_info.__dict__))
1017 logging.info('System info: %r', system_info.__dict__)
1018
Jon Salzeb42f0d2012-07-27 19:14:04 +08001019 def update_factory(self, auto_run_on_restart=False, post_update_hook=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001020 """Commences updating factory software.
Jon Salzeb42f0d2012-07-27 19:14:04 +08001021
1022 Args:
1023 auto_run_on_restart: Auto-run when the machine comes back up.
1024 post_update_hook: Code to call after update but immediately before
1025 restart.
1026
1027 Returns:
1028 Never if the update was successful (we just reboot).
1029 False if the update was unnecessary (no update available).
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001030 """
Jon Salz6dc031d2013-06-19 13:06:23 +08001031 self.kill_active_tests(False, reason='Factory software update')
Jon Salza6711d72012-07-18 14:33:03 +08001032 self.cancel_pending_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +08001033
Jon Salz5c344f62012-07-13 14:31:16 +08001034 def pre_update_hook():
1035 if auto_run_on_restart:
1036 self.state_instance.set_shared_data('tests_after_shutdown',
1037 FORCE_AUTO_RUN)
1038 self.state_instance.close()
1039
Jon Salzeb42f0d2012-07-27 19:14:04 +08001040 if updater.TryUpdate(pre_update_hook=pre_update_hook):
1041 if post_update_hook:
1042 post_update_hook()
1043 self.env.shutdown('reboot')
Jon Salz0697cbf2012-07-04 15:14:04 +08001044
Jon Salzcef132a2012-08-30 04:58:08 +08001045 def handle_sigint(self, dummy_signum, dummy_frame):
Jon Salz77c151e2012-08-28 07:20:37 +08001046 logging.error('Received SIGINT')
1047 self.run_queue.put(None)
1048 raise KeyboardInterrupt()
1049
Jon Salze12c2b32013-06-25 16:24:34 +08001050 def find_kcrashes(self):
1051 """Finds kcrash files, logs them, and marks them as seen."""
1052 seen_crashes = set(
1053 self.state_instance.get_shared_data('seen_crashes', optional=True)
1054 or [])
1055
1056 for path in glob.glob('/var/spool/crash/*'):
1057 if not os.path.isfile(path):
1058 continue
1059 if path in seen_crashes:
1060 continue
1061 try:
1062 stat = os.stat(path)
1063 mtime = utils.TimeString(stat.st_mtime)
1064 logging.info(
1065 'Found new crash file %s (%d bytes at %s)',
1066 path, stat.st_size, mtime)
1067 extra_log_args = {}
1068
1069 try:
1070 _, ext = os.path.splitext(path)
1071 if ext in ['.kcrash', '.meta']:
1072 ext = ext.replace('.', '')
1073 with open(path) as f:
1074 data = f.read(MAX_CRASH_FILE_SIZE)
1075 tell = f.tell()
1076 logging.info(
1077 'Contents of %s%s:%s',
1078 path,
1079 ('' if tell == stat.st_size
1080 else '(truncated to %d bytes)' % MAX_CRASH_FILE_SIZE),
1081 ('\n' + data).replace('\n', '\n ' + ext + '> '))
1082 extra_log_args['data'] = data
1083
1084 # Copy to /var/factory/kcrash for posterity
1085 kcrash_dir = factory.get_factory_root('kcrash')
1086 utils.TryMakeDirs(kcrash_dir)
1087 shutil.copy(path, kcrash_dir)
1088 logging.info('Copied to %s',
1089 os.path.join(kcrash_dir, os.path.basename(path)))
1090 finally:
1091 # Even if something goes wrong with the above, still try to
1092 # log to event log
1093 self.event_log.Log('crash_file',
1094 path=path, size=stat.st_size, mtime=mtime,
1095 **extra_log_args)
1096 except: # pylint: disable=W0702
1097 logging.exception('Unable to handle crash files %s', path)
1098 seen_crashes.add(path)
1099
1100 self.state_instance.set_shared_data('seen_crashes', list(seen_crashes))
1101
Jon Salz128b0932013-07-03 16:55:26 +08001102 def GetTestList(self, test_list_id):
1103 """Returns the test list with the given ID.
1104
1105 Raises:
1106 TestListError: The test list ID is not valid.
1107 """
1108 try:
1109 return self.test_lists[test_list_id]
1110 except KeyError:
1111 raise test_lists.TestListError(
1112 '%r is not a valid test list ID (available IDs are [%s])' % (
1113 test_list_id, ', '.join(sorted(self.test_lists.keys()))))
1114
1115 def InitTestLists(self):
1116 """Reads in all test lists and sets the active test list."""
1117 self.test_lists = test_lists.BuildAllTestLists()
Jon Salzd7550792013-07-12 05:49:27 +08001118 logging.info('Loaded test lists: [%s]',
1119 test_lists.DescribeTestLists(self.test_lists))
Jon Salz128b0932013-07-03 16:55:26 +08001120
1121 if not self.options.test_list:
1122 self.options.test_list = test_lists.GetActiveTestListId()
1123
1124 if os.sep in self.options.test_list:
1125 # It's a path pointing to an old-style test list; use it.
1126 self.test_list = factory.read_test_list(self.options.test_list)
1127 else:
1128 self.test_list = self.GetTestList(self.options.test_list)
1129
1130 logging.info('Active test list: %s', self.test_list.test_list_id)
1131
1132 if isinstance(self.test_list, test_lists.OldStyleTestList):
1133 # Actually load it in. (See OldStyleTestList for an explanation
1134 # of why this is necessary.)
1135 self.test_list = self.test_list.Load()
1136
1137 self.test_list.state_instance = self.state_instance
1138
Shuo-Peng Liao268b40b2013-07-01 15:58:59 +08001139 def init_hooks(self):
1140 """Initializes hooks.
1141
1142 Must run after self.test_list ready.
1143 """
Shuo-Peng Liao52b90da2013-06-30 17:00:06 +08001144 module, cls = self.test_list.options.hooks_class.rsplit('.', 1)
1145 self.hooks = getattr(__import__(module, fromlist=[cls]), cls)()
1146 assert isinstance(self.hooks, factory.Hooks), (
1147 "hooks should be of type Hooks but is %r" % type(self.hooks))
1148 self.hooks.test_list = self.test_list
Shuo-Peng Liao268b40b2013-07-01 15:58:59 +08001149 self.hooks.OnCreatedTestList()
Shuo-Peng Liao52b90da2013-06-30 17:00:06 +08001150
Jon Salz0697cbf2012-07-04 15:14:04 +08001151 def init(self, args=None, env=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001152 """Initializes Goofy.
Jon Salz0697cbf2012-07-04 15:14:04 +08001153
1154 Args:
1155 args: A list of command-line arguments. Uses sys.argv if
1156 args is None.
1157 env: An Environment instance to use (or None to choose
1158 FakeChrootEnvironment or DUTEnvironment as appropriate).
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001159 """
Jon Salz77c151e2012-08-28 07:20:37 +08001160 signal.signal(signal.SIGINT, self.handle_sigint)
1161
Jon Salz0697cbf2012-07-04 15:14:04 +08001162 parser = OptionParser()
1163 parser.add_option('-v', '--verbose', dest='verbose',
Jon Salz8fa8e832012-07-13 19:04:09 +08001164 action='store_true',
1165 help='Enable debug logging')
Jon Salz0697cbf2012-07-04 15:14:04 +08001166 parser.add_option('--print_test_list', dest='print_test_list',
Jon Salz8fa8e832012-07-13 19:04:09 +08001167 metavar='FILE',
1168 help='Read and print test list FILE, and exit')
Jon Salz0697cbf2012-07-04 15:14:04 +08001169 parser.add_option('--restart', dest='restart',
Jon Salz8fa8e832012-07-13 19:04:09 +08001170 action='store_true',
1171 help='Clear all test state')
Jon Salz0697cbf2012-07-04 15:14:04 +08001172 parser.add_option('--ui', dest='ui', type='choice',
Jon Salz8fa8e832012-07-13 19:04:09 +08001173 choices=['none', 'gtk', 'chrome'],
Jon Salz2f881df2013-02-01 17:00:35 +08001174 default='chrome',
Jon Salz8fa8e832012-07-13 19:04:09 +08001175 help='UI to use')
Jon Salz0697cbf2012-07-04 15:14:04 +08001176 parser.add_option('--ui_scale_factor', dest='ui_scale_factor',
Jon Salz8fa8e832012-07-13 19:04:09 +08001177 type='int', default=1,
1178 help=('Factor by which to scale UI '
1179 '(Chrome UI only)'))
Jon Salz0697cbf2012-07-04 15:14:04 +08001180 parser.add_option('--test_list', dest='test_list',
Jon Salz8fa8e832012-07-13 19:04:09 +08001181 metavar='FILE',
1182 help='Use FILE as test list')
Jon Salzc79a9982012-08-30 04:42:01 +08001183 parser.add_option('--dummy_shopfloor', action='store_true',
1184 help='Use a dummy shopfloor server')
Ricky Liang6fe218c2013-12-27 15:17:17 +08001185 parser.add_option('--automation-mode',
1186 choices=[m.lower() for m in AutomationMode],
1187 default='none', help="Factory test automation mode.")
Ricky Liang117484a2014-04-14 11:14:41 +08001188 parser.add_option('--no-auto-run-on-start', dest='auto_run_on_start',
1189 action='store_false', default=True,
1190 help=('do not automatically run the test list on goofy '
1191 'start; this is only valid when factory test '
1192 'automation is enabled'))
Ricky Liang8c2c6c32013-11-02 23:02:44 +08001193 parser.add_option('--guest_login', dest='guest_login', default=False,
Ricky Liangb2432362013-10-02 13:12:41 +08001194 action='store_true',
Ricky Liang8c2c6c32013-11-02 23:02:44 +08001195 help='Log in as guest. This will not own the TPM.')
Jon Salz0697cbf2012-07-04 15:14:04 +08001196 (self.options, self.args) = parser.parse_args(args)
1197
Jon Salz46b89562012-07-05 11:49:22 +08001198 # Make sure factory directories exist.
1199 factory.get_log_root()
1200 factory.get_state_root()
1201 factory.get_test_data_root()
1202
Jon Salz0697cbf2012-07-04 15:14:04 +08001203 global _inited_logging # pylint: disable=W0603
1204 if not _inited_logging:
1205 factory.init_logging('goofy', verbose=self.options.verbose)
1206 _inited_logging = True
Jon Salz8fa8e832012-07-13 19:04:09 +08001207
Jon Salz0f996602012-10-03 15:26:48 +08001208 if self.options.print_test_list:
1209 print factory.read_test_list(
1210 self.options.print_test_list).__repr__(recursive=True)
1211 sys.exit(0)
1212
Jon Salzee85d522012-07-17 14:34:46 +08001213 event_log.IncrementBootSequence()
Jon Salzd15bbcf2013-05-21 17:33:57 +08001214 # Don't defer logging the initial event, so we can make sure
1215 # that device_id, reimage_id, etc. are all set up.
1216 self.event_log = EventLog('goofy', defer=False)
Jon Salz0697cbf2012-07-04 15:14:04 +08001217
1218 if (not suppress_chroot_warning and
1219 factory.in_chroot() and
1220 self.options.ui == 'gtk' and
1221 os.environ.get('DISPLAY') in [None, '', ':0', ':0.0']):
1222 # That's not going to work! Tell the user how to run
1223 # this way.
1224 logging.warn(GOOFY_IN_CHROOT_WARNING)
1225 time.sleep(1)
1226
1227 if env:
1228 self.env = env
1229 elif factory.in_chroot():
1230 self.env = test_environment.FakeChrootEnvironment()
1231 logging.warn(
1232 'Using chroot environment: will not actually run autotests')
1233 else:
Ricky Liang8c2c6c32013-11-02 23:02:44 +08001234 if self.options.guest_login:
1235 os.mknod(test_environment.DUTEnvironment.GUEST_MODE_TAG_FILE)
1236 self.env = test_environment.DUTEnvironment()
Jon Salz0697cbf2012-07-04 15:14:04 +08001237 self.env.goofy = self
1238
1239 if self.options.restart:
1240 state.clear_state()
1241
Jon Salz0697cbf2012-07-04 15:14:04 +08001242 if self.options.ui_scale_factor != 1 and utils.in_qemu():
1243 logging.warn(
1244 'In QEMU; ignoring ui_scale_factor argument')
1245 self.options.ui_scale_factor = 1
1246
1247 logging.info('Started')
1248
1249 self.start_state_server()
1250 self.state_instance.set_shared_data('hwid_cfg', get_hwid_cfg())
1251 self.state_instance.set_shared_data('ui_scale_factor',
Ricky Liang09216dc2013-02-22 17:26:45 +08001252 self.options.ui_scale_factor)
Jon Salz0697cbf2012-07-04 15:14:04 +08001253 self.last_shutdown_time = (
1254 self.state_instance.get_shared_data('shutdown_time', optional=True))
1255 self.state_instance.del_shared_data('shutdown_time', optional=True)
Jon Salzb19ea072013-02-07 16:35:00 +08001256 self.state_instance.del_shared_data('startup_error', optional=True)
Jon Salz0697cbf2012-07-04 15:14:04 +08001257
Ricky Liang6fe218c2013-12-27 15:17:17 +08001258 self.options.automation_mode = ParseAutomationMode(
1259 self.options.automation_mode)
1260 self.state_instance.set_shared_data('automation_mode',
1261 self.options.automation_mode)
1262 self.state_instance.set_shared_data(
1263 'automation_mode_prompt',
1264 AutomationModePrompt[self.options.automation_mode])
1265
Jon Salz128b0932013-07-03 16:55:26 +08001266 try:
1267 self.InitTestLists()
1268 except: # pylint: disable=W0702
1269 logging.exception('Unable to initialize test lists')
1270 self.state_instance.set_shared_data(
1271 'startup_error',
1272 'Unable to initialize test lists\n%s' % (
1273 traceback.format_exc()))
Jon Salzb19ea072013-02-07 16:35:00 +08001274 if self.options.ui == 'chrome':
1275 # Create an empty test list with default options so that the rest of
1276 # startup can proceed.
1277 self.test_list = factory.FactoryTestList(
1278 [], self.state_instance, factory.Options())
1279 else:
1280 # Bail with an error; no point in starting up.
1281 sys.exit('No valid test list; exiting.')
1282
Shuo-Peng Liao268b40b2013-07-01 15:58:59 +08001283 self.init_hooks()
1284
Jon Salz822838b2013-03-25 17:32:33 +08001285 if self.test_list.options.clear_state_on_start:
1286 self.state_instance.clear_test_state()
1287
Vic Yang3e1cf5d2013-06-05 18:50:24 +08001288 if system.SystemInfo().firmware_version is None and not utils.in_chroot():
Vic Yang9bd4f772013-06-04 17:34:00 +08001289 self.state_instance.set_shared_data('startup_error',
1290 'Netboot firmware detected\n'
1291 'Connect Ethernet and reboot to re-image.\n'
1292 u'侦测到网路开机固件\n'
1293 u'请连接乙太网并重启')
1294
Jon Salz0697cbf2012-07-04 15:14:04 +08001295 if not self.state_instance.has_shared_data('ui_lang'):
1296 self.state_instance.set_shared_data('ui_lang',
1297 self.test_list.options.ui_lang)
1298 self.state_instance.set_shared_data(
1299 'test_list_options',
1300 self.test_list.options.__dict__)
1301 self.state_instance.test_list = self.test_list
1302
Cheng-Yi Chiang39d32ad2013-07-23 15:02:38 +08001303 self.check_log_rotation()
Jon Salz83ef34b2012-11-01 19:46:35 +08001304
Jon Salz23926422012-09-01 03:38:13 +08001305 if self.options.dummy_shopfloor:
1306 os.environ[shopfloor.SHOPFLOOR_SERVER_ENV_VAR_NAME] = (
1307 'http://localhost:%d/' % shopfloor.DEFAULT_SERVER_PORT)
1308 self.dummy_shopfloor = Spawn(
1309 [os.path.join(factory.FACTORY_PATH, 'bin', 'shopfloor_server'),
1310 '--dummy'])
1311 elif self.test_list.options.shopfloor_server_url:
1312 shopfloor.set_server_url(self.test_list.options.shopfloor_server_url)
Jon Salz2bf2f6b2013-03-28 18:49:26 +08001313 shopfloor.set_enabled(True)
Jon Salz23926422012-09-01 03:38:13 +08001314
Jon Salz0f996602012-10-03 15:26:48 +08001315 if self.test_list.options.time_sanitizer and not utils.in_chroot():
Jon Salz8fa8e832012-07-13 19:04:09 +08001316 self.time_sanitizer = time_sanitizer.TimeSanitizer(
1317 base_time=time_sanitizer.GetBaseTimeFromFile(
1318 # lsb-factory is written by the factory install shim during
1319 # installation, so it should have a good time obtained from
Jon Salz54882d02012-08-31 01:57:54 +08001320 # the mini-Omaha server. If it's not available, we'll use
1321 # /etc/lsb-factory (which will be much older, but reasonably
1322 # sane) and rely on a shopfloor sync to set a more accurate
1323 # time.
1324 '/usr/local/etc/lsb-factory',
1325 '/etc/lsb-release'))
Jon Salz8fa8e832012-07-13 19:04:09 +08001326 self.time_sanitizer.RunOnce()
1327
Vic Yangd8990da2013-06-27 16:57:43 +08001328 if self.test_list.options.check_cpu_usage_period_secs:
1329 self.cpu_usage_watcher = Spawn(['py/tools/cpu_usage_monitor.py',
1330 '-p', str(self.test_list.options.check_cpu_usage_period_secs)],
1331 cwd=factory.FACTORY_PATH)
1332
Jon Salz0697cbf2012-07-04 15:14:04 +08001333 self.init_states()
1334 self.start_event_server()
1335 self.connection_manager = self.env.create_connection_manager(
Tai-Hsu Lin371351a2012-08-27 14:17:14 +08001336 self.test_list.options.wlans,
1337 self.test_list.options.scan_wifi_period_secs)
Jon Salz0697cbf2012-07-04 15:14:04 +08001338 # Note that we create a log watcher even if
1339 # sync_event_log_period_secs isn't set (no background
1340 # syncing), since we may use it to flush event logs as well.
1341 self.log_watcher = EventLogWatcher(
1342 self.test_list.options.sync_event_log_period_secs,
Jon Salzd15bbcf2013-05-21 17:33:57 +08001343 event_log_db_file=None,
Jon Salz16d10542012-07-23 12:18:45 +08001344 handle_event_logs_callback=self.handle_event_logs)
Jon Salz0697cbf2012-07-04 15:14:04 +08001345 if self.test_list.options.sync_event_log_period_secs:
1346 self.log_watcher.StartWatchThread()
1347
Cheng-Yi Chianga0f6eff2014-01-09 18:27:22 +08001348 # Creates a system log manager to scan logs periocially.
1349 # A scan includes clearing logs and optionally syncing logs if
1350 # enable_syng_log is True. We kick it to sync logs.
1351 self.system_log_manager = SystemLogManager(
1352 sync_log_paths=self.test_list.options.sync_log_paths,
1353 sync_log_period_secs=self.test_list.options.sync_log_period_secs,
1354 scan_log_period_secs=self.test_list.options.scan_log_period_secs,
Cheng-Yi Chiangb8a491c2014-01-20 14:37:57 +08001355 clear_log_paths=self.test_list.options.clear_log_paths,
1356 clear_log_excluded_paths=self.test_list.options.clear_log_excluded_paths)
Cheng-Yi Chianga0f6eff2014-01-09 18:27:22 +08001357 self.system_log_manager.Start()
Cheng-Yi Chiang344b10f2013-05-03 16:44:03 +08001358
Jon Salz0697cbf2012-07-04 15:14:04 +08001359 self.update_system_info()
1360
Vic Yang4953fc12012-07-26 16:19:53 +08001361 assert ((self.test_list.options.min_charge_pct is None) ==
1362 (self.test_list.options.max_charge_pct is None))
Vic Yange83d9a12013-04-19 20:00:20 +08001363 if utils.in_chroot():
1364 logging.info('In chroot, ignoring charge manager and charge state')
1365 elif self.test_list.options.min_charge_pct is not None:
Vic Yang4953fc12012-07-26 16:19:53 +08001366 self.charge_manager = ChargeManager(self.test_list.options.min_charge_pct,
1367 self.test_list.options.max_charge_pct)
Jon Salzad7353b2012-10-15 16:22:46 +08001368 system.SystemStatus.charge_manager = self.charge_manager
Cheng-Yi Chiangd8186952013-04-04 23:41:14 +08001369 else:
1370 # Goofy should set charger state to charge if charge_manager is disabled.
1371 try:
1372 system.GetBoard().SetChargeState(Board.ChargeState.CHARGE)
1373 except BoardException:
1374 logging.exception('Unable to set charge state on this board')
Vic Yang4953fc12012-07-26 16:19:53 +08001375
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001376 self.core_dump_manager = CoreDumpManager(
1377 self.test_list.options.core_dump_watchlist)
1378
Jon Salz0697cbf2012-07-04 15:14:04 +08001379 os.environ['CROS_FACTORY'] = '1'
1380 os.environ['CROS_DISABLE_SITE_SYSINFO'] = '1'
1381
1382 # Set CROS_UI since some behaviors in ui.py depend on the
1383 # particular UI in use. TODO(jsalz): Remove this (and all
1384 # places it is used) when the GTK UI is removed.
1385 os.environ['CROS_UI'] = self.options.ui
1386
Shuo-Peng Liao1ff502e2013-06-30 18:37:02 +08001387 if not utils.in_chroot() and self.test_list.options.use_cpufreq_manager:
Jon Salzddf0d052013-06-18 12:52:44 +08001388 self.cpufreq_manager = CpufreqManager(event_log=self.event_log)
Jon Salzce6a7f82013-06-10 18:22:54 +08001389
Justin Chuang31b02432013-06-27 15:16:51 +08001390 # Startup hooks may want to skip some tests.
1391 self.update_skipped_tests()
Jon Salz416f9cc2013-05-10 18:32:50 +08001392
Jon Salze12c2b32013-06-25 16:24:34 +08001393 self.find_kcrashes()
1394
Shuo-Peng Liao268b40b2013-07-01 15:58:59 +08001395 # Should not move earlier.
1396 self.hooks.OnStartup()
1397
Jon Salz0697cbf2012-07-04 15:14:04 +08001398 if self.options.ui == 'chrome':
1399 self.env.launch_chrome()
1400 logging.info('Waiting for a web socket connection')
Cheng-Yi Chiangfd8ed392013-03-08 21:37:31 +08001401 self.web_socket_manager.wait()
Jon Salz0697cbf2012-07-04 15:14:04 +08001402
1403 # Wait for the test widget size to be set; this is done in
1404 # an asynchronous RPC so there is a small chance that the
1405 # web socket might be opened first.
1406 for _ in range(100): # 10 s
1407 try:
1408 if self.state_instance.get_shared_data('test_widget_size'):
1409 break
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001410 except KeyError:
Jon Salz0697cbf2012-07-04 15:14:04 +08001411 pass # Retry
1412 time.sleep(0.1) # 100 ms
1413 else:
1414 logging.warn('Never received test_widget_size from UI')
Jon Salz45297282013-05-18 14:31:47 +08001415
1416 # Send Chrome a Tab to get focus to the factory UI
1417 # (http://crosbug.com/p/19444). TODO(jsalz): remove this hack
1418 # and figure out the right way to get the focus to Chrome.
1419 if not utils.in_chroot():
Ricky Liangb97f3652013-08-20 17:30:28 +08001420 utils.SendKey('Tab')
Jon Salz0697cbf2012-07-04 15:14:04 +08001421 elif self.options.ui == 'gtk':
1422 self.start_ui()
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001423
Ricky Liang650f6bf2012-09-28 13:22:54 +08001424 # Create download path for autotest beforehand or autotests run at
1425 # the same time might fail due to race condition.
1426 if not factory.in_chroot():
1427 utils.TryMakeDirs(os.path.join('/usr/local/autotest', 'tests',
1428 'download'))
1429
Jon Salz0697cbf2012-07-04 15:14:04 +08001430 def state_change_callback(test, test_state):
1431 self.event_client.post_event(
Ricky Liang4bff3e32014-02-20 18:46:11 +08001432 Event(Event.Type.STATE_CHANGE, path=test.path, state=test_state))
Jon Salz0697cbf2012-07-04 15:14:04 +08001433 self.test_list.state_change_callback = state_change_callback
Jon Salz73e0fd02012-04-04 11:46:38 +08001434
Jon Salza6711d72012-07-18 14:33:03 +08001435 for handler in self.on_ui_startup:
1436 handler()
1437
1438 self.prespawner = Prespawner()
1439 self.prespawner.start()
1440
Ricky Liang48e47f92014-02-26 19:31:51 +08001441 tests_after_shutdown = self.state_instance.get_shared_data(
1442 'tests_after_shutdown', optional=True)
Jon Salz57717ca2012-04-04 16:47:25 +08001443
Jon Salz5c344f62012-07-13 14:31:16 +08001444 force_auto_run = (tests_after_shutdown == FORCE_AUTO_RUN)
1445 if not force_auto_run and tests_after_shutdown is not None:
Ricky Liang48e47f92014-02-26 19:31:51 +08001446 logging.info('Resuming tests after shutdown: %s', tests_after_shutdown)
Jon Salz0697cbf2012-07-04 15:14:04 +08001447 self.tests_to_run.extend(
Ricky Liang4bff3e32014-02-20 18:46:11 +08001448 self.test_list.lookup_path(t) for t in tests_after_shutdown)
Jon Salz0697cbf2012-07-04 15:14:04 +08001449 self.run_queue.put(self.run_next_test)
1450 else:
Jon Salz5c344f62012-07-13 14:31:16 +08001451 if force_auto_run or self.test_list.options.auto_run_on_start:
Ricky Liang117484a2014-04-14 11:14:41 +08001452 # If automation mode is enabled, allow suppress auto_run_on_start.
1453 if (self.options.automation_mode == 'NONE' or
1454 self.options.auto_run_on_start):
1455 self.run_queue.put(
1456 lambda: self.run_tests(self.test_list, untested_only=True))
Jon Salz5c344f62012-07-13 14:31:16 +08001457 self.state_instance.set_shared_data('tests_after_shutdown', None)
Ricky Liang4bff3e32014-02-20 18:46:11 +08001458 self.restore_active_run_state()
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001459
Dean Liao592e4d52013-01-10 20:06:39 +08001460 self.may_disable_cros_shortcut_keys()
1461
1462 def may_disable_cros_shortcut_keys(self):
1463 test_options = self.test_list.options
1464 if test_options.disable_cros_shortcut_keys:
1465 logging.info('Filter ChromeOS shortcut keys.')
1466 self.key_filter = KeyFilter(
1467 unmap_caps_lock=test_options.disable_caps_lock,
1468 caps_lock_keycode=test_options.caps_lock_keycode)
1469 self.key_filter.Start()
1470
Jon Salz0697cbf2012-07-04 15:14:04 +08001471 def run(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001472 """Runs Goofy."""
Jon Salz0697cbf2012-07-04 15:14:04 +08001473 # Process events forever.
1474 while self.run_once(True):
1475 pass
Jon Salz73e0fd02012-04-04 11:46:38 +08001476
Jon Salz0697cbf2012-07-04 15:14:04 +08001477 def run_once(self, block=False):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001478 """Runs all items pending in the event loop.
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001479
Jon Salz0697cbf2012-07-04 15:14:04 +08001480 Args:
1481 block: If true, block until at least one event is processed.
Jon Salz7c15e8b2012-06-19 17:10:37 +08001482
Jon Salz0697cbf2012-07-04 15:14:04 +08001483 Returns:
1484 True to keep going or False to shut down.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001485 """
Jon Salz0697cbf2012-07-04 15:14:04 +08001486 events = utils.DrainQueue(self.run_queue)
cychiang21886742012-07-05 15:16:32 +08001487 while not events:
Jon Salz0697cbf2012-07-04 15:14:04 +08001488 # Nothing on the run queue.
1489 self._run_queue_idle()
1490 if block:
1491 # Block for at least one event...
cychiang21886742012-07-05 15:16:32 +08001492 try:
1493 events.append(self.run_queue.get(timeout=RUN_QUEUE_TIMEOUT_SECS))
1494 except Queue.Empty:
1495 # Keep going (calling _run_queue_idle() again at the top of
1496 # the loop)
1497 continue
Jon Salz0697cbf2012-07-04 15:14:04 +08001498 # ...and grab anything else that showed up at the same
1499 # time.
1500 events.extend(utils.DrainQueue(self.run_queue))
cychiang21886742012-07-05 15:16:32 +08001501 else:
1502 break
Jon Salz51528e12012-07-02 18:54:45 +08001503
Jon Salz0697cbf2012-07-04 15:14:04 +08001504 for event in events:
1505 if not event:
1506 # Shutdown request.
1507 self.run_queue.task_done()
1508 return False
Jon Salz51528e12012-07-02 18:54:45 +08001509
Jon Salz0697cbf2012-07-04 15:14:04 +08001510 try:
1511 event()
Jon Salz85a39882012-07-05 16:45:04 +08001512 except: # pylint: disable=W0702
1513 logging.exception('Error in event loop')
Jon Salz0697cbf2012-07-04 15:14:04 +08001514 self.record_exception(traceback.format_exception_only(
1515 *sys.exc_info()[:2]))
1516 # But keep going
1517 finally:
1518 self.run_queue.task_done()
1519 return True
Jon Salz0405ab52012-03-16 15:26:52 +08001520
Jon Salz0e6532d2012-10-25 16:30:11 +08001521 def _should_sync_time(self, foreground=False):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001522 """Returns True if we should attempt syncing time with shopfloor.
Jon Salz0e6532d2012-10-25 16:30:11 +08001523
1524 Args:
1525 foreground: If True, synchronizes even if background syncing
1526 is disabled (e.g., in explicit sync requests from the
1527 SyncShopfloor test).
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001528 """
Jon Salz0e6532d2012-10-25 16:30:11 +08001529 return ((foreground or
1530 self.test_list.options.sync_time_period_secs) and
Jon Salz54882d02012-08-31 01:57:54 +08001531 self.time_sanitizer and
1532 (not self.time_synced) and
1533 (not factory.in_chroot()))
1534
Jon Salz0e6532d2012-10-25 16:30:11 +08001535 def sync_time_with_shopfloor_server(self, foreground=False):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001536 """Syncs time with shopfloor server, if not yet synced.
Jon Salz54882d02012-08-31 01:57:54 +08001537
Jon Salz0e6532d2012-10-25 16:30:11 +08001538 Args:
1539 foreground: If True, synchronizes even if background syncing
1540 is disabled (e.g., in explicit sync requests from the
1541 SyncShopfloor test).
1542
Jon Salz54882d02012-08-31 01:57:54 +08001543 Returns:
1544 False if no time sanitizer is available, or True if this sync (or a
1545 previous sync) succeeded.
1546
1547 Raises:
1548 Exception if unable to contact the shopfloor server.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001549 """
Jon Salz0e6532d2012-10-25 16:30:11 +08001550 if self._should_sync_time(foreground):
Jon Salz54882d02012-08-31 01:57:54 +08001551 self.time_sanitizer.SyncWithShopfloor()
1552 self.time_synced = True
1553 return self.time_synced
1554
Jon Salzb92c5112012-09-21 15:40:11 +08001555 def log_disk_space_stats(self):
Jon Salz18e0e022013-06-11 17:13:39 +08001556 if (utils.in_chroot() or
1557 not self.test_list.options.log_disk_space_period_secs):
Jon Salzb92c5112012-09-21 15:40:11 +08001558 return
1559
1560 now = time.time()
1561 if (self.last_log_disk_space_time and
1562 now - self.last_log_disk_space_time <
1563 self.test_list.options.log_disk_space_period_secs):
1564 return
1565 self.last_log_disk_space_time = now
1566
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001567 # Upload event if stateful partition usage is above threshold.
1568 # Stateful partition is mounted on /usr/local, while
1569 # encrypted stateful partition is mounted on /var.
1570 # If there are too much logs in the factory process,
1571 # these two partitions might get full.
Jon Salzb92c5112012-09-21 15:40:11 +08001572 try:
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001573 vfs_infos = disk_space.GetAllVFSInfo()
1574 stateful_info, encrypted_info = None, None
1575 for vfs_info in vfs_infos.values():
1576 if '/usr/local' in vfs_info.mount_points:
1577 stateful_info = vfs_info
1578 if '/var' in vfs_info.mount_points:
1579 encrypted_info = vfs_info
1580
1581 stateful = disk_space.GetPartitionUsage(stateful_info)
1582 encrypted = disk_space.GetPartitionUsage(encrypted_info)
1583
1584 above_threshold = (
1585 self.test_list.options.stateful_usage_threshold and
1586 max(stateful.bytes_used_pct,
1587 stateful.inodes_used_pct,
1588 encrypted.bytes_used_pct,
1589 encrypted.inodes_used_pct) >
1590 self.test_list.options.stateful_usage_threshold)
1591
1592 if above_threshold:
1593 self.event_log.Log('stateful_partition_usage',
1594 partitions={
1595 'stateful': {
1596 'bytes_used_pct': FloatDigit(stateful.bytes_used_pct, 2),
1597 'inodes_used_pct': FloatDigit(stateful.inodes_used_pct, 2)},
1598 'encrypted_stateful': {
1599 'bytes_used_pct': FloatDigit(encrypted.bytes_used_pct, 2),
1600 'inodes_used_pct': FloatDigit(encrypted.inodes_used_pct, 2)}
1601 })
1602 self.log_watcher.ScanEventLogs()
Cheng-Yi Chiang00798e72013-06-20 18:16:39 +08001603 if (not utils.in_chroot() and
1604 self.test_list.options.stateful_usage_above_threshold_action):
1605 Spawn(self.test_list.options.stateful_usage_above_threshold_action,
1606 call=True)
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001607
1608 message = disk_space.FormatSpaceUsedAll(vfs_infos)
Jon Salz3c493bb2013-02-07 17:24:58 +08001609 if message != self.last_log_disk_space_message:
Cheng-Yi Chiangd0406522013-04-01 15:40:18 +08001610 if above_threshold:
1611 logging.warning(message)
1612 else:
1613 logging.info(message)
Jon Salz3c493bb2013-02-07 17:24:58 +08001614 self.last_log_disk_space_message = message
Jon Salzb92c5112012-09-21 15:40:11 +08001615 except: # pylint: disable=W0702
1616 logging.exception('Unable to get disk space used')
1617
Justin Chuang83813982013-05-13 01:26:32 +08001618 def check_battery(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001619 """Checks the current battery status.
Justin Chuang83813982013-05-13 01:26:32 +08001620
1621 Logs current battery charging level and status to log. If the battery level
1622 is lower below warning_low_battery_pct, send warning event to shopfloor.
1623 If the battery level is lower below critical_low_battery_pct, flush disks.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001624 """
Justin Chuang83813982013-05-13 01:26:32 +08001625 if not self.test_list.options.check_battery_period_secs:
1626 return
1627
1628 now = time.time()
1629 if (self.last_check_battery_time and
1630 now - self.last_check_battery_time <
1631 self.test_list.options.check_battery_period_secs):
1632 return
1633 self.last_check_battery_time = now
1634
1635 message = ''
1636 log_level = logging.INFO
1637 try:
1638 power = system.GetBoard().power
1639 if not power.CheckBatteryPresent():
1640 message = 'Battery is not present'
1641 else:
1642 ac_present = power.CheckACPresent()
1643 charge_pct = power.GetChargePct(get_float=True)
1644 message = ('Current battery level %.1f%%, AC charger is %s' %
1645 (charge_pct, 'connected' if ac_present else 'disconnected'))
1646
1647 if charge_pct > self.test_list.options.critical_low_battery_pct:
1648 critical_low_battery = False
1649 else:
1650 critical_low_battery = True
1651 # Only sync disks when battery level is still above minimum
1652 # value. This can be used for offline analysis when shopfloor cannot
1653 # be connected.
1654 if charge_pct > MIN_BATTERY_LEVEL_FOR_DISK_SYNC:
1655 logging.warning('disk syncing for critical low battery situation')
1656 os.system('sync; sync; sync')
1657 else:
1658 logging.warning('disk syncing is cancelled '
1659 'because battery level is lower than %.1f',
1660 MIN_BATTERY_LEVEL_FOR_DISK_SYNC)
1661
1662 # Notify shopfloor server
1663 if (critical_low_battery or
1664 (not ac_present and
1665 charge_pct <= self.test_list.options.warning_low_battery_pct)):
1666 log_level = logging.WARNING
1667
1668 self.event_log.Log('low_battery',
1669 battery_level=charge_pct,
1670 charger_connected=ac_present,
1671 critical=critical_low_battery)
1672 self.log_watcher.KickWatchThread()
Cheng-Yi Chianga0f6eff2014-01-09 18:27:22 +08001673 if self.test_list.options.enable_sync_log:
1674 self.system_log_manager.KickToSync()
Justin Chuang83813982013-05-13 01:26:32 +08001675 except: # pylint: disable=W0702
1676 logging.exception('Unable to check battery or notify shopfloor')
1677 finally:
1678 if message != self.last_check_battery_message:
1679 logging.log(log_level, message)
1680 self.last_check_battery_message = message
1681
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001682 def check_core_dump(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001683 """Checks if there is any core dumped file.
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001684
1685 Removes unwanted core dump files immediately.
1686 Syncs those files matching watch list to server with a delay between
1687 each sync. After the files have been synced to server, deletes the files.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001688 """
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001689 core_dump_files = self.core_dump_manager.ScanFiles()
1690 if core_dump_files:
1691 now = time.time()
1692 if (self.last_kick_sync_time and now - self.last_kick_sync_time <
1693 self.test_list.options.kick_sync_min_interval_secs):
1694 return
1695 self.last_kick_sync_time = now
1696
1697 # Sends event to server
1698 self.event_log.Log('core_dumped', files=core_dump_files)
1699 self.log_watcher.KickWatchThread()
1700
1701 # Syncs files to server
Cheng-Yi Chianga0f6eff2014-01-09 18:27:22 +08001702 if self.test_list.options.enable_sync_log:
1703 self.system_log_manager.KickToSync(
Cheng-Yi Chiangd3516a32013-07-17 15:30:47 +08001704 core_dump_files, self.core_dump_manager.ClearFiles)
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001705
Cheng-Yi Chiang39d32ad2013-07-23 15:02:38 +08001706 def check_log_rotation(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001707 """Checks log rotation file presence/absence according to test_list option.
Cheng-Yi Chiang39d32ad2013-07-23 15:02:38 +08001708
1709 Touch /var/lib/cleanup_logs_paused if test_list.options.disable_log_rotation
1710 is True, delete it otherwise. This must be done in idle loop because
1711 autotest client will touch /var/lib/cleanup_logs_paused each time it runs
1712 an autotest.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001713 """
Cheng-Yi Chiang39d32ad2013-07-23 15:02:38 +08001714 if utils.in_chroot():
1715 return
1716 try:
1717 if self.test_list.options.disable_log_rotation:
1718 open(CLEANUP_LOGS_PAUSED, 'w').close()
1719 else:
1720 file_utils.TryUnlink(CLEANUP_LOGS_PAUSED)
1721 except: # pylint: disable=W0702
1722 # Oh well. Logs an error (but no trace)
1723 logging.info(
1724 'Unable to %s %s: %s',
1725 'touch' if self.test_list.options.disable_log_rotation else 'delete',
1726 CLEANUP_LOGS_PAUSED, utils.FormatExceptionOnly())
1727
Jon Salz8fa8e832012-07-13 19:04:09 +08001728 def sync_time_in_background(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001729 """Writes out current time and tries to sync with shopfloor server."""
Jon Salzb22d1172012-08-06 10:38:57 +08001730 if not self.time_sanitizer:
1731 return
1732
1733 # Write out the current time.
1734 self.time_sanitizer.SaveTime()
1735
Jon Salz54882d02012-08-31 01:57:54 +08001736 if not self._should_sync_time():
Jon Salz8fa8e832012-07-13 19:04:09 +08001737 return
1738
1739 now = time.time()
1740 if self.last_sync_time and (
1741 now - self.last_sync_time <
1742 self.test_list.options.sync_time_period_secs):
1743 # Not yet time for another check.
1744 return
1745 self.last_sync_time = now
1746
1747 def target():
1748 try:
Jon Salz54882d02012-08-31 01:57:54 +08001749 self.sync_time_with_shopfloor_server()
Jon Salz8fa8e832012-07-13 19:04:09 +08001750 except: # pylint: disable=W0702
1751 # Oh well. Log an error (but no trace)
1752 logging.info(
1753 'Unable to get time from shopfloor server: %s',
1754 utils.FormatExceptionOnly())
1755
1756 thread = threading.Thread(target=target)
1757 thread.daemon = True
1758 thread.start()
1759
Jon Salz0697cbf2012-07-04 15:14:04 +08001760 def _run_queue_idle(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001761 """Invoked when the run queue has no events.
Vic Yang4953fc12012-07-26 16:19:53 +08001762
1763 This method must not raise exception.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001764 """
Jon Salzb22d1172012-08-06 10:38:57 +08001765 now = time.time()
1766 if (self.last_idle and
1767 now < (self.last_idle + RUN_QUEUE_TIMEOUT_SECS - 1)):
1768 # Don't run more often than once every (RUN_QUEUE_TIMEOUT_SECS -
1769 # 1) seconds.
1770 return
1771
1772 self.last_idle = now
1773
Vic Yang311ddb82012-09-26 12:08:28 +08001774 self.check_exclusive()
cychiang21886742012-07-05 15:16:32 +08001775 self.check_for_updates()
Jon Salz8fa8e832012-07-13 19:04:09 +08001776 self.sync_time_in_background()
Jon Salzb92c5112012-09-21 15:40:11 +08001777 self.log_disk_space_stats()
Justin Chuang83813982013-05-13 01:26:32 +08001778 self.check_battery()
Cheng-Yi Chiangcdfa4182013-05-05 03:20:19 +08001779 self.check_core_dump()
Cheng-Yi Chiang39d32ad2013-07-23 15:02:38 +08001780 self.check_log_rotation()
Jon Salz57717ca2012-04-04 16:47:25 +08001781
Jon Salzd15bbcf2013-05-21 17:33:57 +08001782 def handle_event_logs(self, chunks):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001783 """Callback for event watcher.
Jon Salz258a40c2012-04-19 12:34:01 +08001784
Jon Salz0697cbf2012-07-04 15:14:04 +08001785 Attempts to upload the event logs to the shopfloor server.
Vic Yang93027612013-05-06 02:42:49 +08001786
1787 Args:
Jon Salzd15bbcf2013-05-21 17:33:57 +08001788 chunks: A list of Chunk objects.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001789 """
Vic Yang93027612013-05-06 02:42:49 +08001790 first_exception = None
1791 exception_count = 0
1792
Jon Salzd15bbcf2013-05-21 17:33:57 +08001793 for chunk in chunks:
Vic Yang93027612013-05-06 02:42:49 +08001794 try:
Jon Salzcddb6402013-05-23 12:56:42 +08001795 description = 'event logs (%s)' % str(chunk)
Vic Yang93027612013-05-06 02:42:49 +08001796 start_time = time.time()
1797 shopfloor_client = shopfloor.get_instance(
1798 detect=True,
1799 timeout=self.test_list.options.shopfloor_timeout_secs)
Jon Salzd15bbcf2013-05-21 17:33:57 +08001800 shopfloor_client.UploadEvent(chunk.log_name + "." +
1801 event_log.GetReimageId(),
1802 Binary(chunk.chunk))
Vic Yang93027612013-05-06 02:42:49 +08001803 logging.info(
1804 'Successfully synced %s in %.03f s',
1805 description, time.time() - start_time)
1806 except: # pylint: disable=W0702
Jon Salzd15bbcf2013-05-21 17:33:57 +08001807 first_exception = (first_exception or (chunk.log_name + ': ' +
Vic Yang93027612013-05-06 02:42:49 +08001808 utils.FormatExceptionOnly()))
1809 exception_count += 1
1810
1811 if exception_count:
1812 if exception_count == 1:
1813 msg = 'Log upload failed: %s' % first_exception
1814 else:
1815 msg = '%d log upload failed; first is: %s' % (
1816 exception_count, first_exception)
1817 raise Exception(msg)
1818
Jon Salz57717ca2012-04-04 16:47:25 +08001819
Jon Salz0697cbf2012-07-04 15:14:04 +08001820 def run_tests_with_status(self, statuses_to_run, starting_at=None,
1821 root=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001822 """Runs all top-level tests with a particular status.
Jon Salz0405ab52012-03-16 15:26:52 +08001823
Jon Salz0697cbf2012-07-04 15:14:04 +08001824 All active tests, plus any tests to re-run, are reset.
Jon Salz57717ca2012-04-04 16:47:25 +08001825
Jon Salz0697cbf2012-07-04 15:14:04 +08001826 Args:
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001827 statuses_to_run: The particular status that caller wants to run.
Jon Salz0697cbf2012-07-04 15:14:04 +08001828 starting_at: If provided, only auto-runs tests beginning with
1829 this test.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001830 root: The root of tests to run. If not provided, it will be
1831 the root of all tests.
1832 """
Jon Salz0697cbf2012-07-04 15:14:04 +08001833 root = root or self.test_list
Jon Salz57717ca2012-04-04 16:47:25 +08001834
Jon Salz0697cbf2012-07-04 15:14:04 +08001835 if starting_at:
1836 # Make sure they passed a test, not a string.
1837 assert isinstance(starting_at, factory.FactoryTest)
Jon Salz0405ab52012-03-16 15:26:52 +08001838
Jon Salz0697cbf2012-07-04 15:14:04 +08001839 tests_to_reset = []
1840 tests_to_run = []
Jon Salz0405ab52012-03-16 15:26:52 +08001841
Jon Salz0697cbf2012-07-04 15:14:04 +08001842 found_starting_at = False
Jon Salz0405ab52012-03-16 15:26:52 +08001843
Jon Salz0697cbf2012-07-04 15:14:04 +08001844 for test in root.get_top_level_tests():
1845 if starting_at:
1846 if test == starting_at:
1847 # We've found starting_at; do auto-run on all
1848 # subsequent tests.
1849 found_starting_at = True
1850 if not found_starting_at:
1851 # Don't start this guy yet
1852 continue
Jon Salz0405ab52012-03-16 15:26:52 +08001853
Jon Salz0697cbf2012-07-04 15:14:04 +08001854 status = test.get_state().status
1855 if status == TestState.ACTIVE or status in statuses_to_run:
1856 # Reset the test (later; we will need to abort
1857 # all active tests first).
1858 tests_to_reset.append(test)
1859 if status in statuses_to_run:
1860 tests_to_run.append(test)
Jon Salz0405ab52012-03-16 15:26:52 +08001861
Jon Salz6dc031d2013-06-19 13:06:23 +08001862 self.abort_active_tests('Operator requested run/re-run of certain tests')
Jon Salz258a40c2012-04-19 12:34:01 +08001863
Jon Salz0697cbf2012-07-04 15:14:04 +08001864 # Reset all statuses of the tests to run (in case any tests were active;
1865 # we want them to be run again).
1866 for test_to_reset in tests_to_reset:
1867 for test in test_to_reset.walk():
1868 test.update_state(status=TestState.UNTESTED)
Jon Salz57717ca2012-04-04 16:47:25 +08001869
Jon Salz0697cbf2012-07-04 15:14:04 +08001870 self.run_tests(tests_to_run, untested_only=True)
Jon Salz0405ab52012-03-16 15:26:52 +08001871
Jon Salz0697cbf2012-07-04 15:14:04 +08001872 def restart_tests(self, root=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001873 """Restarts all tests."""
Jon Salz0697cbf2012-07-04 15:14:04 +08001874 root = root or self.test_list
Jon Salz0405ab52012-03-16 15:26:52 +08001875
Jon Salz6dc031d2013-06-19 13:06:23 +08001876 self.abort_active_tests('Operator requested restart of certain tests')
Jon Salz0697cbf2012-07-04 15:14:04 +08001877 for test in root.walk():
Ricky Liang48e47f92014-02-26 19:31:51 +08001878 test.update_state(status=TestState.UNTESTED, shutdown_count=0)
Jon Salz0697cbf2012-07-04 15:14:04 +08001879 self.run_tests(root)
Hung-Te Lin96632362012-03-20 21:14:18 +08001880
Jon Salz0697cbf2012-07-04 15:14:04 +08001881 def auto_run(self, starting_at=None, root=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001882 """"Auto-runs" tests that have not been run yet.
Hung-Te Lin96632362012-03-20 21:14:18 +08001883
Jon Salz0697cbf2012-07-04 15:14:04 +08001884 Args:
1885 starting_at: If provide, only auto-runs tests beginning with
1886 this test.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001887 root: If provided, the root of tests to run. If not provided, the root
1888 will be test_list (root of all tests).
1889 """
Jon Salz0697cbf2012-07-04 15:14:04 +08001890 root = root or self.test_list
1891 self.run_tests_with_status([TestState.UNTESTED, TestState.ACTIVE],
1892 starting_at=starting_at,
1893 root=root)
Jon Salz968e90b2012-03-18 16:12:43 +08001894
Jon Salz0697cbf2012-07-04 15:14:04 +08001895 def re_run_failed(self, root=None):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001896 """Re-runs failed tests."""
Jon Salz0697cbf2012-07-04 15:14:04 +08001897 root = root or self.test_list
1898 self.run_tests_with_status([TestState.FAILED], root=root)
Jon Salz57717ca2012-04-04 16:47:25 +08001899
Jon Salz0697cbf2012-07-04 15:14:04 +08001900 def show_review_information(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001901 """Event handler for showing review information screen.
Jon Salz57717ca2012-04-04 16:47:25 +08001902
Jon Salz0697cbf2012-07-04 15:14:04 +08001903 The information screene is rendered by main UI program (ui.py), so in
1904 goofy we only need to kill all active tests, set them as untested, and
1905 clear remaining tests.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001906 """
Jon Salz0697cbf2012-07-04 15:14:04 +08001907 self.kill_active_tests(False)
Jon Salza6711d72012-07-18 14:33:03 +08001908 self.cancel_pending_tests()
Jon Salz57717ca2012-04-04 16:47:25 +08001909
Jon Salz0697cbf2012-07-04 15:14:04 +08001910 def handle_switch_test(self, event):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001911 """Switches to a particular test.
Jon Salz0405ab52012-03-16 15:26:52 +08001912
Ricky Liang6fe218c2013-12-27 15:17:17 +08001913 Args:
1914 event: The SWITCH_TEST event.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001915 """
Jon Salz0697cbf2012-07-04 15:14:04 +08001916 test = self.test_list.lookup_path(event.path)
1917 if not test:
1918 logging.error('Unknown test %r', event.key)
1919 return
Jon Salz73e0fd02012-04-04 11:46:38 +08001920
Jon Salz0697cbf2012-07-04 15:14:04 +08001921 invoc = self.invocations.get(test)
1922 if invoc and test.backgroundable:
1923 # Already running: just bring to the front if it
1924 # has a UI.
1925 logging.info('Setting visible test to %s', test.path)
Jon Salz36fbbb52012-07-05 13:45:06 +08001926 self.set_visible_test(test)
Jon Salz0697cbf2012-07-04 15:14:04 +08001927 return
Jon Salz73e0fd02012-04-04 11:46:38 +08001928
Jon Salz6dc031d2013-06-19 13:06:23 +08001929 self.abort_active_tests('Operator requested abort (switch_test)')
Jon Salz0697cbf2012-07-04 15:14:04 +08001930 for t in test.walk():
1931 t.update_state(status=TestState.UNTESTED)
Jon Salz73e0fd02012-04-04 11:46:38 +08001932
Jon Salz0697cbf2012-07-04 15:14:04 +08001933 if self.test_list.options.auto_run_on_keypress:
1934 self.auto_run(starting_at=test)
1935 else:
1936 self.run_tests(test)
Jon Salz73e0fd02012-04-04 11:46:38 +08001937
Jon Salz0697cbf2012-07-04 15:14:04 +08001938 def wait(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001939 """Waits for all pending invocations.
Jon Salz0697cbf2012-07-04 15:14:04 +08001940
1941 Useful for testing.
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001942 """
Jon Salz1acc8742012-07-17 17:45:55 +08001943 while self.invocations:
1944 for k, v in self.invocations.iteritems():
1945 logging.info('Waiting for %s to complete...', k)
1946 v.thread.join()
1947 self.reap_completed_tests()
Jon Salz0697cbf2012-07-04 15:14:04 +08001948
1949 def check_exceptions(self):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001950 """Raises an error if any exceptions have occurred in
1951 invocation threads.
1952 """
Jon Salz0697cbf2012-07-04 15:14:04 +08001953 if self.exceptions:
1954 raise RuntimeError('Exception in invocation thread: %r' %
1955 self.exceptions)
1956
1957 def record_exception(self, msg):
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001958 """Records an exception in an invocation thread.
Jon Salz0697cbf2012-07-04 15:14:04 +08001959
1960 An exception with the given message will be rethrown when
Cheng-Yi Chiang1e3e2692013-12-24 18:02:36 +08001961 Goofy is destroyed.
1962 """
Jon Salz0697cbf2012-07-04 15:14:04 +08001963 self.exceptions.append(msg)
Jon Salz73e0fd02012-04-04 11:46:38 +08001964
Hung-Te Linf2f78f72012-02-08 19:27:11 +08001965
1966if __name__ == '__main__':
Jon Salz77c151e2012-08-28 07:20:37 +08001967 goofy = Goofy()
1968 try:
1969 goofy.main()
Jon Salz0f996602012-10-03 15:26:48 +08001970 except SystemExit:
1971 # Propagate SystemExit without logging.
1972 raise
Jon Salz31373eb2012-09-21 16:19:49 +08001973 except:
Jon Salz0f996602012-10-03 15:26:48 +08001974 # Log the error before trying to shut down (unless it's a graceful
1975 # exit).
Jon Salz31373eb2012-09-21 16:19:49 +08001976 logging.exception('Error in main loop')
1977 raise
Jon Salz77c151e2012-08-28 07:20:37 +08001978 finally:
1979 goofy.destroy()