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 98 of file syslogger.h.

◆ LOG_METAINFO_DATAFILE_TMP

#define LOG_METAINFO_DATAFILE_TMP   LOG_METAINFO_DATAFILE ".tmp"

Definition at line 99 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 1573 of file syslogger.c.

1574 {
1575  struct stat stat_buf;
1576 
1577  if (stat(LOGROTATE_SIGNAL_FILE, &stat_buf) == 0)
1578  return true;
1579 
1580  return false;
1581 }
#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 1587 of file syslogger.c.

1588 {
1589  unlink(LOGROTATE_SIGNAL_FILE);
1590 }

References LOGROTATE_SIGNAL_FILE.

Referenced by PostmasterMain(), and process_pm_pmsignal().

◆ SysLogger_Start()

int SysLogger_Start ( void  )

Definition at line 595 of file syslogger.c.

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

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

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

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