PostgreSQL Source Code  git master
syslogger.c File Reference
#include "postgres.h"
#include <fcntl.h>
#include <limits.h>
#include <signal.h>
#include <time.h>
#include <unistd.h>
#include <sys/stat.h>
#include "common/file_perm.h"
#include "lib/stringinfo.h"
#include "libpq/pqsignal.h"
#include "miscadmin.h"
#include "nodes/pg_list.h"
#include "pgstat.h"
#include "pgtime.h"
#include "postmaster/fork_process.h"
#include "postmaster/postmaster.h"
#include "postmaster/syslogger.h"
#include "storage/dsm.h"
#include "storage/fd.h"
#include "storage/ipc.h"
#include "storage/latch.h"
#include "storage/pg_shmem.h"
#include "tcop/tcopprot.h"
#include "utils/guc.h"
#include "utils/ps_status.h"
#include "utils/timestamp.h"
Include dependency graph for syslogger.c:

Go to the source code of this file.

Data Structures

struct  save_buffer
 

Macros

#define READ_BUF_SIZE   (2 * PIPE_CHUNK_SIZE)
 
#define LOGROTATE_SIGNAL_FILE   "logrotate"
 
#define NBUFFER_LISTS   256
 

Functions

NON_EXEC_STATIC void SysLoggerMain (int argc, char *argv[]) pg_attribute_noreturn()
 
static void process_pipe_input (char *logbuffer, int *bytes_in_logbuffer)
 
static void flush_pipe_input (char *logbuffer, int *bytes_in_logbuffer)
 
static FILE * logfile_open (const char *filename, const char *mode, bool allow_errors)
 
static void logfile_rotate (bool time_based_rotation, int size_rotation_for)
 
static char * logfile_getname (pg_time_t timestamp, const char *suffix)
 
static void set_next_rotation_time (void)
 
static void sigHupHandler (SIGNAL_ARGS)
 
static void sigUsr1Handler (SIGNAL_ARGS)
 
static void update_metainfo_datafile (void)
 
int SysLogger_Start (void)
 
void write_syslogger_file (const char *buffer, int count, int destination)
 
bool CheckLogrotateSignal (void)
 
void RemoveLogrotateSignalFiles (void)
 

Variables

bool Logging_collector = false
 
int Log_RotationAge = HOURS_PER_DAY * MINS_PER_HOUR
 
int Log_RotationSize = 10 * 1024
 
char * Log_directory = NULL
 
char * Log_filename = NULL
 
bool Log_truncate_on_rotation = false
 
int Log_file_mode = S_IRUSR | S_IWUSR
 
bool redirection_done
 
static pg_time_t next_rotation_time
 
static bool pipe_eof_seen = false
 
static bool rotation_disabled = false
 
static FILE * syslogFile = NULL
 
static FILE * csvlogFile = NULL
 
NON_EXEC_STATIC pg_time_t first_syslogger_file_time = 0
 
static char * last_file_name = NULL
 
static char * last_csv_file_name = NULL
 
static Listbuffer_lists [NBUFFER_LISTS]
 
int syslogPipe [2] = {-1, -1}
 
static volatile sig_atomic_t got_SIGHUP = false
 
static volatile sig_atomic_t rotation_requested = false
 

Macro Definition Documentation

◆ LOGROTATE_SIGNAL_FILE

#define LOGROTATE_SIGNAL_FILE   "logrotate"

Definition at line 62 of file syslogger.c.

Referenced by CheckLogrotateSignal(), and RemoveLogrotateSignalFiles().

◆ NBUFFER_LISTS

#define NBUFFER_LISTS   256

Definition at line 108 of file syslogger.c.

Referenced by flush_pipe_input(), and process_pipe_input().

◆ READ_BUF_SIZE

#define READ_BUF_SIZE   (2 * PIPE_CHUNK_SIZE)

Definition at line 59 of file syslogger.c.

Referenced by SysLoggerMain(), and write_syslogger_file().

Function Documentation

◆ CheckLogrotateSignal()

bool CheckLogrotateSignal ( void  )

Definition at line 1537 of file syslogger.c.

References LOGROTATE_SIGNAL_FILE, and stat.

Referenced by sigusr1_handler().

1538 {
1539  struct stat stat_buf;
1540 
1541  if (stat(LOGROTATE_SIGNAL_FILE, &stat_buf) == 0)
1542  return true;
1543 
1544  return false;
1545 }
struct stat stat_buf
Definition: pg_standby.c:100
#define stat(a, b)
Definition: win32_port.h:255
#define LOGROTATE_SIGNAL_FILE
Definition: syslogger.c:62

◆ flush_pipe_input()

static void flush_pipe_input ( char *  logbuffer,
int *  bytes_in_logbuffer 
)
static

Definition at line 1028 of file syslogger.c.

References buf, StringInfoData::data, save_buffer::data, i, StringInfoData::len, lfirst, sort-test::list, LOG_DESTINATION_STDERR, NBUFFER_LISTS, pfree(), save_buffer::pid, generate_unaccent_rules::str, and write_syslogger_file().

Referenced by SysLoggerMain(), and write_syslogger_file().

