chiark / gitweb /
journal: add output mode that just prints simple messages without any decorations
[elogind.git] / src / logs-show.c
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
2
3 /***
4   This file is part of systemd.
5
6   Copyright 2012 Lennart Poettering
7
8   systemd is free software; you can redistribute it and/or modify it
9   under the terms of the GNU General Public License as published by
10   the Free Software Foundation; either version 2 of the License, or
11   (at your option) any later version.
12
13   systemd is distributed in the hope that it will be useful, but
14   WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16   General Public License for more details.
17
18   You should have received a copy of the GNU General Public License
19   along with systemd; If not, see <http://www.gnu.org/licenses/>.
20 ***/
21
22 #include <time.h>
23 #include <assert.h>
24 #include <errno.h>
25 #include <sys/poll.h>
26 #include <string.h>
27
28 #include "logs-show.h"
29 #include "log.h"
30 #include "util.h"
31
32 #define PRINT_THRESHOLD 128
33
34 static bool contains_unprintable(const void *p, size_t l) {
35         const char *j;
36
37         for (j = p; j < (const char *) p + l; j++)
38                 if (*j < ' ' || *j >= 127)
39                         return true;
40
41         return false;
42 }
43
44 static int parse_field(const void *data, size_t length, const char *field, char **target, size_t *target_size) {
45         size_t fl, nl;
46         void *buf;
47
48         assert(data);
49         assert(field);
50         assert(target);
51         assert(target_size);
52
53         fl = strlen(field);
54         if (length < fl)
55                 return 0;
56
57         if (memcmp(data, field, fl))
58                 return 0;
59
60         nl = length - fl;
61         buf = malloc(nl+1);
62         memcpy(buf, (const char*) data + fl, nl);
63         ((char*)buf)[nl] = 0;
64         if (!buf) {
65                 log_error("Out of memory");
66                 return -ENOMEM;
67         }
68
69         free(*target);
70         *target = buf;
71         *target_size = nl;
72
73         return 1;
74 }
75
76 static bool shall_print(bool show_all, char *p, size_t l) {
77         if (show_all)
78                 return true;
79
80         if (l > PRINT_THRESHOLD)
81                 return false;
82
83         if (contains_unprintable(p, l))
84                 return false;
85
86         return true;
87 }
88
89 static int output_short(sd_journal *j, unsigned line, bool show_all, bool monotonic_mode) {
90         int r;
91         const void *data;
92         size_t length;
93         size_t n = 0;
94         char *hostname = NULL, *identifier = NULL, *comm = NULL, *pid = NULL, *fake_pid = NULL, *message = NULL, *realtime = NULL, *monotonic = NULL;
95         size_t hostname_len = 0, identifier_len = 0, comm_len = 0, pid_len = 0, fake_pid_len = 0, message_len = 0, realtime_len = 0, monotonic_len = 0;
96
97         assert(j);
98
99         SD_JOURNAL_FOREACH_DATA(j, data, length) {
100
101                 r = parse_field(data, length, "_HOSTNAME=", &hostname, &hostname_len);
102                 if (r < 0)
103                         goto finish;
104                 else if (r > 0)
105                         continue;
106
107                 r = parse_field(data, length, "SYSLOG_IDENTIFIER=", &identifier, &identifier_len);
108                 if (r < 0)
109                         goto finish;
110                 else if (r > 0)
111                         continue;
112
113                 r = parse_field(data, length, "_COMM=", &comm, &comm_len);
114                 if (r < 0)
115                         goto finish;
116                 else if (r > 0)
117                         continue;
118
119                 r = parse_field(data, length, "_PID=", &pid, &pid_len);
120                 if (r < 0)
121                         goto finish;
122                 else if (r > 0)
123                         continue;
124
125                 r = parse_field(data, length, "SYSLOG_PID=", &fake_pid, &fake_pid_len);
126                 if (r < 0)
127                         goto finish;
128                 else if (r > 0)
129                         continue;
130
131                 r = parse_field(data, length, "_SOURCE_REALTIME_TIMESTAMP=", &realtime, &realtime_len);
132                 if (r < 0)
133                         goto finish;
134                 else if (r > 0)
135                         continue;
136
137                 r = parse_field(data, length, "_SOURCE_MONOTONIC_TIMESTAMP=", &monotonic, &monotonic_len);
138                 if (r < 0)
139                         goto finish;
140                 else if (r > 0)
141                         continue;
142
143                 r = parse_field(data, length, "MESSAGE=", &message, &message_len);
144                 if (r < 0)
145                         goto finish;
146         }
147
148         if (!message) {
149                 r = 0;
150                 goto finish;
151         }
152
153         if (monotonic_mode) {
154                 uint64_t t;
155                 sd_id128_t boot_id;
156
157                 r = -ENOENT;
158
159                 if (monotonic)
160                         r = safe_atou64(monotonic, &t);
161
162                 if (r < 0)
163                         r = sd_journal_get_monotonic_usec(j, &t, &boot_id);
164
165                 if (r < 0) {
166                         log_error("Failed to get monotonic: %s", strerror(-r));
167                         goto finish;
168                 }
169
170                 printf("[%5llu.%06llu]",
171                        (unsigned long long) (t / USEC_PER_SEC),
172                        (unsigned long long) (t % USEC_PER_SEC));
173
174                 n += 1 + 5 + 1 + 6 + 1;
175
176         } else {
177                 char buf[64];
178                 uint64_t x;
179                 time_t t;
180                 struct tm tm;
181
182                 r = -ENOENT;
183
184                 if (realtime)
185                         r = safe_atou64(realtime, &x);
186
187                 if (r < 0)
188                         r = sd_journal_get_realtime_usec(j, &x);
189
190                 if (r < 0) {
191                         log_error("Failed to get realtime: %s", strerror(-r));
192                         goto finish;
193                 }
194
195                 t = (time_t) (x / USEC_PER_SEC);
196                 if (strftime(buf, sizeof(buf), "%b %d %H:%M:%S", localtime_r(&t, &tm)) <= 0) {
197                         log_error("Failed to format time.");
198                         goto finish;
199                 }
200
201                 fputs(buf, stdout);
202                 n += strlen(buf);
203         }
204
205         if (hostname && shall_print(show_all, hostname, hostname_len)) {
206                 printf(" %.*s", (int) hostname_len, hostname);
207                 n += hostname_len + 1;
208         }
209
210         if (identifier && shall_print(show_all, identifier, identifier_len)) {
211                 printf(" %.*s", (int) identifier_len, identifier);
212                 n += identifier_len + 1;
213         } else if (comm && shall_print(show_all, comm, comm_len)) {
214                 printf(" %.*s", (int) comm_len, comm);
215                 n += comm_len + 1;
216         }
217
218         if (pid && shall_print(show_all, pid, pid_len)) {
219                 printf("[%.*s]", (int) pid_len, pid);
220                 n += pid_len + 2;
221         } else if (fake_pid && shall_print(show_all, fake_pid, fake_pid_len)) {
222                 printf("[%.*s]", (int) fake_pid_len, fake_pid);
223                 n += fake_pid_len + 2;
224         }
225
226         if (show_all)
227                 printf(": %.*s\n", (int) message_len, message);
228         else if (contains_unprintable(message, message_len))
229                 fputs(": [blob data]\n", stdout);
230         else if (message_len + n < columns())
231                 printf(": %.*s\n", (int) message_len, message);
232         else if (n < columns()) {
233                 char *e;
234
235                 e = ellipsize_mem(message, message_len, columns() - n - 2, 90);
236
237                 if (!e)
238                         printf(": %.*s\n", (int) message_len, message);
239                 else
240                         printf(": %s\n", e);
241
242                 free(e);
243         } else
244                 fputs("\n", stdout);
245
246         r = 0;
247
248 finish:
249         free(hostname);
250         free(identifier);
251         free(comm);
252         free(pid);
253         free(fake_pid);
254         free(message);
255         free(monotonic);
256         free(realtime);
257
258         return r;
259 }
260
261 static int output_short_realtime(sd_journal *j, unsigned line, bool show_all) {
262         return output_short(j, line, show_all, false);
263 }
264
265 static int output_short_monotonic(sd_journal *j, unsigned line, bool show_all) {
266         return output_short(j, line, show_all, true);
267 }
268
269 static int output_verbose(sd_journal *j, unsigned line, bool show_all) {
270         const void *data;
271         size_t length;
272         char *cursor;
273         uint64_t realtime;
274         char ts[FORMAT_TIMESTAMP_MAX];
275         int r;
276
277         assert(j);
278
279         r = sd_journal_get_realtime_usec(j, &realtime);
280         if (r < 0) {
281                 log_error("Failed to get realtime timestamp: %s", strerror(-r));
282                 return r;
283         }
284
285         r = sd_journal_get_cursor(j, &cursor);
286         if (r < 0) {
287                 log_error("Failed to get cursor: %s", strerror(-r));
288                 return r;
289         }
290
291         printf("%s [%s]\n",
292                format_timestamp(ts, sizeof(ts), realtime),
293                cursor);
294
295         free(cursor);
296
297         SD_JOURNAL_FOREACH_DATA(j, data, length) {
298                 if (!show_all && (length > PRINT_THRESHOLD ||
299                                   contains_unprintable(data, length))) {
300                         const char *c;
301
302                         c = memchr(data, '=', length);
303                         if (!c) {
304                                 log_error("Invalid field.");
305                                 return -EINVAL;
306                         }
307
308                         printf("\t%.*s=[blob data]\n",
309                                (int) (c - (const char*) data),
310                                (const char*) data);
311                 } else
312                         printf("\t%.*s\n", (int) length, (const char*) data);
313         }
314
315         return 0;
316 }
317
318 static int output_export(sd_journal *j, unsigned line, bool show_all) {
319         sd_id128_t boot_id;
320         char sid[33];
321         int r;
322         usec_t realtime, monotonic;
323         char *cursor;
324         const void *data;
325         size_t length;
326
327         assert(j);
328
329         r = sd_journal_get_realtime_usec(j, &realtime);
330         if (r < 0) {
331                 log_error("Failed to get realtime timestamp: %s", strerror(-r));
332                 return r;
333         }
334
335         r = sd_journal_get_monotonic_usec(j, &monotonic, &boot_id);
336         if (r < 0) {
337                 log_error("Failed to get monotonic timestamp: %s", strerror(-r));
338                 return r;
339         }
340
341         r = sd_journal_get_cursor(j, &cursor);
342         if (r < 0) {
343                 log_error("Failed to get cursor: %s", strerror(-r));
344                 return r;
345         }
346
347         printf(".cursor=%s\n"
348                ".realtime=%llu\n"
349                ".monotonic=%llu\n"
350                ".boot_id=%s\n",
351                cursor,
352                (unsigned long long) realtime,
353                (unsigned long long) monotonic,
354                sd_id128_to_string(boot_id, sid));
355
356         free(cursor);
357
358         SD_JOURNAL_FOREACH_DATA(j, data, length) {
359
360                 if (contains_unprintable(data, length)) {
361                         const char *c;
362                         uint64_t le64;
363
364                         c = memchr(data, '=', length);
365                         if (!c) {
366                                 log_error("Invalid field.");
367                                 return -EINVAL;
368                         }
369
370                         fwrite(data, c - (const char*) data, 1, stdout);
371                         fputc('\n', stdout);
372                         le64 = htole64(length - (c - (const char*) data) - 1);
373                         fwrite(&le64, sizeof(le64), 1, stdout);
374                         fwrite(c + 1, length - (c - (const char*) data) - 1, 1, stdout);
375                 } else
376                         fwrite(data, length, 1, stdout);
377
378                 fputc('\n', stdout);
379         }
380
381         fputc('\n', stdout);
382
383         return 0;
384 }
385
386 static void json_escape(const char* p, size_t l) {
387
388         if (contains_unprintable(p, l)) {
389                 bool not_first = false;
390
391                 fputs("[ ", stdout);
392
393                 while (l > 0) {
394                         if (not_first)
395                                 printf(", %u", (uint8_t) *p);
396                         else {
397                                 not_first = true;
398                                 printf("%u", (uint8_t) *p);
399                         }
400
401                         p++;
402                         l--;
403                 }
404
405                 fputs(" ]", stdout);
406         } else {
407                 fputc('\"', stdout);
408
409                 while (l > 0) {
410                         if (*p == '"' || *p == '\\') {
411                                 fputc('\\', stdout);
412                                 fputc(*p, stdout);
413                         } else
414                                 fputc(*p, stdout);
415
416                         p++;
417                         l--;
418                 }
419
420                 fputc('\"', stdout);
421         }
422 }
423
424 static int output_json(sd_journal *j, unsigned line, bool show_all) {
425         uint64_t realtime, monotonic;
426         char *cursor;
427         const void *data;
428         size_t length;
429         sd_id128_t boot_id;
430         char sid[33];
431         int r;
432
433         assert(j);
434
435         r = sd_journal_get_realtime_usec(j, &realtime);
436         if (r < 0) {
437                 log_error("Failed to get realtime timestamp: %s", strerror(-r));
438                 return r;
439         }
440
441         r = sd_journal_get_monotonic_usec(j, &monotonic, &boot_id);
442         if (r < 0) {
443                 log_error("Failed to get monotonic timestamp: %s", strerror(-r));
444                 return r;
445         }
446
447         r = sd_journal_get_cursor(j, &cursor);
448         if (r < 0) {
449                 log_error("Failed to get cursor: %s", strerror(-r));
450                 return r;
451         }
452
453         if (line == 1)
454                 fputc('\n', stdout);
455         else
456                 fputs(",\n", stdout);
457
458         printf("{\n"
459                "\t\".cursor\" : \"%s\",\n"
460                "\t\".realtime\" : %llu,\n"
461                "\t\".monotonic\" : %llu,\n"
462                "\t\".boot_id\" : \"%s\"",
463                cursor,
464                (unsigned long long) realtime,
465                (unsigned long long) monotonic,
466                sd_id128_to_string(boot_id, sid));
467
468         free(cursor);
469
470         SD_JOURNAL_FOREACH_DATA(j, data, length) {
471                 const char *c;
472
473                 c = memchr(data, '=', length);
474                 if (!c) {
475                         log_error("Invalid field.");
476                         return -EINVAL;
477                 }
478
479                 fputs(",\n\t", stdout);
480                 json_escape(data, c - (const char*) data);
481                 fputs(" : ", stdout);
482                 json_escape(c + 1, length - (c - (const char*) data) - 1);
483         }
484
485         fputs("\n}", stdout);
486         fflush(stdout);
487
488         return 0;
489 }
490
491 static int output_cat(sd_journal *j, unsigned line, bool show_all) {
492         const void *data;
493         size_t l;
494         int r;
495
496         assert(j);
497
498         r = sd_journal_get_data(j, "MESSAGE", &data, &l);
499         if (r < 0) {
500                 log_error("Failed to get data: %s", strerror(-r));
501                 return r;
502         }
503
504         assert(l >= 8);
505
506         fwrite((const char*) data + 8, 1, l - 8, stdout);
507         putchar('\n');
508
509         return 0;
510 }
511
512 static int (*output_funcs[_OUTPUT_MODE_MAX])(sd_journal*j, unsigned line, bool show_all) = {
513         [OUTPUT_SHORT] = output_short_realtime,
514         [OUTPUT_SHORT_MONOTONIC] = output_short_monotonic,
515         [OUTPUT_VERBOSE] = output_verbose,
516         [OUTPUT_EXPORT] = output_export,
517         [OUTPUT_JSON] = output_json,
518         [OUTPUT_CAT] = output_cat
519 };
520
521 int output_journal(sd_journal *j, OutputMode mode, unsigned line, bool show_all) {
522         assert(mode >= 0);
523         assert(mode < _OUTPUT_MODE_MAX);
524
525         return output_funcs[mode](j, line, show_all);
526 }
527
528 int show_journal_by_unit(
529                 const char *unit,
530                 OutputMode mode,
531                 const char *prefix,
532                 unsigned n_columns,
533                 usec_t not_before,
534                 unsigned how_many,
535                 bool show_all,
536                 bool follow) {
537
538         char *m = NULL;
539         sd_journal *j;
540         int r;
541         int fd;
542         unsigned line = 0;
543         bool need_seek = false;
544
545         assert(mode >= 0);
546         assert(mode < _OUTPUT_MODE_MAX);
547         assert(unit);
548
549         if (!endswith(unit, ".service") &&
550             !endswith(unit, ".socket") &&
551             !endswith(unit, ".mount") &&
552             !endswith(unit, ".swap"))
553                 return 0;
554
555         if (how_many <= 0)
556                 return 0;
557
558         if (n_columns <= 0)
559                 n_columns = columns();
560
561         if (!prefix)
562                 prefix = "";
563
564         if (asprintf(&m, "_SYSTEMD_UNIT=%s", unit) < 0) {
565                 r = -ENOMEM;
566                 goto finish;
567         }
568
569         r = sd_journal_open(&j, SD_JOURNAL_LOCAL_ONLY|SD_JOURNAL_SYSTEM_ONLY);
570         if (r < 0)
571                 goto finish;
572
573         fd = sd_journal_get_fd(j);
574         if (fd < 0)
575                 goto finish;
576
577         r = sd_journal_add_match(j, m, strlen(m));
578         if (r < 0)
579                 goto finish;
580
581         r = sd_journal_seek_tail(j);
582         if (r < 0)
583                 goto finish;
584
585         r = sd_journal_previous_skip(j, how_many);
586         if (r < 0)
587                 goto finish;
588
589         if (mode == OUTPUT_JSON) {
590                 fputc('[', stdout);
591                 fflush(stdout);
592         }
593
594         for (;;) {
595                 for (;;) {
596                         usec_t usec;
597
598                         if (need_seek) {
599                                 r = sd_journal_next(j);
600                                 if (r < 0)
601                                         goto finish;
602                         }
603
604                         if (r == 0)
605                                 break;
606
607                         need_seek = true;
608
609                         if (not_before > 0) {
610                                 r = sd_journal_get_monotonic_usec(j, &usec, NULL);
611
612                                 /* -ESTALE is returned if the
613                                    timestamp is not from this boot */
614                                 if (r == -ESTALE)
615                                         continue;
616                                 else if (r < 0)
617                                         goto finish;
618
619                                 if (usec < not_before)
620                                         continue;
621                         }
622
623                         line ++;
624
625                         r = output_journal(j, mode, line, show_all);
626                         if (r < 0)
627                                 goto finish;
628                 }
629
630                 if (!follow)
631                         break;
632
633                 r = fd_wait_for_event(fd, POLLIN);
634                 if (r < 0)
635                         goto finish;
636
637                 r = sd_journal_process(j);
638                 if (r < 0)
639                         goto finish;
640
641         }
642
643         if (mode == OUTPUT_JSON)
644                 fputs("\n]\n", stdout);
645
646 finish:
647         if (m)
648                 free(m);
649
650         if (j)
651                 sd_journal_close(j);
652
653         return r;
654 }
655
656 static const char *const output_mode_table[_OUTPUT_MODE_MAX] = {
657         [OUTPUT_SHORT] = "short",
658         [OUTPUT_SHORT_MONOTONIC] = "short-monotonic",
659         [OUTPUT_VERBOSE] = "verbose",
660         [OUTPUT_EXPORT] = "export",
661         [OUTPUT_JSON] = "json",
662         [OUTPUT_CAT] = "cat"
663 };
664
665 DEFINE_STRING_TABLE_LOOKUP(output_mode, OutputMode);