logread: fix initial connect. we really need a better reconnect 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 <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/blobmsg_json.h>
29 #include <libubox/usock.h>
30 #include <libubox/uloop.h>
31 #include "libubus.h"
32 #include "syslog.h"
33
34 enum {
35 LOG_STDOUT,
36 LOG_FILE,
37 LOG_NET,
38 };
39
40 enum {
41 LOG_MSG,
42 LOG_ID,
43 LOG_PRIO,
44 LOG_SOURCE,
45 LOG_TIME,
46 __LOG_MAX
47 };
48
49 static const struct blobmsg_policy log_policy[] = {
50 [LOG_MSG] = { .name = "msg", .type = BLOBMSG_TYPE_STRING },
51 [LOG_ID] = { .name = "id", .type = BLOBMSG_TYPE_INT32 },
52 [LOG_PRIO] = { .name = "priority", .type = BLOBMSG_TYPE_INT32 },
53 [LOG_SOURCE] = { .name = "source", .type = BLOBMSG_TYPE_INT32 },
54 [LOG_TIME] = { .name = "time", .type = BLOBMSG_TYPE_INT64 },
55 };
56
57 static struct ubus_subscriber log_event;
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;
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_remove(struct ubus_context *ctx, struct ubus_subscriber *s,
87 uint32_t id)
88 {
89 fprintf(stderr, "Object %08x went away\n", id);
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 ubus_context *ctx, struct ubus_object *obj,
103 struct ubus_request_data *req, const char *method,
104 struct blob_attr *msg)
105 {
106 struct blob_attr *tb[__LOG_MAX];
107 struct stat s;
108 char buf[512];
109 uint32_t p;
110 char *str;
111 time_t t;
112 char *c;
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])
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: %s\n", log_file, strerror(errno));
133 exit(-1);
134 }
135 }
136
137 t = blobmsg_get_u64(tb[LOG_TIME]) / 1000;
138 c = ctime(&t);
139 p = blobmsg_get_u32(tb[LOG_PRIO]);
140 c[strlen(c) - 1] = '\0';
141 str = blobmsg_format_json(msg, true);
142 if (log_type == LOG_NET) {
143 int err;
144
145 *buf = '\0';
146 if (hostname)
147 snprintf(buf, sizeof(buf), "%s ", hostname);
148 if (log_prefix) {
149 strncat(buf, log_prefix, sizeof(buf));
150 strncat(buf, ": ", sizeof(buf));
151 }
152 if (blobmsg_get_u32(tb[LOG_SOURCE]) == SOURCE_KLOG)
153 strncat(buf, "kernel: ", sizeof(buf));
154 strncat(buf, method, sizeof(buf));
155 if (log_udp)
156 err = write(sender.fd, buf, strlen(buf));
157 else
158 err = send(sender.fd, buf, strlen(buf), 0);
159
160 if (err < 0) {
161 syslog(0, "failed to send log data to %s:%s via %s\n",
162 log_ip, log_port, (log_udp) ? ("udp") : ("tcp"));
163 uloop_fd_delete(&sender);
164 close(sender.fd);
165 sender.fd = -1;
166 uloop_timeout_set(&retry, 1000);
167 }
168 } else {
169 snprintf(buf, sizeof(buf), "%s %s.%s%s %s\n",
170 c, getcodetext(LOG_FAC(p) << 3, facilitynames), getcodetext(LOG_PRI(p), prioritynames),
171 (blobmsg_get_u32(tb[LOG_SOURCE])) ? ("") : (" kernel:"),
172 method);
173 write(sender.fd, buf, strlen(buf));
174 }
175
176 free(str);
177 if (log_type == LOG_FILE)
178 fsync(sender.fd);
179
180 return 0;
181 }
182
183 static void follow_log(struct ubus_context *ctx, int id)
184 {
185 FILE *fp;
186 int ret;
187
188 signal(SIGPIPE, SIG_IGN);
189
190 if (pid_file) {
191 fp = fopen(pid_file, "w+");
192 if (fp) {
193 fprintf(fp, "%d", getpid());
194 fclose(fp);
195 }
196 }
197
198 uloop_init();
199 ubus_add_uloop(ctx);
200
201 log_event.remove_cb = log_handle_remove;
202 log_event.cb = log_notify;
203 ret = ubus_register_subscriber(ctx, &log_event);
204 if (ret)
205 fprintf(stderr, "Failed to add watch handler: %s\n", ubus_strerror(ret));
206
207 ret = ubus_subscribe(ctx, &log_event, id);
208 if (ret)
209 fprintf(stderr, "Failed to add watch handler: %s\n", ubus_strerror(ret));
210
211 if (log_ip && log_port) {
212 openlog("logread", LOG_PID, LOG_DAEMON);
213 log_type = LOG_NET;
214 sender.cb = log_handle_fd;
215 retry.cb = log_handle_reconnect;
216 uloop_timeout_set(&retry, 1000);
217 } else if (log_file) {
218 log_type = LOG_FILE;
219 sender.fd = open(log_file, O_CREAT | O_WRONLY| O_APPEND, 0600);
220 if (sender.fd < 0) {
221 fprintf(stderr, "failed to open %s: %s\n", log_file, strerror(errno));
222 exit(-1);
223 }
224 } else {
225 sender.fd = STDOUT_FILENO;
226 }
227
228 uloop_run();
229 ubus_free(ctx);
230 uloop_done();
231 }
232
233 enum {
234 READ_LINE,
235 __READ_MAX
236 };
237
238
239
240 static const struct blobmsg_policy read_policy[] = {
241 [READ_LINE] = { .name = "lines", .type = BLOBMSG_TYPE_ARRAY },
242 };
243
244 static void read_cb(struct ubus_request *req, int type, struct blob_attr *msg)
245 {
246 struct blob_attr *cur;
247 struct blob_attr *_tb[__READ_MAX];
248 time_t t;
249 int rem;
250
251 if (!msg)
252 return;
253
254 blobmsg_parse(read_policy, ARRAY_SIZE(read_policy), _tb, blob_data(msg), blob_len(msg));
255 if (!_tb[READ_LINE])
256 return;
257 blobmsg_for_each_attr(cur, _tb[READ_LINE], rem) {
258 struct blob_attr *tb[__LOG_MAX];
259 uint32_t p;
260 char *c;
261
262 if (blobmsg_type(cur) != BLOBMSG_TYPE_TABLE)
263 continue;
264
265 blobmsg_parse(log_policy, ARRAY_SIZE(log_policy), tb, blobmsg_data(cur), blobmsg_data_len(cur));
266 if (!tb[LOG_MSG] || !tb[LOG_ID] || !tb[LOG_PRIO] || !tb[LOG_SOURCE] || !tb[LOG_TIME])
267 continue;
268
269 t = blobmsg_get_u64(tb[LOG_TIME]);
270 p = blobmsg_get_u32(tb[LOG_PRIO]);
271 c = ctime(&t);
272 c[strlen(c) - 1] = '\0';
273
274 printf("%s %s.%s%s %s\n",
275 c, getcodetext(LOG_FAC(p) << 3, facilitynames), getcodetext(LOG_PRI(p), prioritynames),
276 (blobmsg_get_u32(tb[LOG_SOURCE])) ? ("") : (" kernel:"),
277 blobmsg_get_string(tb[LOG_MSG]));
278 }
279 }
280
281 static int usage(const char *prog)
282 {
283 fprintf(stderr, "Usage: %s [options]\n"
284 "Options:\n"
285 " -s <path> Path to ubus socket\n"
286 " -l <count> Got only the last 'count' messages\n"
287 " -r <server> <port> Stream message to a server\n"
288 " -F <file> Log file\n"
289 " -S <bytes> Log size\n"
290 " -p <file> PID file\n"
291 " -h <hostname> Add hostname to the message\n"
292 " -P <prefix> Prefix custom text to streamed messages\n"
293 " -f Follow log messages\n"
294 " -u Use UDP as the protocol\n"
295 "\n", prog);
296 return 1;
297 }
298
299 int main(int argc, char **argv)
300 {
301 struct ubus_context *ctx;
302 uint32_t id;
303 const char *ubus_socket = NULL;
304 int ch, ret, subscribe = 0, lines = 0;
305 static struct blob_buf b;
306 int retry = 5;
307
308 while ((ch = getopt(argc, argv, "ufcs:l:r:F:p:S:P:h:")) != -1) {
309 switch (ch) {
310 case 'u':
311 log_udp = 1;
312 break;
313 case 's':
314 ubus_socket = optarg;
315 break;
316 case 'r':
317 log_ip = optarg++;
318 log_port = argv[optind++];
319 break;
320 case 'F':
321 log_file = optarg;
322 break;
323 case 'p':
324 pid_file = optarg;
325 break;
326 case 'P':
327 log_prefix = optarg;
328 break;
329 case 'f':
330 subscribe = 1;
331 break;
332 case 'l':
333 lines = atoi(optarg);
334 break;
335 case 'S':
336 log_size = atoi(optarg);
337 if (log_size < 1)
338 log_size = 1;
339 log_size *= 1024;
340 break;
341 case 'h':
342 hostname = optarg;
343 break;
344 default:
345 return usage(*argv);
346 }
347 }
348
349 ctx = ubus_connect(ubus_socket);
350 if (!ctx) {
351 fprintf(stderr, "Failed to connect to ubus\n");
352 return -1;
353 }
354
355 /* ugly ugly ugly ... we need a real reconnect logic */
356 do {
357 ret = ubus_lookup_id(ctx, "log", &id);
358 if (ret) {
359 fprintf(stderr, "Failed to find log object: %s\n", ubus_strerror(ret));
360 sleep(1);
361 continue;
362 }
363 if (!subscribe || lines) {
364 blob_buf_init(&b, 0);
365 if (lines)
366 blobmsg_add_u32(&b, "lines", lines);
367 ubus_invoke(ctx, id, "read", b.head, read_cb, 0, 3000);
368 }
369
370 if (subscribe)
371 follow_log(ctx, id);
372 } while (ret && retry--);
373
374 return 0;
375 }