blob: 6411b4d9bde54178e6c913103bdf7143d7e0cdac [file] [log] [blame]
Luigi Semenzato6fdc0b42013-04-11 17:22:13 -07001/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
2 * Use of this source code is governed by a BSD-style license that can be
3 * found in the LICENSE file.
4 *
5 * This flex program reads /var/log/messages as it grows and saves kernel
6 * warnings to files. It keeps track of warnings it has seen (based on
7 * file/line only, ignoring differences in the stack trace), and reports only
8 * the first warning of each kind, but maintains a count of all warnings by
9 * using their hashes as buckets in a UMA sparse histogram. It also invokes
10 * the crash collector, which collects the warnings and prepares them for later
11 * shipment to the crash server.
12 */
13
14%{
15#include <fcntl.h>
16#include <inttypes.h>
17#include <pwd.h>
18#include <stdarg.h>
19#include <sys/inotify.h>
20#include <sys/select.h>
21#include <sys/stat.h>
22#include <sys/types.h>
23#include <unistd.h>
24
25#include "metrics/c_metrics_library.h"
26
27int WarnStart(void);
28void WarnEnd(void);
Mike Frysinger9f3bf882013-11-10 16:33:21 -050029void WarnInput(char *buf, yy_size_t *result, size_t max_size);
Luigi Semenzato6fdc0b42013-04-11 17:22:13 -070030
31#define YY_INPUT(buf, result, max_size) WarnInput(buf, &result, max_size)
32
33%}
34
35/* Define a few useful regular expressions. */
36
37D [0-9]
38PREFIX .*" kernel: [ "*{D}+"."{D}+"]"
39CUT_HERE {PREFIX}" ------------[ cut here".*
40WARNING {PREFIX}" WARNING: at "
41END_TRACE {PREFIX}" ---[ end trace".*
42
43/* Use exclusive start conditions. */
44%x PRE_WARN WARN
45
46%%
47 /* The scanner itself. */
48
49^{CUT_HERE}\n{WARNING} BEGIN(PRE_WARN);
50.|\n /* ignore all other input in state 0 */
mukesh agrawal32f827f2013-07-02 13:00:01 -070051<PRE_WARN>[^ ]+.[^ ]+\n if (WarnStart()) {
52 /* yytext is
53 "file:line func+offset/offset()\n" */
Luigi Semenzato6fdc0b42013-04-11 17:22:13 -070054 BEGIN(WARN); ECHO;
55 } else {
56 BEGIN(0);
57 }
58
59 /* Assume the warning ends at the "end trace" line */
60<WARN>^{END_TRACE}\n ECHO; BEGIN(0); WarnEnd();
61<WARN>^.*\n ECHO;
62
63%%
64
65#define HASH_BITMAP_SIZE (1 << 15) /* size in bits */
66#define HASH_BITMAP_MASK (HASH_BITMAP_SIZE - 1)
67
68const char warn_hist_name[] = "Platform.KernelWarningHashes";
69uint32_t hash_bitmap[HASH_BITMAP_SIZE / 32];
70CMetricsLibrary metrics_library;
71
72const char *prog_name; /* the name of this program */
73int yyin_fd; /* instead of FILE *yyin to avoid buffering */
74int i_fd; /* for inotify, to detect file changes */
75int testing; /* 1 if running test */
76int filter; /* 1 when using as filter (for development) */
77int fifo; /* 1 when reading from fifo (for devel) */
78int draining; /* 1 when draining renamed log file */
79
80const char *msg_path = "/var/log/messages";
81const char warn_dump_dir[] = "/var/run/kwarn";
82const char *warn_dump_path = "/var/run/kwarn/warning";
83const char *crash_reporter_command;
84
Mike Frysingera569da02013-09-24 14:15:36 -040085__attribute__((__format__(__printf__, 1, 2)))
Luigi Semenzato6fdc0b42013-04-11 17:22:13 -070086static void Die(const char *format, ...) {
87 va_list ap;
88 va_start(ap, format);
89 fprintf(stderr, "%s: ", prog_name);
90 vfprintf(stderr, format, ap);
91 exit(1);
92}
93
94static void RunCrashReporter(void) {
95 int status = system(crash_reporter_command);
96 if (status != 0)
97 Die("%s exited with status %d\n", crash_reporter_command, status);
98}
99
100static uint32_t StringHash(const char *string) {
101 uint32_t hash = 0;
102 while (*string != '\0') {
103 hash = (hash << 5) + hash + *string++;
104 }
105 return hash;
106}
107
108/* We expect only a handful of different warnings per boot session, so the
109 * probability of a collision is very low, and statistically it won't matter
110 * (unless warnings with the same hash also happens in tandem, which is even
111 * rarer).
112 */
113static int HashSeen(uint32_t hash) {
114 int word_index = (hash & HASH_BITMAP_MASK) / 32;
115 int bit_index = (hash & HASH_BITMAP_MASK) % 32;
116 return hash_bitmap[word_index] & 1 << bit_index;
117}
118
119static void SetHashSeen(uint32_t hash) {
120 int word_index = (hash & HASH_BITMAP_MASK) / 32;
121 int bit_index = (hash & HASH_BITMAP_MASK) % 32;
122 hash_bitmap[word_index] |= 1 << bit_index;
123}
124
125int WarnStart(void) {
126 uint32_t hash;
Luigi Semenzatoa59b3df2013-12-16 13:59:03 -0800127 char *spacep;
Luigi Semenzato6fdc0b42013-04-11 17:22:13 -0700128
129 if (filter)
130 return 1;
131
132 hash = StringHash(yytext);
133 if (!(testing || fifo || filter)) {
134 CMetricsLibrarySendSparseToUMA(metrics_library, warn_hist_name, (int) hash);
135 }
136 if (HashSeen(hash))
137 return 0;
138 SetHashSeen(hash);
139
140 yyout = fopen(warn_dump_path, "w");
141 if (yyout == NULL)
142 Die("fopen %s failed: %s\n", warn_dump_path, strerror(errno));
Luigi Semenzatoa59b3df2013-12-16 13:59:03 -0800143 spacep = index(yytext, ' ');
144 if (spacep == NULL || spacep[1] == '\0')
145 spacep = "unknown-function";
146 fprintf(yyout, "%08x-%s\n", hash, spacep + 1);
Luigi Semenzato6fdc0b42013-04-11 17:22:13 -0700147 return 1;
148}
149
150void WarnEnd(void) {
151 if (filter)
152 return;
153 fclose(yyout);
154 yyout = stdout; /* for debugging */
155 RunCrashReporter();
156}
157
158static void WarnOpenInput(const char *path) {
159 yyin_fd = open(path, O_RDONLY);
160 if (yyin_fd < 0)
161 Die("could not open %s: %s\n", path, strerror(errno));
162 if (!fifo) {
163 /* Set up notification of file growth and rename. */
164 i_fd = inotify_init();
165 if (i_fd < 0)
166 Die("inotify_init: %s\n", strerror(errno));
167 if (inotify_add_watch(i_fd, path, IN_MODIFY | IN_MOVE_SELF) < 0)
168 Die("inotify_add_watch: %s\n", strerror(errno));
169 }
170}
171
172/* We replace the default YY_INPUT() for the following reasons:
173 *
174 * 1. We want to read data as soon as it becomes available, but the default
175 * YY_INPUT() uses buffered I/O.
176 *
177 * 2. We want to block on end of input and wait for the file to grow.
178 *
179 * 3. We want to detect log rotation, and reopen the input file as needed.
180 */
Mike Frysinger9f3bf882013-11-10 16:33:21 -0500181void WarnInput(char *buf, yy_size_t *result, size_t max_size) {
Luigi Semenzato6fdc0b42013-04-11 17:22:13 -0700182 while (1) {
Mike Frysinger9f3bf882013-11-10 16:33:21 -0500183 ssize_t ret = read(yyin_fd, buf, max_size);
184 if (ret < 0)
Luigi Semenzato6fdc0b42013-04-11 17:22:13 -0700185 Die("read: %s", strerror(errno));
Mike Frysinger9f3bf882013-11-10 16:33:21 -0500186 *result = ret;
Luigi Semenzato6fdc0b42013-04-11 17:22:13 -0700187 if (*result > 0 || fifo || filter)
188 return;
189 if (draining) {
190 /* Assume we're done with this log, and move to next
191 * log. Rsyslogd may keep writing to the old log file
192 * for a while, but we don't care since we don't have
193 * to be exact.
194 */
195 close(yyin_fd);
196 if (YYSTATE == WARN) {
197 /* Be conservative in case we lose the warn
198 * terminator during the switch---or we may
199 * collect personally identifiable information.
200 */
201 WarnEnd();
202 }
203 BEGIN(0); /* see above comment */
204 sleep(1); /* avoid race with log rotator */
205 WarnOpenInput(msg_path);
206 draining = 0;
207 continue;
208 }
209 /* Nothing left to read, so we must wait. */
210 struct inotify_event event;
Mike Frysinger77bd1562013-05-22 17:47:49 -0400211 while (1) {
212 int n = read(i_fd, &event, sizeof(event));
213 if (n <= 0) {
214 if (errno == EINTR)
215 continue;
216 else
217 Die("inotify: %s\n", strerror(errno));
218 } else
219 break;
220 }
Luigi Semenzato6fdc0b42013-04-11 17:22:13 -0700221 if (event.mask & IN_MOVE_SELF) {
222 /* The file has been renamed. Before switching
223 * to the new one, we process any remaining
224 * content of this file.
225 */
226 draining = 1;
227 }
228 }
229}
230
231int main(int argc, char **argv) {
232 int result;
233 struct passwd *user;
234 prog_name = argv[0];
235
236 if (argc == 2 && strcmp(argv[1], "--test") == 0)
237 testing = 1;
238 else if (argc == 2 && strcmp(argv[1], "--filter") == 0)
239 filter = 1;
240 else if (argc == 2 && strcmp(argv[1], "--fifo") == 0) {
241 fifo = 1;
242 } else if (argc != 1) {
243 fprintf(stderr,
244 "usage: %s [single-flag]\n"
245 "flags (for testing only):\n"
246 "--fifo\tinput is fifo \"fifo\", output is stdout\n"
247 "--filter\tinput is stdin, output is stdout\n"
248 "--test\trun self-test\n",
249 prog_name);
250 exit(1);
251 }
252
253 metrics_library = CMetricsLibraryNew();
254 CMetricsLibraryInit(metrics_library);
255
256 crash_reporter_command = testing ?
257 "./warn_collector_test_reporter.sh" :
258 "/sbin/crash_reporter --kernel_warning";
259
260 /* When filtering with --filter (for development) use stdin for input.
261 * Otherwise read input from a file or a fifo.
262 */
263 yyin_fd = fileno(stdin);
264 if (testing) {
265 msg_path = "messages";
266 warn_dump_path = "warning";
267 }
268 if (fifo) {
269 msg_path = "fifo";
270 }
271 if (!filter) {
272 WarnOpenInput(msg_path);
273 }
274
275 /* Create directory for dump file. Still need to be root here. */
276 unlink(warn_dump_path);
277 if (!testing && !fifo && !filter) {
278 rmdir(warn_dump_dir);
279 result = mkdir(warn_dump_dir, 0755);
280 if (result < 0)
281 Die("could not create %s: %s\n",
282 warn_dump_dir, strerror(errno));
283 }
284
285 if (0) {
286 /* TODO(semenzato): put this back in once we decide it's safe
287 * to make /var/spool/crash rwxrwxrwx root, or use a different
288 * owner and setuid for the crash reporter as well.
289 */
290
291 /* Get low privilege uid, gid. */
292 user = getpwnam("chronos");
293 if (user == NULL)
294 Die("getpwnam failed\n");
295
296 /* Change dump directory ownership. */
297 if (chown(warn_dump_dir, user->pw_uid, user->pw_gid) < 0)
298 Die("chown: %s\n", strerror(errno));
299
300 /* Drop privileges. */
301 if (setuid(user->pw_uid) < 0) {
302 Die("setuid: %s\n", strerror(errno));
303 }
304 }
305
306 /* Go! */
307 return yylex();
308}
309
310/* Flex should really know not to generate these functions.
311 */
312void UnusedFunctionWarningSuppressor(void) {
313 yyunput(0, 0);
314 (void) input();
315}