2 * lxc: linux Container library
4 * (C) Copyright IBM Corp. 2007, 2008
7 * Cedric Le Goater <legoater@free.fr>
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.
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.
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
27 #define __STDC_FORMAT_MACROS /* Required for PRIu64 to work. */
38 #include <sys/types.h>
45 #include "lxccontainer.h"
49 #include "include/strlcpy.h"
59 /* We're logging in seconds and nanoseconds. Assuming that the underlying
60 * datatype is currently at maximum a 64bit integer, we have a date string that
61 * is of maximum length (2^64 - 1) * 2 = (21 + 21) = 42.
63 #define LXC_LOG_TIME_SIZE ((INTTYPE_TO_STRLEN(uint64_t)) * 2)
66 static int syslog_enable
= 0;
67 int lxc_quiet_specified
;
68 int lxc_log_use_global_fd
;
69 static int lxc_loglevel_specified
;
71 static char log_prefix
[LXC_LOG_PREFIX_SIZE
] = "lxc";
72 static char *log_fname
= NULL
;
73 static char *log_vmname
= NULL
;
75 lxc_log_define(log
, lxc
);
77 static int lxc_log_priority_to_syslog(int priority
)
80 case LXC_LOG_LEVEL_FATAL
:
82 case LXC_LOG_LEVEL_ALERT
:
84 case LXC_LOG_LEVEL_CRIT
:
86 case LXC_LOG_LEVEL_ERROR
:
88 case LXC_LOG_LEVEL_WARN
:
90 case LXC_LOG_LEVEL_NOTICE
:
91 case LXC_LOG_LEVEL_NOTSET
:
93 case LXC_LOG_LEVEL_INFO
:
95 case LXC_LOG_LEVEL_TRACE
:
96 case LXC_LOG_LEVEL_DEBUG
:
104 static const char *lxc_log_get_container_name()
107 if (current_config
&& !log_vmname
)
108 return current_config
->name
;
114 static char *lxc_log_get_va_msg(struct lxc_log_event
*event
)
123 va_copy(args
, *event
->vap
);
124 len
= vsnprintf(NULL
, 0, event
->fmt
, args
) + 1;
127 msg
= malloc(len
* sizeof(char));
131 rc
= vsnprintf(msg
, len
, event
->fmt
, *event
->vap
);
132 if (rc
== -1 || rc
>= len
) {
140 /*---------------------------------------------------------------------------*/
141 static int log_append_syslog(const struct lxc_log_appender
*appender
,
142 struct lxc_log_event
*event
)
145 const char *log_container_name
;
150 log_container_name
= lxc_log_get_container_name();
152 msg
= lxc_log_get_va_msg(event
);
156 syslog(lxc_log_priority_to_syslog(event
->priority
),
157 "%s%s %s - %s:%s:%d - %s" ,
158 log_container_name
? log_container_name
: "",
159 log_container_name
? ":" : "",
161 event
->locinfo
->file
, event
->locinfo
->func
,
162 event
->locinfo
->line
,
169 /*---------------------------------------------------------------------------*/
170 static int log_append_stderr(const struct lxc_log_appender
*appender
,
171 struct lxc_log_event
*event
)
173 const char *log_container_name
;
175 if (event
->priority
< LXC_LOG_LEVEL_ERROR
)
178 log_container_name
= lxc_log_get_container_name();
180 fprintf(stderr
, "%s: %s%s", log_prefix
,
181 log_container_name
? log_container_name
: "",
182 log_container_name
? ": " : "");
183 fprintf(stderr
, "%s: %s: %d ", event
->locinfo
->file
,
184 event
->locinfo
->func
, event
->locinfo
->line
);
185 vfprintf(stderr
, event
->fmt
, *event
->vap
);
186 fprintf(stderr
, "\n");
191 /*---------------------------------------------------------------------------*/
192 static int lxc_unix_epoch_to_utc(char *buf
, size_t bufsize
, const struct timespec
*time
)
194 int64_t epoch_to_days
, z
, era
, doe
, yoe
, year
, doy
, mp
, day
, month
,
195 d_in_s
, hours
, h_in_s
, minutes
, seconds
;
196 char nanosec
[INTTYPE_TO_STRLEN(int64_t)];
199 /* See https://howardhinnant.github.io/date_algorithms.html for an
200 * explanation of the algorithm used here.
203 /* Convert Epoch in seconds to number of days. */
204 epoch_to_days
= time
->tv_sec
/ 86400;
206 /* Shift the Epoch from 1970-01-01 to 0000-03-01. */
207 z
= epoch_to_days
+ 719468;
209 /* compute the era from the serial date by simply dividing by the number
210 * of days in an era (146097).
212 era
= (z
>= 0 ? z
: z
- 146096) / 146097;
214 /* The day-of-era (doe) can then be found by subtracting the era number
215 * times the number of days per era, from the serial date.
217 doe
= (z
- era
* 146097);
219 /* From the day-of-era (doe), the year-of-era (yoe, range [0, 399]) can
222 yoe
= (doe
- doe
/ 1460 + doe
/ 36524 - doe
/ 146096) / 365;
224 /* Given year-of-era, and era, one can now compute the year. */
225 year
= yoe
+ era
* 400;
227 /* Also the day-of-year, again with the year beginning on Mar. 1, can be
228 * computed from the day-of-era and year-of-era.
230 doy
= doe
- (365 * yoe
+ yoe
/ 4 - yoe
/ 100);
232 /* Given day-of-year, find the month number. */
233 mp
= (5 * doy
+ 2) / 153;
235 /* From day-of-year and month-of-year we can now easily compute
238 day
= doy
- (153 * mp
+ 2) / 5 + 1;
240 /* Transform the month number from the [0, 11] / [Mar, Feb] system to
241 * the civil system: [1, 12] to find the correct month.
243 month
= mp
+ (mp
< 10 ? 3 : -9);
245 /* The algorithm assumes that a year begins on 1 March, so add 1 before
250 /* Transform days in the epoch to seconds. */
251 d_in_s
= epoch_to_days
* 86400;
253 /* To find the current hour simply substract the Epoch_to_days from the
254 * total Epoch and divide by the number of seconds in an hour.
256 hours
= (time
->tv_sec
- d_in_s
) / 3600;
258 /* Transform hours to seconds. */
259 h_in_s
= hours
* 3600;
261 /* Calculate minutes by substracting the seconds for all days in the
262 * epoch and for all hours in the epoch and divide by the number of
263 * minutes in an hour.
265 minutes
= (time
->tv_sec
- d_in_s
- h_in_s
) / 60;
267 /* Calculate the seconds by substracting the seconds for all days in the
268 * epoch, hours in the epoch and minutes in the epoch.
270 seconds
= (time
->tv_sec
- d_in_s
- h_in_s
- (minutes
* 60));
272 /* Make string from nanoseconds. */
273 ret
= snprintf(nanosec
, sizeof(nanosec
), "%"PRId64
, (int64_t)time
->tv_nsec
);
274 if (ret
< 0 || ret
>= sizeof(nanosec
))
277 /* Create final timestamp for the log and shorten nanoseconds to 3
280 ret
= snprintf(buf
, bufsize
,
281 "%" PRId64
"%02" PRId64
"%02" PRId64
"%02" PRId64
282 "%02" PRId64
"%02" PRId64
".%.3s",
283 year
, month
, day
, hours
, minutes
, seconds
, nanosec
);
284 if (ret
< 0 || (size_t)ret
>= bufsize
)
290 /* This function needs to make extra sure that it is thread-safe. We had some
291 * problems with that before. This especially involves time-conversion
292 * functions. I don't want to find any localtime() or gmtime() functions or
293 * relatives in here. Not even localtime_r() or gmtime_r() or relatives. They
294 * all fiddle with global variables and locking in various libcs. They cause
295 * deadlocks when liblxc is used multi-threaded and no matter how smart you
296 * think you are, you __will__ cause trouble using them.
297 * (As a short example how this can cause trouble: LXD uses forkstart to fork
298 * off a new process that runs the container. At the same time the go runtime
299 * LXD relies on does its own multi-threading thing which we can't control. The
300 * fork()ing + threading then seems to mess with the locking states in these
301 * time functions causing deadlocks.)
302 * The current solution is to be good old unix people and use the Epoch as our
303 * reference point and simply use the seconds and nanoseconds that have past
304 * since then. This relies on clock_gettime() which is explicitly marked MT-Safe
305 * with no restrictions! This way, anyone who is really strongly invested in
306 * getting the actual time the log entry was created, can just convert it for
307 * themselves. Our logging is mostly done for debugging purposes so don't try
308 * to make it pretty. Pretty might cost you thread-safety.
310 static int log_append_logfile(const struct lxc_log_appender
*appender
,
311 struct lxc_log_event
*event
)
313 char buffer
[LXC_LOG_BUFFER_SIZE
];
314 char date_time
[LXC_LOG_TIME_SIZE
];
318 const char *log_container_name
;
322 if (!lxc_log_use_global_fd
)
323 fd_to_use
= current_config
->logfd
;
326 log_container_name
= lxc_log_get_container_name();
329 fd_to_use
= lxc_log_fd
;
334 if (lxc_unix_epoch_to_utc(date_time
, LXC_LOG_TIME_SIZE
, &event
->timestamp
) < 0)
337 n
= snprintf(buffer
, sizeof(buffer
),
338 "%s%s%s %s %-8s %s - %s:%s:%d - ",
340 log_container_name
? " " : "",
341 log_container_name
? log_container_name
: "",
343 lxc_log_priority_to_string(event
->priority
),
345 event
->locinfo
->file
, event
->locinfo
->func
,
346 event
->locinfo
->line
);
350 if ((size_t)n
< STRARRAYLEN(buffer
)) {
351 ret
= vsnprintf(buffer
+ n
, sizeof(buffer
) - n
, event
->fmt
, *event
->vap
);
358 if ((size_t)n
>= sizeof(buffer
))
359 n
= STRARRAYLEN(buffer
);
364 ret
= write(fd_to_use
, buffer
, n
+ 1);
365 if (ret
< 0 && errno
== EINTR
)
372 static int log_append_dlog(const struct lxc_log_appender
*appender
,
373 struct lxc_log_event
*event
)
375 char *msg
= lxc_log_get_va_msg(event
);
376 const char *log_container_name
= lxc_log_get_container_name();
378 switch (event
->priority
) {
379 case LXC_LOG_LEVEL_TRACE
:
380 case LXC_LOG_LEVEL_DEBUG
:
381 print_log(DLOG_DEBUG
, LOG_TAG
, "%s: %s(%d) > [%s] %s",
382 event
->locinfo
->file
, event
->locinfo
->func
, event
->locinfo
->line
,
383 log_container_name
? log_container_name
: "-",
386 case LXC_LOG_LEVEL_INFO
:
387 print_log(DLOG_INFO
, LOG_TAG
, "%s: %s(%d) > [%s] %s",
388 event
->locinfo
->file
, event
->locinfo
->func
, event
->locinfo
->line
,
389 log_container_name
? log_container_name
: "-",
392 case LXC_LOG_LEVEL_NOTICE
:
393 case LXC_LOG_LEVEL_WARN
:
394 print_log(DLOG_WARN
, LOG_TAG
, "%s: %s(%d) > [%s] %s",
395 event
->locinfo
->file
, event
->locinfo
->func
, event
->locinfo
->line
,
396 log_container_name
? log_container_name
: "-",
399 case LXC_LOG_LEVEL_ERROR
:
400 print_log(DLOG_ERROR
, LOG_TAG
, "%s: %s(%d) > [%s] %s",
401 event
->locinfo
->file
, event
->locinfo
->func
, event
->locinfo
->line
,
402 log_container_name
? log_container_name
: "-",
405 case LXC_LOG_LEVEL_CRIT
:
406 case LXC_LOG_LEVEL_ALERT
:
407 case LXC_LOG_LEVEL_FATAL
:
408 print_log(DLOG_FATAL
, LOG_TAG
, "%s: %s(%d) > [%s] %s",
409 event
->locinfo
->file
, event
->locinfo
->func
, event
->locinfo
->line
,
410 log_container_name
? log_container_name
: "-",
422 static struct lxc_log_appender log_appender_syslog
= {
424 .append
= log_append_syslog
,
428 static struct lxc_log_appender log_appender_stderr
= {
430 .append
= log_append_stderr
,
434 static struct lxc_log_appender log_appender_logfile
= {
436 .append
= log_append_logfile
,
441 static struct lxc_log_appender log_appender_dlog
= {
443 .append
= log_append_dlog
,
448 static struct lxc_log_category log_root
= {
450 .priority
= LXC_LOG_LEVEL_ERROR
,
456 struct lxc_log_category lxc_log_category_lxc
= {
458 .priority
= LXC_LOG_LEVEL_TRACE
,
459 .appender
= &log_appender_dlog
,
463 struct lxc_log_category lxc_log_category_lxc
= {
465 .priority
= LXC_LOG_LEVEL_ERROR
,
466 .appender
= &log_appender_logfile
,
471 /*---------------------------------------------------------------------------*/
472 static int build_dir(const char *name
)
476 /* Make copy of the string since we'll be modifying it. */
482 for (p
= n
+ 1; p
< e
; p
++) {
489 ret
= lxc_unpriv(mkdir(n
, 0755));
490 if (ret
&& errno
!= EEXIST
) {
491 SYSERROR("Failed to create directory %s", n
);
503 /*---------------------------------------------------------------------------*/
504 static int log_open(const char *name
)
509 fd
= lxc_unpriv(open(name
, O_CREAT
| O_WRONLY
| O_APPEND
| O_CLOEXEC
, 0666));
511 SYSERROR("Failed to open log file \"%s\"", name
);
518 newfd
= fcntl(fd
, F_DUPFD_CLOEXEC
, STDERR_FILENO
);
520 SYSERROR("Failed to dup log fd %d", fd
);
527 * Build the path to the log file
528 * @name : the name of the container
529 * @lxcpath : the lxcpath to use as a basename or NULL to use LOGPATH
530 * Returns malloced path on success, or NULL on failure
532 static char *build_log_path(const char *name
, const char *lxcpath
)
542 #if USE_CONFIGPATH_LOGS
549 * If USE_CONFIGPATH_LOGS is true or lxcpath is given, the resulting
551 * '$logpath' + '/' + '$name' + '/' + '$name' + '.log' + '\0'
553 * If USE_CONFIGPATH_LOGS is false the resulting path will be:
554 * '$logpath' + '/' + '$name' + '.log' + '\0'
556 len
= strlen(name
) + 6; /* 6 == '/' + '.log' + '\0' */
563 len
+= strlen(lxcpath
) + 1 + strlen(name
) + 1; /* add "/$container_name/" */
565 len
+= strlen(lxcpath
) + 1;
572 ret
= snprintf(p
, len
, "%s/%s/%s.log", lxcpath
, name
, name
);
574 ret
= snprintf(p
, len
, "%s/%s.log", lxcpath
, name
);
575 if (ret
< 0 || (size_t)ret
>= len
) {
584 * This can be called:
585 * 1. when a program calls lxc_log_init with no logfile parameter (in which
586 * case the default is used). In this case lxc.loge can override this.
587 * 2. when a program calls lxc_log_init with a logfile parameter. In this
588 * case we don't want lxc.log to override this.
589 * 3. When a lxc.log entry is found in config file.
591 static int __lxc_log_set_file(const char *fname
, int create_dirs
)
593 /* we are overriding the default. */
594 if (lxc_log_fd
!= -1)
600 if (strlen(fname
) == 0) {
605 #if USE_CONFIGPATH_LOGS
606 /* We don't build_dir for the default if the default is i.e.
607 * /var/lib/lxc/$container/$container.log.
611 if (build_dir(fname
)) {
612 SYSERROR("Failed to create dir for log file \"%s\"", fname
);
616 lxc_log_fd
= log_open(fname
);
617 if (lxc_log_fd
== -1)
620 log_fname
= strdup(fname
);
624 static int _lxc_log_set_file(const char *name
, const char *lxcpath
, int create_dirs
)
629 logfile
= build_log_path(name
, lxcpath
);
631 ERROR("Could not build log path");
635 ret
= __lxc_log_set_file(logfile
, create_dirs
);
642 * Called from lxc front-end programs (like lxc-create, lxc-start) to
643 * initialize the log defaults.
645 int lxc_log_init(struct lxc_log
*log
)
648 int lxc_priority
= LXC_LOG_LEVEL_ERROR
;
653 if (lxc_log_fd
!= -1) {
654 WARN("Log already initialized");
659 lxc_priority
= lxc_log_priority_to_int(log
->level
);
661 if (!lxc_loglevel_specified
) {
662 lxc_log_category_lxc
.priority
= lxc_priority
;
663 lxc_loglevel_specified
= 1;
666 if (!lxc_quiet_specified
)
668 lxc_log_category_lxc
.appender
->next
= &log_appender_stderr
;
671 lxc_log_set_prefix(log
->prefix
);
674 log_vmname
= strdup(log
->name
);
677 if (strcmp(log
->file
, "none") == 0)
680 ret
= __lxc_log_set_file(log
->file
, 1);
682 ERROR("Failed to enable logfile");
686 lxc_log_use_global_fd
= 1;
688 /* if no name was specified, there nothing to do */
695 log
->lxcpath
= LOGPATH
;
697 /* try LOGPATH if lxcpath is the default for the privileged containers */
698 if (!geteuid() && strcmp(LXCPATH
, log
->lxcpath
) == 0)
699 ret
= _lxc_log_set_file(log
->name
, NULL
, 0);
703 ret
= _lxc_log_set_file(log
->name
, log
->lxcpath
, 1);
705 /* try LOGPATH in case its writable by the caller */
707 ret
= _lxc_log_set_file(log
->name
, NULL
, 0);
711 * If !file, that is, if the user did not request this logpath, then
712 * ignore failures and continue logging to console
714 if (!log
->file
&& ret
!= 0) {
715 INFO("Ignoring failure to open default logfile");
719 if (lxc_log_fd
!= -1) {
720 lxc_log_category_lxc
.appender
= &log_appender_logfile
;
721 lxc_log_category_lxc
.appender
->next
= &log_appender_stderr
;
727 void lxc_log_close(void)
734 if (lxc_log_fd
== -1)
744 int lxc_log_syslog(int facility
)
746 struct lxc_log_appender
*appender
;
748 openlog(log_prefix
, LOG_PID
, facility
);
749 if (!lxc_log_category_lxc
.appender
) {
750 lxc_log_category_lxc
.appender
= &log_appender_syslog
;
754 appender
= lxc_log_category_lxc
.appender
;
755 /* Check if syslog was already added, to avoid creating a loop */
757 if (appender
== &log_appender_syslog
) {
758 /* not an error: openlog re-opened the connection */
761 appender
= appender
->next
;
764 appender
= lxc_log_category_lxc
.appender
;
765 while (appender
->next
!= NULL
)
766 appender
= appender
->next
;
767 appender
->next
= &log_appender_syslog
;
772 inline void lxc_log_enable_syslog(void)
778 * This is called when we read a lxc.log.level entry in a lxc.conf file. This
779 * happens after processing command line arguments, which override the .conf
780 * settings. So only set the level if previously unset.
782 int lxc_log_set_level(int *dest
, int level
)
784 if (level
< 0 || level
>= LXC_LOG_LEVEL_NOTSET
) {
785 ERROR("Invalid log priority %d", level
);
793 inline int lxc_log_get_level(void)
795 return lxc_log_category_lxc
.priority
;
798 bool lxc_log_has_valid_level(void)
802 log_level
= lxc_log_get_level();
803 if (log_level
< 0 || log_level
>= LXC_LOG_LEVEL_NOTSET
)
810 * This is called when we read a lxc.logfile entry in a lxc.conf file. This
811 * happens after processing command line arguments, which override the .conf
812 * settings. So only set the file if previously unset.
814 int lxc_log_set_file(int *fd
, const char *fname
)
821 if (build_dir(fname
))
824 *fd
= log_open(fname
);
831 inline const char *lxc_log_get_file(void)
836 inline void lxc_log_set_prefix(const char *prefix
)
838 /* We don't care if the prefix is truncated. */
839 (void)strlcpy(log_prefix
, prefix
, sizeof(log_prefix
));
842 inline const char *lxc_log_get_prefix(void)
847 inline void lxc_log_options_no_override()
849 lxc_quiet_specified
= 1;
850 lxc_loglevel_specified
= 1;