2 * Copyright 2000, International Business Machines Corporation and others.
5 * This software has been released under the terms of the IBM Public
6 * License. For details, see the LICENSE file in the top-level source
7 * directory or online at http://www.openafs.org/dl/license10.html
10 /* serverLog.c - Server logging */
12 /* Information Technology Center */
15 /* Function - These routines implement logging from the servers. */
17 /* ********************************************************************** */
19 #include <afsconfig.h>
20 #include <afs/param.h>
23 #include <afs/procmgmt.h> /* signal(), kill(), wait(), etc. */
25 #include <roken.h> /* Must come after procmgmt.h */
26 #ifdef AFS_PTHREAD_ENV
27 #include <opr/softsig.h>
28 #include <afs/procmgmt_softsig.h> /* Must come after softsig.h */
35 #if defined(AFS_PTHREAD_ENV)
37 static pthread_once_t serverLogOnce = PTHREAD_ONCE_INIT;
38 static pthread_mutex_t serverLogMutex;
39 #define LOCK_SERVERLOG() opr_Verify(pthread_mutex_lock(&serverLogMutex) == 0)
40 #define UNLOCK_SERVERLOG() opr_Verify(pthread_mutex_unlock(&serverLogMutex) == 0)
45 #define NULLDEV "/dev/null"
48 #else /* AFS_PTHREAD_ENV */
49 #define LOCK_SERVERLOG()
50 #define UNLOCK_SERVERLOG()
51 #endif /* AFS_PTHREAD_ENV */
59 * Placeholder function to return dummy thread number.
66 static int (*threadNumProgram) (void) = dummyThreadNum;
68 /* After single-threaded startup, accesses to serverlogFD and
69 * serverLogSyslog* are protected by LOCK_SERVERLOG(). */
70 static int serverLogFD = -1; /*!< The log file descriptor. */
71 static struct logOptions serverLogOpts; /*!< logging options */
73 int LogLevel; /*!< The current logging level. */
74 static int threadIdLogs = 0; /*!< Include the thread id in log messages when true. */
75 static int resetSignals = 0; /*!< Reset signal handlers for the next signal when true. */
76 static char *ourName = NULL; /*!< The fully qualified log file path, saved for reopens. */
78 static int OpenLogFile(const char *fileName);
79 static void RotateLogFile(void);
82 * Determine if the file is a named pipe.
84 * This check is performed to support named pipes as logs by not rotating them
85 * and opening them with a non-blocking flags.
87 * \param[in] fileName log file name
89 * \returns non-zero if log file is a named pipe.
92 IsFIFO(const char *fileName)
95 return (lstat(fileName, &statbuf) == 0) && (S_ISFIFO(statbuf.st_mode));
99 * Return the current logging level.
108 * Return the log destination.
113 return serverLogOpts.lopt_dest;
117 * Get the log filename for file based logging.
119 * An empty string is returned if the log destination is not
120 * file based. The caller must make a copy of the string
121 * if it is accessed after the CloseLog.
126 return serverLogOpts.lopt_dest == logDest_file ? (const char*)ourName : "";
130 * Set the function to log thread numbers.
133 SetLogThreadNumProgram(int (*func) (void) )
135 threadNumProgram = func;
139 * Write a block of bytes to the log.
141 * Write a block of bytes directly to the log without formatting
142 * or prepending a timestamp.
144 * \param[in] buf pointer to bytes to write
145 * \param[in] len number of bytes to write
148 WriteLogBuffer(char *buf, afs_uint32 len)
151 if (serverLogFD >= 0) {
152 if (write(serverLogFD, buf, len) < 0) {
160 * Get the current thread number.
165 return (*threadNumProgram) ();
169 * Write a message to the log.
171 * \param[in] format printf-style format string
172 * \param[in] args variable list of arguments
175 vFSLog(const char *format, va_list args)
184 currenttime = time(NULL);
185 len = strftime(tbuffer, sizeof(tbuffer), "%a %b %d %H:%M:%S %Y ",
186 localtime_r(¤ttime, &tm));
187 info = &tbuffer[len];
190 num = (*threadNumProgram) ();
192 snprintf(info, (sizeof tbuffer) - strlen(tbuffer), "[%d] ",
194 info += strlen(info);
198 vsnprintf(info, (sizeof tbuffer) - strlen(tbuffer), format, args);
200 len = strlen(tbuffer);
203 if (serverLogOpts.dest == logDest_syslog) {
204 syslog(LOG_INFO, "%s", info);
207 if (serverLogFD >= 0) {
208 if (write(serverLogFD, tbuffer, len) < 0) {
214 #if !defined(AFS_PTHREAD_ENV) && !defined(AFS_NT40_ENV)
215 if (serverLogOpts.dest == logDest_file) {
217 fflush(stderr); /* in case they're sharing the same FD */
223 * Write a message to the log.
225 * \param[in] format printf-style format specification
226 * \param[in] ... arguments for format specification
229 FSLog(const char *format, ...)
233 va_start(args, format);
234 vFSLog(format, args);
239 * Write the command-line invocation to the log.
241 * \param[in] argc argument count from main()
242 * \param[in] argv argument vector from main()
243 * \param[in] progname program name
244 * \param[in] version program version
245 * \param[in] logstring log message string
246 * \param[in] log printf-style log function
249 LogCommandLine(int argc, char **argv, const char *progname,
250 const char *version, const char *logstring,
251 void (*log) (const char *format, ...))
254 char *commandLine, *cx;
256 opr_Assert(argc > 0);
258 for (l = i = 0; i < argc; i++)
259 l += strlen(argv[i]) + 1;
260 if ((commandLine = malloc(l))) {
261 for (cx = commandLine, i = 0; i < argc; i++) {
266 commandLine[l-1] = '\0';
267 (*log)("%s %s %s%s(%s)\n", logstring, progname,
268 version, strlen(version)>0?" ":"", commandLine);
271 /* What, we're out of memory already!? */
272 (*log)("%s %s%s%s\n", logstring,
273 progname, strlen(version)>0?" ":"", version);
278 * Write the single-DES deprecation warning to the log.
283 /* The blank newlines help this stand out a bit more in the log. */
285 ViceLog(0, ("WARNING: You are using single-DES keys in a KeyFile. Using single-DES\n"));
286 ViceLog(0, ("WARNING: long-term keys is considered insecure, and it is strongly\n"));
287 ViceLog(0, ("WARNING: recommended that you migrate to stronger encryption. See\n"));
288 ViceLog(0, ("WARNING: OPENAFS-SA-2013-003 on http://www.openafs.org/security/\n"));
289 ViceLog(0, ("WARNING: for details.\n"));
294 * Move the current log file out of the way so a new one can be started.
296 * The format of the new name depends on the logging style. The traditional
297 * Transarc style appends ".old" to the log file name. When MR-AFS style
298 * logging is in effect, a time stamp is appended to the log file name instead
301 * \bug Unfortunately, no check is made to avoid overwriting
302 * old logs in the traditional Transarc mode.
304 * \param fileName fully qualified log file path
307 RenameLogFile(const char *fileName)
310 char *nextName = NULL;
314 struct tm *timeFields;
316 switch (serverLogOpts.lopt_rotateStyle) {
320 code = asprintf(&nextName, "%s.old", fileName);
325 case logRotate_timestamp:
327 for (tries = 0; nextName == NULL && tries < 100; t++, tries++) {
328 timeFields = localtime(&t);
329 code = asprintf(&nextName, "%s.%d%02d%02d%02d%02d%02d",
330 fileName, timeFields->tm_year + 1900,
331 timeFields->tm_mon + 1, timeFields->tm_mday,
332 timeFields->tm_hour, timeFields->tm_min,
338 if (lstat(nextName, &buf) == 0) {
339 /* Avoid clobbering a log. */
348 if (nextName != NULL) {
349 rk_rename(fileName, nextName); /* Don't check the error code. */
355 * Write message to the log to indicate the log level.
357 * This helper function is called by the signal handlers when the log level is
358 * changed, to write a message to the log to indicate the log level has been
364 int loglevel = (intptr_t)param;
366 ViceLog(0, ("Reset Debug levels to 0\n"));
368 ViceLog(0, ("Set Debug On level = %d\n", loglevel));
374 * Signal handler to increase the logging level.
376 * Increase the current logging level to 1 if it in currently 0,
377 * otherwise, increase the current logging level by a factor of 5 if it
378 * is currently non-zero.
380 * Enables thread id logging when the log level is greater than 1.
383 SetDebug_Signal(int signo)
388 #if defined(AFS_PTHREAD_ENV)
389 if (LogLevel > 1 && threadNumProgram != NULL &&
397 #if defined(AFS_PTHREAD_ENV)
398 if (threadIdLogs == 1)
402 #if defined(AFS_PTHREAD_ENV)
403 DebugOn((void *)(intptr_t)LogLevel);
404 #else /* AFS_PTHREAD_ENV */
405 IOMGR_SoftSig(DebugOn, (void *)(intptr_t)LogLevel);
406 #endif /* AFS_PTHREAD_ENV */
409 /* When pthreaded softsig handlers are not in use, some platforms
410 * require this signal handler to be set again. */
411 (void)signal(signo, SetDebug_Signal);
413 } /*SetDebug_Signal */
416 * Signal handler to reset the logging level.
418 * Reset the logging level and disable thread id logging.
420 * \note This handler has the side-effect of rotating and reopening
424 ResetDebug_Signal(int signo)
428 #if defined(AFS_PTHREAD_ENV)
429 DebugOn((void *)(intptr_t)LogLevel);
430 #else /* AFS_PTHREAD_ENV */
431 IOMGR_SoftSig(DebugOn, (void *)(intptr_t)LogLevel);
432 #endif /* AFS_PTHREAD_ENV */
435 /* When pthreaded softsig handlers are not in use, some platforms
436 * require this signal handler to be set again. */
437 (void)signal(signo, ResetDebug_Signal);
439 #if defined(AFS_PTHREAD_ENV)
440 if (threadIdLogs == 1)
443 if (serverLogOpts.lopt_rotateOnReset) {
446 } /*ResetDebug_Signal */
449 * Handle requests to reopen the log.
451 * This signal handler will reopen the log file. A new, empty log file
452 * will be created if the log file does not already exist.
454 * External log rotation programs may rotate a server log file by
455 * renaming the existing server log file and then immediately sending a
456 * signal to the corresponding server process. Server log messages will
457 * continue to be appended to the renamed server log file until the
458 * server log is reopened. After this signal handler completes, server
459 * log messages will be written to the new log file. This allows
460 * external log rotation programs to rotate log files without
461 * messages being dropped.
464 ReOpenLog_Signal(int signo)
468 (void)signal(signo, ReOpenLog_Signal);
472 #ifdef AFS_PTHREAD_ENV
474 * Register pthread-safe signal handlers for server log management.
476 * \note opr_softsig_Init() must be called before this function.
479 SetupLogSoftSignals(void)
481 opr_softsig_Register(SIGHUP, ResetDebug_Signal);
482 opr_softsig_Register(SIGTSTP, SetDebug_Signal);
483 opr_softsig_Register(SIGUSR1, ReOpenLog_Signal);
485 (void)signal(SIGPIPE, SIG_IGN);
488 #endif /* AFS_PTHREAD_ENV */
491 * Register signal handlers for server log management.
493 * \note This function is deprecated and should not be used
494 * in new code. This function should be removed when
495 * all the servers have been converted to pthreads
496 * and lwp has been removed.
499 SetupLogSignals(void)
502 (void)signal(SIGHUP, ResetDebug_Signal);
503 (void)signal(SIGTSTP, SetDebug_Signal);
504 (void)signal(SIGUSR1, ReOpenLog_Signal);
506 (void)signal(SIGPIPE, SIG_IGN);
510 #if defined(AFS_PTHREAD_ENV)
512 InitServerLogMutex(void)
514 opr_Verify(pthread_mutex_init(&serverLogMutex, NULL) == 0);
516 #endif /* AFS_PTHREAD_ENV */
519 * Redirect stdout and stderr to the log file.
521 * \note Call directly after opening the log file.
523 * \param[in] fileName log file name
526 RedirectStdStreams(const char *fileName)
528 if (freopen(fileName, "a", stdout) == NULL) {
531 if (freopen(fileName, "a", stderr) != NULL) {
533 setvbuf(stderr, NULL, _IONBF, 0);
535 setbuf(stderr, NULL);
543 * Open the log file using the options given in OpenLog().
545 * \returns 0 on success
548 OpenLogFile(const char *fileName)
551 * This function should allow various libraries that inconsistently
552 * use stdout/stderr to all go to the same place
555 int flags = O_WRONLY | O_CREAT | O_APPEND;
557 opr_Assert(serverLogOpts.dest == logDest_file);
559 opr_Assert(fileName != NULL);
561 if (IsFIFO(fileName)) {
562 /* Support named pipes as logs by not rotating them. */
564 } else if (serverLogOpts.lopt_rotateOnOpen) {
565 /* Old style logging always started a new log file. */
567 RenameLogFile(fileName);
570 tempfd = open(fileName, flags, 0666);
572 printf("Unable to open log file %s\n", fileName);
575 RedirectStdStreams(fileName);
577 /* Save our name for reopening. */
578 if (ourName != fileName) {
579 /* Make a copy if needed */
581 ourName = strdup(fileName);
582 opr_Assert(ourName != NULL);
585 serverLogFD = tempfd;
591 * Open the log file descriptor or a connection to the system log.
593 * This function should be called once during program initialization and
594 * must be called before calling FSLog() or WriteLogBuffer(). The
595 * fields of the given argument specify the logging destination and
596 * various optional features.
598 * The lopt_logLevel value specifies the initial logging level.
600 * The lopt_dest enum specifies the logging destination; either
601 * file based (logDest_file) or the system log (logDest_syslog).
606 * A file will be opened for log messages when the lopt_dest enum is set
607 * to logDest_file. The file specified by lopt_filename will be opened
608 * for appending log messages. A new file will be created if the log
609 * file does not exist.
611 * The lopt_rotateOnOpen flag specifies whether an existing log file is
612 * to be renamed and a new log file created during the call to OpenLog.
613 * The lopt_rotateOnOpen flag has no effect if the file given by
614 * lopt_filename is a named pipe (fifo).
616 * The lopt_rotateOnReset flag specifies whether the log file is renamed
617 * and then reopened when the reset signal (SIGHUP) is caught.
619 * The lopt_rotateStyle enum specifies how the new log file is renamed when
620 * lopt_rotateOnOpen or lopt_rotateOnReset are set. The lopt_rotateStyle
621 * may be the traditional Transarc style (logRotate_old) or the MR-AFS
622 * style (logRotate_timestamp).
624 * When lopt_rotateStyle is set to logRotate_old, the suffix ".old" is
625 * appended to the log file name. The existing ".old" log file is
628 * When lopt_rotateStyle is set to logRotate_timestamp, a timestamp
629 * string is appended to the log file name and existing files are not
632 * \note Messages written to stdout and stderr are redirected to the log
633 * file when file-based logging is in effect.
638 * A connection to the system log (syslog) will be established for log
639 * messages when the lopt_dest enum is set to logDest_syslog.
641 * The lopt_facility specifies the system log facility to be used when
642 * writing messages to the system log.
644 * The lopt_tag string specifies the indentification string to be used
645 * when writing messages to the system log.
647 * \param opts logging options. A copy of the logging
648 * options will be made before returning to
651 * \returns 0 on success
654 OpenLog(struct logOptions *opts)
658 #if defined(AFS_PTHREAD_ENV)
659 opr_Verify(pthread_once(&serverLogOnce, InitServerLogMutex) == 0);
660 #endif /* AFS_PTHREAD_ENV */
662 LogLevel = serverLogOpts.logLevel = opts->logLevel;
663 serverLogOpts.dest = opts->dest;
664 switch (serverLogOpts.dest) {
666 serverLogOpts.lopt_rotateOnOpen = opts->lopt_rotateOnOpen;
667 serverLogOpts.lopt_rotateOnReset = opts->lopt_rotateOnReset;
668 serverLogOpts.lopt_rotateStyle = opts->lopt_rotateStyle;
669 /* OpenLogFile() sets ourName; don't cache filename here. */
670 code = OpenLogFile(opts->lopt_filename);
674 serverLogOpts.lopt_rotateOnOpen = 0;
675 serverLogOpts.lopt_rotateOnReset = 0;
676 serverLogOpts.lopt_rotateStyle = logRotate_none;
677 openlog(opts->lopt_tag, LOG_PID, opts->lopt_facility);
688 * Reopen the log file descriptor.
690 * Reopen the log file descriptor in order to support rotation
691 * of the log files. Has no effect when logging to the syslog.
693 * \returns 0 on success
698 int flags = O_WRONLY | O_APPEND | O_CREAT;
701 if (serverLogOpts.dest == logDest_syslog) {
707 if (ourName == NULL) {
711 if (IsFIFO(ourName)) {
714 if (serverLogFD >= 0)
716 serverLogFD = open(ourName, flags, 0666);
717 if (serverLogFD >= 0) {
718 RedirectStdStreams(ourName);
721 return serverLogFD < 0 ? -1 : 0;
725 * Rotate the log file by renaming then truncating.
731 if (ourName != NULL) {
732 if (serverLogFD >= 0) {
736 OpenLogFile(ourName);
742 * Close the server log file.
744 * \note Must be preceeded by OpenLog().
752 if (serverLogOpts.dest == logDest_syslog) {
757 if (serverLogFD >= 0) {