a7ab567a9fa0bbd0f6c4b8072f7e35b9128d332c
[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 <stdio.h>
21 #include <unistd.h>
22 #include <sys/types.h>
23 #include <sys/socket.h>
24
25 #define SYSLOG_NAMES
26 #include <syslog.h>
27
28 #include <libubox/ustream.h>
29 #include <libubox/blobmsg_json.h>
30 #include <libubox/usock.h>
31 #include <libubox/uloop.h>
32 #include "libubus.h"
33 #include "syslog.h"
34
35 enum {
36         LOG_STDOUT,
37         LOG_FILE,
38         LOG_NET,
39 };
40
41 enum {
42         LOG_MSG,
43         LOG_ID,
44         LOG_PRIO,
45         LOG_SOURCE,
46         LOG_TIME,
47         __LOG_MAX
48 };
49
50 static const struct blobmsg_policy log_policy[] = {
51         [LOG_MSG] = { .name = "msg", .type = BLOBMSG_TYPE_STRING },
52         [LOG_ID] = { .name = "id", .type = BLOBMSG_TYPE_INT32 },
53         [LOG_PRIO] = { .name = "priority", .type = BLOBMSG_TYPE_INT32 },
54         [LOG_SOURCE] = { .name = "source", .type = BLOBMSG_TYPE_INT32 },
55         [LOG_TIME] = { .name = "time", .type = BLOBMSG_TYPE_INT64 },
56 };
57
58 static struct uloop_timeout retry;
59 static struct uloop_fd sender;
60 static const char *log_file, *log_ip, *log_port, *log_prefix, *pid_file, *hostname;
61 static int log_type = LOG_STDOUT;
62 static int log_size, log_udp, log_follow = 0;
63
64 static const char* getcodetext(int value, CODE *codetable) {
65         CODE *i;
66
67         if (value >= 0)
68                 for (i = codetable; i->c_val != -1; i++)
69                         if (i->c_val == value)
70                                 return (i->c_name);
71         return "<unknown>";
72 };
73
74 static void log_handle_reconnect(struct uloop_timeout *timeout)
75 {
76         sender.fd = usock((log_udp) ? (USOCK_UDP) : (USOCK_TCP), log_ip, log_port);
77         if (sender.fd < 0) {
78                 fprintf(stderr, "failed to connect: %s\n", strerror(errno));
79                 uloop_timeout_set(&retry, 1000);
80         } else {
81                 uloop_fd_add(&sender, ULOOP_READ);
82                 syslog(0, "Logread connected to %s:%s\n", log_ip, log_port);
83         }
84 }
85
86 static void log_handle_fd(struct uloop_fd *u, unsigned int events)
87 {
88         if (u->eof) {
89                 uloop_fd_delete(u);
90                 close(sender.fd);
91                 sender.fd = -1;
92                 uloop_timeout_set(&retry, 1000);
93         }
94 }
95
96 static int log_notify(struct blob_attr *msg)
97 {
98         struct blob_attr *tb[__LOG_MAX];
99         struct stat s;
100         char buf[512];
101         uint32_t p;
102         char *str;
103         time_t t;
104         char *c, *m;
105
106         if (sender.fd < 0)
107                 return 0;
108
109         blobmsg_parse(log_policy, ARRAY_SIZE(log_policy), tb, blob_data(msg), blob_len(msg));
110         if (!tb[LOG_ID] || !tb[LOG_PRIO] || !tb[LOG_SOURCE] || !tb[LOG_TIME] || !tb[LOG_MSG])
111                 return 1;
112
113         if ((log_type == LOG_FILE) && log_size && (!stat(log_file, &s)) && (s.st_size > log_size)) {
114                 char *old = malloc(strlen(log_file) + 5);
115
116                 close(sender.fd);
117                 if (old) {
118                         sprintf(old, "%s.old", log_file);
119                         rename(log_file, old);
120                         free(old);
121                 }
122                 sender.fd = open(log_file, O_CREAT | O_WRONLY | O_APPEND, 0600);
123                 if (sender.fd < 0) {
124                         fprintf(stderr, "failed to open %s: %s\n", log_file, strerror(errno));
125                         exit(-1);
126                 }
127         }
128
129         m = blobmsg_get_string(tb[LOG_MSG]);
130         t = blobmsg_get_u64(tb[LOG_TIME]) / 1000;
131         c = ctime(&t);
132         p = blobmsg_get_u32(tb[LOG_PRIO]);
133         c[strlen(c) - 1] = '\0';
134         str = blobmsg_format_json(msg, true);
135         if (log_type == LOG_NET) {
136                 int err;
137
138                 snprintf(buf, sizeof(buf), "<%u>", p);
139                 strncat(buf, c + 4, 16);
140                 if (hostname) {
141                         strncat(buf, hostname, sizeof(buf));
142                         strncat(buf, " ", sizeof(buf));
143                 }
144                 if (log_prefix) {
145                         strncat(buf, log_prefix, sizeof(buf));
146                         strncat(buf, ": ", sizeof(buf));
147                 }
148                 if (blobmsg_get_u32(tb[LOG_SOURCE]) == SOURCE_KLOG)
149                         strncat(buf, "kernel: ", sizeof(buf));
150                 strncat(buf, m, sizeof(buf));
151                 if (log_udp)
152                         err = write(sender.fd, buf, strlen(buf));
153                 else
154                         err = send(sender.fd, buf, strlen(buf), 0);
155
156                 if (err < 0) {
157                         syslog(0, "failed to send log data to %s:%s via %s\n",
158                                 log_ip, log_port, (log_udp) ? ("udp") : ("tcp"));
159                         uloop_fd_delete(&sender);
160                         close(sender.fd);
161                         sender.fd = -1;
162                         uloop_timeout_set(&retry, 1000);
163                 }
164         } else {
165                 snprintf(buf, sizeof(buf), "%s %s.%s%s %s\n",
166                         c, getcodetext(LOG_FAC(p) << 3, facilitynames), getcodetext(LOG_PRI(p), prioritynames),
167                         (blobmsg_get_u32(tb[LOG_SOURCE])) ? ("") : (" kernel:"), m);
168                 write(sender.fd, buf, strlen(buf));
169         }
170
171         free(str);
172         if (log_type == LOG_FILE)
173                 fsync(sender.fd);
174
175         return 0;
176 }
177
178 static int usage(const char *prog)
179 {
180         fprintf(stderr, "Usage: %s [options]\n"
181                 "Options:\n"
182                 "    -s <path>          Path to ubus socket\n"
183                 "    -l <count>         Got only the last 'count' messages\n"
184                 "    -r <server> <port> Stream message to a server\n"
185                 "    -F <file>          Log file\n"
186                 "    -S <bytes>         Log size\n"
187                 "    -p <file>          PID file\n"
188                 "    -h <hostname>      Add hostname to the message\n"
189                 "    -P <prefix>        Prefix custom text to streamed messages\n"
190                 "    -f                 Follow log messages\n"
191                 "    -u                 Use UDP as the protocol\n"
192                 "\n", prog);
193         return 1;
194 }
195
196 static void logread_fd_data_cb(struct ustream *s, int bytes)
197 {
198         while (true) {
199                 int len;
200                 struct blob_attr *a;
201
202                 a = (void*) ustream_get_read_buf(s, &len);
203                 if (len < sizeof(*a) || len < blob_len(a) + sizeof(*a))
204                         break;
205                 log_notify(a);
206                 ustream_consume(s, blob_len(a) + sizeof(*a));
207         }
208         if (!log_follow)
209                 uloop_end();
210 }
211
212 static void logread_fd_cb(struct ubus_request *req, int fd)
213 {
214         static struct ustream_fd test_fd;
215
216         test_fd.stream.notify_read = logread_fd_data_cb;
217         ustream_fd_init(&test_fd, fd);
218 }
219
220 static void logread_complete_cb(struct ubus_request *req, int ret)
221 {
222 }
223
224 int main(int argc, char **argv)
225 {
226         static struct ubus_request req;
227         struct ubus_context *ctx;
228         uint32_t id;
229         const char *ubus_socket = NULL;
230         int ch, ret, lines = 0;
231         static struct blob_buf b;
232         int tries = 5;
233
234         signal(SIGPIPE, SIG_IGN);
235
236         while ((ch = getopt(argc, argv, "ufcs:l:r:F:p:S:P:h:")) != -1) {
237                 switch (ch) {
238                 case 'u':
239                         log_udp = 1;
240                         break;
241                 case 's':
242                         ubus_socket = optarg;
243                         break;
244                 case 'r':
245                         log_ip = optarg++;
246                         log_port = argv[optind++];
247                         break;
248                 case 'F':
249                         log_file = optarg;
250                         break;
251                 case 'p':
252                         pid_file = optarg;
253                         break;
254                 case 'P':
255                         log_prefix = optarg;
256                         break;
257                 case 'f':
258                         log_follow = 1;
259                         break;
260                 case 'l':
261                         lines = atoi(optarg);
262                         break;
263                 case 'S':
264                         log_size = atoi(optarg);
265                         if (log_size < 1)
266                                 log_size = 1;
267                         log_size *= 1024;
268                         break;
269                 case 'h':
270                         hostname = optarg;
271                         break;
272                 default:
273                         return usage(*argv);
274                 }
275         }
276         uloop_init();
277
278         ctx = ubus_connect(ubus_socket);
279         if (!ctx) {
280                 fprintf(stderr, "Failed to connect to ubus\n");
281                 return -1;
282         }
283         ubus_add_uloop(ctx);
284
285         /* ugly ugly ugly ... we need a real reconnect logic */
286         do {
287                 ret = ubus_lookup_id(ctx, "log", &id);
288                 if (ret) {
289                         fprintf(stderr, "Failed to find log object: %s\n", ubus_strerror(ret));
290                         sleep(1);
291                         continue;
292                 }
293
294                 blob_buf_init(&b, 0);
295                 if (lines)
296                         blobmsg_add_u32(&b, "lines", lines);
297                 else if (log_follow)
298                         blobmsg_add_u32(&b, "lines", 0);
299                 if (log_follow) {
300                         if (pid_file) {
301                                 FILE *fp = fopen(pid_file, "w+");
302                                 if (fp) {
303                                         fprintf(fp, "%d", getpid());
304                                         fclose(fp);
305                                 }
306                         }
307                 }
308
309                 if (log_ip && log_port) {
310                         openlog("logread", LOG_PID, LOG_DAEMON);
311                         log_type = LOG_NET;
312                         sender.cb = log_handle_fd;
313                         retry.cb = log_handle_reconnect;
314                         uloop_timeout_set(&retry, 1000);
315                 } else if (log_file) {
316                         log_type = LOG_FILE;
317                         sender.fd = open(log_file, O_CREAT | O_WRONLY| O_APPEND, 0600);
318                         if (sender.fd < 0) {
319                                 fprintf(stderr, "failed to open %s: %s\n", log_file, strerror(errno));
320                                 exit(-1);
321                         }
322                 } else {
323                         sender.fd = STDOUT_FILENO;
324                 }
325
326                 ubus_invoke_async(ctx, id, "read", b.head, &req);
327                 req.fd_cb = logread_fd_cb;
328                 req.complete_cb = logread_complete_cb;
329                 ubus_complete_request_async(ctx, &req);
330
331                 uloop_run();
332                 ubus_free(ctx);
333                 uloop_done();
334
335         } while (ret && tries--);
336
337         return ret;
338 }