PostgreSQL Source Code  git master
syslogger.h File Reference
#include <limits.h>
Include dependency graph for syslogger.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Data Structures

struct  PipeProtoHeader
 
union  PipeProtoChunk
 

Macros

#define PIPE_CHUNK_SIZE   512
 
#define PIPE_HEADER_SIZE   offsetof(PipeProtoHeader, data)
 
#define PIPE_MAX_PAYLOAD   ((int) (PIPE_CHUNK_SIZE - PIPE_HEADER_SIZE))
 
#define PIPE_PROTO_IS_LAST   0x01 /* last chunk of message? */
 
#define PIPE_PROTO_DEST_STDERR   0x10
 
#define PIPE_PROTO_DEST_CSVLOG   0x20
 
#define PIPE_PROTO_DEST_JSONLOG   0x40
 
#define LOG_METAINFO_DATAFILE   "current_logfiles"
 
#define LOG_METAINFO_DATAFILE_TMP   LOG_METAINFO_DATAFILE ".tmp"
 

Functions

int SysLogger_Start (void)
 
void write_syslogger_file (const char *buffer, int count, int destination)
 
void SysLoggerMain (char *startup_data, size_t startup_data_len) pg_attribute_noreturn()
 
bool CheckLogrotateSignal (void)
 
void RemoveLogrotateSignalFiles (void)
 

Variables

PGDLLIMPORT bool Logging_collector
 
PGDLLIMPORT int Log_RotationAge
 
PGDLLIMPORT int Log_RotationSize
 
PGDLLIMPORT char * Log_directory
 
PGDLLIMPORT char * Log_filename
 
PGDLLIMPORT bool Log_truncate_on_rotation
 
PGDLLIMPORT int Log_file_mode
 
PGDLLIMPORT int syslogPipe [2]
 

Macro Definition Documentation

◆ LOG_METAINFO_DATAFILE

#define LOG_METAINFO_DATAFILE   "current_logfiles"

Definition at line 102 of file syslogger.h.

◆ LOG_METAINFO_DATAFILE_TMP

#define LOG_METAINFO_DATAFILE_TMP   LOG_METAINFO_DATAFILE ".tmp"

Definition at line 103 of file syslogger.h.

◆ PIPE_CHUNK_SIZE

#define PIPE_CHUNK_SIZE   512

Definition at line 41 of file syslogger.h.

◆ PIPE_HEADER_SIZE

#define PIPE_HEADER_SIZE   offsetof(PipeProtoHeader, data)

Definition at line 59 of file syslogger.h.

◆ PIPE_MAX_PAYLOAD

#define PIPE_MAX_PAYLOAD   ((int) (PIPE_CHUNK_SIZE - PIPE_HEADER_SIZE))

Definition at line 60 of file syslogger.h.

◆ PIPE_PROTO_DEST_CSVLOG

#define PIPE_PROTO_DEST_CSVLOG   0x20

Definition at line 66 of file syslogger.h.

◆ PIPE_PROTO_DEST_JSONLOG

#define PIPE_PROTO_DEST_JSONLOG   0x40

Definition at line 67 of file syslogger.h.

◆ PIPE_PROTO_DEST_STDERR

#define PIPE_PROTO_DEST_STDERR   0x10

Definition at line 65 of file syslogger.h.

◆ PIPE_PROTO_IS_LAST

#define PIPE_PROTO_IS_LAST   0x01 /* last chunk of message? */

Definition at line 63 of file syslogger.h.

Function Documentation

◆ CheckLogrotateSignal()

bool CheckLogrotateSignal ( void  )

Definition at line 1571 of file syslogger.c.

1572 {
1573  struct stat stat_buf;
1574 
1575  if (stat(LOGROTATE_SIGNAL_FILE, &stat_buf) == 0)
1576  return true;
1577 
1578  return false;
1579 }
#define LOGROTATE_SIGNAL_FILE
Definition: syslogger.c:63
#define stat
Definition: win32_port.h:284

References LOGROTATE_SIGNAL_FILE, and stat.

Referenced by process_pm_pmsignal().

◆ RemoveLogrotateSignalFiles()

void RemoveLogrotateSignalFiles ( void  )

Definition at line 1585 of file syslogger.c.

1586 {
1587  unlink(LOGROTATE_SIGNAL_FILE);
1588 }

References LOGROTATE_SIGNAL_FILE.

Referenced by PostmasterMain(), and process_pm_pmsignal().

◆ SysLogger_Start()

int SysLogger_Start ( void  )

Definition at line 593 of file syslogger.c.

