blob: 77990b9c5307cfa0fdacd2c233d457a5bd850464 [file] [log] [blame]
barfab@chromium.orgb6d29932012-04-11 09:46:43 +02001# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
Ken Mixter20d9e472010-08-12 10:58:46 -07002# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
Mike Frysinger0fa79ab2014-05-24 21:16:04 -04005import contextlib, fcntl, logging, os, re, shutil
barfab@chromium.orgb6d29932012-04-11 09:46:43 +02006
Bertrand SIMONNET9347d362014-06-30 11:17:59 -07007import common, constants, cros_logging
Eric Lie7c4cab2011-01-05 14:39:19 -08008from autotest_lib.client.bin import test, utils
9from autotest_lib.client.common_lib import error
Ken Mixter20d9e472010-08-12 10:58:46 -070010
11
12class CrashTest(test.test):
Simon Glassa47f0d72011-03-15 11:45:32 -070013 """
14 This class deals with running crash tests, which are tests which crash a
15 user-space program (or the whole machine) and generate a core dump. We
16 want to check that the correct crash dump is available and can be
17 retrieved.
18
19 Chromium OS has a crash sender which checks for new crash data and sends
20 it to a server. This crash data is used to track software quality and find
21 bugs. The system crash sender normally is always running, but can be paused
22 by creating _PAUSE_FILE. When crash sender sees this, it pauses operation.
23
24 The pid of the system crash sender is stored in _CRASH_SENDER_RUN_PATH so
25 we can use this to kill the system crash sender for when we want to run
26 our own.
27
28 For testing purposes we sometimes want to run the crash sender manually.
29 In this case we can set 'OVERRIDE_PAUSE_SENDING=1' in the environment and
30 run the crash sender manually (as a child process).
31
32 Also for testing we sometimes want to mock out the crash sender, and just
33 have it pretend to succeed or fail. The _MOCK_CRASH_SENDING file is used
34 for this. If it doesn't exist, then the crash sender runs normally. If
35 it exists but is empty, the crash sender will succeed (but actually do
36 nothing). If the file contains something, then the crash sender will fail.
37
38 If the user consents to sending crash tests, then the _CONSENT_FILE will
39 exist in the home directory. This test needs to create this file for the
40 crash sending to work.
41
42 Crash reports are rate limited to a certain number of reports each 24
43 hours. If the maximum number has already been sent then reports are held
44 until later. This is administered by a directory _CRASH_SENDER_RATE_DIR
45 which contains one temporary file for each time a report is sent.
46
47 The class provides the ability to push a consent file. This disables
48 consent for this test but allows it to be popped back at later. This
49 makes nested tests easier. If _automatic_consent_saving is True (the
50 default) then consent will be pushed at the start and popped at the end.
51
52 Interesting variables:
53 _log_reader: the log reader used for reading log files
54 _leave_crash_sending: True to enable crash sending on exit from the
55 test, False to disable it. (Default True).
56 _automatic_consent_saving: True to push the consent at the start of
57 the test and pop it afterwards. (Default True).
58
59 Useful places to look for more information are:
60
61 chromeos/src/platform/crash-reporter/crash_sender
62 - sender script which crash crash reporter to create reports, then
63
64 chromeos/src/platform/crash-reporter/
65 - crash reporter program
66 """
67
Ken Mixter20d9e472010-08-12 10:58:46 -070068
69 _CONSENT_FILE = '/home/chronos/Consent To Send Stats'
Ken Mixterddcd92d2010-11-01 19:07:08 -070070 _CORE_PATTERN = '/proc/sys/kernel/core_pattern'
Ken Mixter20d9e472010-08-12 10:58:46 -070071 _CRASH_REPORTER_PATH = '/sbin/crash_reporter'
72 _CRASH_SENDER_PATH = '/sbin/crash_sender'
73 _CRASH_SENDER_RATE_DIR = '/var/lib/crash_sender'
74 _CRASH_SENDER_RUN_PATH = '/var/run/crash_sender.pid'
Mike Frysinger0fa79ab2014-05-24 21:16:04 -040075 _CRASH_SENDER_LOCK_PATH = '/var/lock/crash_sender'
Thieu Lec16253b2011-03-03 11:13:54 -080076 _CRASH_TEST_IN_PROGRESS = '/tmp/crash-test-in-progress'
Ken Mixter20d9e472010-08-12 10:58:46 -070077 _MOCK_CRASH_SENDING = '/tmp/mock-crash-sending'
Ken Mixter38dfe852010-08-18 15:24:00 -070078 _PAUSE_FILE = '/var/lib/crash_sender_paused'
Ken Mixter20d9e472010-08-12 10:58:46 -070079 _SYSTEM_CRASH_DIR = '/var/spool/crash'
Mike Frysingerded8de72013-05-29 20:45:48 -040080 _FALLBACK_USER_CRASH_DIR = '/home/chronos/crash'
81 _USER_CRASH_DIRS = '/home/chronos/u-*/crash'
Ken Mixter20d9e472010-08-12 10:58:46 -070082
Mike Frysingerbb54bc82014-05-14 14:04:56 -040083 # Use the same file format as crash does normally:
84 # <basename>.#.#.#.meta
85 _FAKE_TEST_BASENAME = 'fake.1.2.3'
86
Ken Mixter4f619652010-10-18 12:11:18 -070087 def _set_system_sending(self, is_enabled):
88 """Sets whether or not the system crash_sender is allowed to run.
89
Simon Glassa47f0d72011-03-15 11:45:32 -070090 This is done by creating or removing _PAUSE_FILE.
91
Ken Mixter4f619652010-10-18 12:11:18 -070092 crash_sender may still be allowed to run if _set_child_sending is
Simon Glassa47f0d72011-03-15 11:45:32 -070093 called with True and it is run as a child process.
94
Bertrand SIMONNET72691dd2014-07-07 14:49:45 -070095 @param is_enabled: True to enable crash_sender, False to disable it.
Simon Glassa47f0d72011-03-15 11:45:32 -070096 """
Ken Mixter20d9e472010-08-12 10:58:46 -070097 if is_enabled:
98 if os.path.exists(self._PAUSE_FILE):
99 os.remove(self._PAUSE_FILE)
100 else:
101 utils.system('touch ' + self._PAUSE_FILE)
102
103
Ken Mixter4f619652010-10-18 12:11:18 -0700104 def _set_child_sending(self, is_enabled):
Simon Glassa47f0d72011-03-15 11:45:32 -0700105 """Overrides crash sending enabling for child processes.
106
107 When the system crash sender is disabled this test can manually run
108 the crash sender as a child process. Normally this would do nothing,
109 but this function sets up crash_sender to ignore its disabled status
110 and do its job.
111
Bertrand SIMONNET72691dd2014-07-07 14:49:45 -0700112 @param is_enabled: True to enable crash sending for child processes.
Simon Glassa47f0d72011-03-15 11:45:32 -0700113 """
Ken Mixter4f619652010-10-18 12:11:18 -0700114 if is_enabled:
115 os.environ['OVERRIDE_PAUSE_SENDING'] = "1"
116 else:
117 del os.environ['OVERRIDE_PAUSE_SENDING']
118
119
Michael Krebs6cffa3d2012-09-06 20:09:11 -0700120 def _set_force_official(self, is_enabled):
121 """Sets whether or not reports will upload for unofficial versions.
122
123 Normally, crash reports are only uploaded for official build
124 versions. If the override is set, however, they will also be
125 uploaded for unofficial versions.
126
Bertrand SIMONNET72691dd2014-07-07 14:49:45 -0700127 @param is_enabled: True to enable uploading for unofficial versions.
Michael Krebs6cffa3d2012-09-06 20:09:11 -0700128 """
129 if is_enabled:
130 os.environ['FORCE_OFFICIAL'] = "1"
131 elif os.environ.get('FORCE_OFFICIAL'):
132 del os.environ['FORCE_OFFICIAL']
133
134
Michael Krebsfb875d02012-09-13 16:49:50 -0700135 def _set_mock_developer_mode(self, is_enabled):
136 """Sets whether or not we should pretend we booted in developer mode.
137
Bertrand SIMONNET72691dd2014-07-07 14:49:45 -0700138 @param is_enabled: True to pretend we are in developer mode.
Michael Krebsfb875d02012-09-13 16:49:50 -0700139 """
140 if is_enabled:
141 os.environ['MOCK_DEVELOPER_MODE'] = "1"
142 elif os.environ.get('MOCK_DEVELOPER_MODE'):
143 del os.environ['MOCK_DEVELOPER_MODE']
144
145
Ken Mixter20d9e472010-08-12 10:58:46 -0700146 def _reset_rate_limiting(self):
Simon Glassa47f0d72011-03-15 11:45:32 -0700147 """Reset the count of crash reports sent today.
148
149 This clears the contents of the rate limiting directory which has
150 the effect of reseting our count of crash reports sent.
151 """
Ken Mixter20d9e472010-08-12 10:58:46 -0700152 utils.system('rm -rf ' + self._CRASH_SENDER_RATE_DIR)
153
154
155 def _clear_spooled_crashes(self):
Simon Glassa47f0d72011-03-15 11:45:32 -0700156 """Clears system and user crash directories.
157
158 This will remove all crash reports which are waiting to be sent.
159 """
Ken Mixter20d9e472010-08-12 10:58:46 -0700160 utils.system('rm -rf ' + self._SYSTEM_CRASH_DIR)
Mike Frysingerded8de72013-05-29 20:45:48 -0400161 utils.system('rm -rf %s %s' % (self._USER_CRASH_DIRS,
162 self._FALLBACK_USER_CRASH_DIR))
Ken Mixter20d9e472010-08-12 10:58:46 -0700163
164
165 def _kill_running_sender(self):
Simon Glassa47f0d72011-03-15 11:45:32 -0700166 """Kill the the crash_sender process if running.
167
168 We use the PID file to find the process ID, then kill it with signal 9.
169 """
Ken Mixter20d9e472010-08-12 10:58:46 -0700170 if not os.path.exists(self._CRASH_SENDER_RUN_PATH):
171 return
172 running_pid = int(utils.read_file(self._CRASH_SENDER_RUN_PATH))
Bertrand SIMONNET72691dd2014-07-07 14:49:45 -0700173 logging.warning('Detected running crash sender (%d), killing',
Ken Mixter20d9e472010-08-12 10:58:46 -0700174 running_pid)
175 utils.system('kill -9 %d' % running_pid)
176 os.remove(self._CRASH_SENDER_RUN_PATH)
177
178
179 def _set_sending_mock(self, mock_enabled, send_success=True):
Simon Glassa47f0d72011-03-15 11:45:32 -0700180 """Enables / disables mocking of the sending process.
181
182 This uses the _MOCK_CRASH_SENDING file to achieve its aims. See notes
183 at the top.
184
Bertrand SIMONNET72691dd2014-07-07 14:49:45 -0700185 @param mock_enabled: If True, mocking is enabled, else it is disabled.
186 @param send_success: If mock_enabled this is True for the mocking to
Simon Glassa47f0d72011-03-15 11:45:32 -0700187 indicate success, False to indicate failure.
188 """
Ken Mixter20d9e472010-08-12 10:58:46 -0700189 if mock_enabled:
190 if send_success:
191 data = ''
192 else:
193 data = '1'
194 logging.info('Setting sending mock')
195 utils.open_write_close(self._MOCK_CRASH_SENDING, data)
196 else:
197 utils.system('rm -f ' + self._MOCK_CRASH_SENDING)
198
199
200 def _set_consent(self, has_consent):
Simon Glassa47f0d72011-03-15 11:45:32 -0700201 """Sets whether or not we have consent to send crash reports.
202
203 This creates or deletes the _CONSENT_FILE to control whether
204 crash_sender will consider that it has consent to send crash reports.
Julian Pastarmovd56badb2011-07-15 20:24:45 +0200205 It also copies a policy blob with the proper policy setting.
Simon Glassa47f0d72011-03-15 11:45:32 -0700206
Bertrand SIMONNET72691dd2014-07-07 14:49:45 -0700207 @param has_consent: True to indicate consent, False otherwise
Simon Glassa47f0d72011-03-15 11:45:32 -0700208 """
Ken Mixter20d9e472010-08-12 10:58:46 -0700209 if has_consent:
Bertrand SIMONNET9347d362014-06-30 11:17:59 -0700210 if os.path.isdir(constants.WHITELIST_DIR):
211 # Create policy file that enables metrics/consent.
212 shutil.copy('/usr/local/autotest/cros/mock_metrics_on.policy',
213 constants.SIGNED_POLICY_FILE)
214 shutil.copy('/usr/local/autotest/cros/mock_metrics_owner.key',
215 constants.OWNER_KEY_FILE)
Michael Krebsb4b6f6b2011-08-03 13:52:19 -0700216 # Create deprecated consent file. This is created *after* the
217 # policy file in order to avoid a race condition where chrome
218 # might remove the consent file if the policy's not set yet.
Michael Krebse9028fc2011-08-19 15:00:00 -0700219 # We create it as a temp file first in order to make the creation
220 # of the consent file, owned by chronos, atomic.
Michael Krebsb4b6f6b2011-08-03 13:52:19 -0700221 # See crosbug.com/18413.
Michael Krebse9028fc2011-08-19 15:00:00 -0700222 temp_file = self._CONSENT_FILE + '.tmp';
223 utils.open_write_close(temp_file, 'test-consent')
224 utils.system('chown chronos:chronos "%s"' % (temp_file))
225 shutil.move(temp_file, self._CONSENT_FILE)
Ken Mixter20d9e472010-08-12 10:58:46 -0700226 logging.info('Created ' + self._CONSENT_FILE)
227 else:
Bertrand SIMONNET9347d362014-06-30 11:17:59 -0700228 if os.path.isdir(constants.WHITELIST_DIR):
229 # Create policy file that disables metrics/consent.
230 shutil.copy('/usr/local/autotest/cros/mock_metrics_off.policy',
231 constants.SIGNED_POLICY_FILE)
232 shutil.copy('/usr/local/autotest/cros/mock_metrics_owner.key',
233 constants.OWNER_KEY_FILE)
Michael Krebsb4b6f6b2011-08-03 13:52:19 -0700234 # Remove deprecated consent file.
235 utils.system('rm -f "%s"' % (self._CONSENT_FILE))
Ken Mixter20d9e472010-08-12 10:58:46 -0700236
237
Thieu Lec16253b2011-03-03 11:13:54 -0800238 def _set_crash_test_in_progress(self, in_progress):
239 if in_progress:
240 utils.open_write_close(self._CRASH_TEST_IN_PROGRESS, 'in-progress')
241 logging.info('Created ' + self._CRASH_TEST_IN_PROGRESS)
242 else:
243 utils.system('rm -f "%s"' % (self._CRASH_TEST_IN_PROGRESS))
244
245
Ken Mixter20d9e472010-08-12 10:58:46 -0700246 def _get_pushed_consent_file_path(self):
Simon Glassa47f0d72011-03-15 11:45:32 -0700247 """Returns filename of the pushed consent file."""
Ken Mixter20d9e472010-08-12 10:58:46 -0700248 return os.path.join(self.bindir, 'pushed_consent')
249
250
Julian Pastarmovd56badb2011-07-15 20:24:45 +0200251 def _get_pushed_policy_file_path(self):
252 """Returns filename of the pushed policy file."""
253 return os.path.join(self.bindir, 'pushed_policy')
254
255
256 def _get_pushed_owner_key_file_path(self):
257 """Returns filename of the pushed owner.key file."""
258 return os.path.join(self.bindir, 'pushed_owner_key')
259
260
Ken Mixter20d9e472010-08-12 10:58:46 -0700261 def _push_consent(self):
Simon Glassa47f0d72011-03-15 11:45:32 -0700262 """Push the consent file, thus disabling consent.
263
Julian Pastarmovd56badb2011-07-15 20:24:45 +0200264 The consent files can be created in the new test if required. Call
Simon Glassa47f0d72011-03-15 11:45:32 -0700265 _pop_consent() to restore the original state.
266 """
Ken Mixter20d9e472010-08-12 10:58:46 -0700267 if os.path.exists(self._CONSENT_FILE):
Dale Curtis497c2cb2010-11-16 13:44:33 -0800268 shutil.move(self._CONSENT_FILE,
269 self._get_pushed_consent_file_path())
Bertrand SIMONNET9347d362014-06-30 11:17:59 -0700270 if os.path.exists(constants.SIGNED_POLICY_FILE):
271 shutil.move(constants.SIGNED_POLICY_FILE,
Julian Pastarmovd56badb2011-07-15 20:24:45 +0200272 self._get_pushed_policy_file_path())
Bertrand SIMONNET9347d362014-06-30 11:17:59 -0700273 if os.path.exists(constants.OWNER_KEY_FILE):
274 shutil.move(constants.OWNER_KEY_FILE,
Julian Pastarmovd56badb2011-07-15 20:24:45 +0200275 self._get_pushed_owner_key_file_path())
Ken Mixter20d9e472010-08-12 10:58:46 -0700276
277
278 def _pop_consent(self):
Julian Pastarmovd56badb2011-07-15 20:24:45 +0200279 """Pop the consent files, enabling/disabling consent as it was before
Simon Glassa47f0d72011-03-15 11:45:32 -0700280 we pushed the consent."""
Ken Mixter20d9e472010-08-12 10:58:46 -0700281 if os.path.exists(self._get_pushed_consent_file_path()):
Dale Curtis497c2cb2010-11-16 13:44:33 -0800282 shutil.move(self._get_pushed_consent_file_path(),
283 self._CONSENT_FILE)
Julian Pastarmovd56badb2011-07-15 20:24:45 +0200284 else:
285 utils.system('rm -f "%s"' % self._CONSENT_FILE)
286 if os.path.exists(self._get_pushed_policy_file_path()):
287 shutil.move(self._get_pushed_policy_file_path(),
Bertrand SIMONNET9347d362014-06-30 11:17:59 -0700288 constants.SIGNED_POLICY_FILE)
Julian Pastarmovd56badb2011-07-15 20:24:45 +0200289 else:
Bertrand SIMONNET9347d362014-06-30 11:17:59 -0700290 utils.system('rm -f "%s"' % constants.SIGNED_POLICY_FILE)
Julian Pastarmovd56badb2011-07-15 20:24:45 +0200291 if os.path.exists(self._get_pushed_owner_key_file_path()):
292 shutil.move(self._get_pushed_owner_key_file_path(),
Bertrand SIMONNET9347d362014-06-30 11:17:59 -0700293 constants.OWNER_KEY_FILE)
Julian Pastarmovd56badb2011-07-15 20:24:45 +0200294 else:
Bertrand SIMONNET9347d362014-06-30 11:17:59 -0700295 utils.system('rm -f "%s"' % constants.OWNER_KEY_FILE)
Ken Mixter20d9e472010-08-12 10:58:46 -0700296
297
298 def _get_crash_dir(self, username):
Simon Glassa47f0d72011-03-15 11:45:32 -0700299 """Returns full path to the crash directory for a given username
300
Mike Frysingerded8de72013-05-29 20:45:48 -0400301 This only really works (currently) when no one is logged in. That
302 is OK (currently) as the only test that uses this runs when no one
303 is actually logged in.
304
Bertrand SIMONNET72691dd2014-07-07 14:49:45 -0700305 @param username: username to use:
Simon Glassa47f0d72011-03-15 11:45:32 -0700306 'chronos': Returns user crash directory.
307 'root': Returns system crash directory.
308 """
Ken Mixter20d9e472010-08-12 10:58:46 -0700309 if username == 'chronos':
Mike Frysingerded8de72013-05-29 20:45:48 -0400310 return self._FALLBACK_USER_CRASH_DIR
Ken Mixter20d9e472010-08-12 10:58:46 -0700311 else:
312 return self._SYSTEM_CRASH_DIR
313
314
315 def _initialize_crash_reporter(self):
Simon Glassa47f0d72011-03-15 11:45:32 -0700316 """Start up the crash reporter."""
Ken Mixter20d9e472010-08-12 10:58:46 -0700317 utils.system('%s --init --nounclean_check' % self._CRASH_REPORTER_PATH)
Ken Mixterddcd92d2010-11-01 19:07:08 -0700318 # Completely disable crash_reporter from generating crash dumps
319 # while any tests are running, otherwise a crashy system can make
320 # these tests flaky.
321 self.enable_crash_filtering('none')
Ken Mixter20d9e472010-08-12 10:58:46 -0700322
323
Mike Frysingerbb54bc82014-05-14 14:04:56 -0400324 def get_crash_dir_name(self, name):
325 """Return the full path for |name| inside the system crash directory."""
326 return os.path.join(self._SYSTEM_CRASH_DIR, name)
327
328
Ken Mixter67ff5622010-09-30 15:32:17 -0700329 def write_crash_dir_entry(self, name, contents):
Simon Glassa47f0d72011-03-15 11:45:32 -0700330 """Writes an empty file to the system crash directory.
331
332 This writes a file to _SYSTEM_CRASH_DIR with the given name. This is
333 used to insert new crash dump files for testing purposes.
334
Bertrand SIMONNET72691dd2014-07-07 14:49:45 -0700335 @param name: Name of file to write.
336 @param contents: String to write to the file.
Simon Glassa47f0d72011-03-15 11:45:32 -0700337 """
Mike Frysingerbb54bc82014-05-14 14:04:56 -0400338 entry = self.get_crash_dir_name(name)
Ken Mixter20d9e472010-08-12 10:58:46 -0700339 if not os.path.exists(self._SYSTEM_CRASH_DIR):
340 os.makedirs(self._SYSTEM_CRASH_DIR)
Ken Mixter67ff5622010-09-30 15:32:17 -0700341 utils.open_write_close(entry, contents)
Ken Mixter20d9e472010-08-12 10:58:46 -0700342 return entry
343
344
Ken Mixterdee4e292010-12-14 17:45:21 -0800345 def write_fake_meta(self, name, exec_name, payload, log=None,
346 complete=True):
Simon Glassa47f0d72011-03-15 11:45:32 -0700347 """Writes a fake meta entry to the system crash directory.
348
Bertrand SIMONNET72691dd2014-07-07 14:49:45 -0700349 @param name: Name of file to write.
350 @param exec_name: Value for exec_name item.
351 @param payload: Value for payload item.
352 @param log: Value for log item.
353 @param complete: True to close off the record, otherwise leave it
Simon Glassa47f0d72011-03-15 11:45:32 -0700354 incomplete.
355 """
Ken Mixter1a894e02010-10-28 15:42:52 -0700356 last_line = ''
357 if complete:
358 last_line = 'done=1\n'
Ken Mixterdee4e292010-12-14 17:45:21 -0800359 contents = ('exec_name=%s\n'
360 'ver=my_ver\n'
361 'payload=%s\n'
362 '%s' % (exec_name, payload,
363 last_line))
364 if log:
365 contents = ('log=%s\n' % log) + contents
366 return self.write_crash_dir_entry(name, contents)
Ken Mixter67ff5622010-09-30 15:32:17 -0700367
368
Ken Mixter20d9e472010-08-12 10:58:46 -0700369 def _prepare_sender_one_crash(self,
370 send_success,
371 reports_enabled,
Ken Mixter38dfe852010-08-18 15:24:00 -0700372 report):
Simon Glassa47f0d72011-03-15 11:45:32 -0700373 """Create metadata for a fake crash report.
374
375 This enabled mocking of the crash sender, then creates a fake
376 crash report for testing purposes.
377
Bertrand SIMONNET72691dd2014-07-07 14:49:45 -0700378 @param send_success: True to make the crash_sender success, False to
379 make it fail.
380 @param reports_enabled: True to enable consent to that reports will be
Simon Glassa47f0d72011-03-15 11:45:32 -0700381 sent.
Bertrand SIMONNET72691dd2014-07-07 14:49:45 -0700382 @param report: Report to use for crash, if None we create one.
Simon Glassa47f0d72011-03-15 11:45:32 -0700383 """
Ken Mixter20d9e472010-08-12 10:58:46 -0700384 self._set_sending_mock(mock_enabled=True, send_success=send_success)
385 self._set_consent(reports_enabled)
Ken Mixter38dfe852010-08-18 15:24:00 -0700386 if report is None:
Mike Frysingerbb54bc82014-05-14 14:04:56 -0400387 # Use the same file format as crash does normally:
388 # <basename>.#.#.#.meta
389 payload = self.write_crash_dir_entry(
390 '%s.dmp' % self._FAKE_TEST_BASENAME, '')
391 report = self.write_fake_meta(
392 '%s.meta' % self._FAKE_TEST_BASENAME, 'fake', payload)
Ken Mixter38dfe852010-08-18 15:24:00 -0700393 return report
Ken Mixter20d9e472010-08-12 10:58:46 -0700394
395
396 def _parse_sender_output(self, output):
397 """Parse the log output from the crash_sender script.
398
399 This script can run on the logs from either a mocked or true
400 crash send.
401
Bertrand SIMONNET72691dd2014-07-07 14:49:45 -0700402 @param output: output from the script
Ken Mixter20d9e472010-08-12 10:58:46 -0700403
Bertrand SIMONNET72691dd2014-07-07 14:49:45 -0700404 @returns A dictionary with these values:
Michael Krebs6cffa3d2012-09-06 20:09:11 -0700405 error_type: an error type, if given
Ken Mixter38dfe852010-08-18 15:24:00 -0700406 exec_name: name of executable which crashed
Michael Krebs6cffa3d2012-09-06 20:09:11 -0700407 image_type: type of image ("dev","force-official",...), if given
Michael Krebsfb875d02012-09-13 16:49:50 -0700408 boot_mode: current boot mode ("dev",...), if given
Ken Mixter67ff5622010-09-30 15:32:17 -0700409 meta_path: path to the report metadata file
410 output: the output from the script, copied
Ken Mixter38dfe852010-08-18 15:24:00 -0700411 report_kind: kind of report sent (minidump vs kernel)
Ken Mixter20d9e472010-08-12 10:58:46 -0700412 send_attempt: did the script attempt to send a crash.
413 send_success: if it attempted, was the crash send successful.
Ken Mixterd79140e2010-10-26 14:45:30 -0700414 sig: signature of the report, if given.
Ken Mixter20d9e472010-08-12 10:58:46 -0700415 sleep_time: if it attempted, how long did it sleep before
416 sending (if mocked, how long would it have slept)
Ken Mixter20d9e472010-08-12 10:58:46 -0700417 """
418 sleep_match = re.search('Scheduled to send in (\d+)s', output)
419 send_attempt = sleep_match is not None
420 if send_attempt:
421 sleep_time = int(sleep_match.group(1))
422 else:
423 sleep_time = None
Michael Krebs6cffa3d2012-09-06 20:09:11 -0700424
Ken Mixter67ff5622010-09-30 15:32:17 -0700425 meta_match = re.search('Metadata: (\S+) \((\S+)\)', output)
426 if meta_match:
427 meta_path = meta_match.group(1)
428 report_kind = meta_match.group(2)
Ken Mixter38dfe852010-08-18 15:24:00 -0700429 else:
Ken Mixter67ff5622010-09-30 15:32:17 -0700430 meta_path = None
Ken Mixter38dfe852010-08-18 15:24:00 -0700431 report_kind = None
Michael Krebs6cffa3d2012-09-06 20:09:11 -0700432
Ken Mixter67ff5622010-09-30 15:32:17 -0700433 payload_match = re.search('Payload: (\S+)', output)
434 if payload_match:
435 report_payload = payload_match.group(1)
436 else:
437 report_payload = None
Michael Krebs6cffa3d2012-09-06 20:09:11 -0700438
Ken Mixter38dfe852010-08-18 15:24:00 -0700439 exec_name_match = re.search('Exec name: (\S+)', output)
440 if exec_name_match:
441 exec_name = exec_name_match.group(1)
442 else:
443 exec_name = None
Michael Krebs6cffa3d2012-09-06 20:09:11 -0700444
Ken Mixter10c48672010-11-01 13:37:08 -0700445 sig_match = re.search('sig: (\S+)', output)
Ken Mixterd79140e2010-10-26 14:45:30 -0700446 if sig_match:
447 sig = sig_match.group(1)
448 else:
449 sig = None
Michael Krebs6cffa3d2012-09-06 20:09:11 -0700450
451 error_type_match = re.search('Error type: (\S+)', output)
452 if error_type_match:
453 error_type = error_type_match.group(1)
454 else:
455 error_type = None
456
457 image_type_match = re.search('Image type: (\S+)', output)
458 if image_type_match:
459 image_type = image_type_match.group(1)
460 else:
461 image_type = None
462
Michael Krebsfb875d02012-09-13 16:49:50 -0700463 boot_mode_match = re.search('Boot mode: (\S+)', output)
464 if boot_mode_match:
465 boot_mode = boot_mode_match.group(1)
466 else:
467 boot_mode = None
468
Ken Mixter20d9e472010-08-12 10:58:46 -0700469 send_success = 'Mocking successful send' in output
Ken Mixter38dfe852010-08-18 15:24:00 -0700470 return {'exec_name': exec_name,
471 'report_kind': report_kind,
Ken Mixter67ff5622010-09-30 15:32:17 -0700472 'meta_path': meta_path,
473 'report_payload': report_payload,
Ken Mixter38dfe852010-08-18 15:24:00 -0700474 'send_attempt': send_attempt,
Ken Mixter20d9e472010-08-12 10:58:46 -0700475 'send_success': send_success,
Ken Mixterd79140e2010-10-26 14:45:30 -0700476 'sig': sig,
Michael Krebs6cffa3d2012-09-06 20:09:11 -0700477 'error_type': error_type,
478 'image_type': image_type,
Michael Krebsfb875d02012-09-13 16:49:50 -0700479 'boot_mode': boot_mode,
Ken Mixter20d9e472010-08-12 10:58:46 -0700480 'sleep_time': sleep_time,
481 'output': output}
482
483
Ken Mixter654f32e2010-10-20 11:47:31 -0700484 def wait_for_sender_completion(self):
485 """Wait for crash_sender to complete.
486
487 Wait for no crash_sender's last message to be placed in the
488 system log before continuing and for the process to finish.
489 Otherwise we might get only part of the output."""
Eric Lie7c4cab2011-01-05 14:39:19 -0800490 utils.poll_for_condition(
Ken Mixter654f32e2010-10-20 11:47:31 -0700491 lambda: self._log_reader.can_find('crash_sender done.'),
492 timeout=60,
493 exception=error.TestError(
494 'Timeout waiting for crash_sender to emit done: ' +
495 self._log_reader.get_logs()))
Eric Lie7c4cab2011-01-05 14:39:19 -0800496 utils.poll_for_condition(
Ken Mixter654f32e2010-10-20 11:47:31 -0700497 lambda: utils.system('pgrep crash_sender',
498 ignore_status=True) != 0,
499 timeout=60,
500 exception=error.TestError(
501 'Timeout waiting for crash_sender to finish: ' +
502 self._log_reader.get_logs()))
503
504
Ken Mixter20d9e472010-08-12 10:58:46 -0700505 def _call_sender_one_crash(self,
506 send_success=True,
507 reports_enabled=True,
508 username='root',
Bertrand SIMONNET9347d362014-06-30 11:17:59 -0700509 report=None,
510 should_fail=False):
Ken Mixter20d9e472010-08-12 10:58:46 -0700511 """Call the crash sender script to mock upload one crash.
512
Bertrand SIMONNET72691dd2014-07-07 14:49:45 -0700513 @param send_success: Mock a successful send if true
514 @param reports_enabled: Has the user consented to sending crash reports.
515 @param username: user to emulate a crash from
516 @param report: report to use for crash, if None we create one.
Ken Mixter20d9e472010-08-12 10:58:46 -0700517
Bertrand SIMONNET72691dd2014-07-07 14:49:45 -0700518 @returns a dictionary describing the result with the keys
Ken Mixter20d9e472010-08-12 10:58:46 -0700519 from _parse_sender_output, as well as:
Ken Mixter38dfe852010-08-18 15:24:00 -0700520 report_exists: does the minidump still exist after calling
Ken Mixter20d9e472010-08-12 10:58:46 -0700521 send script
522 rate_count: how many crashes have been uploaded in the past
523 24 hours.
524 """
Ken Mixter38dfe852010-08-18 15:24:00 -0700525 report = self._prepare_sender_one_crash(send_success,
526 reports_enabled,
Ken Mixter38dfe852010-08-18 15:24:00 -0700527 report)
Ken Mixter20d9e472010-08-12 10:58:46 -0700528 self._log_reader.set_start_by_current()
Bertrand SIMONNET9347d362014-06-30 11:17:59 -0700529 script_output = ""
530 try:
531 script_output = utils.system_output(
532 '/bin/sh -c "%s" 2>&1' % self._CRASH_SENDER_PATH,
533 ignore_status=should_fail)
534 except error.CmdError as err:
535 raise error.TestFail('"%s" returned an unexpected non-zero '
536 'value (%s).'
537 % (err.command, err.result_obj.exit_status))
538
Ken Mixter654f32e2010-10-20 11:47:31 -0700539 self.wait_for_sender_completion()
Ken Mixter20d9e472010-08-12 10:58:46 -0700540 output = self._log_reader.get_logs()
541 logging.debug('Crash sender message output:\n' + output)
Bertrand SIMONNET9347d362014-06-30 11:17:59 -0700542
Ken Mixter20d9e472010-08-12 10:58:46 -0700543 if script_output != '':
Bertrand SIMONNET9347d362014-06-30 11:17:59 -0700544 logging.debug('crash_sender stdout/stderr: ' + script_output)
Ken Mixter20d9e472010-08-12 10:58:46 -0700545
Ken Mixter38dfe852010-08-18 15:24:00 -0700546 if os.path.exists(report):
547 report_exists = True
548 os.remove(report)
Ken Mixter20d9e472010-08-12 10:58:46 -0700549 else:
Ken Mixter38dfe852010-08-18 15:24:00 -0700550 report_exists = False
Ken Mixter20d9e472010-08-12 10:58:46 -0700551 if os.path.exists(self._CRASH_SENDER_RATE_DIR):
552 rate_count = len(os.listdir(self._CRASH_SENDER_RATE_DIR))
553 else:
554 rate_count = 0
555
556 result = self._parse_sender_output(output)
Ken Mixter38dfe852010-08-18 15:24:00 -0700557 result['report_exists'] = report_exists
Ken Mixter20d9e472010-08-12 10:58:46 -0700558 result['rate_count'] = rate_count
559
560 # Show the result for debugging but remove 'output' key
561 # since it's large and earlier in debug output.
562 debug_result = dict(result)
563 del debug_result['output']
Bertrand SIMONNET72691dd2014-07-07 14:49:45 -0700564 logging.debug('Result of send (besides output): %s', debug_result)
Ken Mixter20d9e472010-08-12 10:58:46 -0700565
566 return result
567
568
Ken Mixterddcd92d2010-11-01 19:07:08 -0700569 def _replace_crash_reporter_filter_in(self, new_parameter):
Simon Glassa47f0d72011-03-15 11:45:32 -0700570 """Replaces the --filter_in= parameter of the crash reporter.
571
572 The kernel is set up to call the crash reporter with the core dump
573 as stdin when a process dies. This function adds a filter to the
574 command line used to call the crash reporter. This is used to ignore
575 crashes in which we have no interest.
576
577 This removes any --filter_in= parameter and optionally replaces it
578 with a new one.
579
Bertrand SIMONNET72691dd2014-07-07 14:49:45 -0700580 @param new_parameter: This is parameter to add to the command line
Simon Glassa47f0d72011-03-15 11:45:32 -0700581 instead of the --filter_in=... that was there.
582 """
Ken Mixterddcd92d2010-11-01 19:07:08 -0700583 core_pattern = utils.read_file(self._CORE_PATTERN)[:-1]
584 core_pattern = re.sub('--filter_in=\S*\s*', '',
585 core_pattern).rstrip()
586 if new_parameter:
587 core_pattern += ' ' + new_parameter
588 utils.system('echo "%s" > %s' % (core_pattern, self._CORE_PATTERN))
589
590
591 def enable_crash_filtering(self, name):
Simon Glassa47f0d72011-03-15 11:45:32 -0700592 """Add a --filter_in argument to the kernel core dump cmdline.
593
Bertrand SIMONNET72691dd2014-07-07 14:49:45 -0700594 @param name: Filter text to use. This is passed as a --filter_in
Simon Glassa47f0d72011-03-15 11:45:32 -0700595 argument to the crash reporter.
596 """
Ken Mixterddcd92d2010-11-01 19:07:08 -0700597 self._replace_crash_reporter_filter_in('--filter_in=' + name)
598
599
600 def disable_crash_filtering(self):
Simon Glassa47f0d72011-03-15 11:45:32 -0700601 """Remove the --filter_in argument from the kernel core dump cmdline.
602
603 Next time the crash reporter is invoked (due to a crash) it will not
604 receive a --filter_in paramter."""
Ken Mixterddcd92d2010-11-01 19:07:08 -0700605 self._replace_crash_reporter_filter_in('')
606
607
Mike Frysinger0fa79ab2014-05-24 21:16:04 -0400608 @contextlib.contextmanager
609 def hold_crash_lock(self):
610 """A context manager to hold the crash sender lock."""
611 with open(self._CRASH_SENDER_LOCK_PATH, 'w+') as f:
612 fcntl.flock(f.fileno(), fcntl.LOCK_EX)
613 try:
614 yield
615 finally:
616 fcntl.flock(f.fileno(), fcntl.LOCK_UN)
617
618
Ken Mixter20d9e472010-08-12 10:58:46 -0700619 def initialize(self):
Simon Glassa47f0d72011-03-15 11:45:32 -0700620 """Initalize the test."""
Ken Mixter20d9e472010-08-12 10:58:46 -0700621 test.test.initialize(self)
Eric Lie7c4cab2011-01-05 14:39:19 -0800622 self._log_reader = cros_logging.LogReader()
Ken Mixter38dfe852010-08-18 15:24:00 -0700623 self._leave_crash_sending = True
Ken Mixter67ff5622010-09-30 15:32:17 -0700624 self._automatic_consent_saving = True
Ken Mixterddcd92d2010-11-01 19:07:08 -0700625 self.enable_crash_filtering('none')
Thieu Lec16253b2011-03-03 11:13:54 -0800626 self._set_crash_test_in_progress(True)
Ken Mixter20d9e472010-08-12 10:58:46 -0700627
628
629 def cleanup(self):
Simon Glassa47f0d72011-03-15 11:45:32 -0700630 """Cleanup after the test.
631
632 We reset things back to the way we think they should be. This is
633 intended to allow the system to continue normal operation.
634
635 Some variables silently change the behavior:
636 _automatic_consent_saving: if True, we pop the consent file.
637 _leave_crash_sending: True to enable crash sending, False to
638 disable it
639 """
Ken Mixter20d9e472010-08-12 10:58:46 -0700640 self._reset_rate_limiting()
641 self._clear_spooled_crashes()
Ken Mixter4f619652010-10-18 12:11:18 -0700642 self._set_system_sending(self._leave_crash_sending)
Ken Mixter20d9e472010-08-12 10:58:46 -0700643 self._set_sending_mock(mock_enabled=False)
Ken Mixter67ff5622010-09-30 15:32:17 -0700644 if self._automatic_consent_saving:
645 self._pop_consent()
Ken Mixterddcd92d2010-11-01 19:07:08 -0700646 self.disable_crash_filtering()
Thieu Lec16253b2011-03-03 11:13:54 -0800647 self._set_crash_test_in_progress(False)
Ken Mixter20d9e472010-08-12 10:58:46 -0700648 test.test.cleanup(self)
649
650
Ken Mixter38dfe852010-08-18 15:24:00 -0700651 def run_crash_tests(self,
652 test_names,
653 initialize_crash_reporter=False,
654 clear_spool_first=True,
655 must_run_all=True):
656 """Run crash tests defined in this class.
657
Bertrand SIMONNET72691dd2014-07-07 14:49:45 -0700658 @param test_names: Array of test names.
659 @param initialize_crash_reporter: Should set up crash reporter for every
Simon Glassa47f0d72011-03-15 11:45:32 -0700660 run.
Bertrand SIMONNET72691dd2014-07-07 14:49:45 -0700661 @param clear_spool_first: Clear all spooled user/system crashes before
Simon Glassa47f0d72011-03-15 11:45:32 -0700662 starting the test.
Bertrand SIMONNET72691dd2014-07-07 14:49:45 -0700663 @param must_run_all: Should make sure every test in this class is
Simon Glassa47f0d72011-03-15 11:45:32 -0700664 mentioned in test_names.
Ken Mixter38dfe852010-08-18 15:24:00 -0700665 """
Ken Mixter67ff5622010-09-30 15:32:17 -0700666 if self._automatic_consent_saving:
667 self._push_consent()
Ken Mixter20d9e472010-08-12 10:58:46 -0700668
Ken Mixter38dfe852010-08-18 15:24:00 -0700669 if must_run_all:
670 # Sanity check test_names is complete
671 for attr in dir(self):
672 if attr.find('_test_') == 0:
673 test_name = attr[6:]
674 if not test_name in test_names:
675 raise error.TestError('Test %s is missing' % test_name)
Ken Mixter20d9e472010-08-12 10:58:46 -0700676
677 for test_name in test_names:
678 logging.info(('=' * 20) + ('Running %s' % test_name) + ('=' * 20))
Ken Mixter38dfe852010-08-18 15:24:00 -0700679 if initialize_crash_reporter:
680 self._initialize_crash_reporter()
Ken Mixter4f619652010-10-18 12:11:18 -0700681 # Disable crash_sender from running, kill off any running ones, but
682 # set environment so crash_sender may run as a child process.
683 self._set_system_sending(False)
684 self._set_child_sending(True)
Ken Mixter20d9e472010-08-12 10:58:46 -0700685 self._kill_running_sender()
686 self._reset_rate_limiting()
Michael Krebs6cffa3d2012-09-06 20:09:11 -0700687 # Default to not overriding for unofficial versions.
688 self._set_force_official(False)
Michael Krebsfb875d02012-09-13 16:49:50 -0700689 # Default to not pretending we're in developer mode.
690 self._set_mock_developer_mode(False)
Ken Mixter38dfe852010-08-18 15:24:00 -0700691 if clear_spool_first:
692 self._clear_spooled_crashes()
Simon Glassa47f0d72011-03-15 11:45:32 -0700693
694 # Call the test function
Ken Mixter20d9e472010-08-12 10:58:46 -0700695 getattr(self, '_test_' + test_name)()