1029 {
1030  int i;
1031 
1032  /* Dump any incomplete protocol messages */
1033  for (i = 0; i < NBUFFER_LISTS; i++)
1034  {
1035  List *list = buffer_lists[i];
1036  ListCell *cell;
1037 
1038  foreach(cell, list)
1039  {
1040  save_buffer *buf = (save_buffer *) lfirst(cell);
1041 
1042  if (buf->pid != 0)
1043  {
1044  StringInfo str = &(buf->data);
1045 
1046  write_syslogger_file(str->data, str->len,
1048  /* Mark the buffer unused, and reclaim string storage */
1049  buf->pid = 0;
1050  pfree(str->data);
1051  }
1052  }
1053  }
1054 
1055  /*
1056  * Force out any remaining pipe data as-is; we don't bother trying to
1057  * remove any protocol headers that may exist in it.
1058  */
1059  if (*bytes_in_logbuffer > 0)
1060  write_syslogger_file(logbuffer, *bytes_in_logbuffer,
1062  *bytes_in_logbuffer = 0;
1063 }
void write_syslogger_file(const char *buffer, int count, int destination)
Definition: syslogger.c:1079
int32 pid
Definition: syslogger.c:104
void pfree(void *pointer)
Definition: mcxt.c:1056
#define NBUFFER_LISTS
Definition: syslogger.c:108
static char * buf
Definition: pg_test_fsync.c:67
static List * buffer_lists[NBUFFER_LISTS]
Definition: syslogger.c:109
StringInfoData data
Definition: syslogger.c:105
#define LOG_DESTINATION_STDERR
Definition: elog.h:418
#define lfirst(lc)
Definition: pg_list.h:190
int i
Definition: pg_list.h:50

◆ logfile_getname()

static char * logfile_getname ( pg_time_t  timestamp,
const char *  suffix 
)
static

Definition at line 1389 of file syslogger.c.

References filename, Log_directory, Log_filename, log_timezone, MAXPGPATH, palloc(), pg_localtime(), pg_strftime(), snprintf, and strlcpy().

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

1390 {
1391  char *filename;
1392  int len;
1393 
1394  filename = palloc(MAXPGPATH);
1395 
1396  snprintf(filename, MAXPGPATH, "%s/", Log_directory);
1397 
1398  len = strlen(filename);
1399 
1400  /* treat Log_filename as a strftime pattern */
1401  pg_strftime(filename + len, MAXPGPATH - len, Log_filename,
1403 
1404  if (suffix != NULL)
1405  {
1406  len = strlen(filename);
1407  if (len > 4 && (strcmp(filename + (len - 4), ".log") == 0))
1408  len -= 4;
1409  strlcpy(filename + len, suffix, MAXPGPATH - len);
1410  }
1411 
1412  return filename;
1413 }
size_t pg_strftime(char *s, size_t max, const char *format, const struct pg_tm *tm)
Definition: strftime.c:122
char * Log_directory
Definition: syslogger.c:72
int64 timestamp
pg_tz * log_timezone
Definition: pgtz.c:31
#define MAXPGPATH
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
struct pg_tm * pg_localtime(const pg_time_t *timep, const pg_tz *tz)
Definition: localtime.c:1375
char * Log_filename
Definition: syslogger.c:73
static char * filename
Definition: pg_dumpall.c:90
void * palloc(Size size)
Definition: mcxt.c:949
#define snprintf
Definition: port.h:192

◆ logfile_open()

static FILE * logfile_open ( const char *  filename,
const char *  mode,
bool  allow_errors 
)
static

Definition at line 1197 of file syslogger.c.

References ereport, errcode_for_file_access(), errmsg(), FATAL, LOG, Log_file_mode, PG_IOLBF, S_IRWXG, S_IRWXO, S_IRWXU, and S_IWUSR.

Referenced by logfile_rotate(), and SysLogger_Start().

1198 {
1199  FILE *fh;
1200  mode_t oumask;
1201 
1202  /*
1203  * Note we do not let Log_file_mode disable IWUSR, since we certainly want
1204  * to be able to write the files ourselves.
1205  */
1206  oumask = umask((mode_t) ((~(Log_file_mode | S_IWUSR)) & (S_IRWXU | S_IRWXG | S_IRWXO)));
1207  fh = fopen(filename, mode);
1208  umask(oumask);
1209 
1210  if (fh)
1211  {
1212  setvbuf(fh, NULL, PG_IOLBF, 0);
1213 
1214 #ifdef WIN32
1215  /* use CRLF line endings on Windows */
1216  _setmode(_fileno(fh), _O_TEXT);
1217 #endif
1218  }
1219  else
1220  {
1221  int save_errno = errno;
1222 
1223  ereport(allow_errors ? LOG : FATAL,
1225  errmsg("could not open log file \"%s\": %m",
1226  filename)));
1227  errno = save_errno;
1228  }
1229 
1230  return fh;
1231 }
static PgChecksumMode mode
Definition: pg_checksums.c:61
#define LOG
Definition: elog.h:26
int Log_file_mode
Definition: syslogger.c:75
#define S_IWUSR
Definition: win32_port.h:263
#define FATAL
Definition: elog.h:52
#define S_IRWXG
Definition: win32_port.h:281
int errcode_for_file_access(void)
Definition: elog.c:633
#define PG_IOLBF
Definition: port.h:324
#define ereport(elevel,...)
Definition: elog.h:144
static char * filename
Definition: pg_dumpall.c:90
#define S_IRWXU
Definition: win32_port.h:269
int errmsg(const char *fmt,...)
Definition: elog.c:824
#define S_IRWXO
Definition: win32_port.h:293

◆ logfile_rotate()

static void logfile_rotate ( bool  time_based_rotation,
int  size_rotation_for 
)
static

Definition at line 1237 of file syslogger.c.

References csvlogFile, ereport, errmsg(), filename, last_csv_file_name, last_file_name, LOG, Log_destination, LOG_DESTINATION_CSVLOG, LOG_DESTINATION_STDERR, Log_truncate_on_rotation, logfile_getname(), logfile_open(), next_rotation_time, pfree(), rotation_disabled, rotation_requested, set_next_rotation_time(), syslogFile, and update_metainfo_datafile().

Referenced by SysLoggerMain().

1238 {
1239  char *filename;
1240  char *csvfilename = NULL;
1241  pg_time_t fntime;
1242  FILE *fh;
1243 
1244  rotation_requested = false;
1245 
1246  /*
1247  * When doing a time-based rotation, invent the new logfile name based on
1248  * the planned rotation time, not current time, to avoid "slippage" in the
1249  * file name when we don't do the rotation immediately.
1250  */
1251  if (time_based_rotation)
1252  fntime = next_rotation_time;
1253  else
1254  fntime = time(NULL);
1255  filename = logfile_getname(fntime, NULL);
1257  csvfilename = logfile_getname(fntime, ".csv");
1258 
1259  /*
1260  * Decide whether to overwrite or append. We can overwrite if (a)
1261  * Log_truncate_on_rotation is set, (b) the rotation was triggered by
1262  * elapsed time and not something else, and (c) the computed file name is
1263  * different from what we were previously logging into.
1264  *
1265  * Note: last_file_name should never be NULL here, but if it is, append.
1266  */
1267  if (time_based_rotation || (size_rotation_for & LOG_DESTINATION_STDERR))
1268  {
1269  if (Log_truncate_on_rotation && time_based_rotation &&
1270  last_file_name != NULL &&
1271  strcmp(filename, last_file_name) != 0)
1272  fh = logfile_open(filename, "w", true);
1273  else
1274  fh = logfile_open(filename, "a", true);
1275 
1276  if (!fh)
1277  {
1278  /*
1279  * ENFILE/EMFILE are not too surprising on a busy system; just
1280  * keep using the old file till we manage to get a new one.
1281  * Otherwise, assume something's wrong with Log_directory and stop
1282  * trying to create files.
1283  */
1284  if (errno != ENFILE && errno != EMFILE)
1285  {
1286  ereport(LOG,
1287  (errmsg("disabling automatic rotation (use SIGHUP to re-enable)")));
1288  rotation_disabled = true;
1289  }
1290 
1291  if (filename)
1292  pfree(filename);
1293  if (csvfilename)
1294  pfree(csvfilename);
1295  return;
1296  }
1297 
1298  fclose(syslogFile);
1299  syslogFile = fh;
1300 
1301  /* instead of pfree'ing filename, remember it for next time */
1302  if (last_file_name != NULL)
1305  filename = NULL;
1306  }
1307 
1308  /*
1309  * Same as above, but for csv file. Note that if LOG_DESTINATION_CSVLOG
1310  * was just turned on, we might have to open csvlogFile here though it was
1311  * not open before. In such a case we'll append not overwrite (since
1312  * last_csv_file_name will be NULL); that is consistent with the normal
1313  * rules since it's not a time-based rotation.
1314  */
1315  if ((Log_destination & LOG_DESTINATION_CSVLOG) &&
1316  (csvlogFile == NULL ||
1317  time_based_rotation || (size_rotation_for & LOG_DESTINATION_CSVLOG)))
1318  {
1319  if (Log_truncate_on_rotation && time_based_rotation &&
1320  last_csv_file_name != NULL &&
1321  strcmp(csvfilename, last_csv_file_name) != 0)
1322  fh = logfile_open(csvfilename, "w", true);
1323  else
1324  fh = logfile_open(csvfilename, "a", true);
1325 
1326  if (!fh)
1327  {
1328  /*
1329  * ENFILE/EMFILE are not too surprising on a busy system; just
1330  * keep using the old file till we manage to get a new one.
1331  * Otherwise, assume something's wrong with Log_directory and stop
1332  * trying to create files.
1333  */
1334  if (errno != ENFILE && errno != EMFILE)
1335  {
1336  ereport(LOG,
1337  (errmsg("disabling automatic rotation (use SIGHUP to re-enable)")));
1338  rotation_disabled = true;
1339  }
1340 
1341  if (filename)
1342  pfree(filename);
1343  if (csvfilename)
1344  pfree(csvfilename);
1345  return;
1346  }
1347 
1348  if (csvlogFile != NULL)
1349  fclose(csvlogFile);
1350  csvlogFile = fh;
1351 
1352  /* instead of pfree'ing filename, remember it for next time */
1353  if (last_csv_file_name != NULL)
1355  last_csv_file_name = csvfilename;
1356  csvfilename = NULL;
1357  }
1358  else if (!(Log_destination & LOG_DESTINATION_CSVLOG) &&
1359  csvlogFile != NULL)
1360  {
1361  /* CSVLOG was just turned off, so close the old file */
1362  fclose(csvlogFile);
1363  csvlogFile = NULL;
1364  if (last_csv_file_name != NULL)
1366  last_csv_file_name = NULL;
1367  }
1368 
1369  if (filename)
1370  pfree(filename);
1371  if (csvfilename)
1372  pfree(csvfilename);
1373 
1375 
1377 }
static pg_time_t next_rotation_time
Definition: syslogger.c:82
int64 pg_time_t
Definition: pgtime.h:23
static FILE * csvlogFile
Definition: syslogger.c:86
static void set_next_rotation_time(void)
Definition: syslogger.c:1419
#define LOG
Definition: elog.h:26
static char * last_file_name
Definition: syslogger.c:88
void pfree(void *pointer)
Definition: mcxt.c:1056
static char * logfile_getname(pg_time_t timestamp, const char *suffix)
Definition: syslogger.c:1389
static bool rotation_disabled
Definition: syslogger.c:84
static char * last_csv_file_name
Definition: syslogger.c:89
#define LOG_DESTINATION_CSVLOG
Definition: elog.h:421
#define LOG_DESTINATION_STDERR
Definition: elog.h:418
#define ereport(elevel,...)
Definition: elog.h:144
static void update_metainfo_datafile(void)
Definition: syslogger.c:1454
static FILE * syslogFile
Definition: syslogger.c:85
static char * filename
Definition: pg_dumpall.c:90
int errmsg(const char *fmt,...)
Definition: elog.c:824
static FILE * logfile_open(const char *filename, const char *mode, bool allow_errors)
Definition: syslogger.c:1197
bool Log_truncate_on_rotation
Definition: syslogger.c:74
int Log_destination
Definition: elog.c:110
static volatile sig_atomic_t rotation_requested
Definition: syslogger.c:127

◆ process_pipe_input()

static void process_pipe_input ( char *  logbuffer,
int *  bytes_in_logbuffer 
)
static

Definition at line 877 of file syslogger.c.

References appendBinaryStringInfo(), buf, StringInfoData::data, save_buffer::data, generate_unaccent_rules::dest, initStringInfo(), PipeProtoHeader::is_last, lappend(), StringInfoData::len, PipeProtoHeader::len, lfirst, LOG_DESTINATION_CSVLOG, LOG_DESTINATION_STDERR, NBUFFER_LISTS, PipeProtoHeader::nuls, offsetof, palloc(), pfree(), PipeProtoHeader::pid, save_buffer::pid, PIPE_HEADER_SIZE, PIPE_MAX_PAYLOAD, generate_unaccent_rules::str, and write_syslogger_file().

Referenced by SysLoggerMain(), and write_syslogger_file().

878 {
879  char *cursor = logbuffer;
880  int count = *bytes_in_logbuffer;
882 
883  /* While we have enough for a header, process data... */
884  while (count >= (int) (offsetof(PipeProtoHeader, data) + 1))
885  {
886  PipeProtoHeader p;
887  int chunklen;
888 
889  /* Do we have a valid header? */
890  memcpy(&p, cursor, offsetof(PipeProtoHeader, data));
891  if (p.nuls[0] == '\0' && p.nuls[1] == '\0' &&
892  p.len > 0 && p.len <= PIPE_MAX_PAYLOAD &&
893  p.pid != 0 &&
894  (p.is_last == 't' || p.is_last == 'f' ||
895  p.is_last == 'T' || p.is_last == 'F'))
896  {
897  List *buffer_list;
898  ListCell *cell;
899  save_buffer *existing_slot = NULL,
900  *free_slot = NULL;
901  StringInfo str;
902 
903  chunklen = PIPE_HEADER_SIZE + p.len;
904 
905  /* Fall out of loop if we don't have the whole chunk yet */
906  if (count < chunklen)
907  break;
908 
909  dest = (p.is_last == 'T' || p.is_last == 'F') ?
911 
912  /* Locate any existing buffer for this source pid */
913  buffer_list = buffer_lists[p.pid % NBUFFER_LISTS];
914  foreach(cell, buffer_list)
915  {
916  save_buffer *buf = (save_buffer *) lfirst(cell);
917 
918  if (buf->pid == p.pid)
919  {
920  existing_slot = buf;
921  break;
922  }
923  if (buf->pid == 0 && free_slot == NULL)
924  free_slot = buf;
925  }
926 
927  if (p.is_last == 'f' || p.is_last == 'F')
928  {
929  /*
930  * Save a complete non-final chunk in a per-pid buffer
931  */
932  if (existing_slot != NULL)
933  {
934  /* Add chunk to data from preceding chunks */
935  str = &(existing_slot->data);
937  cursor + PIPE_HEADER_SIZE,
938  p.len);
939  }
940  else
941  {
942  /* First chunk of message, save in a new buffer */
943  if (free_slot == NULL)
944  {
945  /*
946  * Need a free slot, but there isn't one in the list,
947  * so create a new one and extend the list with it.
948  */
949  free_slot = palloc(sizeof(save_buffer));
950  buffer_list = lappend(buffer_list, free_slot);
951  buffer_lists[p.pid % NBUFFER_LISTS] = buffer_list;
952  }
953  free_slot->pid = p.pid;
954  str = &(free_slot->data);
955  initStringInfo(str);
957  cursor + PIPE_HEADER_SIZE,
958  p.len);
959  }
960  }
961  else
962  {
963  /*
964  * Final chunk --- add it to anything saved for that pid, and
965  * either way write the whole thing out.
966  */
967  if (existing_slot != NULL)
968  {
969  str = &(existing_slot->data);
971  cursor + PIPE_HEADER_SIZE,
972  p.len);
973  write_syslogger_file(str->data, str->len, dest);
974  /* Mark the buffer unused, and reclaim string storage */
975  existing_slot->pid = 0;
976  pfree(str->data);
977  }
978  else
979  {
980  /* The whole message was one chunk, evidently. */
982  dest);
983  }
984  }
985 
986  /* Finished processing this chunk */
987  cursor += chunklen;
988  count -= chunklen;
989  }
990  else
991  {
992  /* Process non-protocol data */
993 
994  /*
995  * Look for the start of a protocol header. If found, dump data
996  * up to there and repeat the loop. Otherwise, dump it all and
997  * fall out of the loop. (Note: we want to dump it all if at all
998  * possible, so as to avoid dividing non-protocol messages across
999  * logfiles. We expect that in many scenarios, a non-protocol
1000  * message will arrive all in one read(), and we want to respect
1001  * the read() boundary if possible.)
1002  */
1003  for (chunklen = 1; chunklen < count; chunklen++)
1004  {
1005  if (cursor[chunklen] == '\0')
1006  break;
1007  }
1008  /* fall back on the stderr log as the destination */
1009  write_syslogger_file(cursor, chunklen, LOG_DESTINATION_STDERR);
1010  cursor += chunklen;
1011  count -= chunklen;
1012  }
1013  }
1014 
1015  /* We don't have a full chunk, so left-align what remains in the buffer */
1016  if (count > 0 && cursor != logbuffer)
1017  memmove(logbuffer, cursor, count);
1018  *bytes_in_logbuffer = count;
1019 }
#define PIPE_HEADER_SIZE
Definition: syslogger.h:60
void write_syslogger_file(const char *buffer, int count, int destination)
Definition: syslogger.c:1079
int32 pid
Definition: syslogger.c:104
char nuls[2]
Definition: syslogger.h:46
#define PIPE_MAX_PAYLOAD
Definition: syslogger.h:61
void pfree(void *pointer)
Definition: mcxt.c:1056
#define NBUFFER_LISTS
Definition: syslogger.c:108
static char * buf
Definition: pg_test_fsync.c:67
Definition: type.h:130
static List * buffer_lists[NBUFFER_LISTS]
Definition: syslogger.c:109
List * lappend(List *list, void *datum)
Definition: list.c:322
StringInfoData data
Definition: syslogger.c:105
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
#define LOG_DESTINATION_CSVLOG
Definition: elog.h:421
#define LOG_DESTINATION_STDERR
Definition: elog.h:418
#define lfirst(lc)
Definition: pg_list.h:190
void * palloc(Size size)
Definition: mcxt.c:949
Definition: pg_list.h:50
void appendBinaryStringInfo(StringInfo str, const char *data, int datalen)
Definition: stringinfo.c:227
#define offsetof(type, field)
Definition: c.h:661

