/*-------------------------------------------------------------------------
 *
 * syslogger.h
 *	  Exports from postmaster/syslogger.c.
 *
 * Copyright (c) 2004-2023, PostgreSQL Global Development Group
 *
 * src/include/postmaster/syslogger.h
 *
 *-------------------------------------------------------------------------
 */
#ifndef _SYSLOGGER_H
#define _SYSLOGGER_H

#include <limits.h>				/* for PIPE_BUF */


/*
 * Primitive protocol structure for writing to syslogger pipe(s).  The idea
 * here is to divide long messages into chunks that are not more than
 * PIPE_BUF bytes long, which according to POSIX spec must be written into
 * the pipe atomically.  The pipe reader then uses the protocol headers to
 * reassemble the parts of a message into a single string.  The reader can
 * also cope with non-protocol data coming down the pipe, though we cannot
 * guarantee long strings won't get split apart.
 *
 * We use non-nul bytes in is_last to make the protocol a tiny bit
 * more robust against finding a false double nul byte prologue. But
 * we still might find it in the len and/or pid bytes unless we're careful.
 */

#ifdef PIPE_BUF
/* Are there any systems with PIPE_BUF > 64K?  Unlikely, but ... */
#if PIPE_BUF > 65536
#define PIPE_CHUNK_SIZE  65536
#else
#define PIPE_CHUNK_SIZE  ((int) PIPE_BUF)
#endif
#else							/* not defined */
/* POSIX says the value of PIPE_BUF must be at least 512, so use that */
#define PIPE_CHUNK_SIZE  512
#endif

typedef struct
{
	char		nuls[2];		/* always \0\0 */
	uint16		len;			/* size of this chunk (counts data only) */
	int32		pid;			/* writer's pid */
	unsigned char stream_id;	/* 0 for core, > 0 for extensions */
	bits8		flags;			/* bitmask of PIPE_PROTO_* */
	char		data[FLEXIBLE_ARRAY_MEMBER];	/* data payload starts here */
} PipeProtoHeader;

typedef union
{
	PipeProtoHeader proto;
	char		filler[PIPE_CHUNK_SIZE];
} PipeProtoChunk;

#define PIPE_HEADER_SIZE  offsetof(PipeProtoHeader, data)
#define PIPE_MAX_PAYLOAD  ((int) (PIPE_CHUNK_SIZE - PIPE_HEADER_SIZE))

/*
 * The maximum number of log streams the syslogger can collect data from.
 *
 * If increasing this, make sure the new value fits in the stream_id field of
 * PipeProtoHeader.
 */
#define MAXLOGSTREAMS 8
/* flag bits for PipeProtoHeader->flags */
#define PIPE_PROTO_IS_LAST	0x01	/* last chunk of message? */
/* log destinations */
#define PIPE_PROTO_DEST_STDERR	0x10
#define PIPE_PROTO_DEST_CSVLOG	0x20
#define PIPE_PROTO_DEST_JSONLOG	0x40

/* GUC options */
extern PGDLLIMPORT bool Logging_collector;
/*
 * Extensions might need the global variables of the following names, as if
 * this was vanilla PG. The following macros are defined to keep such
 * extensions compatible with PGEE.
 */
#define Log_RotationAge				(log_streams[0].rotation_age)
#define Log_RotationSize			(log_streams[0].rotation_size)
#define Log_directory				(log_streams[0].directory)
#define Log_filename				(log_streams[0].filename)
#define Log_truncate_on_rotation	(log_streams[0].truncate_on_rotation)
#define Log_file_mode				(log_streams[0].file_mode)
#define Log_error_verbosity		(log_streams[0].verbosity)
#define Log_line_prefix			(log_streams[0].line_prefix)
#define Log_destination			(log_streams[0].destination)

/*
 * ereport() associates each message with particular stream so that messages
 * from various sources can be logged to separate files. Each stream can
 * actually end up in multiple files, as specified by log destination
 * (LOG_DESTINATION_STDERR, LOG_DESTINATION_CSVLOG, ...).
 */
