PostgreSQL Source Code  git master
tcopprot.h File Reference
#include "nodes/params.h"
#include "nodes/parsenodes.h"
#include "nodes/plannodes.h"
#include "storage/procsignal.h"
#include "utils/guc.h"
#include "utils/queryenvironment.h"
Include dependency graph for tcopprot.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Macros

#define STACK_DEPTH_SLOP   (512 * 1024L)
 

Enumerations

enum  LogStmtLevel { LOGSTMT_NONE, LOGSTMT_DDL, LOGSTMT_MOD, LOGSTMT_ALL }
 

Functions

Listpg_parse_query (const char *query_string)
 
Listpg_analyze_and_rewrite (RawStmt *parsetree, const char *query_string, Oid *paramTypes, int numParams, QueryEnvironment *queryEnv)
 
Listpg_analyze_and_rewrite_params (RawStmt *parsetree, const char *query_string, ParserSetupHook parserSetup, void *parserSetupArg, QueryEnvironment *queryEnv)
 
PlannedStmtpg_plan_query (Query *querytree, int cursorOptions, ParamListInfo boundParams)
 
Listpg_plan_queries (List *querytrees, int cursorOptions, ParamListInfo boundParams)
 
bool check_max_stack_depth (int *newval, void **extra, GucSource source)
 
void assign_max_stack_depth (int newval, void *extra)
 
void die (SIGNAL_ARGS)
 
void quickdie (SIGNAL_ARGS) pg_attribute_noreturn()
 
void StatementCancelHandler (SIGNAL_ARGS)
 
void FloatExceptionHandler (SIGNAL_ARGS) pg_attribute_noreturn()
 
void RecoveryConflictInterrupt (ProcSignalReason reason)
 
void ProcessClientReadInterrupt (bool blocked)
 
void ProcessClientWriteInterrupt (bool blocked)
 
void process_postgres_switches (int argc, char *argv[], GucContext ctx, const char **dbname)
 
void PostgresMain (int argc, char *argv[], const char *dbname, const char *username) pg_attribute_noreturn()
 
long get_stack_depth_rlimit (void)
 
void ResetUsage (void)
 
void ShowUsage (const char *title)
 
int check_log_duration (char *msec_str, bool was_logged)
 
void set_debug_options (int debug_flag, GucContext context, GucSource source)
 
bool set_plan_disabling_options (const char *arg, GucContext context, GucSource source)
 
const char * get_stats_option_name (const char *arg)
 

Variables

CommandDest whereToSendOutput
 
PGDLLIMPORT const char * debug_query_string
 
int max_stack_depth
 
int PostAuthDelay
 
PGDLLIMPORT int log_statement
 

Macro Definition Documentation

◆ STACK_DEPTH_SLOP

#define STACK_DEPTH_SLOP   (512 * 1024L)

Definition at line 31 of file tcopprot.h.

Referenced by check_max_stack_depth(), and InitializeGUCOptionsFromEnvironment().

Enumeration Type Documentation

◆ LogStmtLevel

Enumerator
LOGSTMT_NONE 
LOGSTMT_DDL 
LOGSTMT_MOD 
LOGSTMT_ALL 

Definition at line 40 of file tcopprot.h.

41 {
42  LOGSTMT_NONE, /* log no statements */
43  LOGSTMT_DDL, /* log data definition statements */
44  LOGSTMT_MOD, /* log modification statements, plus DDL */
45  LOGSTMT_ALL /* log all statements */
46 } LogStmtLevel;
LogStmtLevel
Definition: tcopprot.h:40

Function Documentation

◆ assign_max_stack_depth()

void assign_max_stack_depth ( int  newval,
void *  extra 
)

Definition at line 3230 of file postgres.c.

References max_stack_depth_bytes.

3231 {
3232  long newval_bytes = newval * 1024L;
3233 
3234  max_stack_depth_bytes = newval_bytes;
3235 }
static long max_stack_depth_bytes
Definition: postgres.c:109
#define newval

◆ check_log_duration()

int check_log_duration ( char *  msec_str,
bool  was_logged 
)

Definition at line 2129 of file postgres.c.

References GetCurrentStatementStartTimestamp(), GetCurrentTimestamp(), log_duration, log_min_duration_statement, snprintf(), and TimestampDifference().

Referenced by exec_bind_message(), exec_execute_message(), exec_parse_message(), exec_simple_query(), and HandleFunctionRequest().

2130 {
2132  {
2133  long secs;
2134  int usecs;
2135  int msecs;
2136  bool exceeded;
2137 
2140  &secs, &usecs);
2141  msecs = usecs / 1000;
2142 
2143  /*
2144  * This odd-looking test for log_min_duration_statement being exceeded
2145  * is designed to avoid integer overflow with very long durations:
2146  * don't compute secs * 1000 until we've verified it will fit in int.
2147  */
2148  exceeded = (log_min_duration_statement == 0 ||
2150  (secs > log_min_duration_statement / 1000 ||
2151  secs * 1000 + msecs >= log_min_duration_statement)));
2152 
2153  if (exceeded || log_duration)
2154  {
2155  snprintf(msec_str, 32, "%ld.%03d",
2156  secs * 1000 + msecs, usecs % 1000);
2157  if (exceeded && !was_logged)
2158  return 2;
2159  else
2160  return 1;
2161  }
2162  }
2163 
2164  return 0;
2165 }
int log_min_duration_statement
Definition: guc.c:454
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1570
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
bool log_duration
Definition: guc.c:432
void TimestampDifference(TimestampTz start_time, TimestampTz stop_time, long *secs, int *microsecs)
Definition: timestamp.c:1624
TimestampTz GetCurrentStatementStartTimestamp(void)
Definition: xact.c:710

◆ check_max_stack_depth()

bool check_max_stack_depth ( int *  newval,
void **  extra,
GucSource  source 
)

Definition at line 3213 of file postgres.c.

References get_stack_depth_rlimit(), GUC_check_errdetail, GUC_check_errhint, and STACK_DEPTH_SLOP.

3214 {
3215  long newval_bytes = *newval * 1024L;
3216  long stack_rlimit = get_stack_depth_rlimit();
3217 
3218  if (stack_rlimit > 0 && newval_bytes > stack_rlimit - STACK_DEPTH_SLOP)
3219  {
3220  GUC_check_errdetail("\"max_stack_depth\" must not exceed %ldkB.",
3221  (stack_rlimit - STACK_DEPTH_SLOP) / 1024L);
3222  GUC_check_errhint("Increase the platform's stack depth limit via \"ulimit -s\" or local equivalent.");
3223  return false;
3224  }
3225  return true;
3226 }
#define GUC_check_errdetail
Definition: guc.h:409
long get_stack_depth_rlimit(void)
Definition: postgres.c:4401
#define newval
#define GUC_check_errhint
Definition: guc.h:413
#define STACK_DEPTH_SLOP
Definition: tcopprot.h:31

◆ die()

void die ( SIGNAL_ARGS  )

Definition at line 2652 of file postgres.c.

References DestRemote, DoingCommandRead, InterruptPending, MyLatch, proc_exit_inprogress, ProcDiePending, ProcessInterrupts(), SetLatch(), and whereToSendOutput.

Referenced by ApplyLauncherMain(), ApplyWorkerMain(), autoprewarm_database_main(), AutoVacWorkerMain(), bootstrap_signals(), ParallelWorkerMain(), PostgresMain(), and WalSndSignals().

2653 {
2654  int save_errno = errno;
2655 
2656  /* Don't joggle the elbow of proc_exit */
2657  if (!proc_exit_inprogress)
2658  {
2659  InterruptPending = true;
2660  ProcDiePending = true;
2661  }
2662 
2663  /* If we're still here, waken anything waiting on the process latch */
2664  SetLatch(MyLatch);
2665 
2666  /*
2667  * If we're in single user mode, we want to quit immediately - we can't
2668  * rely on latches as they wouldn't work when stdin/stdout is a file.
2669  * Rather ugly, but it's unlikely to be worthwhile to invest much more
2670  * effort just for the benefit of single user mode.
2671  */
2674 
2675  errno = save_errno;
2676 }
void ProcessInterrupts(void)
Definition: postgres.c:2860
volatile bool InterruptPending
Definition: globals.c:29
void SetLatch(volatile Latch *latch)
Definition: latch.c:414
bool proc_exit_inprogress
Definition: ipc.c:40
static bool DoingCommandRead
Definition: postgres.c:137
volatile bool ProcDiePending
Definition: globals.c:31
struct Latch * MyLatch
Definition: globals.c:52
CommandDest whereToSendOutput
Definition: postgres.c:88

◆ FloatExceptionHandler()

void FloatExceptionHandler ( SIGNAL_ARGS  )

Definition at line 2704 of file postgres.c.

References ereport, errcode(), errdetail(), errmsg(), and ERROR.

Referenced by AutoVacLauncherMain(), AutoVacWorkerMain(), plperl_init_interp(), PostgresMain(), and StartBackgroundWorker().

2705 {
2706  /* We're not returning, so no need to save errno */
2707  ereport(ERROR,
2708  (errcode(ERRCODE_FLOATING_POINT_EXCEPTION),
2709  errmsg("floating-point exception"),
2710  errdetail("An invalid floating-point operation was signaled. "
2711  "This probably means an out-of-range result or an "
2712  "invalid operation, such as division by zero.")));
2713 }
int errcode(int sqlerrcode)
Definition: elog.c:575
#define ERROR
Definition: elog.h:43
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define ereport(elevel, rest)
Definition: elog.h:122
int errmsg(const char *fmt,...)
Definition: elog.c:797

◆ get_stack_depth_rlimit()

long get_stack_depth_rlimit ( void  )

Definition at line 4401 of file postgres.c.

References val.

Referenced by check_max_stack_depth(), and InitializeGUCOptionsFromEnvironment().

4402 {
4403 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_STACK)
4404  static long val = 0;
4405 
4406  /* This won't change after process launch, so check just once */
4407  if (val == 0)
4408  {
4409  struct rlimit rlim;
4410 
4411  if (getrlimit(RLIMIT_STACK, &rlim) < 0)
4412  val = -1;
4413  else if (rlim.rlim_cur == RLIM_INFINITY)
4414  val = LONG_MAX;
4415  /* rlim_cur is probably of an unsigned type, so check for overflow */
4416  else if (rlim.rlim_cur >= LONG_MAX)
4417  val = LONG_MAX;
4418  else
4419  val = rlim.rlim_cur;
4420  }
4421  return val;
4422 #else /* no getrlimit */
4423 #if defined(WIN32) || defined(__CYGWIN__)
4424  /* On Windows we set the backend stack size in src/backend/Makefile */
4425  return WIN32_STACK_RLIMIT;
4426 #else /* not windows ... give up */
4427  return -1;
4428 #endif
4429 #endif
4430 }
long val
Definition: informix.c:689

◆ get_stats_option_name()

const char* get_stats_option_name ( const char *  arg)

Definition at line 3316 of file postgres.c.

References optarg.

Referenced by PostmasterMain(), and process_postgres_switches().

