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 "port/pg_bitutils.h"
#include "postmaster/interrupt.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/memutils.h"
#include "utils/ps_status.h"
Include dependency graph for syslogger.c:

Go to the source code of this file.

Data Structures

struct  save_buffer
 
struct  SysloggerStartupData
 

Macros

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

Functions

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 bool logfile_rotate_dest (bool time_based_rotation, int size_rotation_for, pg_time_t fntime, int target_dest, char **last_file_name, FILE **logFile)
 
static char * logfile_getname (pg_time_t timestamp, const char *suffix)
 
static void set_next_rotation_time (void)
 
static void sigUsr1Handler (SIGNAL_ARGS)
 
static void update_metainfo_datafile (void)
 
void SysLoggerMain (char *startup_data, size_t startup_data_len)
 
int SysLogger_Start (int child_slot)
 
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
 
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
 
static FILE * jsonlogFile = NULL
 
NON_EXEC_STATIC pg_time_t first_syslogger_file_time = 0
 
static char * last_sys_file_name = NULL
 
static char * last_csv_file_name = NULL
 
static char * last_json_file_name = NULL
 
static Listbuffer_lists [NBUFFER_LISTS]
 
int syslogPipe [2] = {-1, -1}
 
static volatile sig_atomic_t rotation_requested = false
 

Macro Definition Documentation

◆ LOGROTATE_SIGNAL_FILE

#define LOGROTATE_SIGNAL_FILE   "logrotate"

Definition at line 63 of file syslogger.c.

◆ NBUFFER_LISTS

#define NBUFFER_LISTS   256

Definition at line 109 of file syslogger.c.

◆ READ_BUF_SIZE

#define READ_BUF_SIZE   (2 * PIPE_CHUNK_SIZE)

Definition at line 60 of file syslogger.c.

Function Documentation

◆ CheckLogrotateSignal()

bool CheckLogrotateSignal ( void  )

Definition at line 1572 of file syslogger.c.

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

References LOGROTATE_SIGNAL_FILE, and stat.

Referenced by process_pm_pmsignal().

◆ flush_pipe_input()

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

Definition at line 1042 of file syslogger.c.

