blob: 5cb12f12ca9881bccc81200958e40f79209c0836 [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);
29void WarnInput(char *buf, int *result, size_t max_size);
30
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 */
177void WarnInput(char *buf, int *result, size_t max_size) {
178 while (1) {
179 *result = read(yyin_fd, buf, max_size);
180 if (*result < 0)
181 Die("read: %s", strerror(errno));
182 if (*result > 0 || fifo || filter)
183 return;
184 if (draining) {
185 /* Assume we're done with this log, and move to next
186 * log. Rsyslogd may keep writing to the old log file
187 * for a while, but we don't care since we don't have
188 * to be exact.
189 */
190 close(yyin_fd);
191 if (YYSTATE == WARN) {
192 /* Be conservative in case we lose the warn
193 * terminator during the switch---or we may
194 * collect personally identifiable information.
195 */
196 WarnEnd();
197 }
198 BEGIN(0); /* see above comment */
199 sleep(1); /* avoid race with log rotator */
200 WarnOpenInput(msg_path);
201 draining = 0;
202 continue;
203 }
204 /* Nothing left to read, so we must wait. */
205 struct inotify_event event;
Mike Frysinger77bd1562013-05-22 17:47:49 -0400206 while (1) {
207 int n = read(i_fd, &event, sizeof(event));
208 if (n <= 0) {
209 if (errno == EINTR)
210 continue;
211 else
212 Die("inotify: %s\n", strerror(errno));
213 } else
214 break;
215 }
Luigi Semenzato6fdc0b42013-04-11 17:22:13 -0700216 if (event.mask & IN_MOVE_SELF) {
217 /* The file has been renamed. Before switching
218 * to the new one, we process any remaining
219 * content of this file.
220 */
221 draining = 1;
222 }
223 }
224}
225
226int main(int argc, char **argv) {
227 int result;
228 struct passwd *user;
229 prog_name = argv[0];
230
231 if (argc == 2 && strcmp(argv[1], "--test") == 0)
232 testing = 1;
233 else if (argc == 2 && strcmp(argv[1], "--filter") == 0)
234 filter = 1;
235 else if (argc == 2 && strcmp(argv[1], "--fifo") == 0) {
236 fifo = 1;
237 } else if (argc != 1) {
238 fprintf(stderr,
239 "usage: %s [single-flag]\n"
240 "flags (for testing only):\n"
241 "--fifo\tinput is fifo \"fifo\", output is stdout\n"
242 "--filter\tinput is stdin, output is stdout\n"
243 "--test\trun self-test\n",
244 prog_name);
245 exit(1);
246 }
247
248 metrics_library = CMetricsLibraryNew();
249 CMetricsLibraryInit(metrics_library);
250
251 crash_reporter_command = testing ?
252 "./warn_collector_test_reporter.sh" :
253 "/sbin/crash_reporter --kernel_warning";
254
255 /* When filtering with --filter (for development) use stdin for input.
256 * Otherwise read input from a file or a fifo.
257 */
258 yyin_fd = fileno(stdin);
259 if (testing) {
260 msg_path = "messages";
261 warn_dump_path = "warning";
262 }
263 if (fifo) {
264 msg_path = "fifo";
265 }
266 if (!filter) {
267 WarnOpenInput(msg_path);
268 }
269
270 /* Create directory for dump file. Still need to be root here. */
271 unlink(warn_dump_path);
272 if (!testing && !fifo && !filter) {
273 rmdir(warn_dump_dir);
274 result = mkdir(warn_dump_dir, 0755);
275 if (result < 0)
276 Die("could not create %s: %s\n",
277 warn_dump_dir, strerror(errno));
278 }
279
280 if (0) {
281 /* TODO(semenzato): put this back in once we decide it's safe
282 * to make /var/spool/crash rwxrwxrwx root, or use a different
283 * owner and setuid for the crash reporter as well.
284 */
285
286 /* Get low privilege uid, gid. */
287 user = getpwnam("chronos");
288 if (user == NULL)
289 Die("getpwnam failed\n");
290
291 /* Change dump directory ownership. */
292 if (chown(warn_dump_dir, user->pw_uid, user->pw_gid) < 0)
293 Die("chown: %s\n", strerror(errno));
294
295 /* Drop privileges. */
296 if (setuid(user->pw_uid) < 0) {
297 Die("setuid: %s\n", strerror(errno));
298 }
299 }
300
301 /* Go! */
302 return yylex();
303}
304
305/* Flex should really know not to generate these functions.
306 */
307void UnusedFunctionWarningSuppressor(void) {
308 yyunput(0, 0);
309 (void) input();
310}