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
25 #define __STDC_FORMAT_MACROS /* Required for PRIu64 to work. */
32 #include <sys/types.h>
46 #include "lxccontainer.h"
49 #include "include/strlcpy.h"
52 /* We're logging in seconds and nanoseconds. Assuming that the underlying
53 * datatype is currently at maximum a 64bit integer, we have a date string that
54 * is of maximum length (2^64 - 1) * 2 = (21 + 21) = 42.
56 #define LXC_LOG_TIME_SIZE ((INTTYPE_TO_STRLEN(uint64_t)) * 2)
59 static int syslog_enable
= 0;
60 int lxc_quiet_specified
;
61 int lxc_log_use_global_fd
;
62 static int lxc_loglevel_specified
;
64 static char log_prefix
[LXC_LOG_PREFIX_SIZE
] = "lxc";
65 static char *log_fname
= NULL
;
66 static char *log_vmname
= NULL
;
68 lxc_log_define(log
, lxc
);
70 static int lxc_log_priority_to_syslog(int priority
)
73 case LXC_LOG_LEVEL_FATAL
:
75 case LXC_LOG_LEVEL_ALERT
:
77 case LXC_LOG_LEVEL_CRIT
:
79 case LXC_LOG_LEVEL_ERROR
:
81 case LXC_LOG_LEVEL_WARN
:
83 case LXC_LOG_LEVEL_NOTICE
:
84 case LXC_LOG_LEVEL_NOTSET
:
86 case LXC_LOG_LEVEL_INFO
:
88 case LXC_LOG_LEVEL_TRACE
:
89 case LXC_LOG_LEVEL_DEBUG
:
97 /*---------------------------------------------------------------------------*/
98 static int log_append_syslog(const struct lxc_log_appender
*appender
,
99 struct lxc_log_event
*event
)
104 const char *log_container_name
= log_vmname
;
107 if (current_config
&& !log_container_name
)
108 log_container_name
= current_config
->name
;
114 va_copy(args
, *event
->vap
);
115 len
= vsnprintf(NULL
, 0, event
->fmt
, args
) + 1;
118 msg
= malloc(len
* sizeof(char));
122 rc
= vsnprintf(msg
, len
, event
->fmt
, *event
->vap
);
123 if (rc
== -1 || rc
>= len
) {
128 syslog(lxc_log_priority_to_syslog(event
->priority
),
129 "%s%s %s - %s:%s:%d - %s" ,
130 log_container_name
? log_container_name
: "",
131 log_container_name
? ":" : "",
133 event
->locinfo
->file
, event
->locinfo
->func
,
134 event
->locinfo
->line
,
141 /*---------------------------------------------------------------------------*/
142 static int log_append_stderr(const struct lxc_log_appender
*appender
,
143 struct lxc_log_event
*event
)
145 const char *log_container_name
;
147 if (event
->priority
< LXC_LOG_LEVEL_ERROR
)
150 log_container_name
= log_vmname
;
153 if (current_config
&& !log_container_name
)
154 log_container_name
= current_config
->name
;
157 fprintf(stderr
, "%s: %s%s", log_prefix
,
158 log_container_name
? log_container_name
: "",
159 log_container_name
? ": " : "");
160 fprintf(stderr
, "%s: %s: %d ", event
->locinfo
->file
,
161 event
->locinfo
->func
, event
->locinfo
->line
);
162 vfprintf(stderr
, event
->fmt
, *event
->vap
);
163 fprintf(stderr
, "\n");
168 /*---------------------------------------------------------------------------*/
169 static int lxc_unix_epoch_to_utc(char *buf
, size_t bufsize
, const struct timespec
*time
)
171 int64_t epoch_to_days
, z
, era
, doe
, yoe
, year
, doy
, mp
, day
, month
,
172 d_in_s
, hours
, h_in_s
, minutes
, seconds
;
173 char nanosec
[INTTYPE_TO_STRLEN(int64_t)];
176 /* See https://howardhinnant.github.io/date_algorithms.html for an
177 * explanation of the algorithm used here.
180 /* Convert Epoch in seconds to number of days. */
181 epoch_to_days
= time
->tv_sec
/ 86400;
183 /* Shift the Epoch from 1970-01-01 to 0000-03-01. */
184 z
= epoch_to_days
+ 719468;
186 /* compute the era from the serial date by simply dividing by the number
187 * of days in an era (146097).
189 era
= (z
>= 0 ? z
: z
- 146096) / 146097;
191 /* The day-of-era (doe) can then be found by subtracting the era number
192 * times the number of days per era, from the serial date.
194 doe
= (z
- era
* 146097);
196 /* From the day-of-era (doe), the year-of-era (yoe, range [0, 399]) can
199 yoe
= (doe
- doe
/ 1460 + doe
/ 36524 - doe
/ 146096) / 365;
201 /* Given year-of-era, and era, one can now compute the year. */
202 year
= yoe
+ era
* 400;
204 /* Also the day-of-year, again with the year beginning on Mar. 1, can be
205 * computed from the day-of-era and year-of-era.
207 doy
= doe
- (365 * yoe
+ yoe
/ 4 - yoe
/ 100);
209 /* Given day-of-year, find the month number. */
210 mp
= (5 * doy
+ 2) / 153;
212 /* From day-of-year and month-of-year we can now easily compute
215 day
= doy
- (153 * mp
+ 2) / 5 + 1;
217 /* Transform the month number from the [0, 11] / [Mar, Feb] system to
218 * the civil system: [1, 12] to find the correct month.
220 month
= mp
+ (mp
< 10 ? 3 : -9);
222 /* The algorithm assumes that a year begins on 1 March, so add 1 before
227 /* Transform days in the epoch to seconds. */
228 d_in_s
= epoch_to_days
* 86400;
230 /* To find the current hour simply substract the Epoch_to_days from the
231 * total Epoch and divide by the number of seconds in an hour.
233 hours
= (time
->tv_sec
- d_in_s
) / 3600;
235 /* Transform hours to seconds. */
236 h_in_s
= hours
* 3600;
238 /* Calculate minutes by substracting the seconds for all days in the
239 * epoch and for all hours in the epoch and divide by the number of
240 * minutes in an hour.
242 minutes
= (time
->tv_sec
- d_in_s
- h_in_s
) / 60;
244 /* Calculate the seconds by substracting the seconds for all days in the
245 * epoch, hours in the epoch and minutes in the epoch.
247 seconds
= (time
->tv_sec
- d_in_s
- h_in_s
- (minutes
* 60));
249 /* Make string from nanoseconds. */
250 ret
= snprintf(nanosec
, sizeof(nanosec
), "%"PRId64
, (int64_t)time
->tv_nsec
);
251 if (ret
< 0 || ret
>= sizeof(nanosec
))
254 /* Create final timestamp for the log and shorten nanoseconds to 3
257 ret
= snprintf(buf
, bufsize
,
258 "%" PRId64
"%02" PRId64
"%02" PRId64
"%02" PRId64
259 "%02" PRId64
"%02" PRId64
".%.3s",
260 year
, month
, day
, hours
, minutes
, seconds
, nanosec
);
261 if (ret
< 0 || (size_t)ret
>= bufsize
)
267 /* This function needs to make extra sure that it is thread-safe. We had some
268 * problems with that before. This especially involves time-conversion
269 * functions. I don't want to find any localtime() or gmtime() functions or
270 * relatives in here. Not even localtime_r() or gmtime_r() or relatives. They
271 * all fiddle with global variables and locking in various libcs. They cause
272 * deadlocks when liblxc is used multi-threaded and no matter how smart you
273 * think you are, you __will__ cause trouble using them.
274 * (As a short example how this can cause trouble: LXD uses forkstart to fork
275 * off a new process that runs the container. At the same time the go runtime
276 * LXD relies on does its own multi-threading thing which we can't controll. The
277 * fork()ing + threading then seems to mess with the locking states in these
278 * time functions causing deadlocks.)
279 * The current solution is to be good old unix people and use the Epoch as our
280 * reference point and simply use the seconds and nanoseconds that have past
281 * since then. This relies on clock_gettime() which is explicitly marked MT-Safe
282 * with no restrictions! This way, anyone who is really strongly invested in
283 * getting the actual time the log entry was created, can just convert it for
284 * themselves. Our logging is mostly done for debugging purposes so don't try
285 * to make it pretty. Pretty might cost you thread-safety.
287 static int log_append_logfile(const struct lxc_log_appender
*appender
,
288 struct lxc_log_event
*event
)
290 char buffer
[LXC_LOG_BUFFER_SIZE
];
291 char date_time
[LXC_LOG_TIME_SIZE
];
295 const char *log_container_name
= log_vmname
;
298 if (current_config
) {
299 if (!lxc_log_use_global_fd
)
300 fd_to_use
= current_config
->logfd
;
302 if (!log_container_name
)
303 log_container_name
= current_config
->name
;
308 fd_to_use
= lxc_log_fd
;
313 if (lxc_unix_epoch_to_utc(date_time
, LXC_LOG_TIME_SIZE
, &event
->timestamp
) < 0)
316 n
= snprintf(buffer
, sizeof(buffer
),
317 "%s%s%s %s %-8s %s - %s:%s:%d - ",
319 log_container_name
? " " : "",
320 log_container_name
? log_container_name
: "",
322 lxc_log_priority_to_string(event
->priority
),
324 event
->locinfo
->file
, event
->locinfo
->func
,
325 event
->locinfo
->line
);
329 if ((size_t)n
< (sizeof(buffer
) - 1)) {
330 ret
= vsnprintf(buffer
+ n
, sizeof(buffer
) - n
, event
->fmt
, *event
->vap
);
337 if ((size_t)n
>= sizeof(buffer
))
338 n
= sizeof(buffer
) - 1;
343 ret
= write(fd_to_use
, buffer
, n
+ 1);
344 if (ret
< 0 && errno
== EINTR
)
350 static struct lxc_log_appender log_appender_syslog
= {
352 .append
= log_append_syslog
,
356 static struct lxc_log_appender log_appender_stderr
= {
358 .append
= log_append_stderr
,
362 static struct lxc_log_appender log_appender_logfile
= {
364 .append
= log_append_logfile
,
368 static struct lxc_log_category log_root
= {
370 .priority
= LXC_LOG_LEVEL_ERROR
,
375 struct lxc_log_category lxc_log_category_lxc
= {
377 .priority
= LXC_LOG_LEVEL_ERROR
,
378 .appender
= &log_appender_logfile
,
382 /*---------------------------------------------------------------------------*/
383 static int build_dir(const char *name
)
387 /* Make copy of the string since we'll be modifying it. */
393 for (p
= n
+ 1; p
< e
; p
++) {
400 ret
= lxc_unpriv(mkdir(n
, 0755));
401 if (ret
&& errno
!= EEXIST
) {
402 SYSERROR("Failed to create directory %s", n
);
414 /*---------------------------------------------------------------------------*/
415 static int log_open(const char *name
)
420 fd
= lxc_unpriv(open(name
, O_CREAT
| O_WRONLY
| O_APPEND
| O_CLOEXEC
, 0666));
422 SYSERROR("Failed to open log file \"%s\"", name
);
429 newfd
= fcntl(fd
, F_DUPFD_CLOEXEC
, STDERR_FILENO
);
431 SYSERROR("Failed to dup log fd %d", fd
);
438 * Build the path to the log file
439 * @name : the name of the container
440 * @lxcpath : the lxcpath to use as a basename or NULL to use LOGPATH
441 * Returns malloced path on success, or NULL on failure
443 static char *build_log_path(const char *name
, const char *lxcpath
)
453 #if USE_CONFIGPATH_LOGS
460 * If USE_CONFIGPATH_LOGS is true or lxcpath is given, the resulting
462 * '$logpath' + '/' + '$name' + '/' + '$name' + '.log' + '\0'
464 * If USE_CONFIGPATH_LOGS is false the resulting path will be:
465 * '$logpath' + '/' + '$name' + '.log' + '\0'
467 len
= strlen(name
) + 6; /* 6 == '/' + '.log' + '\0' */
474 len
+= strlen(lxcpath
) + 1 + strlen(name
) + 1; /* add "/$container_name/" */
476 len
+= strlen(lxcpath
) + 1;
483 ret
= snprintf(p
, len
, "%s/%s/%s.log", lxcpath
, name
, name
);
485 ret
= snprintf(p
, len
, "%s/%s.log", lxcpath
, name
);
486 if (ret
< 0 || (size_t)ret
>= len
) {
495 * This can be called:
496 * 1. when a program calls lxc_log_init with no logfile parameter (in which
497 * case the default is used). In this case lxc.loge can override this.
498 * 2. when a program calls lxc_log_init with a logfile parameter. In this
499 * case we don't want lxc.log to override this.
500 * 3. When a lxc.log entry is found in config file.
502 static int __lxc_log_set_file(const char *fname
, int create_dirs
)
504 /* we are overriding the default. */
505 if (lxc_log_fd
!= -1)
511 if (strlen(fname
) == 0) {
516 #if USE_CONFIGPATH_LOGS
517 /* We don't build_dir for the default if the default is i.e.
518 * /var/lib/lxc/$container/$container.log.
522 if (build_dir(fname
)) {
523 SYSERROR("Failed to create dir for log file \"%s\"", fname
);
527 lxc_log_fd
= log_open(fname
);
528 if (lxc_log_fd
== -1)
531 log_fname
= strdup(fname
);
535 static int _lxc_log_set_file(const char *name
, const char *lxcpath
, int create_dirs
)
540 logfile
= build_log_path(name
, lxcpath
);
542 ERROR("Could not build log path");
546 ret
= __lxc_log_set_file(logfile
, create_dirs
);
553 * Called from lxc front-end programs (like lxc-create, lxc-start) to
554 * initalize the log defaults.
556 int lxc_log_init(struct lxc_log
*log
)
559 int lxc_priority
= LXC_LOG_LEVEL_ERROR
;
564 if (lxc_log_fd
!= -1) {
565 WARN("Log already initialized");
570 lxc_priority
= lxc_log_priority_to_int(log
->level
);
572 if (!lxc_loglevel_specified
) {
573 lxc_log_category_lxc
.priority
= lxc_priority
;
574 lxc_loglevel_specified
= 1;
577 if (!lxc_quiet_specified
)
579 lxc_log_category_lxc
.appender
->next
= &log_appender_stderr
;
582 lxc_log_set_prefix(log
->prefix
);
585 log_vmname
= strdup(log
->name
);
588 if (strcmp(log
->file
, "none") == 0)
591 ret
= __lxc_log_set_file(log
->file
, 1);
593 ERROR("Failed to enable logfile");
597 lxc_log_use_global_fd
= 1;
599 /* if no name was specified, there nothing to do */
606 log
->lxcpath
= LOGPATH
;
608 /* try LOGPATH if lxcpath is the default for the privileged containers */
609 if (!geteuid() && strcmp(LXCPATH
, log
->lxcpath
) == 0)
610 ret
= _lxc_log_set_file(log
->name
, NULL
, 0);
614 ret
= _lxc_log_set_file(log
->name
, log
->lxcpath
, 1);
616 /* try LOGPATH in case its writable by the caller */
618 ret
= _lxc_log_set_file(log
->name
, NULL
, 0);
622 * If !file, that is, if the user did not request this logpath, then
623 * ignore failures and continue logging to console
625 if (!log
->file
&& ret
!= 0) {
626 INFO("Ignoring failure to open default logfile");
630 if (lxc_log_fd
!= -1) {
631 lxc_log_category_lxc
.appender
= &log_appender_logfile
;
632 lxc_log_category_lxc
.appender
->next
= &log_appender_stderr
;
638 void lxc_log_close(void)
645 if (lxc_log_fd
== -1)
655 int lxc_log_syslog(int facility
)
657 struct lxc_log_appender
*appender
;
659 openlog(log_prefix
, LOG_PID
, facility
);
660 if (!lxc_log_category_lxc
.appender
) {
661 lxc_log_category_lxc
.appender
= &log_appender_syslog
;
665 appender
= lxc_log_category_lxc
.appender
;
666 /* Check if syslog was already added, to avoid creating a loop */
668 if (appender
== &log_appender_syslog
) {
669 /* not an error: openlog re-opened the connection */
672 appender
= appender
->next
;
675 appender
= lxc_log_category_lxc
.appender
;
676 while (appender
->next
!= NULL
)
677 appender
= appender
->next
;
678 appender
->next
= &log_appender_syslog
;
683 inline void lxc_log_enable_syslog(void)
689 * This is called when we read a lxc.log.level entry in a lxc.conf file. This
690 * happens after processing command line arguments, which override the .conf
691 * settings. So only set the level if previously unset.
693 int lxc_log_set_level(int *dest
, int level
)
695 if (level
< 0 || level
>= LXC_LOG_LEVEL_NOTSET
) {
696 ERROR("Invalid log priority %d", level
);
704 inline int lxc_log_get_level(void)
706 return lxc_log_category_lxc
.priority
;
709 bool lxc_log_has_valid_level(void)
713 log_level
= lxc_log_get_level();
714 if (log_level
< 0 || log_level
>= LXC_LOG_LEVEL_NOTSET
)
721 * This is called when we read a lxc.logfile entry in a lxc.conf file. This
722 * happens after processing command line arguments, which override the .conf
723 * settings. So only set the file if previously unset.
725 int lxc_log_set_file(int *fd
, const char *fname
)
732 if (build_dir(fname
))
735 *fd
= log_open(fname
);
742 inline const char *lxc_log_get_file(void)
747 inline void lxc_log_set_prefix(const char *prefix
)
749 /* We don't care if thte prefix is truncated. */
750 (void)strlcpy(log_prefix
, prefix
, sizeof(log_prefix
));
753 inline const char *lxc_log_get_prefix(void)
758 inline void lxc_log_options_no_override()
760 lxc_quiet_specified
= 1;
761 lxc_loglevel_specified
= 1;