3317 {
3318  switch (arg[0])
3319  {
3320  case 'p':
3321  if (optarg[1] == 'a') /* "parser" */
3322  return "log_parser_stats";
3323  else if (optarg[1] == 'l') /* "planner" */
3324  return "log_planner_stats";
3325  break;
3326 
3327  case 'e': /* "executor" */
3328  return "log_executor_stats";
3329  break;
3330  }
3331 
3332  return NULL;
3333 }
char * optarg
Definition: getopt.c:53
void * arg

◆ pg_analyze_and_rewrite()

List* pg_analyze_and_rewrite ( RawStmt parsetree,
const char *  query_string,
Oid paramTypes,
int  numParams,
QueryEnvironment queryEnv 
)

Definition at line 649 of file postgres.c.

References log_parser_stats, parse_analyze(), pg_rewrite_query(), ResetUsage(), and ShowUsage().

Referenced by _SPI_execute_plan(), _SPI_prepare_plan(), BeginCopy(), exec_simple_query(), execute_sql_string(), and RevalidateCachedQuery().

652 {
653  Query *query;
654  List *querytree_list;
655 
656  TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
657 
658  /*
659  * (1) Perform parse analysis.
660  */
661  if (log_parser_stats)
662  ResetUsage();
663 
664  query = parse_analyze(parsetree, query_string, paramTypes, numParams,
665  queryEnv);
666 
667  if (log_parser_stats)
668  ShowUsage("PARSE ANALYSIS STATISTICS");
669 
670  /*
671  * (2) Rewrite the queries, as necessary
672  */
673  querytree_list = pg_rewrite_query(query);
674 
675  TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
676 
677  return querytree_list;
678 }
bool log_parser_stats
Definition: guc.c:438
void ShowUsage(const char *title)
Definition: postgres.c:4444
void ResetUsage(void)
Definition: postgres.c:4437
static List * pg_rewrite_query(Query *query)
Definition: postgres.c:738
Query * parse_analyze(RawStmt *parseTree, const char *sourceText, Oid *paramTypes, int numParams, QueryEnvironment *queryEnv)
Definition: analyze.c:96
Definition: pg_list.h:45

◆ pg_analyze_and_rewrite_params()

List* pg_analyze_and_rewrite_params ( RawStmt parsetree,
const char *  query_string,
ParserSetupHook  parserSetup,
void *  parserSetupArg,
QueryEnvironment queryEnv 
)

Definition at line 686 of file postgres.c.

References Assert, free_parsestate(), log_parser_stats, make_parsestate(), ParseState::p_queryEnv, ParseState::p_sourcetext, pg_rewrite_query(), post_parse_analyze_hook, ResetUsage(), ShowUsage(), and transformTopLevelStmt().

Referenced by _SPI_execute_plan(), _SPI_prepare_plan(), fmgr_sql_validator(), init_sql_fcache(), inline_set_returning_function(), and RevalidateCachedQuery().

691 {
692  ParseState *pstate;
693  Query *query;
694  List *querytree_list;
695 
696  Assert(query_string != NULL); /* required as of 8.4 */
697 
698  TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
699 
700  /*
701  * (1) Perform parse analysis.
702  */
703  if (log_parser_stats)
704  ResetUsage();
705 
706  pstate = make_parsestate(NULL);
707  pstate->p_sourcetext = query_string;
708  pstate->p_queryEnv = queryEnv;
709  (*parserSetup) (pstate, parserSetupArg);
710 
711  query = transformTopLevelStmt(pstate, parsetree);
712 
714  (*post_parse_analyze_hook) (pstate, query);
715 
716  free_parsestate(pstate);
717 
718  if (log_parser_stats)
719  ShowUsage("PARSE ANALYSIS STATISTICS");
720 
721  /*
722  * (2) Rewrite the queries, as necessary
723  */
724  querytree_list = pg_rewrite_query(query);
725 
726  TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
727 
728  return querytree_list;
729 }
bool log_parser_stats
Definition: guc.c:438
QueryEnvironment * p_queryEnv
Definition: parse_node.h:196
void ShowUsage(const char *title)
Definition: postgres.c:4444
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
void ResetUsage(void)
Definition: postgres.c:4437
const char * p_sourcetext
Definition: parse_node.h:172
static List * pg_rewrite_query(Query *query)
Definition: postgres.c:738
#define Assert(condition)
Definition: c.h:680
Query * transformTopLevelStmt(ParseState *pstate, RawStmt *parseTree)
Definition: analyze.c:187
void free_parsestate(ParseState *pstate)
Definition: parse_node.c:77
Definition: pg_list.h:45
post_parse_analyze_hook_type post_parse_analyze_hook
Definition: analyze.c:49

◆ pg_parse_query()

List* pg_parse_query ( const char *  query_string)

Definition at line 607 of file postgres.c.

References copyObject, elog, equal(), log_parser_stats, new_list(), raw_parser(), ResetUsage(), ShowUsage(), and WARNING.

Referenced by _SPI_prepare_oneshot_plan(), _SPI_prepare_plan(), exec_parse_message(), exec_simple_query(), execute_sql_string(), fmgr_sql_validator(), ImportForeignSchema(), init_sql_fcache(), inline_function(), and inline_set_returning_function().

608 {
609  List *raw_parsetree_list;
610 
611  TRACE_POSTGRESQL_QUERY_PARSE_START(query_string);
612 
613  if (log_parser_stats)
614  ResetUsage();
615 
616  raw_parsetree_list = raw_parser(query_string);
617 
618  if (log_parser_stats)
619  ShowUsage("PARSER STATISTICS");
620 
621 #ifdef COPY_PARSE_PLAN_TREES
622  /* Optional debugging check: pass raw parsetrees through copyObject() */
623  {
624  List *new_list = copyObject(raw_parsetree_list);
625 
626  /* This checks both copyObject() and the equal() routines... */
627  if (!equal(new_list, raw_parsetree_list))
628  elog(WARNING, "copyObject() failed to produce an equal raw parse tree");
629  else
630  raw_parsetree_list = new_list;
631  }
632 #endif
633 
634  TRACE_POSTGRESQL_QUERY_PARSE_DONE(query_string);
635 
636  return raw_parsetree_list;
637 }
List * raw_parser(const char *str)
Definition: parser.c:36
bool log_parser_stats
Definition: guc.c:438
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:2984
void ShowUsage(const char *title)
Definition: postgres.c:4444
static List * new_list(NodeTag type)
Definition: list.c:63
void ResetUsage(void)
Definition: postgres.c:4437
#define WARNING
Definition: elog.h:40
#define elog
Definition: elog.h:219
#define copyObject(obj)
Definition: nodes.h:625
Definition: pg_list.h:45

◆ pg_plan_queries()

List* pg_plan_queries ( List querytrees,
int  cursorOptions,
ParamListInfo  boundParams 
)

Definition at line 851 of file postgres.c.

References PlannedStmt::canSetTag, Query::canSetTag, CMD_UTILITY, PlannedStmt::commandType, Query::commandType, lappend(), lfirst_node, makeNode, NIL, pg_plan_query(), PlannedStmt::stmt_len, Query::stmt_len, PlannedStmt::stmt_location, Query::stmt_location, PlannedStmt::utilityStmt, and Query::utilityStmt.

Referenced by BuildCachedPlan(), exec_simple_query(), and execute_sql_string().

852 {
853  List *stmt_list = NIL;
854  ListCell *query_list;
855 
856  foreach(query_list, querytrees)
857  {
858  Query *query = lfirst_node(Query, query_list);
859  PlannedStmt *stmt;
860 
861  if (query->commandType == CMD_UTILITY)
862  {
863  /* Utility commands require no planning. */
864  stmt = makeNode(PlannedStmt);
865  stmt->commandType = CMD_UTILITY;
866  stmt->canSetTag = query->canSetTag;
867  stmt->utilityStmt = query->utilityStmt;
868  stmt->stmt_location = query->stmt_location;
869  stmt->stmt_len = query->stmt_len;
870  }
871  else
872  {
873  stmt = pg_plan_query(query, cursorOptions, boundParams);
874  }
875 
876  stmt_list = lappend(stmt_list, stmt);
877  }
878 
879  return stmt_list;
880 }
#define NIL
Definition: pg_list.h:69
int stmt_location
Definition: parsenodes.h:179
Node * utilityStmt
Definition: parsenodes.h:118
int stmt_len
Definition: plannodes.h:98
#define lfirst_node(type, lc)
Definition: pg_list.h:109
int stmt_location
Definition: plannodes.h:97
Node * utilityStmt
Definition: plannodes.h:94
List * lappend(List *list, void *datum)
Definition: list.c:128
bool canSetTag
Definition: plannodes.h:53
CmdType commandType
Definition: plannodes.h:45
CmdType commandType
Definition: parsenodes.h:110
#define makeNode(_type_)
Definition: nodes.h:560
bool canSetTag
Definition: parsenodes.h:116
Definition: pg_list.h:45
int stmt_len
Definition: parsenodes.h:180
PlannedStmt * pg_plan_query(Query *querytree, int cursorOptions, ParamListInfo boundParams)
Definition: postgres.c:790

◆ pg_plan_query()

PlannedStmt* pg_plan_query ( Query querytree,
int  cursorOptions,
ParamListInfo  boundParams 
)

Definition at line 790 of file postgres.c.

References ActiveSnapshotSet(), Assert, CMD_UTILITY, Query::commandType, copyObject, Debug_pretty_print, Debug_print_plan, elog, elog_node_display(), equal(), LOG, log_planner_stats, planner(), ResetUsage(), ShowUsage(), and WARNING.

Referenced by BeginCopy(), ExecCreateTableAs(), ExplainOneQuery(), init_execution_state(), PerformCursorOpen(), pg_plan_queries(), and refresh_matview_datafill().

791 {
792  PlannedStmt *plan;
793 
794  /* Utility commands have no plans. */
795  if (querytree->commandType == CMD_UTILITY)
796  return NULL;
797 
798  /* Planner must have a snapshot in case it calls user-defined functions. */
800 
801  TRACE_POSTGRESQL_QUERY_PLAN_START();
802 
803  if (log_planner_stats)
804  ResetUsage();
805 
806  /* call the optimizer */
807  plan = planner(querytree, cursorOptions, boundParams);
808 
809  if (log_planner_stats)
810  ShowUsage("PLANNER STATISTICS");
811 
812 #ifdef COPY_PARSE_PLAN_TREES
813  /* Optional debugging check: pass plan output through copyObject() */
814  {
815  PlannedStmt *new_plan = copyObject(plan);
816 
817  /*
818  * equal() currently does not have routines to compare Plan nodes, so
819  * don't try to test equality here. Perhaps fix someday?
820  */
821 #ifdef NOT_USED
822  /* This checks both copyObject() and the equal() routines... */
823  if (!equal(new_plan, plan))
824  elog(WARNING, "copyObject() failed to produce an equal plan tree");
825  else
826 #endif
827  plan = new_plan;
828  }
829 #endif
830 
831  /*
832  * Print plan if debugging.
833  */
834  if (Debug_print_plan)
835  elog_node_display(LOG, "plan", plan, Debug_pretty_print);
836 
837  TRACE_POSTGRESQL_QUERY_PLAN_DONE();
838 
839  return plan;
840 }
void elog_node_display(int lev, const char *title, const void *obj, bool pretty)
Definition: print.c:71
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:2984
void ShowUsage(const char *title)
Definition: postgres.c:4444
#define LOG
Definition: elog.h:26
PlannedStmt * planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
Definition: planner.c:204
void ResetUsage(void)
Definition: postgres.c:4437
bool Debug_print_plan
Definition: guc.c:433
bool ActiveSnapshotSet(void)
Definition: snapmgr.c:851
#define WARNING
Definition: elog.h:40
CmdType commandType
Definition: parsenodes.h:110
#define Assert(condition)
Definition: c.h:680
bool Debug_pretty_print
Definition: guc.c:436
#define elog
Definition: elog.h:219
#define copyObject(obj)
Definition: nodes.h:625
bool log_planner_stats
Definition: guc.c:439

