1 /*-------------------------------------------------------------------------
2  *
3  * syslogger.c
4  *
5  * The system logger (syslogger) appeared in Postgres 8.0. It catches all
6  * stderr output from the postmaster, backends, and other subprocesses
7  * by redirecting to a pipe, and writes it to a set of logfiles.
8  * It's possible to have size and age limits for the logfile configured
9  * in postgresql.conf. If these limits are reached or passed, the
10  * current logfile is closed and a new one is created (rotated).
11  * The logfiles are stored in a subdirectory (configurable in
12  * postgresql.conf), using a user-selectable naming scheme.
13  *
14  * Author: Andreas Pflug <pgadmin@pse-consulting.de>
15  *
16  * Copyright (c) 2004-2017, PostgreSQL Global Development Group
17  *
18  *
19  * IDENTIFICATION
20  *	  src/backend/postmaster/syslogger.c
21  *
22  *-------------------------------------------------------------------------
23  */
24 #include "postgres.h"
25 
26 #include <fcntl.h>
27 #include <limits.h>
28 #include <signal.h>
29 #include <time.h>
30 #include <unistd.h>
31 #include <sys/stat.h>
32 #include <sys/time.h>
33 
34 #include "lib/stringinfo.h"
35 #include "libpq/pqsignal.h"
36 #include "miscadmin.h"
37 #include "nodes/pg_list.h"
38 #include "pgstat.h"
39 #include "pgtime.h"
40 #include "postmaster/fork_process.h"
41 #include "postmaster/postmaster.h"
42 #include "postmaster/syslogger.h"
43 #include "storage/dsm.h"
44 #include "storage/ipc.h"
45 #include "storage/latch.h"
46 #include "storage/pg_shmem.h"
47 #include "tcop/tcopprot.h"
48 #include "utils/guc.h"
49 #include "utils/ps_status.h"
50 #include "utils/timestamp.h"
51 
52 /*
53  * We read() into a temp buffer twice as big as a chunk, so that any fragment
54  * left after processing can be moved down to the front and we'll still have
55  * room to read a full chunk.
56  */
57 #define READ_BUF_SIZE (2 * PIPE_CHUNK_SIZE)
58 
59 
60 /*
61  * GUC parameters.  Logging_collector cannot be changed after postmaster
62  * start, but the rest can change at SIGHUP.
63  */
64 bool		Logging_collector = false;
65 int			Log_RotationAge = HOURS_PER_DAY * MINS_PER_HOUR;
66 int			Log_RotationSize = 10 * 1024;
67 char	   *Log_directory = NULL;
68 char	   *Log_filename = NULL;
69 bool		Log_truncate_on_rotation = false;
70 int			Log_file_mode = S_IRUSR | S_IWUSR;
71 
72 /*
73  * Globally visible state (used by elog.c)
74  */
75 bool		am_syslogger = false;
76 
77 extern bool redirection_done;
78 
79 /*
80  * Private state
81  */
82 static pg_time_t next_rotation_time;
83 static bool pipe_eof_seen = false;
84 static bool rotation_disabled = false;
85 static FILE *syslogFile = NULL;
86 static FILE *csvlogFile = NULL;
87 NON_EXEC_STATIC pg_time_t first_syslogger_file_time = 0;
88 static char *last_file_name = NULL;
89 static char *last_csv_file_name = NULL;
90 
91 /*
92  * Buffers for saving partial messages from different backends.
93  *
94  * Keep NBUFFER_LISTS lists of these, with the entry for a given source pid
95  * being in the list numbered (pid % NBUFFER_LISTS), so as to cut down on
96  * the number of entries we have to examine for any one incoming message.
97  * There must never be more than one entry for the same source pid.
98  *
99  * An inactive buffer is not removed from its list, just held for re-use.
100  * An inactive buffer has pid == 0 and undefined contents of data.
101  */
102 typedef struct
103 {
104 	int32		pid;			/* PID of source process */
105 	StringInfoData data;		/* accumulated data, as a StringInfo */
106 } save_buffer;
107 
108 #define NBUFFER_LISTS 256
109 static List *buffer_lists[NBUFFER_LISTS];
110 
111 /* These must be exported for EXEC_BACKEND case ... annoying */
112 #ifndef WIN32
113 int			syslogPipe[2] = {-1, -1};
114 #else
115 HANDLE		syslogPipe[2] = {0, 0};
116 #endif
117 
118 #ifdef WIN32
119 static HANDLE threadHandle = 0;
120 static CRITICAL_SECTION sysloggerSection;
121 #endif
122 
123 /*
124  * Flags set by interrupt handlers for later service in the main loop.
125  */
126 static volatile sig_atomic_t got_SIGHUP = false;
127 static volatile sig_atomic_t rotation_requested = false;
128 
129 
130 /* Local subroutines */
131 #ifdef EXEC_BACKEND
132 static pid_t syslogger_forkexec(void);
133 static void syslogger_parseArgs(int argc, char *argv[]);
134 #endif
135 NON_EXEC_STATIC void SysLoggerMain(int argc, char *argv[]) pg_attribute_noreturn();
136 static void process_pipe_input(char *logbuffer, int *bytes_in_logbuffer);
137 static void flush_pipe_input(char *logbuffer, int *bytes_in_logbuffer);
138 static FILE *logfile_open(const char *filename, const char *mode,
139 			 bool allow_errors);
140 
141 #ifdef WIN32
142 static unsigned int __stdcall pipeThread(void *arg);
143 #endif
144 static void logfile_rotate(bool time_based_rotation, int size_rotation_for);
145 static char *logfile_getname(pg_time_t timestamp, const char *suffix);
146 static void set_next_rotation_time(void);
147 static void sigHupHandler(SIGNAL_ARGS);
148 static void sigUsr1Handler(SIGNAL_ARGS);
149 static void update_metainfo_datafile(void);
150 
151 
152 /*
153  * Main entry point for syslogger process
154  * argc/argv parameters are valid only in EXEC_BACKEND case.
155  */
156 NON_EXEC_STATIC void
SysLoggerMain(int argc,char * argv[])157 SysLoggerMain(int argc, char *argv[])
158 {
159 #ifndef WIN32
160 	char		logbuffer[READ_BUF_SIZE];
161 	int			bytes_in_logbuffer = 0;
162 #endif
163 	char	   *currentLogDir;
164 	char	   *currentLogFilename;
165 	int			currentLogRotationAge;
166 	pg_time_t	now;
167 
168 	now = MyStartTime;
169 
170 #ifdef EXEC_BACKEND
171 	syslogger_parseArgs(argc, argv);
172 #endif							/* EXEC_BACKEND */
173 
174 	am_syslogger = true;
175 
176 	init_ps_display("logger process", "", "", "");
177 
178 	/*
179 	 * If we restarted, our stderr is already redirected into our own input
180 	 * pipe.  This is of course pretty useless, not to mention that it
181 	 * interferes with detecting pipe EOF.  Point stderr to /dev/null. This
182 	 * assumes that all interesting messages generated in the syslogger will
183 	 * come through elog.c and will be sent to write_syslogger_file.
184 	 */
185 	if (redirection_done)
186 	{
187 		int			fd = open(DEVNULL, O_WRONLY, 0);
188 
189 		/*
190 		 * The closes might look redundant, but they are not: we want to be
191 		 * darn sure the pipe gets closed even if the open failed.  We can
192 		 * survive running with stderr pointing nowhere, but we can't afford
193 		 * to have extra pipe input descriptors hanging around.
194 		 *
195 		 * As we're just trying to reset these to go to DEVNULL, there's not
196 		 * much point in checking for failure from the close/dup2 calls here,
197 		 * if they fail then presumably the file descriptors are closed and
198 		 * any writes will go into the bitbucket anyway.
199 		 */
200 		close(fileno(stdout));
201 		close(fileno(stderr));
202 		if (fd != -1)
203 		{
204 			(void) dup2(fd, fileno(stdout));
205 			(void) dup2(fd, fileno(stderr));
206 			close(fd);
207 		}
208 	}
209 
210 	/*
211 	 * Syslogger's own stderr can't be the syslogPipe, so set it back to text
212 	 * mode if we didn't just close it. (It was set to binary in
213 	 * SubPostmasterMain).
214 	 */
215 #ifdef WIN32
216 	else
217 		_setmode(_fileno(stderr), _O_TEXT);
218 #endif
219 
220 	/*
221 	 * Also close our copy of the write end of the pipe.  This is needed to
222 	 * ensure we can detect pipe EOF correctly.  (But note that in the restart
223 	 * case, the postmaster already did this.)
224 	 */
225 #ifndef WIN32
226 	if (syslogPipe[1] >= 0)
227 		close(syslogPipe[1]);
228 	syslogPipe[1] = -1;
229 #else
230 	if (syslogPipe[1])
231 		CloseHandle(syslogPipe[1]);
232 	syslogPipe[1] = 0;
233 #endif
234 
235 	/*
236 	 * Properly accept or ignore signals the postmaster might send us
237 	 *
238 	 * Note: we ignore all termination signals, and instead exit only when all
239 	 * upstream processes are gone, to ensure we don't miss any dying gasps of
240 	 * broken backends...
241 	 */
242 
243 	pqsignal(SIGHUP, sigHupHandler);	/* set flag to read config file */
244 	pqsignal(SIGINT, SIG_IGN);
245 	pqsignal(SIGTERM, SIG_IGN);
246 	pqsignal(SIGQUIT, SIG_IGN);
247 	pqsignal(SIGALRM, SIG_IGN);
248 	pqsignal(SIGPIPE, SIG_IGN);
249 	pqsignal(SIGUSR1, sigUsr1Handler);	/* request log rotation */
250 	pqsignal(SIGUSR2, SIG_IGN);
251 
252 	/*
253 	 * Reset some signals that are accepted by postmaster but not here
254 	 */
255 	pqsignal(SIGCHLD, SIG_DFL);
256 	pqsignal(SIGTTIN, SIG_DFL);
257 	pqsignal(SIGTTOU, SIG_DFL);
258 	pqsignal(SIGCONT, SIG_DFL);
259 	pqsignal(SIGWINCH, SIG_DFL);
260 
261 	PG_SETMASK(&UnBlockSig);
262 
263 #ifdef WIN32
264 	/* Fire up separate data transfer thread */
265 	InitializeCriticalSection(&sysloggerSection);
266 	EnterCriticalSection(&sysloggerSection);
267 
268 	threadHandle = (HANDLE) _beginthreadex(NULL, 0, pipeThread, NULL, 0, NULL);
269 	if (threadHandle == 0)
270 		elog(FATAL, "could not create syslogger data transfer thread: %m");
271 #endif							/* WIN32 */
272 
273 	/*
274 	 * Remember active logfiles' name(s).  We recompute 'em from the reference
275 	 * time because passing down just the pg_time_t is a lot cheaper than
276 	 * passing a whole file path in the EXEC_BACKEND case.
277 	 */
278 	last_file_name = logfile_getname(first_syslogger_file_time, NULL);
279 	if (csvlogFile != NULL)
280 		last_csv_file_name = logfile_getname(first_syslogger_file_time, ".csv");
281 
282 	/* remember active logfile parameters */
283 	currentLogDir = pstrdup(Log_directory);
284 	currentLogFilename = pstrdup(Log_filename);
285 	currentLogRotationAge = Log_RotationAge;
286 	/* set next planned rotation time */
287 	set_next_rotation_time();
288 	update_metainfo_datafile();
289 
290 	/*
291 	 * Reset whereToSendOutput, as the postmaster will do (but hasn't yet, at
292 	 * the point where we forked).  This prevents duplicate output of messages
293 	 * from syslogger itself.
294 	 */
295 	whereToSendOutput = DestNone;
296 
297 	/* main worker loop */
298 	for (;;)
299 	{
300 		bool		time_based_rotation = false;
301 		int			size_rotation_for = 0;
302 		long		cur_timeout;
303 		int			cur_flags;
304 
305 #ifndef WIN32
306 		int			rc;
307 #endif
308 
309 		/* Clear any already-pending wakeups */
310 		ResetLatch(MyLatch);
311 
312 		/*
313 		 * Process any requests or signals received recently.
314 		 */
315 		if (got_SIGHUP)
316 		{
317 			got_SIGHUP = false;
318 			ProcessConfigFile(PGC_SIGHUP);
319 
320 			/*
321 			 * Check if the log directory or filename pattern changed in
322 			 * postgresql.conf. If so, force rotation to make sure we're
323 			 * writing the logfiles in the right place.
324 			 */
325 			if (strcmp(Log_directory, currentLogDir) != 0)
326 			{
327 				pfree(currentLogDir);
328 				currentLogDir = pstrdup(Log_directory);
329 				rotation_requested = true;
330 
331 				/*
332 				 * Also, create new directory if not present; ignore errors
333 				 */
334 				mkdir(Log_directory, S_IRWXU);
335 			}
336 			if (strcmp(Log_filename, currentLogFilename) != 0)
337 			{
338 				pfree(currentLogFilename);
339 				currentLogFilename = pstrdup(Log_filename);
340 				rotation_requested = true;
341 			}
342 
343 			/*
344 			 * Force a rotation if CSVLOG output was just turned on or off and
345 			 * we need to open or close csvlogFile accordingly.
346 			 */
347 			if (((Log_destination & LOG_DESTINATION_CSVLOG) != 0) !=
348 				(csvlogFile != NULL))
349 				rotation_requested = true;
350 
351 			/*
352 			 * If rotation time parameter changed, reset next rotation time,
353 			 * but don't immediately force a rotation.
354 			 */
355 			if (currentLogRotationAge != Log_RotationAge)
356 			{
357 				currentLogRotationAge = Log_RotationAge;
358 				set_next_rotation_time();
359 			}
360 
361 			/*
362 			 * If we had a rotation-disabling failure, re-enable rotation
363 			 * attempts after SIGHUP, and force one immediately.
364 			 */
365 			if (rotation_disabled)
366 			{
367 				rotation_disabled = false;
368 				rotation_requested = true;
369 			}
370 
371 			/*
372 			 * Force rewriting last log filename when reloading configuration.
373 			 * Even if rotation_requested is false, log_destination may have
374 			 * been changed and we don't want to wait the next file rotation.
375 			 */
376 			update_metainfo_datafile();
377 		}
378 
379 		if (Log_RotationAge > 0 && !rotation_disabled)
380 		{
381 			/* Do a logfile rotation if it's time */
382 			now = (pg_time_t) time(NULL);
383 			if (now >= next_rotation_time)
384 				rotation_requested = time_based_rotation = true;
385 		}
386 
387 		if (!rotation_requested && Log_RotationSize > 0 && !rotation_disabled)
388 		{
389 			/* Do a rotation if file is too big */
390 			if (ftell(syslogFile) >= Log_RotationSize * 1024L)
391 			{
392 				rotation_requested = true;
393 				size_rotation_for |= LOG_DESTINATION_STDERR;
394 			}
395 			if (csvlogFile != NULL &&
396 				ftell(csvlogFile) >= Log_RotationSize * 1024L)
397 			{
398 				rotation_requested = true;
399 				size_rotation_for |= LOG_DESTINATION_CSVLOG;
400 			}
401 		}
402 
403 		if (rotation_requested)
404 		{
405 			/*
406 			 * Force rotation when both values are zero. It means the request
407 			 * was sent by pg_rotate_logfile.
408 			 */
409 			if (!time_based_rotation && size_rotation_for == 0)
410 				size_rotation_for = LOG_DESTINATION_STDERR | LOG_DESTINATION_CSVLOG;
411 			logfile_rotate(time_based_rotation, size_rotation_for);
412 		}
413 
414 		/*
415 		 * Calculate time till next time-based rotation, so that we don't
416 		 * sleep longer than that.  We assume the value of "now" obtained
417 		 * above is still close enough.  Note we can't make this calculation
418 		 * until after calling logfile_rotate(), since it will advance
419 		 * next_rotation_time.
420 		 *
421 		 * Also note that we need to beware of overflow in calculation of the
422 		 * timeout: with large settings of Log_RotationAge, next_rotation_time
423 		 * could be more than INT_MAX msec in the future.  In that case we'll
424 		 * wait no more than INT_MAX msec, and try again.
425 		 */
426 		if (Log_RotationAge > 0 && !rotation_disabled)
427 		{
428 			pg_time_t	delay;
429 
430 			delay = next_rotation_time - now;
431 			if (delay > 0)
432 			{
433 				if (delay > INT_MAX / 1000)
434 					delay = INT_MAX / 1000;
435 				cur_timeout = delay * 1000L;	/* msec */
436 			}
437 			else
438 				cur_timeout = 0;
439 			cur_flags = WL_TIMEOUT;
440 		}
441 		else
442 		{
443 			cur_timeout = -1L;
444 			cur_flags = 0;
445 		}
446 
447 		/*
448 		 * Sleep until there's something to do
449 		 */
450 #ifndef WIN32
451 		rc = WaitLatchOrSocket(MyLatch,
452 							   WL_LATCH_SET | WL_SOCKET_READABLE | cur_flags,
453 							   syslogPipe[0],
454 							   cur_timeout,
455 							   WAIT_EVENT_SYSLOGGER_MAIN);
456 
457 		if (rc & WL_SOCKET_READABLE)
458 		{
459 			int			bytesRead;
460 
461 			bytesRead = read(syslogPipe[0],
462 							 logbuffer + bytes_in_logbuffer,
463 							 sizeof(logbuffer) - bytes_in_logbuffer);
464 			if (bytesRead < 0)
465 			{
466 				if (errno != EINTR)
467 					ereport(LOG,
468 							(errcode_for_socket_access(),
469 							 errmsg("could not read from logger pipe: %m")));
470 			}
471 			else if (bytesRead > 0)
472 			{
473 				bytes_in_logbuffer += bytesRead;
474 				process_pipe_input(logbuffer, &bytes_in_logbuffer);
475 				continue;
476 			}
477 			else
478 			{
479 				/*
480 				 * Zero bytes read when select() is saying read-ready means
481 				 * EOF on the pipe: that is, there are no longer any processes
482 				 * with the pipe write end open.  Therefore, the postmaster
483 				 * and all backends are shut down, and we are done.
484 				 */
485 				pipe_eof_seen = true;
486 
487 				/* if there's any data left then force it out now */
488 				flush_pipe_input(logbuffer, &bytes_in_logbuffer);
489 			}
490 		}
491 #else							/* WIN32 */
492 
493 		/*
494 		 * On Windows we leave it to a separate thread to transfer data and
495 		 * detect pipe EOF.  The main thread just wakes up to handle SIGHUP
496 		 * and rotation conditions.
497 		 *
498 		 * Server code isn't generally thread-safe, so we ensure that only one
499 		 * of the threads is active at a time by entering the critical section
500 		 * whenever we're not sleeping.
501 		 */
502 		LeaveCriticalSection(&sysloggerSection);
503 
504 		(void) WaitLatch(MyLatch,
505 						 WL_LATCH_SET | cur_flags,
506 						 cur_timeout,
507 						 WAIT_EVENT_SYSLOGGER_MAIN);
508 
509 		EnterCriticalSection(&sysloggerSection);
510 #endif							/* WIN32 */
511 
512 		if (pipe_eof_seen)
513 		{
514 			/*
515 			 * seeing this message on the real stderr is annoying - so we make
516 			 * it DEBUG1 to suppress in normal use.
517 			 */
518 			ereport(DEBUG1,
519 					(errmsg("logger shutting down")));
520 
521 			/*
522 			 * Normal exit from the syslogger is here.  Note that we
523 			 * deliberately do not close syslogFile before exiting; this is to
524 			 * allow for the possibility of elog messages being generated
525 			 * inside proc_exit.  Regular exit() will take care of flushing
526 			 * and closing stdio channels.
527 			 */
528 			proc_exit(0);
529 		}
530 	}
531 }
532 
533 /*
534  * Postmaster subroutine to start a syslogger subprocess.
535  */
536 int
SysLogger_Start(void)537 SysLogger_Start(void)
538 {
539 	pid_t		sysloggerPid;
540 	char	   *filename;
541 
542 	if (!Logging_collector)
543 		return 0;
544 
545 	/*
546 	 * If first time through, create the pipe which will receive stderr
547 	 * output.
548 	 *
549 	 * If the syslogger crashes and needs to be restarted, we continue to use
550 	 * the same pipe (indeed must do so, since extant backends will be writing
551 	 * into that pipe).
552 	 *
553 	 * This means the postmaster must continue to hold the read end of the
554 	 * pipe open, so we can pass it down to the reincarnated syslogger. This
555 	 * is a bit klugy but we have little choice.
556 	 */
557 #ifndef WIN32
558 	if (syslogPipe[0] < 0)
559 	{
560 		if (pipe(syslogPipe) < 0)
561 			ereport(FATAL,
562 					(errcode_for_socket_access(),
563 					 (errmsg("could not create pipe for syslog: %m"))));
564 	}
565 #else
566 	if (!syslogPipe[0])
567 	{
568 		SECURITY_ATTRIBUTES sa;
569 
570 		memset(&sa, 0, sizeof(SECURITY_ATTRIBUTES));
571 		sa.nLength = sizeof(SECURITY_ATTRIBUTES);
572 		sa.bInheritHandle = TRUE;
573 
574 		if (!CreatePipe(&syslogPipe[0], &syslogPipe[1], &sa, 32768))
575 			ereport(FATAL,
576 					(errcode_for_file_access(),
577 					 (errmsg("could not create pipe for syslog: %m"))));
578 	}
579 #endif
580 
581 	/*
582 	 * Create log directory if not present; ignore errors
583 	 */
584 	mkdir(Log_directory, S_IRWXU);
585 
586 	/*
587 	 * The initial logfile is created right in the postmaster, to verify that
588 	 * the Log_directory is writable.  We save the reference time so that the
589 	 * syslogger child process can recompute this file name.
590 	 *
591 	 * It might look a bit strange to re-do this during a syslogger restart,
592 	 * but we must do so since the postmaster closed syslogFile after the
593 	 * previous fork (and remembering that old file wouldn't be right anyway).
594 	 * Note we always append here, we won't overwrite any existing file.  This
595 	 * is consistent with the normal rules, because by definition this is not
596 	 * a time-based rotation.
597 	 */
598 	first_syslogger_file_time = time(NULL);
599 
600 	filename = logfile_getname(first_syslogger_file_time, NULL);
601 
602 	syslogFile = logfile_open(filename, "a", false);
603 
604 	pfree(filename);
605 
606 	/*
607 	 * Likewise for the initial CSV log file, if that's enabled.  (Note that
608 	 * we open syslogFile even when only CSV output is nominally enabled,
609 	 * since some code paths will write to syslogFile anyway.)
610 	 */
611 	if (Log_destination & LOG_DESTINATION_CSVLOG)
612 	{
613 		filename = logfile_getname(first_syslogger_file_time, ".csv");
614 
615 		csvlogFile = logfile_open(filename, "a", false);
616 
617 		pfree(filename);
618 	}
619 
620 #ifdef EXEC_BACKEND
621 	switch ((sysloggerPid = syslogger_forkexec()))
622 #else
623 	switch ((sysloggerPid = fork_process()))
624 #endif
625 	{
626 		case -1:
627 			ereport(LOG,
628 					(errmsg("could not fork system logger: %m")));
629 			return 0;
630 
631 #ifndef EXEC_BACKEND
632 		case 0:
633 			/* in postmaster child ... */
634 			InitPostmasterChild();
635 
636 			/* Close the postmaster's sockets */
637 			ClosePostmasterPorts(true);
638 
639 			/* Drop our connection to postmaster's shared memory, as well */
640 			dsm_detach_all();
641 			PGSharedMemoryDetach();
642 
643 			/* do the work */
644 			SysLoggerMain(0, NULL);
645 			break;
646 #endif
647 
648 		default:
649 			/* success, in postmaster */
650 
651 			/* now we redirect stderr, if not done already */
652 			if (!redirection_done)
653 			{
654 #ifdef WIN32
655 				int			fd;
656 #endif
657 
658 				/*
659 				 * Leave a breadcrumb trail when redirecting, in case the user
660 				 * forgets that redirection is active and looks only at the
661 				 * original stderr target file.
662 				 */
663 				ereport(LOG,
664 						(errmsg("redirecting log output to logging collector process"),
665 						 errhint("Future log output will appear in directory \"%s\".",
666 								 Log_directory)));
667 
668 #ifndef WIN32
669 				fflush(stdout);
670 				if (dup2(syslogPipe[1], fileno(stdout)) < 0)
671 					ereport(FATAL,
672 							(errcode_for_file_access(),
673 							 errmsg("could not redirect stdout: %m")));
674 				fflush(stderr);
675 				if (dup2(syslogPipe[1], fileno(stderr)) < 0)
676 					ereport(FATAL,
677 							(errcode_for_file_access(),
678 							 errmsg("could not redirect stderr: %m")));
679 				/* Now we are done with the write end of the pipe. */
680 				close(syslogPipe[1]);
681 				syslogPipe[1] = -1;
682 #else
683 
684 				/*
685 				 * open the pipe in binary mode and make sure stderr is binary
686 				 * after it's been dup'ed into, to avoid disturbing the pipe
687 				 * chunking protocol.
688 				 */
689 				fflush(stderr);
690 				fd = _open_osfhandle((intptr_t) syslogPipe[1],
691 									 _O_APPEND | _O_BINARY);
692 				if (dup2(fd, _fileno(stderr)) < 0)
693 					ereport(FATAL,
694 							(errcode_for_file_access(),
695 							 errmsg("could not redirect stderr: %m")));
696 				close(fd);
697 				_setmode(_fileno(stderr), _O_BINARY);
698 
699 				/*
700 				 * Now we are done with the write end of the pipe.
701 				 * CloseHandle() must not be called because the preceding
702 				 * close() closes the underlying handle.
703 				 */
704 				syslogPipe[1] = 0;
705 #endif
706 				redirection_done = true;
707 			}
708 
709 			/* postmaster will never write the file(s); close 'em */
710 			fclose(syslogFile);
711 			syslogFile = NULL;
712 			if (csvlogFile != NULL)
713 			{
714 				fclose(csvlogFile);
715 				csvlogFile = NULL;
716 			}
717 			return (int) sysloggerPid;
718 	}
719 
720 	/* we should never reach here */
721 	return 0;
722 }
723 
724 
725 #ifdef EXEC_BACKEND
726 
727 /*
728  * syslogger_forkexec() -
729  *
730  * Format up the arglist for, then fork and exec, a syslogger process
731  */
732 static pid_t
syslogger_forkexec(void)733 syslogger_forkexec(void)
734 {
735 	char	   *av[10];
736 	int			ac = 0;
737 	char		filenobuf[32];
738 	char		csvfilenobuf[32];
739 
740 	av[ac++] = "postgres";
741 	av[ac++] = "--forklog";
742 	av[ac++] = NULL;			/* filled in by postmaster_forkexec */
743 
744 	/* static variables (those not passed by write_backend_variables) */
745 #ifndef WIN32
746 	if (syslogFile != NULL)
747 		snprintf(filenobuf, sizeof(filenobuf), "%d",
748 				 fileno(syslogFile));
749 	else
750 		strcpy(filenobuf, "-1");
751 #else							/* WIN32 */
752 	if (syslogFile != NULL)
753 		snprintf(filenobuf, sizeof(filenobuf), "%ld",
754 				 (long) _get_osfhandle(_fileno(syslogFile)));
755 	else
756 		strcpy(filenobuf, "0");
757 #endif							/* WIN32 */
758 	av[ac++] = filenobuf;
759 
760 #ifndef WIN32
761 	if (csvlogFile != NULL)
762 		snprintf(csvfilenobuf, sizeof(csvfilenobuf), "%d",
763 				 fileno(csvlogFile));
764 	else
765 		strcpy(csvfilenobuf, "-1");
766 #else							/* WIN32 */
767 	if (csvlogFile != NULL)
768 		snprintf(csvfilenobuf, sizeof(csvfilenobuf), "%ld",
769 				 (long) _get_osfhandle(_fileno(csvlogFile)));
770 	else
771 		strcpy(csvfilenobuf, "0");
772 #endif							/* WIN32 */
773 	av[ac++] = csvfilenobuf;
774 
775 	av[ac] = NULL;
776 	Assert(ac < lengthof(av));
777 
778 	return postmaster_forkexec(ac, av);
779 }
780 
781 /*
782  * syslogger_parseArgs() -
783  *
784  * Extract data from the arglist for exec'ed syslogger process
785  */
786 static void
syslogger_parseArgs(int argc,char * argv[])787 syslogger_parseArgs(int argc, char *argv[])
788 {
789 	int			fd;
790 
791 	Assert(argc == 5);
792 	argv += 3;
793 
794 	/*
795 	 * Re-open the error output files that were opened by SysLogger_Start().
796 	 *
797 	 * We expect this will always succeed, which is too optimistic, but if it
798 	 * fails there's not a lot we can do to report the problem anyway.  As
799 	 * coded, we'll just crash on a null pointer dereference after failure...
800 	 */
801 #ifndef WIN32
802 	fd = atoi(*argv++);
803 	if (fd != -1)
804 	{
805 		syslogFile = fdopen(fd, "a");
806 		setvbuf(syslogFile, NULL, PG_IOLBF, 0);
807 	}
808 	fd = atoi(*argv++);
809 	if (fd != -1)
810 	{
811 		csvlogFile = fdopen(fd, "a");
812 		setvbuf(csvlogFile, NULL, PG_IOLBF, 0);
813 	}
814 #else							/* WIN32 */
815 	fd = atoi(*argv++);
816 	if (fd != 0)
817 	{
818 		fd = _open_osfhandle(fd, _O_APPEND | _O_TEXT);
819 		if (fd > 0)
820 		{
821 			syslogFile = fdopen(fd, "a");
822 			setvbuf(syslogFile, NULL, PG_IOLBF, 0);
823 		}
824 	}
825 	fd = atoi(*argv++);
826 	if (fd != 0)
827 	{
828 		fd = _open_osfhandle(fd, _O_APPEND | _O_TEXT);
829 		if (fd > 0)
830 		{
831 			csvlogFile = fdopen(fd, "a");
832 			setvbuf(csvlogFile, NULL, PG_IOLBF, 0);
833 		}
834 	}
835 #endif							/* WIN32 */
836 }
837 #endif							/* EXEC_BACKEND */
838 
839 
840 /* --------------------------------
841  *		pipe protocol handling
842  * --------------------------------
843  */
844 
845 /*
846  * Process data received through the syslogger pipe.
847  *
848  * This routine interprets the log pipe protocol which sends log messages as
849  * (hopefully atomic) chunks - such chunks are detected and reassembled here.
850  *
851  * The protocol has a header that starts with two nul bytes, then has a 16 bit
852  * length, the pid of the sending process, and a flag to indicate if it is
853  * the last chunk in a message. Incomplete chunks are saved until we read some
854  * more, and non-final chunks are accumulated until we get the final chunk.
855  *
856  * All of this is to avoid 2 problems:
857  * . partial messages being written to logfiles (messes rotation), and
858  * . messages from different backends being interleaved (messages garbled).
859  *
860  * Any non-protocol messages are written out directly. These should only come
861  * from non-PostgreSQL sources, however (e.g. third party libraries writing to
862  * stderr).
863  *
864  * logbuffer is the data input buffer, and *bytes_in_logbuffer is the number
865  * of bytes present.  On exit, any not-yet-eaten data is left-justified in
866  * logbuffer, and *bytes_in_logbuffer is updated.
867  */
868 static void
process_pipe_input(char * logbuffer,int * bytes_in_logbuffer)869 process_pipe_input(char *logbuffer, int *bytes_in_logbuffer)
870 {
871 	char	   *cursor = logbuffer;
872 	int			count = *bytes_in_logbuffer;
873 	int			dest = LOG_DESTINATION_STDERR;
874 
875 	/* While we have enough for a header, process data... */
876 	while (count >= (int) (offsetof(PipeProtoHeader, data) + 1))
877 	{
878 		PipeProtoHeader p;
879 		int			chunklen;
880 
881 		/* Do we have a valid header? */
882 		memcpy(&p, cursor, offsetof(PipeProtoHeader, data));
883 		if (p.nuls[0] == '\0' && p.nuls[1] == '\0' &&
884 			p.len > 0 && p.len <= PIPE_MAX_PAYLOAD &&
885 			p.pid != 0 &&
886 			(p.is_last == 't' || p.is_last == 'f' ||
887 			 p.is_last == 'T' || p.is_last == 'F'))
888 		{
889 			List	   *buffer_list;
890 			ListCell   *cell;
891 			save_buffer *existing_slot = NULL,
892 					   *free_slot = NULL;
893 			StringInfo	str;
894 
895 			chunklen = PIPE_HEADER_SIZE + p.len;
896 
897 			/* Fall out of loop if we don't have the whole chunk yet */
898 			if (count < chunklen)
899 				break;
900 
901 			dest = (p.is_last == 'T' || p.is_last == 'F') ?
902 				LOG_DESTINATION_CSVLOG : LOG_DESTINATION_STDERR;
903 
904 			/* Locate any existing buffer for this source pid */
905 			buffer_list = buffer_lists[p.pid % NBUFFER_LISTS];
906 			foreach(cell, buffer_list)
907 			{
908 				save_buffer *buf = (save_buffer *) lfirst(cell);
909 
910 				if (buf->pid == p.pid)
911 				{
912 					existing_slot = buf;
913 					break;
914 				}
915 				if (buf->pid == 0 && free_slot == NULL)
916 					free_slot = buf;
917 			}
918 
919 			if (p.is_last == 'f' || p.is_last == 'F')
920 			{
921 				/*
922 				 * Save a complete non-final chunk in a per-pid buffer
923 				 */
924 				if (existing_slot != NULL)
925 				{
926 					/* Add chunk to data from preceding chunks */
927 					str = &(existing_slot->data);
928 					appendBinaryStringInfo(str,
929 										   cursor + PIPE_HEADER_SIZE,
930 										   p.len);
931 				}
932 				else
933 				{
934 					/* First chunk of message, save in a new buffer */
935 					if (free_slot == NULL)
936 					{
937 						/*
938 						 * Need a free slot, but there isn't one in the list,
939 						 * so create a new one and extend the list with it.
940 						 */
941 						free_slot = palloc(sizeof(save_buffer));
942 						buffer_list = lappend(buffer_list, free_slot);
943 						buffer_lists[p.pid % NBUFFER_LISTS] = buffer_list;
944 					}
945 					free_slot->pid = p.pid;
946 					str = &(free_slot->data);
947 					initStringInfo(str);
948 					appendBinaryStringInfo(str,
949 										   cursor + PIPE_HEADER_SIZE,
950 										   p.len);
951 				}
952 			}
953 			else
954 			{
955 				/*
956 				 * Final chunk --- add it to anything saved for that pid, and
957 				 * either way write the whole thing out.
958 				 */
959 				if (existing_slot != NULL)
960 				{
961 					str = &(existing_slot->data);
962 					appendBinaryStringInfo(str,
963 										   cursor + PIPE_HEADER_SIZE,
964 										   p.len);
965 					write_syslogger_file(str->data, str->len, dest);
966 					/* Mark the buffer unused, and reclaim string storage */
967 					existing_slot->pid = 0;
968 					pfree(str->data);
969 				}
970 				else
971 				{
972 					/* The whole message was one chunk, evidently. */
973 					write_syslogger_file(cursor + PIPE_HEADER_SIZE, p.len,
974 										 dest);
975 				}
976 			}
977 
978 			/* Finished processing this chunk */
979 			cursor += chunklen;
980 			count -= chunklen;
981 		}
982 		else
983 		{
984 			/* Process non-protocol data */
985 
986 			/*
987 			 * Look for the start of a protocol header.  If found, dump data
988 			 * up to there and repeat the loop.  Otherwise, dump it all and
989 			 * fall out of the loop.  (Note: we want to dump it all if at all
990 			 * possible, so as to avoid dividing non-protocol messages across
991 			 * logfiles.  We expect that in many scenarios, a non-protocol
992 			 * message will arrive all in one read(), and we want to respect
993 			 * the read() boundary if possible.)
994 			 */
995 			for (chunklen = 1; chunklen < count; chunklen++)
996 			{
997 				if (cursor[chunklen] == '\0')
998 					break;
999 			}
1000 			/* fall back on the stderr log as the destination */
1001 			write_syslogger_file(cursor, chunklen, LOG_DESTINATION_STDERR);
1002 			cursor += chunklen;
1003 			count -= chunklen;
1004 		}
1005 	}
1006 
1007 	/* We don't have a full chunk, so left-align what remains in the buffer */
1008 	if (count > 0 && cursor != logbuffer)
1009 		memmove(logbuffer, cursor, count);
1010 	*bytes_in_logbuffer = count;
1011 }
1012 
1013 /*
1014  * Force out any buffered data
1015  *
1016  * This is currently used only at syslogger shutdown, but could perhaps be
1017  * useful at other times, so it is careful to leave things in a clean state.
1018  */
1019 static void
flush_pipe_input(char * logbuffer,int * bytes_in_logbuffer)1020 flush_pipe_input(char *logbuffer, int *bytes_in_logbuffer)
1021 {
1022 	int			i;
1023 
1024 	/* Dump any incomplete protocol messages */
1025 	for (i = 0; i < NBUFFER_LISTS; i++)
1026 	{
1027 		List	   *list = buffer_lists[i];
1028 		ListCell   *cell;
1029 
1030 		foreach(cell, list)
1031 		{
1032 			save_buffer *buf = (save_buffer *) lfirst(cell);
1033 
1034 			if (buf->pid != 0)
1035 			{
1036 				StringInfo	str = &(buf->data);
1037 
1038 				write_syslogger_file(str->data, str->len,
1039 									 LOG_DESTINATION_STDERR);
1040 				/* Mark the buffer unused, and reclaim string storage */
1041 				buf->pid = 0;
1042 				pfree(str->data);
1043 			}
1044 		}
1045 	}
1046 
1047 	/*
1048 	 * Force out any remaining pipe data as-is; we don't bother trying to
1049 	 * remove any protocol headers that may exist in it.
1050 	 */
1051 	if (*bytes_in_logbuffer > 0)
1052 		write_syslogger_file(logbuffer, *bytes_in_logbuffer,
1053 							 LOG_DESTINATION_STDERR);
1054 	*bytes_in_logbuffer = 0;
1055 }
1056 
1057 
1058 /* --------------------------------
1059  *		logfile routines
1060  * --------------------------------
1061  */
1062 
1063 /*
1064  * Write text to the currently open logfile
1065  *
1066  * This is exported so that elog.c can call it when am_syslogger is true.
1067  * This allows the syslogger process to record elog messages of its own,
1068  * even though its stderr does not point at the syslog pipe.
1069  */
1070 void
write_syslogger_file(const char * buffer,int count,int destination)1071 write_syslogger_file(const char *buffer, int count, int destination)
1072 {
1073 	int			rc;
1074 	FILE	   *logfile;
1075 
1076 	/*
1077 	 * If we're told to write to csvlogFile, but it's not open, dump the data
1078 	 * to syslogFile (which is always open) instead.  This can happen if CSV
1079 	 * output is enabled after postmaster start and we've been unable to open
1080 	 * csvlogFile.  There are also race conditions during a parameter change
1081 	 * whereby backends might send us CSV output before we open csvlogFile or
1082 	 * after we close it.  Writing CSV-formatted output to the regular log
1083 	 * file isn't great, but it beats dropping log output on the floor.
1084 	 *
1085 	 * Think not to improve this by trying to open csvlogFile on-the-fly.  Any
1086 	 * failure in that would lead to recursion.
1087 	 */
1088 	logfile = (destination == LOG_DESTINATION_CSVLOG &&
1089 			   csvlogFile != NULL) ? csvlogFile : syslogFile;
1090 
1091 	rc = fwrite(buffer, 1, count, logfile);
1092 
1093 	/*
1094 	 * Try to report any failure.  We mustn't use ereport because it would
1095 	 * just recurse right back here, but write_stderr is OK: it will write
1096 	 * either to the postmaster's original stderr, or to /dev/null, but never
1097 	 * to our input pipe which would result in a different sort of looping.
1098 	 */
1099 	if (rc != count)
1100 		write_stderr("could not write to log file: %s\n", strerror(errno));
1101 }
1102 
1103 #ifdef WIN32
1104 
1105 /*
1106  * Worker thread to transfer data from the pipe to the current logfile.
1107  *
1108  * We need this because on Windows, WaitforMultipleObjects does not work on
1109  * unnamed pipes: it always reports "signaled", so the blocking ReadFile won't
1110  * allow for SIGHUP; and select is for sockets only.
1111  */
1112 static unsigned int __stdcall
pipeThread(void * arg)1113 pipeThread(void *arg)
1114 {
1115 	char		logbuffer[READ_BUF_SIZE];
1116 	int			bytes_in_logbuffer = 0;
1117 
1118 	for (;;)
1119 	{
1120 		DWORD		bytesRead;
1121 		BOOL		result;
1122 
1123 		result = ReadFile(syslogPipe[0],
1124 						  logbuffer + bytes_in_logbuffer,
1125 						  sizeof(logbuffer) - bytes_in_logbuffer,
1126 						  &bytesRead, 0);
1127 
1128 		/*
1129 		 * Enter critical section before doing anything that might touch
1130 		 * global state shared by the main thread. Anything that uses
1131 		 * palloc()/pfree() in particular are not safe outside the critical
1132 		 * section.
1133 		 */
1134 		EnterCriticalSection(&sysloggerSection);
1135 		if (!result)
1136 		{
1137 			DWORD		error = GetLastError();
1138 
1139 			if (error == ERROR_HANDLE_EOF ||
1140 				error == ERROR_BROKEN_PIPE)
1141 				break;
1142 			_dosmaperr(error);
1143 			ereport(LOG,
1144 					(errcode_for_file_access(),
1145 					 errmsg("could not read from logger pipe: %m")));
1146 		}
1147 		else if (bytesRead > 0)
1148 		{
1149 			bytes_in_logbuffer += bytesRead;
1150 			process_pipe_input(logbuffer, &bytes_in_logbuffer);
1151 		}
1152 
1153 		/*
1154 		 * If we've filled the current logfile, nudge the main thread to do a
1155 		 * log rotation.
1156 		 */
1157 		if (Log_RotationSize > 0)
1158 		{
1159 			if (ftell(syslogFile) >= Log_RotationSize * 1024L ||
1160 				(csvlogFile != NULL && ftell(csvlogFile) >= Log_RotationSize * 1024L))
1161 				SetLatch(MyLatch);
1162 		}
1163 		LeaveCriticalSection(&sysloggerSection);
1164 	}
1165 
1166 	/* We exit the above loop only upon detecting pipe EOF */
1167 	pipe_eof_seen = true;
1168 
1169 	/* if there's any data left then force it out now */
1170 	flush_pipe_input(logbuffer, &bytes_in_logbuffer);
1171 
1172 	/* set the latch to waken the main thread, which will quit */
1173 	SetLatch(MyLatch);
1174 
1175 	LeaveCriticalSection(&sysloggerSection);
1176 	_endthread();
1177 	return 0;
1178 }
1179 #endif							/* WIN32 */
1180 
1181 /*
1182  * Open a new logfile with proper permissions and buffering options.
1183  *
1184  * If allow_errors is true, we just log any open failure and return NULL
1185  * (with errno still correct for the fopen failure).
1186  * Otherwise, errors are treated as fatal.
1187  */
1188 static FILE *
logfile_open(const char * filename,const char * mode,bool allow_errors)1189 logfile_open(const char *filename, const char *mode, bool allow_errors)
1190 {
1191 	FILE	   *fh;
1192 	mode_t		oumask;
1193 
1194 	/*
1195 	 * Note we do not let Log_file_mode disable IWUSR, since we certainly want
1196 	 * to be able to write the files ourselves.
1197 	 */
1198 	oumask = umask((mode_t) ((~(Log_file_mode | S_IWUSR)) & (S_IRWXU | S_IRWXG | S_IRWXO)));
1199 	fh = fopen(filename, mode);
1200 	umask(oumask);
1201 
1202 	if (fh)
1203 	{
1204 		setvbuf(fh, NULL, PG_IOLBF, 0);
1205 
1206 #ifdef WIN32
1207 		/* use CRLF line endings on Windows */
1208 		_setmode(_fileno(fh), _O_TEXT);
1209 #endif
1210 	}
1211 	else
1212 	{
1213 		int			save_errno = errno;
1214 
1215 		ereport(allow_errors ? LOG : FATAL,
1216 				(errcode_for_file_access(),
1217 				 errmsg("could not open log file \"%s\": %m",
1218 						filename)));
1219 		errno = save_errno;
1220 	}
1221 
1222 	return fh;
1223 }
1224 
1225 /*
1226  * perform logfile rotation
1227  */
1228 static void
logfile_rotate(bool time_based_rotation,int size_rotation_for)1229 logfile_rotate(bool time_based_rotation, int size_rotation_for)
1230 {
1231 	char	   *filename;
1232 	char	   *csvfilename = NULL;
1233 	pg_time_t	fntime;
1234 	FILE	   *fh;
1235 
1236 	rotation_requested = false;
1237 
1238 	/*
1239 	 * When doing a time-based rotation, invent the new logfile name based on
1240 	 * the planned rotation time, not current time, to avoid "slippage" in the
1241 	 * file name when we don't do the rotation immediately.
1242 	 */
1243 	if (time_based_rotation)
1244 		fntime = next_rotation_time;
1245 	else
1246 		fntime = time(NULL);
1247 	filename = logfile_getname(fntime, NULL);
1248 	if (Log_destination & LOG_DESTINATION_CSVLOG)
1249 		csvfilename = logfile_getname(fntime, ".csv");
1250 
1251 	/*
1252 	 * Decide whether to overwrite or append.  We can overwrite if (a)
1253 	 * Log_truncate_on_rotation is set, (b) the rotation was triggered by
1254 	 * elapsed time and not something else, and (c) the computed file name is
1255 	 * different from what we were previously logging into.
1256 	 *
1257 	 * Note: last_file_name should never be NULL here, but if it is, append.
1258 	 */
1259 	if (time_based_rotation || (size_rotation_for & LOG_DESTINATION_STDERR))
1260 	{
1261 		if (Log_truncate_on_rotation && time_based_rotation &&
1262 			last_file_name != NULL &&
1263 			strcmp(filename, last_file_name) != 0)
1264 			fh = logfile_open(filename, "w", true);
1265 		else
1266 			fh = logfile_open(filename, "a", true);
1267 
1268 		if (!fh)
1269 		{
1270 			/*
1271 			 * ENFILE/EMFILE are not too surprising on a busy system; just
1272 			 * keep using the old file till we manage to get a new one.
1273 			 * Otherwise, assume something's wrong with Log_directory and stop
1274 			 * trying to create files.
1275 			 */
1276 			if (errno != ENFILE && errno != EMFILE)
1277 			{
1278 				ereport(LOG,
1279 						(errmsg("disabling automatic rotation (use SIGHUP to re-enable)")));
1280 				rotation_disabled = true;
1281 			}
1282 
1283 			if (filename)
1284 				pfree(filename);
1285 			if (csvfilename)
1286 				pfree(csvfilename);
1287 			return;
1288 		}
1289 
1290 		fclose(syslogFile);
1291 		syslogFile = fh;
1292 
1293 		/* instead of pfree'ing filename, remember it for next time */
1294 		if (last_file_name != NULL)
1295 			pfree(last_file_name);
1296 		last_file_name = filename;
1297 		filename = NULL;
1298 	}
1299 
1300 	/*
1301 	 * Same as above, but for csv file.  Note that if LOG_DESTINATION_CSVLOG
1302 	 * was just turned on, we might have to open csvlogFile here though it was
1303 	 * not open before.  In such a case we'll append not overwrite (since
1304 	 * last_csv_file_name will be NULL); that is consistent with the normal
1305 	 * rules since it's not a time-based rotation.
1306 	 */
1307 	if ((Log_destination & LOG_DESTINATION_CSVLOG) &&
1308 		(csvlogFile == NULL ||
1309 		 time_based_rotation || (size_rotation_for & LOG_DESTINATION_CSVLOG)))
1310 	{
1311 		if (Log_truncate_on_rotation && time_based_rotation &&
1312 			last_csv_file_name != NULL &&
1313 			strcmp(csvfilename, last_csv_file_name) != 0)
1314 			fh = logfile_open(csvfilename, "w", true);
1315 		else
1316 			fh = logfile_open(csvfilename, "a", true);
1317 
1318 		if (!fh)
1319 		{
1320 			/*
1321 			 * ENFILE/EMFILE are not too surprising on a busy system; just
1322 			 * keep using the old file till we manage to get a new one.
1323 			 * Otherwise, assume something's wrong with Log_directory and stop
1324 			 * trying to create files.
1325 			 */
1326 			if (errno != ENFILE && errno != EMFILE)
1327 			{
1328 				ereport(LOG,
1329 						(errmsg("disabling automatic rotation (use SIGHUP to re-enable)")));
1330 				rotation_disabled = true;
1331 			}
1332 
1333 			if (filename)
1334 				pfree(filename);
1335 			if (csvfilename)
1336 				pfree(csvfilename);
1337 			return;
1338 		}
1339 
1340 		if (csvlogFile != NULL)
1341 			fclose(csvlogFile);
1342 		csvlogFile = fh;
1343 
1344 		/* instead of pfree'ing filename, remember it for next time */
1345 		if (last_csv_file_name != NULL)
1346 			pfree(last_csv_file_name);
1347 		last_csv_file_name = csvfilename;
1348 		csvfilename = NULL;
1349 	}
1350 	else if (!(Log_destination & LOG_DESTINATION_CSVLOG) &&
1351 			 csvlogFile != NULL)
1352 	{
1353 		/* CSVLOG was just turned off, so close the old file */
1354 		fclose(csvlogFile);
1355 		csvlogFile = NULL;
1356 		if (last_csv_file_name != NULL)
1357 			pfree(last_csv_file_name);
1358 		last_csv_file_name = NULL;
1359 	}
1360 
1361 	if (filename)
1362 		pfree(filename);
1363 	if (csvfilename)
1364 		pfree(csvfilename);
1365 
1366 	update_metainfo_datafile();
1367 
1368 	set_next_rotation_time();
1369 }
1370 
1371 
1372 /*
1373  * construct logfile name using timestamp information
1374  *
1375  * If suffix isn't NULL, append it to the name, replacing any ".log"
1376  * that may be in the pattern.
1377  *
1378  * Result is palloc'd.
1379  */
1380 static char *
logfile_getname(pg_time_t timestamp,const char * suffix)1381 logfile_getname(pg_time_t timestamp, const char *suffix)
1382 {
1383 	char	   *filename;
1384 	int			len;
1385 
1386 	filename = palloc(MAXPGPATH);
1387 
1388 	snprintf(filename, MAXPGPATH, "%s/", Log_directory);
1389 
1390 	len = strlen(filename);
1391 
1392 	/* treat Log_filename as a strftime pattern */
1393 	pg_strftime(filename + len, MAXPGPATH - len, Log_filename,
1394 				pg_localtime(&timestamp, log_timezone));
1395 
1396 	if (suffix != NULL)
1397 	{
1398 		len = strlen(filename);
1399 		if (len > 4 && (strcmp(filename + (len - 4), ".log") == 0))
1400 			len -= 4;
1401 		strlcpy(filename + len, suffix, MAXPGPATH - len);
1402 	}
1403 
1404 	return filename;
1405 }
1406 
1407 /*
1408  * Determine the next planned rotation time, and store in next_rotation_time.
1409  */
1410 static void
set_next_rotation_time(void)1411 set_next_rotation_time(void)
1412 {
1413 	pg_time_t	now;
1414 	struct pg_tm *tm;
1415 	int			rotinterval;
1416 
1417 	/* nothing to do if time-based rotation is disabled */
1418 	if (Log_RotationAge <= 0)
1419 		return;
1420 
1421 	/*
1422 	 * The requirements here are to choose the next time > now that is a
1423 	 * "multiple" of the log rotation interval.  "Multiple" can be interpreted
1424 	 * fairly loosely.  In this version we align to log_timezone rather than
1425 	 * GMT.
1426 	 */
1427 	rotinterval = Log_RotationAge * SECS_PER_MINUTE;	/* convert to seconds */
1428 	now = (pg_time_t) time(NULL);
1429 	tm = pg_localtime(&now, log_timezone);
1430 	now += tm->tm_gmtoff;
1431 	now -= now % rotinterval;
1432 	now += rotinterval;
1433 	now -= tm->tm_gmtoff;
1434 	next_rotation_time = now;
1435 }
1436 
1437 /*
1438  * Store the name of the file(s) where the log collector, when enabled, writes
1439  * log messages.  Useful for finding the name(s) of the current log file(s)
1440  * when there is time-based logfile rotation.  Filenames are stored in a
1441  * temporary file and which is renamed into the final destination for
1442  * atomicity.
1443  */
1444 static void
update_metainfo_datafile(void)1445 update_metainfo_datafile(void)
1446 {
1447 	FILE	   *fh;
1448 
1449 	if (!(Log_destination & LOG_DESTINATION_STDERR) &&
1450 		!(Log_destination & LOG_DESTINATION_CSVLOG))
1451 	{
1452 		if (unlink(LOG_METAINFO_DATAFILE) < 0 && errno != ENOENT)
1453 			ereport(LOG,
1454 					(errcode_for_file_access(),
1455 					 errmsg("could not remove file \"%s\": %m",
1456 							LOG_METAINFO_DATAFILE)));
1457 		return;
1458 	}
1459 
1460 	if ((fh = logfile_open(LOG_METAINFO_DATAFILE_TMP, "w", true)) == NULL)
1461 	{
1462 		ereport(LOG,
1463 				(errcode_for_file_access(),
1464 				 errmsg("could not open file \"%s\": %m",
1465 						LOG_METAINFO_DATAFILE_TMP)));
1466 		return;
1467 	}
1468 
1469 	if (last_file_name && (Log_destination & LOG_DESTINATION_STDERR))
1470 	{
1471 		if (fprintf(fh, "stderr %s\n", last_file_name) < 0)
1472 		{
1473 			ereport(LOG,
1474 					(errcode_for_file_access(),
1475 					 errmsg("could not write file \"%s\": %m",
1476 							LOG_METAINFO_DATAFILE_TMP)));
1477 			fclose(fh);
1478 			return;
1479 		}
1480 	}
1481 
1482 	if (last_csv_file_name && (Log_destination & LOG_DESTINATION_CSVLOG))
1483 	{
1484 		if (fprintf(fh, "csvlog %s\n", last_csv_file_name) < 0)
1485 		{
1486 			ereport(LOG,
1487 					(errcode_for_file_access(),
1488 					 errmsg("could not write file \"%s\": %m",
1489 							LOG_METAINFO_DATAFILE_TMP)));
1490 			fclose(fh);
1491 			return;
1492 		}
1493 	}
1494 	fclose(fh);
1495 
1496 	if (rename(LOG_METAINFO_DATAFILE_TMP, LOG_METAINFO_DATAFILE) != 0)
1497 		ereport(LOG,
1498 				(errcode_for_file_access(),
1499 				 errmsg("could not rename file \"%s\" to \"%s\": %m",
1500 						LOG_METAINFO_DATAFILE_TMP, LOG_METAINFO_DATAFILE)));
1501 }
1502 
1503 /* --------------------------------
1504  *		signal handler routines
1505  * --------------------------------
1506  */
1507 
1508 /* SIGHUP: set flag to reload config file */
1509 static void
sigHupHandler(SIGNAL_ARGS)1510 sigHupHandler(SIGNAL_ARGS)
1511 {
1512 	int			save_errno = errno;
1513 
1514 	got_SIGHUP = true;
1515 	SetLatch(MyLatch);
1516 
1517 	errno = save_errno;
1518 }
1519 
1520 /* SIGUSR1: set flag to rotate logfile */
1521 static void
sigUsr1Handler(SIGNAL_ARGS)1522 sigUsr1Handler(SIGNAL_ARGS)
1523 {
1524 	int			save_errno = errno;
1525 
1526 	rotation_requested = true;
1527 	SetLatch(MyLatch);
1528 
1529 	errno = save_errno;
1530 }
1531