1043 {
1044  int i;
1045 
1046  /* Dump any incomplete protocol messages */
1047  for (i = 0; i < NBUFFER_LISTS; i++)
1048  {
1049  List *list = buffer_lists[i];
1050  ListCell *cell;
1051 
1052  foreach(cell, list)
1053  {
1054  save_buffer *buf = (save_buffer *) lfirst(cell);
1055 
1056  if (buf->pid != 0)
1057  {
1058  StringInfo str = &(buf->data);
1059 
1060  write_syslogger_file(str->data, str->len,
1062  /* Mark the buffer unused, and reclaim string storage */
1063  buf->pid = 0;
1064  pfree(str->data);
1065  }
1066  }
1067  }
1068 
1069  /*
1070  * Force out any remaining pipe data as-is; we don't bother trying to
1071  * remove any protocol headers that may exist in it.
1072  */
1073  if (*bytes_in_logbuffer > 0)
1074  write_syslogger_file(logbuffer, *bytes_in_logbuffer,
1076  *bytes_in_logbuffer = 0;
1077 }
#define LOG_DESTINATION_STDERR
Definition: elog.h:493
const char * str
int i
Definition: isn.c:72
void pfree(void *pointer)
Definition: mcxt.c:1521
#define lfirst(lc)
Definition: pg_list.h:172
static char * buf
Definition: pg_test_fsync.c:72
Definition: pg_list.h:54
#define NBUFFER_LISTS
Definition: syslogger.c:109
void write_syslogger_file(const char *buffer, int count, int destination)
Definition: syslogger.c:1093
static List * buffer_lists[NBUFFER_LISTS]
Definition: syslogger.c:110

References buf, buffer_lists, i, lfirst, sort-test::list, LOG_DESTINATION_STDERR, NBUFFER_LISTS, pfree(), str, and write_syslogger_file().

Referenced by SysLoggerMain().

◆ logfile_getname()

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

Definition at line 1410 of file syslogger.c.

1411 {
1412  char *filename;
1413  int len;
1414 
1416 
1418 
1419  len = strlen(filename);
1420 
1421  /* treat Log_filename as a strftime pattern */
1424 
1425  if (suffix != NULL)
1426  {
1427  len = strlen(filename);
1428  if (len > 4 && (strcmp(filename + (len - 4), ".log") == 0))
1429  len -= 4;
1430  strlcpy(filename + len, suffix, MAXPGPATH - len);
1431  }
1432 
1433  return filename;
1434 }
void * palloc(Size size)
Definition: mcxt.c:1317
#define MAXPGPATH
const void size_t len
static char * filename
Definition: pg_dumpall.c:119
struct pg_tm * pg_localtime(const pg_time_t *timep, const pg_tz *tz)
Definition: localtime.c:1344
size_t pg_strftime(char *s, size_t maxsize, const char *format, const struct pg_tm *t)
Definition: strftime.c:128
PGDLLIMPORT pg_tz * log_timezone
Definition: pgtz.c:31
int64 timestamp
#define snprintf
Definition: port.h:238
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
char * Log_directory
Definition: syslogger.c:73
char * Log_filename
Definition: syslogger.c:74

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

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

◆ logfile_open()

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

Definition at line 1217 of file syslogger.c.

1218 {
1219  FILE *fh;
1220  mode_t oumask;
1221 
1222  /*
1223  * Note we do not let Log_file_mode disable IWUSR, since we certainly want
1224  * to be able to write the files ourselves.
1225  */
1226  oumask = umask((mode_t) ((~(Log_file_mode | S_IWUSR)) & (S_IRWXU | S_IRWXG | S_IRWXO)));
1227  fh = fopen(filename, mode);
1228  umask(oumask);
1229 
1230  if (fh)
1231  {
1232  setvbuf(fh, NULL, PG_IOLBF, 0);
1233 
1234 #ifdef WIN32
1235  /* use CRLF line endings on Windows */
1236  _setmode(_fileno(fh), _O_TEXT);
1237 #endif
1238  }
1239  else
1240  {
1241  int save_errno = errno;
1242 
1243  ereport(allow_errors ? LOG : FATAL,
1245  errmsg("could not open log file \"%s\": %m",
1246  filename)));
1247  errno = save_errno;
1248  }
1249 
1250  return fh;
1251 }
int errcode_for_file_access(void)
Definition: elog.c:876
int errmsg(const char *fmt,...)
Definition: elog.c:1070
#define LOG
Definition: elog.h:31
#define FATAL
Definition: elog.h:41
#define ereport(elevel,...)
Definition: elog.h:149
static PgChecksumMode mode
Definition: pg_checksums.c:55
#define PG_IOLBF
Definition: port.h:361
int Log_file_mode
Definition: syslogger.c:76
#define S_IRWXG
Definition: win32_port.h:310
#define S_IRWXO
Definition: win32_port.h:322
#define S_IWUSR
Definition: win32_port.h:292
#define S_IRWXU
Definition: win32_port.h:298

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

Referenced by logfile_rotate_dest(), and SysLogger_Start().

◆ logfile_rotate()

static void logfile_rotate ( bool  time_based_rotation,
int  size_rotation_for 
)
static

Definition at line 1361 of file syslogger.c.

1362 {
1363  pg_time_t fntime;
1364 
1365  rotation_requested = false;
1366 
1367  /*
1368  * When doing a time-based rotation, invent the new logfile name based on
1369  * the planned rotation time, not current time, to avoid "slippage" in the
1370  * file name when we don't do the rotation immediately.
1371  */
1372  if (time_based_rotation)
1373  fntime = next_rotation_time;
1374  else
1375  fntime = time(NULL);
1376 
1377  /* file rotation for stderr */
1378  if (!logfile_rotate_dest(time_based_rotation, size_rotation_for, fntime,
1380  &syslogFile))
1381  return;
1382 
1383  /* file rotation for csvlog */
1384  if (!logfile_rotate_dest(time_based_rotation, size_rotation_for, fntime,
1386  &csvlogFile))
1387  return;
1388 
1389  /* file rotation for jsonlog */
1390  if (!logfile_rotate_dest(time_based_rotation, size_rotation_for, fntime,
1392  &jsonlogFile))
1393  return;
1394 
1396 
1398 }
#define LOG_DESTINATION_JSONLOG
Definition: elog.h:497
#define LOG_DESTINATION_CSVLOG
Definition: elog.h:496
int64 pg_time_t
Definition: pgtime.h:23
static bool logfile_rotate_dest(bool time_based_rotation, int size_rotation_for, pg_time_t fntime, int target_dest, char **last_file_name, FILE **logFile)
Definition: syslogger.c:1262
static void update_metainfo_datafile(void)
Definition: syslogger.c:1475
static char * last_csv_file_name
Definition: syslogger.c:89
static FILE * syslogFile
Definition: syslogger.c:84
static pg_time_t next_rotation_time
Definition: syslogger.c:81
static volatile sig_atomic_t rotation_requested
Definition: syslogger.c:127
static FILE * csvlogFile
Definition: syslogger.c:85
static void set_next_rotation_time(void)
Definition: syslogger.c:1440
static FILE * jsonlogFile
Definition: syslogger.c:86
static char * last_json_file_name
Definition: syslogger.c:90
static char * last_sys_file_name
Definition: syslogger.c:88

References csvlogFile, jsonlogFile, last_csv_file_name, last_json_file_name, last_sys_file_name, LOG_DESTINATION_CSVLOG, LOG_DESTINATION_JSONLOG, LOG_DESTINATION_STDERR, logfile_rotate_dest(), next_rotation_time, rotation_requested, set_next_rotation_time(), syslogFile, and update_metainfo_datafile().

Referenced by SysLoggerMain().

◆ logfile_rotate_dest()

static bool logfile_rotate_dest ( bool  time_based_rotation,
int  size_rotation_for,
pg_time_t  fntime,
int  target_dest,
char **  last_file_name,
FILE **  logFile 
)
static

Definition at line 1262 of file syslogger.c.

1265 {
1266  char *logFileExt = NULL;
1267  char *filename;
1268  FILE *fh;
1269 
1270  /*
1271  * If the target destination was just turned off, close the previous file
1272  * and unregister its data. This cannot happen for stderr as syslogFile
1273  * is assumed to be always opened even if stderr is disabled in
1274  * log_destination.
1275  */
1276  if ((Log_destination & target_dest) == 0 &&
1277  target_dest != LOG_DESTINATION_STDERR)
1278  {
1279  if (*logFile != NULL)
1280  fclose(*logFile);
1281  *logFile = NULL;
1282  if (*last_file_name != NULL)
1283  pfree(*last_file_name);
1284  *last_file_name = NULL;
1285  return true;
1286  }
1287 
1288  /*
1289  * Leave if it is not time for a rotation or if the target destination has
1290  * no need to do a rotation based on the size of its file.
1291  */
1292  if (!time_based_rotation && (size_rotation_for & target_dest) == 0)
1293  return true;
1294 
1295  /* file extension depends on the destination type */
1296  if (target_dest == LOG_DESTINATION_STDERR)
1297  logFileExt = NULL;
1298  else if (target_dest == LOG_DESTINATION_CSVLOG)
1299  logFileExt = ".csv";
1300  else if (target_dest == LOG_DESTINATION_JSONLOG)
1301  logFileExt = ".json";
1302  else
1303  {
1304  /* cannot happen */
1305  Assert(false);
1306  }
1307 
1308  /* build the new file name */
1309  filename = logfile_getname(fntime, logFileExt);
1310 
1311  /*
1312  * Decide whether to overwrite or append. We can overwrite if (a)
1313  * Log_truncate_on_rotation is set, (b) the rotation was triggered by
1314  * elapsed time and not something else, and (c) the computed file name is
1315  * different from what we were previously logging into.
1316  */
1317  if (Log_truncate_on_rotation && time_based_rotation &&
1318  *last_file_name != NULL &&
1319  strcmp(filename, *last_file_name) != 0)
1320  fh = logfile_open(filename, "w", true);
1321  else
1322  fh = logfile_open(filename, "a", true);
1323 
1324  if (!fh)
1325  {
1326  /*
1327  * ENFILE/EMFILE are not too surprising on a busy system; just keep
1328  * using the old file till we manage to get a new one. Otherwise,
1329  * assume something's wrong with Log_directory and stop trying to
1330  * create files.
1331  */
1332  if (errno != ENFILE && errno != EMFILE)
1333  {
1334  ereport(LOG,
1335  (errmsg("disabling automatic rotation (use SIGHUP to re-enable)")));
1336  rotation_disabled = true;
1337  }
1338 
1339  if (filename)
1340  pfree(filename);
1341  return false;
1342  }
1343 
1344  /* fill in the new information */
1345  if (*logFile != NULL)
1346  fclose(*logFile);
1347  *logFile = fh;
1348 
1349  /* instead of pfree'ing filename, remember it for next time */
1350  if (*last_file_name != NULL)
1351  pfree(*last_file_name);
1352  *last_file_name = filename;
1353 
1354  return true;
1355 }
#define Assert(condition)
Definition: c.h:812
int Log_destination
Definition: elog.c:110
bool Log_truncate_on_rotation
Definition: syslogger.c:75
static bool rotation_disabled
Definition: syslogger.c:83
static char * logfile_getname(pg_time_t timestamp, const char *suffix)
Definition: syslogger.c:1410
static FILE * logfile_open(const char *filename, const char *mode, bool allow_errors)
Definition: syslogger.c:1217

References Assert, ereport, errmsg(), filename, LOG, Log_destination, LOG_DESTINATION_CSVLOG, LOG_DESTINATION_JSONLOG, LOG_DESTINATION_STDERR, Log_truncate_on_rotation, logfile_getname(), logfile_open(), pfree(), and rotation_disabled.

Referenced by logfile_rotate().

◆ process_pipe_input()

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

Definition at line 879 of file syslogger.c.

880 {
881  char *cursor = logbuffer;
882  int count = *bytes_in_logbuffer;
884 
885  /* While we have enough for a header, process data... */
886  while (count >= (int) (offsetof(PipeProtoHeader, data) + 1))
887  {
888  PipeProtoHeader p;
889  int chunklen;
890  bits8 dest_flags;
891 
892  /* Do we have a valid header? */
893  memcpy(&p, cursor, offsetof(PipeProtoHeader, data));
894  dest_flags = p.flags & (PIPE_PROTO_DEST_STDERR |
897  if (p.nuls[0] == '\0' && p.nuls[1] == '\0' &&
898  p.len > 0 && p.len <= PIPE_MAX_PAYLOAD &&
899  p.pid != 0 &&
900  pg_number_of_ones[dest_flags] == 1)
901  {
902  List *buffer_list;
903  ListCell *cell;
904  save_buffer *existing_slot = NULL,
905  *free_slot = NULL;
906  StringInfo str;
907 
908  chunklen = PIPE_HEADER_SIZE + p.len;
909 
910  /* Fall out of loop if we don't have the whole chunk yet */
911  if (count < chunklen)
912  break;
913 
914  if ((p.flags & PIPE_PROTO_DEST_STDERR) != 0)
916  else if ((p.flags & PIPE_PROTO_DEST_CSVLOG) != 0)
918  else if ((p.flags & PIPE_PROTO_DEST_JSONLOG) != 0)
920  else
921  {
922  /* this should never happen as of the header validation */
923  Assert(false);
924  }
925 
926  /* Locate any existing buffer for this source pid */
927  buffer_list = buffer_lists[p.pid % NBUFFER_LISTS];
928  foreach(cell, buffer_list)
929  {
930  save_buffer *buf = (save_buffer *) lfirst(cell);
931 
932  if (buf->pid == p.pid)
933  {
934  existing_slot = buf;
935  break;
936  }
937  if (buf->pid == 0 && free_slot == NULL)
938  free_slot = buf;
939  }
940 
941  if ((p.flags & PIPE_PROTO_IS_LAST) == 0)
942  {
943  /*
944  * Save a complete non-final chunk in a per-pid buffer
945  */
946  if (existing_slot != NULL)
947  {
948  /* Add chunk to data from preceding chunks */
949  str = &(existing_slot->data);
952  p.len);
953  }
954  else
955  {
956  /* First chunk of message, save in a new buffer */
957  if (free_slot == NULL)
958  {
959  /*
960  * Need a free slot, but there isn't one in the list,
961  * so create a new one and extend the list with it.
962  */
963  free_slot = palloc(sizeof(save_buffer));
964  buffer_list = lappend(buffer_list, free_slot);
965  buffer_lists[p.pid % NBUFFER_LISTS] = buffer_list;
966  }
967  free_slot->pid = p.pid;
968  str = &(free_slot->data);
972  p.len);
973  }
974  }
975  else
976  {
977  /*
978  * Final chunk --- add it to anything saved for that pid, and
979  * either way write the whole thing out.
980  */
981  if (existing_slot != NULL)
982  {
983  str = &(existing_slot->data);
986  p.len);
987  write_syslogger_file(str->data, str->len, dest);
988  /* Mark the buffer unused, and reclaim string storage */
989  existing_slot->pid = 0;
990  pfree(str->data);
991  }
992  else
993  {
994  /* The whole message was one chunk, evidently. */
996  dest);
997  }
998  }
999 
1000  /* Finished processing this chunk */
1001  cursor += chunklen;
1002  count -= chunklen;
1003  }
1004  else
1005  {
1006  /* Process non-protocol data */
1007 
1008  /*
1009  * Look for the start of a protocol header. If found, dump data
1010  * up to there and repeat the loop. Otherwise, dump it all and
1011  * fall out of the loop. (Note: we want to dump it all if at all
1012  * possible, so as to avoid dividing non-protocol messages across
1013  * logfiles. We expect that in many scenarios, a non-protocol
1014  * message will arrive all in one read(), and we want to respect
1015  * the read() boundary if possible.)
1016  */
1017  for (chunklen = 1; chunklen < count; chunklen++)
1018  {
1019  if (cursor[chunklen] == '\0')
1020  break;
1021  }
1022  /* fall back on the stderr log as the destination */
1024  cursor += chunklen;
1025  count -= chunklen;
1026  }
1027  }
1028 
1029  /* We don't have a full chunk, so left-align what remains in the buffer */
1030  if (count > 0 && cursor != logbuffer)
1031  memmove(logbuffer, cursor, count);
1032  *bytes_in_logbuffer = count;
1033 }
uint8 bits8
Definition: c.h:492
List * lappend(List *list, void *datum)
Definition: list.c:339
PGDLLIMPORT const uint8 pg_number_of_ones[256]
Definition: pg_bitutils.c:87
const void * data
void appendBinaryStringInfo(StringInfo str, const void *data, int datalen)
Definition: stringinfo.c:230
void initStringInfo(StringInfo str)
Definition: stringinfo.c:56
char nuls[2]
Definition: syslogger.h:46
Definition: type.h:138
StringInfoData data
Definition: syslogger.c:106
int32 pid
Definition: syslogger.c:105
#define PIPE_PROTO_DEST_JSONLOG
Definition: syslogger.h:67
#define PIPE_PROTO_IS_LAST
Definition: syslogger.h:63
#define PIPE_PROTO_DEST_CSVLOG
Definition: syslogger.h:66
#define PIPE_PROTO_DEST_STDERR
Definition: syslogger.h:65
#define PIPE_MAX_PAYLOAD
Definition: syslogger.h:60
#define PIPE_HEADER_SIZE
Definition: syslogger.h:59