◆ RemoveLogrotateSignalFiles()

void RemoveLogrotateSignalFiles ( void  )

Definition at line 1551 of file syslogger.c.

References LOGROTATE_SIGNAL_FILE.

Referenced by PostmasterMain(), and sigusr1_handler().

1552 {
1553  unlink(LOGROTATE_SIGNAL_FILE);
1554 }
#define LOGROTATE_SIGNAL_FILE
Definition: syslogger.c:62

◆ set_next_rotation_time()

static void set_next_rotation_time ( void  )
static

Definition at line 1419 of file syslogger.c.

References Log_RotationAge, log_timezone, next_rotation_time, now(), pg_localtime(), SECS_PER_MINUTE, tm, and pg_tm::tm_gmtoff.

Referenced by logfile_rotate(), and SysLoggerMain().

1420 {
1421  pg_time_t now;
1422  struct pg_tm *tm;
1423  int rotinterval;
1424 
1425  /* nothing to do if time-based rotation is disabled */
1426  if (Log_RotationAge <= 0)
1427  return;
1428 
1429  /*
1430  * The requirements here are to choose the next time > now that is a
1431  * "multiple" of the log rotation interval. "Multiple" can be interpreted
1432  * fairly loosely. In this version we align to log_timezone rather than
1433  * GMT.
1434  */
1435  rotinterval = Log_RotationAge * SECS_PER_MINUTE; /* convert to seconds */
1436  now = (pg_time_t) time(NULL);
1437  tm = pg_localtime(&now, log_timezone);
1438  now += tm->tm_gmtoff;
1439  now -= now % rotinterval;
1440  now += rotinterval;
1441  now -= tm->tm_gmtoff;
1443 }
static pg_time_t next_rotation_time
Definition: syslogger.c:82
int64 pg_time_t
Definition: pgtime.h:23
long int tm_gmtoff
Definition: pgtime.h:36
Definition: pgtime.h:25
static struct pg_tm tm
Definition: localtime.c:108
pg_tz * log_timezone
Definition: pgtz.c:31
#define SECS_PER_MINUTE
Definition: timestamp.h:88
int Log_RotationAge
Definition: syslogger.c:70
struct pg_tm * pg_localtime(const pg_time_t *timep, const pg_tz *tz)
Definition: localtime.c:1375
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1547

