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>
34 #if defined(AFS_PTHREAD_ENV)
36 static pthread_once_t serverLogOnce = PTHREAD_ONCE_INIT;
37 static pthread_mutex_t serverLogMutex;
38 #define LOCK_SERVERLOG() opr_Verify(pthread_mutex_lock(&serverLogMutex) == 0)
39 #define UNLOCK_SERVERLOG() opr_Verify(pthread_mutex_unlock(&serverLogMutex) == 0)
44 #define NULLDEV "/dev/null"
47 #else /* AFS_PTHREAD_ENV */
48 #define LOCK_SERVERLOG()
49 #define UNLOCK_SERVERLOG()
50 #endif /* AFS_PTHREAD_ENV */
58 * Placeholder function to return dummy thread number.
65 static int (*threadNumProgram) (void) = dummyThreadNum;
67 /* After single-threaded startup, accesses to serverlogFD and
68 * serverLogSyslog* are protected by LOCK_SERVERLOG(). */
69 static int serverLogFD = -1; /*!< The log file descriptor. */
70 static struct logOptions serverLogOpts; /*!< logging options */
72 int LogLevel; /*!< The current logging level. */
73 static int threadIdLogs = 0; /*!< Include the thread id in log messages when true. */
74 static int resetSignals = 0; /*!< Reset signal handlers for the next signal when true. */
75 static char *ourName = NULL; /*!< The fully qualified log file path, saved for reopens. */
77 static int OpenLogFile(const char *fileName);
78 static void RotateLogFile(void);
81 * Determine if the file is a named pipe.
83 * This check is performed to support named pipes as logs by not rotating them
84 * and opening them with a non-blocking flags.
86 * \param[in] fileName log file name
88 * \returns non-zero if log file is a named pipe.
91 IsFIFO(const char *fileName)
94 return (lstat(fileName, &statbuf) == 0) && (S_ISFIFO(statbuf.st_mode));
98 * Return the current logging level.
107 * Return the log destination.
112 return serverLogOpts.lopt_dest;
116 * Get the log filename for file based logging.
118 * An empty string is returned if the log destination is not
119 * file based. The caller must make a copy of the string
120 * if it is accessed after the CloseLog.
125 return serverLogOpts.lopt_dest == logDest_file ? (const char*)ourName : "";
129 * Set the function to log thread numbers.
132 SetLogThreadNumProgram(int (*func) (void) )
134 threadNumProgram = func;
138 * Write a block of bytes to the log.
140 * Write a block of bytes directly to the log without formatting
141 * or prepending a timestamp.
143 * \param[in] buf pointer to bytes to write
144 * \param[in] len number of bytes to write
147 WriteLogBuffer(char *buf, afs_uint32 len)
150 if (serverLogFD >= 0) {
151 if (write(serverLogFD, buf, len) < 0) {
159 * Get the current thread number.
164 return (*threadNumProgram) ();
168 * Write a message to the log.
170 * \param[in] format printf-style format string
171 * \param[in] args variable list of arguments
174 vFSLog(const char *format, va_list args)
183 currenttime = time(NULL);
184 len = strftime(tbuffer, sizeof(tbuffer), "%a %b %d %H:%M:%S %Y ",
185 localtime_r(¤ttime, &tm));
186 info = &tbuffer[len];
189 num = (*threadNumProgram) ();
191 snprintf(info, (sizeof tbuffer) - strlen(tbuffer), "[%d] ",
193 info += strlen(info);
197 vsnprintf(info, (sizeof tbuffer) - strlen(tbuffer), format, args);
199 len = strlen(tbuffer);
202 if (serverLogOpts.dest == logDest_syslog) {
203 syslog(LOG_INFO, "%s", info);
206 if (serverLogFD >= 0) {
207 if (write(serverLogFD, tbuffer, len) < 0) {
213 #if !defined(AFS_PTHREAD_ENV) && !defined(AFS_NT40_ENV)
214 if (serverLogOpts.dest == logDest_file) {
216 fflush(stderr); /* in case they're sharing the same FD */
222 * Write a message to the log.
224 * \param[in] format printf-style format specification
225 * \param[in] ... arguments for format specification
228 FSLog(const char *format, ...)
232 va_start(args, format);
233 vFSLog(format, args);
238 * Write the command-line invocation to the log.
240 * \param[in] argc argument count from main()
241 * \param[in] argv argument vector from main()
242 * \param[in] progname program name
243 * \param[in] version program version
244 * \param[in] logstring log message string
245 * \param[in] log printf-style log function
248 LogCommandLine(int argc, char **argv, const char *progname,
249 const char *version, const char *logstring,
250 void (*log) (const char *format, ...))
253 char *commandLine, *cx;
255 opr_Assert(argc > 0);
257 for (l = i = 0; i < argc; i++)
258 l += strlen(argv[i]) + 1;
259 if ((commandLine = malloc(l))) {
260 for (cx = commandLine, i = 0; i < argc; i++) {
265 commandLine[l-1] = '\0';
266 (*log)("%s %s %s%s(%s)\n", logstring, progname,
267 version, strlen(version)>0?" ":"", commandLine);
270 /* What, we're out of memory already!? */
271 (*log)("%s %s%s%s\n", logstring,
272 progname, strlen(version)>0?" ":"", version);
277 * Move the current log file out of the way so a new one can be started.
279 * The format of the new name depends on the logging style. The traditional
280 * Transarc style appends ".old" to the log file name. When MR-AFS style
281 * logging is in effect, a time stamp is appended to the log file name instead
284 * \bug Unfortunately, no check is made to avoid overwriting
285 * old logs in the traditional Transarc mode.
287 * \param fileName fully qualified log file path
290 RenameLogFile(const char *fileName)
293 char *nextName = NULL;
297 struct tm *timeFields;
299 switch (serverLogOpts.lopt_rotateStyle) {
303 code = asprintf(&nextName, "%s.old", fileName);
308 case logRotate_timestamp:
310 for (tries = 0; nextName == NULL && tries < 100; t++, tries++) {
311 timeFields = localtime(&t);
312 code = asprintf(&nextName, "%s.%d%02d%02d%02d%02d%02d",
313 fileName, timeFields->tm_year + 1900,
314 timeFields->tm_mon + 1, timeFields->tm_mday,
315 timeFields->tm_hour, timeFields->tm_min,
321 if (lstat(nextName, &buf) == 0) {
322 /* Avoid clobbering a log. */
331 if (nextName != NULL) {
332 rk_rename(fileName, nextName); /* Don't check the error code. */
338 * Write message to the log to indicate the log level.
340 * This helper function is called by the signal handlers when the log level is
341 * changed, to write a message to the log to indicate the log level has been
347 int loglevel = (intptr_t)param;
349 ViceLog(0, ("Reset Debug levels to 0\n"));
351 ViceLog(0, ("Set Debug On level = %d\n", loglevel));
357 * Signal handler to increase the logging level.
359 * Increase the current logging level to 1 if it in currently 0,
360 * otherwise, increase the current logging level by a factor of 5 if it
361 * is currently non-zero.
363 * Enables thread id logging when the log level is greater than 1.
366 SetDebug_Signal(int signo)
371 #if defined(AFS_PTHREAD_ENV)
372 if (LogLevel > 1 && threadNumProgram != NULL &&
380 #if defined(AFS_PTHREAD_ENV)
381 if (threadIdLogs == 1)
385 #if defined(AFS_PTHREAD_ENV)
386 DebugOn((void *)(intptr_t)LogLevel);
387 #else /* AFS_PTHREAD_ENV */
388 IOMGR_SoftSig(DebugOn, (void *)(intptr_t)LogLevel);
389 #endif /* AFS_PTHREAD_ENV */
392 /* When pthreaded softsig handlers are not in use, some platforms
393 * require this signal handler to be set again. */
394 (void)signal(signo, SetDebug_Signal);
396 } /*SetDebug_Signal */
399 * Signal handler to reset the logging level.
401 * Reset the logging level and disable thread id logging.
403 * \note This handler has the side-effect of rotating and reopening
407 ResetDebug_Signal(int signo)
411 #if defined(AFS_PTHREAD_ENV)
412 DebugOn((void *)(intptr_t)LogLevel);
413 #else /* AFS_PTHREAD_ENV */
414 IOMGR_SoftSig(DebugOn, (void *)(intptr_t)LogLevel);
415 #endif /* AFS_PTHREAD_ENV */
418 /* When pthreaded softsig handlers are not in use, some platforms
419 * require this signal handler to be set again. */
420 (void)signal(signo, ResetDebug_Signal);
422 #if defined(AFS_PTHREAD_ENV)
423 if (threadIdLogs == 1)
426 if (serverLogOpts.lopt_rotateOnReset) {
429 } /*ResetDebug_Signal */
432 * Handle requests to reopen the log.
434 * This signal handler will reopen the log file. A new, empty log file
435 * will be created if the log file does not already exist.
437 * External log rotation programs may rotate a server log file by
438 * renaming the existing server log file and then immediately sending a
439 * signal to the corresponding server process. Server log messages will
440 * continue to be appended to the renamed server log file until the
441 * server log is reopened. After this signal handler completes, server
442 * log messages will be written to the new log file. This allows
443 * external log rotation programs to rotate log files without
444 * messages being dropped.
447 ReOpenLog_Signal(int signo)
451 (void)signal(signo, ReOpenLog_Signal);
455 #ifdef AFS_PTHREAD_ENV
457 * Register pthread-safe signal handlers for server log management.
459 * \note opr_softsig_Init() must be called before this function.
462 SetupLogSoftSignals(void)
464 opr_softsig_Register(SIGHUP, ResetDebug_Signal);
465 opr_softsig_Register(SIGTSTP, SetDebug_Signal);
466 opr_softsig_Register(SIGUSR1, ReOpenLog_Signal);
468 (void)signal(SIGPIPE, SIG_IGN);
471 #endif /* AFS_PTHREAD_ENV */
474 * Register signal handlers for server log management.
476 * \note This function is deprecated and should not be used
477 * in new code. This function should be removed when
478 * all the servers have been converted to pthreads
479 * and lwp has been removed.
482 SetupLogSignals(void)
485 (void)signal(SIGHUP, ResetDebug_Signal);
486 (void)signal(SIGTSTP, SetDebug_Signal);
487 (void)signal(SIGUSR1, ReOpenLog_Signal);
489 (void)signal(SIGPIPE, SIG_IGN);
493 #if defined(AFS_PTHREAD_ENV)
501 UnlockServerLog(void)
507 InitServerLogMutex(void)
509 opr_Verify(pthread_mutex_init(&serverLogMutex, NULL) == 0);
510 # ifndef AFS_NT40_ENV
511 opr_Verify(pthread_atfork(LockServerLog, UnlockServerLog, UnlockServerLog) == 0);
514 #endif /* AFS_PTHREAD_ENV */
517 * Redirect stdout and stderr to the log file.
519 * \note Call directly after opening the log file.
521 * \param[in] fileName log file name
524 RedirectStdStreams(const char *fileName)
526 if (freopen(fileName, "a", stdout) == NULL) {
529 if (freopen(fileName, "a", stderr) != NULL) {
531 setvbuf(stderr, NULL, _IONBF, 0);
533 setbuf(stderr, NULL);
541 * Open the log file using the options given in OpenLog().
543 * \returns 0 on success
546 OpenLogFile(const char *fileName)
549 * This function should allow various libraries that inconsistently
550 * use stdout/stderr to all go to the same place
553 int flags = O_WRONLY | O_CREAT | O_APPEND;
555 opr_Assert(serverLogOpts.dest == logDest_file);
557 opr_Assert(fileName != NULL);
559 if (IsFIFO(fileName)) {
560 /* Support named pipes as logs by not rotating them. */
562 } else if (serverLogOpts.lopt_rotateOnOpen) {
563 /* Old style logging always started a new log file. */
565 RenameLogFile(fileName);
568 tempfd = open(fileName, flags, 0666);
570 printf("Unable to open log file %s\n", fileName);
573 RedirectStdStreams(fileName);
575 /* Save our name for reopening. */
576 if (ourName != fileName) {
577 /* Make a copy if needed */
579 ourName = strdup(fileName);
580 opr_Assert(ourName != NULL);
583 serverLogFD = tempfd;
589 * Open the log file descriptor or a connection to the system log.
591 * This function should be called once during program initialization and
592 * must be called before calling FSLog() or WriteLogBuffer(). The
593 * fields of the given argument specify the logging destination and
594 * various optional features.
596 * The lopt_logLevel value specifies the initial logging level.
598 * The lopt_dest enum specifies the logging destination; either
599 * file based (logDest_file) or the system log (logDest_syslog).
604 * A file will be opened for log messages when the lopt_dest enum is set
605 * to logDest_file. The file specified by lopt_filename will be opened
606 * for appending log messages. A new file will be created if the log
607 * file does not exist.
609 * The lopt_rotateOnOpen flag specifies whether an existing log file is
610 * to be renamed and a new log file created during the call to OpenLog.
611 * The lopt_rotateOnOpen flag has no effect if the file given by
612 * lopt_filename is a named pipe (fifo).
614 * The lopt_rotateOnReset flag specifies whether the log file is renamed
615 * and then reopened when the reset signal (SIGHUP) is caught.
617 * The lopt_rotateStyle enum specifies how the new log file is renamed when
618 * lopt_rotateOnOpen or lopt_rotateOnReset are set. The lopt_rotateStyle
619 * may be the traditional Transarc style (logRotate_old) or the MR-AFS
620 * style (logRotate_timestamp).
622 * When lopt_rotateStyle is set to logRotate_old, the suffix ".old" is
623 * appended to the log file name. The existing ".old" log file is
626 * When lopt_rotateStyle is set to logRotate_timestamp, a timestamp
627 * string is appended to the log file name and existing files are not
630 * \note Messages written to stdout and stderr are redirected to the log
631 * file when file-based logging is in effect.
636 * A connection to the system log (syslog) will be established for log
637 * messages when the lopt_dest enum is set to logDest_syslog.
639 * The lopt_facility specifies the system log facility to be used when
640 * writing messages to the system log.
642 * The lopt_tag string specifies the indentification string to be used
643 * when writing messages to the system log.
645 * \param opts logging options. A copy of the logging
646 * options will be made before returning to
649 * \returns 0 on success
652 OpenLog(struct logOptions *opts)
656 #if defined(AFS_PTHREAD_ENV)
657 opr_Verify(pthread_once(&serverLogOnce, InitServerLogMutex) == 0);
658 #endif /* AFS_PTHREAD_ENV */
660 LogLevel = serverLogOpts.logLevel = opts->logLevel;
661 serverLogOpts.dest = opts->dest;
662 switch (serverLogOpts.dest) {
664 serverLogOpts.lopt_rotateOnOpen = opts->lopt_rotateOnOpen;
665 serverLogOpts.lopt_rotateOnReset = opts->lopt_rotateOnReset;
666 serverLogOpts.lopt_rotateStyle = opts->lopt_rotateStyle;
667 /* OpenLogFile() sets ourName; don't cache filename here. */
668 code = OpenLogFile(opts->lopt_filename);
672 serverLogOpts.lopt_rotateOnOpen = 0;
673 serverLogOpts.lopt_rotateOnReset = 0;
674 serverLogOpts.lopt_rotateStyle = logRotate_none;
675 openlog(opts->lopt_tag, LOG_PID, opts->lopt_facility);
686 * Reopen the log file descriptor.
688 * Reopen the log file descriptor in order to support rotation
689 * of the log files. Has no effect when logging to the syslog.
691 * \returns 0 on success
696 int flags = O_WRONLY | O_APPEND | O_CREAT;
699 if (serverLogOpts.dest == logDest_syslog) {
705 if (ourName == NULL) {
709 if (IsFIFO(ourName)) {
712 if (serverLogFD >= 0)
714 serverLogFD = open(ourName, flags, 0666);
715 if (serverLogFD >= 0) {
716 RedirectStdStreams(ourName);
719 return serverLogFD < 0 ? -1 : 0;
723 * Rotate the log file by renaming then truncating.
729 if (ourName != NULL) {
730 if (serverLogFD >= 0) {
734 OpenLogFile(ourName);
740 * Close the server log file.
742 * \note Must be preceeded by OpenLog().
750 if (serverLogOpts.dest == logDest_syslog) {
755 if (serverLogFD >= 0) {