blob: 0ca944a18163de3e2ef07d55d64ed7d452820d8a [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;
127
128 if (filter)
129 return 1;
130
131 hash = StringHash(yytext);
132 if (!(testing || fifo || filter)) {
133 CMetricsLibrarySendSparseToUMA(metrics_library, warn_hist_name, (int) hash);
134 }
135 if (HashSeen(hash))
136 return 0;
137 SetHashSeen(hash);
138
139 yyout = fopen(warn_dump_path, "w");
140 if (yyout == NULL)
141 Die("fopen %s failed: %s\n", warn_dump_path, strerror(errno));
142 fprintf(yyout, "%08x\n", hash);
143 return 1;
144}
145
146void WarnEnd(void) {
147 if (filter)
148 return;
149 fclose(yyout);
150 yyout = stdout; /* for debugging */
151 RunCrashReporter();
152}
153
154static void WarnOpenInput(const char *path) {
155 yyin_fd = open(path, O_RDONLY);
156 if (yyin_fd < 0)
157 Die("could not open %s: %s\n", path, strerror(errno));
158 if (!fifo) {
159 /* Set up notification of file growth and rename. */
160 i_fd = inotify_init();
161 if (i_fd < 0)
162 Die("inotify_init: %s\n", strerror(errno));
163 if (inotify_add_watch(i_fd, path, IN_MODIFY | IN_MOVE_SELF) < 0)
164 Die("inotify_add_watch: %s\n", strerror(errno));
165 }
166}
167
168/* We replace the default YY_INPUT() for the following reasons:
169 *
170 * 1. We want to read data as soon as it becomes available, but the default
171 * YY_INPUT() uses buffered I/O.
172 *
173 * 2. We want to block on end of input and wait for the file to grow.
174 *
175 * 3. We want to detect log rotation, and reopen the input file as needed.
176 */
Mike Frysinger9f3bf882013-11-10 16:33:21 -0500177void WarnInput(char *buf, yy_size_t *result, size_t max_size) {
Luigi Semenzato6fdc0b42013-04-11 17:22:13 -0700178 while (1) {
Mike Frysinger9f3bf882013-11-10 16:33:21 -0500179 ssize_t ret = read(yyin_fd, buf, max_size);
180 if (ret < 0)
Luigi Semenzato6fdc0b42013-04-11 17:22:13 -0700181 Die("read: %s", strerror(errno));
Mike Frysinger9f3bf882013-11-10 16:33:21 -0500182 *result = ret;
Luigi Semenzato6fdc0b42013-04-11 17:22:13 -0700183 if (*result > 0 || fifo || filter)
184 return;
185 if (draining) {
186 /* Assume we're done with this log, and move to next
187 * log. Rsyslogd may keep writing to the old log file
188 * for a while, but we don't care since we don't have
189 * to be exact.
190 */
191 close(yyin_fd);
192 if (YYSTATE == WARN) {
193 /* Be conservative in case we lose the warn
194 * terminator during the switch---or we may
195 * collect personally identifiable information.
196 */
197 WarnEnd();
198 }
199 BEGIN(0); /* see above comment */
200 sleep(1); /* avoid race with log rotator */
201 WarnOpenInput(msg_path);
202 draining = 0;
203 continue;
204 }
205 /* Nothing left to read, so we must wait. */
206 struct inotify_event event;
Mike Frysinger77bd1562013-05-22 17:47:49 -0400207 while (1) {
208 int n = read(i_fd, &event, sizeof(event));
209 if (n <= 0) {
210 if (errno == EINTR)
211 continue;
212 else
213 Die("inotify: %s\n", strerror(errno));
214 } else
215 break;
216 }
Luigi Semenzato6fdc0b42013-04-11 17:22:13 -0700217 if (event.mask & IN_MOVE_SELF) {
218 /* The file has been renamed. Before switching
219 * to the new one, we process any remaining
220 * content of this file.
221 */
222 draining = 1;
223 }
224 }
225}
226
227int main(int argc, char **argv) {
228 int result;
229 struct passwd *user;
230 prog_name = argv[0];
231
232 if (argc == 2 && strcmp(argv[1], "--test") == 0)
233 testing = 1;
234 else if (argc == 2 && strcmp(argv[1], "--filter") == 0)
235 filter = 1;
236 else if (argc == 2 && strcmp(argv[1], "--fifo") == 0) {
237 fifo = 1;
238 } else if (argc != 1) {
239 fprintf(stderr,
240 "usage: %s [single-flag]\n"
241 "flags (for testing only):\n"
242 "--fifo\tinput is fifo \"fifo\", output is stdout\n"
243 "--filter\tinput is stdin, output is stdout\n"
244 "--test\trun self-test\n",
245 prog_name);
246 exit(1);
247 }
248
249 metrics_library = CMetricsLibraryNew();
250 CMetricsLibraryInit(metrics_library);
251
252 crash_reporter_command = testing ?
253 "./warn_collector_test_reporter.sh" :
254 "/sbin/crash_reporter --kernel_warning";
255
256 /* When filtering with --filter (for development) use stdin for input.
257 * Otherwise read input from a file or a fifo.
258 */
259 yyin_fd = fileno(stdin);
260 if (testing) {
261 msg_path = "messages";
262 warn_dump_path = "warning";
263 }
264 if (fifo) {
265 msg_path = "fifo";
266 }
267 if (!filter) {
268 WarnOpenInput(msg_path);
269 }
270
271 /* Create directory for dump file. Still need to be root here. */
272 unlink(warn_dump_path);
273 if (!testing && !fifo && !filter) {
274 rmdir(warn_dump_dir);
275 result = mkdir(warn_dump_dir, 0755);
276 if (result < 0)
277 Die("could not create %s: %s\n",
278 warn_dump_dir, strerror(errno));
279 }
280
281 if (0) {
282 /* TODO(semenzato): put this back in once we decide it's safe
283 * to make /var/spool/crash rwxrwxrwx root, or use a different
284 * owner and setuid for the crash reporter as well.
285 */
286
287 /* Get low privilege uid, gid. */
288 user = getpwnam("chronos");
289 if (user == NULL)
290 Die("getpwnam failed\n");
291
292 /* Change dump directory ownership. */
293 if (chown(warn_dump_dir, user->pw_uid, user->pw_gid) < 0)
294 Die("chown: %s\n", strerror(errno));
295
296 /* Drop privileges. */
297 if (setuid(user->pw_uid) < 0) {
298 Die("setuid: %s\n", strerror(errno));
299 }
300 }
301
302 /* Go! */
303 return yylex();
304}
305
306/* Flex should really know not to generate these functions.
307 */
308void UnusedFunctionWarningSuppressor(void) {
309 yyunput(0, 0);
310 (void) input();
311}