◆ PostgresMain()

void PostgresMain ( int  argc,
char *  argv[],
const char *  dbname,
const char *  username 
)

Definition at line 3615 of file postgres.c.

References AbortCurrentTransaction(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, am_walsender, Assert, BaseInit(), BeginReportingGUCOptions(), BlockSig, buf, ChangeToDataDir(), CHECK_FOR_INTERRUPTS, ConfigReloadPending, CreateDataDirLockFile(), DataDir, debug_query_string, DestDebug, DestNone, DestRemote, die(), disable_all_timeouts(), disable_timeout(), doing_extended_query_message, DoingCommandRead, drop_unnamed_stmt(), DropPreparedStatement(), EmitErrorReport(), enable_timeout_after(), ereport, errcode(), errmsg(), ERROR, error_context_stack, exec_bind_message(), exec_describe_portal_message(), exec_describe_statement_message(), exec_execute_message(), exec_parse_message(), exec_replication_command(), exec_simple_query(), FATAL, finish_xact_command(), FloatExceptionHandler(), FlushErrorState(), forbidden_in_wal_sender(), GetCurrentTimestamp(), GetPortalByName(), HandleFunctionRequest(), HOLD_INTERRUPTS, i, IDLE_IN_TRANSACTION_SESSION_TIMEOUT, IdleInTransactionSessionTimeout, ignore_till_sync, InitializeGUCOptions(), InitializeMaxBackends(), InitializeTimeouts(), InitPostgres(), InitProcess(), InitProcessing, InitStandaloneProcess(), initStringInfo(), InitWalSender(), InvalidateCatalogSnapshotConditionally(), InvalidOid, IsAbortedTransactionBlockState(), IsTransactionOrTransactionBlock(), IsUnderPostmaster, LocalProcessControlFile(), Log_disconnections, log_disconnections(), MemoryContextDelete(), MemoryContextResetAndDeleteChildren, MemoryContextSwitchTo(), MessageContext, MyCancelKey, MyProcPid, MyReplicationSlot, NormalProcessing, on_proc_exit(), palloc(), PG_exception_stack, PG_SETMASK, PGC_POSTMASTER, PGC_SIGHUP, PgStartTime, pgstat_report_activity(), pgstat_report_stat(), PortalDrop(), PortalIsValid, PostgresSigHupHandler(), PostmasterContext, pq_beginmessage(), pq_comm_reset, pq_endmessage(), pq_flush, pq_getmsgbyte(), pq_getmsgend(), pq_getmsgint(), pq_getmsgstring(), pq_is_reading_msg(), pq_putemptymessage(), pq_sendint32(), pqinitmask(), pqsignal(), proc_exit(), process_postgres_switches(), process_session_preload_libraries(), ProcessCompletedNotifies(), ProcessConfigFile(), procsignal_sigusr1_handler(), progname, QueryCancelPending, quickdie(), ReadCommand(), ReadyForQuery(), ReplicationSlotCleanup(), ReplicationSlotRelease(), RESUME_INTERRUPTS, SelectConfigFiles(), set_ps_display(), SetCurrentStatementStartTimestamp(), SetProcessingMode, SIG_DFL, SIG_IGN, SIGCHLD, SIGHUP, SIGPIPE, SIGQUIT, SIGUSR1, SIGUSR2, start_xact_command(), STATE_FASTPATH, STATE_IDLE, STATE_IDLEINTRANSACTION, STATE_IDLEINTRANSACTION_ABORTED, StatementCancelHandler(), TopMemoryContext, UnBlockSig, userDoption, username, ValidatePgVersion(), WalSndErrorCleanup(), WalSndSignals(), whereToSendOutput, and xact_started.

Referenced by BackendRun(), and main().

3618 {
3619  int firstchar;
3620  StringInfoData input_message;
3621  sigjmp_buf local_sigjmp_buf;
3622  volatile bool send_ready_for_query = true;
3623  bool disable_idle_in_transaction_timeout = false;
3624 
3625  /* Initialize startup process environment if necessary. */
3626  if (!IsUnderPostmaster)
3627  InitStandaloneProcess(argv[0]);
3628 
3630 
3631  /*
3632  * Set default values for command-line options.
3633  */
3634  if (!IsUnderPostmaster)
3636 
3637  /*
3638  * Parse command-line options.
3639  */
3641 
3642  /* Must have gotten a database name, or have a default (the username) */
3643  if (dbname == NULL)
3644  {
3645  dbname = username;
3646  if (dbname == NULL)
3647  ereport(FATAL,
3648  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3649  errmsg("%s: no database nor user name specified",
3650  progname)));
3651  }
3652 
3653  /* Acquire configuration parameters, unless inherited from postmaster */
3654  if (!IsUnderPostmaster)
3655  {
3657  proc_exit(1);
3658  }
3659 
3660  /*
3661  * Set up signal handlers and masks.
3662  *
3663  * Note that postmaster blocked all signals before forking child process,
3664  * so there is no race condition whereby we might receive a signal before
3665  * we have set up the handler.
3666  *
3667  * Also note: it's best not to use any signals that are SIG_IGNored in the
3668  * postmaster. If such a signal arrives before we are able to change the
3669  * handler to non-SIG_IGN, it'll get dropped. Instead, make a dummy
3670  * handler in the postmaster to reserve the signal. (Of course, this isn't
3671  * an issue for signals that are locally generated, such as SIGALRM and
3672  * SIGPIPE.)
3673  */
3674  if (am_walsender)
3675  WalSndSignals();
3676  else
3677  {
3678  pqsignal(SIGHUP, PostgresSigHupHandler); /* set flag to read config
3679  * file */
3680  pqsignal(SIGINT, StatementCancelHandler); /* cancel current query */
3681  pqsignal(SIGTERM, die); /* cancel current query and exit */
3682 
3683  /*
3684  * In a standalone backend, SIGQUIT can be generated from the keyboard
3685  * easily, while SIGTERM cannot, so we make both signals do die()
3686  * rather than quickdie().
3687  */
3688  if (IsUnderPostmaster)
3689  pqsignal(SIGQUIT, quickdie); /* hard crash time */
3690  else
3691  pqsignal(SIGQUIT, die); /* cancel current query and exit */
3692  InitializeTimeouts(); /* establishes SIGALRM handler */
3693 
3694  /*
3695  * Ignore failure to write to frontend. Note: if frontend closes
3696  * connection, we will notice it and exit cleanly when control next
3697  * returns to outer loop. This seems safer than forcing exit in the
3698  * midst of output during who-knows-what operation...
3699  */
3704 
3705  /*
3706  * Reset some signals that are accepted by postmaster but not by
3707  * backend
3708  */
3709  pqsignal(SIGCHLD, SIG_DFL); /* system() requires this on some
3710  * platforms */
3711  }
3712 
3713  pqinitmask();
3714 
3715  if (IsUnderPostmaster)
3716  {
3717  /* We allow SIGQUIT (quickdie) at all times */
3718  sigdelset(&BlockSig, SIGQUIT);
3719  }
3720 
3721  PG_SETMASK(&BlockSig); /* block everything except SIGQUIT */
3722 
3723  if (!IsUnderPostmaster)
3724  {
3725  /*
3726  * Validate we have been given a reasonable-looking DataDir (if under
3727  * postmaster, assume postmaster did this already).
3728  */
3729  Assert(DataDir);
3731 
3732  /* Change into DataDir (if under postmaster, was done already) */
3733  ChangeToDataDir();
3734 
3735  /*
3736  * Create lockfile for data directory.
3737  */
3738  CreateDataDirLockFile(false);
3739 
3740  /* read control file (error checking and contains config ) */
3741  LocalProcessControlFile(false);
3742 
3743  /* Initialize MaxBackends (if under postmaster, was done already) */
3745  }
3746 
3747  /* Early initialization */
3748  BaseInit();
3749 
3750  /*
3751  * Create a per-backend PGPROC struct in shared memory, except in the
3752  * EXEC_BACKEND case where this was done in SubPostmasterMain. We must do
3753  * this before we can use LWLocks (and in the EXEC_BACKEND case we already
3754  * had to do some stuff with LWLocks).
3755  */
3756 #ifdef EXEC_BACKEND
3757  if (!IsUnderPostmaster)
3758  InitProcess();
3759 #else
3760  InitProcess();
3761 #endif
3762 
3763  /* We need to allow SIGINT, etc during the initial transaction */
3765 
3766  /*
3767  * General initialization.
3768  *
3769  * NOTE: if you are tempted to add code in this vicinity, consider putting
3770  * it inside InitPostgres() instead. In particular, anything that
3771  * involves database access should be there, not here.
3772  */
3774 
3775  /*
3776  * If the PostmasterContext is still around, recycle the space; we don't
3777  * need it anymore after InitPostgres completes. Note this does not trash
3778  * *MyProcPort, because ConnCreate() allocated that space with malloc()
3779  * ... else we'd need to copy the Port data first. Also, subsidiary data
3780  * such as the username isn't lost either; see ProcessStartupPacket().
3781  */
3782  if (PostmasterContext)
3783  {
3785  PostmasterContext = NULL;
3786  }
3787 
3789 
3790  /*
3791  * Now all GUC states are fully set up. Report them to client if
3792  * appropriate.
3793  */
3795 
3796  /*
3797  * Also set up handler to log session end; we have to wait till now to be
3798  * sure Log_disconnections has its final value.
3799  */
3802 
3803  /* Perform initialization specific to a WAL sender process. */
3804  if (am_walsender)
3805  InitWalSender();
3806 
3807  /*
3808  * process any libraries that should be preloaded at backend start (this
3809  * likewise can't be done until GUC settings are complete)
3810  */
3812 
3813  /*
3814  * Send this backend's cancellation info to the frontend.
3815  */
3817  {
3819 
3820  pq_beginmessage(&buf, 'K');
3821  pq_sendint32(&buf, (int32) MyProcPid);
3822  pq_sendint32(&buf, (int32) MyCancelKey);
3823  pq_endmessage(&buf);
3824  /* Need not flush since ReadyForQuery will do it. */
3825  }
3826 
3827  /* Welcome banner for standalone case */
3829  printf("\nPostgreSQL stand-alone backend %s\n", PG_VERSION);
3830 
3831  /*
3832  * Create the memory context we will use in the main loop.
3833  *
3834  * MessageContext is reset once per iteration of the main loop, ie, upon
3835  * completion of processing of each command message from the client.
3836  */
3838  "MessageContext",
3840 
3841  /*
3842  * Create memory context and buffer used for RowDescription messages. As
3843  * SendRowDescriptionMessage(), via exec_describe_statement_message(), is
3844  * frequently executed for ever single statement, we don't want to
3845  * allocate a separate buffer every time.
3846  */
3848  "RowDescriptionContext",
3853 
3854  /*
3855  * Remember stand-alone backend startup time
3856  */
3857  if (!IsUnderPostmaster)
3859 
3860  /*
3861  * POSTGRES main processing loop begins here
3862  *
3863  * If an exception is encountered, processing resumes here so we abort the
3864  * current transaction and start a new one.
3865  *
3866  * You might wonder why this isn't coded as an infinite loop around a
3867  * PG_TRY construct. The reason is that this is the bottom of the
3868  * exception stack, and so with PG_TRY there would be no exception handler
3869  * in force at all during the CATCH part. By leaving the outermost setjmp
3870  * always active, we have at least some chance of recovering from an error
3871  * during error recovery. (If we get into an infinite loop thereby, it
3872  * will soon be stopped by overflow of elog.c's internal state stack.)
3873  *
3874  * Note that we use sigsetjmp(..., 1), so that this function's signal mask
3875  * (to wit, UnBlockSig) will be restored when longjmp'ing to here. This
3876  * is essential in case we longjmp'd out of a signal handler on a platform
3877  * where that leaves the signal blocked. It's not redundant with the
3878  * unblock in AbortTransaction() because the latter is only called if we
3879  * were inside a transaction.
3880  */
3881 
3882  if (sigsetjmp(local_sigjmp_buf, 1) != 0)
3883  {
3884  /*
3885  * NOTE: if you are tempted to add more code in this if-block,
3886  * consider the high probability that it should be in
3887  * AbortTransaction() instead. The only stuff done directly here
3888  * should be stuff that is guaranteed to apply *only* for outer-level
3889  * error recovery, such as adjusting the FE/BE protocol status.
3890  */
3891 
3892  /* Since not using PG_TRY, must reset error stack by hand */
3893  error_context_stack = NULL;
3894 
3895  /* Prevent interrupts while cleaning up */
3896  HOLD_INTERRUPTS();
3897 
3898  /*
3899  * Forget any pending QueryCancel request, since we're returning to
3900  * the idle loop anyway, and cancel any active timeout requests. (In
3901  * future we might want to allow some timeout requests to survive, but
3902  * at minimum it'd be necessary to do reschedule_timeouts(), in case
3903  * we got here because of a query cancel interrupting the SIGALRM
3904  * interrupt handler.) Note in particular that we must clear the
3905  * statement and lock timeout indicators, to prevent any future plain
3906  * query cancels from being misreported as timeouts in case we're
3907  * forgetting a timeout cancel.
3908  */
3909  disable_all_timeouts(false);
3910  QueryCancelPending = false; /* second to avoid race condition */
3911 
3912  /* Not reading from the client anymore. */
3913  DoingCommandRead = false;
3914 
3915  /* Make sure libpq is in a good state */
3916  pq_comm_reset();
3917 
3918  /* Report the error to the client and/or server log */
3919  EmitErrorReport();
3920 
3921  /*
3922  * Make sure debug_query_string gets reset before we possibly clobber
3923  * the storage it points at.
3924  */
3925  debug_query_string = NULL;
3926 
3927  /*
3928  * Abort the current transaction in order to recover.
3929  */
3931 
3932  if (am_walsender)
3934 
3935  /*
3936  * We can't release replication slots inside AbortTransaction() as we
3937  * need to be able to start and abort transactions while having a slot
3938  * acquired. But we never need to hold them across top level errors,
3939  * so releasing here is fine. There's another cleanup in ProcKill()
3940  * ensuring we'll correctly cleanup on FATAL errors as well.
3941  */
3942  if (MyReplicationSlot != NULL)
3944 
3945  /* We also want to cleanup temporary slots on error. */
3947 
3948  /*
3949  * Now return to normal top-level context and clear ErrorContext for
3950  * next time.
3951  */
3953  FlushErrorState();
3954 
3955  /*
3956  * If we were handling an extended-query-protocol message, initiate
3957  * skip till next Sync. This also causes us not to issue
3958  * ReadyForQuery (until we get Sync).
3959  */
3961  ignore_till_sync = true;
3962 
3963  /* We don't have a transaction command open anymore */
3964  xact_started = false;
3965 
3966  /*
3967  * If an error occurred while we were reading a message from the
3968  * client, we have potentially lost track of where the previous
3969  * message ends and the next one begins. Even though we have
3970  * otherwise recovered from the error, we cannot safely read any more
3971  * messages from the client, so there isn't much we can do with the
3972  * connection anymore.
3973  */
3974  if (pq_is_reading_msg())
3975  ereport(FATAL,
3976  (errcode(ERRCODE_PROTOCOL_VIOLATION),
3977  errmsg("terminating connection because protocol synchronization was lost")));
3978 
3979  /* Now we can allow interrupts again */
3981  }
3982 
3983  /* We can now handle ereport(ERROR) */
3984  PG_exception_stack = &local_sigjmp_buf;
3985 
3986  if (!ignore_till_sync)
3987  send_ready_for_query = true; /* initially, or after error */
3988 
3989  /*
3990  * Non-error queries loop here.
3991  */
3992 
3993  for (;;)
3994  {
3995  /*
3996  * At top of loop, reset extended-query-message flag, so that any
3997  * errors encountered in "idle" state don't provoke skip.
3998  */
4000 
4001  /*
4002  * Release storage left over from prior query cycle, and create a new
4003  * query input buffer in the cleared MessageContext.
4004  */
4007 
4008  initStringInfo(&input_message);
4009 
4010  /*
4011  * Also consider releasing our catalog snapshot if any, so that it's
4012  * not preventing advance of global xmin while we wait for the client.
4013  */
4015 
4016  /*
4017  * (1) If we've reached idle state, tell the frontend we're ready for
4018  * a new query.
4019  *
4020  * Note: this includes fflush()'ing the last of the prior output.
4021  *
4022  * This is also a good time to send collected statistics to the
4023  * collector, and to update the PS stats display. We avoid doing
4024  * those every time through the message loop because it'd slow down
4025  * processing of batched messages, and because we don't want to report
4026  * uncommitted updates (that confuses autovacuum). The notification
4027  * processor wants a call too, if we are not in a transaction block.
4028  */
4029  if (send_ready_for_query)
4030  {
4032  {
4033  set_ps_display("idle in transaction (aborted)", false);
4035 
4036  /* Start the idle-in-transaction timer */
4038  {
4039  disable_idle_in_transaction_timeout = true;
4042  }
4043  }
4045  {
4046  set_ps_display("idle in transaction", false);
4048 
4049  /* Start the idle-in-transaction timer */
4051  {
4052  disable_idle_in_transaction_timeout = true;
4055  }
4056  }
4057  else
4058  {
4060  pgstat_report_stat(false);
4061 
4062  set_ps_display("idle", false);
4064  }
4065 
4067  send_ready_for_query = false;
4068  }
4069 
4070  /*
4071  * (2) Allow asynchronous signals to be executed immediately if they
4072  * come in while we are waiting for client input. (This must be
4073  * conditional since we don't want, say, reads on behalf of COPY FROM
4074  * STDIN doing the same thing.)
4075  */
4076  DoingCommandRead = true;
4077 
4078  /*
4079  * (3) read a command (loop blocks here)
4080  */
4081  firstchar = ReadCommand(&input_message);
4082 
4083  /*
4084  * (4) disable async signal conditions again.
4085  *
4086  * Query cancel is supposed to be a no-op when there is no query in
4087  * progress, so if a query cancel arrived while we were idle, just
4088  * reset QueryCancelPending. ProcessInterrupts() has that effect when
4089  * it's called when DoingCommandRead is set, so check for interrupts
4090  * before resetting DoingCommandRead.
4091  */
4093  DoingCommandRead = false;
4094 
4095  /*
4096  * (5) turn off the idle-in-transaction timeout
4097  */
4098  if (disable_idle_in_transaction_timeout)
4099  {
4101  disable_idle_in_transaction_timeout = false;
4102  }
4103 
4104  /*
4105  * (6) check for any other interesting events that happened while we
4106  * slept.
4107  */
4108  if (ConfigReloadPending)
4109  {
4110  ConfigReloadPending = false;
4112  }
4113 
4114  /*
4115  * (7) process the command. But ignore it if we're skipping till
4116  * Sync.
4117  */
4118  if (ignore_till_sync && firstchar != EOF)
4119  continue;
4120 
4121  switch (firstchar)
4122  {
4123  case 'Q': /* simple query */
4124  {
4125  const char *query_string;
4126 
4127  /* Set statement_timestamp() */
4129 
4130  query_string = pq_getmsgstring(&input_message);
4131  pq_getmsgend(&input_message);
4132 
4133  if (am_walsender)
4134  {
4135  if (!exec_replication_command(query_string))
4136  exec_simple_query(query_string);
4137  }
4138  else
4139  exec_simple_query(query_string);
4140 
4141  send_ready_for_query = true;
4142  }
4143  break;
4144 
4145  case 'P': /* parse */
4146  {
4147  const char *stmt_name;
4148  const char *query_string;
4149  int numParams;
4150  Oid *paramTypes = NULL;
4151 
4152  forbidden_in_wal_sender(firstchar);
4153 
4154  /* Set statement_timestamp() */
4156 
4157  stmt_name = pq_getmsgstring(&input_message);
4158  query_string = pq_getmsgstring(&input_message);
4159  numParams = pq_getmsgint(&input_message, 2);
4160  if (numParams > 0)
4161  {
4162  int i;
4163 
4164  paramTypes = (Oid *) palloc(numParams * sizeof(Oid));
4165  for (i = 0; i < numParams; i++)
4166  paramTypes[i] = pq_getmsgint(&input_message, 4);
4167  }
4168  pq_getmsgend(&input_message);
4169 
4170  exec_parse_message(query_string, stmt_name,
4171  paramTypes, numParams);
4172  }
4173  break;
4174 
4175  case 'B': /* bind */
4176  forbidden_in_wal_sender(firstchar);
4177 
4178  /* Set statement_timestamp() */
4180 
4181  /*
4182  * this message is complex enough that it seems best to put
4183  * the field extraction out-of-line
4184  */
4185  exec_bind_message(&input_message);
4186  break;
4187 
4188  case 'E': /* execute */
4189  {
4190  const char *portal_name;
4191  int max_rows;
4192 
4193  forbidden_in_wal_sender(firstchar);
4194 
4195  /* Set statement_timestamp() */
4197 
4198  portal_name = pq_getmsgstring(&input_message);
4199  max_rows = pq_getmsgint(&input_message, 4);
4200  pq_getmsgend(&input_message);
4201 
4202  exec_execute_message(portal_name, max_rows);
4203  }
4204  break;
4205 
4206  case 'F': /* fastpath function call */
4207  forbidden_in_wal_sender(firstchar);
4208 
4209  /* Set statement_timestamp() */
4211 
4212  /* Report query to various monitoring facilities. */
4214  set_ps_display("<FASTPATH>", false);
4215 
4216  /* start an xact for this function invocation */
4218 
4219  /*
4220  * Note: we may at this point be inside an aborted
4221  * transaction. We can't throw error for that until we've
4222  * finished reading the function-call message, so
4223  * HandleFunctionRequest() must check for it after doing so.
4224  * Be careful not to do anything that assumes we're inside a
4225  * valid transaction here.
4226  */
4227 
4228  /* switch back to message context */
4230 
4231  HandleFunctionRequest(&input_message);
4232 
4233  /* commit the function-invocation transaction */
4235 
4236  send_ready_for_query = true;
4237  break;
4238 
4239  case 'C': /* close */
4240  {
4241  int close_type;
4242  const char *close_target;
4243 
4244  forbidden_in_wal_sender(firstchar);
4245 
4246  close_type = pq_getmsgbyte(&input_message);
4247  close_target = pq_getmsgstring(&input_message);
4248  pq_getmsgend(&input_message);
4249 
4250  switch (close_type)
4251  {
4252  case 'S':
4253  if (close_target[0] != '\0')
4254  DropPreparedStatement(close_target, false);
4255  else
4256  {
4257  /* special-case the unnamed statement */
4259  }
4260  break;
4261  case 'P':
4262  {
4263  Portal portal;
4264 
4265  portal = GetPortalByName(close_target);
4266  if (PortalIsValid(portal))
4267  PortalDrop(portal, false);
4268  }
4269  break;
4270  default:
4271  ereport(ERROR,
4272  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4273  errmsg("invalid CLOSE message subtype %d",
4274  close_type)));
4275  break;
4276  }
4277 
4279  pq_putemptymessage('3'); /* CloseComplete */
4280  }
4281  break;
4282 
4283  case 'D': /* describe */
4284  {
4285  int describe_type;
4286  const char *describe_target;
4287 
4288  forbidden_in_wal_sender(firstchar);
4289 
4290  /* Set statement_timestamp() (needed for xact) */
4292 
4293  describe_type = pq_getmsgbyte(&input_message);
4294  describe_target = pq_getmsgstring(&input_message);
4295  pq_getmsgend(&input_message);
4296 
4297  switch (describe_type)
4298  {
4299  case 'S':
4300  exec_describe_statement_message(describe_target);
4301  break;
4302  case 'P':
4303  exec_describe_portal_message(describe_target);
4304  break;
4305  default:
4306  ereport(ERROR,
4307  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4308  errmsg("invalid DESCRIBE message subtype %d",
4309  describe_type)));
4310  break;
4311  }
4312  }
4313  break;
4314 
4315  case 'H': /* flush */
4316  pq_getmsgend(&input_message);
4318  pq_flush();
4319  break;
4320 
4321  case 'S': /* sync */
4322  pq_getmsgend(&input_message);
4324  send_ready_for_query = true;
4325  break;
4326 
4327  /*
4328  * 'X' means that the frontend is closing down the socket. EOF
4329  * means unexpected loss of frontend connection. Either way,
4330  * perform normal shutdown.
4331  */
4332  case 'X':
4333  case EOF:
4334 
4335  /*
4336  * Reset whereToSendOutput to prevent ereport from attempting
4337  * to send any more messages to client.
4338  */
4341 
4342  /*
4343  * NOTE: if you are tempted to add more code here, DON'T!
4344  * Whatever you had in mind to do should be set up as an
4345  * on_proc_exit or on_shmem_exit callback, instead. Otherwise
4346  * it will fail to be called during other backend-shutdown
4347  * scenarios.
4348  */
4349  proc_exit(0);
4350 
4351  case 'd': /* copy data */
4352  case 'c': /* copy done */
4353  case 'f': /* copy fail */
4354 
4355  /*
4356  * Accept but ignore these messages, per protocol spec; we
4357  * probably got here because a COPY failed, and the frontend
4358  * is still sending data.
4359  */
4360  break;
4361 
4362  default:
4363  ereport(FATAL,
4364  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4365  errmsg("invalid frontend message type %d",
4366  firstchar)));
4367  }
4368  } /* end of input-reading loop */
4369 }
void InitializeTimeouts(void)
Definition: timeout.c:340
void AbortCurrentTransaction(void)
Definition: xact.c:2985
static void exec_describe_portal_message(const char *portal_name)
Definition: postgres.c:2415
#define SIGQUIT
Definition: win32_port.h:164
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:198
void BeginReportingGUCOptions(void)
Definition: guc.c:5388
int MyProcPid
Definition: globals.c:39
#define pq_flush()
Definition: libpq.h:39
static int ReadCommand(StringInfo inBuf)
Definition: postgres.c:507
static void finish_xact_command(void)
Definition: postgres.c:2487
void ProcessConfigFile(GucContext context)
bool exec_replication_command(const char *cmd_string)
Definition: walsender.c:1424
#define SIGUSR1
Definition: win32_port.h:177
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1570
void on_proc_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:292
void pgstat_report_activity(BackendState state, const char *cmd_str)
Definition: pgstat.c:2994
#define SIGCHLD
Definition: win32_port.h:173
const char * pq_getmsgstring(StringInfo msg)
Definition: pqformat.c:581
static void pq_sendint32(StringInfo buf, int32 i)
Definition: pqformat.h:148
Portal GetPortalByName(const char *name)
Definition: portalmem.c:129
void InitStandaloneProcess(const char *argv0)
Definition: miscinit.c:220
void ValidatePgVersion(const char *path)
Definition: miscinit.c:1358
bool IsAbortedTransactionBlockState(void)
Definition: xact.c:371
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void set_ps_display(const char *activity, bool force)
Definition: ps_status.c:326
static void forbidden_in_wal_sender(char firstchar)
Definition: postgres.c:4379
void proc_exit(int code)
Definition: ipc.c:99
int errcode(int sqlerrcode)
Definition: elog.c:575
bool IsTransactionOrTransactionBlock(void)
Definition: xact.c:4466
void pq_putemptymessage(char msgtype)
Definition: pqformat.c:390
#define SetProcessingMode(mode)
Definition: miscadmin.h:373
void BaseInit(void)
Definition: postinit.c:518
#define SIGPIPE
Definition: win32_port.h:168
#define SIGUSR2
Definition: win32_port.h:178
unsigned int Oid
Definition: postgres_ext.h:31
volatile bool QueryCancelPending
Definition: globals.c:30
const char * progname
Definition: pg_standby.c:37
void FlushErrorState(void)
Definition: elog.c:1587
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
void pq_beginmessage(StringInfo buf, char msgtype)
Definition: pqformat.c:87
void StatementCancelHandler(SIGNAL_ARGS)
Definition: postgres.c:2683
signed int int32
Definition: c.h:294
static void exec_execute_message(const char *portal_name, long max_rows)
Definition: postgres.c:1866
static void log_disconnections(int code, Datum arg)
Definition: postgres.c:4546
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:117
ErrorContextCallback * error_context_stack
Definition: elog.c:88
void pqinitmask(void)
Definition: pqsignal.c:41
bool am_walsender
Definition: walsender.c:114
void disable_all_timeouts(bool keep_indicators)
Definition: timeout.c:596
#define ERROR
Definition: elog.h:43
void CreateDataDirLockFile(bool amPostmaster)
Definition: miscinit.c:1081
bool pq_is_reading_msg(void)
Definition: pqcomm.c:1250
int IdleInTransactionSessionTimeout
Definition: proc.c:63
int32 MyCancelKey
Definition: globals.c:42
void WalSndSignals(void)
Definition: walsender.c:2944
#define FATAL
Definition: elog.h:52
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:197
void InitProcess(void)
Definition: proc.c:288
Definition: dest.h:88
static char * buf
Definition: pg_test_fsync.c:67
bool IsUnderPostmaster
Definition: globals.c:101
static void exec_bind_message(StringInfo input_message)
Definition: postgres.c:1482
Definition: dest.h:89
#define SIGHUP
Definition: win32_port.h:163
void PostgresSigHupHandler(SIGNAL_ARGS)
Definition: postgres.c:2723
void LocalProcessControlFile(bool reset)
Definition: xlog.c:4831
void ChangeToDataDir(void)
Definition: miscinit.c:116
void ReplicationSlotRelease(void)
Definition: slot.c:416
sigset_t UnBlockSig
Definition: pqsignal.c:22
static bool xact_started
Definition: postgres.c:130
void InitWalSender(void)
#define ereport(elevel, rest)
Definition: elog.h:122
MemoryContext TopMemoryContext
Definition: mcxt.c:43
Definition: guc.h:72
volatile sig_atomic_t ConfigReloadPending
Definition: globals.c:34
#define SIG_IGN
Definition: win32_port.h:160
#define AllocSetContextCreate(parent, name, allocparams)
Definition: memutils.h:165
void initStringInfo(StringInfo str)
Definition: stringinfo.c:46
const char * debug_query_string
Definition: postgres.c:85
#define MemoryContextResetAndDeleteChildren(ctx)
Definition: memutils.h:67
static void exec_parse_message(const char *query_string, const char *stmt_name, Oid *paramTypes, int numParams)
Definition: postgres.c:1219
#define PortalIsValid(p)
Definition: portal.h:199
static void start_xact_command(void)
Definition: postgres.c:2467
static bool doing_extended_query_message
Definition: postgres.c:143
sigset_t BlockSig
Definition: pqsignal.c:22
void process_session_preload_libraries(void)
Definition: miscinit.c:1500
void WalSndErrorCleanup(void)
Definition: walsender.c:291
bool SelectConfigFiles(const char *userDoption, const char *progname)
Definition: guc.c:4717
void EmitErrorReport(void)
Definition: elog.c:1446
static StringInfoData row_description_buf
Definition: postgres.c:170
TimestampTz PgStartTime
Definition: timestamp.c:49
static char * username
Definition: initdb.c:132
#define InvalidOid
Definition: postgres_ext.h:36
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:168
int pq_getmsgbyte(StringInfo msg)
Definition: pqformat.c:401
void enable_timeout_after(TimeoutId id, int delay_ms)
Definition: timeout.c:428
ReplicationSlot * MyReplicationSlot
Definition: slot.c:96
#define pq_comm_reset()
Definition: libpq.h:38
#define SIG_DFL
Definition: win32_port.h:158
#define Assert(condition)
Definition: c.h:680
void ProcessCompletedNotifies(void)
Definition: async.c:1101
void HandleFunctionRequest(StringInfo msgBuf)
Definition: fastpath.c:259
void InvalidateCatalogSnapshotConditionally(void)
Definition: snapmgr.c:531
static bool DoingCommandRead
Definition: postgres.c:137
void InitializeMaxBackends(void)
Definition: postinit.c:496
char * dbname
Definition: streamutil.c:42
MemoryContext MessageContext
Definition: mcxt.c:47
sigjmp_buf * PG_exception_stack
Definition: elog.c:90
static const char * userDoption
Definition: postgres.c:159
void SetCurrentStatementStartTimestamp(void)
Definition: xact.c:733
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, char *out_dbname)
Definition: postinit.c:559
void * palloc(Size size)
Definition: mcxt.c:835
int errmsg(const char *fmt,...)
Definition: elog.c:797
void PortalDrop(Portal portal, bool isTopCommit)
Definition: portalmem.c:461
void ReadyForQuery(CommandDest dest)
Definition: dest.c:241
void pq_endmessage(StringInfo buf)
Definition: pqformat.c:298
void die(SIGNAL_ARGS)
Definition: postgres.c:2652
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:115
int i
void FloatExceptionHandler(SIGNAL_ARGS)
Definition: postgres.c:2704
static void drop_unnamed_stmt(void)
Definition: postgres.c:2566
char * DataDir
Definition: globals.c:60
void ReplicationSlotCleanup(void)
Definition: slot.c:471
unsigned int pq_getmsgint(StringInfo msg, int b)
Definition: pqformat.c:417
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:98
bool Log_disconnections
Definition: postgres.c:91
void process_postgres_switches(int argc, char *argv[], GucContext ctx, const char **dbname)
Definition: postgres.c:3356
void pq_getmsgend(StringInfo msg)
Definition: pqformat.c:637
void disable_timeout(TimeoutId id, bool keep_indicator)
Definition: timeout.c:525
void procsignal_sigusr1_handler(SIGNAL_ARGS)
Definition: procsignal.c:261
CommandDest whereToSendOutput
Definition: postgres.c:88
static bool ignore_till_sync
Definition: postgres.c:144
static MemoryContext row_description_context
Definition: postgres.c:169
void quickdie(SIGNAL_ARGS)
Definition: postgres.c:2591
MemoryContext PostmasterContext
Definition: mcxt.c:45
static void exec_simple_query(const char *query_string)
Definition: postgres.c:889
void InitializeGUCOptions(void)
Definition: guc.c:4495
void pgstat_report_stat(bool force)
Definition: pgstat.c:812
void DropPreparedStatement(const char *stmt_name, bool showError)
Definition: prepare.c:579
static void exec_describe_statement_message(const char *stmt_name)
Definition: postgres.c:2319