◆ sigHupHandler()

static void sigHupHandler ( SIGNAL_ARGS  )
static

Definition at line 1558 of file syslogger.c.

References got_SIGHUP, MyLatch, and SetLatch().

Referenced by SysLoggerMain().

1559 {
1560  int save_errno = errno;
1561 
1562  got_SIGHUP = true;
1563  SetLatch(MyLatch);
1564 
1565  errno = save_errno;
1566 }
void SetLatch(Latch *latch)
Definition: latch.c:457
static volatile sig_atomic_t got_SIGHUP
Definition: syslogger.c:126
struct Latch * MyLatch
Definition: globals.c:54

◆ sigUsr1Handler()

static void sigUsr1Handler ( SIGNAL_ARGS  )
static

Definition at line 1570 of file syslogger.c.

References MyLatch, rotation_requested, and SetLatch().

Referenced by SysLoggerMain().

1571 {
1572  int save_errno = errno;
1573 
1574  rotation_requested = true;
1575  SetLatch(MyLatch);
1576 
1577  errno = save_errno;
1578 }
void SetLatch(Latch *latch)
Definition: latch.c:457
struct Latch * MyLatch
Definition: globals.c:54
static volatile sig_atomic_t rotation_requested
Definition: syslogger.c:127

◆ SysLogger_Start()

int SysLogger_Start ( void  )

Definition at line 540 of file syslogger.c.

References Assert, av, close, ClosePostmasterPorts(), csvlogFile, dsm_detach_all(), ereport, errcode_for_file_access(), errcode_for_socket_access(), errhint(), errmsg(), FATAL, fd(), filename, first_syslogger_file_time, fork_process(), InitPostmasterChild(), lengthof, LOG, Log_destination, LOG_DESTINATION_CSVLOG, Log_directory, logfile_getname(), logfile_open(), Logging_collector, MakePGDirectory(), pfree(), PG_IOLBF, PGSharedMemoryDetach(), redirection_done, snprintf, generate_unaccent_rules::stdout, syslogFile, SysLoggerMain(), and syslogPipe.

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

