]> git.proxmox.com Git - mirror_lxc.git/blob - src/lxc/log.c
Merge pull request #1718 from agaida/patch-1
[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, "%ld", 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 else
301 n = sizeof(buffer) - 1;
302
303 buffer[n] = '\n';
304
305 return write(fd_to_use, buffer, n + 1);
306 }
307
308 static struct lxc_log_appender log_appender_syslog = {
309 .name = "syslog",
310 .append = log_append_syslog,
311 .next = NULL,
312 };
313
314 static struct lxc_log_appender log_appender_stderr = {
315 .name = "stderr",
316 .append = log_append_stderr,
317 .next = NULL,
318 };
319
320 static struct lxc_log_appender log_appender_logfile = {
321 .name = "logfile",
322 .append = log_append_logfile,
323 .next = NULL,
324 };
325
326 static struct lxc_log_category log_root = {
327 .name = "root",
328 .priority = LXC_LOG_LEVEL_ERROR,
329 .appender = NULL,
330 .parent = NULL,
331 };
332
333 struct lxc_log_category lxc_log_category_lxc = {
334 .name = "lxc",
335 .priority = LXC_LOG_LEVEL_ERROR,
336 .appender = &log_appender_logfile,
337 .parent = &log_root
338 };
339
340 /*---------------------------------------------------------------------------*/
341 static int build_dir(const char *name)
342 {
343 int ret;
344 char *e, *n, *p;
345
346 /* Make copy of string since we'll be modifying it. */
347 n = strdup(name);
348 if (!n) {
349 ERROR("Out of memory while creating directory '%s'.", name);
350 return -1;
351 }
352
353 e = &n[strlen(n)];
354 for (p = n+1; p < e; p++) {
355 if (*p != '/')
356 continue;
357 *p = '\0';
358 if (access(n, F_OK)) {
359 ret = lxc_unpriv(mkdir(n, 0755));
360 if (ret && errno != EEXIST) {
361 SYSERROR("failed to create directory '%s'.", n);
362 free(n);
363 return -1;
364 }
365 }
366 *p = '/';
367 }
368 free(n);
369 return 0;
370 }
371
372 /*---------------------------------------------------------------------------*/
373 static int log_open(const char *name)
374 {
375 int fd;
376 int newfd;
377
378 fd = lxc_unpriv(open(name, O_CREAT | O_WRONLY |
379 O_APPEND | O_CLOEXEC, 0666));
380 if (fd == -1) {
381 ERROR("failed to open log file \"%s\" : %s", name,
382 strerror(errno));
383 return -1;
384 }
385
386 if (fd > 2)
387 return fd;
388
389 newfd = fcntl(fd, F_DUPFD_CLOEXEC, 3);
390 if (newfd == -1)
391 ERROR("failed to dup log fd %d : %s", fd, strerror(errno));
392
393 close(fd);
394 return newfd;
395 }
396
397 /*
398 * Build the path to the log file
399 * @name : the name of the container
400 * @lxcpath : the lxcpath to use as a basename or NULL to use LOGPATH
401 * Returns malloced path on success, or NULL on failure
402 */
403 static char *build_log_path(const char *name, const char *lxcpath)
404 {
405 char *p;
406 int len, ret, use_dir;
407
408 if (!name)
409 return NULL;
410
411 #if USE_CONFIGPATH_LOGS
412 use_dir = 1;
413 #else
414 use_dir = 0;
415 #endif
416
417 /*
418 * If USE_CONFIGPATH_LOGS is true or lxcpath is given, the resulting
419 * path will be:
420 * '$logpath' + '/' + '$name' + '/' + '$name' + '.log' + '\0'
421 *
422 * If USE_CONFIGPATH_LOGS is false the resulting path will be:
423 * '$logpath' + '/' + '$name' + '.log' + '\0'
424 */
425 len = strlen(name) + 6; /* 6 == '/' + '.log' + '\0' */
426 if (lxcpath)
427 use_dir = 1;
428 else
429 lxcpath = LOGPATH;
430
431 if (use_dir)
432 len += strlen(lxcpath) + 1 + strlen(name) + 1; /* add "/$container_name/" */
433 else
434 len += strlen(lxcpath) + 1;
435 p = malloc(len);
436 if (!p)
437 return p;
438
439 if (use_dir)
440 ret = snprintf(p, len, "%s/%s/%s.log", lxcpath, name, name);
441 else
442 ret = snprintf(p, len, "%s/%s.log", lxcpath, name);
443
444 if (ret < 0 || ret >= len) {
445 free(p);
446 return NULL;
447 }
448 return p;
449 }
450
451 extern void lxc_log_close(void)
452 {
453 closelog();
454 free(log_vmname);
455 log_vmname = NULL;
456 if (lxc_log_fd == -1)
457 return;
458 close(lxc_log_fd);
459 lxc_log_fd = -1;
460 free(log_fname);
461 log_fname = NULL;
462 }
463
464 /*
465 * This can be called:
466 * 1. when a program calls lxc_log_init with no logfile parameter (in which
467 * case the default is used). In this case lxc.loge can override this.
468 * 2. when a program calls lxc_log_init with a logfile parameter. In this
469 * case we don't want lxc.log to override this.
470 * 3. When a lxc.log entry is found in config file.
471 */
472 static int __lxc_log_set_file(const char *fname, int create_dirs)
473 {
474 /* we are overriding the default. */
475 if (lxc_log_fd != -1)
476 lxc_log_close();
477
478 if (!fname)
479 return -1;
480
481 if (strlen(fname) == 0) {
482 log_fname = NULL;
483 return 0;
484 }
485
486 #if USE_CONFIGPATH_LOGS
487 /* We don't build_dir for the default if the default is i.e.
488 * /var/lib/lxc/$container/$container.log.
489 */
490 if (create_dirs)
491 #endif
492 if (build_dir(fname)) {
493 ERROR("failed to create dir for log file \"%s\" : %s", fname,
494 strerror(errno));
495 return -1;
496 }
497
498 lxc_log_fd = log_open(fname);
499 if (lxc_log_fd == -1)
500 return -1;
501
502 log_fname = strdup(fname);
503 return 0;
504 }
505
506 static int _lxc_log_set_file(const char *name, const char *lxcpath, int create_dirs)
507 {
508 char *logfile;
509 int ret;
510
511 logfile = build_log_path(name, lxcpath);
512 if (!logfile) {
513 ERROR("could not build log path");
514 return -1;
515 }
516 ret = __lxc_log_set_file(logfile, create_dirs);
517 free(logfile);
518 return ret;
519 }
520
521 extern int lxc_log_syslog(int facility)
522 {
523 struct lxc_log_appender *appender;
524
525 openlog(log_prefix, LOG_PID, facility);
526 if (!lxc_log_category_lxc.appender) {
527 lxc_log_category_lxc.appender = &log_appender_syslog;
528 return 0;
529 }
530 appender = lxc_log_category_lxc.appender;
531 while (appender->next != NULL)
532 appender = appender->next;
533 appender->next = &log_appender_syslog;
534
535 return 0;
536 }
537
538 extern void lxc_log_enable_syslog(void)
539 {
540 syslog_enable = 1;
541 }
542
543 /*
544 * lxc_log_init:
545 * Called from lxc front-end programs (like lxc-create, lxc-start) to
546 * initalize the log defaults.
547 */
548 extern int lxc_log_init(struct lxc_log *log)
549 {
550 int lxc_priority = LXC_LOG_LEVEL_ERROR;
551 int ret;
552
553 if (lxc_log_fd != -1) {
554 WARN("lxc_log_init called with log already initialized");
555 return 0;
556 }
557
558 if (log->level)
559 lxc_priority = lxc_log_priority_to_int(log->level);
560
561 if (!lxc_loglevel_specified) {
562 lxc_log_category_lxc.priority = lxc_priority;
563 lxc_loglevel_specified = 1;
564 }
565
566 if (!lxc_quiet_specified) {
567 if (!log->quiet)
568 lxc_log_category_lxc.appender->next = &log_appender_stderr;
569 }
570
571 if (log->prefix)
572 lxc_log_set_prefix(log->prefix);
573
574 if (log->name)
575 log_vmname = strdup(log->name);
576
577 if (log->file) {
578 if (strcmp(log->file, "none") == 0)
579 return 0;
580 ret = __lxc_log_set_file(log->file, 1);
581 lxc_log_use_global_fd = 1;
582 } else {
583 /* if no name was specified, there nothing to do */
584 if (!log->name)
585 return 0;
586
587 ret = -1;
588
589 if (!log->lxcpath)
590 log->lxcpath = LOGPATH;
591
592 /* try LOGPATH if lxcpath is the default for the privileged containers */
593 if (!geteuid() && strcmp(LXCPATH, log->lxcpath) == 0)
594 ret = _lxc_log_set_file(log->name, NULL, 0);
595
596 /* try in lxcpath */
597 if (ret < 0)
598 ret = _lxc_log_set_file(log->name, log->lxcpath, 1);
599
600 /* try LOGPATH in case its writable by the caller */
601 if (ret < 0)
602 ret = _lxc_log_set_file(log->name, NULL, 0);
603 }
604
605 /*
606 * If !file, that is, if the user did not request this logpath, then
607 * ignore failures and continue logging to console
608 */
609 if (!log->file && ret != 0) {
610 INFO("Ignoring failure to open default logfile.");
611 ret = 0;
612 }
613
614 return ret;
615 }
616
617 /*
618 * This is called when we read a lxc.log.level entry in a lxc.conf file. This
619 * happens after processing command line arguments, which override the .conf
620 * settings. So only set the level if previously unset.
621 */
622 extern int lxc_log_set_level(int *dest, int level)
623 {
624 if (level < 0 || level >= LXC_LOG_LEVEL_NOTSET) {
625 ERROR("invalid log priority %d", level);
626 return -1;
627 }
628 *dest = level;
629 return 0;
630 }
631
632 extern int lxc_log_get_level(void)
633 {
634 return lxc_log_category_lxc.priority;
635 }
636
637 extern bool lxc_log_has_valid_level(void)
638 {
639 int log_level = lxc_log_get_level();
640 if (log_level < 0 || log_level >= LXC_LOG_LEVEL_NOTSET)
641 return false;
642 return true;
643 }
644
645 /*
646 * This is called when we read a lxc.logfile entry in a lxc.conf file. This
647 * happens after processing command line arguments, which override the .conf
648 * settings. So only set the file if previously unset.
649 */
650 extern int lxc_log_set_file(int *fd, const char *fname)
651 {
652 if (*fd != -1) {
653 close(*fd);
654 *fd = -1;
655 }
656
657 if (build_dir(fname)) {
658 ERROR("failed to create dir for log file \"%s\" : %s", fname,
659 strerror(errno));
660 return -1;
661 }
662
663 *fd = log_open(fname);
664 if (*fd == -1)
665 return -errno;
666 return 0;
667 }
668
669 extern const char *lxc_log_get_file(void)
670 {
671 return log_fname;
672 }
673
674 extern void lxc_log_set_prefix(const char *prefix)
675 {
676 strncpy(log_prefix, prefix, sizeof(log_prefix));
677 log_prefix[sizeof(log_prefix) - 1] = 0;
678 }
679
680 extern const char *lxc_log_get_prefix(void)
681 {
682 return log_prefix;
683 }
684
685 extern void lxc_log_options_no_override()
686 {
687 lxc_quiet_specified = 1;
688 lxc_loglevel_specified = 1;
689 }