◆ process_postgres_switches()

void process_postgres_switches ( int  argc,
char *  argv[],
GucContext  ctx,
const char **  dbname 
)

Definition at line 3356 of file postgres.c.

References EchoQuery, ereport, errcode(), errhint(), errmsg(), ERROR, FATAL, flag(), free, FrontendProtocol, get_stats_option_name(), getopt(), IsBinaryUpgrade, IsUnderPostmaster, MAXPGPATH, name, optarg, opterr, optind, OutputFileName, ParseLongOption(), PGC_POSTMASTER, PGC_S_ARGV, PGC_S_CLIENT, progname, set_debug_options(), set_plan_disabling_options(), SetConfigOption(), strlcpy(), userDoption, UseSemiNewlineNewline, and value.

Referenced by PostgresMain(), and process_startup_options().

3358 {
3359  bool secure = (ctx == PGC_POSTMASTER);
3360  int errs = 0;
3361  GucSource gucsource;
3362  int flag;
3363 
3364  if (secure)
3365  {
3366  gucsource = PGC_S_ARGV; /* switches came from command line */
3367 
3368  /* Ignore the initial --single argument, if present */
3369  if (argc > 1 && strcmp(argv[1], "--single") == 0)
3370  {
3371  argv++;
3372  argc--;
3373  }
3374  }
3375  else
3376  {
3377  gucsource = PGC_S_CLIENT; /* switches came from client */
3378  }
3379 
3380 #ifdef HAVE_INT_OPTERR
3381 
3382  /*
3383  * Turn this off because it's either printed to stderr and not the log
3384  * where we'd want it, or argv[0] is now "--single", which would make for
3385  * a weird error message. We print our own error message below.
3386  */
3387  opterr = 0;
3388 #endif
3389 
3390  /*
3391  * Parse command-line options. CAUTION: keep this in sync with
3392  * postmaster/postmaster.c (the option sets should not conflict) and with
3393  * the common help() function in main/main.c.
3394  */
3395  while ((flag = getopt(argc, argv, "B:bc:C:D:d:EeFf:h:ijk:lN:nOo:Pp:r:S:sTt:v:W:-:")) != -1)
3396  {
3397  switch (flag)
3398  {
3399  case 'B':
3400  SetConfigOption("shared_buffers", optarg, ctx, gucsource);
3401  break;
3402 
3403  case 'b':
3404  /* Undocumented flag used for binary upgrades */
3405  if (secure)
3406  IsBinaryUpgrade = true;
3407  break;
3408 
3409  case 'C':
3410  /* ignored for consistency with the postmaster */
3411  break;
3412 
3413  case 'D':
3414  if (secure)
3415  userDoption = strdup(optarg);
3416  break;
3417 
3418  case 'd':
3419  set_debug_options(atoi(optarg), ctx, gucsource);
3420  break;
3421 
3422  case 'E':
3423  if (secure)
3424  EchoQuery = true;
3425  break;
3426 
3427  case 'e':
3428  SetConfigOption("datestyle", "euro", ctx, gucsource);
3429  break;
3430 
3431  case 'F':
3432  SetConfigOption("fsync", "false", ctx, gucsource);
3433  break;
3434 
3435  case 'f':
3436  if (!set_plan_disabling_options(optarg, ctx, gucsource))
3437  errs++;
3438  break;
3439 
3440  case 'h':
3441  SetConfigOption("listen_addresses", optarg, ctx, gucsource);
3442  break;
3443 
3444  case 'i':
3445  SetConfigOption("listen_addresses", "*", ctx, gucsource);
3446  break;
3447 
3448  case 'j':
3449  if (secure)
3450  UseSemiNewlineNewline = true;
3451  break;
3452 
3453  case 'k':
3454  SetConfigOption("unix_socket_directories", optarg, ctx, gucsource);
3455  break;
3456 
3457  case 'l':
3458  SetConfigOption("ssl", "true", ctx, gucsource);
3459  break;
3460 
3461  case 'N':
3462  SetConfigOption("max_connections", optarg, ctx, gucsource);
3463  break;
3464 
3465  case 'n':
3466  /* ignored for consistency with postmaster */
3467  break;
3468 
3469  case 'O':
3470  SetConfigOption("allow_system_table_mods", "true", ctx, gucsource);
3471  break;
3472 
3473  case 'o':
3474  errs++;
3475  break;
3476 
3477  case 'P':
3478  SetConfigOption("ignore_system_indexes", "true", ctx, gucsource);
3479  break;
3480 
3481  case 'p':
3482  SetConfigOption("port", optarg, ctx, gucsource);
3483  break;
3484 
3485  case 'r':
3486  /* send output (stdout and stderr) to the given file */
3487  if (secure)
3489  break;
3490 
3491  case 'S':
3492  SetConfigOption("work_mem", optarg, ctx, gucsource);
3493  break;
3494 
3495  case 's':
3496  SetConfigOption("log_statement_stats", "true", ctx, gucsource);
3497  break;
3498 
3499  case 'T':
3500  /* ignored for consistency with the postmaster */
3501  break;
3502 
3503  case 't':
3504  {
3505  const char *tmp = get_stats_option_name(optarg);
3506 
3507  if (tmp)
3508  SetConfigOption(tmp, "true", ctx, gucsource);
3509  else
3510  errs++;
3511  break;
3512  }
3513 
3514  case 'v':
3515 
3516  /*
3517  * -v is no longer used in normal operation, since
3518  * FrontendProtocol is already set before we get here. We keep
3519  * the switch only for possible use in standalone operation,
3520  * in case we ever support using normal FE/BE protocol with a
3521  * standalone backend.
3522  */
3523  if (secure)
3525  break;
3526 
3527  case 'W':
3528  SetConfigOption("post_auth_delay", optarg, ctx, gucsource);
3529  break;
3530 
3531  case 'c':
3532  case '-':
3533  {
3534  char *name,
3535  *value;
3536 
3537  ParseLongOption(optarg, &name, &value);
3538  if (!value)
3539  {
3540  if (flag == '-')
3541  ereport(ERROR,
3542  (errcode(ERRCODE_SYNTAX_ERROR),
3543  errmsg("--%s requires a value",
3544  optarg)));
3545  else
3546  ereport(ERROR,
3547  (errcode(ERRCODE_SYNTAX_ERROR),
3548  errmsg("-c %s requires a value",
3549  optarg)));
3550  }
3551  SetConfigOption(name, value, ctx, gucsource);
3552  free(name);
3553  if (value)
3554  free(value);
3555  break;
3556  }
3557 
3558  default:
3559  errs++;
3560  break;
3561  }
3562 
3563  if (errs)
3564  break;
3565  }
3566 
3567  /*
3568  * Optional database name should be there only if *dbname is NULL.
3569  */
3570  if (!errs && dbname && *dbname == NULL && argc - optind >= 1)
3571  *dbname = strdup(argv[optind++]);
3572 
3573  if (errs || argc != optind)
3574  {
3575  if (errs)
3576  optind--; /* complain about the previous argument */
3577 
3578  /* spell the error message a bit differently depending on context */
3579  if (IsUnderPostmaster)
3580  ereport(FATAL,
3581  (errcode(ERRCODE_SYNTAX_ERROR),
3582  errmsg("invalid command-line argument for server process: %s", argv[optind]),
3583  errhint("Try \"%s --help\" for more information.", progname)));
3584  else
3585  ereport(FATAL,
3586  (errcode(ERRCODE_SYNTAX_ERROR),
3587  errmsg("%s: invalid command-line argument: %s",
3588  progname, argv[optind]),
3589  errhint("Try \"%s --help\" for more information.", progname)));
3590  }
3591 
3592  /*
3593  * Reset getopt(3) library so that it will work correctly in subprocesses
3594  * or when this function is called a second time with another array.
3595  */
3596  optind = 1;
3597 #ifdef HAVE_INT_OPTRESET
3598  optreset = 1; /* some systems need this too */
3599 #endif
3600 }
int errhint(const char *fmt,...)
Definition: elog.c:987
void ParseLongOption(const char *string, char **name, char **value)
Definition: guc.c:9397
bool set_plan_disabling_options(const char *arg, GucContext context, GucSource source)
Definition: postgres.c:3274
int errcode(int sqlerrcode)
Definition: elog.c:575
const char * get_stats_option_name(const char *arg)
Definition: postgres.c:3316
void set_debug_options(int debug_flag, GucContext context, GucSource source)
Definition: postgres.c:3245
const char * progname
Definition: pg_standby.c:37
bool IsBinaryUpgrade
Definition: globals.c:102
int getopt(int nargc, char *const *nargv, const char *ostr)
Definition: getopt.c:72
GucSource
Definition: guc.h:105
int optind
Definition: getopt.c:51
#define ERROR
Definition: elog.h:43
#define FATAL
Definition: elog.h:52
#define MAXPGPATH
static struct @121 value
char OutputFileName[MAXPGPATH]
Definition: globals.c:62
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:6700
bool IsUnderPostmaster
Definition: globals.c:101
char * flag(int b)
Definition: test-ctype.c:33
int opterr
Definition: getopt.c:50
#define ereport(elevel, rest)
Definition: elog.h:122
uint32 ProtocolVersion
Definition: pqcomm.h:113
#define free(a)
Definition: header.h:65
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
char * dbname
Definition: streamutil.c:42
const char * name
Definition: encode.c:521
static bool EchoQuery
Definition: postgres.c:160
static const char * userDoption
Definition: postgres.c:159
static bool UseSemiNewlineNewline
Definition: postgres.c:161
int errmsg(const char *fmt,...)
Definition: elog.c:797
char * optarg
Definition: getopt.c:53
ProtocolVersion FrontendProtocol
Definition: globals.c:27

