]> git.proxmox.com Git - mirror_lxc.git/blob - src/lxc/log.c
Merge pull request #2344 from brauner/2018-05-23/on_demand_log_file
[mirror_lxc.git] / src / lxc / log.c
1 /*
2 * lxc: linux Container library
3 *
4 * (C) Copyright IBM Corp. 2007, 2008
5 *
6 * Authors:
7 * Cedric Le Goater <legoater@free.fr>
8 *
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
13 *
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
18 *
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this library; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22 */
23
24 #define _GNU_SOURCE
25 #define __STDC_FORMAT_MACROS /* Required for PRIu64 to work. */
26 #include <stdint.h>
27 #include <stdio.h>
28 #include <errno.h>
29 #include <inttypes.h>
30 #include <limits.h>
31 #include <unistd.h>
32 #include <sys/types.h>
33 #include <sys/stat.h>
34 #include <string.h>
35 #include <pthread.h>
36 #include <time.h>
37
38 #include <syslog.h>
39 #include <stdio.h>
40
41 #include <fcntl.h>
42 #include <stdlib.h>
43
44 #include "log.h"
45 #include "caps.h"
46 #include "utils.h"
47 #include "lxccontainer.h"
48
49 #ifndef HAVE_STRLCPY
50 #include "include/strlcpy.h"
51 #endif
52
53 /* We're logging in seconds and nanoseconds. Assuming that the underlying
54 * datatype is currently at maximum a 64bit integer, we have a date string that
55 * is of maximum length (2^64 - 1) * 2 = (21 + 21) = 42.
56 */
57 #define LXC_LOG_TIME_SIZE ((LXC_NUMSTRLEN64)*2)
58
59 int lxc_log_fd = -1;
60 static int syslog_enable = 0;
61 int lxc_quiet_specified;
62 int lxc_log_use_global_fd;
63 static int lxc_loglevel_specified;
64
65 static char log_prefix[LXC_LOG_PREFIX_SIZE] = "lxc";
66 static char *log_fname = NULL;
67 static char *log_vmname = NULL;
68
69 lxc_log_define(lxc_log, lxc);
70
71 static int lxc_log_priority_to_syslog(int priority)
72 {
73 switch (priority) {
74 case LXC_LOG_LEVEL_FATAL:
75 return LOG_EMERG;
76 case LXC_LOG_LEVEL_ALERT:
77 return LOG_ALERT;
78 case LXC_LOG_LEVEL_CRIT:
79 return LOG_CRIT;
80 case LXC_LOG_LEVEL_ERROR:
81 return LOG_ERR;
82 case LXC_LOG_LEVEL_WARN:
83 return LOG_WARNING;
84 case LXC_LOG_LEVEL_NOTICE:
85 case LXC_LOG_LEVEL_NOTSET:
86 return LOG_NOTICE;
87 case LXC_LOG_LEVEL_INFO:
88 return LOG_INFO;
89 case LXC_LOG_LEVEL_TRACE:
90 case LXC_LOG_LEVEL_DEBUG:
91 return LOG_DEBUG;
92 }
93
94 /* Not reached */
95 return LOG_NOTICE;
96 }
97
98 /*---------------------------------------------------------------------------*/
99 static int log_append_syslog(const struct lxc_log_appender *appender,
100 struct lxc_log_event *event)
101 {
102 char *msg;
103 int rc, len;
104 va_list args;
105 const char *log_container_name = log_vmname;
106
107 #ifndef NO_LXC_CONF
108 if (current_config && !log_container_name)
109 log_container_name = current_config->name;
110 #endif
111
112 if (!syslog_enable)
113 return 0;
114
115 va_copy(args, *event->vap);
116 len = vsnprintf(NULL, 0, event->fmt, args) + 1;
117 va_end(args);
118
119 msg = malloc(len * sizeof(char));
120 if (msg == NULL)
121 return 0;
122
123 rc = vsnprintf(msg, len, event->fmt, *event->vap);
124 if (rc == -1 || rc >= len) {
125 free(msg);
126 return 0;
127 }
128
129 syslog(lxc_log_priority_to_syslog(event->priority),
130 "%s%s %s - %s:%s:%d - %s" ,
131 log_container_name ? log_container_name : "",
132 log_container_name ? ":" : "",
133 event->category,
134 event->locinfo->file, event->locinfo->func,
135 event->locinfo->line,
136 msg);
137 free(msg);
138
139 return 0;
140 }
141
142 /*---------------------------------------------------------------------------*/
143 static int log_append_stderr(const struct lxc_log_appender *appender,
144 struct lxc_log_event *event)
145 {
146 const char *log_container_name;
147
148 if (event->priority < LXC_LOG_LEVEL_ERROR)
149 return 0;
150
151 log_container_name = log_vmname;
152
153 #ifndef NO_LXC_CONF
154 if (current_config && !log_container_name)
155 log_container_name = current_config->name;
156 #endif
157
158 fprintf(stderr, "%s: %s%s", log_prefix,
159 log_container_name ? log_container_name : "",
160 log_container_name ? ": " : "");
161 fprintf(stderr, "%s: %s: %d ", event->locinfo->file,
162 event->locinfo->func, event->locinfo->line);
163 vfprintf(stderr, event->fmt, *event->vap);
164 fprintf(stderr, "\n");
165
166 return 0;
167 }
168
169 /*---------------------------------------------------------------------------*/
170 int lxc_unix_epoch_to_utc(char *buf, size_t bufsize, const struct timespec *time)
171 {
172 int64_t epoch_to_days, z, era, doe, yoe, year, doy, mp, day, month,
173 d_in_s, hours, h_in_s, minutes, seconds;
174 char nanosec[LXC_NUMSTRLEN64];
175 int ret;
176
177 /* See https://howardhinnant.github.io/date_algorithms.html for an
178 * explanation of the algorithm used here.
179 */
180
181 /* Convert Epoch in seconds to number of days. */
182 epoch_to_days = time->tv_sec / 86400;
183
184 /* Shift the Epoch from 1970-01-01 to 0000-03-01. */
185 z = epoch_to_days + 719468;
186
187 /* compute the era from the serial date by simply dividing by the number
188 * of days in an era (146097).
189 */
190 era = (z >= 0 ? z : z - 146096) / 146097;
191
192 /* The day-of-era (doe) can then be found by subtracting the era number
193 * times the number of days per era, from the serial date.
194 */
195 doe = (z - era * 146097);
196
197 /* From the day-of-era (doe), the year-of-era (yoe, range [0, 399]) can
198 * be computed.
199 */
200 yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
201
202 /* Given year-of-era, and era, one can now compute the year. */
203 year = yoe + era * 400;
204
205 /* Also the day-of-year, again with the year beginning on Mar. 1, can be
206 * computed from the day-of-era and year-of-era.
207 */
208 doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
209
210 /* Given day-of-year, find the month number. */
211 mp = (5 * doy + 2) / 153;
212
213 /* From day-of-year and month-of-year we can now easily compute
214 * day-of-month.
215 */
216 day = doy - (153 * mp + 2) / 5 + 1;
217
218 /* Transform the month number from the [0, 11] / [Mar, Feb] system to
219 * the civil system: [1, 12] to find the correct month.
220 */
221 month = mp + (mp < 10 ? 3 : -9);
222
223 /* The algorithm assumes that a year begins on 1 March, so add 1 before
224 * that. */
225 if (month < 3)
226 year++;
227
228 /* Transform days in the epoch to seconds. */
229 d_in_s = epoch_to_days * 86400;
230
231 /* To find the current hour simply substract the Epoch_to_days from the
232 * total Epoch and divide by the number of seconds in an hour.
233 */
234 hours = (time->tv_sec - d_in_s) / 3600;
235
236 /* Transform hours to seconds. */
237 h_in_s = hours * 3600;
238
239 /* Calculate minutes by substracting the seconds for all days in the
240 * epoch and for all hours in the epoch and divide by the number of
241 * minutes in an hour.
242 */
243 minutes = (time->tv_sec - d_in_s - h_in_s) / 60;
244
245 /* Calculate the seconds by substracting the seconds for all days in the
246 * epoch, hours in the epoch and minutes in the epoch.
247 */
248 seconds = (time->tv_sec - d_in_s - h_in_s - (minutes * 60));
249
250 /* Make string from nanoseconds. */
251 ret = snprintf(nanosec, LXC_NUMSTRLEN64, "%"PRId64, (int64_t)time->tv_nsec);
252 if (ret < 0 || ret >= LXC_NUMSTRLEN64)
253 return -1;
254
255 /* Create final timestamp for the log and shorten nanoseconds to 3
256 * digit precision.
257 */
258 ret = snprintf(buf, bufsize,
259 "%" PRId64 "%02" PRId64 "%02" PRId64 "%02" PRId64
260 "%02" PRId64 "%02" PRId64 ".%.3s",
261 year, month, day, hours, minutes, seconds, nanosec);
262 if (ret < 0 || (size_t)ret >= bufsize)
263 return -1;
264
265 return 0;
266 }
267
268 /* This function needs to make extra sure that it is thread-safe. We had some
269 * problems with that before. This especially involves time-conversion
270 * functions. I don't want to find any localtime() or gmtime() functions or
271 * relatives in here. Not even localtime_r() or gmtime_r() or relatives. They
272 * all fiddle with global variables and locking in various libcs. They cause
273 * deadlocks when liblxc is used multi-threaded and no matter how smart you
274 * think you are, you __will__ cause trouble using them.
275 * (As a short example how this can cause trouble: LXD uses forkstart to fork
276 * off a new process that runs the container. At the same time the go runtime
277 * LXD relies on does its own multi-threading thing which we can't controll. The
278 * fork()ing + threading then seems to mess with the locking states in these
279 * time functions causing deadlocks.)
280 * The current solution is to be good old unix people and use the Epoch as our
281 * reference point and simply use the seconds and nanoseconds that have past
282 * since then. This relies on clock_gettime() which is explicitly marked MT-Safe
283 * with no restrictions! This way, anyone who is really strongly invested in
284 * getting the actual time the log entry was created, can just convert it for
285 * themselves. Our logging is mostly done for debugging purposes so don't try
286 * to make it pretty. Pretty might cost you thread-safety.
287 */
288 static int log_append_logfile(const struct lxc_log_appender *appender,
289 struct lxc_log_event *event)
290 {
291 char buffer[LXC_LOG_BUFFER_SIZE];
292 char date_time[LXC_LOG_TIME_SIZE];
293 int n, ret;
294 int fd_to_use = -1;
295 const char *log_container_name = log_vmname;
296
297 #ifndef NO_LXC_CONF
298 if (current_config) {
299 if (!lxc_log_use_global_fd)
300 fd_to_use = current_config->logfd;
301
302 if (!log_container_name)
303 log_container_name = current_config->name;
304 }
305 #endif
306
307 if (fd_to_use == -1)
308 fd_to_use = lxc_log_fd;
309
310 if (fd_to_use == -1)
311 return 0;
312
313 if (lxc_unix_epoch_to_utc(date_time, LXC_LOG_TIME_SIZE, &event->timestamp) < 0)
314 return 0;
315
316 n = snprintf(buffer, sizeof(buffer),
317 "%s%s%s %s %-8s %s - %s:%s:%d - ",
318 log_prefix,
319 log_container_name ? " " : "",
320 log_container_name ? log_container_name : "",
321 date_time,
322 lxc_log_priority_to_string(event->priority),
323 event->category,
324 event->locinfo->file, event->locinfo->func,
325 event->locinfo->line);
326
327 if (n < 0)
328 return n;
329
330 if ((size_t)n < (sizeof(buffer) - 1)) {
331 ret = vsnprintf(buffer + n, sizeof(buffer) - n, event->fmt, *event->vap);
332 if (ret < 0)
333 return 0;
334
335 n += ret;
336 }
337
338 if ((size_t)n >= sizeof(buffer))
339 n = sizeof(buffer) - 1;
340
341 buffer[n] = '\n';
342
343 return write(fd_to_use, buffer, n + 1);
344 }
345
346 static struct lxc_log_appender log_appender_syslog = {
347 .name = "syslog",
348 .append = log_append_syslog,
349 .next = NULL,
350 };
351
352 static struct lxc_log_appender log_appender_stderr = {
353 .name = "stderr",
354 .append = log_append_stderr,
355 .next = NULL,
356 };
357
358 static struct lxc_log_appender log_appender_logfile = {
359 .name = "logfile",
360 .append = log_append_logfile,
361 .next = NULL,
362 };
363
364 static struct lxc_log_category log_root = {
365 .name = "root",
366 .priority = LXC_LOG_LEVEL_ERROR,
367 .appender = NULL,
368 .parent = NULL,
369 };
370
371 struct lxc_log_category lxc_log_category_lxc = {
372 .name = "lxc",
373 .priority = LXC_LOG_LEVEL_ERROR,
374 .appender = &log_appender_logfile,
375 .parent = &log_root
376 };
377
378 /*---------------------------------------------------------------------------*/
379 static int build_dir(const char *name)
380 {
381 int ret;
382 char *e, *n, *p;
383
384 /* Make copy of string since we'll be modifying it. */
385 n = strdup(name);
386 if (!n) {
387 ERROR("Out of memory while creating directory '%s'.", name);
388 return -1;
389 }
390
391 e = &n[strlen(n)];
392 for (p = n+1; p < e; p++) {
393 if (*p != '/')
394 continue;
395 *p = '\0';
396 if (access(n, F_OK)) {
397 ret = lxc_unpriv(mkdir(n, 0755));
398 if (ret && errno != EEXIST) {
399 SYSERROR("failed to create directory '%s'.", n);
400 free(n);
401 return -1;
402 }
403 }
404 *p = '/';
405 }
406 free(n);
407 return 0;
408 }
409
410 /*---------------------------------------------------------------------------*/
411 static int log_open(const char *name)
412 {
413 int fd;
414 int newfd;
415
416 fd = lxc_unpriv(open(name, O_CREAT | O_WRONLY |
417 O_APPEND | O_CLOEXEC, 0666));
418 if (fd == -1) {
419 ERROR("failed to open log file \"%s\" : %s", name,
420 strerror(errno));
421 return -1;
422 }
423
424 if (fd > 2)
425 return fd;
426
427 newfd = fcntl(fd, F_DUPFD_CLOEXEC, 3);
428 if (newfd == -1)
429 ERROR("failed to dup log fd %d : %s", fd, strerror(errno));
430
431 close(fd);
432 return newfd;
433 }
434
435 /*
436 * Build the path to the log file
437 * @name : the name of the container
438 * @lxcpath : the lxcpath to use as a basename or NULL to use LOGPATH
439 * Returns malloced path on success, or NULL on failure
440 */
441 static char *build_log_path(const char *name, const char *lxcpath)
442 {
443 char *p;
444 int len, ret, use_dir;
445
446 if (!name)
447 return NULL;
448
449 #if USE_CONFIGPATH_LOGS
450 use_dir = 1;
451 #else
452 use_dir = 0;
453 #endif
454
455 /*
456 * If USE_CONFIGPATH_LOGS is true or lxcpath is given, the resulting
457 * path will be:
458 * '$logpath' + '/' + '$name' + '/' + '$name' + '.log' + '\0'
459 *
460 * If USE_CONFIGPATH_LOGS is false the resulting path will be:
461 * '$logpath' + '/' + '$name' + '.log' + '\0'
462 */
463 len = strlen(name) + 6; /* 6 == '/' + '.log' + '\0' */
464 if (lxcpath)
465 use_dir = 1;
466 else
467 lxcpath = LOGPATH;
468
469 if (use_dir)
470 len += strlen(lxcpath) + 1 + strlen(name) + 1; /* add "/$container_name/" */
471 else
472 len += strlen(lxcpath) + 1;
473 p = malloc(len);
474 if (!p)
475 return p;
476
477 if (use_dir)
478 ret = snprintf(p, len, "%s/%s/%s.log", lxcpath, name, name);
479 else
480 ret = snprintf(p, len, "%s/%s.log", lxcpath, name);
481
482 if (ret < 0 || ret >= len) {
483 free(p);
484 return NULL;
485 }
486 return p;
487 }
488
489 extern void lxc_log_close(void)
490 {
491 closelog();
492 free(log_vmname);
493 log_vmname = NULL;
494 if (lxc_log_fd == -1)
495 return;
496 close(lxc_log_fd);
497 lxc_log_fd = -1;
498 free(log_fname);
499 log_fname = NULL;
500 }
501
502 /*
503 * This can be called:
504 * 1. when a program calls lxc_log_init with no logfile parameter (in which
505 * case the default is used). In this case lxc.loge can override this.
506 * 2. when a program calls lxc_log_init with a logfile parameter. In this
507 * case we don't want lxc.log to override this.
508 * 3. When a lxc.log entry is found in config file.
509 */
510 static int __lxc_log_set_file(const char *fname, int create_dirs)
511 {
512 /* we are overriding the default. */
513 if (lxc_log_fd != -1)
514 lxc_log_close();
515
516 if (!fname)
517 return -1;
518
519 if (strlen(fname) == 0) {
520 log_fname = NULL;
521 return 0;
522 }
523
524 #if USE_CONFIGPATH_LOGS
525 /* We don't build_dir for the default if the default is i.e.
526 * /var/lib/lxc/$container/$container.log.
527 */
528 if (create_dirs)
529 #endif
530 if (build_dir(fname)) {
531 ERROR("failed to create dir for log file \"%s\" : %s", fname,
532 strerror(errno));
533 return -1;
534 }
535
536 lxc_log_fd = log_open(fname);
537 if (lxc_log_fd == -1)
538 return -1;
539
540 log_fname = strdup(fname);
541 return 0;
542 }
543
544 static int _lxc_log_set_file(const char *name, const char *lxcpath, int create_dirs)
545 {
546 char *logfile;
547 int ret;
548
549 logfile = build_log_path(name, lxcpath);
550 if (!logfile) {
551 ERROR("could not build log path");
552 return -1;
553 }
554 ret = __lxc_log_set_file(logfile, create_dirs);
555 free(logfile);
556 return ret;
557 }
558
559 extern int lxc_log_syslog(int facility)
560 {
561 struct lxc_log_appender *appender;
562
563 openlog(log_prefix, LOG_PID, facility);
564 if (!lxc_log_category_lxc.appender) {
565 lxc_log_category_lxc.appender = &log_appender_syslog;
566 return 0;
567 }
568
569 appender = lxc_log_category_lxc.appender;
570 /* Check if syslog was already added, to avoid creating a loop */
571 while (appender) {
572 if (appender == &log_appender_syslog) {
573 /* not an error: openlog re-opened the connection */
574 return 0;
575 }
576 appender = appender->next;
577 }
578
579 appender = lxc_log_category_lxc.appender;
580 while (appender->next != NULL)
581 appender = appender->next;
582 appender->next = &log_appender_syslog;
583
584 return 0;
585 }
586
587 extern void lxc_log_enable_syslog(void)
588 {
589 syslog_enable = 1;
590 }
591
592 /*
593 * lxc_log_init:
594 * Called from lxc front-end programs (like lxc-create, lxc-start) to
595 * initalize the log defaults.
596 */
597 extern int lxc_log_init(struct lxc_log *log)
598 {
599 int lxc_priority = LXC_LOG_LEVEL_ERROR;
600 int ret;
601
602 if (lxc_log_fd != -1) {
603 WARN("lxc_log_init called with log already initialized");
604 return 0;
605 }
606
607 if (log->level)
608 lxc_priority = lxc_log_priority_to_int(log->level);
609
610 if (!lxc_loglevel_specified) {
611 lxc_log_category_lxc.priority = lxc_priority;
612 lxc_loglevel_specified = 1;
613 }
614
615 if (!lxc_quiet_specified) {
616 if (!log->quiet)
617 lxc_log_category_lxc.appender->next = &log_appender_stderr;
618 }
619
620 if (log->prefix)
621 lxc_log_set_prefix(log->prefix);
622
623 if (log->name)
624 log_vmname = strdup(log->name);
625
626 if (log->file) {
627 if (strcmp(log->file, "none") == 0)
628 return 0;
629 ret = __lxc_log_set_file(log->file, 1);
630 lxc_log_use_global_fd = 1;
631 } else {
632 /* if no name was specified, there nothing to do */
633 if (!log->name)
634 return 0;
635
636 ret = -1;
637
638 if (!log->lxcpath)
639 log->lxcpath = LOGPATH;
640
641 /* try LOGPATH if lxcpath is the default for the privileged containers */
642 if (!geteuid() && strcmp(LXCPATH, log->lxcpath) == 0)
643 ret = _lxc_log_set_file(log->name, NULL, 0);
644
645 /* try in lxcpath */
646 if (ret < 0)
647 ret = _lxc_log_set_file(log->name, log->lxcpath, 1);
648
649 /* try LOGPATH in case its writable by the caller */
650 if (ret < 0)
651 ret = _lxc_log_set_file(log->name, NULL, 0);
652 }
653
654 /*
655 * If !file, that is, if the user did not request this logpath, then
656 * ignore failures and continue logging to console
657 */
658 if (!log->file && ret != 0) {
659 INFO("Ignoring failure to open default logfile.");
660 ret = 0;
661 }
662
663 return ret;
664 }
665
666 /*
667 * This is called when we read a lxc.log.level entry in a lxc.conf file. This
668 * happens after processing command line arguments, which override the .conf
669 * settings. So only set the level if previously unset.
670 */
671 extern int lxc_log_set_level(int *dest, int level)
672 {
673 if (level < 0 || level >= LXC_LOG_LEVEL_NOTSET) {
674 ERROR("invalid log priority %d", level);
675 return -1;
676 }
677 *dest = level;
678 return 0;
679 }
680
681 extern int lxc_log_get_level(void)
682 {
683 return lxc_log_category_lxc.priority;
684 }
685
686 extern bool lxc_log_has_valid_level(void)
687 {
688 int log_level = lxc_log_get_level();
689 if (log_level < 0 || log_level >= LXC_LOG_LEVEL_NOTSET)
690 return false;
691 return true;
692 }
693
694 /*
695 * This is called when we read a lxc.logfile entry in a lxc.conf file. This
696 * happens after processing command line arguments, which override the .conf
697 * settings. So only set the file if previously unset.
698 */
699 extern int lxc_log_set_file(int *fd, const char *fname)
700 {
701 if (*fd != -1) {
702 close(*fd);
703 *fd = -1;
704 }
705
706 if (build_dir(fname)) {
707 ERROR("failed to create dir for log file \"%s\" : %s", fname,
708 strerror(errno));
709 return -1;
710 }
711
712 *fd = log_open(fname);
713 if (*fd == -1)
714 return -errno;
715 return 0;
716 }
717
718 extern const char *lxc_log_get_file(void)
719 {
720 return log_fname;
721 }
722
723 extern void lxc_log_set_prefix(const char *prefix)
724 {
725 /* We don't care if thte prefix is truncated. */
726 (void)strlcpy(log_prefix, prefix, sizeof(log_prefix));
727 }
728
729 extern const char *lxc_log_get_prefix(void)
730 {
731 return log_prefix;
732 }
733
734 extern void lxc_log_options_no_override()
735 {
736 lxc_quiet_specified = 1;
737 lxc_loglevel_specified = 1;
738 }