594 {
595  pid_t sysloggerPid;
596  char *filename;
597 #ifdef EXEC_BACKEND
598  SysloggerStartupData startup_data;
599 #endif /* EXEC_BACKEND */
600 
601  if (!Logging_collector)
602  return 0;
603 
604  /*
605  * If first time through, create the pipe which will receive stderr
606  * output.
607  *
608  * If the syslogger crashes and needs to be restarted, we continue to use
609  * the same pipe (indeed must do so, since extant backends will be writing
610  * into that pipe).
611  *
612  * This means the postmaster must continue to hold the read end of the
613  * pipe open, so we can pass it down to the reincarnated syslogger. This
614  * is a bit klugy but we have little choice.
615  *
616  * Also note that we don't bother counting the pipe FDs by calling
617  * Reserve/ReleaseExternalFD. There's no real need to account for them
618  * accurately in the postmaster or syslogger process, and both ends of the
619  * pipe will wind up closed in all other postmaster children.
620  */
621 #ifndef WIN32
622  if (syslogPipe[0] < 0)
623  {
624  if (pipe(syslogPipe) < 0)
625  ereport(FATAL,
627  errmsg("could not create pipe for syslog: %m")));
628  }
629 #else
630  if (!syslogPipe[0])
631  {
632  SECURITY_ATTRIBUTES sa;
633 
634  memset(&sa, 0, sizeof(SECURITY_ATTRIBUTES));
635  sa.nLength = sizeof(SECURITY_ATTRIBUTES);
636  sa.bInheritHandle = TRUE;
637 
638  if (!CreatePipe(&syslogPipe[0], &syslogPipe[1], &sa, 32768))
639  ereport(FATAL,
641  errmsg("could not create pipe for syslog: %m")));
642  }
643 #endif
644 
645  /*
646  * Create log directory if not present; ignore errors
647  */
649 
650  /*
651  * The initial logfile is created right in the postmaster, to verify that
652  * the Log_directory is writable. We save the reference time so that the
653  * syslogger child process can recompute this file name.
654  *
655  * It might look a bit strange to re-do this during a syslogger restart,
656  * but we must do so since the postmaster closed syslogFile after the
657  * previous fork (and remembering that old file wouldn't be right anyway).
658  * Note we always append here, we won't overwrite any existing file. This
659  * is consistent with the normal rules, because by definition this is not
660  * a time-based rotation.
661  */
662  first_syslogger_file_time = time(NULL);
663 
665 
666  syslogFile = logfile_open(filename, "a", false);
667 
668  pfree(filename);
669 
670  /*
671  * Likewise for the initial CSV log file, if that's enabled. (Note that
672  * we open syslogFile even when only CSV output is nominally enabled,
673  * since some code paths will write to syslogFile anyway.)
674  */
676  {
678 
679  csvlogFile = logfile_open(filename, "a", false);
680 
681  pfree(filename);
682  }
683 
684  /*
685  * Likewise for the initial JSON log file, if that's enabled. (Note that
686  * we open syslogFile even when only JSON output is nominally enabled,
687  * since some code paths will write to syslogFile anyway.)
688  */
690  {
692 
693  jsonlogFile = logfile_open(filename, "a", false);
694 
695  pfree(filename);
696  }
697 
698 #ifdef EXEC_BACKEND
699  startup_data.syslogFile = syslogger_fdget(syslogFile);
700  startup_data.csvlogFile = syslogger_fdget(csvlogFile);
701  startup_data.jsonlogFile = syslogger_fdget(jsonlogFile);
702  sysloggerPid = postmaster_child_launch(B_LOGGER, (char *) &startup_data, sizeof(startup_data), NULL);
703 #else
704  sysloggerPid = postmaster_child_launch(B_LOGGER, NULL, 0, NULL);
705 #endif /* EXEC_BACKEND */
706 
707  if (sysloggerPid == -1)
708  {
709  ereport(LOG,
710  (errmsg("could not fork system logger: %m")));
711  return 0;
712  }
713 
714  /* success, in postmaster */
715 
716  /* now we redirect stderr, if not done already */
717  if (!redirection_done)
718  {
719 #ifdef WIN32
720  int fd;
721 #endif
722 
723  /*
724  * Leave a breadcrumb trail when redirecting, in case the user forgets
725  * that redirection is active and looks only at the original stderr
726  * target file.
727  */
728  ereport(LOG,
729  (errmsg("redirecting log output to logging collector process"),
730  errhint("Future log output will appear in directory \"%s\".",
731  Log_directory)));
732 
733 #ifndef WIN32
734  fflush(stdout);
735  if (dup2(syslogPipe[1], STDOUT_FILENO) < 0)
736  ereport(FATAL,
738  errmsg("could not redirect stdout: %m")));
739  fflush(stderr);
740  if (dup2(syslogPipe[1], STDERR_FILENO) < 0)
741  ereport(FATAL,
743  errmsg("could not redirect stderr: %m")));
744  /* Now we are done with the write end of the pipe. */
745  close(syslogPipe[1]);
746  syslogPipe[1] = -1;
747 #else
748 
749  /*
750  * open the pipe in binary mode and make sure stderr is binary after
751  * it's been dup'ed into, to avoid disturbing the pipe chunking
752  * protocol.
753  */
754  fflush(stderr);
755  fd = _open_osfhandle((intptr_t) syslogPipe[1],
756  _O_APPEND | _O_BINARY);
757  if (dup2(fd, STDERR_FILENO) < 0)
758  ereport(FATAL,
760  errmsg("could not redirect stderr: %m")));
761  close(fd);
762  _setmode(STDERR_FILENO, _O_BINARY);
763 
764  /*
765  * Now we are done with the write end of the pipe. CloseHandle() must
766  * not be called because the preceding close() closes the underlying
767  * handle.
768  */
769  syslogPipe[1] = 0;
770 #endif
771  redirection_done = true;
772  }
773 
774  /* postmaster will never write the file(s); close 'em */
775  fclose(syslogFile);
776  syslogFile = NULL;
777  if (csvlogFile != NULL)
778  {
779  fclose(csvlogFile);
780  csvlogFile = NULL;
781  }
782  if (jsonlogFile != NULL)
783  {
784  fclose(jsonlogFile);
785  jsonlogFile = NULL;
786  }
787  return (int) sysloggerPid;
788 }
int errcode_for_socket_access(void)
Definition: elog.c:953
int errcode_for_file_access(void)
Definition: elog.c:876
int Log_destination
Definition: elog.c:110
int errhint(const char *fmt,...)
Definition: elog.c:1317
int errmsg(const char *fmt,...)
Definition: elog.c:1070
#define LOG
Definition: elog.h:31
#define FATAL
Definition: elog.h:41
#define LOG_DESTINATION_JSONLOG
Definition: elog.h:496
#define ereport(elevel,...)
Definition: elog.h:149
#define LOG_DESTINATION_CSVLOG
Definition: elog.h:495
int MakePGDirectory(const char *directoryName)
Definition: fd.c:3913
#define close(a)
Definition: win32.h:12
pid_t postmaster_child_launch(BackendType child_type, char *startup_data, size_t startup_data_len, ClientSocket *client_sock)
static void const char fflush(stdout)
void pfree(void *pointer)
Definition: mcxt.c:1521
@ B_LOGGER
Definition: miscadmin.h:367
static char * filename
Definition: pg_dumpall.c:119
bool redirection_done
Definition: postmaster.c:353
static int fd(const char *x, int i)
Definition: preproc-init.c:105
char * Log_directory
Definition: syslogger.c:73
static char * logfile_getname(pg_time_t timestamp, const char *suffix)
Definition: syslogger.c:1409
static FILE * logfile_open(const char *filename, const char *mode, bool allow_errors)
Definition: syslogger.c:1216
NON_EXEC_STATIC pg_time_t first_syslogger_file_time
Definition: syslogger.c:87
int syslogPipe[2]
Definition: syslogger.c:114
static FILE * syslogFile
Definition: syslogger.c:84
bool Logging_collector
Definition: syslogger.c:70
static FILE * csvlogFile
Definition: syslogger.c:85
static FILE * jsonlogFile
Definition: syslogger.c:86
#define STDOUT_FILENO
Definition: unistd.h:8
#define STDERR_FILENO
Definition: unistd.h:9