◆ ProcessClientReadInterrupt()

void ProcessClientReadInterrupt ( bool  blocked)

Definition at line 527 of file postgres.c.

References catchupInterruptPending, CHECK_FOR_INTERRUPTS, DoingCommandRead, notifyInterruptPending, ProcDiePending, ProcessCatchupInterrupt(), and ProcessNotifyInterrupt().

Referenced by interactive_getc(), and secure_read().

528 {
529  int save_errno = errno;
530 
531  if (DoingCommandRead)
532  {
533  /* Check for general interrupts that arrived while reading */
535 
536  /* Process sinval catchup interrupts that happened while reading */
539 
540  /* Process sinval catchup interrupts that happened while reading */
543  }
544  else if (ProcDiePending && blocked)
545  {
546  /*
547  * We're dying. It's safe (and sane) to handle that now.
548  */
550  }
551 
552  errno = save_errno;
553 }
void ProcessCatchupInterrupt(void)
Definition: sinval.c:177
void ProcessNotifyInterrupt(void)
Definition: async.c:1731
static bool DoingCommandRead
Definition: postgres.c:137
volatile bool ProcDiePending
Definition: globals.c:31
volatile sig_atomic_t notifyInterruptPending
Definition: async.c:358
volatile sig_atomic_t catchupInterruptPending
Definition: sinval.c:41
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:98

