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