References B_LOGGER, close, csvlogFile, SysloggerStartupData::csvlogFile, ereport, errcode_for_file_access(), errcode_for_socket_access(), errhint(), errmsg(), FATAL, fd(), fflush(), filename, first_syslogger_file_time, jsonlogFile, SysloggerStartupData::jsonlogFile, LOG, Log_destination, LOG_DESTINATION_CSVLOG, LOG_DESTINATION_JSONLOG, Log_directory, logfile_getname(), logfile_open(), Logging_collector, MakePGDirectory(), pfree(), postmaster_child_launch(), redirection_done, STDERR_FILENO, generate_unaccent_rules::stdout, STDOUT_FILENO, syslogFile, SysloggerStartupData::syslogFile, and syslogPipe.

Referenced by PostmasterMain(), process_pm_child_exit(), and ServerLoop().

◆ SysLoggerMain()

void SysLoggerMain ( char *  startup_data,
size_t  startup_data_len 
)

Definition at line 165 of file syslogger.c.

166 {
167 #ifndef WIN32
168  char logbuffer[READ_BUF_SIZE];
169  int bytes_in_logbuffer = 0;
170 #endif
171  char *currentLogDir;
172  char *currentLogFilename;
173  int currentLogRotationAge;
174  pg_time_t now;
175  WaitEventSet *wes;
176 
177  /*
178  * Re-open the error output files that were opened by SysLogger_Start().
179  *
180  * We expect this will always succeed, which is too optimistic, but if it
181  * fails there's not a lot we can do to report the problem anyway. As
182  * coded, we'll just crash on a null pointer dereference after failure...
183  */
184 #ifdef EXEC_BACKEND
185  {
186  SysloggerStartupData *slsdata = (SysloggerStartupData *) startup_data;
187 
188  Assert(startup_data_len == sizeof(*slsdata));
189  syslogFile = syslogger_fdopen(slsdata->syslogFile);
190  csvlogFile = syslogger_fdopen(slsdata->csvlogFile);
191  jsonlogFile = syslogger_fdopen(slsdata->jsonlogFile);
192  }
193 #else
194  Assert(startup_data_len == 0);
195 #endif
196 
197  /*
198  * Now that we're done reading the startup data, release postmaster's
199  * working memory context.
200  */
201  if (PostmasterContext)
202  {
204  PostmasterContext = NULL;
205  }
206 
207  now = MyStartTime;
208 
210  init_ps_display(NULL);
211 
212  /*
213  * If we restarted, our stderr is already redirected into our own input
214  * pipe. This is of course pretty useless, not to mention that it
215  * interferes with detecting pipe EOF. Point stderr to /dev/null. This
216  * assumes that all interesting messages generated in the syslogger will
217  * come through elog.c and will be sent to write_syslogger_file.
218  */
219  if (redirection_done)
220  {
221  int fd = open(DEVNULL, O_WRONLY, 0);
222 
223  /*
224  * The closes might look redundant, but they are not: we want to be
225  * darn sure the pipe gets closed even if the open failed. We can
226  * survive running with stderr pointing nowhere, but we can't afford
227  * to have extra pipe input descriptors hanging around.
228  *
229  * As we're just trying to reset these to go to DEVNULL, there's not
230  * much point in checking for failure from the close/dup2 calls here,
231  * if they fail then presumably the file descriptors are closed and
232  * any writes will go into the bitbucket anyway.
233  */
236  if (fd != -1)
237  {
238  (void) dup2(fd, STDOUT_FILENO);
239  (void) dup2(fd, STDERR_FILENO);
240  close(fd);
241  }
242  }
243 
244  /*
245  * Syslogger's own stderr can't be the syslogPipe, so set it back to text
246  * mode if we didn't just close it. (It was set to binary in
247  * SubPostmasterMain).
248  */
249 #ifdef WIN32
250  else
251  _setmode(STDERR_FILENO, _O_TEXT);
252 #endif
253 
254  /*
255  * Also close our copy of the write end of the pipe. This is needed to
256  * ensure we can detect pipe EOF correctly. (But note that in the restart
257  * case, the postmaster already did this.)
258  */
259 #ifndef WIN32
260  if (syslogPipe[1] >= 0)
261  close(syslogPipe[1]);
262  syslogPipe[1] = -1;
263 #else
264  if (syslogPipe[1])
265  CloseHandle(syslogPipe[1]);
266  syslogPipe[1] = 0;
267 #endif
268 
269  /*
270  * Properly accept or ignore signals the postmaster might send us
271  *
272  * Note: we ignore all termination signals, and instead exit only when all
273  * upstream processes are gone, to ensure we don't miss any dying gasps of
274  * broken backends...
275  */
276 
277  pqsignal(SIGHUP, SignalHandlerForConfigReload); /* set flag to read config
278  * file */
279  pqsignal(SIGINT, SIG_IGN);
280  pqsignal(SIGTERM, SIG_IGN);
284  pqsignal(SIGUSR1, sigUsr1Handler); /* request log rotation */
286 
287  /*
288  * Reset some signals that are accepted by postmaster but not here
289  */
291 
292  sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
293 
294 #ifdef WIN32
295  /* Fire up separate data transfer thread */
296  InitializeCriticalSection(&sysloggerSection);
297  EnterCriticalSection(&sysloggerSection);
298 
299  threadHandle = (HANDLE) _beginthreadex(NULL, 0, pipeThread, NULL, 0, NULL);
300  if (threadHandle == 0)
301  elog(FATAL, "could not create syslogger data transfer thread: %m");
302 #endif /* WIN32 */
303 
304  /*
305  * Remember active logfiles' name(s). We recompute 'em from the reference
306  * time because passing down just the pg_time_t is a lot cheaper than
307  * passing a whole file path in the EXEC_BACKEND case.
308  */
310  if (csvlogFile != NULL)
312  if (jsonlogFile != NULL)
314 
315  /* remember active logfile parameters */
316  currentLogDir = pstrdup(Log_directory);
317  currentLogFilename = pstrdup(Log_filename);
318  currentLogRotationAge = Log_RotationAge;
319  /* set next planned rotation time */
322 
323  /*
324  * Reset whereToSendOutput, as the postmaster will do (but hasn't yet, at
325  * the point where we forked). This prevents duplicate output of messages
326  * from syslogger itself.
327  */
329 
330  /*
331  * Set up a reusable WaitEventSet object we'll use to wait for our latch,
332  * and (except on Windows) our socket.
333  *
334  * Unlike all other postmaster child processes, we'll ignore postmaster
335  * death because we want to collect final log output from all backends and
336  * then exit last. We'll do that by running until we see EOF on the
337  * syslog pipe, which implies that all other backends have exited
338  * (including the postmaster).
339  */
340  wes = CreateWaitEventSet(NULL, 2);
342 #ifndef WIN32
343  AddWaitEventToSet(wes, WL_SOCKET_READABLE, syslogPipe[0], NULL, NULL);
344 #endif
345 
346  /* main worker loop */
347  for (;;)
348  {
349  bool time_based_rotation = false;
350  int size_rotation_for = 0;
351  long cur_timeout;
352  WaitEvent event;
353 
354 #ifndef WIN32
355  int rc;
356 #endif
357 
358  /* Clear any already-pending wakeups */
360 
361  /*
362  * Process any requests or signals received recently.
363  */
365  {
366  ConfigReloadPending = false;
368 
369  /*
370  * Check if the log directory or filename pattern changed in
371  * postgresql.conf. If so, force rotation to make sure we're
372  * writing the logfiles in the right place.
373  */
374  if (strcmp(Log_directory, currentLogDir) != 0)
375  {
376  pfree(currentLogDir);
377  currentLogDir = pstrdup(Log_directory);
378  rotation_requested = true;
379 
380  /*
381  * Also, create new directory if not present; ignore errors
382  */
384  }
385  if (strcmp(Log_filename, currentLogFilename) != 0)
386  {
387  pfree(currentLogFilename);
388  currentLogFilename = pstrdup(Log_filename);
389  rotation_requested = true;
390  }
391 
392  /*
393  * Force a rotation if CSVLOG output was just turned on or off and
394  * we need to open or close csvlogFile accordingly.
395  */
396  if (((Log_destination & LOG_DESTINATION_CSVLOG) != 0) !=
397  (csvlogFile != NULL))
398  rotation_requested = true;
399 
400  /*
401  * Force a rotation if JSONLOG output was just turned on or off
402  * and we need to open or close jsonlogFile accordingly.
403  */
404  if (((Log_destination & LOG_DESTINATION_JSONLOG) != 0) !=
405  (jsonlogFile != NULL))
406  rotation_requested = true;
407 
408  /*
409  * If rotation time parameter changed, reset next rotation time,
410  * but don't immediately force a rotation.
411  */
412  if (currentLogRotationAge != Log_RotationAge)
413  {
414  currentLogRotationAge = Log_RotationAge;
416  }
417 
418  /*
419  * If we had a rotation-disabling failure, re-enable rotation
420  * attempts after SIGHUP, and force one immediately.
421  */
422  if (rotation_disabled)
423  {
424  rotation_disabled = false;
425  rotation_requested = true;
426  }
427 
428  /*
429  * Force rewriting last log filename when reloading configuration.
430  * Even if rotation_requested is false, log_destination may have
431  * been changed and we don't want to wait the next file rotation.
432  */
434  }
435 
437  {
438  /* Do a logfile rotation if it's time */
439  now = (pg_time_t) time(NULL);
440  if (now >= next_rotation_time)
441  rotation_requested = time_based_rotation = true;
442  }
443 
445  {
446  /* Do a rotation if file is too big */
447  if (ftell(syslogFile) >= Log_RotationSize * 1024L)
448  {
449  rotation_requested = true;
450  size_rotation_for |= LOG_DESTINATION_STDERR;
451  }
452  if (csvlogFile != NULL &&
453  ftell(csvlogFile) >= Log_RotationSize * 1024L)
454  {
455  rotation_requested = true;
456  size_rotation_for |= LOG_DESTINATION_CSVLOG;
457  }
458  if (jsonlogFile != NULL &&
459  ftell(jsonlogFile) >= Log_RotationSize * 1024L)
460  {
461  rotation_requested = true;
462  size_rotation_for |= LOG_DESTINATION_JSONLOG;
463  }
464  }
465 
466  if (rotation_requested)
467  {
468  /*
469  * Force rotation when both values are zero. It means the request
470  * was sent by pg_rotate_logfile() or "pg_ctl logrotate".
471  */
472  if (!time_based_rotation && size_rotation_for == 0)
473  size_rotation_for = LOG_DESTINATION_STDERR |
476  logfile_rotate(time_based_rotation, size_rotation_for);
477  }
478 
479  /*
480  * Calculate time till next time-based rotation, so that we don't
481  * sleep longer than that. We assume the value of "now" obtained
482  * above is still close enough. Note we can't make this calculation
483  * until after calling logfile_rotate(), since it will advance
484  * next_rotation_time.
485  *
486  * Also note that we need to beware of overflow in calculation of the
487  * timeout: with large settings of Log_RotationAge, next_rotation_time
488  * could be more than INT_MAX msec in the future. In that case we'll
489  * wait no more than INT_MAX msec, and try again.
490  */
492  {
493  pg_time_t delay;
494 
495  delay = next_rotation_time - now;
496  if (delay > 0)
497  {
498  if (delay > INT_MAX / 1000)
499  delay = INT_MAX / 1000;
500  cur_timeout = delay * 1000L; /* msec */
501  }
502  else
503  cur_timeout = 0;
504  }
505  else
506  cur_timeout = -1L;
507 
508  /*
509  * Sleep until there's something to do
510  */
511 #ifndef WIN32
512  rc = WaitEventSetWait(wes, cur_timeout, &event, 1,
513  WAIT_EVENT_SYSLOGGER_MAIN);
514 
515  if (rc == 1 && event.events == WL_SOCKET_READABLE)
516  {
517  int bytesRead;
518 
519  bytesRead = read(syslogPipe[0],
520  logbuffer + bytes_in_logbuffer,
521  sizeof(logbuffer) - bytes_in_logbuffer);
522  if (bytesRead < 0)
523  {
524  if (errno != EINTR)
525  ereport(LOG,
527  errmsg("could not read from logger pipe: %m")));
528  }
529  else if (bytesRead > 0)
530  {
531  bytes_in_logbuffer += bytesRead;
532  process_pipe_input(logbuffer, &bytes_in_logbuffer);
533  continue;
534  }
535  else
536  {
537  /*
538  * Zero bytes read when select() is saying read-ready means
539  * EOF on the pipe: that is, there are no longer any processes
540  * with the pipe write end open. Therefore, the postmaster
541  * and all backends are shut down, and we are done.
542  */
543  pipe_eof_seen = true;
544 
545  /* if there's any data left then force it out now */
546  flush_pipe_input(logbuffer, &bytes_in_logbuffer);
547  }
548  }
549 #else /* WIN32 */
550 
551  /*
552  * On Windows we leave it to a separate thread to transfer data and
553  * detect pipe EOF. The main thread just wakes up to handle SIGHUP
554  * and rotation conditions.
555  *
556  * Server code isn't generally thread-safe, so we ensure that only one
557  * of the threads is active at a time by entering the critical section
558  * whenever we're not sleeping.
559  */
560  LeaveCriticalSection(&sysloggerSection);
561 
562  (void) WaitEventSetWait(wes, cur_timeout, &event, 1,
563  WAIT_EVENT_SYSLOGGER_MAIN);
564 
565  EnterCriticalSection(&sysloggerSection);
566 #endif /* WIN32 */
567 
568  if (pipe_eof_seen)
569  {
570  /*
571  * seeing this message on the real stderr is annoying - so we make
572  * it DEBUG1 to suppress in normal use.
573  */
574  ereport(DEBUG1,
575  (errmsg_internal("logger shutting down")));
576 
577  /*
578  * Normal exit from the syslogger is here. Note that we
579  * deliberately do not close syslogFile before exiting; this is to
580  * allow for the possibility of elog messages being generated
581  * inside proc_exit. Regular exit() will take care of flushing
582  * and closing stdio channels.
583  */
584  proc_exit(0);
585  }
586  }
587 }
sigset_t UnBlockSig
Definition: pqsignal.c:22
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1619
#define Assert(condition)
Definition: c.h:858
@ DestNone
Definition: dest.h:87
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1157
#define DEBUG1
Definition: elog.h:30
#define elog(elevel,...)
Definition: elog.h:224
#define LOG_DESTINATION_STDERR
Definition: elog.h:492
pg_time_t MyStartTime
Definition: globals.c:47
struct Latch * MyLatch
Definition: globals.c:61
@ PGC_SIGHUP
Definition: guc.h:71
void ProcessConfigFile(GucContext context)
#define read(a, b, c)
Definition: win32.h:13
volatile sig_atomic_t ConfigReloadPending
Definition: interrupt.c:27
void SignalHandlerForConfigReload(SIGNAL_ARGS)
Definition: interrupt.c:61
void proc_exit(int code)
Definition: ipc.c:104
WaitEventSet * CreateWaitEventSet(ResourceOwner resowner, int nevents)
Definition: latch.c:751
int AddWaitEventToSet(WaitEventSet *set, uint32 events, pgsocket fd, Latch *latch, void *user_data)
Definition: latch.c:963
int WaitEventSetWait(WaitEventSet *set, long timeout, WaitEvent *occurred_events, int nevents, uint32 wait_event_info)
Definition: latch.c:1424
void ResetLatch(Latch *latch)
Definition: latch.c:724
#define WL_SOCKET_READABLE
Definition: latch.h:128
#define WL_LATCH_SET
Definition: latch.h:127
char * pstrdup(const char *in)
Definition: mcxt.c:1696
MemoryContext PostmasterContext
Definition: mcxt.c:151
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:454
BackendType MyBackendType
Definition: miscinit.c:63
int64 pg_time_t
Definition: pgtime.h:23
pqsigfunc pqsignal(int signo, pqsigfunc func)
#define DEVNULL
Definition: port.h:160
#define PGINVALID_SOCKET
Definition: port.h:31
CommandDest whereToSendOutput
Definition: postgres.c:90
void init_ps_display(const char *fixed_part)
Definition: ps_status.c:267
uint32 events
Definition: latch.h:155
static bool rotation_disabled
Definition: syslogger.c:83
static void logfile_rotate(bool time_based_rotation, int size_rotation_for)
Definition: syslogger.c:1360
static bool pipe_eof_seen
Definition: syslogger.c:82
#define READ_BUF_SIZE
Definition: syslogger.c:60
static void update_metainfo_datafile(void)
Definition: syslogger.c:1474
static char * last_csv_file_name
Definition: syslogger.c:89
int Log_RotationAge
Definition: syslogger.c:71
static void process_pipe_input(char *logbuffer, int *bytes_in_logbuffer)
Definition: syslogger.c:878
char * Log_filename
Definition: syslogger.c:74
static pg_time_t next_rotation_time
Definition: syslogger.c:81
static volatile sig_atomic_t rotation_requested
Definition: syslogger.c:127
int Log_RotationSize
Definition: syslogger.c:72
static void sigUsr1Handler(SIGNAL_ARGS)
Definition: syslogger.c:1592
static void set_next_rotation_time(void)
Definition: syslogger.c:1439
static void flush_pipe_input(char *logbuffer, int *bytes_in_logbuffer)
Definition: syslogger.c:1041
static char * last_json_file_name
Definition: syslogger.c:90
static char * last_sys_file_name
Definition: syslogger.c:88
#define SIGCHLD
Definition: win32_port.h:178
#define SIGHUP
Definition: win32_port.h:168
#define SIG_DFL
Definition: win32_port.h:163
#define EINTR
Definition: win32_port.h:374
#define SIGPIPE
Definition: win32_port.h:173
#define SIGQUIT
Definition: win32_port.h:169
#define SIGUSR1
Definition: win32_port.h:180
#define SIGALRM
Definition: win32_port.h:174
#define SIGUSR2
Definition: win32_port.h:181
#define SIG_IGN
Definition: win32_port.h:165