References appendBinaryStringInfo(), Assert, buf, buffer_lists, save_buffer::data, data, generate_unaccent_rules::dest, PipeProtoHeader::flags, initStringInfo(), lappend(), PipeProtoHeader::len, lfirst, LOG_DESTINATION_CSVLOG, LOG_DESTINATION_JSONLOG, LOG_DESTINATION_STDERR, NBUFFER_LISTS, PipeProtoHeader::nuls, palloc(), pfree(), pg_number_of_ones, save_buffer::pid, PipeProtoHeader::pid, PIPE_HEADER_SIZE, PIPE_MAX_PAYLOAD, PIPE_PROTO_DEST_CSVLOG, PIPE_PROTO_DEST_JSONLOG, PIPE_PROTO_DEST_STDERR, PIPE_PROTO_IS_LAST, str, and write_syslogger_file().

Referenced by SysLoggerMain().

◆ RemoveLogrotateSignalFiles()

void RemoveLogrotateSignalFiles ( void  )

Definition at line 1586 of file syslogger.c.

1587 {
1588  unlink(LOGROTATE_SIGNAL_FILE);
1589 }

References LOGROTATE_SIGNAL_FILE.

Referenced by PostmasterMain(), and process_pm_pmsignal().

◆ set_next_rotation_time()

