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