References AddWaitEventToSet(), Assert, B_LOGGER, close, ConfigReloadPending, CreateWaitEventSet(), csvlogFile, SysloggerStartupData::csvlogFile, DEBUG1, DestNone, DEVNULL, EINTR, elog, ereport, errcode_for_socket_access(), errmsg(), errmsg_internal(), WaitEvent::events, FATAL, fd(), first_syslogger_file_time, flush_pipe_input(), init_ps_display(), jsonlogFile, SysloggerStartupData::jsonlogFile, last_csv_file_name, last_json_file_name, last_sys_file_name, LOG, Log_destination, LOG_DESTINATION_CSVLOG, LOG_DESTINATION_JSONLOG, LOG_DESTINATION_STDERR, Log_directory, Log_filename, Log_RotationAge, Log_RotationSize, logfile_getname(), logfile_rotate(), MakePGDirectory(), MemoryContextDelete(), MyBackendType, MyLatch, MyStartTime, next_rotation_time, now(), pfree(), PGC_SIGHUP, PGINVALID_SOCKET, pipe_eof_seen, PostmasterContext, pqsignal(), proc_exit(), process_pipe_input(), ProcessConfigFile(), pstrdup(), read, READ_BUF_SIZE, redirection_done, ResetLatch(), rotation_disabled, rotation_requested, set_next_rotation_time(), SIG_DFL, SIG_IGN, SIGALRM, SIGCHLD, SIGHUP, SignalHandlerForConfigReload(), SIGPIPE, SIGQUIT, SIGUSR1, sigUsr1Handler(), SIGUSR2, STDERR_FILENO, STDOUT_FILENO, syslogFile, SysloggerStartupData::syslogFile, syslogPipe, UnBlockSig, update_metainfo_datafile(), WaitEventSetWait(), whereToSendOutput, WL_LATCH_SET, and WL_SOCKET_READABLE.