static void set_next_rotation_time ( void  )
static

Definition at line 1440 of file syslogger.c.

1441 {
1442  pg_time_t now;
1443  struct pg_tm *tm;
1444  int rotinterval;
1445 
1446  /* nothing to do if time-based rotation is disabled */
1447  if (Log_RotationAge <= 0)
1448  return;
1449 
1450  /*
1451  * The requirements here are to choose the next time > now that is a
1452  * "multiple" of the log rotation interval. "Multiple" can be interpreted
1453  * fairly loosely. In this version we align to log_timezone rather than
1454  * GMT.
1455  */
1456  rotinterval = Log_RotationAge * SECS_PER_MINUTE; /* convert to seconds */
1457  now = (pg_time_t) time(NULL);
1459  now += tm->tm_gmtoff;
1460  now -= now % rotinterval;
1461  now += rotinterval;
1462  now -= tm->tm_gmtoff;
1464 }
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1608
#define SECS_PER_MINUTE
Definition: timestamp.h:128
static struct pg_tm tm
Definition: localtime.c:104
Definition: pgtime.h:35
long int tm_gmtoff
Definition: pgtime.h:45
int Log_RotationAge
Definition: syslogger.c:71

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().

◆ sigUsr1Handler()

static void sigUsr1Handler ( SIGNAL_ARGS  )
static