◆ ProcessClientWriteInterrupt()

void ProcessClientWriteInterrupt ( bool  blocked)

Definition at line 565 of file postgres.c.

References CHECK_FOR_INTERRUPTS, DestNone, DestRemote, ProcDiePending, and whereToSendOutput.

Referenced by secure_write().

566 {
567  int save_errno = errno;
568 
569  /*
570  * We only want to process the interrupt here if socket writes are
571  * blocking to increase the chance to get an error message to the client.
572  * If we're not blocked there'll soon be a CHECK_FOR_INTERRUPTS(). But if
573  * we're blocked we'll never get out of that situation if the client has
574  * died.
575  */
576  if (ProcDiePending && blocked)
577  {
578  /*
579  * We're dying. It's safe (and sane) to handle that now. But we don't
580  * want to send the client the error message as that a) would possibly
581  * block again b) would possibly lead to sending an error message to
582  * the client, while we already started to send something else.
583  */
586 
588  }
589 
590  errno = save_errno;
591 }
Definition: dest.h:88
volatile bool ProcDiePending
Definition: globals.c:31
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:98
CommandDest whereToSendOutput
Definition: postgres.c:88

◆ quickdie()

void quickdie ( SIGNAL_ARGS  )

Definition at line 2591 of file postgres.c.

