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>
44 #include "file_utils.h"
46 #include "lxccontainer.h"
50 #include "include/strlcpy.h"
60 /* We're logging in seconds and nanoseconds. Assuming that the underlying
61 * datatype is currently at maximum a 64bit integer, we have a date string that
62 * is of maximum length (2^64 - 1) * 2 = (21 + 21) = 42.
64 #define LXC_LOG_TIME_SIZE ((INTTYPE_TO_STRLEN(uint64_t)) * 2)
67 static int syslog_enable
= 0;
68 int lxc_quiet_specified
;
69 int lxc_log_use_global_fd
;
70 static int lxc_loglevel_specified
;
72 static char log_prefix
[LXC_LOG_PREFIX_SIZE
] = "lxc";
73 static char *log_fname
= NULL
;
74 static char *log_vmname
= NULL
;
76 lxc_log_define(log
, lxc
);
78 static int lxc_log_priority_to_syslog(int priority
)
81 case LXC_LOG_LEVEL_FATAL
:
83 case LXC_LOG_LEVEL_ALERT
:
85 case LXC_LOG_LEVEL_CRIT
:
87 case LXC_LOG_LEVEL_ERROR
:
89 case LXC_LOG_LEVEL_WARN
:
91 case LXC_LOG_LEVEL_NOTICE
:
92 case LXC_LOG_LEVEL_NOTSET
:
94 case LXC_LOG_LEVEL_INFO
:
96 case LXC_LOG_LEVEL_TRACE
:
97 case LXC_LOG_LEVEL_DEBUG
:
105 static const char *lxc_log_get_container_name()
108 if (current_config
&& !log_vmname
)
109 return current_config
->name
;
115 static char *lxc_log_get_va_msg(struct lxc_log_event
*event
)
124 va_copy(args
, *event
->vap
);
125 #pragma GCC diagnostic push
126 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
127 len
= vsnprintf(NULL
, 0, event
->fmt
, args
) + 1;
128 #pragma GCC diagnostic pop
131 msg
= malloc(len
* sizeof(char));
135 #pragma GCC diagnostic push
136 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
137 rc
= vsnprintf(msg
, len
, event
->fmt
, *event
->vap
);
138 #pragma GCC diagnostic pop
139 if (rc
== -1 || rc
>= len
) {
147 /*---------------------------------------------------------------------------*/
148 static int log_append_syslog(const struct lxc_log_appender
*appender
,
149 struct lxc_log_event
*event
)
152 const char *log_container_name
;
157 log_container_name
= lxc_log_get_container_name();
159 msg
= lxc_log_get_va_msg(event
);
163 syslog(lxc_log_priority_to_syslog(event
->priority
),
164 "%s%s %s - %s:%s:%d - %s" ,
165 log_container_name
? log_container_name
: "",
166 log_container_name
? ":" : "",
168 event
->locinfo
->file
, event
->locinfo
->func
,
169 event
->locinfo
->line
,
176 /*---------------------------------------------------------------------------*/
177 static int log_append_stderr(const struct lxc_log_appender
*appender
,
178 struct lxc_log_event
*event
)
180 const char *log_container_name
;
182 if (event
->priority
< LXC_LOG_LEVEL_ERROR
)
185 log_container_name
= lxc_log_get_container_name();
187 fprintf(stderr
, "%s: %s%s", log_prefix
,
188 log_container_name
? log_container_name
: "",
189 log_container_name
? ": " : "");
190 fprintf(stderr
, "%s: %s: %d ", event
->locinfo
->file
,
191 event
->locinfo
->func
, event
->locinfo
->line
);
192 #pragma GCC diagnostic push
193 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
194 vfprintf(stderr
, event
->fmt
, *event
->vap
);
195 #pragma GCC diagnostic pop
196 fprintf(stderr
, "\n");
201 /*---------------------------------------------------------------------------*/
202 static int lxc_unix_epoch_to_utc(char *buf
, size_t bufsize
, const struct timespec
*time
)
204 int64_t epoch_to_days
, z
, era
, doe
, yoe
, year
, doy
, mp
, day
, month
,
205 d_in_s
, hours
, h_in_s
, minutes
, seconds
;
206 char nanosec
[INTTYPE_TO_STRLEN(int64_t)];
209 /* See https://howardhinnant.github.io/date_algorithms.html for an
210 * explanation of the algorithm used here.
213 /* Convert Epoch in seconds to number of days. */
214 epoch_to_days
= time
->tv_sec
/ 86400;
216 /* Shift the Epoch from 1970-01-01 to 0000-03-01. */
217 z
= epoch_to_days
+ 719468;
219 /* compute the era from the serial date by simply dividing by the number
220 * of days in an era (146097).
222 era
= (z
>= 0 ? z
: z
- 146096) / 146097;
224 /* The day-of-era (doe) can then be found by subtracting the era number
225 * times the number of days per era, from the serial date.
227 doe
= (z
- era
* 146097);
229 /* From the day-of-era (doe), the year-of-era (yoe, range [0, 399]) can
232 yoe
= (doe
- doe
/ 1460 + doe
/ 36524 - doe
/ 146096) / 365;
234 /* Given year-of-era, and era, one can now compute the year. */
235 year
= yoe
+ era
* 400;
237 /* Also the day-of-year, again with the year beginning on Mar. 1, can be
238 * computed from the day-of-era and year-of-era.
240 doy
= doe
- (365 * yoe
+ yoe
/ 4 - yoe
/ 100);
242 /* Given day-of-year, find the month number. */
243 mp
= (5 * doy
+ 2) / 153;
245 /* From day-of-year and month-of-year we can now easily compute
248 day
= doy
- (153 * mp
+ 2) / 5 + 1;
250 /* Transform the month number from the [0, 11] / [Mar, Feb] system to
251 * the civil system: [1, 12] to find the correct month.
253 month
= mp
+ (mp
< 10 ? 3 : -9);
255 /* The algorithm assumes that a year begins on 1 March, so add 1 before
260 /* Transform days in the epoch to seconds. */
261 d_in_s
= epoch_to_days
* 86400;
263 /* To find the current hour simply substract the Epoch_to_days from the
264 * total Epoch and divide by the number of seconds in an hour.
266 hours
= (time
->tv_sec
- d_in_s
) / 3600;
268 /* Transform hours to seconds. */
269 h_in_s
= hours
* 3600;
271 /* Calculate minutes by subtracting the seconds for all days in the
272 * epoch and for all hours in the epoch and divide by the number of
273 * minutes in an hour.
275 minutes
= (time
->tv_sec
- d_in_s
- h_in_s
) / 60;
277 /* Calculate the seconds by subtracting the seconds for all days in the
278 * epoch, hours in the epoch and minutes in the epoch.
280 seconds
= (time
->tv_sec
- d_in_s
- h_in_s
- (minutes
* 60));
282 /* Make string from nanoseconds. */
283 ret
= snprintf(nanosec
, sizeof(nanosec
), "%"PRId64
, (int64_t)time
->tv_nsec
);
284 if (ret
< 0 || ret
>= sizeof(nanosec
))
287 /* Create final timestamp for the log and shorten nanoseconds to 3
290 ret
= snprintf(buf
, bufsize
,
291 "%" PRId64
"%02" PRId64
"%02" PRId64
"%02" PRId64
292 "%02" PRId64
"%02" PRId64
".%.3s",
293 year
, month
, day
, hours
, minutes
, seconds
, nanosec
);
294 if (ret
< 0 || (size_t)ret
>= bufsize
)
300 /* This function needs to make extra sure that it is thread-safe. We had some
301 * problems with that before. This especially involves time-conversion
302 * functions. I don't want to find any localtime() or gmtime() functions or
303 * relatives in here. Not even localtime_r() or gmtime_r() or relatives. They
304 * all fiddle with global variables and locking in various libcs. They cause
305 * deadlocks when liblxc is used multi-threaded and no matter how smart you
306 * think you are, you __will__ cause trouble using them.
307 * (As a short example how this can cause trouble: LXD uses forkstart to fork
308 * off a new process that runs the container. At the same time the go runtime
309 * LXD relies on does its own multi-threading thing which we can't control. The
310 * fork()ing + threading then seems to mess with the locking states in these
311 * time functions causing deadlocks.)
312 * The current solution is to be good old unix people and use the Epoch as our
313 * reference point and simply use the seconds and nanoseconds that have past
314 * since then. This relies on clock_gettime() which is explicitly marked MT-Safe
315 * with no restrictions! This way, anyone who is really strongly invested in
316 * getting the actual time the log entry was created, can just convert it for
317 * themselves. Our logging is mostly done for debugging purposes so don't try
318 * to make it pretty. Pretty might cost you thread-safety.
320 static int log_append_logfile(const struct lxc_log_appender
*appender
,
321 struct lxc_log_event
*event
)
323 char buffer
[LXC_LOG_BUFFER_SIZE
];
324 char date_time
[LXC_LOG_TIME_SIZE
];
328 const char *log_container_name
;
332 if (!lxc_log_use_global_fd
)
333 fd_to_use
= current_config
->logfd
;
336 log_container_name
= lxc_log_get_container_name();
339 fd_to_use
= lxc_log_fd
;
344 if (lxc_unix_epoch_to_utc(date_time
, LXC_LOG_TIME_SIZE
, &event
->timestamp
) < 0)
347 n
= snprintf(buffer
, sizeof(buffer
),
348 "%s%s%s %s %-8s %s - %s:%s:%d - ",
350 log_container_name
? " " : "",
351 log_container_name
? log_container_name
: "",
353 lxc_log_priority_to_string(event
->priority
),
355 event
->locinfo
->file
, event
->locinfo
->func
,
356 event
->locinfo
->line
);
360 if ((size_t)n
< STRARRAYLEN(buffer
)) {
361 #pragma GCC diagnostic push
362 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
363 ret
= vsnprintf(buffer
+ n
, sizeof(buffer
) - n
, event
->fmt
, *event
->vap
);
364 #pragma GCC diagnostic pop
371 if ((size_t)n
>= sizeof(buffer
))
372 n
= STRARRAYLEN(buffer
);
376 return lxc_write_nointr(fd_to_use
, buffer
, n
+ 1);
380 static int log_append_dlog(const struct lxc_log_appender
*appender
,
381 struct lxc_log_event
*event
)
383 char *msg
= lxc_log_get_va_msg(event
);
384 const char *log_container_name
= lxc_log_get_container_name();
386 switch (event
->priority
) {
387 case LXC_LOG_LEVEL_TRACE
:
388 case LXC_LOG_LEVEL_DEBUG
:
389 print_log(DLOG_DEBUG
, LOG_TAG
, "%s: %s(%d) > [%s] %s",
390 event
->locinfo
->file
, event
->locinfo
->func
, event
->locinfo
->line
,
391 log_container_name
? log_container_name
: "-",
394 case LXC_LOG_LEVEL_INFO
:
395 print_log(DLOG_INFO
, LOG_TAG
, "%s: %s(%d) > [%s] %s",
396 event
->locinfo
->file
, event
->locinfo
->func
, event
->locinfo
->line
,
397 log_container_name
? log_container_name
: "-",
400 case LXC_LOG_LEVEL_NOTICE
:
401 case LXC_LOG_LEVEL_WARN
:
402 print_log(DLOG_WARN
, LOG_TAG
, "%s: %s(%d) > [%s] %s",
403 event
->locinfo
->file
, event
->locinfo
->func
, event
->locinfo
->line
,
404 log_container_name
? log_container_name
: "-",
407 case LXC_LOG_LEVEL_ERROR
:
408 print_log(DLOG_ERROR
, LOG_TAG
, "%s: %s(%d) > [%s] %s",
409 event
->locinfo
->file
, event
->locinfo
->func
, event
->locinfo
->line
,
410 log_container_name
? log_container_name
: "-",
413 case LXC_LOG_LEVEL_CRIT
:
414 case LXC_LOG_LEVEL_ALERT
:
415 case LXC_LOG_LEVEL_FATAL
:
416 print_log(DLOG_FATAL
, LOG_TAG
, "%s: %s(%d) > [%s] %s",
417 event
->locinfo
->file
, event
->locinfo
->func
, event
->locinfo
->line
,
418 log_container_name
? log_container_name
: "-",
430 static struct lxc_log_appender log_appender_syslog
= {
432 .append
= log_append_syslog
,
436 static struct lxc_log_appender log_appender_stderr
= {
438 .append
= log_append_stderr
,
442 static struct lxc_log_appender log_appender_logfile
= {
444 .append
= log_append_logfile
,
449 static struct lxc_log_appender log_appender_dlog
= {
451 .append
= log_append_dlog
,
456 static struct lxc_log_category log_root
= {
458 .priority
= LXC_LOG_LEVEL_ERROR
,
464 struct lxc_log_category lxc_log_category_lxc
= {
466 .priority
= LXC_LOG_LEVEL_TRACE
,
467 .appender
= &log_appender_dlog
,
471 struct lxc_log_category lxc_log_category_lxc
= {
473 .priority
= LXC_LOG_LEVEL_ERROR
,
474 .appender
= &log_appender_logfile
,
479 /*---------------------------------------------------------------------------*/
480 static int build_dir(const char *name
)
484 /* Make copy of the string since we'll be modifying it. */
490 for (p
= n
+ 1; p
< e
; p
++) {
497 ret
= lxc_unpriv(mkdir(n
, 0755));
498 if (ret
&& errno
!= EEXIST
) {
499 SYSERROR("Failed to create directory \"%s\"", n
);
511 /*---------------------------------------------------------------------------*/
512 static int log_open(const char *name
)
517 fd
= lxc_unpriv(open(name
, O_CREAT
| O_WRONLY
| O_APPEND
| O_CLOEXEC
, 0660));
519 SYSERROR("Failed to open log file \"%s\"", name
);
526 newfd
= fcntl(fd
, F_DUPFD_CLOEXEC
, STDERR_FILENO
);
528 SYSERROR("Failed to dup log fd %d", fd
);
535 * Build the path to the log file
536 * @name : the name of the container
537 * @lxcpath : the lxcpath to use as a basename or NULL to use LOGPATH
538 * Returns malloced path on success, or NULL on failure
540 static char *build_log_path(const char *name
, const char *lxcpath
)
550 #if USE_CONFIGPATH_LOGS
557 * If USE_CONFIGPATH_LOGS is true or lxcpath is given, the resulting
559 * '$logpath' + '/' + '$name' + '/' + '$name' + '.log' + '\0'
561 * If USE_CONFIGPATH_LOGS is false the resulting path will be:
562 * '$logpath' + '/' + '$name' + '.log' + '\0'
564 len
= strlen(name
) + 6; /* 6 == '/' + '.log' + '\0' */
571 len
+= strlen(lxcpath
) + 1 + strlen(name
) + 1; /* add "/$container_name/" */
573 len
+= strlen(lxcpath
) + 1;
580 ret
= snprintf(p
, len
, "%s/%s/%s.log", lxcpath
, name
, name
);
582 ret
= snprintf(p
, len
, "%s/%s.log", lxcpath
, name
);
583 if (ret
< 0 || (size_t)ret
>= len
) {
592 * This can be called:
593 * 1. when a program calls lxc_log_init with no logfile parameter (in which
594 * case the default is used). In this case lxc.loge can override this.
595 * 2. when a program calls lxc_log_init with a logfile parameter. In this
596 * case we don't want lxc.log to override this.
597 * 3. When a lxc.log entry is found in config file.
599 static int __lxc_log_set_file(const char *fname
, int create_dirs
)
601 /* we are overriding the default. */
602 if (lxc_log_fd
!= -1)
608 if (strlen(fname
) == 0) {
613 #if USE_CONFIGPATH_LOGS
614 /* We don't build_dir for the default if the default is i.e.
615 * /var/lib/lxc/$container/$container.log.
619 if (build_dir(fname
)) {
620 SYSERROR("Failed to create dir for log file \"%s\"", fname
);
624 lxc_log_fd
= log_open(fname
);
625 if (lxc_log_fd
== -1)
628 log_fname
= strdup(fname
);
632 static int _lxc_log_set_file(const char *name
, const char *lxcpath
, int create_dirs
)
637 logfile
= build_log_path(name
, lxcpath
);
639 ERROR("Could not build log path");
643 ret
= __lxc_log_set_file(logfile
, create_dirs
);
650 * Called from lxc front-end programs (like lxc-create, lxc-start) to
651 * initialize the log defaults.
653 int lxc_log_init(struct lxc_log
*log
)
656 int lxc_priority
= LXC_LOG_LEVEL_ERROR
;
661 if (lxc_log_fd
!= -1) {
662 WARN("Log already initialized");
667 lxc_priority
= lxc_log_priority_to_int(log
->level
);
669 if (!lxc_loglevel_specified
) {
670 lxc_log_category_lxc
.priority
= lxc_priority
;
671 lxc_loglevel_specified
= 1;
674 if (!lxc_quiet_specified
)
676 lxc_log_category_lxc
.appender
->next
= &log_appender_stderr
;
679 lxc_log_set_prefix(log
->prefix
);
682 log_vmname
= strdup(log
->name
);
685 if (strcmp(log
->file
, "none") == 0)
688 ret
= __lxc_log_set_file(log
->file
, 1);
690 ERROR("Failed to enable logfile");
694 lxc_log_use_global_fd
= 1;
696 /* if no name was specified, there nothing to do */
703 log
->lxcpath
= LOGPATH
;
705 /* try LOGPATH if lxcpath is the default for the privileged containers */
706 if (!geteuid() && strcmp(LXCPATH
, log
->lxcpath
) == 0)
707 ret
= _lxc_log_set_file(log
->name
, NULL
, 0);
711 ret
= _lxc_log_set_file(log
->name
, log
->lxcpath
, 1);
713 /* try LOGPATH in case its writable by the caller */
715 ret
= _lxc_log_set_file(log
->name
, NULL
, 0);
719 * If !file, that is, if the user did not request this logpath, then
720 * ignore failures and continue logging to console
722 if (!log
->file
&& ret
!= 0) {
723 INFO("Ignoring failure to open default logfile");
727 if (lxc_log_fd
!= -1) {
728 lxc_log_category_lxc
.appender
= &log_appender_logfile
;
729 lxc_log_category_lxc
.appender
->next
= &log_appender_stderr
;
735 void lxc_log_close(void)
742 if (lxc_log_fd
== -1)
752 int lxc_log_syslog(int facility
)
754 struct lxc_log_appender
*appender
;
756 openlog(log_prefix
, LOG_PID
, facility
);
757 if (!lxc_log_category_lxc
.appender
) {
758 lxc_log_category_lxc
.appender
= &log_appender_syslog
;
762 appender
= lxc_log_category_lxc
.appender
;
763 /* Check if syslog was already added, to avoid creating a loop */
765 if (appender
== &log_appender_syslog
) {
766 /* not an error: openlog re-opened the connection */
769 appender
= appender
->next
;
772 appender
= lxc_log_category_lxc
.appender
;
773 while (appender
->next
!= NULL
)
774 appender
= appender
->next
;
775 appender
->next
= &log_appender_syslog
;
780 inline void lxc_log_enable_syslog(void)
786 * This is called when we read a lxc.log.level entry in a lxc.conf file. This
787 * happens after processing command line arguments, which override the .conf
788 * settings. So only set the level if previously unset.
790 int lxc_log_set_level(int *dest
, int level
)
792 if (level
< 0 || level
>= LXC_LOG_LEVEL_NOTSET
) {
793 ERROR("Invalid log priority %d", level
);
801 inline int lxc_log_get_level(void)
803 return lxc_log_category_lxc
.priority
;
806 bool lxc_log_has_valid_level(void)
810 log_level
= lxc_log_get_level();
811 if (log_level
< 0 || log_level
>= LXC_LOG_LEVEL_NOTSET
)
818 * This is called when we read a lxc.logfile entry in a lxc.conf file. This
819 * happens after processing command line arguments, which override the .conf
820 * settings. So only set the file if previously unset.
822 int lxc_log_set_file(int *fd
, const char *fname
)
829 if (build_dir(fname
))
832 *fd
= log_open(fname
);
839 inline const char *lxc_log_get_file(void)
844 inline void lxc_log_set_prefix(const char *prefix
)
846 /* We don't care if the prefix is truncated. */
847 (void)strlcpy(log_prefix
, prefix
, sizeof(log_prefix
));
850 inline const char *lxc_log_get_prefix(void)
855 inline void lxc_log_options_no_override()
857 lxc_quiet_specified
= 1;
858 lxc_loglevel_specified
= 1;