◆ write_syslogger_file()

void write_syslogger_file ( const char *  buffer,
int  count,
int  destination 
)

Definition at line 1092 of file syslogger.c.

1093 {
1094  int rc;
1095  FILE *logfile;
1096 
1097  /*
1098  * If we're told to write to a structured log file, but it's not open,
1099  * dump the data to syslogFile (which is always open) instead. This can
1100  * happen if structured output is enabled after postmaster start and we've
1101  * been unable to open logFile. There are also race conditions during a
1102  * parameter change whereby backends might send us structured output
1103  * before we open the logFile or after we close it. Writing formatted
1104  * output to the regular log file isn't great, but it beats dropping log
1105  * output on the floor.
1106  *
1107  * Think not to improve this by trying to open logFile on-the-fly. Any
1108  * failure in that would lead to recursion.
1109  */
1110  if ((destination & LOG_DESTINATION_CSVLOG) && csvlogFile != NULL)
1111  logfile = csvlogFile;
1112  else if ((destination & LOG_DESTINATION_JSONLOG) && jsonlogFile != NULL)
1113  logfile = jsonlogFile;
1114  else
1115  logfile = syslogFile;
1116 
1117  rc = fwrite(buffer, 1, count, logfile);
1118 
1119  /*
1120  * Try to report any failure. We mustn't use ereport because it would
1121  * just recurse right back here, but write_stderr is OK: it will write
1122  * either to the postmaster's original stderr, or to /dev/null, but never
1123  * to our input pipe which would result in a different sort of looping.
1124  */
1125  if (rc != count)
1126  write_stderr("could not write to log file: %m\n");
1127 }
#define write_stderr(str)
Definition: parallel.c:184
static FILE * logfile
Definition: pg_regress.c:127

