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