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)
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)
212 #if !defined(AFS_PTHREAD_ENV) && !defined(AFS_NT40_ENV)
213 if (serverLogOpts.dest == logDest_file) {
215 fflush(stderr); /* in case they're sharing the same FD */
221 * Write a message to the log.
223 * \param[in] format printf-style format specification
224 * \param[in] ... arguments for format specification
227 FSLog(const char *format, ...)
231 va_start(args, format);
232 vFSLog(format, args);
237 * Write the command-line invocation to the log.
239 * \param[in] argc argument count from main()
240 * \param[in] argv argument vector from main()
241 * \param[in] progname program name
242 * \param[in] version program version
243 * \param[in] logstring log message string
244 * \param[in] log printf-style log function
247 LogCommandLine(int argc, char **argv, const char *progname,
248 const char *version, const char *logstring,
249 void (*log) (const char *format, ...))
252 char *commandLine, *cx;
254 opr_Assert(argc > 0);
256 for (l = i = 0; i < argc; i++)
257 l += strlen(argv[i]) + 1;
258 if ((commandLine = malloc(l))) {
259 for (cx = commandLine, i = 0; i < argc; i++) {
264 commandLine[l-1] = '\0';
265 (*log)("%s %s %s%s(%s)\n", logstring, progname,
266 version, strlen(version)>0?" ":"", commandLine);
269 /* What, we're out of memory already!? */
270 (*log)("%s %s%s%s\n", logstring,
271 progname, strlen(version)>0?" ":"", version);
276 * Write the single-DES deprecation warning to the log.
281 /* The blank newlines help this stand out a bit more in the log. */
283 ViceLog(0, ("WARNING: You are using single-DES keys in a KeyFile. Using single-DES\n"));
284 ViceLog(0, ("WARNING: long-term keys is considered insecure, and it is strongly\n"));
285 ViceLog(0, ("WARNING: recommended that you migrate to stronger encryption. See\n"));
286 ViceLog(0, ("WARNING: OPENAFS-SA-2013-003 on http://www.openafs.org/security/\n"));
287 ViceLog(0, ("WARNING: for details.\n"));
292 * Move the current log file out of the way so a new one can be started.
294 * The format of the new name depends on the logging style. The traditional
295 * Transarc style appends ".old" to the log file name. When MR-AFS style
296 * logging is in effect, a time stamp is appended to the log file name instead
299 * \bug Unfortunately, no check is made to avoid overwriting
300 * old logs in the traditional Transarc mode.
302 * \param fileName fully qualified log file path
305 RenameLogFile(const char *fileName)
308 char *nextName = NULL;
312 struct tm *timeFields;
314 switch (serverLogOpts.lopt_rotateStyle) {
318 code = asprintf(&nextName, "%s.old", fileName);
323 case logRotate_timestamp:
325 for (tries = 0; nextName == NULL && tries < 100; t++, tries++) {
326 timeFields = localtime(&t);
327 code = asprintf(&nextName, "%s.%d%02d%02d%02d%02d%02d",
328 fileName, timeFields->tm_year + 1900,
329 timeFields->tm_mon + 1, timeFields->tm_mday,
330 timeFields->tm_hour, timeFields->tm_min,
336 if (lstat(nextName, &buf) == 0) {
337 /* Avoid clobbering a log. */
346 if (nextName != NULL) {
347 rk_rename(fileName, nextName); /* Don't check the error code. */
353 * Write message to the log to indicate the log level.
355 * This helper function is called by the signal handlers when the log level is
356 * changed, to write a message to the log to indicate the log level has been
362 int loglevel = (intptr_t)param;
364 ViceLog(0, ("Reset Debug levels to 0\n"));
366 ViceLog(0, ("Set Debug On level = %d\n", loglevel));
372 * Signal handler to increase the logging level.
374 * Increase the current logging level to 1 if it in currently 0,
375 * otherwise, increase the current logging level by a factor of 5 if it
376 * is currently non-zero.
378 * Enables thread id logging when the log level is greater than 1.
381 SetDebug_Signal(int signo)
386 #if defined(AFS_PTHREAD_ENV)
387 if (LogLevel > 1 && threadNumProgram != NULL &&
395 #if defined(AFS_PTHREAD_ENV)
396 if (threadIdLogs == 1)
400 #if defined(AFS_PTHREAD_ENV)
401 DebugOn((void *)(intptr_t)LogLevel);
402 #else /* AFS_PTHREAD_ENV */
403 IOMGR_SoftSig(DebugOn, (void *)(intptr_t)LogLevel);
404 #endif /* AFS_PTHREAD_ENV */
407 /* When pthreaded softsig handlers are not in use, some platforms
408 * require this signal handler to be set again. */
409 (void)signal(signo, SetDebug_Signal);
411 } /*SetDebug_Signal */
414 * Signal handler to reset the logging level.
416 * Reset the logging level and disable thread id logging.
418 * \note This handler has the side-effect of rotating and reopening
422 ResetDebug_Signal(int signo)
426 #if defined(AFS_PTHREAD_ENV)
427 DebugOn((void *)(intptr_t)LogLevel);
428 #else /* AFS_PTHREAD_ENV */
429 IOMGR_SoftSig(DebugOn, (void *)(intptr_t)LogLevel);
430 #endif /* AFS_PTHREAD_ENV */
433 /* When pthreaded softsig handlers are not in use, some platforms
434 * require this signal handler to be set again. */
435 (void)signal(signo, ResetDebug_Signal);
437 #if defined(AFS_PTHREAD_ENV)
438 if (threadIdLogs == 1)
441 if (serverLogOpts.lopt_rotateOnReset) {
444 } /*ResetDebug_Signal */
447 * Handle requests to reopen the log.
449 * This signal handler will reopen the log file. A new, empty log file
450 * will be created if the log file does not already exist.
452 * External log rotation programs may rotate a server log file by
453 * renaming the existing server log file and then immediately sending a
454 * signal to the corresponding server process. Server log messages will
455 * continue to be appended to the renamed server log file until the
456 * server log is reopened. After this signal handler completes, server
457 * log messages will be written to the new log file. This allows
458 * external log rotation programs to rotate log files without
459 * messages being dropped.
462 ReOpenLog_Signal(int signo)
466 (void)signal(signo, ReOpenLog_Signal);
470 #ifdef AFS_PTHREAD_ENV
472 * Register pthread-safe signal handlers for server log management.
474 * \note opr_softsig_Init() must be called before this function.
477 SetupLogSoftSignals(void)
479 opr_softsig_Register(SIGHUP, ResetDebug_Signal);
480 opr_softsig_Register(SIGTSTP, SetDebug_Signal);
481 opr_softsig_Register(SIGUSR1, ReOpenLog_Signal);
483 (void)signal(SIGPIPE, SIG_IGN);
486 #endif /* AFS_PTHREAD_ENV */
489 * Register signal handlers for server log management.
491 * \note This function is deprecated and should not be used
492 * in new code. This function should be removed when
493 * all the servers have been converted to pthreads
494 * and lwp has been removed.
497 SetupLogSignals(void)
500 (void)signal(SIGHUP, ResetDebug_Signal);
501 (void)signal(SIGTSTP, SetDebug_Signal);
502 (void)signal(SIGUSR1, ReOpenLog_Signal);
504 (void)signal(SIGPIPE, SIG_IGN);
508 #if defined(AFS_PTHREAD_ENV)
510 InitServerLogMutex(void)
512 opr_Verify(pthread_mutex_init(&serverLogMutex, NULL) == 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)
528 if (freopen(fileName, "a", stderr) != NULL) {
530 setvbuf(stderr, NULL, _IONBF, 0);
532 setbuf(stderr, NULL);
540 * Open the log file using the options given in OpenLog().
542 * \returns 0 on success
545 OpenLogFile(const char *fileName)
548 * This function should allow various libraries that inconsistently
549 * use stdout/stderr to all go to the same place
552 int flags = O_WRONLY | O_CREAT | O_APPEND;
554 opr_Assert(serverLogOpts.dest == logDest_file);
556 opr_Assert(fileName != NULL);
558 if (IsFIFO(fileName)) {
559 /* Support named pipes as logs by not rotating them. */
561 } else if (serverLogOpts.lopt_rotateOnOpen) {
562 /* Old style logging always started a new log file. */
564 RenameLogFile(fileName);
567 tempfd = open(fileName, flags, 0666);
569 printf("Unable to open log file %s\n", fileName);
572 RedirectStdStreams(fileName);
574 /* Save our name for reopening. */
576 ourName = strdup(fileName);
577 opr_Assert(ourName != NULL);
579 serverLogFD = tempfd;
585 * Open the log file descriptor or a connection to the system log.
587 * This function should be called once during program initialization and
588 * must be called before calling FSLog() or WriteLogBuffer(). The
589 * fields of the given argument specify the logging destination and
590 * various optional features.
592 * The lopt_logLevel value specifies the initial logging level.
594 * The lopt_dest enum specifies the logging destination; either
595 * file based (logDest_file) or the system log (logDest_syslog).
600 * A file will be opened for log messages when the lopt_dest enum is set
601 * to logDest_file. The file specified by lopt_filename will be opened
602 * for appending log messages. A new file will be created if the log
603 * file does not exist.
605 * The lopt_rotateOnOpen flag specifies whether an existing log file is
606 * to be renamed and a new log file created during the call to OpenLog.
607 * The lopt_rotateOnOpen flag has no effect if the file given by
608 * lopt_filename is a named pipe (fifo).
610 * The lopt_rotateOnReset flag specifies whether the log file is renamed
611 * and then reopened when the reset signal (SIGHUP) is caught.
613 * The lopt_rotateStyle enum specifies how the new log file is renamed when
614 * lopt_rotateOnOpen or lopt_rotateOnReset are set. The lopt_rotateStyle
615 * may be the traditional Transarc style (logRotate_old) or the MR-AFS
616 * style (logRotate_timestamp).
618 * When lopt_rotateStyle is set to logRotate_old, the suffix ".old" is
619 * appended to the log file name. The existing ".old" log file is
622 * When lopt_rotateStyle is set to logRotate_timestamp, a timestamp
623 * string is appended to the log file name and existing files are not
626 * \note Messages written to stdout and stderr are redirected to the log
627 * file when file-based logging is in effect.
632 * A connection to the system log (syslog) will be established for log
633 * messages when the lopt_dest enum is set to logDest_syslog.
635 * The lopt_facility specifies the system log facility to be used when
636 * writing messages to the system log.
638 * The lopt_tag string specifies the indentification string to be used
639 * when writing messages to the system log.
641 * \param opts logging options. A copy of the logging
642 * options will be made before returning to
645 * \returns 0 on success
648 OpenLog(struct logOptions *opts)
652 #if defined(AFS_PTHREAD_ENV)
653 opr_Verify(pthread_once(&serverLogOnce, InitServerLogMutex) == 0);
654 #endif /* AFS_PTHREAD_ENV */
656 LogLevel = serverLogOpts.logLevel = opts->logLevel;
657 serverLogOpts.dest = opts->dest;
658 switch (serverLogOpts.dest) {
660 serverLogOpts.lopt_rotateOnOpen = opts->lopt_rotateOnOpen;
661 serverLogOpts.lopt_rotateOnReset = opts->lopt_rotateOnReset;
662 serverLogOpts.lopt_rotateStyle = opts->lopt_rotateStyle;
663 /* OpenLogFile() sets ourName; don't cache filename here. */
664 code = OpenLogFile(opts->lopt_filename);
668 serverLogOpts.lopt_rotateOnOpen = 0;
669 serverLogOpts.lopt_rotateOnReset = 0;
670 serverLogOpts.lopt_rotateStyle = logRotate_none;
671 openlog(opts->lopt_tag, LOG_PID, opts->lopt_facility);
682 * Reopen the log file descriptor.
684 * Reopen the log file descriptor in order to support rotation
685 * of the log files. Has no effect when logging to the syslog.
687 * \returns 0 on success
692 int flags = O_WRONLY | O_APPEND | O_CREAT;
695 if (serverLogOpts.dest == logDest_syslog) {
701 if (ourName == NULL) {
705 if (IsFIFO(ourName)) {
708 if (serverLogFD >= 0)
710 serverLogFD = open(ourName, flags, 0666);
711 if (serverLogFD >= 0) {
712 RedirectStdStreams(ourName);
715 return serverLogFD < 0 ? -1 : 0;
719 * Rotate the log file by renaming then truncating.
725 if (ourName != NULL) {
726 if (serverLogFD >= 0) {
730 OpenLogFile(ourName);
736 * Close the server log file.
738 * \note Must be preceeded by OpenLog().
746 if (serverLogOpts.dest == logDest_syslog) {
751 if (serverLogFD >= 0) {