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