References csvlogFile, jsonlogFile, LOG_DESTINATION_CSVLOG, LOG_DESTINATION_JSONLOG, logfile, syslogFile, and write_stderr.

Referenced by flush_pipe_input(), process_pipe_input(), send_message_to_server_log(), write_csvlog(), and write_jsonlog().

Variable Documentation

◆ Log_directory

PGDLLIMPORT char* Log_directory
extern

◆ Log_file_mode

PGDLLIMPORT int Log_file_mode
extern

Definition at line 76 of file syslogger.c.

Referenced by logfile_open(), and show_log_file_mode().

◆ Log_filename

PGDLLIMPORT char* Log_filename
extern

Definition at line 74 of file syslogger.c.

Referenced by logfile_getname(), and SysLoggerMain().

◆ Log_RotationAge

PGDLLIMPORT int Log_RotationAge
extern

Definition at line 71 of file syslogger.c.

Referenced by set_next_rotation_time(), and SysLoggerMain().

◆ Log_RotationSize

PGDLLIMPORT int Log_RotationSize
extern

Definition at line 72 of file syslogger.c.

Referenced by SysLoggerMain().

◆ Log_truncate_on_rotation

PGDLLIMPORT bool Log_truncate_on_rotation
extern

Definition at line 75 of file syslogger.c.

Referenced by logfile_rotate_dest().

◆ Logging_collector

PGDLLIMPORT bool Logging_collector
extern

Definition at line 70 of file syslogger.c.

Referenced by pg_rotate_logfile(), ServerLoop(), and SysLogger_Start().

◆ syslogPipe

PGDLLIMPORT int syslogPipe[2]
extern

Definition at line 114 of file syslogger.c.

Referenced by ClosePostmasterPorts(), SysLogger_Start(), and SysLoggerMain().