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 am_syslogger = false
 
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 113 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 1538 of file syslogger.c.

References LOGROTATE_SIGNAL_FILE, and stat.

Referenced by sigusr1_handler().

1539 {
1540  struct stat stat_buf;
1541 
1542  if (stat(LOGROTATE_SIGNAL_FILE, &stat_buf) == 0)
1543  return true;
1544 
1545  return false;
1546 }
struct stat stat_buf
Definition: pg_standby.c:101
#define stat(a, b)
Definition: win32_port.h:264
#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 1029 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().

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

1391 {
1392  char *filename;
1393  int len;
1394 
1395  filename = palloc(MAXPGPATH);
1396 
1397  snprintf(filename, MAXPGPATH, "%s/", Log_directory);
1398 
1399  len = strlen(filename);
1400 
1401  /* treat Log_filename as a strftime pattern */
1402  pg_strftime(filename + len, MAXPGPATH - len, Log_filename,
1404 
1405  if (suffix != NULL)
1406  {
1407  len = strlen(filename);
1408  if (len > 4 && (strcmp(filename + (len - 4), ".log") == 0))
1409  len -= 4;
1410  strlcpy(filename + len, suffix, MAXPGPATH - len);
1411  }
1412 
1413  return filename;
1414 }
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:91
void * palloc(Size size)
Definition: mcxt.c:924
#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 1198 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().

1199 {
1200  FILE *fh;
1201  mode_t oumask;
1202 
1203  /*
1204  * Note we do not let Log_file_mode disable IWUSR, since we certainly want
1205  * to be able to write the files ourselves.
1206  */
1207  oumask = umask((mode_t) ((~(Log_file_mode | S_IWUSR)) & (S_IRWXU | S_IRWXG | S_IRWXO)));
1208  fh = fopen(filename, mode);
1209  umask(oumask);
1210 
1211  if (fh)
1212  {
1213  setvbuf(fh, NULL, PG_IOLBF, 0);
1214 
1215 #ifdef WIN32
1216  /* use CRLF line endings on Windows */
1217  _setmode(_fileno(fh), _O_TEXT);
1218 #endif
1219  }
1220  else
1221  {
1222  int save_errno = errno;
1223 
1224  ereport(allow_errors ? LOG : FATAL,
1226  errmsg("could not open log file \"%s\": %m",
1227  filename)));
1228  errno = save_errno;
1229  }
1230 
1231  return fh;
1232 }
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:272
#define FATAL
Definition: elog.h:52
#define S_IRWXG
Definition: win32_port.h:290
int errcode_for_file_access(void)
Definition: elog.c:593
#define ereport(elevel, rest)
Definition: elog.h:141
#define PG_IOLBF
Definition: port.h:324
static char * filename
Definition: pg_dumpall.c:91
#define S_IRWXU
Definition: win32_port.h:278
int errmsg(const char *fmt,...)
Definition: elog.c:784
#define S_IRWXO
Definition: win32_port.h:302

◆ logfile_rotate()

static void logfile_rotate ( bool  time_based_rotation,
int  size_rotation_for 
)
static

Definition at line 1238 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().

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

◆ process_pipe_input()

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

Definition at line 878 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, memmove, 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().

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

◆ RemoveLogrotateSignalFiles()

void RemoveLogrotateSignalFiles ( void  )

Definition at line 1552 of file syslogger.c.

References LOGROTATE_SIGNAL_FILE.

Referenced by PostmasterMain(), and sigusr1_handler().

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

◆ set_next_rotation_time()

static void set_next_rotation_time ( void  )
static

Definition at line 1420 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().

1421 {
1422  pg_time_t now;
1423  struct pg_tm *tm;
1424  int rotinterval;
1425 
1426  /* nothing to do if time-based rotation is disabled */
1427  if (Log_RotationAge <= 0)
1428  return;
1429 
1430  /*
1431  * The requirements here are to choose the next time > now that is a
1432  * "multiple" of the log rotation interval. "Multiple" can be interpreted
1433  * fairly loosely. In this version we align to log_timezone rather than
1434  * GMT.
1435  */
1436  rotinterval = Log_RotationAge * SECS_PER_MINUTE; /* convert to seconds */
1437  now = (pg_time_t) time(NULL);
1438  tm = pg_localtime(&now, log_timezone);
1439  now += tm->tm_gmtoff;
1440  now -= now % rotinterval;
1441  now += rotinterval;
1442  now -= tm->tm_gmtoff;
1444 }
static pg_time_t next_rotation_time
Definition: syslogger.c:87
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:1533

◆ sigHupHandler()

static void sigHupHandler ( SIGNAL_ARGS  )
static