541 {
542  pid_t sysloggerPid;
543  char *filename;
544 
545  if (!Logging_collector)
546  return 0;
547 
548  /*
549  * If first time through, create the pipe which will receive stderr
550  * output.
551  *
552  * If the syslogger crashes and needs to be restarted, we continue to use
553  * the same pipe (indeed must do so, since extant backends will be writing
554  * into that pipe).
555  *
556  * This means the postmaster must continue to hold the read end of the
557  * pipe open, so we can pass it down to the reincarnated syslogger. This
558  * is a bit klugy but we have little choice.
559  *
560  * Also note that we don't bother counting the pipe FDs by calling
561  * Reserve/ReleaseExternalFD. There's no real need to account for them
562  * accurately in the postmaster or syslogger process, and both ends of the
563  * pipe will wind up closed in all other postmaster children.
564  */
565 #ifndef WIN32
566  if (syslogPipe[0] < 0)
567  {
568  if (pipe(syslogPipe) < 0)
569  ereport(FATAL,
571  errmsg("could not create pipe for syslog: %m")));
572  }
573 #else
574  if (!syslogPipe[0])
575  {
576  SECURITY_ATTRIBUTES sa;
577 
578  memset(&sa, 0, sizeof(SECURITY_ATTRIBUTES));
579  sa.nLength = sizeof(SECURITY_ATTRIBUTES);
580  sa.bInheritHandle = TRUE;
581 
582  if (!CreatePipe(&syslogPipe[0], &syslogPipe[1], &sa, 32768))
583  ereport(FATAL,
585  errmsg("could not create pipe for syslog: %m")));
586  }
587 #endif
588 
589  /*
590  * Create log directory if not present; ignore errors
591  */
593 
594  /*
595  * The initial logfile is created right in the postmaster, to verify that
596  * the Log_directory is writable. We save the reference time so that the
597  * syslogger child process can recompute this file name.
598  *
599  * It might look a bit strange to re-do this during a syslogger restart,
600  * but we must do so since the postmaster closed syslogFile after the
601  * previous fork (and remembering that old file wouldn't be right anyway).
602  * Note we always append here, we won't overwrite any existing file. This
603  * is consistent with the normal rules, because by definition this is not
604  * a time-based rotation.
605  */
606  first_syslogger_file_time = time(NULL);
607 
608  filename = logfile_getname(first_syslogger_file_time, NULL);
609 
610  syslogFile = logfile_open(filename, "a", false);
611 
612  pfree(filename);
613 
614  /*
615  * Likewise for the initial CSV log file, if that's enabled. (Note that
616  * we open syslogFile even when only CSV output is nominally enabled,
617  * since some code paths will write to syslogFile anyway.)
618  */
620  {
621  filename = logfile_getname(first_syslogger_file_time, ".csv");
622 
623  csvlogFile = logfile_open(filename, "a", false);
624 
625  pfree(filename);
626  }
627 
628 #ifdef EXEC_BACKEND
629  switch ((sysloggerPid = syslogger_forkexec()))
630 #else
631  switch ((sysloggerPid = fork_process()))
632 #endif
633  {
634  case -1:
635  ereport(LOG,
636  (errmsg("could not fork system logger: %m")));
637  return 0;
638 
639 #ifndef EXEC_BACKEND
640  case 0:
641  /* in postmaster child ... */
643 
644  /* Close the postmaster's sockets */
645  ClosePostmasterPorts(true);
646 
647  /* Drop our connection to postmaster's shared memory, as well */
648  dsm_detach_all();
650 
651  /* do the work */
652  SysLoggerMain(0, NULL);
653  break;
654 #endif
655 
656  default:
657  /* success, in postmaster */
658 
659  /* now we redirect stderr, if not done already */
660  if (!redirection_done)
661  {
662 #ifdef WIN32
663  int fd;
664 #endif
665 
666  /*
667  * Leave a breadcrumb trail when redirecting, in case the user
668  * forgets that redirection is active and looks only at the
669  * original stderr target file.
670  */
671  ereport(LOG,
672  (errmsg("redirecting log output to logging collector process"),
673  errhint("Future log output will appear in directory \"%s\".",
674  Log_directory)));
675 
676 #ifndef WIN32
677  fflush(stdout);
678  if (dup2(syslogPipe[1], fileno(stdout)) < 0)
679  ereport(FATAL,
681  errmsg("could not redirect stdout: %m")));
682  fflush(stderr);
683  if (dup2(syslogPipe[1], fileno(stderr)) < 0)
684  ereport(FATAL,
686  errmsg("could not redirect stderr: %m")));
687  /* Now we are done with the write end of the pipe. */
688  close(syslogPipe[1]);
689  syslogPipe[1] = -1;
690 #else
691 
692  /*
693  * open the pipe in binary mode and make sure stderr is binary
694  * after it's been dup'ed into, to avoid disturbing the pipe
695  * chunking protocol.
696  */
697  fflush(stderr);
698  fd = _open_osfhandle((intptr_t) syslogPipe[1],
699  _O_APPEND | _O_BINARY);
700  if (dup2(fd, _fileno(stderr)) < 0)
701  ereport(FATAL,
703  errmsg("could not redirect stderr: %m")));
704  close(fd);
705  _setmode(_fileno(stderr), _O_BINARY);
706 
707  /*
708  * Now we are done with the write end of the pipe.
709  * CloseHandle() must not be called because the preceding
710  * close() closes the underlying handle.
711  */
712  syslogPipe[1] = 0;
713 #endif
714  redirection_done = true;
715  }
716 
717  /* postmaster will never write the file(s); close 'em */
718  fclose(syslogFile);
719  syslogFile = NULL;
720  if (csvlogFile != NULL)
721  {
722  fclose(csvlogFile);
723  csvlogFile = NULL;
724  }
725  return (int) sysloggerPid;
726  }
727 
728  /* we should never reach here */
729  return 0;
730 }
NON_EXEC_STATIC void SysLoggerMain(int argc, char *argv[]) pg_attribute_noreturn()
Definition: syslogger.c:157
int errhint(const char *fmt,...)
Definition: elog.c:1071
char * Log_directory
Definition: syslogger.c:72
void InitPostmasterChild(void)
Definition: miscinit.c:91
pid_t fork_process(void)
Definition: fork_process.c:32
static FILE * csvlogFile
Definition: syslogger.c:86
#define LOG
Definition: elog.h:26
void ClosePostmasterPorts(bool am_syslogger)
Definition: postmaster.c:2546
static int fd(const char *x, int i)
Definition: preproc-init.c:105
void PGSharedMemoryDetach(void)
Definition: sysv_shmem.c:881
bool Logging_collector
Definition: syslogger.c:69
bool redirection_done
Definition: postmaster.c:355
void pfree(void *pointer)
Definition: mcxt.c:1056
#define FATAL
Definition: elog.h:52
static char * logfile_getname(pg_time_t timestamp, const char *suffix)
Definition: syslogger.c:1389
int errcode_for_file_access(void)
Definition: elog.c:633
int errcode_for_socket_access(void)
Definition: elog.c:704
#define LOG_DESTINATION_CSVLOG
Definition: elog.h:421
#define ereport(elevel,...)
Definition: elog.h:144
int MakePGDirectory(const char *directoryName)
Definition: fd.c:3574
NON_EXEC_STATIC pg_time_t first_syslogger_file_time
Definition: syslogger.c:87
void dsm_detach_all(void)
Definition: dsm.c:630
static FILE * syslogFile
Definition: syslogger.c:85
static char * filename
Definition: pg_dumpall.c:90
int errmsg(const char *fmt,...)
Definition: elog.c:824
static FILE * logfile_open(const char *filename, const char *mode, bool allow_errors)
Definition: syslogger.c:1197
int Log_destination
Definition: elog.c:110
#define close(a)
Definition: win32.h:12
int syslogPipe[2]
Definition: syslogger.c:113

◆ SysLoggerMain()

NON_EXEC_STATIC void SysLoggerMain ( int  argc,
char *  argv[] 
)

Definition at line 157 of file syslogger.c.

References AddWaitEventToSet(), B_LOGGER, close, CreateWaitEventSet(), csvlogFile, CurrentMemoryContext, DEBUG1, DestNone, DEVNULL, EINTR, elog, ereport, errcode_for_socket_access(), errmsg(), WaitEvent::events, FATAL, fd(), first_syslogger_file_time, flush_pipe_input(), got_SIGHUP, init_ps_display(), last_csv_file_name, last_file_name, LOG, Log_destination, LOG_DESTINATION_CSVLOG, LOG_DESTINATION_STDERR, Log_directory, Log_filename, Log_RotationAge, Log_RotationSize, logfile_getname(), logfile_rotate(), MakePGDirectory(), MyBackendType, MyLatch, MyStartTime, next_rotation_time, now(), pfree(), PG_SETMASK, PGC_SIGHUP, PGINVALID_SOCKET, pipe_eof_seen, 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, sigHupHandler(), SIGPIPE, SIGQUIT, SIGUSR1, sigUsr1Handler(), SIGUSR2, generate_unaccent_rules::stdout, syslogFile, syslogPipe, UnBlockSig, update_metainfo_datafile(), WAIT_EVENT_SYSLOGGER_MAIN, WaitEventSetWait(), whereToSendOutput, WL_LATCH_SET, and WL_SOCKET_READABLE.

Referenced by BackendRun(), and SysLogger_Start().

