logd: implement oneshot mode for stream log read
[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_state_cb(struct ustream *s)
244 {
245         uloop_end();
246 }
247
248 static void logread_fd_cb(struct ubus_request *req, int fd)
249 {
250         static struct ustream_fd test_fd;
251
252         test_fd.stream.notify_read = logread_fd_data_cb;
253         test_fd.stream.notify_state = logread_fd_state_cb;
254         ustream_fd_init(&test_fd, fd);
255 }
256
257 int main(int argc, char **argv)
258 {
259         static struct ubus_request req;
260         struct ubus_context *ctx;
261         uint32_t id;
262         const char *ubus_socket = NULL;
263         int ch, ret, lines = 0;
264         static struct blob_buf b;
265         int tries = 5;
266
267         signal(SIGPIPE, SIG_IGN);
268
269         while ((ch = getopt(argc, argv, "u0fcs:l:r:F:p:S:P:h:e:t")) != -1) {
270                 switch (ch) {
271                 case 'u':
272                         log_udp = 1;
273                         break;
274                 case '0':
275                         log_trailer_null = 1;
276                         break;
277                 case 's':
278                         ubus_socket = optarg;
279                         break;
280                 case 'r':
281                         log_ip = optarg++;
282                         log_port = argv[optind++];
283                         break;
284                 case 'F':
285                         log_file = optarg;
286                         break;
287                 case 'p':
288                         pid_file = optarg;
289                         break;
290                 case 'P':
291                         log_prefix = optarg;
292                         break;
293                 case 'f':
294                         log_follow = 1;
295                         break;
296                 case 'l':
297                         lines = atoi(optarg);
298                         break;
299                 case 'S':
300                         log_size = atoi(optarg);
301                         if (log_size < 1)
302                                 log_size = 1;
303                         log_size *= 1024;
304                         break;
305                 case 'h':
306                         hostname = optarg;
307                         break;
308                 case 'e':
309                         if (!regcomp(&regexp_preg, optarg, REG_NOSUB)) {
310                                 regexp_pattern = optarg;
311                         }
312                         break;
313                 case 't':
314                         log_timestamp = 1;
315                         break;
316                 default:
317                         return usage(*argv);
318                 }
319         }
320         uloop_init();
321
322         ctx = ubus_connect(ubus_socket);
323         if (!ctx) {
324                 fprintf(stderr, "Failed to connect to ubus\n");
325                 return -1;
326         }
327         ubus_add_uloop(ctx);
328
329         /* ugly ugly ugly ... we need a real reconnect logic */
330         do {
331                 ret = ubus_lookup_id(ctx, "log", &id);
332                 if (ret) {
333                         fprintf(stderr, "Failed to find log object: %s\n", ubus_strerror(ret));
334                         sleep(1);
335                         continue;
336                 }
337
338                 blob_buf_init(&b, 0);
339                 blobmsg_add_u8(&b, "stream", 1);
340                 if (lines)
341                         blobmsg_add_u32(&b, "lines", lines);
342                 else if (log_follow)
343                         blobmsg_add_u32(&b, "lines", 0);
344                 if (log_follow) {
345                         if (pid_file) {
346                                 FILE *fp = fopen(pid_file, "w+");
347                                 if (fp) {
348                                         fprintf(fp, "%d", getpid());
349                                         fclose(fp);
350                                 }
351                         }
352                 }
353
354                 if (log_ip && log_port) {
355                         openlog("logread", LOG_PID, LOG_DAEMON);
356                         log_type = LOG_NET;
357                         sender.cb = log_handle_fd;
358                         retry.cb = log_handle_reconnect;
359                         uloop_timeout_set(&retry, 1000);
360                 } else if (log_file) {
361                         log_type = LOG_FILE;
362                         sender.fd = open(log_file, O_CREAT | O_WRONLY| O_APPEND, 0600);
363                         if (sender.fd < 0) {
364                                 fprintf(stderr, "failed to open %s: %s\n", log_file, strerror(errno));
365                                 exit(-1);
366                         }
367                 } else {
368                         sender.fd = STDOUT_FILENO;
369                 }
370
371                 ubus_invoke_async(ctx, id, "read", b.head, &req);
372                 req.fd_cb = logread_fd_cb;
373                 ubus_complete_request_async(ctx, &req);
374
375                 uloop_run();
376                 ubus_free(ctx);
377                 uloop_done();
378
379         } while (ret && tries--);
380
381         return ret;
382 }