References BlockSig, ClientAuthInProgress, DestNone, DestRemote, ereport, errcode(), errdetail(), errhint(), errmsg(), HOLD_INTERRUPTS, on_exit_reset(), PG_SETMASK, SIGQUIT, WARNING, and whereToSendOutput.

Referenced by AutoVacLauncherMain(), AutoVacWorkerMain(), PostgresMain(), and WalSndSignals().

2592 {
2593  sigaddset(&BlockSig, SIGQUIT); /* prevent nested calls */
2594  PG_SETMASK(&BlockSig);
2595 
2596  /*
2597  * Prevent interrupts while exiting; though we just blocked signals that
2598  * would queue new interrupts, one may have been pending. We don't want a
2599  * quickdie() downgraded to a mere query cancel.
2600  */
2601  HOLD_INTERRUPTS();
2602 
2603  /*
2604  * If we're aborting out of client auth, don't risk trying to send
2605  * anything to the client; we will likely violate the protocol, not to
2606  * mention that we may have interrupted the guts of OpenSSL or some
2607  * authentication library.
2608  */
2611 
2612  /*
2613  * Ideally this should be ereport(FATAL), but then we'd not get control
2614  * back...
2615  */
2616  ereport(WARNING,
2617  (errcode(ERRCODE_CRASH_SHUTDOWN),
2618  errmsg("terminating connection because of crash of another server process"),
2619  errdetail("The postmaster has commanded this server process to roll back"
2620  " the current transaction and exit, because another"
2621  " server process exited abnormally and possibly corrupted"
2622  " shared memory."),
2623  errhint("In a moment you should be able to reconnect to the"
2624  " database and repeat your command.")));
2625 
2626  /*
2627  * We DO NOT want to run proc_exit() callbacks -- we're here because
2628  * shared memory may be corrupted, so we don't want to try to clean up our
2629  * transaction. Just nail the windows shut and get out of town. Now that
2630  * there's an atexit callback to prevent third-party code from breaking
2631  * things by calling exit() directly, we have to reset the callbacks
2632  * explicitly to make this work as intended.
2633  */
2634  on_exit_reset();
2635 
2636  /*
2637  * Note we do exit(2) not exit(0). This is to force the postmaster into a
2638  * system reset cycle if some idiot DBA sends a manual SIGQUIT to a random
2639  * backend. This is necessary precisely because we don't clean up our
2640  * shared memory state. (The "dead man switch" mechanism in pmsignal.c
2641  * should ensure the postmaster sees this as a crash, too, but no harm in
2642  * being doubly sure.)
2643  */
2644  exit(2);
2645 }
#define SIGQUIT
Definition: win32_port.h:164
int errhint(const char *fmt,...)
Definition: elog.c:987
int errcode(int sqlerrcode)
Definition: elog.c:575
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
bool ClientAuthInProgress
Definition: postmaster.c:350
void on_exit_reset(void)
Definition: ipc.c:396
Definition: dest.h:88
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define ereport(elevel, rest)
Definition: elog.h:122
#define WARNING
Definition: elog.h:40
sigset_t BlockSig
Definition: pqsignal.c:22
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:115
CommandDest whereToSendOutput
Definition: postgres.c:88

◆ RecoveryConflictInterrupt()

void RecoveryConflictInterrupt ( ProcSignalReason  reason)

Definition at line 2740 of file postgres.c.

References Assert, elog, FATAL, HoldingBufferPinThatDelaysRecovery(), InterruptPending, IsAbortedTransactionBlockState(), IsSubTransaction(), IsTransactionOrTransactionBlock(), IsWaitingForLock(), MyLatch, MyProc, proc_exit_inprogress, ProcDiePending, PROCSIG_RECOVERY_CONFLICT_BUFFERPIN, PROCSIG_RECOVERY_CONFLICT_DATABASE, PROCSIG_RECOVERY_CONFLICT_LOCK, PROCSIG_RECOVERY_CONFLICT_SNAPSHOT, PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK, PROCSIG_RECOVERY_CONFLICT_TABLESPACE, QueryCancelPending, PGPROC::recoveryConflictPending, RecoveryConflictPending, RecoveryConflictReason, RecoveryConflictRetryable, and SetLatch().

Referenced by procsignal_sigusr1_handler().

2741 {
2742  int save_errno = errno;
2743 
2744  /*
2745  * Don't joggle the elbow of proc_exit
2746  */
2747  if (!proc_exit_inprogress)
2748  {
2749  RecoveryConflictReason = reason;
2750  switch (reason)
2751  {
2753 
2754  /*
2755  * If we aren't waiting for a lock we can never deadlock.
2756  */
2757  if (!IsWaitingForLock())
2758  return;
2759 
2760  /* Intentional drop through to check wait for pin */
2761 
2763 
2764  /*
2765  * If we aren't blocking the Startup process there is nothing
2766  * more to do.
2767  */
2769  return;
2770 
2772 
2773  /* Intentional drop through to error handling */
2774 
2778 
2779  /*
2780  * If we aren't in a transaction any longer then ignore.
2781  */
2783  return;
2784 
2785  /*
2786  * If we can abort just the current subtransaction then we are
2787  * OK to throw an ERROR to resolve the conflict. Otherwise
2788  * drop through to the FATAL case.
2789  *
2790  * XXX other times that we can throw just an ERROR *may* be
2791  * PROCSIG_RECOVERY_CONFLICT_LOCK if no locks are held in
2792  * parent transactions
2793  *
2794  * PROCSIG_RECOVERY_CONFLICT_SNAPSHOT if no snapshots are held
2795  * by parent transactions and the transaction is not
2796  * transaction-snapshot mode
2797  *
2798  * PROCSIG_RECOVERY_CONFLICT_TABLESPACE if no temp files or
2799  * cursors open in parent transactions
2800  */
2801  if (!IsSubTransaction())
2802  {
2803  /*
2804  * If we already aborted then we no longer need to cancel.
2805  * We do this here since we do not wish to ignore aborted
2806  * subtransactions, which must cause FATAL, currently.
2807  */
2809  return;
2810 
2811  RecoveryConflictPending = true;
2812  QueryCancelPending = true;
2813  InterruptPending = true;
2814  break;
2815  }
2816 
2817  /* Intentional drop through to session cancel */
2818 
2820  RecoveryConflictPending = true;
2821  ProcDiePending = true;
2822  InterruptPending = true;
2823  break;
2824 
2825  default:
2826  elog(FATAL, "unrecognized conflict mode: %d",
2827  (int) reason);
2828  }
2829 
2831 
2832  /*
2833  * All conflicts apart from database cause dynamic errors where the
2834  * command or transaction can be retried at a later point with some
2835  * potential for success. No need to reset this, since non-retryable
2836  * conflict errors are currently FATAL.
2837  */
2838  if (reason == PROCSIG_RECOVERY_CONFLICT_DATABASE)
2839  RecoveryConflictRetryable = false;
2840  }
2841 
2842  /*
2843  * Set the process latch. This function essentially emulates signal
2844  * handlers like die() and StatementCancelHandler() and it seems prudent
2845  * to behave similarly as they do.
2846  */
2847  SetLatch(MyLatch);
2848 
2849  errno = save_errno;
2850 }
bool IsWaitingForLock(void)
Definition: proc.c:669
PGPROC * MyProc
Definition: proc.c:67
bool IsAbortedTransactionBlockState(void)
Definition: xact.c:371
bool IsTransactionOrTransactionBlock(void)
Definition: xact.c:4466
volatile bool QueryCancelPending
Definition: globals.c:30
#define FATAL
Definition: elog.h:52
bool recoveryConflictPending
Definition: proc.h:124
static ProcSignalReason RecoveryConflictReason
Definition: postgres.c:166
static bool RecoveryConflictPending
Definition: postgres.c:164
static bool RecoveryConflictRetryable
Definition: postgres.c:165
volatile bool InterruptPending
Definition: globals.c:29
void SetLatch(volatile Latch *latch)
Definition: latch.c:414
#define Assert(condition)
Definition: c.h:680
bool proc_exit_inprogress
Definition: ipc.c:40
bool HoldingBufferPinThatDelaysRecovery(void)
Definition: bufmgr.c:3692
bool IsSubTransaction(void)
Definition: xact.c:4521
volatile bool ProcDiePending
Definition: globals.c:31
struct Latch * MyLatch
Definition: globals.c:52
#define elog
Definition: elog.h:219

◆ ResetUsage()

void ResetUsage ( void  )

Definition at line 4437 of file postgres.c.

References getrusage(), gettimeofday(), RUSAGE_SELF, Save_r, and Save_t.

Referenced by _bt_leafbuild(), _SPI_pquery(), btbuild(), exec_bind_message(), exec_execute_message(), exec_parse_message(), exec_simple_query(), pg_analyze_and_rewrite(), pg_analyze_and_rewrite_params(), pg_parse_query(), pg_plan_query(), pg_rewrite_query(), PortalRun(), and PortalRunMulti().

