ubox: Add an option for more accurate timestamps in log
[project/ubox.git] / log / logread.c
1 /*
2 * Copyright (C) 2013 Felix Fietkau <nbd@openwrt.org>
3 * Copyright (C) 2013 John Crispin <blogic@openwrt.org>
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU Lesser General Public License version 2.1
7 * as published by the Free Software Foundation
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 */
14
15 #include <sys/types.h>
16 #include <sys/stat.h>
17
18 #include <fcntl.h>
19 #include <time.h>
20 #include <regex.h>
21 #include <stdio.h>
22 #include <unistd.h>
23 #include <sys/types.h>
24 #include <sys/socket.h>
25
26 #define SYSLOG_NAMES
27 #include <syslog.h>
28
29 #include <libubox/ustream.h>
30 #include <libubox/blobmsg_json.h>
31 #include <libubox/usock.h>
32 #include <libubox/uloop.h>
33 #include "libubus.h"
34 #include "syslog.h"
35
36 enum {
37 LOG_STDOUT,
38 LOG_FILE,
39 LOG_NET,
40 };
41
42 enum {
43 LOG_MSG,
44 LOG_ID,
45 LOG_PRIO,
46 LOG_SOURCE,
47 LOG_TIME,
48 __LOG_MAX
49 };
50
51 static const struct blobmsg_policy log_policy[] = {
52 [LOG_MSG] = { .name = "msg", .type = BLOBMSG_TYPE_STRING },
53 [LOG_ID] = { .name = "id", .type = BLOBMSG_TYPE_INT32 },
54 [LOG_PRIO] = { .name = "priority", .type = BLOBMSG_TYPE_INT32 },
55 [LOG_SOURCE] = { .name = "source", .type = BLOBMSG_TYPE_INT32 },
56 [LOG_TIME] = { .name = "time", .type = BLOBMSG_TYPE_INT64 },
57 };
58
59 static struct uloop_timeout retry;
60 static struct uloop_fd sender;
61 static regex_t regexp_preg;
62 static const char *log_file, *log_ip, *log_port, *log_prefix, *pid_file, *hostname, *regexp_pattern;
63 static int log_type = LOG_STDOUT;
64 static int log_size, log_udp, log_follow, log_trailer_null = 0;
65 static int log_timestamp;
66
67 static const char* getcodetext(int value, CODE *codetable) {
68 CODE *i;
69
70 if (value >= 0)
71 for (i = codetable; i->c_val != -1; i++)
72 if (i->c_val == value)
73 return (i->c_name);
74 return "<unknown>";
75 };
76
77 static void log_handle_reconnect(struct uloop_timeout *timeout)
78 {
79 sender.fd = usock((log_udp) ? (USOCK_UDP) : (USOCK_TCP), log_ip, log_port);
80 if (sender.fd < 0) {
81 fprintf(stderr, "failed to connect: %s\n", strerror(errno));
82 uloop_timeout_set(&retry, 1000);
83 } else {
84 uloop_fd_add(&sender, ULOOP_READ);
85 syslog(LOG_INFO, "Logread connected to %s:%s\n", log_ip, log_port);
86 }
87 }
88
89 static void log_handle_fd(struct uloop_fd *u, unsigned int events)
90 {
91 if (u->eof) {
92 uloop_fd_delete(u);
93 close(sender.fd);
94 sender.fd = -1;
95 uloop_timeout_set(&retry, 1000);
96 }
97 }
98
99 static int log_notify(struct blob_attr *msg)
100 {
101 struct blob_attr *tb[__LOG_MAX];
102 struct stat s;
103 char buf[512];
104 char buf_ts[32];
105 uint32_t p;
106 char *str;
107 time_t t;
108 uint32_t t_ms = 0;
109 char *c, *m;
110 int ret = 0;
111
112 if (sender.fd < 0)
113 return 0;
114
115 blobmsg_parse(log_policy, ARRAY_SIZE(log_policy), tb, blob_data(msg), blob_len(msg));
116 if (!tb[LOG_ID] || !tb[LOG_PRIO] || !tb[LOG_SOURCE] || !tb[LOG_TIME] || !tb[LOG_MSG])
117 return 1;
118
119 if ((log_type == LOG_FILE) && log_size && (!stat(log_file, &s)) && (s.st_size > log_size)) {
120 char *old = malloc(strlen(log_file) + 5);
121
122 close(sender.fd);
123 if (old) {
124 sprintf(old, "%s.old", log_file);
125 rename(log_file, old);
126 free(old);
127 }
128 sender.fd = open(log_file, O_CREAT | O_WRONLY | O_APPEND, 0600);
129 if (sender.fd < 0) {
130 fprintf(stderr, "failed to open %s: %s\n", log_file, strerror(errno));
131 exit(-1);
132 }
133 }
134
135 m = blobmsg_get_string(tb[LOG_MSG]);
136 if (regexp_pattern &&
137 regexec(&regexp_preg, m, 0, NULL, 0) == REG_NOMATCH)
138 return 0;
139 t = blobmsg_get_u64(tb[LOG_TIME]) / 1000;
140 if (log_timestamp) {
141 t_ms = blobmsg_get_u64(tb[LOG_TIME]) % 1000;
142 snprintf(buf_ts, sizeof(buf_ts), "[%lu.%03u] ",
143 (unsigned long)t, t_ms);
144 }
145 c = ctime(&t);
146 p = blobmsg_get_u32(tb[LOG_PRIO]);
147 c[strlen(c) - 1] = '\0';
148 str = blobmsg_format_json(msg, true);
149 if (log_type == LOG_NET) {
150 int err;
151
152 snprintf(buf, sizeof(buf), "<%u>", p);
153 strncat(buf, c + 4, 16);
154 if (log_timestamp) {
155 strncat(buf, buf_ts, sizeof(buf) - strlen(buf) - 1);
156 }
157 if (hostname) {
158 strncat(buf, hostname, sizeof(buf) - strlen(buf) - 1);
159 strncat(buf, " ", sizeof(buf) - strlen(buf) - 1);
160 }
161 if (log_prefix) {
162 strncat(buf, log_prefix, sizeof(buf) - strlen(buf) - 1);
163 strncat(buf, ": ", sizeof(buf) - strlen(buf) - 1);
164 }
165 if (blobmsg_get_u32(tb[LOG_SOURCE]) == SOURCE_KLOG)
166 strncat(buf, "kernel: ", sizeof(buf) - strlen(buf) - 1);
167 strncat(buf, m, sizeof(buf) - strlen(buf) - 1);
168 if (log_udp)
169 err = write(sender.fd, buf, strlen(buf));
170 else {
171 size_t buflen = strlen(buf);
172 if (!log_trailer_null)
173 buf[buflen] = '\n';
174 err = send(sender.fd, buf, buflen + 1, 0);
175 }
176
177 if (err < 0) {
178 syslog(LOG_INFO, "failed to send log data to %s:%s via %s\n",
179 log_ip, log_port, (log_udp) ? ("udp") : ("tcp"));
180 uloop_fd_delete(&sender);
181 close(sender.fd);
182 sender.fd = -1;
183 uloop_timeout_set(&retry, 1000);
184 }
185 } else {
186 snprintf(buf, sizeof(buf), "%s %s%s.%s%s %s\n",
187 c, log_timestamp ? buf_ts : "",
188 getcodetext(LOG_FAC(p) << 3, facilitynames),
189 getcodetext(LOG_PRI(p), prioritynames),
190 (blobmsg_get_u32(tb[LOG_SOURCE])) ? ("") : (" kernel:"), m);
191 ret = write(sender.fd, buf, strlen(buf));
192 }
193
194 free(str);
195 if (log_type == LOG_FILE)
196 fsync(sender.fd);
197
198 return ret;
199 }
200
201 static int usage(const char *prog)
202 {
203 fprintf(stderr, "Usage: %s [options]\n"
204 "Options:\n"
205 " -s <path> Path to ubus socket\n"
206 " -l <count> Got only the last 'count' messages\n"
207 " -e <pattern> Filter messages with a regexp\n"
208 " -r <server> <port> Stream message to a server\n"
209 " -F <file> Log file\n"
210 " -S <bytes> Log size\n"
211 " -p <file> PID file\n"
212 " -h <hostname> Add hostname to the message\n"
213 " -P <prefix> Prefix custom text to streamed messages\n"
214 " -f Follow log messages\n"
215 " -u Use UDP as the protocol\n"
216 " -t Add an extra timestamp\n"
217 " -0 Use \\0 instead of \\n as trailer when using TCP\n"
218 "\n", prog);
219 return 1;
220 }
221
222 static void logread_fd_data_cb(struct ustream *s, int bytes)
223 {
224 while (true) {
225 struct blob_attr *a;
226 int len, cur_len;
227
228 a = (void*) ustream_get_read_buf(s, &len);
229 if (len < sizeof(*a))
230 break;
231
232 cur_len = blob_len(a) + sizeof(*a);
233 if (len < cur_len)
234 break;
235
236 log_notify(a);
237 ustream_consume(s, cur_len);
238 }
239 if (!log_follow)
240 uloop_end();
241 }
242
243 static void logread_fd_cb(struct ubus_request *req, int fd)
244 {
245 static struct ustream_fd test_fd;
246
247 test_fd.stream.notify_read = logread_fd_data_cb;
248 ustream_fd_init(&test_fd, fd);
249 }
250
251 int main(int argc, char **argv)
252 {
253 static struct ubus_request req;
254 struct ubus_context *ctx;
255 uint32_t id;
256 const char *ubus_socket = NULL;
257 int ch, ret, lines = 0;
258 static struct blob_buf b;
259 int tries = 5;
260
261 signal(SIGPIPE, SIG_IGN);
262
263 while ((ch = getopt(argc, argv, "u0fcs:l:r:F:p:S:P:h:e:t")) != -1) {
264 switch (ch) {
265 case 'u':
266 log_udp = 1;
267 break;
268 case '0':
269 log_trailer_null = 1;
270 break;
271 case 's':
272 ubus_socket = optarg;
273 break;
274 case 'r':
275 log_ip = optarg++;
276 log_port = argv[optind++];
277 break;
278 case 'F':
279 log_file = optarg;
280 break;
281 case 'p':
282 pid_file = optarg;
283 break;
284 case 'P':
285 log_prefix = optarg;
286 break;
287 case 'f':
288 log_follow = 1;
289 break;
290 case 'l':
291 lines = atoi(optarg);
292 break;
293 case 'S':
294 log_size = atoi(optarg);
295 if (log_size < 1)
296 log_size = 1;
297 log_size *= 1024;
298 break;
299 case 'h':
300 hostname = optarg;
301 break;
302 case 'e':
303 if (!regcomp(&regexp_preg, optarg, REG_NOSUB)) {
304 regexp_pattern = optarg;
305 }
306 break;
307 case 't':
308 log_timestamp = 1;
309 break;
310 default:
311 return usage(*argv);
312 }
313 }
314 uloop_init();
315
316 ctx = ubus_connect(ubus_socket);
317 if (!ctx) {
318 fprintf(stderr, "Failed to connect to ubus\n");
319 return -1;
320 }
321 ubus_add_uloop(ctx);
322
323 /* ugly ugly ugly ... we need a real reconnect logic */
324 do {
325 ret = ubus_lookup_id(ctx, "log", &id);
326 if (ret) {
327 fprintf(stderr, "Failed to find log object: %s\n", ubus_strerror(ret));
328 sleep(1);
329 continue;
330 }
331
332 blob_buf_init(&b, 0);
333 blobmsg_add_u8(&b, "stream", 1);
334 if (lines)
335 blobmsg_add_u32(&b, "lines", lines);
336 else if (log_follow)
337 blobmsg_add_u32(&b, "lines", 0);
338 if (log_follow) {
339 if (pid_file) {
340 FILE *fp = fopen(pid_file, "w+");
341 if (fp) {
342 fprintf(fp, "%d", getpid());
343 fclose(fp);
344 }
345 }
346 }
347
348 if (log_ip && log_port) {
349 openlog("logread", LOG_PID, LOG_DAEMON);
350 log_type = LOG_NET;
351 sender.cb = log_handle_fd;
352 retry.cb = log_handle_reconnect;
353 uloop_timeout_set(&retry, 1000);
354 } else if (log_file) {
355 log_type = LOG_FILE;
356 sender.fd = open(log_file, O_CREAT | O_WRONLY| O_APPEND, 0600);
357 if (sender.fd < 0) {
358 fprintf(stderr, "failed to open %s: %s\n", log_file, strerror(errno));
359 exit(-1);
360 }
361 } else {
362 sender.fd = STDOUT_FILENO;
363 }
364
365 ubus_invoke_async(ctx, id, "read", b.head, &req);
366 req.fd_cb = logread_fd_cb;
367 ubus_complete_request_async(ctx, &req);
368
369 uloop_run();
370 ubus_free(ctx);
371 uloop_done();
372
373 } while (ret && tries--);
374
375 return ret;
376 }