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 * Write the single-DES deprecation warning to the log.
282 /* The blank newlines help this stand out a bit more in the log. */
284 ViceLog(0, ("WARNING: You are using single-DES keys in a KeyFile. Using single-DES\n"));
285 ViceLog(0, ("WARNING: long-term keys is considered insecure, and it is strongly\n"));
286 ViceLog(0, ("WARNING: recommended that you migrate to stronger encryption. See\n"));
287 ViceLog(0, ("WARNING: OPENAFS-SA-2013-003 on http://www.openafs.org/security/\n"));
288 ViceLog(0, ("WARNING: for details.\n"));
293 * Move the current log file out of the way so a new one can be started.
295 * The format of the new name depends on the logging style. The traditional
296 * Transarc style appends ".old" to the log file name. When MR-AFS style
297 * logging is in effect, a time stamp is appended to the log file name instead
300 * \bug Unfortunately, no check is made to avoid overwriting
301 * old logs in the traditional Transarc mode.
303 * \param fileName fully qualified log file path
306 RenameLogFile(const char *fileName)
309 char *nextName = NULL;
313 struct tm *timeFields;
315 switch (serverLogOpts.lopt_rotateStyle) {
319 code = asprintf(&nextName, "%s.old", fileName);
324 case logRotate_timestamp:
326 for (tries = 0; nextName == NULL && tries < 100; t++, tries++) {
327 timeFields = localtime(&t);
328 code = asprintf(&nextName, "%s.%d%02d%02d%02d%02d%02d",
329 fileName, timeFields->tm_year + 1900,
330 timeFields->tm_mon + 1, timeFields->tm_mday,
331 timeFields->tm_hour, timeFields->tm_min,
337 if (lstat(nextName, &buf) == 0) {
338 /* Avoid clobbering a log. */
347 if (nextName != NULL) {
348 rk_rename(fileName, nextName); /* Don't check the error code. */
354 * Write message to the log to indicate the log level.
356 * This helper function is called by the signal handlers when the log level is
357 * changed, to write a message to the log to indicate the log level has been
363 int loglevel = (intptr_t)param;
365 ViceLog(0, ("Reset Debug levels to 0\n"));
367 ViceLog(0, ("Set Debug On level = %d\n", loglevel));
373 * Signal handler to increase the logging level.
375 * Increase the current logging level to 1 if it in currently 0,
376 * otherwise, increase the current logging level by a factor of 5 if it
377 * is currently non-zero.
379 * Enables thread id logging when the log level is greater than 1.
382 SetDebug_Signal(int signo)
387 #if defined(AFS_PTHREAD_ENV)
388 if (LogLevel > 1 && threadNumProgram != NULL &&
396 #if defined(AFS_PTHREAD_ENV)
397 if (threadIdLogs == 1)
401 #if defined(AFS_PTHREAD_ENV)
402 DebugOn((void *)(intptr_t)LogLevel);
403 #else /* AFS_PTHREAD_ENV */
404 IOMGR_SoftSig(DebugOn, (void *)(intptr_t)LogLevel);
405 #endif /* AFS_PTHREAD_ENV */
408 /* When pthreaded softsig handlers are not in use, some platforms
409 * require this signal handler to be set again. */
410 (void)signal(signo, SetDebug_Signal);
412 } /*SetDebug_Signal */
415 * Signal handler to reset the logging level.
417 * Reset the logging level and disable thread id logging.
419 * \note This handler has the side-effect of rotating and reopening
423 ResetDebug_Signal(int signo)
427 #if defined(AFS_PTHREAD_ENV)
428 DebugOn((void *)(intptr_t)LogLevel);
429 #else /* AFS_PTHREAD_ENV */
430 IOMGR_SoftSig(DebugOn, (void *)(intptr_t)LogLevel);
431 #endif /* AFS_PTHREAD_ENV */
434 /* When pthreaded softsig handlers are not in use, some platforms
435 * require this signal handler to be set again. */
436 (void)signal(signo, ResetDebug_Signal);
438 #if defined(AFS_PTHREAD_ENV)
439 if (threadIdLogs == 1)
442 if (serverLogOpts.lopt_rotateOnReset) {
445 } /*ResetDebug_Signal */
448 * Handle requests to reopen the log.
450 * This signal handler will reopen the log file. A new, empty log file
451 * will be created if the log file does not already exist.
453 * External log rotation programs may rotate a server log file by
454 * renaming the existing server log file and then immediately sending a
455 * signal to the corresponding server process. Server log messages will
456 * continue to be appended to the renamed server log file until the
457 * server log is reopened. After this signal handler completes, server
458 * log messages will be written to the new log file. This allows
459 * external log rotation programs to rotate log files without
460 * messages being dropped.
463 ReOpenLog_Signal(int signo)
467 (void)signal(signo, ReOpenLog_Signal);
471 #ifdef AFS_PTHREAD_ENV
473 * Register pthread-safe signal handlers for server log management.
475 * \note opr_softsig_Init() must be called before this function.
478 SetupLogSoftSignals(void)
480 opr_softsig_Register(SIGHUP, ResetDebug_Signal);
481 opr_softsig_Register(SIGTSTP, SetDebug_Signal);
482 opr_softsig_Register(SIGUSR1, ReOpenLog_Signal);
484 (void)signal(SIGPIPE, SIG_IGN);
487 #endif /* AFS_PTHREAD_ENV */
490 * Register signal handlers for server log management.
492 * \note This function is deprecated and should not be used
493 * in new code. This function should be removed when
494 * all the servers have been converted to pthreads
495 * and lwp has been removed.
498 SetupLogSignals(void)
501 (void)signal(SIGHUP, ResetDebug_Signal);
502 (void)signal(SIGTSTP, SetDebug_Signal);
503 (void)signal(SIGUSR1, ReOpenLog_Signal);
505 (void)signal(SIGPIPE, SIG_IGN);
509 #if defined(AFS_PTHREAD_ENV)
517 UnlockServerLog(void)
523 InitServerLogMutex(void)
525 opr_Verify(pthread_mutex_init(&serverLogMutex, NULL) == 0);
526 # ifndef AFS_NT40_ENV
527 opr_Verify(pthread_atfork(LockServerLog, UnlockServerLog, UnlockServerLog) == 0);
530 #endif /* AFS_PTHREAD_ENV */
533 * Redirect stdout and stderr to the log file.
535 * \note Call directly after opening the log file.
537 * \param[in] fileName log file name
540 RedirectStdStreams(const char *fileName)
542 if (freopen(fileName, "a", stdout) == NULL) {
545 if (freopen(fileName, "a", stderr) != NULL) {
547 setvbuf(stderr, NULL, _IONBF, 0);
549 setbuf(stderr, NULL);
557 * Open the log file using the options given in OpenLog().
559 * \returns 0 on success
562 OpenLogFile(const char *fileName)
565 * This function should allow various libraries that inconsistently
566 * use stdout/stderr to all go to the same place
569 int flags = O_WRONLY | O_CREAT | O_APPEND;
571 opr_Assert(serverLogOpts.dest == logDest_file);
573 opr_Assert(fileName != NULL);
575 if (IsFIFO(fileName)) {
576 /* Support named pipes as logs by not rotating them. */
578 } else if (serverLogOpts.lopt_rotateOnOpen) {
579 /* Old style logging always started a new log file. */
581 RenameLogFile(fileName);
584 tempfd = open(fileName, flags, 0666);
586 printf("Unable to open log file %s\n", fileName);
589 RedirectStdStreams(fileName);
591 /* Save our name for reopening. */
592 if (ourName != fileName) {
593 /* Make a copy if needed */
595 ourName = strdup(fileName);
596 opr_Assert(ourName != NULL);
599 serverLogFD = tempfd;
605 * Open the log file descriptor or a connection to the system log.
607 * This function should be called once during program initialization and
608 * must be called before calling FSLog() or WriteLogBuffer(). The
609 * fields of the given argument specify the logging destination and
610 * various optional features.
612 * The lopt_logLevel value specifies the initial logging level.
614 * The lopt_dest enum specifies the logging destination; either
615 * file based (logDest_file) or the system log (logDest_syslog).
620 * A file will be opened for log messages when the lopt_dest enum is set
621 * to logDest_file. The file specified by lopt_filename will be opened
622 * for appending log messages. A new file will be created if the log
623 * file does not exist.
625 * The lopt_rotateOnOpen flag specifies whether an existing log file is
626 * to be renamed and a new log file created during the call to OpenLog.
627 * The lopt_rotateOnOpen flag has no effect if the file given by
628 * lopt_filename is a named pipe (fifo).
630 * The lopt_rotateOnReset flag specifies whether the log file is renamed
631 * and then reopened when the reset signal (SIGHUP) is caught.
633 * The lopt_rotateStyle enum specifies how the new log file is renamed when
634 * lopt_rotateOnOpen or lopt_rotateOnReset are set. The lopt_rotateStyle
635 * may be the traditional Transarc style (logRotate_old) or the MR-AFS
636 * style (logRotate_timestamp).
638 * When lopt_rotateStyle is set to logRotate_old, the suffix ".old" is
639 * appended to the log file name. The existing ".old" log file is
642 * When lopt_rotateStyle is set to logRotate_timestamp, a timestamp
643 * string is appended to the log file name and existing files are not
646 * \note Messages written to stdout and stderr are redirected to the log
647 * file when file-based logging is in effect.
652 * A connection to the system log (syslog) will be established for log
653 * messages when the lopt_dest enum is set to logDest_syslog.
655 * The lopt_facility specifies the system log facility to be used when
656 * writing messages to the system log.
658 * The lopt_tag string specifies the indentification string to be used
659 * when writing messages to the system log.
661 * \param opts logging options. A copy of the logging
662 * options will be made before returning to
665 * \returns 0 on success
668 OpenLog(struct logOptions *opts)
672 #if defined(AFS_PTHREAD_ENV)
673 opr_Verify(pthread_once(&serverLogOnce, InitServerLogMutex) == 0);
674 #endif /* AFS_PTHREAD_ENV */
676 LogLevel = serverLogOpts.logLevel = opts->logLevel;
677 serverLogOpts.dest = opts->dest;
678 switch (serverLogOpts.dest) {
680 serverLogOpts.lopt_rotateOnOpen = opts->lopt_rotateOnOpen;
681 serverLogOpts.lopt_rotateOnReset = opts->lopt_rotateOnReset;
682 serverLogOpts.lopt_rotateStyle = opts->lopt_rotateStyle;
683 /* OpenLogFile() sets ourName; don't cache filename here. */
684 code = OpenLogFile(opts->lopt_filename);
688 serverLogOpts.lopt_rotateOnOpen = 0;
689 serverLogOpts.lopt_rotateOnReset = 0;
690 serverLogOpts.lopt_rotateStyle = logRotate_none;
691 openlog(opts->lopt_tag, LOG_PID, opts->lopt_facility);
702 * Reopen the log file descriptor.
704 * Reopen the log file descriptor in order to support rotation
705 * of the log files. Has no effect when logging to the syslog.
707 * \returns 0 on success
712 int flags = O_WRONLY | O_APPEND | O_CREAT;
715 if (serverLogOpts.dest == logDest_syslog) {
721 if (ourName == NULL) {
725 if (IsFIFO(ourName)) {
728 if (serverLogFD >= 0)
730 serverLogFD = open(ourName, flags, 0666);
731 if (serverLogFD >= 0) {
732 RedirectStdStreams(ourName);
735 return serverLogFD < 0 ? -1 : 0;
739 * Rotate the log file by renaming then truncating.
745 if (ourName != NULL) {
746 if (serverLogFD >= 0) {
750 OpenLogFile(ourName);
756 * Close the server log file.
758 * \note Must be preceeded by OpenLog().
766 if (serverLogOpts.dest == logDest_syslog) {
771 if (serverLogFD >= 0) {