extend logread
[project/procd.git] / 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
33 enum {
34         LOG_STDOUT,
35         LOG_FILE,
36         LOG_NET,
37 };
38
39 enum {
40         LOG_MSG,
41         LOG_ID,
42         LOG_PRIO,
43         LOG_SOURCE,
44         LOG_TIME,
45         __LOG_MAX
46 };
47
48 static const struct blobmsg_policy log_policy[] = {
49         [LOG_MSG] = { .name = "msg", .type = BLOBMSG_TYPE_STRING },
50         [LOG_ID] = { .name = "id", .type = BLOBMSG_TYPE_INT32 },
51         [LOG_PRIO] = { .name = "priority", .type = BLOBMSG_TYPE_INT32 },
52         [LOG_SOURCE] = { .name = "source", .type = BLOBMSG_TYPE_INT32 },
53         [LOG_TIME] = { .name = "time", .type = BLOBMSG_TYPE_INT64 },
54 };
55
56 static struct ubus_subscriber log_event;
57 static struct uloop_timeout retry;
58 static struct uloop_fd sender;
59 static const char *log_file, *log_ip, *log_port, *pid_file;
60 static int log_type = LOG_STDOUT;
61 static int log_size;
62
63 static void log_handle_reconnect(struct uloop_timeout *timeout)
64 {
65         sender.fd = usock(USOCK_TCP | USOCK_NUMERIC, log_ip, log_port);
66         if (sender.fd < 0) {
67                 fprintf(stderr, "failed to connect: %s\n", strerror(errno));
68                 uloop_timeout_set(&retry, 1000);
69         } else {
70                 uloop_fd_add(&sender, ULOOP_READ);
71                 syslog(0, "Logread connected to %s:%s\n", log_ip, log_port);
72         }
73 }
74
75 static void log_handle_remove(struct ubus_context *ctx, struct ubus_subscriber *s,
76                         uint32_t id)
77 {
78         fprintf(stderr, "Object %08x went away\n", id);
79 }
80
81 static void log_handle_fd(struct uloop_fd *u, unsigned int events)
82 {
83         if (u->eof) {
84                 uloop_fd_delete(u);
85                 close(sender.fd);
86                 sender.fd = -1;
87                 uloop_timeout_set(&retry, 1000);
88         }
89 }
90
91 static int log_notify(struct ubus_context *ctx, struct ubus_object *obj,
92                         struct ubus_request_data *req, const char *method,
93                         struct blob_attr *msg)
94 {
95         struct blob_attr *tb[__LOG_MAX];
96         struct stat s;
97         char buf[256];
98         uint32_t p;
99         char *str;
100         time_t t;
101         char *c;
102
103         if (sender.fd < 0)
104                 return 0;
105
106         blobmsg_parse(log_policy, ARRAY_SIZE(log_policy), tb, blob_data(msg), blob_len(msg));
107         if (!tb[LOG_ID] || !tb[LOG_PRIO] || !tb[LOG_SOURCE] || !tb[LOG_TIME])
108                 return 1;
109
110         if ((log_type == LOG_FILE) && log_size && (!stat(log_file, &s)) && (s.st_size > log_size)) {
111                 char *old = malloc(strlen(log_file) + 5);
112
113                 close(sender.fd);
114                 if (old) {
115                         sprintf(old, "%s.old", log_file);
116                         rename(log_file, old);
117                         free(old);
118                 }
119                 sender.fd = open(log_file, O_CREAT | O_WRONLY | O_TRUNC);
120                 if (sender.fd < 0) {
121 //                      fprintf(stderr, "failed to open %s: %s\n", log_file, strerror(errno));
122                         exit(-1);
123                 }
124         }
125
126         t = blobmsg_get_u64(tb[LOG_TIME]) / 1000;
127         c = ctime(&t);
128         p = blobmsg_get_u32(tb[LOG_PRIO]);
129         c[strlen(c) - 1] = '\0';
130         str = blobmsg_format_json(msg, true);
131         snprintf(buf, sizeof(buf), "%s %s.%s%s %s\n",
132                 c, facilitynames[LOG_FAC(p)].c_name, prioritynames[LOG_PRI(p)].c_name,
133                 (blobmsg_get_u32(tb[LOG_SOURCE])) ? ("") : (" kernel:"),
134                 method);
135         if (log_type == LOG_NET)
136                 send(sender.fd, buf, strlen(buf), 0);
137         else
138                 write(sender.fd, buf, strlen(buf));
139
140         free(str);
141         if (log_type == LOG_FILE)
142                 fsync(sender.fd);
143
144         return 0;
145 }
146
147 static void follow_log(struct ubus_context *ctx, int id)
148 {
149         FILE *fp;
150         int ret;
151
152         signal(SIGPIPE, SIG_IGN);
153
154         if (pid_file) {
155                 fp = fopen(pid_file, "w+");
156                 if (fp) {
157                         fprintf(fp, "%d", getpid());
158                         fclose(fp);
159                 }
160         }
161
162         uloop_init();
163         ubus_add_uloop(ctx);
164
165         log_event.remove_cb = log_handle_remove;
166         log_event.cb = log_notify;
167         ret = ubus_register_subscriber(ctx, &log_event);
168         if (ret)
169                 fprintf(stderr, "Failed to add watch handler: %s\n", ubus_strerror(ret));
170
171         ret = ubus_subscribe(ctx, &log_event, id);
172         if (ret)
173                 fprintf(stderr, "Failed to add watch handler: %s\n", ubus_strerror(ret));
174
175         if (log_ip && log_port) {
176                 openlog("logread", LOG_PID, LOG_DAEMON);
177                 log_type = LOG_NET;
178                 sender.cb = log_handle_fd;
179                 retry.cb = log_handle_reconnect;
180                 uloop_timeout_set(&retry, 1000);
181         } else if (log_file) {
182                 log_type = LOG_FILE;
183                 sender.fd = open(log_file, O_CREAT | O_WRONLY);
184                 if (sender.fd < 0) {
185                         fprintf(stderr, "failed to open %s: %s\n", log_file, strerror(errno));
186                         exit(-1);
187                 }
188         } else {
189                 sender.fd = STDOUT_FILENO;
190         }
191
192         uloop_run();
193         ubus_free(ctx);
194         uloop_done();
195 }
196
197 enum {
198         READ_LINE,
199         __READ_MAX
200 };
201
202 static const struct blobmsg_policy read_policy[] = {
203         [READ_LINE] = { .name = "lines", .type = BLOBMSG_TYPE_ARRAY },
204 };
205
206 static void read_cb(struct ubus_request *req, int type, struct blob_attr *msg)
207 {
208         struct blob_attr *cur;
209         struct blob_attr *_tb[__READ_MAX];
210         time_t t;
211         int rem;
212
213         if (!msg)
214                 return;
215
216         blobmsg_parse(read_policy, ARRAY_SIZE(read_policy), _tb, blob_data(msg), blob_len(msg));
217         if (!_tb[READ_LINE])
218                 return;
219         blobmsg_for_each_attr(cur, _tb[READ_LINE], rem) {
220                 struct blob_attr *tb[__LOG_MAX];
221                 uint32_t p;
222                 char *c;
223
224                 if (blobmsg_type(cur) != BLOBMSG_TYPE_TABLE)
225                         continue;
226
227                 blobmsg_parse(log_policy, ARRAY_SIZE(log_policy), tb, blobmsg_data(cur), blobmsg_data_len(cur));
228                 if (!tb[LOG_MSG] || !tb[LOG_ID] || !tb[LOG_PRIO] || !tb[LOG_SOURCE] || !tb[LOG_TIME])
229                         continue;
230
231                 t = blobmsg_get_u64(tb[LOG_TIME]);
232                 p = blobmsg_get_u32(tb[LOG_PRIO]);
233                 c = ctime(&t);
234                 c[strlen(c) - 1] = '\0';
235
236                 printf("%s %s.%s%s %s\n",
237                         c, facilitynames[LOG_FAC(p)].c_name, prioritynames[LOG_PRI(p)].c_name,
238                         (blobmsg_get_u32(tb[LOG_SOURCE])) ? ("") : (" kernel:"),
239                         blobmsg_get_string(tb[LOG_MSG]));
240         }
241 }
242
243 static int usage(const char *prog)
244 {
245         fprintf(stderr, "Usage: %s [options]\n"
246                 "Options:\n"
247                 "    -s <path>          Path to ubus socket\n"
248                 "    -l <count>         Got only the last 'count' messages\n"
249                 "    -r <server> <port> Stream message to a server\n"
250                 "    -F <file>          Log file\n"
251                 "    -S <bytes>         Log size\n"
252                 "    -p <file>          PID file\n"
253                 "    -f                 Follow log messages\n"
254                 "\n", prog);
255         return 1;
256 }
257
258 int main(int argc, char **argv)
259 {
260         struct ubus_context *ctx;
261         uint32_t id;
262         const char *ubus_socket = NULL;
263         int ch, ret, subscribe = 0, lines = 0;
264         static struct blob_buf b;
265
266         while ((ch = getopt(argc, argv, "fcs:l:r:F:p:S:")) != -1) {
267                 switch (ch) {
268                 case 's':
269                         ubus_socket = optarg;
270                         break;
271                 case 'r':
272                         log_ip = optarg++;
273                         log_port = argv[optind++];
274                         break;
275                 case 'F':
276                         log_file = optarg;
277                         break;
278                 case 'p':
279                         pid_file = optarg;
280                         break;
281                 case 'f':
282                         subscribe = 1;
283                         break;
284                 case 'l':
285                         lines = atoi(optarg);
286                         break;
287                 case 'S':
288                         log_size = atoi(optarg);
289                         if (log_size < 1)
290                                 log_size = 1;
291                         log_size *= 1024;
292                         break;
293                 default:
294                         return usage(*argv);
295                 }
296         }
297
298         ctx = ubus_connect(ubus_socket);
299         if (!ctx) {
300                 fprintf(stderr, "Failed to connect to ubus\n");
301                 return -1;
302         }
303
304         ret = ubus_lookup_id(ctx, "log", &id);
305         if (ret)
306                 fprintf(stderr, "Failed to find log object: %s\n", ubus_strerror(ret));
307
308         if (!subscribe || lines) {
309                 blob_buf_init(&b, 0);
310                 if (lines)
311                         blobmsg_add_u32(&b, "lines", lines);
312                 ubus_invoke(ctx, id, "read", b.head, read_cb, 0, 3000);
313         }
314
315         if (subscribe)
316                 follow_log(ctx, id);
317
318         return 0;
319 }