158 {
159 #ifndef WIN32
160  char logbuffer[READ_BUF_SIZE];
161  int bytes_in_logbuffer = 0;
162 #endif
163  char *currentLogDir;
164  char *currentLogFilename;
165  int currentLogRotationAge;
166  pg_time_t now;
167  WaitEventSet *wes;
168 
169  now = MyStartTime;
170 
171 #ifdef EXEC_BACKEND
172  syslogger_parseArgs(argc, argv);
173 #endif /* EXEC_BACKEND */
174 
176  init_ps_display(NULL);
177 
178  /*
179  * If we restarted, our stderr is already redirected into our own input
180  * pipe. This is of course pretty useless, not to mention that it
181  * interferes with detecting pipe EOF. Point stderr to /dev/null. This
182  * assumes that all interesting messages generated in the syslogger will
183  * come through elog.c and will be sent to write_syslogger_file.
184  */
185  if (redirection_done)
186  {
187  int fd = open(DEVNULL, O_WRONLY, 0);
188 
189  /*
190  * The closes might look redundant, but they are not: we want to be
191  * darn sure the pipe gets closed even if the open failed. We can
192  * survive running with stderr pointing nowhere, but we can't afford
193  * to have extra pipe input descriptors hanging around.
194  *
195  * As we're just trying to reset these to go to DEVNULL, there's not
196  * much point in checking for failure from the close/dup2 calls here,
197  * if they fail then presumably the file descriptors are closed and
198  * any writes will go into the bitbucket anyway.
199  */
200  close(fileno(stdout));
201  close(fileno(stderr));
202  if (fd != -1)
203  {
204  (void) dup2(fd, fileno(stdout));
205  (void) dup2(fd, fileno(stderr));
206  close(fd);
207  }
208  }
209 
210  /*
211  * Syslogger's own stderr can't be the syslogPipe, so set it back to text
212  * mode if we didn't just close it. (It was set to binary in
213  * SubPostmasterMain).
214  */
215 #ifdef WIN32
216  else
217  _setmode(_fileno(stderr), _O_TEXT);
218 #endif
219 
220  /*
221  * Also close our copy of the write end of the pipe. This is needed to
222  * ensure we can detect pipe EOF correctly. (But note that in the restart
223  * case, the postmaster already did this.)
224  */
225 #ifndef WIN32
226  if (syslogPipe[1] >= 0)
227  close(syslogPipe[1]);
228  syslogPipe[1] = -1;
229 #else
230  if (syslogPipe[1])
231  CloseHandle(syslogPipe[1]);
232  syslogPipe[1] = 0;
233 #endif
234 
235  /*
236  * Properly accept or ignore signals the postmaster might send us
237  *
238  * Note: we ignore all termination signals, and instead exit only when all
239  * upstream processes are gone, to ensure we don't miss any dying gasps of
240  * broken backends...
241  */
242 
243  pqsignal(SIGHUP, sigHupHandler); /* set flag to read config file */
244  pqsignal(SIGINT, SIG_IGN);
245  pqsignal(SIGTERM, SIG_IGN);
249  pqsignal(SIGUSR1, sigUsr1Handler); /* request log rotation */
251 
252  /*
253  * Reset some signals that are accepted by postmaster but not here
254  */
256 
258 
259 #ifdef WIN32
260  /* Fire up separate data transfer thread */
261  InitializeCriticalSection(&sysloggerSection);
262  EnterCriticalSection(&sysloggerSection);
263 
264  threadHandle = (HANDLE) _beginthreadex(NULL, 0, pipeThread, NULL, 0, NULL);
265  if (threadHandle == 0)
266  elog(FATAL, "could not create syslogger data transfer thread: %m");
267 #endif /* WIN32 */
268 
269  /*
270  * Remember active logfiles' name(s). We recompute 'em from the reference
271  * time because passing down just the pg_time_t is a lot cheaper than
272  * passing a whole file path in the EXEC_BACKEND case.
273  */
275  if (csvlogFile != NULL)
277 
278  /* remember active logfile parameters */
279  currentLogDir = pstrdup(Log_directory);
280  currentLogFilename = pstrdup(Log_filename);
281  currentLogRotationAge = Log_RotationAge;
282  /* set next planned rotation time */
285 
286  /*
287  * Reset whereToSendOutput, as the postmaster will do (but hasn't yet, at
288  * the point where we forked). This prevents duplicate output of messages
289  * from syslogger itself.
290  */
292 
293  /*
294  * Set up a reusable WaitEventSet object we'll use to wait for our latch,
295  * and (except on Windows) our socket.
296  *
297  * Unlike all other postmaster child processes, we'll ignore postmaster
298  * death because we want to collect final log output from all backends and
299  * then exit last. We'll do that by running until we see EOF on the
300  * syslog pipe, which implies that all other backends have exited
301  * (including the postmaster).
302  */
305 #ifndef WIN32
306  AddWaitEventToSet(wes, WL_SOCKET_READABLE, syslogPipe[0], NULL, NULL);
307 #endif
308 
309  /* main worker loop */
310  for (;;)
311  {
312  bool time_based_rotation = false;
313  int size_rotation_for = 0;
314  long cur_timeout;
315  WaitEvent event;
316 
317 #ifndef WIN32
318  int rc;
319 #endif
320 
321  /* Clear any already-pending wakeups */
323 
324  /*
325  * Process any requests or signals received recently.
326  */
327  if (got_SIGHUP)
328  {
329  got_SIGHUP = false;
331 
332  /*
333  * Check if the log directory or filename pattern changed in
334  * postgresql.conf. If so, force rotation to make sure we're
335  * writing the logfiles in the right place.
336  */
337  if (strcmp(Log_directory, currentLogDir) != 0)
338  {
339  pfree(currentLogDir);
340  currentLogDir = pstrdup(Log_directory);
341  rotation_requested = true;
342 
343  /*
344  * Also, create new directory if not present; ignore errors
345  */
347  }
348  if (strcmp(Log_filename, currentLogFilename) != 0)
349  {
350  pfree(currentLogFilename);
351  currentLogFilename = pstrdup(Log_filename);
352  rotation_requested = true;
353  }
354 
355  /*
356  * Force a rotation if CSVLOG output was just turned on or off and
357  * we need to open or close csvlogFile accordingly.
358  */
359  if (((Log_destination & LOG_DESTINATION_CSVLOG) != 0) !=
360  (csvlogFile != NULL))
361  rotation_requested = true;
362 
363  /*
364  * If rotation time parameter changed, reset next rotation time,
365  * but don't immediately force a rotation.
366  */
367  if (currentLogRotationAge != Log_RotationAge)
368  {
369  currentLogRotationAge = Log_RotationAge;
371  }
372 
373  /*
374  * If we had a rotation-disabling failure, re-enable rotation
375  * attempts after SIGHUP, and force one immediately.
376  */
377  if (rotation_disabled)
378  {
379  rotation_disabled = false;
380  rotation_requested = true;
381  }
382 
383  /*
384  * Force rewriting last log filename when reloading configuration.
385  * Even if rotation_requested is false, log_destination may have
386  * been changed and we don't want to wait the next file rotation.
387  */
389  }
390 
392  {
393  /* Do a logfile rotation if it's time */
394  now = (pg_time_t) time(NULL);
395  if (now >= next_rotation_time)
396  rotation_requested = time_based_rotation = true;
397  }
398 
400  {
401  /* Do a rotation if file is too big */
402  if (ftell(syslogFile) >= Log_RotationSize * 1024L)
403  {
404  rotation_requested = true;
405  size_rotation_for |= LOG_DESTINATION_STDERR;
406  }
407  if (csvlogFile != NULL &&
408  ftell(csvlogFile) >= Log_RotationSize * 1024L)
409  {
410  rotation_requested = true;
411  size_rotation_for |= LOG_DESTINATION_CSVLOG;
412  }
413  }
414 
415  if (rotation_requested)
416  {
417  /*
418  * Force rotation when both values are zero. It means the request
419  * was sent by pg_rotate_logfile() or "pg_ctl logrotate".
420  */
421  if (!time_based_rotation && size_rotation_for == 0)
422  size_rotation_for = LOG_DESTINATION_STDERR | LOG_DESTINATION_CSVLOG;
423  logfile_rotate(time_based_rotation, size_rotation_for);
424  }
425 
426  /*
427  * Calculate time till next time-based rotation, so that we don't
428  * sleep longer than that. We assume the value of "now" obtained
429  * above is still close enough. Note we can't make this calculation
430  * until after calling logfile_rotate(), since it will advance
431  * next_rotation_time.
432  *
433  * Also note that we need to beware of overflow in calculation of the
434  * timeout: with large settings of Log_RotationAge, next_rotation_time
435  * could be more than INT_MAX msec in the future. In that case we'll
436  * wait no more than INT_MAX msec, and try again.
437  */
439  {
440  pg_time_t delay;
441 
442  delay = next_rotation_time - now;
443  if (delay > 0)
444  {
445  if (delay > INT_MAX / 1000)
446  delay = INT_MAX / 1000;
447  cur_timeout = delay * 1000L; /* msec */
448  }
449  else
450  cur_timeout = 0;
451  }
452  else
453  cur_timeout = -1L;
454 
455  /*
456  * Sleep until there's something to do
457  */
458 #ifndef WIN32
459  rc = WaitEventSetWait(wes, cur_timeout, &event, 1,
461 
462  if (rc == 1 && event.events == WL_SOCKET_READABLE)
463  {
464  int bytesRead;
465 
466  bytesRead = read(syslogPipe[0],
467  logbuffer + bytes_in_logbuffer,
468  sizeof(logbuffer) - bytes_in_logbuffer);
469  if (bytesRead < 0)
470  {
471  if (errno != EINTR)
472  ereport(LOG,
474  errmsg("could not read from logger pipe: %m")));
475  }
476  else if (bytesRead > 0)
477  {
478  bytes_in_logbuffer += bytesRead;
479  process_pipe_input(logbuffer, &bytes_in_logbuffer);
480  continue;
481  }
482  else
483  {
484  /*
485  * Zero bytes read when select() is saying read-ready means
486  * EOF on the pipe: that is, there are no longer any processes
487  * with the pipe write end open. Therefore, the postmaster
488  * and all backends are shut down, and we are done.
489  */
490  pipe_eof_seen = true;
491 
492  /* if there's any data left then force it out now */
493  flush_pipe_input(logbuffer, &bytes_in_logbuffer);
494  }
495  }
496 #else /* WIN32 */
497 
498  /*
499  * On Windows we leave it to a separate thread to transfer data and
500  * detect pipe EOF. The main thread just wakes up to handle SIGHUP
501  * and rotation conditions.
502  *
503  * Server code isn't generally thread-safe, so we ensure that only one
504  * of the threads is active at a time by entering the critical section
505  * whenever we're not sleeping.
506  */
507  LeaveCriticalSection(&sysloggerSection);
508 
509  (void) WaitEventSetWait(wes, cur_timeout, &event, 1,
511 
512  EnterCriticalSection(&sysloggerSection);
513 #endif /* WIN32 */
514 
515  if (pipe_eof_seen)
516  {
517  /*
518  * seeing this message on the real stderr is annoying - so we make
519  * it DEBUG1 to suppress in normal use.
520  */
521  ereport(DEBUG1,
522  (errmsg("logger shutting down")));
523 
524  /*
525  * Normal exit from the syslogger is here. Note that we
526  * deliberately do not close syslogFile before exiting; this is to
527  * allow for the possibility of elog messages being generated
528  * inside proc_exit. Regular exit() will take care of flushing
529  * and closing stdio channels.
530  */
531  proc_exit(0);
532  }
533  }
534 }
static void logfile_rotate(bool time_based_rotation, int size_rotation_for)
Definition: syslogger.c:1237
static pg_time_t next_rotation_time
Definition: syslogger.c:82
#define SIGQUIT
Definition: win32_port.h:154
#define DEBUG1
Definition: elog.h:25
int64 pg_time_t
Definition: pgtime.h:23
char * Log_directory
Definition: syslogger.c:72
void ProcessConfigFile(GucContext context)
int AddWaitEventToSet(WaitEventSet *set, uint32 events, pgsocket fd, Latch *latch, void *user_data)
Definition: latch.c:760
#define SIGUSR1
Definition: win32_port.h:165
BackendType MyBackendType
Definition: miscinit.c:60
#define SIGCHLD
Definition: win32_port.h:163
#define READ_BUF_SIZE
Definition: syslogger.c:59
char * pstrdup(const char *in)
Definition: mcxt.c:1186
static FILE * csvlogFile
Definition: syslogger.c:86
pg_time_t MyStartTime
Definition: globals.c:41
static void sigHupHandler(SIGNAL_ARGS)
Definition: syslogger.c:1558
void proc_exit(int code)
Definition: ipc.c:104
#define WL_SOCKET_READABLE
Definition: latch.h:125
#define SIGPIPE
Definition: win32_port.h:158
#define SIGUSR2
Definition: win32_port.h:166
static void set_next_rotation_time(void)
Definition: syslogger.c:1419
#define LOG
Definition: elog.h:26
static int fd(const char *x, int i)
Definition: preproc-init.c:105
void ResetLatch(Latch *latch)
Definition: latch.c:540
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
int Log_RotationSize
Definition: syslogger.c:71
bool redirection_done
Definition: postmaster.c:355
WaitEventSet * CreateWaitEventSet(MemoryContext context, int nevents)
Definition: latch.c:563
static char * last_file_name
Definition: syslogger.c:88
void pfree(void *pointer)
Definition: mcxt.c:1056
#define FATAL
Definition: elog.h:52
uint32 events
Definition: latch.h:144
static void sigUsr1Handler(SIGNAL_ARGS)
Definition: syslogger.c:1570
static void process_pipe_input(char *logbuffer, int *bytes_in_logbuffer)
Definition: syslogger.c:877
static char * logfile_getname(pg_time_t timestamp, const char *suffix)
Definition: syslogger.c:1389
Definition: dest.h:89
static bool rotation_disabled
Definition: syslogger.c:84
#define SIGHUP
Definition: win32_port.h:153
sigset_t UnBlockSig
Definition: pqsignal.c:22
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
#define DEVNULL
Definition: port.h:123
static char * last_csv_file_name
Definition: syslogger.c:89
int errcode_for_socket_access(void)
Definition: elog.c:704
Definition: guc.h:72
#define SIG_IGN
Definition: win32_port.h:150
#define PGINVALID_SOCKET
Definition: port.h:33
#define LOG_DESTINATION_CSVLOG
Definition: elog.h:421
#define LOG_DESTINATION_STDERR
Definition: elog.h:418
#define ereport(elevel,...)
Definition: elog.h:144
int MakePGDirectory(const char *directoryName)
Definition: fd.c:3574
int Log_RotationAge
Definition: syslogger.c:70
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:170
static volatile sig_atomic_t got_SIGHUP
Definition: syslogger.c:126
#define SIG_DFL
Definition: win32_port.h:148
#define SIGALRM
Definition: win32_port.h:159
NON_EXEC_STATIC pg_time_t first_syslogger_file_time
Definition: syslogger.c:87
static void update_metainfo_datafile(void)
Definition: syslogger.c:1454
static FILE * syslogFile
Definition: syslogger.c:85
char * Log_filename
Definition: syslogger.c:73
static bool pipe_eof_seen
Definition: syslogger.c:83
static void flush_pipe_input(char *logbuffer, int *bytes_in_logbuffer)
Definition: syslogger.c:1028
int errmsg(const char *fmt,...)
Definition: elog.c:824
#define elog(elevel,...)
Definition: elog.h:214
struct Latch * MyLatch
Definition: globals.c:54
int Log_destination
Definition: elog.c:110
void init_ps_display(const char *fixed_part)
Definition: ps_status.c:258
#define close(a)
Definition: win32.h:12
#define EINTR
Definition: win32_port.h:323
CommandDest whereToSendOutput
Definition: postgres.c:91
static volatile sig_atomic_t rotation_requested
Definition: syslogger.c:127
#define WL_LATCH_SET
Definition: latch.h:124
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1547
#define read(a, b, c)
Definition: win32.h:13
int WaitEventSetWait(WaitEventSet *set, long timeout, WaitEvent *occurred_events, int nevents, uint32 wait_event_info)
Definition: latch.c:1167
int syslogPipe[2]
Definition: syslogger.c:113

◆ update_metainfo_datafile()

static void update_metainfo_datafile ( void  )
static

Definition at line 1454 of file syslogger.c.

References ereport, errcode_for_file_access(), errmsg(), fprintf, last_csv_file_name, last_file_name, LOG, Log_destination, LOG_DESTINATION_CSVLOG, LOG_DESTINATION_STDERR, LOG_METAINFO_DATAFILE, LOG_METAINFO_DATAFILE_TMP, PG_IOLBF, and pg_mode_mask.

Referenced by logfile_rotate(), and SysLoggerMain().

1455 {
1456  FILE *fh;
1457  mode_t oumask;
1458 
1461  {
1462  if (unlink(LOG_METAINFO_DATAFILE) < 0 && errno != ENOENT)
1463  ereport(LOG,
1465  errmsg("could not remove file \"%s\": %m",
1467  return;
1468  }
1469 
1470  /* use the same permissions as the data directory for the new file */
1471  oumask = umask(pg_mode_mask);
1472  fh = fopen(LOG_METAINFO_DATAFILE_TMP, "w");
1473  umask(oumask);
1474 
1475  if (fh)
1476  {
1477  setvbuf(fh, NULL, PG_IOLBF, 0);
1478 
1479 #ifdef WIN32
1480  /* use CRLF line endings on Windows */
1481  _setmode(_fileno(fh), _O_TEXT);
1482 #endif
1483  }
1484  else
1485  {
1486  ereport(LOG,
1488  errmsg("could not open file \"%s\": %m",
1490  return;
1491  }
1492 
1493  if (last_file_name && (Log_destination & LOG_DESTINATION_STDERR))
1494  {
1495  if (fprintf(fh, "stderr %s\n", last_file_name) < 0)
1496  {
1497  ereport(LOG,
1499  errmsg("could not write file \"%s\": %m",
1501  fclose(fh);
1502  return;
1503  }
1504  }
1505 
1506  if (last_csv_file_name && (Log_destination & LOG_DESTINATION_CSVLOG))
1507  {
1508  if (fprintf(fh, "csvlog %s\n", last_csv_file_name) < 0)
1509  {
1510  ereport(LOG,
1512  errmsg("could not write file \"%s\": %m",
1514  fclose(fh);
1515  return;
1516  }
1517  }
1518  fclose(fh);
1519 
1521  ereport(LOG,
1523  errmsg("could not rename file \"%s\" to \"%s\": %m",
1525 }
#define LOG_METAINFO_DATAFILE
Definition: syslogger.h:95
#define LOG
Definition: elog.h:26
#define fprintf
Definition: port.h:196
static char * last_file_name
Definition: syslogger.c:88
int errcode_for_file_access(void)
Definition: elog.c:633
static char * last_csv_file_name
Definition: syslogger.c:89
#define PG_IOLBF
Definition: port.h:324
#define LOG_DESTINATION_CSVLOG
Definition: elog.h:421
#define LOG_DESTINATION_STDERR
Definition: elog.h:418
#define ereport(elevel,...)
Definition: elog.h:144
#define LOG_METAINFO_DATAFILE_TMP
Definition: syslogger.h:96
int errmsg(const char *fmt,...)
Definition: elog.c:824
int Log_destination
Definition: elog.c:110
int pg_mode_mask
Definition: file_perm.c:25

◆ write_syslogger_file()

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

Definition at line 1079 of file syslogger.c.

References _dosmaperr(), arg, csvlogFile, ereport, errcode_for_file_access(), errmsg(), error(), flush_pipe_input(), LOG, LOG_DESTINATION_CSVLOG, Log_RotationSize, logfile, MyLatch, pipe_eof_seen, process_pipe_input(), READ_BUF_SIZE, SetLatch(), strerror, syslogFile, syslogPipe, and write_stderr.

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

1080 {
1081  int rc;
1082  FILE *logfile;
1083 
1084  /*
1085  * If we're told to write to csvlogFile, but it's not open, dump the data
1086  * to syslogFile (which is always open) instead. This can happen if CSV
1087  * output is enabled after postmaster start and we've been unable to open
1088  * csvlogFile. There are also race conditions during a parameter change
1089  * whereby backends might send us CSV output before we open csvlogFile or
1090  * after we close it. Writing CSV-formatted output to the regular log
1091  * file isn't great, but it beats dropping log output on the floor.
1092  *
1093  * Think not to improve this by trying to open csvlogFile on-the-fly. Any
1094  * failure in that would lead to recursion.
1095  */
1096  logfile = (destination == LOG_DESTINATION_CSVLOG &&
1097  csvlogFile != NULL) ? csvlogFile : syslogFile;
1098 
1099  rc = fwrite(buffer, 1, count, logfile);
1100 
1101  /*
1102  * Try to report any failure. We mustn't use ereport because it would
1103  * just recurse right back here, but write_stderr is OK: it will write
1104  * either to the postmaster's original stderr, or to /dev/null, but never
1105  * to our input pipe which would result in a different sort of looping.
1106  */
1107  if (rc != count)
1108  write_stderr("could not write to log file: %s\n", strerror(errno));
1109 }
static FILE * csvlogFile
Definition: syslogger.c:86
#define write_stderr(str)
Definition: parallel.c:186
static FILE * logfile
Definition: pg_regress.c:100
#define LOG_DESTINATION_CSVLOG
Definition: elog.h:421
#define strerror
Definition: port.h:205
static FILE * syslogFile
Definition: syslogger.c:85

Variable Documentation

◆ buffer_lists

List* buffer_lists[NBUFFER_LISTS]
static

Definition at line 109 of file syslogger.c.

◆ csvlogFile

FILE* csvlogFile = NULL
static

Definition at line 86 of file syslogger.c.

Referenced by logfile_rotate(), SysLogger_Start(), SysLoggerMain(), and write_syslogger_file().

◆ first_syslogger_file_time

NON_EXEC_STATIC pg_time_t first_syslogger_file_time = 0

Definition at line 87 of file syslogger.c.

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

◆ got_SIGHUP

volatile sig_atomic_t got_SIGHUP = false
static

Definition at line 126 of file syslogger.c.

Referenced by sigHupHandler(), and SysLoggerMain().

◆ last_csv_file_name

char* last_csv_file_name = NULL
static

Definition at line 89 of file syslogger.c.

Referenced by logfile_rotate(), SysLoggerMain(), and update_metainfo_datafile().

◆ last_file_name

char* last_file_name = NULL
static

Definition at line 88 of file syslogger.c.

Referenced by logfile_rotate(), SysLoggerMain(), and update_metainfo_datafile().

◆ Log_directory

char* Log_directory = NULL

◆ Log_file_mode

int Log_file_mode = S_IRUSR | S_IWUSR

Definition at line 75 of file syslogger.c.

Referenced by logfile_open(), and show_log_file_mode().

◆ Log_filename

char* Log_filename = NULL

Definition at line 73 of file syslogger.c.

Referenced by logfile_getname(), pg_logdir_ls_internal(), and SysLoggerMain().

◆ Log_RotationAge

int Log_RotationAge = HOURS_PER_DAY * MINS_PER_HOUR

Definition at line 70 of file syslogger.c.

Referenced by set_next_rotation_time(), and SysLoggerMain().

◆ Log_RotationSize

int Log_RotationSize = 10 * 1024

Definition at line 71 of file syslogger.c.

Referenced by SysLoggerMain(), and write_syslogger_file().

◆ Log_truncate_on_rotation

bool Log_truncate_on_rotation = false

Definition at line 74 of file syslogger.c.

Referenced by logfile_rotate().

◆ Logging_collector

bool Logging_collector = false

Definition at line 69 of file syslogger.c.

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

◆ next_rotation_time

pg_time_t next_rotation_time
static

Definition at line 82 of file syslogger.c.

Referenced by logfile_rotate(), set_next_rotation_time(), and SysLoggerMain().

◆ pipe_eof_seen

bool pipe_eof_seen = false
static

Definition at line 83 of file syslogger.c.

Referenced by SysLoggerMain(), and write_syslogger_file().

◆ redirection_done

bool redirection_done

Definition at line 355 of file postmaster.c.

Referenced by SysLogger_Start(), and SysLoggerMain().

◆ rotation_disabled

bool rotation_disabled = false
static

Definition at line 84 of file syslogger.c.

Referenced by logfile_rotate(), and SysLoggerMain().

◆ rotation_requested

volatile sig_atomic_t rotation_requested = false
static

Definition at line 127 of file syslogger.c.

Referenced by logfile_rotate(), sigUsr1Handler(), and SysLoggerMain().

◆ syslogFile

FILE* syslogFile = NULL
static

Definition at line 85 of file syslogger.c.

Referenced by logfile_rotate(), SysLogger_Start(), SysLoggerMain(), and write_syslogger_file().

◆ syslogPipe

int syslogPipe[2] = {-1, -1}