typedef struct LogStream
{
	/*
	 * The following variables can take their value from the related GUCs.
	 *
	 * The comments below show the corresponding variables in the PG core. The
	 * GUCs first.
	 */
	int			verbosity;		/* Log_error_verbosity */
	int			destination;	/* Log_destination */
	char	   *directory;		/* Log_directory */
	char	   *filename;		/* Log_filename */
	int			file_mode;		/* Log_file_mode */
	int			rotation_age;	/* Log_RotationAge */
	int			rotation_size;	/* Log_RotationSize */
	bool		truncate_on_rotation; /* Log_truncate_on_rotation */
	char	   *line_prefix;		  /* Log_line_prefix */

	char	   *id;

	pg_time_t	next_rotation_time;	  /* next_rotation_time */
	/*
	 * Is rotation needed for reasons other than pg_rotate_logfile() or
	 * "pg_ctl logrotate"? There's no such distinction in the PG core.
	 */
	bool		rotation_needed;
	int			current_rotation_age; /* currentLogRotationAge */
	FILE	   *syslog_file;	/* syslogFile */
#ifdef EXEC_BACKEND
	int			syslog_fd;
	int			csvlog_fd;
	int			jsonlog_fd;
#endif							/* EXEC_BACKEND */
	FILE	   *csvlog_file;	/* csvlogFile */
	FILE	   *jsonlog_file;		 /* jsonlogFile */
	char	   *last_file_name;	/* last_sys_file_name */
	char	   *last_csv_file_name; /* last_csv_file_name */
	char	   *last_json_file_name; /* last_json_file_name */
	char	   *current_dir;		 /* currentLogDir */
	char	   *current_filename;	 /* currentLogFilename */
} LogStream;

#ifdef EXEC_BACKEND
extern bool log_streams_initialized;

/*
 * directory, filename and line_prefix need to be passed in the EXEC_BACKEND
 * case, so store the actual strings, not just pointers. Since there's no size
 * limit on line_prefix, put it at the end of the structure.
 */
typedef struct LogStreamFlat
{
	Size		size;
	int			verbosity;
	int			destination;
	char		directory[MAXPGPATH];
	char		filename[MAXPGPATH];
	char		id[MAXPGPATH];
	int			file_mode;
	int			rotation_age;
	int			rotation_size;
	bool		truncate_on_rotation;

	int			syslog_fd;
	int			csvlog_fd;
	int			jsonlog_fd;

	char		line_prefix[FLEXIBLE_ARRAY_MEMBER];
} LogStreamFlat;

/*
 * The structures are stored w/o alignment, so the next one can immediately
 * follow the end of line_prefix.
 */
#define LOG_STREAM_FLAT_SIZE(s) (offsetof(LogStreamFlat, line_prefix) + \
								 strlen((s)->line_prefix) + 1)
#endif							/* EXEC_BACKEND */

extern PGDLLIMPORT LogStream log_streams[MAXLOGSTREAMS];
extern PGDLLIMPORT int	log_streams_active;

#ifndef WIN32
extern PGDLLIMPORT int	syslogPipe[2];
#else
extern PGDLLIMPORT HANDLE syslogPipe[2];
#endif


extern int	SysLogger_Start(void);

extern void write_syslogger_file(const char *buffer, int count, int destination,
								 int stream_id);
extern int	get_log_stream(char *id, LogStream **stream_p);
extern void init_log_stream_non_gucs(LogStream *stream);

#ifdef EXEC_BACKEND
extern void SysLoggerMain(int argc, char *argv[]) pg_attribute_noreturn();
#endif

extern bool CheckLogrotateSignal(void);
extern void RemoveLogrotateSignalFiles(void);

/*
 * Name of files saving meta-data information about the log
 * files currently in use by the syslogger
 */
#define LOG_METAINFO_DATAFILE  "current_logfiles"
#define LOG_METAINFO_DATAFILE_TMP  LOG_METAINFO_DATAFILE ".tmp"

#endif							/* _SYSLOGGER_H */