Definition at line 1559 of file syslogger.c.

References got_SIGHUP, MyLatch, and SetLatch().

Referenced by SysLoggerMain().

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

◆ sigUsr1Handler()

static void sigUsr1Handler ( SIGNAL_ARGS  )
static

Definition at line 1571 of file syslogger.c.

References MyLatch, rotation_requested, and SetLatch().

Referenced by SysLoggerMain().

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

◆ SysLogger_Start()

int SysLogger_Start ( void  )

Definition at line 546 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(), syslogPipe, and TRUE.

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

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

◆ SysLoggerMain()

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

Definition at line 162 of file syslogger.c.

References AddWaitEventToSet(), am_syslogger, 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(), 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().

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

◆ update_metainfo_datafile()

static void update_metainfo_datafile ( void  )
static

Definition at line 1455 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().

1456 {
1457  FILE *fh;
1458  mode_t oumask;
1459 
1462  {
1463  if (unlink(LOG_METAINFO_DATAFILE) < 0 && errno != ENOENT)
1464  ereport(LOG,
1466  errmsg("could not remove file \"%s\": %m",
1468  return;
1469  }
1470 
1471  /* use the same permissions as the data directory for the new file */
1472  oumask = umask(pg_mode_mask);
1473  fh = fopen(LOG_METAINFO_DATAFILE_TMP, "w");
1474  umask(oumask);
1475 
1476  if (fh)
1477  {
1478  setvbuf(fh, NULL, PG_IOLBF, 0);
1479 
1480 #ifdef WIN32
1481  /* use CRLF line endings on Windows */
1482  _setmode(_fileno(fh), _O_TEXT);
1483 #endif
1484  }
1485  else
1486  {
1487  ereport(LOG,
1489  errmsg("could not open file \"%s\": %m",
1491  return;
1492  }
1493 
1494  if (last_file_name && (Log_destination & LOG_DESTINATION_STDERR))
1495  {
1496  if (fprintf(fh, "stderr %s\n", last_file_name) < 0)
1497  {
1498  ereport(LOG,
1500  errmsg("could not write file \"%s\": %m",
1502  fclose(fh);
1503  return;
1504  }
1505  }
1506 
1507  if (last_csv_file_name && (Log_destination & LOG_DESTINATION_CSVLOG))
1508  {
1509  if (fprintf(fh, "csvlog %s\n", last_csv_file_name) < 0)
1510  {
1511  ereport(LOG,
1513  errmsg("could not write file \"%s\": %m",
1515  fclose(fh);
1516  return;
1517  }
1518  }
1519  fclose(fh);
1520 
1522  ereport(LOG,
1524  errmsg("could not rename file \"%s\" to \"%s\": %m",
1526 }
#define LOG_METAINFO_DATAFILE
Definition: syslogger.h:97
#define LOG
Definition: elog.h:26
#define fprintf
Definition: port.h:196
static char * last_file_name
Definition: syslogger.c:93
int errcode_for_file_access(void)
Definition: elog.c:593
#define ereport(elevel, rest)
Definition: elog.h:141
static char * last_csv_file_name
Definition: syslogger.c:94
#define PG_IOLBF
Definition: port.h:324
#define LOG_DESTINATION_CSVLOG
Definition: elog.h:415
#define LOG_DESTINATION_STDERR
Definition: elog.h:412
#define LOG_METAINFO_DATAFILE_TMP
Definition: syslogger.h:98
int errmsg(const char *fmt,...)
Definition: elog.c:784
int Log_destination
Definition: elog.c:106
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 1080 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().

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

Variable Documentation

◆ am_syslogger

bool am_syslogger = false

Definition at line 80 of file syslogger.c.

Referenced by send_message_to_server_log(), SysLoggerMain(), and write_csvlog().

◆ buffer_lists

List* buffer_lists[NBUFFER_LISTS]
static

Definition at line 114 of file syslogger.c.

◆ csvlogFile

FILE* csvlogFile = NULL
static

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

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

◆ got_SIGHUP

volatile sig_atomic_t got_SIGHUP = false
static

Definition at line 131 of file syslogger.c.

Referenced by sigHupHandler(), and SysLoggerMain().

◆ last_csv_file_name

char* last_csv_file_name = NULL
static

Definition at line 94 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 93 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 87 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 88 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 89 of file syslogger.c.

Referenced by logfile_rotate(), and SysLoggerMain().

◆ rotation_requested

volatile sig_atomic_t rotation_requested = false
static

Definition at line 132 of file syslogger.c.

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

◆ syslogFile

FILE* syslogFile = NULL
static

Definition at line 90 of file syslogger.c.

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

◆ syslogPipe

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