Definition at line 1593 of file syslogger.c.

1594 {
1595  rotation_requested = true;
1596  SetLatch(MyLatch);
1597 }
struct Latch * MyLatch
Definition: globals.c:62
void SetLatch(Latch *latch)
Definition: latch.c:632

References MyLatch, rotation_requested, and SetLatch().

Referenced by SysLoggerMain().

◆ SysLogger_Start()

int SysLogger_Start ( int  child_slot)

Definition at line 593 of file syslogger.c.

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

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

Referenced by StartSysLogger().

◆ SysLoggerMain()

void SysLoggerMain ( char *  startup_data,
size_t  startup_data_len 
)

Definition at line 165 of file syslogger.c.

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

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

◆ update_metainfo_datafile()

static void update_metainfo_datafile ( void  )
static

Definition at line 1475 of file syslogger.c.

1476 {
1477  FILE *fh;
1478  mode_t oumask;
1479 
1483  {
1484  if (unlink(LOG_METAINFO_DATAFILE) < 0 && errno != ENOENT)
1485  ereport(LOG,
1487  errmsg("could not remove file \"%s\": %m",
1489  return;
1490  }
1491 
1492  /* use the same permissions as the data directory for the new file */
1493  oumask = umask(pg_mode_mask);
1494  fh = fopen(LOG_METAINFO_DATAFILE_TMP, "w");
1495  umask(oumask);
1496 
1497  if (fh)
1498  {
1499  setvbuf(fh, NULL, PG_IOLBF, 0);
1500 
1501 #ifdef WIN32
1502  /* use CRLF line endings on Windows */
1503  _setmode(_fileno(fh), _O_TEXT);
1504 #endif
1505  }
1506  else
1507  {
1508  ereport(LOG,
1510  errmsg("could not open file \"%s\": %m",
1512  return;
1513  }
1514 
1516  {
1517  if (fprintf(fh, "stderr %s\n", last_sys_file_name) < 0)
1518  {
1519  ereport(LOG,
1521  errmsg("could not write file \"%s\": %m",
1523  fclose(fh);
1524  return;
1525  }
1526  }
1527 
1529  {
1530  if (fprintf(fh, "csvlog %s\n", last_csv_file_name) < 0)
1531  {
1532  ereport(LOG,
1534  errmsg("could not write file \"%s\": %m",
1536  fclose(fh);
1537  return;
1538  }
1539  }
1540 
1542  {
1543  if (fprintf(fh, "jsonlog %s\n", last_json_file_name) < 0)
1544  {
1545  ereport(LOG,
1547  errmsg("could not write file \"%s\": %m",
1549  fclose(fh);
1550  return;
1551  }
1552  }
1553  fclose(fh);
1554 
1556  ereport(LOG,
1558  errmsg("could not rename file \"%s\" to \"%s\": %m",
1560 }
int pg_mode_mask
Definition: file_perm.c:25
#define fprintf
Definition: port.h:242
#define LOG_METAINFO_DATAFILE_TMP
Definition: syslogger.h:103
#define LOG_METAINFO_DATAFILE
Definition: syslogger.h:102

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

Referenced by logfile_rotate(), and SysLoggerMain().

◆ write_syslogger_file()

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

Definition at line 1093 of file syslogger.c.

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

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

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

Variable Documentation

◆ buffer_lists

List* buffer_lists[NBUFFER_LISTS]
static

Definition at line 110 of file syslogger.c.

Referenced by flush_pipe_input(), and process_pipe_input().

◆ csvlogFile

FILE* csvlogFile = NULL
static

Definition at line 85 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 SysLogger_Start(), and SysLoggerMain().

◆ jsonlogFile

FILE* jsonlogFile = NULL
static

Definition at line 86 of file syslogger.c.

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

◆ 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_json_file_name

char* last_json_file_name = NULL
static

Definition at line 90 of file syslogger.c.

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

◆ last_sys_file_name

char* last_sys_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 76 of file syslogger.c.

Referenced by logfile_open(), and show_log_file_mode().

◆ Log_filename

char* Log_filename = NULL

Definition at line 74 of file syslogger.c.

Referenced by logfile_getname(), and SysLoggerMain().

◆ Log_RotationAge

int Log_RotationAge = HOURS_PER_DAY * MINS_PER_HOUR

Definition at line 71 of file syslogger.c.

Referenced by set_next_rotation_time(), and SysLoggerMain().

◆ Log_RotationSize

int Log_RotationSize = 10 * 1024

Definition at line 72 of file syslogger.c.

Referenced by SysLoggerMain().

◆ Log_truncate_on_rotation

bool Log_truncate_on_rotation = false

Definition at line 75 of file syslogger.c.

Referenced by logfile_rotate_dest().

◆ Logging_collector

bool Logging_collector = false

◆ next_rotation_time

pg_time_t next_rotation_time
static

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

Referenced by SysLoggerMain().

◆ rotation_disabled

bool rotation_disabled = false
static

Definition at line 83 of file syslogger.c.

Referenced by logfile_rotate_dest(), 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 84 of file syslogger.c.

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

◆ syslogPipe

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

Definition at line 114 of file syslogger.c.

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