4438 {
4440  gettimeofday(&Save_t, NULL);
4441 }
int gettimeofday(struct timeval *tp, struct timezone *tzp)
Definition: gettimeofday.c:105
static struct rusage Save_r
Definition: postgres.c:4433
int getrusage(int who, struct rusage *rusage)
Definition: getrusage.c:31
static struct timeval Save_t
Definition: postgres.c:4434
#define RUSAGE_SELF
Definition: rusagestub.h:23

◆ set_debug_options()

void set_debug_options ( int  debug_flag,
GucContext  context,
GucSource  source 
)

Definition at line 3245 of file postgres.c.

References PGC_POSTMASTER, and SetConfigOption().

Referenced by PostmasterMain(), and process_postgres_switches().

3246 {
3247  if (debug_flag > 0)
3248  {
3249  char debugstr[64];
3250 
3251  sprintf(debugstr, "debug%d", debug_flag);
3252  SetConfigOption("log_min_messages", debugstr, context, source);
3253  }
3254  else
3255  SetConfigOption("log_min_messages", "notice", context, source);
3256 
3257  if (debug_flag >= 1 && context == PGC_POSTMASTER)
3258  {
3259  SetConfigOption("log_connections", "true", context, source);
3260  SetConfigOption("log_disconnections", "true", context, source);
3261  }
3262  if (debug_flag >= 2)
3263  SetConfigOption("log_statement", "all", context, source);
3264  if (debug_flag >= 3)
3265  SetConfigOption("debug_print_parse", "true", context, source);
3266  if (debug_flag >= 4)
3267  SetConfigOption("debug_print_plan", "true", context, source);
3268  if (debug_flag >= 5)
3269  SetConfigOption("debug_print_rewritten", "true", context, source);
3270 }
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:6700

◆ set_plan_disabling_options()

bool set_plan_disabling_options ( const char *  arg,
GucContext  context,
GucSource  source 
)

Definition at line 3274 of file postgres.c.

References SetConfigOption().

Referenced by PostmasterMain(), and process_postgres_switches().

3275 {
3276  const char *tmp = NULL;
3277 
3278  switch (arg[0])
3279  {
3280  case 's': /* seqscan */
3281  tmp = "enable_seqscan";
3282  break;
3283  case 'i': /* indexscan */
3284  tmp = "enable_indexscan";
3285  break;
3286  case 'o': /* indexonlyscan */
3287  tmp = "enable_indexonlyscan";
3288  break;
3289  case 'b': /* bitmapscan */
3290  tmp = "enable_bitmapscan";
3291  break;
3292  case 't': /* tidscan */
3293  tmp = "enable_tidscan";
3294  break;
3295  case 'n': /* nestloop */
3296  tmp = "enable_nestloop";
3297  break;
3298  case 'm': /* mergejoin */
3299  tmp = "enable_mergejoin";
3300  break;
3301  case 'h': /* hashjoin */
3302  tmp = "enable_hashjoin";
3303  break;
3304  }
3305  if (tmp)
3306  {
3307  SetConfigOption(tmp, "false", context, source);
3308  return true;
3309  }
3310  else
3311  return false;
3312 }
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:6700
void * arg

◆ ShowUsage()

void ShowUsage ( const char *  title)

Definition at line 4444 of file postgres.c.

References __darwin__, appendStringInfo(), appendStringInfoString(), StringInfoData::data, ereport, errdetail_internal(), errmsg_internal(), getrusage(), gettimeofday(), initStringInfo(), StringInfoData::len, LOG, pfree(), rusage::ru_stime, rusage::ru_utime, RUSAGE_SELF, Save_r, Save_t, and generate_unaccent_rules::str.

Referenced by _bt_leafbuild(), _SPI_pquery(), btbuild(), exec_bind_message(), exec_execute_message(), exec_parse_message(), exec_simple_query(), pg_analyze_and_rewrite(), pg_analyze_and_rewrite_params(), pg_parse_query(), pg_plan_query(), pg_rewrite_query(), PortalRun(), and PortalRunMulti().

4445 {
4447  struct timeval user,
4448  sys;
4449  struct timeval elapse_t;
4450  struct rusage r;
4451 
4452  getrusage(RUSAGE_SELF, &r);
4453  gettimeofday(&elapse_t, NULL);
4454  memcpy((char *) &user, (char *) &r.ru_utime, sizeof(user));
4455  memcpy((char *) &sys, (char *) &r.ru_stime, sizeof(sys));
4456  if (elapse_t.tv_usec < Save_t.tv_usec)
4457  {
4458  elapse_t.tv_sec--;
4459  elapse_t.tv_usec += 1000000;
4460  }
4461  if (r.ru_utime.tv_usec < Save_r.ru_utime.tv_usec)
4462  {
4463  r.ru_utime.tv_sec--;
4464  r.ru_utime.tv_usec += 1000000;
4465  }
4466  if (r.ru_stime.tv_usec < Save_r.ru_stime.tv_usec)
4467  {
4468  r.ru_stime.tv_sec--;
4469  r.ru_stime.tv_usec += 1000000;
4470  }
4471 
4472  /*
4473  * The only stats we don't show here are ixrss, idrss, isrss. It takes
4474  * some work to interpret them, and most platforms don't fill them in.
4475  */
4476  initStringInfo(&str);
4477 
4478  appendStringInfoString(&str, "! system usage stats:\n");
4479  appendStringInfo(&str,
4480  "!\t%ld.%06ld s user, %ld.%06ld s system, %ld.%06ld s elapsed\n",
4481  (long) (r.ru_utime.tv_sec - Save_r.ru_utime.tv_sec),
4482  (long) (r.ru_utime.tv_usec - Save_r.ru_utime.tv_usec),
4483  (long) (r.ru_stime.tv_sec - Save_r.ru_stime.tv_sec),
4484  (long) (r.ru_stime.tv_usec - Save_r.ru_stime.tv_usec),
4485  (long) (elapse_t.tv_sec - Save_t.tv_sec),
4486  (long) (elapse_t.tv_usec - Save_t.tv_usec));
4487  appendStringInfo(&str,
4488  "!\t[%ld.%06ld s user, %ld.%06ld s system total]\n",
4489  (long) user.tv_sec,
4490  (long) user.tv_usec,
4491  (long) sys.tv_sec,
4492  (long) sys.tv_usec);
4493 #if defined(HAVE_GETRUSAGE)
4494  appendStringInfo(&str,
4495  "!\t%ld kB max resident size\n",
4496 #if defined(__darwin__)
4497  /* in bytes on macOS */
4498  r.ru_maxrss / 1024
4499 #else
4500  /* in kilobytes on most other platforms */
4501  r.ru_maxrss
4502 #endif
4503  );
4504  appendStringInfo(&str,
4505  "!\t%ld/%ld [%ld/%ld] filesystem blocks in/out\n",
4506  r.ru_inblock - Save_r.ru_inblock,
4507  /* they only drink coffee at dec */
4508  r.ru_oublock - Save_r.ru_oublock,
4509  r.ru_inblock, r.ru_oublock);
4510  appendStringInfo(&str,
4511  "!\t%ld/%ld [%ld/%ld] page faults/reclaims, %ld [%ld] swaps\n",
4512  r.ru_majflt - Save_r.ru_majflt,
4513  r.ru_minflt - Save_r.ru_minflt,
4514  r.ru_majflt, r.ru_minflt,
4515  r.ru_nswap - Save_r.ru_nswap,
4516  r.ru_nswap);
4517  appendStringInfo(&str,
4518  "!\t%ld [%ld] signals rcvd, %ld/%ld [%ld/%ld] messages rcvd/sent\n",
4519  r.ru_nsignals - Save_r.ru_nsignals,
4520  r.ru_nsignals,
4521  r.ru_msgrcv - Save_r.ru_msgrcv,
4522  r.ru_msgsnd - Save_r.ru_msgsnd,
4523  r.ru_msgrcv, r.ru_msgsnd);
4524  appendStringInfo(&str,
4525  "!\t%ld/%ld [%ld/%ld] voluntary/involuntary context switches\n",
4526  r.ru_nvcsw - Save_r.ru_nvcsw,
4527  r.ru_nivcsw - Save_r.ru_nivcsw,
4528  r.ru_nvcsw, r.ru_nivcsw);
4529 #endif /* HAVE_GETRUSAGE */
4530 
4531  /* remove trailing newline */
4532  if (str.data[str.len - 1] == '\n')
4533  str.data[--str.len] = '\0';
4534 
4535  ereport(LOG,
4536  (errmsg_internal("%s", title),
4537  errdetail_internal("%s", str.data)));
4538 
4539  pfree(str.data);
4540 }
int gettimeofday(struct timeval *tp, struct timezone *tzp)
Definition: gettimeofday.c:105
static struct rusage Save_r
Definition: postgres.c:4433
struct timeval ru_stime
Definition: rusagestub.h:29
int getrusage(int who, struct rusage *rusage)
Definition: getrusage.c:31
#define LOG
Definition: elog.h:26
#define __darwin__
Definition: darwin.h:3
int errdetail_internal(const char *fmt,...)
Definition: elog.c:900
void pfree(void *pointer)
Definition: mcxt.c:936
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:157
static struct timeval Save_t
Definition: postgres.c:4434
#define ereport(elevel, rest)
Definition: elog.h:122
void initStringInfo(StringInfo str)
Definition: stringinfo.c:46
struct timeval ru_utime
Definition: rusagestub.h:28
#define RUSAGE_SELF
Definition: rusagestub.h:23
int errmsg_internal(const char *fmt,...)
Definition: elog.c:827
static char * user
Definition: pg_regress.c:93

◆ StatementCancelHandler()

void StatementCancelHandler ( SIGNAL_ARGS  )

Definition at line 2683 of file postgres.c.

References InterruptPending, MyLatch, proc_exit_inprogress, QueryCancelPending, and SetLatch().

Referenced by AutoVacLauncherMain(), AutoVacWorkerMain(), PostgresMain(), StartBackgroundWorker(), and WalSndSignals().

2684 {
2685  int save_errno = errno;
2686 
2687  /*
2688  * Don't joggle the elbow of proc_exit
2689  */
2690  if (!proc_exit_inprogress)
2691  {
2692  InterruptPending = true;
2693  QueryCancelPending = true;
2694  }
2695 
2696  /* If we're still here, waken anything waiting on the process latch */
2697  SetLatch(MyLatch);
2698 
2699  errno = save_errno;
2700 }
volatile bool QueryCancelPending
Definition: globals.c:30
volatile bool InterruptPending
Definition: globals.c:29
void SetLatch(volatile Latch *latch)
Definition: latch.c:414
bool proc_exit_inprogress
Definition: ipc.c:40
struct Latch * MyLatch
Definition: globals.c:52

Variable Documentation

◆ debug_query_string

◆ log_statement

PGDLLIMPORT int log_statement

Definition at line 93 of file postgres.c.

Referenced by check_log_statement(), and HandleFunctionRequest().

◆ max_stack_depth

int max_stack_depth

Definition at line 96 of file postgres.c.

Referenced by check_stack_depth().

◆ PostAuthDelay

int PostAuthDelay

◆ whereToSendOutput